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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
client/src/main/kotlin/org/findy_network/findy_common_kt/ProtocolClient.kt
|
findy-network
| 494,781,002
| false
|
{"Kotlin": 12352, "Shell": 2114, "Java": 217}
|
package org.findy_network.findy_common_kt
import io.grpc.CallCredentials.*
import io.grpc.ManagedChannel
import org.findy_network.findy_common_kt.ProtocolServiceGrpcKt.ProtocolServiceCoroutineStub
class ProofRequestAttribute(val name: String, val credDefId: String)
class ProtocolClient(private val channel: ManagedChannel, private val token: String) {
private val stub: ProtocolServiceCoroutineStub =
ProtocolServiceCoroutineStub(channel).withCallCredentials(Creds(token = token))
suspend fun status(id: String): ProtocolStatus {
return stub.status(ProtocolID.newBuilder().setID(id).build())
}
suspend fun connect(invitationURL: String, label: String): ProtocolID {
return stub.start(
Protocol.newBuilder()
.setTypeID(Protocol.Type.DIDEXCHANGE)
.setRole(Protocol.Role.INITIATOR)
.setDIDExchange(
Protocol.DIDExchangeMsg.newBuilder()
.setInvitationJSON(invitationURL)
.setLabel(label)
)
.build()
)
}
suspend fun sendMessage(connectionId: String, message: String): ProtocolID {
return stub.start(
Protocol.newBuilder()
.setTypeID(Protocol.Type.BASIC_MESSAGE)
.setRole(Protocol.Role.INITIATOR)
.setConnectionID(connectionId)
.setBasicMessage(Protocol.BasicMessageMsg.newBuilder().setContent(message))
.build()
)
}
suspend fun sendCredentialOffer(
connectionId: String,
attributes: Map<String, String>,
credDefId: String,
): ProtocolID {
val credAttributes =
attributes.map {
Protocol.IssuingAttributes.Attribute.newBuilder()
.setName(it.key)
.setValue(it.value)
.build()
}
return stub.start(
Protocol.newBuilder()
.setTypeID(Protocol.Type.ISSUE_CREDENTIAL)
.setRole(Protocol.Role.INITIATOR)
.setConnectionID(connectionId)
.setIssueCredential(
Protocol.IssueCredentialMsg.newBuilder()
.setCredDefID(credDefId)
.setAttributes(
Protocol.IssuingAttributes.newBuilder()
.addAllAttributes(credAttributes)
.build()
)
)
.build()
)
}
suspend fun sendProofRequest(
connectionId: String,
attributes: List<ProofRequestAttribute>,
): ProtocolID {
val proofAttributes =
attributes.map {
Protocol.Proof.Attribute.newBuilder().setName(it.name).setCredDefID(it.credDefId).build()
}
return stub.start(
Protocol.newBuilder()
.setTypeID(Protocol.Type.PRESENT_PROOF)
.setRole(Protocol.Role.INITIATOR)
.setConnectionID(connectionId)
.setPresentProof(
Protocol.PresentProofMsg.newBuilder()
.setAttributes(
Protocol.Proof.newBuilder().addAllAttributes(proofAttributes).build()
)
)
.build()
)
}
suspend fun resumeProofRequest(protocolId: String, accept: Boolean): ProtocolID {
return stub.resume(
ProtocolState.newBuilder()
.setProtocolID(
ProtocolID.newBuilder()
.setTypeID(Protocol.Type.PRESENT_PROOF)
.setRole(Protocol.Role.RESUMER)
.setID(protocolId)
)
.setState(if (accept) ProtocolState.State.ACK else ProtocolState.State.NACK)
.build()
)
}
}
| 0
|
Kotlin
|
1
| 0
|
5ea09532bb2ce952f7fdcdf39501050311e70a3b
| 3,665
|
findy-common-kt
|
Apache License 2.0
|
funcify-feature-eng-json/src/main/kotlin/funcify/feature/json/behavior/KJsonScalarBehavior.kt
|
anticipasean
| 458,910,592
| false
|
{"Kotlin": 2751524, "HTML": 1817}
|
package funcify.feature.json.behavior
internal interface KJsonScalarBehavior<WT> : KJsonBehavior<WT>
| 0
|
Kotlin
|
0
| 0
|
284b941de10a5b85b9ba1b5236a1d57289e10492
| 102
|
funcify-feature-eng
|
Apache License 2.0
|
messaging-ui/src/main/java/com/nabla/sdk/messaging/ui/scene/messages/adapter/content/FileMessageContentBinder.kt
|
nabla
| 478,468,099
| false
| null |
package com.nabla.sdk.messaging.ui.scene.messages.adapter.content
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.AttrRes
import coil.load
import com.google.android.material.resources.TextAppearance
import com.nabla.sdk.core.data.helper.toAndroidUri
import com.nabla.sdk.core.data.helper.toJvmUri
import com.nabla.sdk.core.ui.helpers.ColorIntOrStateList
import com.nabla.sdk.core.ui.helpers.coil.LocalPdfPreviewFetcher
import com.nabla.sdk.core.ui.helpers.context
import com.nabla.sdk.core.ui.helpers.getThemeColor
import com.nabla.sdk.core.ui.helpers.getThemeStyle
import com.nabla.sdk.core.ui.helpers.setBackgroundColor
import com.nabla.sdk.messaging.ui.R
import com.nabla.sdk.messaging.ui.databinding.NablaConversationTimelineItemFileMessageBinding
import com.nabla.sdk.messaging.ui.scene.messages.TimelineItem
@SuppressLint("RestrictedApi") // TextAppearance class
internal class FileMessageContentBinder(
@AttrRes contentTextAppearanceAttr: Int,
@AttrRes surfaceColorAttr: Int,
private val binding: NablaConversationTimelineItemFileMessageBinding,
) : MessageContentBinder<TimelineItem.Message.File>() {
private val contentAppearance = TextAppearance(binding.context, binding.context.getThemeStyle(contentTextAppearanceAttr))
private val contentAppearanceRes: Int = binding.context.getThemeStyle(contentTextAppearanceAttr)
private val surfaceColor: ColorIntOrStateList = binding.context.getThemeColor(surfaceColorAttr)
override fun bind(messageId: String, item: TimelineItem.Message.File) {
if (item.thumbnailUri != null) {
binding.chatFileMessagePreviewImageView.load(item.thumbnailUri.toAndroidUri()) {
memoryCacheKey(messageId)
placeholderMemoryCacheKey(messageId)
placeholder(R.drawable.nabla_file_placeholder)
}
} else {
binding.chatFileMessagePreviewImageView.load(item) {
memoryCacheKey(messageId)
placeholderMemoryCacheKey(messageId)
placeholder(R.drawable.nabla_file_placeholder)
error(R.drawable.nabla_file_placeholder)
fetcherFactory<TimelineItem.Message.File> { data, options, _ ->
LocalPdfPreviewFetcher(binding.context, data.uri.toJvmUri(), options)
}
}
}
binding.chatFileMessageTitleContainer.setBackgroundColor(surfaceColor)
binding.chatFileMessageIconImageView.imageTintList = contentAppearance.textColor
binding.chatFileMessageTitleTextView.setTextAppearance(contentAppearanceRes)
binding.chatFileMessageTitleTextView.text = item.fileName
}
companion object {
fun create(
@AttrRes contentTextAppearanceAttr: Int,
@AttrRes surfaceColorAttr: Int,
inflater: LayoutInflater,
parent: ViewGroup,
): FileMessageContentBinder {
return FileMessageContentBinder(
contentTextAppearanceAttr = contentTextAppearanceAttr,
surfaceColorAttr = surfaceColorAttr,
binding = NablaConversationTimelineItemFileMessageBinding.inflate(inflater, parent, true)
)
}
}
}
| 0
|
Kotlin
|
1
| 16
|
83f1c42f21e826dd11b1330fb2d800a67720ea6c
| 3,308
|
nabla-android
|
MIT License
|
app/src/main/java/id/uinjkt/salaamustadz/ui/adapter/profile/AdapterProfileUser.kt
|
Teguhmr
| 848,863,621
| false
|
{"Kotlin": 556881, "Java": 799, "JavaScript": 174}
|
package id.uinjkt.salaamustadz.ui.adapter.profile
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import com.google.android.material.shape.CornerFamily
import com.google.android.material.shape.ShapeAppearanceModel
import id.uinjkt.salaamustadz.R
import id.uinjkt.salaamustadz.data.models.user.ProfileUser
import id.uinjkt.salaamustadz.databinding.ItemDetailProfileBinding
import id.uinjkt.salaamustadz.utils.gone
import id.uinjkt.salaamustadz.utils.show
class AdapterProfileUser(
private val context: Context,
private var dataList: ArrayList<ProfileUser>
): RecyclerView.Adapter<AdapterProfileUser.MenuHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MenuHolder {
return MenuHolder(
ItemDetailProfileBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun getItemCount(): Int {
return dataList.size
}
override fun onBindViewHolder(holder: MenuHolder, position: Int) {
val data = dataList[position]
holder.apply {
data.apply {
txtTitle.text = title
txtSubtitle.text = subtitleData
if (data.title == "Bidang Keilmuan"){
txtSubtitle.gone()
chipGroup.show()
setChipsFromArrayList(listKnowLedge, chipGroup)
}
}
}
}
private fun setChipsFromArrayList(stringList:List<String>, chipGroup: ChipGroup) {
for (text in stringList) {
val shapeAppearanceModel = ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED, 50f)
.build()
val chip = Chip(context)
chip.text = text
chip.setTextColor(ContextCompat.getColor(context, R.color.gray))
chip.textSize = 13f
chip.shapeAppearanceModel = shapeAppearanceModel
chip.setChipBackgroundColorResource(R.color.gray_chip)
chip.chipStrokeWidth = 0f
chip.isCloseIconVisible = false // Set to true if you want to show close icon
chip.isClickable = false
// Set any other properties for the chip as needed (e.g., chip background, text color, etc.)
// Add the chip to the ChipGroup
chipGroup.addView(chip)
}
}
inner class MenuHolder(binding: ItemDetailProfileBinding): RecyclerView.ViewHolder(binding.root) {
val txtTitle: TextView = binding.tvTitle
val txtSubtitle: TextView = binding.tvSubtitle
val chipGroup: ChipGroup = binding.chipGroup
}
}
| 0
|
Kotlin
|
0
| 0
|
305c5c91e2d065342778ac556dbbdcb957e1f71e
| 2,981
|
Salaam-Ustadz
|
Apache License 2.0
|
app/core/src/main/java/com/thechance/core/domain/usecase/coupon/ClipCouponUseCase.kt
|
TheChance101
| 642,833,370
| false
|
{"Kotlin": 344872, "Dockerfile": 185}
|
package com.thechance.core.domain.usecase.coupon
import com.thechance.core.domain.repository.HoneyMartRepository
import com.thechance.core.utils.*
import org.koin.core.component.KoinComponent
class ClipCouponUseCase(private val repository: HoneyMartRepository) : KoinComponent {
suspend operator fun invoke(userId: Long?, role: String?, couponId: Long?): Boolean {
return when {
isInvalidId(userId) || !isValidRole(NORMAL_USER_ROLE, role) -> {
throw InvalidUserIdException()
}
isInvalidId(couponId) -> {
throw InvalidCouponIdException()
}
repository.isCouponClipped(couponId!!, userId!!) -> {
throw CouponAlreadyClippedException()
}
!repository.isValidCoupon(couponId) -> {
throw InvalidCouponException()
}
else -> {
repository.clipCoupon(couponId, userId)
}
}
}
}
| 1
|
Kotlin
|
6
| 22
|
aad54550989c7eb8b75c256c36d2d9f795cbb189
| 991
|
Honey-Mart-Server
|
Apache License 2.0
|
network-protection/network-protection-impl/src/test/java/com/duckduckgo/networkprotection/impl/settings/geoswitching/CountryUtilsKtTest.kt
|
duckduckgo
| 78,869,127
| false
|
{"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784}
|
package com.duckduckgo.networkprotection.impl.settings.geoswitching
import org.junit.Assert.assertEquals
import org.junit.Test
class CountryUtilsTest {
@Test
fun testEmojiForCountryCode() {
assertEquals("🇬🇧", getEmojiForCountryCode("gb"))
assertEquals("🇬🇧", getEmojiForCountryCode("GB"))
assertEquals("🇫🇷", getEmojiForCountryCode("fr"))
assertEquals("🇫🇷", getEmojiForCountryCode("FR"))
assertEquals("🇨🇦", getEmojiForCountryCode("ca"))
assertEquals("🇨🇦", getEmojiForCountryCode("CA"))
assertEquals("🇺🇸", getEmojiForCountryCode("us"))
assertEquals("🇺🇸", getEmojiForCountryCode("US"))
assertEquals("🇩🇪", getEmojiForCountryCode("de"))
assertEquals("🇩🇪", getEmojiForCountryCode("DE"))
assertEquals("🇪🇸", getEmojiForCountryCode("es"))
assertEquals("🇪🇸", getEmojiForCountryCode("ES"))
assertEquals("🇳🇱", getEmojiForCountryCode("nl"))
assertEquals("🇳🇱", getEmojiForCountryCode("NL"))
assertEquals("🏳️", getEmojiForCountryCode(""))
}
}
| 67
|
Kotlin
|
901
| 3,823
|
6415f0f087a11a51c0a0f15faad5cce9c790417c
| 1,069
|
Android
|
Apache License 2.0
|
payment-sdk-core/src/main/java/payment/sdk/android/core/Utils.kt
|
network-international
| 187,156,001
| false
|
{"Kotlin": 374798, "Java": 39575}
|
package payment.sdk.android.core
object Utils {
fun String.getQueryParameter(param: String): String? {
return parseUrlParameters(this)[param]
}
private fun parseUrlParameters(urlString: String): Map<String, String> {
val params = mutableMapOf<String, String>()
val regex = Regex("[?&]([^=]+)=([^&]+)")
val matchResults = regex.findAll(urlString)
for (matchResult in matchResults) {
val (key, value) = matchResult.destructured
params[key] = value
}
return params
}
}
| 2
|
Kotlin
|
7
| 5
|
49bc36af7d87dcd46ef8152e342e4cb4e172de95
| 567
|
payment-sdk-android
|
MIT No Attribution
|
src/com/vitorblog/antiop/model/Jar.kt
|
Jaoow
| 377,959,433
| true
|
{"Kotlin": 12198}
|
package com.vitorblog.antiop.model
import java.io.File
/* <NameWithPackage, Class> */
class Jar(val file:File, val files:HashMap<String, String>)
| 0
| null |
0
| 0
|
f651ac694a6e2d23066af0c082556be13991dd19
| 180
|
BlogAntiForceOp
|
MIT License
|
kotlin-antd/src/main/kotlin/antd/grid/Row.kt
|
rbargues
| 302,350,324
| true
|
{"Kotlin": 1224294, "HTML": 1503}
|
@file:JsModule("antd/lib/grid/row")
@file:JsNonModule
package antd.grid
import antd.*
import org.w3c.dom.*
import react.*
@JsName("default")
external object RowComponent : Component<RowProps, RowState> {
override fun render(): ReactElement?
}
external interface RowProps : HTMLAttributes<HTMLDivElement>, RProps {
var gutter: Any? /* Number | Map<RowBreakpoint, Number> */
var type: RowType?
var align: RowAlign?
var justify: RowJustify?
var prefixCls: String?
}
external interface RowState : RState {
var screens: BreakpointMap
}
| 0
| null |
0
| 0
|
439ef1f01ffea759cf3fc51ede4e60a896cbfd87
| 564
|
kotlin-js-wrappers
|
Apache License 2.0
|
arrow-libs/fx/arrow-fx/src/main/kotlin/arrow/fx/extensions/duration/semigroup/DurationSemigroup.kt
|
clojj
| 343,913,289
| true
|
{"Kotlin": 6274993, "SCSS": 78040, "JavaScript": 77812, "HTML": 21200, "Scala": 8073, "Shell": 2474, "Ruby": 83}
|
package arrow.fx.extensions.duration.semigroup
import arrow.fx.IODeprecation
import arrow.fx.extensions.DurationSemigroup
import arrow.fx.typeclasses.Duration
import arrow.fx.typeclasses.Duration.Companion
import kotlin.Deprecated
import kotlin.PublishedApi
import kotlin.Suppress
import kotlin.jvm.JvmName
/**
* cached extension
*/
@PublishedApi()
internal val semigroup_singleton: DurationSemigroup = object : arrow.fx.extensions.DurationSemigroup
{}
@JvmName("plus")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(IODeprecation)
operator fun Duration.plus(arg1: Duration): Duration =
arrow.fx.typeclasses.Duration.semigroup().run {
this@plus.plus(arg1) as arrow.fx.typeclasses.Duration
}
@JvmName("maybeCombine")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(IODeprecation)
fun Duration.maybeCombine(arg1: Duration): Duration =
arrow.fx.typeclasses.Duration.semigroup().run {
this@maybeCombine.maybeCombine(arg1) as arrow.fx.typeclasses.Duration
}
@Suppress(
"UNCHECKED_CAST",
"NOTHING_TO_INLINE"
)
@Deprecated(IODeprecation)
inline fun Companion.semigroup(): DurationSemigroup = semigroup_singleton
| 0
| null |
0
| 0
|
5eae605bbaeb2b911f69a5bccf3fa45c42578416
| 1,273
|
arrow
|
Apache License 2.0
|
app/src/main/java/com/pechuro/cashdebts/ui/fragment/countryselection/CountrySelectionFragmentViewModel.kt
|
Ilyshka991
| 171,679,797
| false
| null |
package com.pechuro.cashdebts.ui.fragment.countryselection
import androidx.recyclerview.widget.DiffUtil
import com.pechuro.cashdebts.model.entity.DiffResult
import com.pechuro.cashdebts.model.entity.CountryData
import com.pechuro.cashdebts.ui.base.BaseViewModel
import com.pechuro.cashdebts.ui.fragment.countryselection.model.CountrySelectionDiffCallback
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observables.ConnectableObservable
import io.reactivex.rxkotlin.addTo
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class CountrySelectionFragmentViewModel @Inject constructor(
private val countries: List<CountryData>,
private val diffCallback: CountrySelectionDiffCallback
) : BaseViewModel() {
val searchQuery = PublishSubject.create<String>()
val countriesListSource: ConnectableObservable<DiffResult<CountryData>> =
Observable.just(DiffResult(null, countries)).mergeWith(
searchQuery
.debounce(100, TimeUnit.MILLISECONDS)
.distinctUntilChanged()
.map { query ->
countries.filter { it.name.startsWith(query, true) }
}
.map {
val filteredList = mutableListOf<CountryData>()
if (it.isEmpty()) {
filteredList += CountryData.EMPTY
} else {
filteredList += it
}
filteredList
}
.map {
diffCallback.newList = it
val diffResult = DiffUtil.calculateDiff(diffCallback)
diffCallback.oldList = it
DiffResult(diffResult, it)
})
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.replay(1)
init {
countriesListSource.connect().addTo(compositeDisposable)
}
}
| 0
|
Kotlin
|
0
| 3
|
afb871ebb70b2863a1f2c290f7e06a3f5b9feab6
| 2,113
|
CashDebts
|
Apache License 2.0
|
app/src/main/java/com/eltonkola/comfyflux/app/usecase/QueueUseCase.kt
|
eltonkola
| 837,643,078
| false
|
{"Kotlin": 274642, "Jupyter Notebook": 8656}
|
package com.eltonkola.comfyflux.app.usecase
import android.util.Log
import com.eltonkola.comfyflux.data.model.QueueUiState
import com.eltonkola.comfyflux.data.netwrok.FluxAPI
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
class QueueUseCase(
private val fluxAPI: FluxAPI
) {
private val _queueUiState = MutableStateFlow(QueueUiState())
val queueUiState: StateFlow<QueueUiState> = _queueUiState.asStateFlow()
suspend fun loadQueue(showLoading: Boolean = true, onDone: () -> Unit) {
if (showLoading) {
_queueUiState.update { it.copy(loading = true) }
}
try {
val queue = fluxAPI.fetchQueue()
Log.d("HistoryQueueViewModel", "queue pending: ${queue.pending.size}")
_queueUiState.update { it.copy(loading = false, queue = queue, error = false) }
} catch (e: Exception) {
_queueUiState.update { it.copy(loading = false, error = true) }
}
onDone()
}
}
| 0
|
Kotlin
|
1
| 1
|
c0d2a6d106ff9df1bc9cf0ddce6d92a4da1254b7
| 1,099
|
ComfyFlux
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/transformer/PersonTransformer.kt
|
ministryofjustice
| 515,276,548
| false
| null |
package uk.gov.justice.digital.hmpps.approvedpremisesapi.transformer
import org.springframework.stereotype.Component
import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.Person
import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.community.OffenderDetailSummary
import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.prisonsapi.InOutStatus
import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.prisonsapi.InmateDetail
@Component
class PersonTransformer {
fun transformModelToApi(offenderDetailSummary: OffenderDetailSummary, inmateDetail: InmateDetail) = Person(
crn = offenderDetailSummary.otherIds.crn,
name = "${offenderDetailSummary.firstName} ${offenderDetailSummary.surname}",
dateOfBirth = offenderDetailSummary.dateOfBirth,
sex = offenderDetailSummary.gender,
status = inOutStatusToApiStatus(inmateDetail.inOutStatus),
nomsNumber = inmateDetail.offenderNo,
nationality = offenderDetailSummary.offenderProfile.nationality,
religionOrBelief = offenderDetailSummary.offenderProfile.religion,
genderIdentity = when (offenderDetailSummary.offenderProfile.genderIdentity) {
"Prefer to self-describe" -> offenderDetailSummary.offenderProfile.selfDescribedGender
else -> offenderDetailSummary.offenderProfile.genderIdentity
},
prisonName = inOutStatusToApiStatus(inmateDetail.inOutStatus).takeIf { it == Person.Status.inCustody }?.let {
inmateDetail.assignedLivingUnit?.agencyName ?: inmateDetail.assignedLivingUnit?.agencyId
},
)
private fun inOutStatusToApiStatus(inOutStatus: InOutStatus) = when (inOutStatus) {
InOutStatus.IN -> Person.Status.inCustody
InOutStatus.OUT -> Person.Status.inCommunity
InOutStatus.TRN -> Person.Status.inCustody
}
}
| 9
|
Kotlin
|
1
| 1
|
78538b994b84b450dcab3172b4ff66a538447d6d
| 1,775
|
hmpps-approved-premises-api
|
MIT License
|
src/main/kotlin/ui/components/Navigation.kt
|
wcodesoft
| 373,918,234
| false
|
{"Kotlin": 27490}
|
package ui.components
import androidx.compose.foundation.layout.size
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import ui.viewmodel.NavigationViewModel
@Composable
fun Navigation(navigationViewModel: NavigationViewModel) {
val items = navigationViewModel.navigationMenu
val selectedItem by navigationViewModel.selectedItem.collectAsState()
BottomNavigation {
items.forEachIndexed { index, item ->
BottomNavigationItem(
icon = { Icon(item.icon, contentDescription = null, modifier = Modifier.size(20.dp, 20.dp)) },
label = { Text(item.text) },
selected = selectedItem == index,
onClick = { navigationViewModel.selectMenu(index) }
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
69cc64f41fc13e22261f1998980003dffc68c3a8
| 1,003
|
sentency-desktop
|
MIT License
|
app/src/main/kotlin/su/katso/synonym/common/entities/EncryptionInfo.kt
|
dakatso
| 158,115,410
| false
|
{"Kotlin": 57799}
|
package su.katso.synonym.common.entities
import com.google.gson.annotations.SerializedName
data class EncryptionInfo(
@SerializedName("cipherkey")
val cipherKey: String,
@SerializedName("ciphertoken")
val cipherToken: String,
@SerializedName("public_key")
val publicKey: String,
@SerializedName("server_time")
val serverTime: Long
)
| 0
|
Kotlin
|
0
| 1
|
38137f03e94d1c1c864d0faebaffd3cddac70ddc
| 367
|
Synonym
|
Apache License 2.0
|
StorageExplorer/src/main/java/com/commonsware/android/storage/StorageRepository.kt
|
Armyoftheworld
| 620,695,260
| false
| null |
/*
Copyright (c) 2019 CommonsWare, 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.
Covered in detail in the book _Elements of Android Q
https://commonsware.com/AndroidQ
*/
package com.commonsware.android.storage
import android.content.Context
import android.os.Environment
import android.provider.MediaStore
enum class StorageScenario {
INTERNAL_FILES,
EXTERNAL_FILES,
EXTERNAL_CACHE,
EXTERNAL_ROOT,
EXTERNAL_MUSIC,
EXTERNAL_IMAGES,
EXTERNAL_VIDEOS,
EXTERNAL_ALARMS,
EXTERNAL_DCIM,
EXTERNAL_DOCUMENTS,
EXTERNAL_DOWNLOADS,
EXTERNAL_NOTIFICATIONS,
EXTERNAL_PODCASTS,
EXTERNAL_RINGTONES,
MEDIA_MUSIC,
MEDIA_IMAGES,
MEDIA_VIDEOS,
MEDIA_FILES
}
class StorageRepository(val ctxt: Context) {
fun getSource(scenario: StorageScenario): IStorageSource = when (scenario) {
StorageScenario.INTERNAL_FILES -> ContentSource.on(ctxt, ctxt.filesDir)
StorageScenario.EXTERNAL_FILES -> ContentSource.on(
ctxt,
ctxt.getExternalFilesDir(
null
)!!
)
StorageScenario.EXTERNAL_CACHE -> ContentSource.on(
ctxt,
ctxt.externalCacheDir!!
)
StorageScenario.EXTERNAL_ROOT -> ContentSource.on(
ctxt,
Environment.getExternalStorageDirectory()
)
StorageScenario.EXTERNAL_MUSIC -> ContentSource.onPublic(
ctxt,
Environment.DIRECTORY_MUSIC
)
StorageScenario.EXTERNAL_IMAGES -> ContentSource.onPublic(
ctxt,
Environment.DIRECTORY_PICTURES
)
StorageScenario.EXTERNAL_VIDEOS -> ContentSource.onPublic(
ctxt,
Environment.DIRECTORY_MOVIES
)
StorageScenario.EXTERNAL_ALARMS -> ContentSource.onPublic(
ctxt,
Environment.DIRECTORY_ALARMS
)
StorageScenario.EXTERNAL_DCIM -> ContentSource.onPublic(
ctxt,
Environment.DIRECTORY_DCIM
)
StorageScenario.EXTERNAL_DOWNLOADS -> ContentSource.onPublic(
ctxt,
Environment.DIRECTORY_DOWNLOADS
)
StorageScenario.EXTERNAL_DOCUMENTS -> ContentSource.onPublic(
ctxt,
Environment.DIRECTORY_DOCUMENTS
)
StorageScenario.EXTERNAL_NOTIFICATIONS -> ContentSource.onPublic(
ctxt,
Environment.DIRECTORY_NOTIFICATIONS
)
StorageScenario.EXTERNAL_PODCASTS -> ContentSource.onPublic(
ctxt,
Environment.DIRECTORY_PODCASTS
)
StorageScenario.EXTERNAL_RINGTONES -> ContentSource.onPublic(
ctxt,
Environment.DIRECTORY_RINGTONES
)
StorageScenario.MEDIA_MUSIC -> MediaSource(
ctxt,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
ctxt.contentResolver
)
StorageScenario.MEDIA_IMAGES -> MediaSource(
ctxt,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
ctxt.contentResolver
)
StorageScenario.MEDIA_VIDEOS -> MediaSource(
ctxt,
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
ctxt.contentResolver
)
StorageScenario.MEDIA_FILES -> MediaSource(
ctxt,
MediaStore.Files.getContentUri("external"),
ctxt.contentResolver
)
}
}
| 0
|
Kotlin
|
0
| 0
|
eb0bae4d156921709edb384af82bd7aa448b5049
| 3,507
|
cw-android-q
|
Apache License 2.0
|
app/src/main/java/com/jiangkang/ktools/web/HybridActivity.kt
|
155zhang
| 123,068,902
| true
|
{"Kotlin": 387549, "JavaScript": 14024, "HTML": 5095, "CMake": 3043, "CSS": 2570, "C++": 968, "Makefile": 689, "Shell": 429}
|
package com.jiangkang.ktools.web
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.jiangkang.ktools.R
import com.jiangkang.tools.utils.ToastUtils
import kotlinx.android.synthetic.main.activity_hybrid.*
class HybridActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_hybrid)
handleClick()
}
private fun handleClick() {
btnResourceInterceptor.setOnClickListener {
ToastUtils.showShortToast("待开发")
}
btnImgLazyLoading.setOnClickListener {
ToastUtils.showShortToast("待开发")
}
btnCertificateVerify.setOnClickListener {
ToastUtils.showShortToast("待开发")
}
btnGeoRequest.setOnClickListener {
ToastUtils.showShortToast("待开发")
}
btnPageCache.setOnClickListener {
ToastUtils.showShortToast("待开发")
}
btnJsInject.setOnClickListener {
ToastUtils.showShortToast("待开发")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
26ecade56fe1980722975a94b4aae1ad1783309f
| 1,118
|
KTools
|
MIT License
|
order/src/main/kotlin/me/rasztabiga/thesis/order/domain/query/handler/OrderHandler.kt
|
BartlomiejRasztabiga
| 604,846,079
| false
| null |
package me.rasztabiga.thesis.order.domain.query.handler
import me.rasztabiga.thesis.order.adapter.`in`.rest.api.OrderResponse
import me.rasztabiga.thesis.order.domain.command.event.OrderStartedEvent
import me.rasztabiga.thesis.order.domain.query.exception.OrderNotFoundException
import me.rasztabiga.thesis.order.domain.query.mapper.OrderMapper.mapToEntity
import me.rasztabiga.thesis.order.domain.query.mapper.OrderMapper.mapToResponse
import me.rasztabiga.thesis.order.domain.query.query.FindOrderByIdQuery
import org.axonframework.config.ProcessingGroup
import org.axonframework.eventhandling.EventHandler
import org.axonframework.queryhandling.QueryHandler
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono
@Component
@ProcessingGroup("order")
class OrderHandler(
private val orderRepository: OrderRepository
) {
@EventHandler
fun on(event: OrderStartedEvent) {
val entity = mapToEntity(event)
orderRepository.save(entity)
}
@QueryHandler
fun handle(query: FindOrderByIdQuery): Mono<OrderResponse> {
return orderRepository.load(query.orderId)
?.let { Mono.just(mapToResponse(it)) }
?: Mono.error(OrderNotFoundException(query.orderId))
}
}
| 14
|
Kotlin
|
0
| 0
|
a343a10934d0b69d185c3ba632fd2e802077d7f9
| 1,256
|
thesis
|
MIT License
|
androidapp/src/com/lilli/gulliver/TorrentDownloader.kt
|
chenkaigithub
| 57,477,549
| true
|
{"Kotlin": 34863, "Python": 12192, "Java": 3848}
|
package com.lilli.gulliver
import android.content.Context
import com.lilli.gulliver.torrentprovider.TorrentContract
import java.io.File
object TorrentDownloader : Downloader {
val AUTHORITY = "com.lilli.gulliver.torrentprovider"
public override fun getData(resource: String, context: Context?, options: Map<String, String?>?): File? {
val resolver = context?.getContentResolver()
val uri = TorrentContract.Objects.CONTENT_URI
.buildUpon()
?.appendPath(resource)
?.build()
val row = resolver?.query(uri, array(TorrentContract.Objects.DATA), null, null, null)
row?.moveToFirst()
val path = row?.getString(0)
if (path != null) {
return File(path)
}
return null
}
public fun toString() : String {
return "bittorent"
}
}
| 0
|
Kotlin
|
0
| 0
|
e027f48ddee22609c3302b2a9f7f40d522741c5a
| 860
|
lilli
|
The Unlicense
|
app/src/main/java/wannabit/io/cosmostaion/ui/main/chain/evm/EvmEcoSystemViewHolder.kt
|
cosmostation
| 418,314,439
| false
|
{"Java": 5007328, "Kotlin": 3109600, "Shell": 3941}
|
package wannabit.io.cosmostaion.ui.main.chain.evm
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.JsonObject
import com.squareup.picasso.Picasso
import wannabit.io.cosmostaion.R
import wannabit.io.cosmostaion.common.goneOrVisible
import wannabit.io.cosmostaion.databinding.ItemEcoSystemBinding
class EvmEcoSystemViewHolder(
val context: Context, private val binding: ItemEcoSystemBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(info: JsonObject) {
binding.apply {
dappView.setBackgroundResource(R.drawable.item_bg)
val url = info["thumbnail"].asString
Picasso.get().load(url).into(resourceImg)
dappTypeBadge.text = info["type"].asString
dappTitle.text = info["name"].asString
dappDescription.text = info["description"].asString
dappNotImg.goneOrVisible(info.get("support")?.asBoolean ?: true)
}
}
}
| 0
|
Java
|
43
| 83
|
b04f3615c7c7b4407d719e160155a8c03fbae3a9
| 982
|
cosmostation-android
|
MIT License
|
app/src/main/java/com/mbobiosio/rickandmorty/presentation/characterlist/CharacterFragment.kt
|
mbobiosio
| 490,827,613
| false
| null |
package com.mbobiosio.rickandmorty.presentation.characterlist
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.mbobiosio.rickandmorty.R
import com.mbobiosio.rickandmorty.databinding.FragmentCharacterBinding
import com.mbobiosio.rickandmorty.domain.model.Character
import com.mbobiosio.rickandmorty.interfaces.CharacterClickListener
import com.mbobiosio.rickandmorty.utils.safeNavigate
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
@AndroidEntryPoint
class CharacterFragment : Fragment(R.layout.fragment_character), CharacterClickListener {
private lateinit var characterListBinding: FragmentCharacterBinding
private val characterViewModel: CharacterViewModel by viewModels()
private val characterAdapter = CharacterAdapter()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
characterListBinding = FragmentCharacterBinding.bind(view)
setupCharacterRecyclerView()
collectFromViewModel()
}
override fun onCreate(savedInstanceState: Bundle?) {
setHasOptionsMenu(true)
super.onCreate(savedInstanceState)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.search_menu, menu)
val search = menu.findItem(R.id.search)
val searchView = search.actionView as? SearchView
searchView?.isSubmitButtonEnabled = true
searchView?.queryHint = "search..."
searchView?.setQuery(characterViewModel.searchQuery.value, true)
searchView?.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(query: String): Boolean {
performSearchEvent(query)
return false
}
})
}
private fun performSearchEvent(characterName: String) {
characterViewModel.onEvent(CharacterEvent.GetAllCharactersByName(characterName))
}
private fun setupCharacterRecyclerView() {
characterAdapter.characterClickListener = this@CharacterFragment
characterListBinding.apply {
characterRecyclerView.apply {
setHasFixedSize(true)
layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
adapter = characterAdapter
}
}
}
private fun collectFromViewModel() {
lifecycleScope.launch {
characterViewModel.charactersFlow
.collectLatest {
characterAdapter.submitData(it)
}
}
}
override fun onCharacterClicked(character: Character?) {
character?.let {
findNavController().safeNavigate(
CharacterFragmentDirections.actionCharacterFragmentToCharacterDetailFragment(
it
)
)
}
}
}
| 0
|
Kotlin
|
1
| 2
|
d88c43ecb806ddff4a914f9a8e365b4b2f256a18
| 3,452
|
RickAndMorty-GraphQL
|
Apache License 2.0
|
db-async-common/src/main/kotlin/com/github/mauricio/async/db/SSLConfiguration.kt
|
KotlinPorts
| 77,183,383
| false
| null |
package com.github.mauricio.async.db
import java.io.File
/**
*
* Contains the SSL configuration necessary to connect to a database.
*
* @param mode whether and with what priority a SSL connection will be negotiated, default disabled
* @param rootCert path to PEM encoded trusted root certificates, None to use internal JDK cacerts, defaults to None
*
*/
data class SSLConfiguration(val mode: Mode = Mode.Disable, val rootCert: java.io.File? = null) {
constructor(properties: Map<String, String>) :
this(
modeByValue(properties.getOrDefault("sslmode", "disable")),
properties.get("sslrootcert").let { if (it!=null) File(it) else null }
)
companion object SSLConfiguration {
enum class Mode(val value: String) {
Disable("disable"), // only try a non-SSL connection
Prefer("prefer"), // first try an SSL connection; if that fails, try a non-SSL connection
Require("require"), // only try an SSL connection, but don't verify Certificate Authority
VerifyCA("verify-ca"), // only try an SSL connection, and verify that the server certificate is issued by a trusted certificate authority (CA)
VerifyFull("verify-full") // only try an SSL connection, verify that the server certificate is issued by a trusted CA and that the server host name matches that in the certificate
}
fun modeByValue(t: String) = Mode.values().find { it.value == t }!!
}
}
| 5
|
Kotlin
|
2
| 23
|
942ebfeee4601f9580916ed551fcfd2f8084d701
| 1,514
|
pooled-client
|
Apache License 2.0
|
clouddriver-sql/src/main/kotlin/com/netflix/spinnaker/config/SqlEventCleanupAgentConfigProperties.kt
|
spinnaker
| 37,556,951
| false
| null |
/*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.config
import java.time.Duration
import javax.validation.constraints.Positive
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.validation.annotation.Validated
@Validated
@ConfigurationProperties("spinnaker.clouddriver.eventing.cleanup-agent")
class SqlEventCleanupAgentConfigProperties {
/**
* The frequency, in milliseconds, of how often the cleanup agent will run. Defaults to 1 minute.
*/
var frequency: Duration = Duration.ofMinutes(1)
/**
* The ceiling execution time that the agent should be allowed to run before it will be timed out and available for
* reschedule onto a different Clouddriver instance. Defaults to 45 seconds.
*/
var timeout: Duration = Duration.ofSeconds(45)
/**
* The max age of an [Aggregate]. Defaults to 7 days.
*/
@Positive
var maxAggregateAgeDays: Long = 7
/**
* The max number of events to cleanup in each agent invocation. Defaults to 1000.
*/
@Positive
var cleanupLimit: Int = EVENT_CLEANUP_LIMIT
companion object {
const val EVENT_CLEANUP_LIMIT = 1_000
}
}
| 18
| null |
1028
| 434
|
11707d495925eee4665e1e8faf09c0c61ca73a04
| 1,732
|
clouddriver
|
Apache License 2.0
|
documentation/src/test/kotlin/guides/Coroutines.kt
|
smallrye
| 198,222,234
| false
|
{"Java": 3979205, "Kotlin": 37999, "Shell": 3208, "Just": 2073}
|
import io.smallrye.mutiny.Multi
import io.smallrye.mutiny.Uni
// <importStatements>
import io.smallrye.mutiny.coroutines.asFlow
import io.smallrye.mutiny.coroutines.asMulti
import io.smallrye.mutiny.coroutines.asUni
import io.smallrye.mutiny.coroutines.awaitSuspending
// </importStatements>
import io.smallrye.mutiny.coroutines.uni
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
suspend fun uniAwaitSuspending() {
// <uniAwaitSuspending>
val uni: Uni<String> = Uni.createFrom().item("Mutiny ❤ Kotlin")
try {
// Available within suspend function and CoroutineScope
val item: String = uni.awaitSuspending()
} catch (failure: Throwable) {
// onFailure event happened
}
// </uniAwaitSuspending>
}
@ExperimentalCoroutinesApi
suspend fun deferredAsUni() {
// <deferredAsUni>
val deferred: Deferred<String> = GlobalScope.async { "Kotlin ❤ Mutiny" }
val uni: Uni<String> = deferred.asUni()
// </deferredAsUni>
}
@ExperimentalCoroutinesApi
suspend fun multiAsFlow() {
// <multiAsFlow>
val multi: Multi<String> = Multi.createFrom().items("Mutiny", "❤", "Kotlin")
val flow: Flow<String> = multi.asFlow()
// </multiAsFlow>
}
suspend fun flowAsMulti() {
// <flowAsMulti>
val flow: Flow<String> = flowOf("Kotlin", "❤", "Mutiny")
val multi: Multi<String> = flow.asMulti()
// </flowAsMulti>
}
suspend fun uniBuilder() {
// <uniBuilder>
// import io.smallrye.mutiny.coroutines.uni
coroutineScope {
val uni: Uni<String> = uni { "λ 🚧" }
}
// </uniBuilder>
}
| 18
|
Java
|
125
| 814
|
9fe309f9106b7e820be2d5bbe334bd7abe34bc5b
| 1,794
|
smallrye-mutiny
|
Apache License 2.0
|
platform/workspaceModel/ide/src/com/intellij/workspaceModel/ide/impl/IdeVirtualFileUrlManagerImpl.kt
|
LemonNekoGH
| 135,536,587
| false
| null |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.impl.ProjectRootManagerImpl
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.annotations.TestOnly
class IdeVirtualFileUrlManagerImpl(private val project: Project) : VirtualFileUrlManager {
private var testDisposable: Disposable? = null
private var projectDisposable = Disposer.newDisposable(project, "VirtualFileUrlManager")
private val filePointerManager = VirtualFilePointerManager.getInstance()
private val rootsValidityChangedListener
get() = ProjectRootManagerImpl.getInstanceImpl(project).rootsValidityChangedListener
private val virtualFilePointerListener = object: VirtualFilePointerListener {
override fun beforeValidityChanged(pointers: Array<VirtualFilePointer>) {
if (project.isDisposed) return
if (!isValidRootsChangedForWorkspaceModel(pointers)) return;
rootsValidityChangedListener.beforeValidityChanged(pointers)
}
override fun validityChanged(pointers: Array<VirtualFilePointer>) {
if (project.isDisposed) return
if (!isValidRootsChangedForWorkspaceModel(pointers)) return;
rootsValidityChangedListener.validityChanged(pointers)
}
private fun isValidRootsChangedForWorkspaceModel(pointers: Array<VirtualFilePointer>): Boolean {
val entityStorage = WorkspaceModel.getInstance(project).entityStorage.current
val virtualFileUrlIndex = entityStorage.getVirtualFileUrlIndex()
for (pointer in pointers) {
if (virtualFileUrlIndex.findEntitiesByUrl((pointer as VirtualFileUrl)).iterator().hasNext()) return true
}
return false
}
}
override fun fromUrl(url: String): VirtualFileUrl {
return filePointerManager.create(url, testDisposable ?: projectDisposable, virtualFilePointerListener) as VirtualFileUrl
}
fun fromDirUrl(url: String): VirtualFileUrl {
return filePointerManager.createDirectoryPointer(url, true, testDisposable ?: projectDisposable, virtualFilePointerListener) as VirtualFileUrl
}
override fun fromPath(path: String): VirtualFileUrl {
val systemIndependentName = FileUtil.toSystemIndependentName(path)
return fromUrl("file://$systemIndependentName")
}
override fun getParentVirtualUrl(vfu: VirtualFileUrl): VirtualFileUrl? {
val fileUrl = vfu.url
val index = fileUrl.lastIndexOf('/')
return if (index >= 0) fromUrl(fileUrl.substring(0, index)) else null
}
@TestOnly
fun startTrackPointersCreatedInTest() {
testDisposable = Disposer.newDisposable("VirtualFileUrlManager")
}
@TestOnly
fun disposePointersCreatedInTest() {
if (testDisposable != null) {
Disposer.dispose(testDisposable!!)
testDisposable = null
}
}
}
| 1
| null |
1
| 1
|
e75042a90a9a0dcb1f72d0fb48be880ec0a035c3
| 3,383
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/guideme/volunteers/ui/fragments/genericlist/Ext.kt
|
mniami
| 79,149,480
| false
|
{"Kotlin": 138804, "Java": 16817, "Shell": 349}
|
package guideme.volunteers.ui.fragments.genericlist
import guideme.volunteers.helpers.dataservices.datasource.DataSource
import guideme.volunteers.helpers.dataservices.datasource.ObservableDataSource
fun DataSource.isObservableDataSource(): Boolean {
return this is ObservableDataSource<*>
}
| 0
|
Kotlin
|
0
| 1
|
ec79ba258d26206d8cd2ee7eb8ebcdc94696be5f
| 298
|
volunteers
|
Apache License 2.0
|
app/src/main/java/guideme/volunteers/ui/fragments/genericlist/Ext.kt
|
mniami
| 79,149,480
| false
|
{"Kotlin": 138804, "Java": 16817, "Shell": 349}
|
package guideme.volunteers.ui.fragments.genericlist
import guideme.volunteers.helpers.dataservices.datasource.DataSource
import guideme.volunteers.helpers.dataservices.datasource.ObservableDataSource
fun DataSource.isObservableDataSource(): Boolean {
return this is ObservableDataSource<*>
}
| 0
|
Kotlin
|
0
| 1
|
ec79ba258d26206d8cd2ee7eb8ebcdc94696be5f
| 298
|
volunteers
|
Apache License 2.0
|
remoter/src/main/java/remoter/compiler/kbuilder/Common.kt
|
josesamuel
| 100,955,488
| false
|
{"Kotlin": 310103, "Java": 254447, "HTML": 2432, "AIDL": 1911}
|
package remoter.compiler.kbuilder
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.STAR
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.asTypeName
import remoter.annotations.NullableType
import javax.lang.model.element.Element
import javax.lang.model.element.ElementKind
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
import javax.lang.model.type.*
/**
* Returns whether this element is nullable
*/
internal fun Element.isNullable(builder: KRemoterBuilder? = null): Boolean {
return (this.getAnnotation(org.jetbrains.annotations.Nullable::class.java) != null)
}
internal fun TypeMirror.isNullable(builder: KRemoterBuilder? = null): Boolean {
return (this.getAnnotation(org.jetbrains.annotations.Nullable::class.java) != null)
}
internal fun Element.isNullableType(typeIndex: Int, builder: KRemoterBuilder? = null): Boolean {
return this.getAnnotation(NullableType::class.java)?.nullableIndexes?.contains(typeIndex) == true
}
/**
* Checks whether this element has any suspend function methods in it
*/
fun Element.hasSuspendFunction(): Boolean {
var suspendFound = false
if (this is TypeElement) {
for (typeMirror in interfaces) {
if (typeMirror is DeclaredType) {
if (!suspendFound) {
val superElement = typeMirror.asElement()
suspendFound = superElement.hasSuspendFunction()
} else {
break
}
}
}
if (!suspendFound) {
for (member in this.getEnclosedElements()) {
if (!suspendFound) {
if (member.kind == ElementKind.METHOD) {
val executableElement = member as ExecutableElement
suspendFound = executableElement.isSuspendFunction()
}
} else {
break
}
}
}
}
return suspendFound
}
internal fun Element.asKotlinType(builder: KRemoterBuilder? = null, isMutable: Boolean = false) = asType().asKotlinType(builder, this, isMutable).copy(isNullable(builder))
internal fun getNameForClassNameSearch(name: String): String {
val result = name.split(' ').last()
return javaToKotlinMap[result] ?: result
}
internal fun ExecutableElement.getReturnAsKotlinType(builder: KRemoterBuilder? = null): TypeName {
return if (isSuspendFunction()) {
getReturnTypeOfSuspend().asKotlinType(builder, this).copy(this.isSuspendReturningNullable())
} else {
returnType.asKotlinType(builder, this).copy(isNullable())
}
}
internal fun ExecutableElement.getReturnAsTypeMirror(builder: KRemoterBuilder? = null): TypeMirror {
return if (isSuspendFunction()) {
getReturnTypeOfSuspend()
} else {
returnType
}
}
internal fun TypeMirror.asKotlinType(builder: KRemoterBuilder? = null, sourceElement: Element? = null, isMutable: Boolean = false): TypeName {
val name = asTypeName()
val isNullable = getAnnotation(org.jetbrains.annotations.Nullable::class.java) != null
val result = when (kind) {
TypeKind.ARRAY -> {
val aKind = this as ArrayType
val arrayComponentType = aKind.componentType
when (arrayComponentType.kind) {
TypeKind.BOOLEAN -> BooleanArray::class.asTypeName()
TypeKind.BYTE -> ByteArray::class.asTypeName()
TypeKind.CHAR -> CharArray::class.asTypeName()
TypeKind.DOUBLE -> DoubleArray::class.asTypeName()
TypeKind.FLOAT -> FloatArray::class.asTypeName()
TypeKind.INT -> IntArray::class.asTypeName()
TypeKind.LONG -> LongArray::class.asTypeName()
TypeKind.SHORT -> ShortArray::class.asTypeName()
else -> {
val typeIsNullable = sourceElement?.isNullableType(0) == true
ClassName.bestGuess("kotlin.Array").parameterizedBy(arrayComponentType.asKotlinType(builder, sourceElement).copy(typeIsNullable))
}
}
}
TypeKind.WILDCARD -> {
val wType = this as WildcardType
if (name == STAR) {
STAR
} else {
val mappedName = javaToKotlinMap[wType.toString().split(' ').last()]
if (mappedName != null) {
ClassName.bestGuess(getNameForClassNameSearch(mappedName))
} else {
val nameString = name.toString()
if (nameString.contains(' ') || nameString.contains('<')) {
val mainType = ClassName.bestGuess(getNameForClassNameSearch(nameString.split('<').first()))
var result: TypeName = mainType
if (nameString.contains('<')) {
val typeString = nameString.substring(nameString.indexOf('<') + 1, nameString.indexOf('>'))
result = mainType.parameterizedBy(typeString.split(',').map { ClassName.bestGuess(getNameForClassNameSearch(it)).copy(true) })
}
result
} else {
name
}
}
}
}
TypeKind.BOOLEAN -> Boolean::class.asTypeName()
TypeKind.BYTE -> Byte::class.asTypeName()
TypeKind.CHAR -> Char::class.asTypeName()
TypeKind.DOUBLE -> Double::class.asTypeName()
TypeKind.FLOAT -> Float::class.asTypeName()
TypeKind.INT -> Int::class.asTypeName()
TypeKind.LONG -> Long::class.asTypeName()
TypeKind.SHORT -> Short::class.asTypeName()
TypeKind.DECLARED -> {
val declaredType = this as DeclaredType
val elementType = declaredType.asElement()
val mappedName = javaToKotlinMap[elementType.toString()]
val declaredClassName = if (mappedName != null) {
ClassName.bestGuess(getNameForClassNameSearch(mappedName))
} else {
ClassName.bestGuess(elementType.toString())
}
var result: TypeName = declaredClassName
if (declaredType.typeArguments.isNotEmpty()) {
var typeIndex = 0
result = declaredClassName.parameterizedBy(declaredType.typeArguments.map {
val typeArgTypeMirror = it.asKotlinType()
val typeIsNullable = sourceElement?.isNullableType(typeIndex) == true
typeIndex++
if (typeArgTypeMirror != STAR) {
ClassName.bestGuess(getNameForClassNameSearch(it.asKotlinType().toString())).copy(typeIsNullable || it.isNullable())
} else {
typeArgTypeMirror
}
})
}
result
}
else -> {
name
}
}
return result.copy(isNullable)
}
fun ExecutableElement.isSuspendFunction() = parameters.isNotEmpty()
&& parameters.last().asType().toString().contains("kotlin.coroutines.Continuation")
fun ExecutableElement.isSuspendReturningNullable() = getAnnotation(NullableType::class.java) != null
fun ExecutableElement.getReturnTypeOfSuspend(): TypeMirror {
val contiuatinDeclaredType = parameters.last().asType() as DeclaredType
return (contiuatinDeclaredType.typeArguments.first() as WildcardType).superBound
}
| 3
|
Kotlin
|
14
| 81
|
34736563db8d675208be0b0962273e1a7221cdc4
| 7,679
|
remoter
|
Apache License 2.0
|
fork-runner/src/main/java/com/shazam/fork/preprocessor/TestsPreprocessor.kt
|
agoda-com
| 110,643,626
| true
|
{"Gradle": 16, "Java Properties": 17, "Shell": 5, "Ignore List": 4, "Batchfile": 2, "YAML": 1, "Markdown": 1, "Java": 276, "HTML": 9, "CSS": 7, "Kotlin": 38, "Less": 1, "JavaScript": 17, "Groovy": 4, "INI": 3, "Proguard": 1, "XML": 2, "JSON": 2, "JSON with Comments": 1, "SCSS": 12, "Text": 1}
|
package com.shazam.fork.preprocessor
import com.shazam.fork.CustomExecutionStrategy
import com.shazam.fork.model.TestCaseEvent
class TestsPreprocessor(private val executionStrategy: CustomExecutionStrategy) {
fun process(input: Collection<TestCaseEvent>): Collection<TestCaseEvent> {
return if (executionStrategy.flakinessStrategy != null) {
val count = executionStrategy.flakinessStrategy.count
input.flatMap { test ->
(1..count).map { test }
}
} else {
input
}
}
}
| 4
|
Java
|
4
| 16
|
0440615dc627d7650893279eae90f7bd4299a483
| 565
|
fork
|
Apache License 2.0
|
plugins/kotlin/idea/tests/testData/intentions/declarations/convertMemberToExtension/genericClassWithInVariance.kt
|
ingokegel
| 72,937,917
| true
| null |
// AFTER-WARNING: Parameter 'x' is never used
class Foo<in T> {
fun <caret>bar(x: T) {}
}
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 93
|
intellij-community
|
Apache License 2.0
|
src/test/kotlin/com/babylonml/backend/training/operations/AddTests.kt
|
babylonml
| 800,853,059
| false
|
{"Gradle Kotlin DSL": 1, "Shell": 1, "Text": 2, "Ignore List": 1, "Batchfile": 1, "INI": 1, "Kotlin": 21, "Java": 48, "YAML": 2}
|
package com.babylonml.backend.training.operations
import com.babylonml.backend.training.optimizer.SimpleGradientDescentOptimizer
import com.babylonml.backend.training.TrainingExecutionContext
import com.babylonml.matrix.FloatMatrix
import com.babylonml.SeedsArgumentsProvider
import org.apache.commons.rng.simple.RandomSource
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ArgumentsSource
class AddTests {
@ParameterizedTest
@ArgumentsSource(SeedsArgumentsProvider::class)
fun forwardTest(seed: Long) {
val source = RandomSource.ISAAC.create(seed)
val rows = source.nextInt(100)
val columns = source.nextInt(100)
val firstMatrix = FloatMatrix.random(rows, columns, source)
val secondMatrix = FloatMatrix.random(rows, columns, source)
val executionContext = TrainingExecutionContext()
val optimizer =
SimpleGradientDescentOptimizer(NullDataSource())
val learningRate = 0.01f
val firstVariable = firstMatrix.toVariable(executionContext, optimizer, learningRate)
val secondVariable = secondMatrix.toVariable(executionContext, optimizer, learningRate)
val add = Add(executionContext, firstVariable, secondVariable, false)
executionContext.initializeExecution(add)
val result = executionContext.executeForwardPropagation()
val buffer = executionContext.getMemoryBuffer(result)
val resultOffset = TrainingExecutionContext.addressOffset(result)
val expectedResult = firstMatrix + secondMatrix
Assertions.assertArrayEquals(
expectedResult.toFlatArray(),
buffer.copyOfRange(resultOffset, resultOffset + rows * columns), 0.001f
)
}
@ParameterizedTest
@ArgumentsSource(SeedsArgumentsProvider::class)
fun differentiationTest(seed: Long) {
val source = RandomSource.ISAAC.create(seed)
val rows = source.nextInt(100)
val columns = source.nextInt(100)
val firstMatrix = FloatMatrix.random(rows, columns, source)
val secondMatrix = FloatMatrix.random(rows, columns, source)
val executionContext = TrainingExecutionContext()
val optimizer =
SimpleGradientDescentOptimizer(NullDataSource())
val learningRate = 0.01f
val firstVariable = firstMatrix.toVariable(executionContext, optimizer, learningRate)
val secondVariable = secondMatrix.toVariable(executionContext, optimizer, learningRate)
val add = Add(executionContext, firstVariable, secondVariable, false)
val gradients = FloatMatrix.random(rows, columns, source)
val gradientSource = GradientSource(executionContext, rows, columns, gradients.toFlatArray(), add)
executionContext.initializeExecution(gradientSource)
executionContext.executePropagation(1)
val firstExpectedResult = firstMatrix - gradients * learningRate
val secondExpectedResult = secondMatrix - gradients * learningRate
Assertions.assertArrayEquals(firstExpectedResult.toFlatArray(), firstVariable.data, 0.001f)
Assertions.assertArrayEquals(secondExpectedResult.toFlatArray(), secondVariable.data, 0.001f)
}
}
| 1
|
Java
|
0
| 1
|
0caac6021678044e0cec4e7ba9c0041d5509d0ee
| 3,293
|
babylonml
|
Apache License 2.0
|
src/main/kotlin/com/stepanov/bbf/bugfinder/manager/ReportProperties.kt
|
mandelshtamd
| 249,374,670
| false
|
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
|
package com.stepanov.bbf.bugfinder.manager
import com.stepanov.bbf.reduktor.util.ReduKtorProperties
import java.io.File
import java.util.*
object ReportProperties {
private val file = File("bbf.conf")
fun getPropValue(name: String): String? {
val props = Properties()
props.load(file.inputStream())
return props.getProperty(name)
}
fun getPropAsBoolean(name: String): Boolean? = ReduKtorProperties.getPropValue(name)?.toBoolean()
}
| 1
| null |
1
| 1
|
da010bdc91c159492ae74456ad14d93bdb5fdd0a
| 476
|
bbfgradle
|
Apache License 2.0
|
dexplore-cli/src/main/java/io/github/neonorbit/dexplore/CommandLine.kt
|
NeonOrbit
| 477,329,014
| false
|
{"Gradle": 5, "Shell": 5, "Text": 1, "Ignore List": 4, "Batchfile": 2, "Git Attributes": 1, "Markdown": 1, "Kotlin": 27, "Java": 71, "INI": 1, "Smali": 13, "XML": 19}
|
/*
* Copyright (C) 2022 NeonOrbit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.neonorbit.dexplore
internal object CommandLine {
val TITLE: String? = CommandLine::class.java.getPackage().specificationTitle
val VERSION: String? = CommandLine::class.java.getPackage().specificationVersion
@JvmStatic
fun main(args: Array<String>) {
try {
Commander(args).run()
} catch (throwable: Throwable) {
CommandUtils.print()
CommandUtils.error("Error", throwable)
args.takeIf { it.isNotEmpty() }?.first()
.takeIf { it in listOf("-v", "--verbose") }?.let {
CommandUtils.print(throwable.stackTraceToString())
}
CommandUtils.print()
}
}
}
| 0
|
Java
|
5
| 92
|
8dab4cb5b1ff62d67c7a26c490ee4e660c726f7c
| 1,317
|
Dexplore
|
Apache License 2.0
|
dexplore-cli/src/main/java/io/github/neonorbit/dexplore/CommandLine.kt
|
NeonOrbit
| 477,329,014
| false
|
{"Gradle": 5, "Shell": 5, "Text": 1, "Ignore List": 4, "Batchfile": 2, "Git Attributes": 1, "Markdown": 1, "Kotlin": 27, "Java": 71, "INI": 1, "Smali": 13, "XML": 19}
|
/*
* Copyright (C) 2022 NeonOrbit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.neonorbit.dexplore
internal object CommandLine {
val TITLE: String? = CommandLine::class.java.getPackage().specificationTitle
val VERSION: String? = CommandLine::class.java.getPackage().specificationVersion
@JvmStatic
fun main(args: Array<String>) {
try {
Commander(args).run()
} catch (throwable: Throwable) {
CommandUtils.print()
CommandUtils.error("Error", throwable)
args.takeIf { it.isNotEmpty() }?.first()
.takeIf { it in listOf("-v", "--verbose") }?.let {
CommandUtils.print(throwable.stackTraceToString())
}
CommandUtils.print()
}
}
}
| 0
|
Java
|
5
| 92
|
8dab4cb5b1ff62d67c7a26c490ee4e660c726f7c
| 1,317
|
Dexplore
|
Apache License 2.0
|
src/main/kotlin/no/fg/hilflingbackend/controller/SearchController.kt
|
Fotogjengen
| 206,387,255
| false
|
{"Kotlin": 219625, "Java": 3634, "Dockerfile": 1064, "Shell": 891}
|
package no.fg.hilflingbackend.controller
import no.fg.hilflingbackend.dto.MotiveDto
import no.fg.hilflingbackend.service.SearchService
import no.fg.hilflingbackend.utils.ResponseOk
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/search")
class SearchController(val service: SearchService) {
@GetMapping("/{searchTerm}")
fun getBySearchTerm(@PathVariable("searchTerm") searchTerm: String): ResponseEntity<List<MotiveDto>> =
ResponseOk(service.findMotives(searchTerm))
}
| 12
|
Kotlin
|
1
| 1
|
c685c0696d45a6e786b5ce7df5ddafdb5ed5205c
| 755
|
hilfling-photo-backend
|
MIT License
|
ldtk-api/src/commonMain/kotlin/com/lehaine/ldtk/LayerIntGridAutoLayer.kt
|
LeHaine
| 317,728,558
| false
| null |
package com.lehaine.ldtk
open class LayerIntGridAutoLayer(
project: Project,
val tilesetDefJson: TilesetDefinition,
intGridValues: List<IntGridValueDefinition>,
json: LayerInstance
) : LayerIntGrid(project, intGridValues, json) {
open val tileset = project.tilesets[json.tilesetDefUid]!!
val autoTiles: List<LayerAutoLayer.AutoTile> =
json.autoLayerTiles.map {
LayerAutoLayer.AutoTile(
tileId = it.t,
flips = it.f,
renderX = it.px[0],
renderY = it.px[1]
)
}
private val _autoTilesCoordIdMap = mutableMapOf<Int, LayerAutoLayer.AutoTile>()
val autoTilesCoordIdMap: Map<Int, LayerAutoLayer.AutoTile>
init {
json.autoLayerTiles.forEach {
val autoTile = LayerAutoLayer.AutoTile(
tileId = it.t,
flips = it.f,
renderX = it.px[0],
renderY = it.px[1]
)
_autoTilesCoordIdMap[getCoordId(autoTile.renderX / gridSize, autoTile.renderY / gridSize)] = autoTile
}
autoTilesCoordIdMap = _autoTilesCoordIdMap.toMap()
}
}
| 2
|
Kotlin
|
3
| 9
|
dd534a8d90ec9d818c8247f591a0538ef4c2f6a0
| 1,173
|
kt-ldtk-api
|
MIT License
|
app/src/main/java/com/ctech/eaty/response/SearchResponse.kt
|
dbof10
| 116,687,959
| false
| null |
package com.ctech.eaty.response
import com.ctech.eaty.entity.Product
import com.google.gson.annotations.SerializedName
data class SearchResponse(@SerializedName("hits")val products: List<Product>)
| 2
| null |
11
| 49
|
2e3445debaedfea03f9b44ab62744046fe07f1cc
| 198
|
hunt-android
|
Apache License 2.0
|
espressopageobject/src/main/java/com/atiurin/espressopageobject/core/espresso/action/EspressoAction.kt
|
alex-tiurin
| 203,062,137
| false
|
{"Markdown": 12, "Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "YAML": 1, "Proguard": 2, "XML": 41, "Kotlin": 96, "Java": 2}
|
package com.atiurin.espressopageobject.core.espresso.action
import androidx.test.espresso.ViewAction
import androidx.test.espresso.ViewInteraction
import com.atiurin.espressopageobject.core.common.Operation
import com.atiurin.espressopageobject.core.common.OperationIterationResult
import com.atiurin.espressopageobject.core.common.OperationType
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
interface EspressoAction : Operation {
val viewAction: ViewAction
override val name: String
override val type: OperationType
override val description: String
override val timeoutMs: Long
}
| 0
|
Kotlin
|
6
| 21
|
927500c698a84f67e0c15e133db4f5b04ee82b1a
| 656
|
espresso-page-object
|
Apache License 2.0
|
appKotlin/src/main/java/com/pvryan/easycryptsample/Constants.kt
|
ryan652
| 95,847,881
| false
| null |
/*
* Copyright 2018 Priyank Vasa
* 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.pvryan.easycryptsample
internal object Constants {
const val TITLE = "title"
const val SUB_TITLE = "subTitle"
const val INPUT_STRING = "inputString"
const val DEFAULT_PASSWORD_LENGTH = 12
const val rCStoragePermissions = 1
const val rCCameraPermissions = 2
const val rCCameraResult = 3
//const val rCHandleGMS = 9001
/*val ORIENTATIONS = SparseIntArray()
init {
ORIENTATIONS.append(Surface.ROTATION_0, 90)
ORIENTATIONS.append(Surface.ROTATION_90, 0)
ORIENTATIONS.append(Surface.ROTATION_180, 270)
ORIENTATIONS.append(Surface.ROTATION_270, 180)
}*/
}
| 3
|
Kotlin
|
18
| 109
|
4ef803c4bf097079401708caf92be434d11fd8e1
| 1,232
|
EasyCrypt
|
Apache License 2.0
|
src/main/kotlin/coroutines/async.kt
|
nazmulidris
| 116,611,009
| false
| null |
/*
* Copyright 2020 Nazmul Idris All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package coroutines_async
import com.importre.crayon.blue
import kotlinx.coroutines.*
import utils.red
import java.net.URL
import java.net.URLEncoder
import kotlin.reflect.KFunction
fun main() {
println("-- asynchronous".red())
coroutines_sync.runTimedBlock("runSynchronous") {
runAsynchronous()
}
}
fun runAsynchronous() {
runBlocking {
GlobalScope.launch(Dispatchers.IO) {
val deferredList = mutableListOf<Deferred<Any>>()
deferredList += async { execute(::api_debug, "boo") }
deferredList += async { execute(::api_ipify) }
deferredList += async { execute(::api_nominatim, "mountain view, ca") }
deferredList.forEach { it.await() }
}.join()
}
}
// API function implementations.
fun api_debug(vararg args: Any?): String = args.joinToString()
fun api_ipify(vararg args: Any?): String {
val url = "https://api.ipify.org?format=json"
return URL(url).readText()
}
fun api_nominatim(vararg args: Any?): String {
val query = URLEncoder.encode(args[0] as String, "UTF-8")
val url =
"https://nominatim.openstreetmap.org/search" +
"?q=${query}" +
"&format=geojson&addressdetails=1" +
"&limit=1"
return URL(url).readText()
}
// Driver that takes an API function and executes it w/ metering.
suspend fun execute(apiFunction: KFunction<Any>, vararg args: Any?): Any =
runTimedBlock("execute-function") {
println("execute using apiFunction: ${apiFunction.name}")
println("execute on thread: ${Thread.currentThread()}")
val response: Any = apiFunction.call(args)
println("response = ${response}")
response
}
// Utils.
fun runTimedBlock(name: String, block: () -> Any): Any {
val startTime = System.currentTimeMillis()
try {
return block()
}
finally {
val endTime = System.currentTimeMillis()
println("$name block took ${endTime - startTime} ms to run".blue())
}
}
| 1
|
Kotlin
|
1
| 1
|
e7770f3b7003775d3c17f951f636850d1312a2b7
| 2,524
|
kt-scratch
|
Apache License 2.0
|
legacy/ui/legacy/src/main/java/com/fsck/k9/ui/push/PushInfoFragment.kt
|
thunderbird
| 1,326,671
| false
| null |
package com.fsck.k9.ui.push
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import app.k9mail.core.common.provider.AppNameProvider
import com.fsck.k9.controller.push.PushController
import com.fsck.k9.notification.NotificationChannelManager
import com.fsck.k9.ui.R
import com.google.android.material.button.MaterialButton
import com.google.android.material.textview.MaterialTextView
import org.koin.android.ext.android.inject
private const val LEARN_MORE_URL = "https://k9mail.app/go/push-info"
class PushInfoFragment : Fragment() {
private val notificationChannelManager: NotificationChannelManager by inject()
private val pushController: PushController by inject()
private val appNameProvider: AppNameProvider by inject()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_push_info, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
initializeNotificationSection(view)
initializeDisablePushSection(view)
}
private fun initializeNotificationSection(view: View) {
val notificationTextView = view.findViewById<MaterialTextView>(R.id.notificationText)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val configureNotificationText = getString(R.string.push_info_configure_notification_text)
notificationTextView.text = getString(
R.string.push_info_notification_explanation_text,
appNameProvider.appName,
configureNotificationText,
)
val configureNotificationButton = view.findViewById<MaterialButton>(R.id.configureNotificationButton)
configureNotificationButton.isVisible = true
configureNotificationButton.setOnClickListener {
launchNotificationSettings()
}
} else {
notificationTextView.text = getString(
R.string.push_info_notification_explanation_text,
appNameProvider.appName,
"",
)
}
view.findViewById<MaterialButton>(R.id.learnMoreButton).setOnClickListener {
launchLearnMoreAction()
}
}
private fun initializeDisablePushSection(view: View) {
val disablePushButton = view.findViewById<MaterialButton>(R.id.disablePushButton)
disablePushButton.setOnClickListener(::disablePush)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun launchNotificationSettings() {
val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS).apply {
putExtra(Settings.EXTRA_APP_PACKAGE, this@PushInfoFragment.requireContext().packageName)
putExtra(Settings.EXTRA_CHANNEL_ID, notificationChannelManager.pushChannelId)
}
startActivity(intent)
}
private fun launchLearnMoreAction() {
try {
val viewIntent = Intent(Intent.ACTION_VIEW, Uri.parse(LEARN_MORE_URL))
startActivity(viewIntent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(requireContext(), R.string.error_activity_not_found, Toast.LENGTH_SHORT).show()
}
}
private fun disablePush(disablePushButton: View) {
disablePushButton.isEnabled = false
pushController.disablePush()
}
}
| 846
| null |
2467
| 9,969
|
8b3932098cfa53372d8a8ae364bd8623822bd74c
| 3,779
|
thunderbird-android
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Cube.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.Cube: ImageVector
get() {
if (_cube != null) {
return _cube!!
}
_cube = Builder(name = "Cube", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.122f, 0.0f)
lineTo(1.622f, 6.0f)
lineTo(1.622f, 18.0f)
lineToRelative(10.5f, 6.0f)
lineToRelative(10.5f, -6.0f)
lineTo(22.622f, 6.0f)
close()
moveTo(19.635f, 6.6f)
lineTo(12.012f, 10.852f)
lineTo(4.673f, 6.56f)
lineTo(12.122f, 2.3f)
close()
moveTo(3.622f, 8.262f)
lineTo(11.0f, 12.574f)
verticalLineToRelative(8.482f)
lineTo(3.622f, 16.839f)
close()
moveTo(13.0f, 21.194f)
lineTo(13.0f, 12.587f)
lineToRelative(7.622f, -4.251f)
verticalLineToRelative(8.5f)
close()
}
}
.build()
return _cube!!
}
private var _cube: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 2,011
|
icons
|
MIT License
|
app/src/main/java/io/homeassistant/companion/android/settings/websocket/views/WebsocketSettingView.kt
|
psbankar
| 469,704,063
| true
|
{"Kotlin": 1335494}
|
package io.homeassistant.companion.android.settings.websocket.views
import android.app.UiModeManager
import android.content.res.Configuration
import android.os.Build
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.content.getSystemService
import io.homeassistant.companion.android.BuildConfig
import io.homeassistant.companion.android.common.R
import io.homeassistant.companion.android.common.util.websocketChannel
import io.homeassistant.companion.android.database.settings.WebsocketSetting
import io.homeassistant.companion.android.util.compose.InfoNotification
import io.homeassistant.companion.android.util.compose.RadioButtonRow
@Composable
fun WebsocketSettingView(
websocketSetting: WebsocketSetting,
onSettingChanged: (WebsocketSetting) -> Unit
) {
val scrollState = rememberScrollState()
val context = LocalContext.current
Column(
modifier = Modifier
.padding(20.dp)
.verticalScroll(scrollState)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(bottom = 20.dp)
) {
Text(stringResource(R.string.websocket_setting_description))
}
Divider()
RadioButtonRow(
text = stringResource(if (BuildConfig.FLAVOR == "full") R.string.websocket_setting_never else R.string.websocket_setting_never_minimal),
selected = websocketSetting == WebsocketSetting.NEVER,
onClick = { onSettingChanged(WebsocketSetting.NEVER) }
)
RadioButtonRow(
text = stringResource(R.string.websocket_setting_home_wifi),
selected = websocketSetting == WebsocketSetting.HOME_WIFI,
onClick = { onSettingChanged(WebsocketSetting.HOME_WIFI) }
)
RadioButtonRow(
text = stringResource(if (BuildConfig.FLAVOR == "full") R.string.websocket_setting_while_screen_on else R.string.websocket_setting_while_screen_on_minimal),
selected = websocketSetting == WebsocketSetting.SCREEN_ON,
onClick = { onSettingChanged(WebsocketSetting.SCREEN_ON) }
)
RadioButtonRow(
text = stringResource(if (BuildConfig.FLAVOR == "full") R.string.websocket_setting_always else R.string.websocket_setting_always_minimal),
selected = websocketSetting == WebsocketSetting.ALWAYS,
onClick = { onSettingChanged(WebsocketSetting.ALWAYS) }
)
val uiManager = context.getSystemService<UiModeManager>()
if (websocketSetting != WebsocketSetting.NEVER && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && uiManager?.currentModeType != Configuration.UI_MODE_TYPE_TELEVISION) {
InfoNotification(
infoString = R.string.websocket_persistent_notification,
channelId = websocketChannel,
buttonString = R.string.websocket_notification_channel
)
}
}
}
| 0
| null |
0
| 0
|
2de5815123956bde81badac7f413fe0f20484aa3
| 3,486
|
android
|
Apache License 2.0
|
app/src/main/java/com/udacity/loadapp/util/DownloadRequestsStore.kt
|
jploz
| 343,891,618
| false
| null |
package com.udacity.loadapp.util
import android.content.Context
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
class DownloadRequestsStore(context: Context) {
companion object {
const val PREFERENCES_NAME = "com.udacity.loadapp.downloads"
const val KEY_DOWNLOAD_IDS = "DOWNLOADS"
}
private var prefs = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
private suspend fun store(ids: List<Long>) {
withContext(Dispatchers.IO) {
val encoded = Json.encodeToString(ids)
Log.i("DownloadRequestStore", "store: ids = '$ids'")
prefs.edit().putString(KEY_DOWNLOAD_IDS, encoded).apply()
}
}
suspend fun add(id: Long) {
withContext(Dispatchers.IO) {
val ids = getAll()
ids.add(id)
store(ids)
}
}
suspend fun remove(id: Long) {
withContext(Dispatchers.IO) {
val ids = getAll()
ids.remove(id)
store(ids)
}
}
suspend fun getAll(): MutableList<Long> {
val ids = mutableListOf<Long>()
withContext(Dispatchers.IO) {
val encoded = prefs.getString(KEY_DOWNLOAD_IDS, "[]")
encoded?.let { ids.addAll(Json.decodeFromString<List<Long>>(it)) }
Log.i("DownloadRequestStore", "getAll: ids = '$ids'")
}
return ids
}
}
| 0
|
Kotlin
|
0
| 0
|
7259636d163ce979cc7eed61f16444b381ccd274
| 1,584
|
android-nd-load-app
|
Apache License 2.0
|
couchbase-entity/src/test/resources/SimpleMapperTest.kt
|
SchwarzIT
| 92,849,438
| false
| null |
import kaufland.com.coachbasebinderapi.mapify.IMapifyable
import kaufland.com.coachbasebinderapi.mapify.Mapify
import kaufland.com.coachbasebinderapi.mapify.Mapifyable
import kaufland.com.coachbasebinderapi.mapify.Mapper
import java.io.Serializable
@Mapper
class SimpleMapperTest {
@Mapify
private val name : String? = ""
@Mapify
private val innerObject : MyMapifyableTest = MyMapifyableTest()
@Mapify
private val listInnerObject : List<MyMapifyableTest> = listOf(MyMapifyableTest(), MyMapifyableTest())
@Mapify
private val testSerializable : TestSerializable = TestSerializable("test123", 5)
@Mapify
private val booleanValue: Boolean = true
data class TestSerializable(val test1: String, val test2: Int) : Serializable
@Mapifyable(MyMapifyableTest.Mapper::class)
class MyMapifyableTest {
class Mapper : IMapifyable<MyMapifyableTest> {
override fun fromMap(map: Map<String, Any>): MyMapifyableTest {
return MyMapifyableTest()
}
override fun toMap(obj: MyMapifyableTest): Map<String, Any> {
return mapOf()
}
}
}
}
| 0
|
Kotlin
|
0
| 9
|
4cb0ef258f932c9334eafa736768f7ff60fd4d97
| 1,175
|
andcouchbaseentity
|
MIT License
|
libraries/core-ui/src/main/kotlin/io/plastique/core/dialogs/OnConfirmListener.kt
|
plastiqueapp
| 150,879,887
| false
| null |
package io.plastique.core.dialogs
interface OnConfirmListener {
fun onConfirm(dialog: ConfirmationDialogFragment)
}
| 0
|
Kotlin
|
2
| 9
|
9271853f3741add18822858cbad9d4f8e8104f54
| 121
|
plastique
|
Apache License 2.0
|
app/src/main/java/com/chhemsronglong/together/MessageTab/AlertViewModel.kt
|
srongch
| 165,931,762
| false
|
{"Kotlin": 250907}
|
package com.chhemsronglong.together.MessageTab
import android.arch.lifecycle.LiveData
import com.google.android.gms.tasks.OnFailureListener
import com.chhemsronglong.together.Common.*
import com.chhemsronglong.together.DataModel.*
import com.chhemsronglong.together.Firebase.*
import com.chhemsronglong.together.util.map
class AlertViewModel(onFailureListener: OnFailureListener,
private val feedsRepo: FeedPostsRepository) : BaseViewModel(onFailureListener) {
lateinit var uid: String
lateinit var alertList: LiveData<List<UserAlertModel>>
private var notification = mapOf <String, LiveData<AlertModel>>()
fun init(uid: String) {
if (!this::uid.isInitialized) {
this.uid = uid
alertList = feedsRepo.getUserAlerts(uid).map {
it.sortedByDescending {
it.timestamp
}
}
}
}
fun getNotificaiton(notificationId: String): LiveData<AlertModel>? = notification[notificationId]
fun loadNofitication(notificationId: String): LiveData<AlertModel> {
val existingLoadedNotification = getNotificaiton(notificationId)
if (existingLoadedNotification == null) {
val liveData = feedsRepo.getNotification(notificationId)
notification += notificationId to liveData
return liveData
} else {
return existingLoadedNotification
}
}
}
| 0
|
Kotlin
|
0
| 0
|
56fd2f99fbe2e8d010180acd84eaf36a8d47a8b2
| 1,443
|
Together
|
MIT License
|
app/src/main/java/com/android/skeleton/data/feature/GetRecipesRecipe.kt
|
tlundgren
| 409,930,171
| false
|
{"Kotlin": 66971}
|
package com.android.skeleton.data.feature
/**
* Recipe embedded in a [GetRecipesHit].
*/
class GetRecipesRecipe(
val label: String
)
| 0
|
Kotlin
|
0
| 0
|
7328ab2fe8d88ea16d9517d53bc56993ff6b8c66
| 139
|
skeleton_android
|
MIT License
|
src/main/kotlin/top/kanetah/kotlin/pattern/adapterPattern/TestAdapterPattern.kt
|
kanetah
| 125,836,744
| false
| null |
package top.kanetah.kotlin.pattern.adapterPattern
import org.junit.Test
/**
* create by kanetah on 2018/3/26
* 适配器将一个类的接口转换成客户希望的另外一个接口。
* 适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
*/
class TestAdapterPattern {
@Test
fun test() {
val captain = Captain(FishingBoatAdapter())
captain.row()
}
}
| 0
|
Kotlin
|
0
| 0
|
201d093534f2e94c8e295f1bc75a8d520d5ed890
| 319
|
KotlinPattern
|
MIT License
|
modules/vm/src/test/kotlin/org/acornlang/vm/unit/unary.kt
|
mworzala
| 506,414,489
| false
| null |
package org.acornlang.vm.unit
import org.acornlang.vm.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class TestUnaryEval {
@Test
fun `unary negate`() {
val source = """
-1
""".trimIndent()
val value = evalExpr(source)
val intValue = value.assert<IntValue>()
assertEquals(-1, intValue.value)
}
@Test
fun `unary not`() {
val source = """
!false
""".trimIndent()
val value = evalExpr(source)
val intValue = value.assert<BoolValue>()
assertEquals(true, intValue.value)
}
}
| 1
|
Kotlin
|
0
| 0
|
f1b2565aa7c3f0d17f516ce594f96c3eb27a7407
| 646
|
acorn-interpreter
|
Apache License 2.0
|
BazaarPay/src/main/java/ir/cafebazaar/bazaarpay/data/payment/models/pay/BalanceResult.kt
|
cafebazaar
| 489,705,723
| false
|
{"Kotlin": 379916, "Java": 39842}
|
package ir.cafebazaar.bazaarpay.data.payment.models.pay
data class BalanceResult(
val amount: String,
val humanReadableAmount: String
)
| 2
|
Kotlin
|
2
| 9
|
cd3a3befd8eb51fc635133baf356d130502b5d49
| 144
|
BazaarPay
|
Apache License 2.0
|
sample/src/main/java/cn/nekocode/template/screen/UIRouter.kt
|
devopsmi
| 96,514,604
| true
|
{"Kotlin": 5030}
|
package cn.nekocode.template.screen
import android.content.Context
import cn.nekocode.meepo.annotation.Bundle
import cn.nekocode.meepo.annotation.TargetClass
import cn.nekocode.meepo.Meepo
import cn.nekocode.template.data.DO.Meizi
import cn.nekocode.template.screen.page2.Page2Activity
import cn.nekocode.template.screen.page2.Page2Presenter
/**
* @author nekocode (<EMAIL>)
*/
interface UIRouter {
companion object {
val IMPL = Meepo.Builder().build().create(UIRouter::class.java)
}
@TargetClass(Page2Activity::class)
fun gotoPage2(context: Context?, @Bundle(Page2Presenter.ARG_MEIZI) meizi: Meizi) {
IMPL.gotoPage2(context, meizi)
}
}
| 0
|
Kotlin
|
0
| 0
|
33676f670bc796e2b0df8028bcdd2c21f8c5cb46
| 678
|
Kotlin-Android-Template
|
Apache License 2.0
|
src/main/kotlin/ru/nsu_null/npide/ide/platform/Scrollbar.kt
|
null-company
| 423,876,507
| false
|
{"Kotlin": 163037, "ANTLR": 8015}
|
package ru.nsu_null.npide.ide.platform
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.rememberScrollbarAdapter
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
@Composable
fun VerticalScrollbar(
modifier: Modifier,
scrollState: ScrollState
) = androidx.compose.foundation.VerticalScrollbar(
rememberScrollbarAdapter(scrollState),
modifier
)
@Composable
fun VerticalScrollbar(
modifier: Modifier,
scrollState: LazyListState,
itemCount: Int,
averageItemSize: Dp
) = androidx.compose.foundation.VerticalScrollbar(
rememberScrollbarAdapter(scrollState),
modifier
)
| 2
|
Kotlin
|
0
| 2
|
c2549fe8d27df6eedba7443d888a1c2cb6bd9c18
| 759
|
NPidE
|
MIT License
|
kotlin-antd/antd-samples/src/main/kotlin/samples/tabs/Position.kt
|
oxiadenine
| 206,398,615
| false
|
{"Kotlin": 1619835, "HTML": 1515}
|
package samples.tabs
import antd.select.SelectComponent
import antd.select.SelectValue
import antd.select.option
import antd.select.select
import antd.tabs.tabPane
import antd.tabs.tabs
import kotlinx.css.marginBottom
import kotlinx.css.px
import react.*
import react.dom.div
import styled.css
import styled.styledDiv
external interface PositionDemoState : State {
var tabPosition: String
}
class PositionDemo : RComponent<Props, PositionDemoState>() {
private val changeTabPosition = fun(value: SelectValue, _: Any) {
setState {
tabPosition = value.unsafeCast<String>()
}
}
override fun PositionDemoState.init() {
tabPosition = "top"
}
override fun RBuilder.render() {
div {
styledDiv {
css { marginBottom = 16.px }
+"Tab position:"
select<String, SelectComponent<String>> {
attrs {
value = state.tabPosition
onChange = changeTabPosition
dropdownMatchSelectWidth = false
}
option {
attrs.value = "top"
+"top"
}
option {
attrs.value = "bottom"
+"bottom"
}
option {
attrs.value = "left"
+"left"
}
option {
attrs.value = "right"
+"right"
}
}
}
tabs {
attrs.tabPosition = state.tabPosition
tabPane {
attrs {
tab = "Tab 1"
key = "1"
}
+"Content of tab 1"
}
tabPane {
attrs {
tab = "Tab 2"
key = "2"
}
+"Content of tab 2"
}
tabPane {
attrs {
tab = "Tab 3"
key = "3"
}
+"Content of tab 3"
}
}
}
}
}
fun RBuilder.positionDemo() = child(PositionDemo::class) {}
fun RBuilder.position() {
styledDiv {
css { +TabsStyles.position }
positionDemo()
}
}
| 1
|
Kotlin
|
8
| 50
|
e0017a108b36025630c354c7663256347e867251
| 2,562
|
kotlin-js-wrappers
|
Apache License 2.0
|
kotlin-electron/src/jsMain/generated/electron/main/WillNavigateEvent.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 12635434, "JavaScript": 423801}
|
// Generated by Karakum - do not modify it manually!
package electron.main
typealias WillNavigateEvent = electron.core.WillNavigateEvent
| 38
|
Kotlin
|
162
| 1,347
|
997ed3902482883db4a9657585426f6ca167d556
| 139
|
kotlin-wrappers
|
Apache License 2.0
|
library_widget/src/main/java/com/crimson/widget/loading/EmptyLayout.kt
|
crimson0829
| 231,767,479
| false
| null |
package com.crimson.widget.loading
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import com.crimson.widget.R
/**
* @author crimson
* @date 2020-02-21
* 空数据布局
*/
class EmptyLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
init {
val textView = AppCompatTextView(context)
addView(textView)
layoutParams =
LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
textView.apply {
text = context.resources.getString(R.string.widget_loading_empty)
setTextColor(ContextCompat.getColor(context, R.color.textGray))
textSize = 15f
gravity = Gravity.CENTER
val lp = layoutParams
lp.width = ViewGroup.LayoutParams.MATCH_PARENT
lp.height = dp2px(100)
if (lp is LayoutParams) {
lp.gravity = Gravity.CENTER
lp.topMargin = dp2px(40)
}
layoutParams = lp
}
}
/**
* dip to px
*/
private fun dp2px(dpValue: Int): Int {
val scale = context?.resources?.displayMetrics?.density ?: 0f
return (dpValue * scale + 0.5).toInt()
}
}
| 0
|
Kotlin
|
1
| 1
|
f5a7282fa1c288b6f02f593ac903ba438e2ed247
| 1,516
|
MVVM_Module
|
Apache License 2.0
|
app/src/main/kotlin/com/whereismymotivation/ui/navigation/Destination.kt
|
unusualcodeorg
| 730,655,456
| false
|
{"Kotlin": 472092}
|
package com.whereismymotivation.ui.navigation
import androidx.navigation.NavType
import androidx.navigation.navArgument
object Destination {
data object Splash : Screen("splash")
data object Login : Screen("login")
data object Onboarding : Screen("onboarding")
data object ServerUnreachable : Screen("server-unreachable")
data object ExploreMentors : Screen("explore-mentor")
data object Mentor : DynamicScreen("mentor", "mentorId")
data object Topic : DynamicScreen("topic", "topicId")
data object YouTube : DynamicScreen("youtube", "contentId")
data object Content : DynamicScreen("content", "contentId")
data object Home : Screen("home") {
data object Feed : Screen("home/feed")
data object Mentors : Screen("home/mentors")
data object MyBox : Screen("home/my_box")
data object Search : DynamicScreen("home/search", "searchMode")
data object Profile : DynamicScreen("home/profile", "profileTab")
}
abstract class Screen(baseRoute: String) {
companion object {
const val baseDeeplinkUrl = "app://wimm"
}
open val route = baseRoute
open val deeplink = "${baseDeeplinkUrl}/$baseRoute"
}
abstract class DynamicScreen(
private val baseRoute: String,
val routeArgName: String,
) : Screen(baseRoute) {
val navArguments = listOf(navArgument(routeArgName) { type = NavType.StringType })
override val route = "$baseRoute/{$routeArgName}"
override val deeplink = "${baseDeeplinkUrl}/$baseRoute/{$routeArgName}"
fun dynamicRoute(param: String) = "$baseRoute/$param"
fun dynamicDeeplink(param: String) = "$baseDeeplinkUrl/$baseRoute/${param}"
}
}
| 0
|
Kotlin
|
4
| 38
|
5b77e6a6b14ae9ad21e8edd55e8c9b3cc2066f75
| 1,752
|
wimm-android-app
|
Apache License 2.0
|
app/src/main/java/com/mayur/banksymoney/data/local/database/DateConverter.kt
|
mayurdw
| 593,101,496
| false
| null |
package com.mayur.banksymoney.data.local.database
import androidx.room.TypeConverter
import java.time.Month
/**
* Copied from [https://developer.android.com/training/data-storage/room/referencing-data]
* */
class DateConverter {
@TypeConverter
fun toMonth(value: Int) : Month {
return Month.of(value)
}
@TypeConverter
fun fromMonth(month: Month) : Int {
return month.value
}
}
| 0
|
Kotlin
|
0
| 0
|
5b6f3e71caf96415d235cb74e14a4c46fa1d30a2
| 423
|
BanksyMoney
|
MIT License
|
app/src/main/java/de/svedie/eqonomize/fragments/EqonomizeFileFragment.kt
|
svedie
| 165,522,109
| false
| null |
package de.svedie.eqonomize.fragments
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.provider.OpenableColumns
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import de.svedie.eqonomize.R
import de.svedie.eqonomize.adapters.EqonomizeFileAdapter
import de.svedie.eqonomize.database.entities.EqonomizeFile
import de.svedie.eqonomize.database.service.EqonomizeFileService
import de.svedie.eqonomize.utils.common.AppConstants
import de.svedie.eqonomize.utils.common.MessageDialog
import kotlinx.android.synthetic.main.eqonomizefile_fragment.view.*
/**
* EqonomizeFile fragment, where the user opens, creates or selects files.
*
* @author svedie
*/
class EqonomizeFileFragment : Fragment() {
private lateinit var mainView: View
companion object {
const val READ_FILE_RESULT_CODE = 1
const val CREATE_FILE_RESULT_CODE = 2
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mainView = inflater.inflate(R.layout.eqonomizefile_fragment, container, false)
mainView.file_activity_b_select_file?.setOnClickListener { selectFileIntent() }
mainView.file_activity_b_create_file?.setOnClickListener { createFile(mainView.context) }
setAdapter(mainView)
return mainView
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if ((requestCode == READ_FILE_RESULT_CODE || requestCode == CREATE_FILE_RESULT_CODE)
&& resultCode == Activity.RESULT_OK
) {
var name = ""
var path = ""
data?.data?.let { uri ->
path = uri.path
this.context!!.contentResolver.query(uri, null, null, null, null)
}?.use { cursor ->
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
cursor.moveToFirst()
name = cursor.getString(nameIndex)
cursor.close()
}
if (name.endsWith(AppConstants.EXTENSION)) {
EqonomizeFileService(this.context!!).insertFile(EqonomizeFile(path, name))
setAdapter(mainView)
} else {
MessageDialog(this.context!!).showErrorDialog(
R.string.eqonomizefile_activity_dialog_error,
R.string.eqonomizefile_activity_dialog_error_file,
null
)
}
}
}
/**
* Shows an alert dialog to user and calls createFileIntent method.
*/
private fun createFile(viewContext: Context) {
val dialog = MessageDialog(viewContext)
dialog.showAlertDialog(R.string.eqonomizefile_activity_dialog_alert,
R.string.eqonomizefile_activity_dialog_alert_file,
DialogInterface.OnClickListener { _: DialogInterface, _: Int ->
createFileIntent()
}
)
}
/**
* Open a file using Android Storage Framework.
*/
private fun selectFileIntent() {
val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
type = "*/*"
}
startActivityForResult(intent, READ_FILE_RESULT_CODE)
}
/**
* Create a file using Android Storage Framework.
*/
private fun createFileIntent() {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "*/*"
intent.putExtra(Intent.EXTRA_TITLE, AppConstants.FILE_NAME)
startActivityForResult(intent, CREATE_FILE_RESULT_CODE)
}
/**
* Sets an adapter to the list.
*/
private fun setAdapter(mainView: View) {
val fileAdapter =
EqonomizeFileAdapter(mainView.context, EqonomizeFileService(mainView.context).getAll())
mainView.file_activity_lv_files.adapter = fileAdapter
mainView.file_activity_lv_files.setOnItemClickListener { _, _, _, _ -> println("onClickListener") }
mainView.file_activity_lv_files.setOnItemLongClickListener { _, _, _, _ ->
println("onLongClickListener")
true
}
}
}
| 0
|
Kotlin
|
0
| 0
|
114bb1631a37b0b4280364732992cd29088b58b2
| 4,004
|
Eqonomize-Android
|
MIT License
|
modules/conflate-jvm/src/test/kotlin/com/encodeering/conflate/experimental/jvm/co/RequeueContinuationTest.kt
|
encodeering
| 81,722,175
| false
| null |
package com.encodeering.conflate.experimental.jvm.co
import com.encodeering.conflate.experimental.test.any
import com.encodeering.conflate.experimental.test.mock
import com.encodeering.conflate.experimental.test.whenever
import com.winterbe.expekt.expect
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.mockito.Mockito.never
import org.mockito.Mockito.verify
import kotlin.coroutines.experimental.Continuation
import kotlin.coroutines.experimental.CoroutineContext
/**
* @author <NAME> - <EMAIL>
*/
@RunWith (JUnitPlatform::class)
class RequeueContinuationTest : Spek ({
describe ("RequeueException") {
fun exception () = RequeueException("message")
it ("should be a runtime exception") {
expect (exception ()).to.satisfy { it is RuntimeException }
}
}
describe ("RequeueContinuation") {
class RequeueTestContinuation<in T> (
continuation : Continuation<T>,
val immediately : Boolean,
val success : () -> Boolean
) : RequeueContinuation<T> (continuation) {
override fun immediately () = immediately
override fun requeue (call : () -> Unit) : Boolean = success ().apply { if (this) call () }
}
fun <T> immediate (continuation : Continuation<T>) = RequeueTestContinuation (continuation, true, { true })
fun <T> requeue (continuation : Continuation<T>, success : Boolean = true) = RequeueTestContinuation (continuation, false, { success })
fun <T> continuation () = mock<Continuation<T>> ()
fun context () = mock<CoroutineContext> ()
it ("uses the given coroutine context") {
val continuation = continuation<Int> ()
val context = context ()
whenever (continuation.context).thenReturn (context)
expect (immediate (continuation).context).to.equal (context)
expect (requeue (continuation).context).to.equal (context)
}
describe ("immediate") {
it ("should resume") {
val continuation = continuation<Int> ()
immediate (continuation).resume (42)
verify (continuation).resume (42)
verify (continuation, never ()).resumeWithException (any ())
}
it ("should resume with an exception") {
val continuation = continuation<Int> ()
val exception = IllegalStateException ()
immediate (continuation).resumeWithException (exception)
verify (continuation, never ()).resume (any ())
verify (continuation).resumeWithException (exception)
}
}
describe ("requeue") {
it ("should resume") {
val continuation = continuation<Int> ()
requeue (continuation, true).resume (42)
verify (continuation).resume (42)
verify (continuation, never ()).resumeWithException (any ())
}
it ("should resume with an exception") {
val continuation = continuation<Int> ()
val exception = IllegalStateException ()
requeue (continuation, true).resumeWithException (exception)
verify (continuation, never ()).resume (any ())
verify (continuation).resumeWithException (exception)
}
it ("should resume with an exception if resume can't be requeued") {
val continuation = continuation<Int> ()
requeue (continuation, false).resume (42)
verify (continuation, never ()).resume (any ())
verify (continuation).resumeWithException (RequeueException("couldn't requeue '42' message on the looper"))
}
it ("should resume with an exception if resume-with-an-exception can't be requeued") {
val continuation = continuation<Int> ()
val exception = IllegalStateException ("oink")
requeue (continuation, false).resumeWithException (exception)
verify (continuation, never ()).resume (any ())
verify (continuation).resumeWithException (RequeueException("couldn't requeue 'java.lang.IllegalStateException: oink' message on the looper"))
}
}
}
})
| 3
|
Kotlin
|
0
| 1
|
51fd2e4cee32e29bb72cd182611393d7f8420914
| 4,555
|
conflate
|
Apache License 2.0
|
app/src/main/java/me/pisal/abaclone/model/entity/User.kt
|
pisalcoding
| 528,368,088
| false
|
{"Kotlin": 97565, "Java": 10129}
|
package me.pisal.abaclone.model.entity
import java.io.Serializable
data class User(
val id: String,
val name: String,
val dob: String? = null,
val occupation: String? = null,
val profileUrl: String? = null,
): Serializable
| 0
|
Kotlin
|
0
| 3
|
eb85740b5a43588d74db121179092bc5816bf9e8
| 244
|
aba-ui-clone
|
Apache License 2.0
|
ROOMDemo/app/src/main/java/com/jjh/android/roomdemo/db/FriendRepository.kt
|
johnehunt
| 277,604,143
| false
| null |
package com.jjh.android.roomdemo.db
import android.app.Application
import android.util.Log
import com.jjh.android.roomdemo.model.Friend
import io.reactivex.rxjava3.core.Observable
class FriendRepository(private val application: Application,
private val schedulerProvider: SchedulerProvider = DefaultSchedulerProvider) {
companion object {
private const val TAG = "FriendRepository"
}
private val friendDao: FriendDao =
FriendRoomDatabase.getDatabase(application).friendDao()
fun close() {
FriendRoomDatabase.getDatabase(application).close()
}
fun insertFriend(friend: Friend): Observable<Long> {
return Observable.create<Long> {
val result = friendDao.insert(friend)
it.onNext(result)
it.onComplete()
}.subscribeOn(schedulerProvider.newThread())
}
fun findAllFriends(): Observable<List<Friend>> {
return Observable.create<List<Friend>> {
val results = friendDao.findAll()
it.onNext(results)
it.onComplete()
}.subscribeOn(schedulerProvider.newThread())
.doOnNext { Log.d(TAG, "findAllFriendsObservable next: $it") }
.doOnError { Log.d(TAG, "findAllFriendsObservable error $it") }
.doOnComplete { Log.d(TAG, "findAllFriendsObservable Completed") }
}
fun findFriendById(id: Int): Observable<Friend> {
return Observable.create<Friend> {
Log.d(TAG, "findFriendById($id) - starting Observable")
val friend = friendDao.findById(id)
Log.d(TAG, "findFriendById($id) - search completed emitting data")
it.onNext(friend)
it.onComplete()
}.subscribeOn(schedulerProvider.newThread())
}
fun deleteFriend(friend: Friend): Observable<Int> {
return Observable.create<Int> {
val result = friendDao.delete(friend)
it.onNext(result)
it.onComplete()
}.subscribeOn(schedulerProvider.newThread())
}
fun deleteFriendById(id: Int): Observable<Int> {
return Observable.create<Int> {
val result = friendDao.deleteById(id)
it.onNext(result)
it.onComplete()
}.subscribeOn(schedulerProvider.newThread())
}
}
| 0
|
Kotlin
|
1
| 1
|
5f3640ff4c37270b28cd7fa00c77e45039e2592d
| 2,315
|
kotlin-android
|
Apache License 2.0
|
src/main/java/com/sdk/platform/apis/audittrail/AuditTrailApiList.kt
|
gofynd
| 337,940,340
| false
| null |
package com.sdk.platform.apis.audittrail
import kotlinx.coroutines.Deferred
import retrofit2.Response
import okhttp3.ResponseBody
import retrofit2.http.*
import com.sdk.platform.*
import com.sdk.platform.models.audittrail.*
interface AuditTrailApiList {
@GET ("/service/platform/audit-trail/v1.0/company/{company_id}/logs/")
fun getAuditLogs(@Path("company_id") companyId: String, @Query("qs") qs: String)
: Deferred<Response<LogSchemaResponse>>
@POST ("/service/platform/audit-trail/v1.0/company/{company_id}/logs/")
fun createAuditLog(@Path("company_id") companyId: String,@Body body: RequestBodyAuditLog)
: Deferred<Response<CreateLogResponse>>
@GET ("/service/platform/audit-trail/v1.0/company/{company_id}/logs/{id}")
fun getAuditLog(@Path("company_id") companyId: String, @Path("id") id: String)
: Deferred<Response<LogSchemaResponse>>
@GET ("/service/platform/audit-trail/v1.0/company/{company_id}/entity-types")
fun getEntityTypes(@Path("company_id") companyId: String)
: Deferred<Response<EntityTypesResponse>>
}
| 0
|
Kotlin
|
4
| 4
|
5e0246485c5e7fc207734325e283b6b201ef6a31
| 1,096
|
fdk-client-kotlin
|
MIT License
|
src/main/kotlin/nl/marc/game/GameWithChosenNumbers.kt
|
AvansInformatica-Marc
| 260,951,112
| false
| null |
package nl.marc.game
class GameWithChosenNumbers(override val numbers: List<Int>, override val result: Int) : Game()
| 0
|
Kotlin
|
0
| 0
|
d7380c04133b139c527993c917bcac6a83f7616d
| 118
|
CalculateNumberAI
|
MIT License
|
travako-starter/travako-starter-processor/src/main/java/io/arkitik/travako/starter/processor/logger/logger-ext.kt
|
arkitik
| 441,685,610
| false
| null |
package io.arkitik.travako.starter.processor.logger
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* Created By [*<NAME> *](https://www.linkedin.com/in/iloom/)
* Created At 30 10:03 PM, **Thu, December 2021**
* Project *travako* [arkitik.io](https://arkitik.io)
*/
inline fun <reified T> logger(): Logger {
return LoggerFactory.getLogger(T::class.java)
}
| 1
|
Kotlin
|
0
| 3
|
567a8d28861733b2a8a56c8b052e3cc91977e7e7
| 378
|
travako
|
Apache License 2.0
|
src/main/kotlin/topic_2/NumberOfWords.kt
|
GionRubitschung
| 708,739,829
| false
|
{"Kotlin": 8611}
|
package topic_2
fun getNumOfWords(sentence: String): Int {
/**
* `(\p{L}+)` captures one or more unicode letters and puts the match into a group --> matches a word in any language
*
* `|` the or operator, separates the word matcher with the separator matcher
*
* `[^\p{L}]+` captures all characters that are not unicode letters --> separators
*/
val groupWordsPattern = "(?<word>\\p{L}+)|[^\\p{L}]+".toRegex()
val words = groupWordsPattern.findAll(sentence)
/**
* Maps all group "word" matches to a list and returns the size
*/
return words.map { it.groups["word"]?.value }.filterNotNull().toList().size
}
fun main(args: Array<String>) {
val input = args.joinToString(separator = " ")
val words = getNumOfWords(input)
println("\"$input\" contains $words words")
}
| 0
|
Kotlin
|
0
| 0
|
b42267a9c18fdeb75150bcadd5f7b264546b7f78
| 839
|
kotlin_1
|
MIT License
|
androidApp/src/main/java/secret/formula/android/ui/design/Typography.kt
|
RamziJabali
| 579,563,509
| false
|
{"Kotlin": 19442, "Ruby": 1706, "Swift": 342}
|
package io.etip.mobile.android.ui.design
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
// Set of Material typography styles to start with
object Typography {
val GraphikTypography = Typography(
h1 = TextStyle(
fontFamily = Fonts.Graphik,
fontWeight = FontWeight.W500,
fontSize = TextSize.xxl,
color = Color.EtipBlue
),
h2 = TextStyle(
fontFamily = Fonts.Graphik,
fontWeight = FontWeight.W500,
fontSize = TextSize.xl,
color = Color.EtipBlue
),
h3 = TextStyle(
fontFamily = Fonts.Graphik,
fontWeight = FontWeight.W500,
fontSize = TextSize.l,
color = Color.EtipBlue
),
h4 = TextStyle(
fontFamily = Fonts.Graphik,
fontWeight = FontWeight.W400,
fontSize = TextSize.m,
color = Color.EtipBlue
),
h5 = TextStyle(
fontFamily = Fonts.Graphik,
fontWeight = FontWeight.W400,
fontSize = TextSize.s,
color = Color.EtipBlue
),
h6 = TextStyle(
fontFamily = Fonts.Graphik,
fontWeight = FontWeight.W400,
fontSize = TextSize.xs,
color = Color.EtipBlue
),
subtitle1 = TextStyle(
fontFamily = Fonts.Graphik,
fontWeight = FontWeight.W400,
fontSize = TextSize.xs,
),
subtitle2 = TextStyle(
fontFamily = Fonts.Graphik,
fontWeight = FontWeight.W400,
fontSize = TextSize.xxs
),
button = TextStyle(
fontFamily = Fonts.Graphik,
fontWeight = FontWeight.W400,
fontSize = TextSize.xs,
color = Color.White
)
)
}
| 0
|
Kotlin
|
0
| 0
|
bc05ce514856fae9aaf040aeae8405e6568d8d00
| 1,930
|
secret-formula-kmm
|
Apache License 2.0
|
src/test/kotlin/org/rust/ide/formatter/RsSingleImportRemoveBracesFormatProcessorTest.kt
|
SaarYogev
| 211,165,404
| true
|
{"Kotlin": 3257698, "Rust": 77474, "Lex": 18933, "HTML": 11268, "Shell": 760, "Java": 586, "RenderScript": 318}
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.formatter
class RsSingleImportRemoveBracesFormatProcessorTest : RsFormatterTestBase() {
fun `test remove braces if single import`() = doTextTest("use getopts::{optopt};", "use getopts::optopt;")
fun `test remove braces if single import with alias`() =
doTextTest("use getopts::{A as B};", "use getopts::A as B;")
fun `test remove braces if single import with alias and comma`() =
doTextTest("use getopts::{A as B,};", "use getopts::A as B;")
fun `test won't remove braces if single import with alias with left comment`() =
checkNotChanged("use getopts::{/*comment*/A as B};")
fun `test won't remove braces if single import with alias with right comment`() =
checkNotChanged("use getopts::{A as B/*comment*/};")
fun `test won't remove braces if single import with alias with inner left comment`() =
checkNotChanged("use getopts::{A /*comment*/as B};")
fun `test won't remove braces if single import with alias with inner right comment`() =
checkNotChanged("use getopts::{A as /*comment*/ B};")
fun `test remove braces if single import with extra comma`() =
doTextTest("use getopts::{optopt,};", "use getopts::optopt;")
fun `test won't remove braces if import with left comment`() = checkNotChanged("use getopts::{/*comment*/optopt};")
fun `test won't remove braces if import with right comment`() = checkNotChanged("use getopts::{optopt/*comment*/};")
fun `test wont remove braces if multi import`() = checkNotChanged(
"use getopts::{optopt, optarg};"
)
fun `test won't remove braces for single self`() = checkNotChanged(
"use getopts::{self};"
)
fun `test remove braces with multiple imports`() = doTextTest(
"""
use getopts::{optopt};
use std::io::{self, Read, Write};
use std::Vec::{Vec};
use std::Vec::{Vec,};
use getopts::{A as B};
""", """
use getopts::optopt;
use std::io::{self, Read, Write};
use std::Vec::Vec;
use std::Vec::Vec;
use getopts::A as B;
""")
}
| 0
| null |
0
| 1
|
26be75d84b07150b9f4687216cc4923221de659f
| 2,237
|
intellij-rust
|
MIT License
|
data_collector/src/main/kotlin/com/sortinghat/backend/data_collector/utils/HttpAbstraction.kt
|
the-sortinghat
| 529,660,037
| false
| null |
package com.sortinghat.backend.data_collector.utils
interface HttpAbstraction<T> {
fun get(url: String): ResponseHttp<T>
}
| 0
|
Kotlin
|
0
| 0
|
95695a1808e477ce67d8257891f4fa9be21f8cce
| 128
|
backend
|
MIT License
|
lib/src/commonMain/kotlin/xyz/mcxross/ksui/model/Transaction.kt
|
mcxross
| 611,172,630
| false
| null |
package xyz.mcxross.ksui.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import xyz.mcxross.ksui.model.serializer.DisassembledFieldSerializer
import xyz.mcxross.ksui.model.serializer.ObjectChangeSerializer
@Serializable
data class Transaction(
val data: Data,
val txSignatures: List<String>,
)
@Serializable
abstract class TransactionKind {
@Serializable
data class DefaultTransaction(
val kind: String,
) : TransactionKind()
data class MoveCall(
@SerialName("package") val pakage: String,
val module: String,
val function: String,
@SerialName("type_arguments") val typeArguments: List<String>? = emptyList(),
) : TransactionKind()
@Serializable
data class Transfer(
val recipient: String,
@SerialName("objectRef") val objectReference: ObjectReference
) : TransactionKind()
@Serializable
data class PaySui(
val coins: List<ObjectReference>,
val recipients: List<String>,
val amounts: List<Long>,
) : TransactionKind()
@Serializable
data class TransferSui(
val recipient: String,
val amount: Long,
) : TransactionKind()
@Serializable
data class PayAllSui(
val recipient: String,
val coins: List<ObjectReference>,
) : TransactionKind()
@Serializable
data class Publish(
@Serializable(with = DisassembledFieldSerializer::class) val disassembled: Any,
) : TransactionKind()
@Serializable
data class SplitCoin(
@SerialName("SplitCoins") val splitCoins: List<String>,
) : TransactionKind()
}
@Serializable
data class TransactionBlockResponse(
val digest: String,
val transaction: Transaction? = null,
val rawTransaction: String = "",
val effects: Effects? = null,
val events: List<Event> = emptyList(),
@Serializable(with = ObjectChangeSerializer::class)
val objectChanges: List<ObjectChange> = emptyList(),
val balanceChanges: List<BalanceChange> = emptyList(),
val timestampMs: Long,
val checkpoint: Long,
)
/** The options for the transaction response. */
@Serializable
data class TransactionBlockResponseOptions(
val showInput: Boolean,
val showRawInput: Boolean,
val showEffects: Boolean,
val showEvents: Boolean,
val showObjectChanges: Boolean,
val showBalanceChanges: Boolean
)
| 0
|
Kotlin
|
0
| 0
|
163a0be41d3841e2be7770eff20afb6d7aeb57a8
| 2,276
|
ksui
|
Apache License 2.0
|
kotlin-compiler-plugin-common/src/main/kotlin/com/lightningkite/khrysalis/util/actualFqName.kt
|
lightningkite
| 161,243,441
| false
| null |
package com.lightningkite.khrysalis.util
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.js.descriptorUtils.getJetTypeFqName
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
val DeclarationDescriptor.simpleFqName: String get() = when{
this is SyntheticJavaPropertyDescriptor -> {
val result = getMethod.containingDeclaration.fqNameSafe.asString() + "." + this.fqNameSafe.asString()
result
}
this is FunctionDescriptor && this.extensionReceiverParameter != null -> this.fqNameSafe.asString() + (this.extensionReceiverParameter?.type?.fqNameWithTypeArgs?.let { ">$it" } ?: "")
this is PropertyDescriptor && this.extensionReceiverParameter != null -> this.fqNameSafe.asString() + (this.extensionReceiverParameter?.type?.fqNameWithTypeArgs?.let { ">$it" } ?: "")
else -> this.fqNameSafe.asString().substringBefore(".<")
}
val DeclarationDescriptor.simplerFqName: String get() = this.fqNameSafe.asString()
val DeclarationDescriptor.fqNamesToCheck: Sequence<String> get() = sequenceOf(
simpleFqName,
simplerFqName
).plus(arrayTypes.asSequence().mapNotNull { if(this.fqNameSafe.asString().startsWith(it)) "array" + this.fqNameSafe.asString().removePrefix(it) else null })
| 13
|
Kotlin
|
0
| 9
|
b620e939c7461799ae1dae91e9b4b426fa3acfc1
| 1,705
|
khrysalis
|
MIT License
|
samples/packs/packv4.voodoo.kts
|
Geometrically
| 327,736,142
| true
|
{"Kotlin": 631508, "Java": 11999, "Shell": 2818}
|
mcVersion = "1.12.2"
title = "1.12.2 Pack v4"
authors = listOf("therealfarfetchd")
version = "1.0.0"
modloader {
forge(Forge_12_2.mc1_12_2_latest)
}
icon = rootFolder.resolve("icon.png")
pack {
userFiles = FnPatternList(
include = listOf(
"options.txt",
"quark.cfg",
"foamfix.cfg"
),
exclude = listOf("")
)
}
mods {
entry.validMcVersions = setOf("1.12.2", "1.12.1", "1.12")
+Curse {
entry.releaseTypes = setOf(FileType.Release, FileType.Beta, FileType.Alpha)
+Mod.buildcraft
+Mod.buildcraftCompat
+Mod.forestry
+Mod.binniesMods
+Mod.additionalPipesForBuildcraft
+Mod.industrialCraft
+Mod.compactSolars
+Mod.worldControl
+Mod.projectRedBase
+Mod.projectRedIntegration
+Mod.projectRedLighting
+Mod.projectRedFabrication
+Mod.projectRedMechanical
+Mod.projectRedWorld
+Mod.projectRedCompat
+Mod.advancedRocketry
+Mod.theAetherIi
+Mod.minecraftTransportSimulator
+Mod.transportSimulatorOfficialVehicleSet
+Mod.ironChests
+Mod.mystcraft
+Mod.biomesOPlenty
+Mod.traverseLegacyContinued
// +Mod.valkyrienWarfare
+Mod.wirelessRedstoneCbe
// Misc.
+Mod.chickenChunks18
+Mod.project74246 // doomlike dungeons
// +Mod.muon
+Mod.morpheus
+Mod.quark
+Mod.streams
+Mod.yabba
// Util mods
+Mod.backTools
+Mod.betterPlacement
+Mod.dynamicSurroundings
+Mod.foamfixOptimizationMod
+Mod.gottaGoFast
+Mod.inventoryTweaks
+Mod.jei
+Mod.jeiBees
+Mod.justEnoughResourcesJer
+Mod.justEnoughPatternBanners
+Mod.mapwriter2
+Mod.openeye
+Mod.vanillafix
+inheritProvider {
entry.side = Side.CLIENT
+Mod.blur
+Mod.betterFoliage
+Mod.betterfps
+Mod.discordsuite
+Mod.firstPersonRender
+Mod.itemphysicLite
+Mod.justthetips
+Mod.keyboardWizard
+Mod.mage
// +"shoulder-surfing-reloaded"
+Mod.soundFilters
+Mod.tipthescales
}
}
+Jenkins {
entry.jenkinsUrl = "https://ci.rs485.network"
+"logisticspipes" {
entry.job = "LogisticsPipes-0.10-mc112"
}
}
}
| 0
| null |
0
| 0
|
72b9e4c67ee0d8e91232150667877290667da1d0
| 2,503
|
Voodoo
|
MIT License
|
src/test/kotlin/me/camdenorrb/crescentvm/PTIRTests.kt
|
camdenorrb
| 261,362,729
| false
| null |
package me.camdenorrb.crescentvm
/*
import jdk.incubator.foreign.MemorySegment
import me.camdenorrb.crescentvm.data.TestCode
import me.camdenorrb.crescentvm.lexers.CrescentLexer
import me.camdenorrb.crescentvm.parsers.CrescentParser
import me.camdenorrb.crescentvm.utils.collectSystemOut
import me.camdenorrb.crescentvm.utils.fakeUserInput
import me.camdenorrb.crescentvm.vm.CrescentToPTIR
import me.camdenorrb.crescentvm.vm.CrescentVM
import tech.poder.ir.Machine
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import kotlin.io.path.Path
import kotlin.test.Test
import kotlin.test.assertEquals
internal class PTIRTests {
@Test
fun argsHelloWorld() {
val file = CrescentParser.invoke(Path("example.crescent"), CrescentLexer.invoke(TestCode.argsHelloWorld))
val result = CrescentToPTIR.craft(file)
val vm = Machine()
vm.loadPackage(result)
assertEquals(
"Hello World\n",
collectSystemOut {
vm.execute("static.main", "Hello World")
}
)
}
@Test
fun maths() {
val file = CrescentParser.invoke(Path("example.crescent"), CrescentLexer.invoke(TestCode.math))
val result = CrescentToPTIR.craft(file)
val vm = Machine()
vm.loadPackage(result)
vm.execute("static.main")
}
@Test
fun tree() {
val file = CrescentParser.invoke(Path("example.crescent"), CrescentLexer.invoke(TestCode.triangleRecursion))
val result = CrescentToPTIR.craft(file)
val vm = Machine()
vm.loadPackage(result)
collectSystemOut {
vm.execute("static.main")
}
}
@Test
fun helloWorld() {
val file = CrescentParser.invoke(Path("example.crescent"), CrescentLexer.invoke(TestCode.helloWorlds))
val result = CrescentToPTIR.craft(file)
val vm = Machine()
vm.loadPackage(result)
assertEquals(
"""
Hello World
Hello World
Hello World
""".trimIndent(),
collectSystemOut {
vm.execute("static.main")
}
)
}
@Test
fun whileLoop() {
val file = CrescentParser.invoke(Path("example.crescent"), CrescentLexer.invoke(TestCode.whileLoop))
val result = CrescentToPTIR.craft(file)
val vm = Machine()
vm.loadPackage(result)
vm.execute("static.main")
}
@Test
fun forLoop() {
val file = CrescentParser.invoke(Path("example.crescent"), CrescentLexer.invoke(TestCode.forLoop2))
val result = CrescentToPTIR.craft(file)
val vm = Machine()
vm.loadPackage(result)
vm.execute("static.main")
}
@Test
fun funThing() {
val file = CrescentParser.invoke(Path("example.crescent"), CrescentLexer.invoke(TestCode.funThing))
val result = CrescentToPTIR.craft(file)
val vm = Machine()
vm.loadPackage(result)
assertEquals(
"I am a fun thing :)\n",
collectSystemOut {
vm.execute("static.main")
}
)
}
@Test
fun ifStatement() {
val file = CrescentParser.invoke(Path("example.crescent"), CrescentLexer.invoke(TestCode.ifStatement))
val result = CrescentToPTIR.craft(file)
val vm = Machine()
vm.loadPackage(result)
assertEquals(
"Meow\n",
collectSystemOut {
vm.execute("static.main", "true")
}
)
assertEquals(
"Hiss\n",
collectSystemOut {
vm.execute("static.main", "false")
}
)
}
@Test
fun ifInputStatement() {
val file = CrescentParser.invoke(Path("example.crescent"), CrescentLexer.invoke(TestCode.ifInputStatement))
//val result = CrescentToPTIR.invoke(file)
//Machine.loadCode(*result.toTypedArray())
assertEquals(
"""
Enter a boolean value [true/false]
Meow
""".trimIndent(),
collectSystemOut {
fakeUserInput("true") {
CrescentVM(listOf(file), file).invoke()
}
},
)
assertEquals(
"""
Enter a boolean value [true/false]
Hiss
""".trimIndent(),
collectSystemOut {
fakeUserInput("false") {
CrescentVM(listOf(file), file).invoke()
}
}
)
}
@Test
fun incubatorTest() {
MemorySegment.allocateNative(2)
}
}*/
| 0
|
Kotlin
|
0
| 2
|
59c75ee82a0e5296b90d842825dad7c91e352a82
| 4,703
|
CrescentVM
|
MIT License
|
app/src/main/java/com/github/crisacm/sessionmanager/navigation/destinations/SplashScreenDestination.kt
|
crisacm
| 787,713,317
| false
|
{"Kotlin": 84072}
|
package com.github.crisacm.sessionmanager.navigation.destinations
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import com.github.crisacm.sessionmanager.navigation.Home
import com.github.crisacm.sessionmanager.navigation.Login
import com.github.crisacm.sessionmanager.navigation.Splash
import com.github.crisacm.sessionmanager.presentation.screens.splash.SplashContracts
import com.github.crisacm.sessionmanager.presentation.screens.splash.SplashViewModel
import com.github.crisacm.sessionmanager.presentation.screens.splash.composables.SplashScreen
import org.koin.androidx.compose.getViewModel
@Composable
fun SplashScreenDestination(navController: NavController) {
val viewModel = getViewModel<SplashViewModel>()
SplashScreen(
effectFlow = viewModel.effect,
onNavigationRequested = {
when (it) {
SplashContracts.Effect.Navigation.ToLogin -> {
navController.navigate(Login)
}
is SplashContracts.Effect.Navigation.ToMain -> {
navController.navigate(
Home(
it.user.name.ifEmpty { null },
it.user.email.ifEmpty { null },
it.user.photoUrl.ifEmpty { null }
)
)
}
}
}
)
}
| 0
|
Kotlin
|
0
| 0
|
cd2e1ccd31361ec4a5fea6df25ae7f04c4cee000
| 1,425
|
android-session-manager
|
Apache License 2.0
|
publish-component/src/main/java/com/kotlin/android/publish/component/ui/editor/EditorViewModel.kt
|
R-Gang-H
| 538,443,254
| false
| null |
package com.kotlin.android.publish.component.ui.editor
import com.kotlin.android.api.base.BaseUIModel
import com.kotlin.android.api.base.call
import com.kotlin.android.core.BaseViewModel
import com.kotlin.android.app.data.annotation.ContentType
import com.kotlin.android.app.data.constant.CommConstant
import com.kotlin.android.app.data.entity.CommContentList
import com.kotlin.android.app.data.entity.common.CommBizCodeResult
import com.kotlin.android.app.data.entity.common.PublishResult
import com.kotlin.android.app.data.entity.common.StatusResult
import com.kotlin.android.app.data.entity.community.content.CheckReleasedResult
import com.kotlin.android.app.data.entity.community.content.CommunityContent
import com.kotlin.android.app.data.entity.community.group.GroupSectionList
import com.kotlin.android.app.data.entity.community.publish.Footmarks
import com.kotlin.android.app.data.entity.community.publish.Group
import com.kotlin.android.app.data.entity.community.publish.RecommendTypes
import com.kotlin.android.app.data.entity.community.record.PostContent
import com.kotlin.android.app.data.entity.movie.LatestComment
import com.kotlin.android.app.data.entity.upload.ApplyUpload
import com.kotlin.android.publish.component.repo.EditorRepository
/**
* 发布社区内容:
*
* Created on 2020/10/9.
*
* @author o.s
*/
class EditorViewModel : BaseViewModel() {
private val repo by lazy { EditorRepository() }
private val contentUIModel by lazy { BaseUIModel<CommunityContent>() }
private val postContentUIModel by lazy { BaseUIModel<PublishResult>() }
private val movieRatingUIModel by lazy { BaseUIModel<StatusResult>() }
private val latestCommentUIModel by lazy { BaseUIModel<LatestComment>() }
private val deleteCommentUIModel by lazy { BaseUIModel<CommBizCodeResult>() }
private val familyListUIModel by lazy { BaseUIModel<ArrayList<Group>>() }
private val footmarksUIModel by lazy { BaseUIModel<Footmarks>() }
private val recommendTypesUIModel by lazy { BaseUIModel<RecommendTypes>() }
private val sectionListUIModel by lazy { BaseUIModel<GroupSectionList>() }
private val applyUploadUIModel by lazy { BaseUIModel<ApplyUpload>() } //发起上传视频
private val completeUIModel by lazy { BaseUIModel<CommBizCodeResult>() } //上传完成
private val checkReleasedUIModel by lazy { BaseUIModel<CheckReleasedResult>() }
private val relationArticlesUIModel by lazy { BaseUIModel<CommContentList>() }
private val movieUIModel by lazy { BaseUIModel<String>() }
val contentUIState = contentUIModel.uiState
val postContentUIState = postContentUIModel.uiState
val movieRatingUIState = movieRatingUIModel.uiState
val latestCommentUIState = latestCommentUIModel.uiState
val deleteCommentUIState = deleteCommentUIModel.uiState
val familyListUIState = familyListUIModel.uiState
val footmarksUIState = footmarksUIModel.uiState
val recommendTypesUIState = recommendTypesUIModel.uiState
val sectionListUIState = sectionListUIModel.uiState
val applyUploadUIState = applyUploadUIModel.uiState
val completeUIState = completeUIModel.uiState
val checkReleasedUIState = checkReleasedUIModel.uiState
val relationArticlesUIState = relationArticlesUIModel.uiState
val movieUIState = movieUIModel.uiState
fun getContent(
@ContentType type: Long,
contentId: Long,
recId: Long?
) {
call(
uiModel = contentUIModel,
) {
repo.getContent(
type = type,
contentId = contentId,
recId = recId
)
}
}
fun publishContent(content: PostContent) {
call(
uiModel = postContentUIModel,
) {
repo.postContent(content)
}
}
fun movieRating(
movieId: Long,
rating: Double,
subRatingDesc: String
) {
call(
uiModel = movieRatingUIModel
) {
repo.getMovieRating(movieId, rating, subRatingDesc)
}
}
fun getMovieRating(movieId: Long) {
call(
uiModel = latestCommentUIModel
) {
repo.getMovieLatestComment(movieId)
}
}
fun postDeleteContent(@ContentType type: Long, contentId: Long) {
call(
uiModel = deleteCommentUIModel
) {
repo.postDeleteContent(type, contentId)
}
}
/**
* 检查内容是否为发布状态
*/
fun checkReleased(
type: Long = CommConstant.CHECK_RELEASED_CONTENT_TYPE_ARTICLE,
articleId: Long
) {
call(
uiModel = checkReleasedUIModel,
) {
repo.checkReleased(
type = type,
contentId = articleId
)
}
}
/**
* 加载家族列表
*/
fun loadFamilyList() {
call(
uiModel = familyListUIModel,
) {
repo.loadFamilyList()
}
}
/**
* 获取家族分区列表
*/
fun getGroupSectionList(groupId: Long) {
call(
uiModel = sectionListUIModel
) {
repo.getGroupSectionList(groupId = groupId)
}
}
/**
* 种草家族列表
*/
fun getGroupFootmarks() {
call(
uiModel = footmarksUIModel
) {
repo.getGroupFootmarks()
}
}
/**
* 按推荐类型获取子分类
*/
fun getGroupSubTypes() {
call(
uiModel = recommendTypesUIModel
) {
repo.getGroupSubTypes()
}
}
/**
* 发起视频上传获取一次性token
*/
fun applyUpload(filName: String) {
call(
uiModel = applyUploadUIModel
) {
repo.applyUpload(fileName = filName)
}
}
/**
* 视频在腾讯云点播上传完成后同步给服务器
*/
fun completeUpload(
videoId: Long,
mediaId: String,
mediaUrl: String
) {
call(uiModel = completeUIModel) {
repo.completeUpload(
videoId = videoId,
mediaId = mediaId,
mediaUrl = mediaUrl
)
}
}
/**
* 获取关联文章列表
*/
fun getRelationArticles(
contentId: Long? = null,
recId: Long? = null,
) {
call(
uiModel = relationArticlesUIModel,
hasMore = {
it.hasNext
}
) {
repo.getRelationArticles(
contentId = contentId,
recId = recId,
pageIndex = relationArticlesUIModel.pageIndex,
pageSize = relationArticlesUIModel.pageSize
)
}
}
/**
* 获取电影名称
*/
fun getMovieName(movieId: Long) {
call(
uiModel = movieUIModel,
) {
repo.getMovieName(movieId = movieId)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28
| 6,842
|
Mtime
|
Apache License 2.0
|
app/src/androidTest/java/com/theathletic/interview/FileReader.kt
|
ruysay
| 334,640,882
| false
| null |
package com.theathletic.interview
import androidx.test.platform.app.InstrumentationRegistry
import com.theathletic.interview.main.MainApplication
import java.io.IOException
import java.io.InputStreamReader
object FileReader {
fun readStringFromFile(fileId: Int): String {
try {
val inputStream = (InstrumentationRegistry.getInstrumentation().targetContext
.applicationContext as MainApplication).resources.openRawResource(fileId)
val builder = StringBuilder()
val reader = InputStreamReader(inputStream, "UTF-8")
reader.readLines().forEach {
builder.append(it)
}
return builder.toString()
} catch (e: IOException) {
throw e
}
}
}
| 0
|
Kotlin
|
0
| 0
|
0481b0e8a7ba9c6398d56d7b28befd6df76b81bd
| 780
|
AthleticMVP
|
Apache License 2.0
|
app - Copy/src/main/java/com/SShayar/greenglobe/adapter/PostAdapter.kt
|
krishanmurariji
| 758,797,770
| false
|
{"Kotlin": 89164, "Shell": 5766, "Batchfile": 2674}
|
package com.SShayar.greenglobe.adapter
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.SShayar.greenglobe.Models.Post
import com.SShayar.greenglobe.Models.User
import com.SShayar.greenglobe.R
import com.SShayar.greenglobe.databinding.PostRvBinding
import com.SShayar.greenglobe.utils.USER_NODE
import com.bumptech.glide.Glide
import com.github.marlonlom.utilities.timeago.TimeAgo
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.firestore.ktx.toObject
import com.google.firebase.ktx.Firebase
class PostAdapter(var context: Context, var postList: ArrayList<Post>) :
RecyclerView.Adapter<PostAdapter.MyHolder>() {
inner class MyHolder(var binding: PostRvBinding) : RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
var binding = PostRvBinding.inflate(LayoutInflater.from(context), parent, false)
return MyHolder(binding)
}
override fun getItemCount(): Int {
return postList.size
}
override fun onBindViewHolder(holder: MyHolder, position: Int) {
try {
Firebase.firestore.collection(USER_NODE).document(postList.get(position).uid).get()
.addOnSuccessListener {
var user = it.toObject<User>()
Glide.with(context).load(user!!.image).placeholder(R.drawable.user)
.into(holder.binding.profileImage)
holder.binding.name.text = user.name
}
} catch (e: Exception) {
}
Glide.with(context).load(postList.get(position).postUrl).placeholder(R.drawable.loading)
.into(holder.binding.postImage)
try {
val text = TimeAgo.using(postList.get(position).time.toLong())
holder.binding.time.text = text
} catch (e: Exception) {
holder.binding.time.text = ""
}
holder.binding.share.setOnClickListener{
var i = Intent(Intent.ACTION_SEND)
i.type="text/plain"
i.putExtra(Intent.EXTRA_TEXT,postList.get(position).postUrl)
context.startActivity(i)
}
holder.binding.caption.text = postList.get(position).caption
holder.binding.like.setOnClickListener {
holder.binding.like.setImageResource(R.drawable.heart_like)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c3f0a29de67421961285011164c39fcc0035d5b4
| 2,521
|
InstagramClone
|
MIT License
|
app - Copy/src/main/java/com/SShayar/greenglobe/adapter/PostAdapter.kt
|
krishanmurariji
| 758,797,770
| false
|
{"Kotlin": 89164, "Shell": 5766, "Batchfile": 2674}
|
package com.SShayar.greenglobe.adapter
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.SShayar.greenglobe.Models.Post
import com.SShayar.greenglobe.Models.User
import com.SShayar.greenglobe.R
import com.SShayar.greenglobe.databinding.PostRvBinding
import com.SShayar.greenglobe.utils.USER_NODE
import com.bumptech.glide.Glide
import com.github.marlonlom.utilities.timeago.TimeAgo
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.firestore.ktx.toObject
import com.google.firebase.ktx.Firebase
class PostAdapter(var context: Context, var postList: ArrayList<Post>) :
RecyclerView.Adapter<PostAdapter.MyHolder>() {
inner class MyHolder(var binding: PostRvBinding) : RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
var binding = PostRvBinding.inflate(LayoutInflater.from(context), parent, false)
return MyHolder(binding)
}
override fun getItemCount(): Int {
return postList.size
}
override fun onBindViewHolder(holder: MyHolder, position: Int) {
try {
Firebase.firestore.collection(USER_NODE).document(postList.get(position).uid).get()
.addOnSuccessListener {
var user = it.toObject<User>()
Glide.with(context).load(user!!.image).placeholder(R.drawable.user)
.into(holder.binding.profileImage)
holder.binding.name.text = user.name
}
} catch (e: Exception) {
}
Glide.with(context).load(postList.get(position).postUrl).placeholder(R.drawable.loading)
.into(holder.binding.postImage)
try {
val text = TimeAgo.using(postList.get(position).time.toLong())
holder.binding.time.text = text
} catch (e: Exception) {
holder.binding.time.text = ""
}
holder.binding.share.setOnClickListener{
var i = Intent(Intent.ACTION_SEND)
i.type="text/plain"
i.putExtra(Intent.EXTRA_TEXT,postList.get(position).postUrl)
context.startActivity(i)
}
holder.binding.caption.text = postList.get(position).caption
holder.binding.like.setOnClickListener {
holder.binding.like.setImageResource(R.drawable.heart_like)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c3f0a29de67421961285011164c39fcc0035d5b4
| 2,521
|
InstagramClone
|
MIT License
|
app/src/test/java/com/example/football/presentation/viewmodel/StandingsViewModelTest.kt
|
joeMalebe
| 585,552,196
| false
|
{"Kotlin": 216425}
|
package com.example.football.presentation.viewmodel
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import com.example.football.FootballService
import com.example.football.data.model.StandingsResponse
import com.example.football.data.repository.StandingsRepository
import com.example.football.data.repository.StandingsRepositoryImpl
import com.example.football.data.repository.TestData.standingsResponse
import com.example.football.domain.StandingsResult
import com.example.football.domain.StandingsViewDataMapperImpl
import com.example.football.domain.usecase.StandingsUseCase
import com.example.football.domain.usecase.StandingsUseCaseImpl
import com.example.football.presentation.viewmodel.viewstate.LeagueTableViewState
import java.util.Calendar
import java.util.Calendar.YEAR
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.*
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@OptIn(ExperimentalCoroutinesApi::class)
class StandingsViewModelTest {
private lateinit var standingsViewModel: StandingsViewModel
private lateinit var standingsUseCase: StandingsUseCase
private lateinit var standingsRepository: StandingsRepository
private val standingsViewDataMapper = StandingsViewDataMapperImpl()
private val testDispatcher = UnconfinedTestDispatcher(scheduler = TestCoroutineScheduler())
private val year = Calendar.getInstance().get(YEAR).toString()
@Mock
lateinit var footballService: FootballService
@Mock
private lateinit var observer: Observer<LeagueTableViewState>
@get:Rule
val rule = InstantTaskExecutorRule()
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
Dispatchers.setMain(testDispatcher)
standingsRepository = StandingsRepositoryImpl(footballService, testDispatcher)
standingsUseCase = StandingsUseCaseImpl(standingsRepository, standingsViewDataMapper)
standingsViewModel = StandingsViewModel(standingsUseCase, testDispatcher)
}
@Test
fun `When getting standings fails then return error view state`() = runTest {
whenever(footballService.getStandings("3", year)).thenReturn(
Result.failure(Throwable("errorr"))
)
val argumentCaptor = argumentCaptor<LeagueTableViewState>()
standingsViewModel.standingsViewState.observeForever(observer)
standingsViewModel.getStandings(leagueId = "3")
argumentCaptor.run {
verify(observer, times(3)).onChanged(this.capture())
assertEquals(LeagueTableViewState.Initial, firstValue)
assertEquals(LeagueTableViewState.Loading, secondValue)
assertSame(LeagueTableViewState.Error, thirdValue)
}
}
@Test
fun `When football service fails then return error standings Result`() = runTest {
whenever(footballService.getStandings("3", year)).thenReturn(
Result.failure(Throwable("Error"))
)
val sut = standingsUseCase.getLeagueStandings("3")
assertEquals(StandingsResult.Error, sut)
verify(footballService).getStandings("3", year)
}
@Test
fun `When football service throws an exception then return error standings result`() = runTest {
whenever(footballService.getStandings("3", year)).thenThrow(
java.lang.RuntimeException("error")
)
val sut = standingsUseCase.getLeagueStandings("3")
assertSame(StandingsResult.Error, sut)
}
@Test
fun `When get standings is successful then emit standings loaded state`() = runTest {
whenever(footballService.getStandings("5", year)).thenReturn(
Result.success(
standingsResponse
)
)
val argumentCaptor = argumentCaptor<LeagueTableViewState>()
standingsViewModel.standingsViewState.observeForever(observer)
standingsViewModel.getStandings("5")
argumentCaptor.run {
verify(observer, times(3)).onChanged(this.capture())
assertSame(LeagueTableViewState.Initial, firstValue)
assertSame(LeagueTableViewState.Loading, secondValue)
assertSame(LeagueTableViewState.StandingsLoaded::class.java, thirdValue::class.java)
}
}
@Test
fun `When get standings has no standings data then emit no information state`() = runTest {
whenever(footballService.getStandings("12", year)).thenReturn(
Result.success(
StandingsResponse(emptyList())
)
)
val argumentCaptor = argumentCaptor<LeagueTableViewState>()
standingsViewModel.standingsViewState.observeForever(observer)
standingsViewModel.getStandings("12")
argumentCaptor.run {
verify(observer, times(3)).onChanged(this.capture())
assertSame(LeagueTableViewState.Initial, firstValue)
assertSame(LeagueTableViewState.Loading, secondValue)
assertSame(LeagueTableViewState.NoInformation, thirdValue)
}
}
@After
fun after() {
Dispatchers.resetMain()
}
}
| 1
|
Kotlin
|
0
| 0
|
41509fa010b49d1b956f90ab4d20129f9f96fa44
| 5,463
|
Football
|
Apache License 2.0
|
src/commonMain/kotlin/matt/http/internet/internet.kt
|
mgroth0
| 532,378,353
| false
| null |
package matt.http.internet
import matt.http.url.MURL
import matt.lang.not
import matt.model.code.valjson.ValJson.Port
class TheInternet {
// val wasAvailableInThisRuntime by lazy {
// isAvailable()
// }
// val wasNotAvailableInThisRuntime get() = not(wasAvailableInThisRuntime)
private var gotAReport = false
fun reportUnavailability() {
gotAReport = true
}
val wasAlwaysAvailableInThisRuntime get() = !gotAReport
val wasUnavilableThisRuntime get() = gotAReport
}
expect fun TheInternet.isAvailable(): Boolean
fun TheInternet.isNotAvailable() = not(isAvailable())
/*not https*/
val LOCAL_TEST_URL = MURL("http://0.0.0.0:${Port.localKtorTest}")
| 0
|
Kotlin
|
0
| 0
|
50905ac93334c10c5d8ada8571ece565b2b435a7
| 697
|
http
|
MIT License
|
src/main/kotlin/io/spring/shinyay/observability/TanzuApplication.kt
|
shinyay
| 436,214,231
| false
|
{"Kotlin": 2658}
|
package io.spring.shinyay.observability
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class TanzuApplication
fun main(args: Array<String>) {
runApplication<TanzuApplication>(*args)
}
val Any.logger: Logger
get() = LoggerFactory.getLogger(this::class.java)
| 0
|
Kotlin
|
0
| 0
|
c0c69f4f591df869cec9cd9134dbc9331a185bfc
| 409
|
tanzu-observability-gs
|
MIT License
|
protocol/osrs-225/osrs-225-desktop/src/main/kotlin/net/rsprot/protocol/game/outgoing/codec/camera/CamResetEncoder.kt
|
blurite
| 771,753,685
| false
|
{"Kotlin": 11355829}
|
package net.rsprot.protocol.game.outgoing.codec.camera
import net.rsprot.protocol.ServerProt
import net.rsprot.protocol.game.outgoing.camera.CamReset
import net.rsprot.protocol.game.outgoing.prot.GameServerProt
import net.rsprot.protocol.message.codec.NoOpMessageEncoder
import net.rsprot.protocol.metadata.Consistent
@Consistent
public class CamResetEncoder : NoOpMessageEncoder<CamReset> {
override val prot: ServerProt = GameServerProt.CAM_RESET
}
| 5
|
Kotlin
|
6
| 27
|
d08cb7c11ae758b5dcabd6e85d34a4bfdba7ad3c
| 457
|
rsprot
|
MIT License
|
app/src/main/java/com/example/dessertclicker/MainActivity.kt
|
SeppoVolsk
| 646,752,785
| false
| null |
/*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.example.dessertclicker
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.dessertclicker.data.Datasource
import com.example.dessertclicker.model.Dessert
import com.example.dessertclicker.ui.components.DessertClickerApp
import com.example.dessertclicker.ui.theme.DessertClickerTheme
import com.example.dessertclicker.ui.viewmodel.AppViewModel
// Tag for logging
private const val TAG = "MainActivity"
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate Called")
setContent {
DessertClickerTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DessertClickerApp()
}
}
}
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart Called")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume Called")
}
override fun onRestart() {
super.onRestart()
Log.d(TAG, "onRestart Called")
}
override fun onPause() {
super.onPause()
Log.d(TAG, "onPause Called")
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStop Called")
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy Called")
}
}
@Preview
@Composable
fun MyDessertClickerAppPreview() {
DessertClickerTheme {
DessertClickerApp()
}
}
| 0
|
Kotlin
|
0
| 0
|
db7b24e9f74e5a324e3fdfcd64fd9485f15fa895
| 4,178
|
Dessert_Clicker
|
Apache License 2.0
|
app/src/main/java/com/migferlab/justpizza/domain/flux/UserStore.kt
|
miguefl
| 271,397,963
| false
| null |
package com.migferlab.justpizza.domain.flux
import com.hoopcarpool.fluxy.FluxyStore
import com.hoopcarpool.fluxy.Result
import com.migferlab.justpizza.domain.model.User
data class UserState(val userResult: Result<User> = Result.Empty())
class UserStore(private val userSideEffects: UserSideEffects) : FluxyStore<UserState>() {
override fun init() {
reduce<UserSignUpAction> {
newState = state.copy(userResult = Result.Loading())
userSideEffects.singUp(it.email, it.password)
}
reduce<UserSignUpResolvedAction> {
newState = state.copy(userResult = it.result)
}
reduce<UserLogInAction> {
newState = state.copy(userResult = Result.Loading())
userSideEffects.logIn(it.email, it.password)
}
reduce<UserLogInResolvedAction> {
newState = state.copy(userResult = it.result)
}
reduce<UserLogOutAction> {
newState = state.copy(userResult = Result.Empty())
userSideEffects.logOut()
}
reduce<GoogleSignInAction> {
newState = state.copy(userResult = Result.Loading())
userSideEffects.singInGoogle(it.credential)
}
}
}
| 0
|
Kotlin
|
0
| 2
|
61943b933081d7d2ccc0f37d99944da719f40683
| 1,236
|
JustPizzaApp
|
Apache License 2.0
|
src/main/kotlin/com/charleskorn/kaml/YAML.kt
|
staylward
| 162,601,309
| true
|
{"Kotlin": 139130, "Shell": 2724}
|
/*
Copyright 2018 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.charleskorn.kaml
import kotlinx.serialization.AbstractSerialFormat
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.StringFormat
import kotlinx.serialization.decode
object YAML : AbstractSerialFormat(), StringFormat {
override fun <T> parse(serializer: DeserializationStrategy<T>, string: String): T {
val parser = YamlParser(string)
val rootNode = YamlNode.fromParser(parser)
val input = YamlInput.createFor(rootNode)
return input.decode(serializer)
}
override fun <T> stringify(serializer: SerializationStrategy<T>, obj: T): String {
TODO("not implemented")
}
}
| 0
|
Kotlin
|
0
| 0
|
f31c90b5f09f06187f2930c8235d303b3341bea6
| 1,306
|
kaml
|
Apache License 2.0
|
fontawesome/src/de/msrd0/fontawesome/icons/FA_USERS_LINE.kt
|
msrd0
| 363,665,023
| false
| null |
/* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* 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 de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
/** Users Line */
object FA_USERS_LINE: Icon {
override val name get() = "Users Line"
override val unicode get() = "e592"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path d="M211.2 96C211.2 131.3 182.5 160 147.2 160C111.9 160 83.2 131.3 83.2 96C83.2 60.65 111.9 32 147.2 32C182.5 32 211.2 60.65 211.2 96zM32 256C32 220.7 60.65 192 96 192H192C204.2 192 215.7 195.4 225.4 201.4C188.2 216.5 159.8 248.6 149.6 288H64C46.33 288 32 273.7 32 256V256zM415.9 200.6C425.3 195.1 436.3 192 448 192H544C579.3 192 608 220.7 608 256C608 273.7 593.7 288 576 288H493.6C483.2 247.9 453.1 215.4 415.9 200.6zM391.2 226.4C423.3 233.8 449.3 257.3 460.1 288C463.7 298 465.6 308.8 465.6 320C465.6 337.7 451.3 352 433.6 352H209.6C191.9 352 177.6 337.7 177.6 320C177.6 308.8 179.5 298 183.1 288C193.6 258.3 218.3 235.2 249.1 227.1C256.1 225.1 265.1 224 273.6 224H369.6C377 224 384.3 224.8 391.2 226.4zM563.2 96C563.2 131.3 534.5 160 499.2 160C463.9 160 435.2 131.3 435.2 96C435.2 60.65 463.9 32 499.2 32C534.5 32 563.2 60.65 563.2 96zM241.6 112C241.6 67.82 277.4 32 321.6 32C365.8 32 401.6 67.82 401.6 112C401.6 156.2 365.8 192 321.6 192C277.4 192 241.6 156.2 241.6 112zM608 416C625.7 416 640 430.3 640 448C640 465.7 625.7 480 608 480H32C14.33 480 0 465.7 0 448C0 430.3 14.33 416 32 416H608z"/></svg>"""
else -> null
}
}
| 0
|
Kotlin
|
0
| 0
|
b2fdb74278104be68c95e8f083fc75ab74395112
| 2,312
|
fontawesome-kt
|
Apache License 2.0
|
app/src/main/java/com/android/sample/app/util/LinkNavType.kt
|
alirezaeiii
| 459,039,118
| false
|
{"Kotlin": 41731}
|
package com.android.sample.app.util
import android.os.Bundle
import androidx.navigation.NavType
import com.android.sample.app.domain.Link
import com.google.gson.Gson
class LinkNavType : NavType<Link>(isNullableAllowed = false) {
override fun get(bundle: Bundle, key: String): Link? {
return bundle.getParcelable(key)
}
override fun parseValue(value: String): Link {
return Gson().fromJson(value, Link::class.java)
}
override fun put(bundle: Bundle, key: String, value: Link) {
bundle.putParcelable(key, value)
}
}
| 0
|
Kotlin
|
4
| 8
|
2415e52dabb4c9ad2edb524d4bfc527ff94e5e48
| 565
|
Navigation-Compose
|
The Unlicense
|
src/client/kotlin/slabmagic/utils/ImageBuilder.kt
|
Jempasam
| 717,593,852
| false
|
{"Kotlin": 356942, "Java": 1036}
|
package slabmagic.utils
import org.joml.Vector3f
import java.awt.image.BufferedImage
import java.awt.image.WritableRaster
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class ImageBuilder {
private var image: BufferedImage? = null
private fun target(toPaintOn: BufferedImage?=null): BufferedImage {
return image
?: if (toPaintOn == null) throw Exception("No Root Image")
else {
val nimage = BufferedImage(toPaintOn.width, toPaintOn.height, BufferedImage.TYPE_INT_ARGB)
image = nimage
nimage
}
}
fun paint(toPaintOn: BufferedImage, x: Int=0, y: Int=0): ImageBuilder{
val image= target(toPaintOn)
val graphics=image.createGraphics()
graphics.drawImage(toPaintOn,x,y,null)
graphics.dispose()
return this
}
fun apply(selector: Selector, transformer: Transformer): ImageBuilder{
val image= target()
val raster= image.raster
for(x in 0 until image.width){
for(y in 0 until image.height){
if(selector.test(raster,x,y)) transformer.apply(raster,x,y)
}
}
return this
}
fun result(): BufferedImage = image ?: throw Exception("No Root Image")
/* SELECTORS AND TRANSFORMERS */
fun interface Selector{
fun test(raster: WritableRaster, x: Int, y: Int): Boolean
}
fun interface Transformer{
fun apply(raster: WritableRaster, x: Int, y: Int)
}
}
/* SELECTORS */
val sAll = ImageBuilder.Selector{ _, _, _ -> true }
val sOpaque = ImageBuilder.Selector{ raster, x, y ->
val pixel= raster.getPixel(x,y,IntArray(4))
pixel[3]==255
}
val sVisible = ImageBuilder.Selector{ raster, x, y ->
val pixel= raster.getPixel(x,y,IntArray(4))
pixel[3]>0
}
val sOutline = ImageBuilder.Selector{ raster, x, y ->
fun isVisible(x: Int, y: Int): Boolean{
if(x<0 || y<0 || x>=raster.width || y>=raster.height) return false
val pixel= raster.getPixel(x,y,IntArray(4))
return pixel[3]==0
}
!isVisible(x,y) && (isVisible(x+1,y) || isVisible(x-1,y) || isVisible(x,y+1) || isVisible(x,y-1))
}
val sInnerOutline = ImageBuilder.Selector{ raster, x, y ->
fun isVisible(x: Int, y: Int): Boolean{
if(x<0 || y<0 || x>=raster.width || y>=raster.height) return false
val pixel= raster.getPixel(x,y,IntArray(4))
return pixel[3]==0
}
isVisible(x,y) && (!isVisible(x+1,y) || !isVisible(x-1,y) || !isVisible(x,y+1) || !isVisible(x,y-1))
}
fun sCombine(vararg selectors: ImageBuilder.Selector) = ImageBuilder.Selector{ raster, x, y ->
for(selector in selectors){
if(!selector.test(raster,x,y)) return@Selector false
}
true
}
fun sColor(color: Vector3f, tolerance: Float=0.1f) = ImageBuilder.Selector{ raster, x, y ->
val pixel= raster.getPixel(x,y,IntArray(4))
val distance= abs(color.x*255-pixel[0]) + abs(color.y*255-pixel[1]) + abs(color.z*255-pixel[2])
distance<tolerance
}
fun sTint(tint: Vector3f, tolerance: Float=0.1f) = ImageBuilder.Selector{ raster, x, y ->
val pixel= raster.getPixel(x,y,IntArray(4))
val targetTint= Vector3f(pixel[0]/255f,pixel[1]/255f,pixel[2]/255f)
targetTint.apply { normalize() ; sub(tint) }
val distance= abs(targetTint.x) + abs(targetTint.y) + abs(targetTint.z)
distance<tolerance
}
fun sHue(tint: Vector3f, tolerance: Float=0.1f) = ImageBuilder.Selector{ raster, x, y ->
val pixel= raster.getPixel(x,y,IntArray(4))
val v=Vector3f(pixel[0].toFloat(),pixel[1].toFloat(),pixel[2].toFloat())
val min= min(v.x,min(v.y,v.z))
v.modify{ it-min }
val max= max(v.x, max(v.y,v.z))
v.modify { it/max }
v.sub(tint)
val distance= abs(v.x) + abs(v.y) + abs(v.z)
distance<tolerance
}
/* TRANSFORMERS */
fun tSequence(vararg transformers: ImageBuilder.Transformer) = ImageBuilder.Transformer{ raster, x, y ->
for(transformer in transformers){
transformer.apply(raster,x,y)
}
}
fun tTint(tint: Vector3f) = ImageBuilder.Transformer{ raster, x, y ->
val pixel= raster.getPixel(x,y,IntArray(4))
val targetLuminosity= (pixel[0]+pixel[1]+pixel[2])/3f
val newColor= Vector3f(tint.x*targetLuminosity,tint.y*targetLuminosity,tint.z*targetLuminosity)
raster.setPixel(x,y,intArrayOf(newColor.x.toInt(),newColor.y.toInt(),newColor.z.toInt(),pixel[3]))
}
fun tLuminosity(luminosity: Float) = ImageBuilder.Transformer{ raster, x, y ->
val pixel= raster.getPixel(x,y,IntArray(4))
val targetTint= Vector3f(pixel[0].toFloat(), pixel[1].toFloat(), pixel[2].toFloat())
val luminosity=luminosity*255f
targetTint.apply { normalize() ; mul(luminosity,luminosity,luminosity) }
raster.setPixel(x,y,intArrayOf(targetTint.x.toInt(),targetTint.y.toInt(),targetTint.z.toInt(),pixel[3]))
}
fun tImBlend(im: BufferedImage, ox: Int=0, oy: Int=0, opacity: Float=1f) = tImage(im,ox,oy){ source, target ->
val alpha=source[3]/255f*opacity
val ralpha=1f-alpha
for(i in 0..<3) target[i] = (target[i]*ralpha + source[i]*alpha).toInt()
target[3]= min(255, target[3]+source[3])
target
}
fun tImMultiply(im: BufferedImage, ox: Int=0, oy: Int=0) = tImage(im,ox,oy){ source, target ->
for(i in 0..<4) target[i] = (target[i]*source[i]/255f).toInt()
target
}
private fun tImage(bufferedImage: BufferedImage, ox: Int=0, oy: Int=0, run: (IntArray, IntArray)->IntArray) = ImageBuilder.Transformer{ raster, x, y ->
val sx= x-ox
val sy= y-oy
if(sx<0 || sy<0 || sx>=bufferedImage.width || sy>=bufferedImage.height) return@Transformer
val sourcePixel= bufferedImage.raster.getPixel(sx,sy,IntArray(4))
val targetPixel= raster.getPixel(x,y,IntArray(4))
raster.setPixel(x,y,run(sourcePixel,targetPixel))
}
| 0
|
Kotlin
|
0
| 0
|
5293f67ccc2484961d3c588c2d0824743be4066f
| 5,825
|
SlateMagic
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/uk/gov/justice/digital/hmpps/assessrisksandneeds/api/controllers/SupplementaryRisksController.kt
|
ministryofjustice
| 373,137,019
| false
| null |
package uk.gov.justice.digital.hmpps.assessrisksandneeds.api.controllers
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.responses.ApiResponses
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import uk.gov.justice.digital.hmpps.assessrisksandneeds.api.model.CreateSupplementaryRiskDto
import uk.gov.justice.digital.hmpps.assessrisksandneeds.api.model.Source
import uk.gov.justice.digital.hmpps.assessrisksandneeds.api.model.SupplementaryRiskDto
import uk.gov.justice.digital.hmpps.assessrisksandneeds.services.SupplementaryRiskService
import java.util.UUID
@RestController
class SupplementaryRisksController(
val supplementaryRiskService: SupplementaryRiskService
) {
@RequestMapping(path = ["/risks/supplementary/{sourceType}/{sourceId}"], method = [RequestMethod.GET])
@Operation(description = "Gets supplementary risk for a given source")
@ApiResponses(
value = [
ApiResponse(responseCode = "403", description = "Unauthorized"),
ApiResponse(responseCode = "404", description = "Supplementary risk source Not Found"),
ApiResponse(responseCode = "200", description = "OK")
]
)
@PreAuthorize("hasAnyRole('ROLE_PROBATION', 'ROLE_CRS_PROVIDER')")
fun getSupplementaryRiskBySource(
@Parameter(description = "Source ID", required = true, example = "78beac68-884c-4784-9bea-fd8088f52a47")
@PathVariable sourceId: String,
@Parameter(description = "Source Type", required = true, example = "INTERVENTION_REFERRAL")
@PathVariable sourceType: Source
): SupplementaryRiskDto {
return supplementaryRiskService.getRiskBySourceAndSourceId(sourceType, sourceId)
}
@RequestMapping(path = ["/risks/supplementary/crn/{crn}"], method = [RequestMethod.GET])
@Operation(description = "Gets supplementary risk for a given CRN")
@ApiResponses(
value = [
ApiResponse(responseCode = "403", description = "Unauthorized"),
ApiResponse(responseCode = "404", description = "Supplementary risk source Not Found"),
ApiResponse(responseCode = "200", description = "OK")
]
)
@PreAuthorize("hasAnyRole('ROLE_PROBATION')")
fun getSupplementaryRisksByCrn(
@Parameter(description = "CRN", required = true, example = "X123456")
@PathVariable crn: String
): List<SupplementaryRiskDto> {
return supplementaryRiskService.getRisksByCrn(crn)
}
@RequestMapping(path = ["/risks/supplementary/{supplementaryRiskId}"], method = [RequestMethod.GET])
@Operation(description = "Gets supplementary risk for a given ID")
@ApiResponses(
value = [
ApiResponse(responseCode = "403", description = "Unauthorized"),
ApiResponse(responseCode = "404", description = "Supplementary risk source Not Found"),
ApiResponse(responseCode = "200", description = "OK")
]
)
@PreAuthorize("hasAnyRole('ROLE_PROBATION', 'ROLE_CRS_PROVIDER')")
fun getSupplementaryRiskById(
@Parameter(description = "Supplementary ID", required = true, example = "78beac68-884c-4784-9bea-fd8088f52a47")
@PathVariable supplementaryRiskId: UUID
): SupplementaryRiskDto {
return supplementaryRiskService.getRiskBySupplementaryRiskUuid(supplementaryRiskId)
}
@RequestMapping(path = ["/risks/supplementary"], method = [RequestMethod.POST])
@Operation(description = "Create new supplementary risk for a given source")
@ApiResponses(
value = [
ApiResponse(responseCode = "403", description = "Unauthorized"),
ApiResponse(responseCode = "200", description = "OK")
]
)
@PreAuthorize("hasAnyRole('ROLE_PROBATION')")
fun createSupplementaryRisk(
@Parameter(description = "Supplementary Risk", required = true)
@RequestBody supplementaryRisk: CreateSupplementaryRiskDto
): SupplementaryRiskDto {
return supplementaryRiskService.createNewSupplementaryRisk(supplementaryRisk)
}
}
| 9
|
Kotlin
|
0
| 0
|
0c3f3bd758a851727092a4410f6d55633f77c182
| 4,266
|
hmpps-assess-risks-and-needs
|
MIT License
|
day24/src/main/kotlin/Main.kt
|
rstockbridge
| 159,586,951
| false
| null |
import java.io.File
fun main() {
println("Part I: the solution is ${solvePartI(readImmuneSystemInputFile(), readInfectionInputFile())}.")
println("Part II: the solution is ${solvePartII(readImmuneSystemInputFile(), readInfectionInputFile())}.")
}
fun readImmuneSystemInputFile(): List<String> {
return File(ClassLoader.getSystemResource("immune_system_input.txt").file).readLines()
}
fun readInfectionInputFile(): List<String> {
return File(ClassLoader.getSystemResource("infection_input.txt").file).readLines()
}
fun solvePartI(immuneSystemInput: List<String>, infectionInput: List<String>): Int {
val immuneSystemArmy = createArmy(immuneSystemInput, ArmyType.IMMUNE_SYSTEM)
val infectionArmy = createArmy(infectionInput, ArmyType.INFECTION)
val outcome = runCombat(immuneSystemArmy, infectionArmy)
return if (outcome == Outcome.IMMUNE_SYSTEM) {
immuneSystemArmy.groups.sumBy { group -> group.numberOfUnits }
} else { // assuming outcome will never be a stalemate
infectionArmy.groups.sumBy { group -> group.numberOfUnits }
}
}
fun solvePartII(immuneSystemInput: List<String>, infectionInput: List<String>): Int {
var boost = 76
while (true) {
val immuneSystemArmy = createArmy(immuneSystemInput, ArmyType.IMMUNE_SYSTEM)
val infectionArmy = createArmy(infectionInput, ArmyType.INFECTION)
immuneSystemArmy.boostBy(boost)
val outcome = runCombat(immuneSystemArmy, infectionArmy)
if (outcome == Outcome.IMMUNE_SYSTEM) {
return immuneSystemArmy.groups.sumBy { group -> group.numberOfUnits }
} else {
boost++
}
}
}
fun createArmy(input: List<String>, armyType: ArmyType): Army {
val groupRegex = "(\\d+) units each with (\\d+) hit points(\\s?.+\\s?)with an attack that does (\\d+) (.+) damage at initiative (\\d+)".toRegex()
var groupId = 0
return Army(
input.map { groupInput ->
val (numberOfUnitsString,
numberOfHitPointsString,
immunitiesWeaknessesString,
attackDamageString,
attackTypeString,
initiativeString) = groupRegex.matchEntire(groupInput)!!.destructured
var weaknesses = listOf<Attack>()
var immunities = listOf<Attack>()
if (immunitiesWeaknessesString.isNotEmpty()) {
if (";" in immunitiesWeaknessesString) {
val splitImmunitiesWeaknesses = immunitiesWeaknessesString.split(";")
if ("weak" in splitImmunitiesWeaknesses[0]) {
weaknesses = Attack.identify(splitImmunitiesWeaknesses[0])
} else if ("weak" in splitImmunitiesWeaknesses[1]) {
weaknesses = Attack.identify(splitImmunitiesWeaknesses[1])
}
if ("immune" in splitImmunitiesWeaknesses[0]) {
immunities = Attack.identify(splitImmunitiesWeaknesses[0])
} else if ("immune" in splitImmunitiesWeaknesses[1]) {
immunities = Attack.identify(splitImmunitiesWeaknesses[1])
}
} else {
if ("weak" in immunitiesWeaknessesString) {
weaknesses = Attack.identify(immunitiesWeaknessesString)
}
if ("immune" in immunitiesWeaknessesString) {
immunities = Attack.identify(immunitiesWeaknessesString)
}
}
}
groupId++
Group(armyType,
armyType.toString() + groupId,
numberOfUnitsString.toInt(),
numberOfHitPointsString.toInt(),
attackDamageString.toInt(),
Attack.identify(attackTypeString)[0],
initiativeString.toInt(),
weaknesses,
immunities)
}
.toMutableList())
}
fun getGroup(army: Army, id: String): Group {
return army.groups.first { group -> group.id == id }
}
fun calculateTargetIds(attackingArmy: Army, defendingArmy: Army): Map<String, String?> {
val sortedAttackingArmyGroups = attackingArmy
.groups
.sortedWith(compareByDescending<Group> { attackingGroup ->
attackingGroup.effectivePower
}.thenByDescending { attackingGroup -> attackingGroup.initiative })
val mutableDefendingArmyGroups = defendingArmy.groups.toMutableList()
val result = mutableMapOf<String, String?>()
sortedAttackingArmyGroups.forEach { attackingGroup ->
if (mutableDefendingArmyGroups.isNotEmpty()) {
val potentialDefendingTarget = mutableDefendingArmyGroups
.sortedWith(compareByDescending<Group> { defendingGroup ->
defendingGroup.damageBy(attackingGroup)
}.thenByDescending { defendingGroup ->
defendingGroup.effectivePower
}.thenByDescending { defendingGroup ->
defendingGroup.initiative
})
.first()
if (potentialDefendingTarget.damageBy(attackingGroup) > 0) {
result[attackingGroup.id] = potentialDefendingTarget.id
mutableDefendingArmyGroups -= potentialDefendingTarget
} else {
result[attackingGroup.id] = null
}
} else {
result[attackingGroup.id] = null
}
}
return result.toMap()
}
fun runCombat(immuneSystemArmy: Army, infectionArmy: Army): Outcome {
var currentImmuneSystemTotalSize = immuneSystemArmy.totalSize()
var currentInfectionTotalSize = infectionArmy.totalSize()
while (true) {
// targets must be calculated first, rather than on the fly
val immuneSystemTargetIds = calculateTargetIds(immuneSystemArmy, infectionArmy)
val infectionTargetIds = calculateTargetIds(infectionArmy, immuneSystemArmy)
val sortedCombinedGroups = (immuneSystemArmy.groups + infectionArmy.groups)
.sortedByDescending { group -> group.initiative }
sortedCombinedGroups.forEach { attackingGroup ->
if (attackingGroup.numberOfUnits != 0) {
val targetIds: Map<String, String?>
val targetArmy: Army
when (attackingGroup.armyType) {
ArmyType.IMMUNE_SYSTEM -> {
targetIds = immuneSystemTargetIds
targetArmy = infectionArmy
}
ArmyType.INFECTION -> {
targetIds = infectionTargetIds
targetArmy = immuneSystemArmy
}
}
val targetId = targetIds[attackingGroup.id]
if (targetId != null) {
val targetGroup = getGroup(targetArmy, targetId)
targetGroup.attackBy(attackingGroup)
}
targetArmy.groups.removeIf { group -> group.numberOfUnits <= 0 }
}
}
if (immuneSystemArmy.isEmpty()) {
return Outcome.INFECTION
} else if (infectionArmy.isEmpty()) {
return Outcome.IMMUNE_SYSTEM
} else if (currentImmuneSystemTotalSize == immuneSystemArmy.totalSize() && currentInfectionTotalSize == infectionArmy.totalSize()) {
return Outcome.STALEMATE
} else {
currentImmuneSystemTotalSize = immuneSystemArmy.totalSize()
currentInfectionTotalSize = infectionArmy.totalSize()
}
}
}
data class Army(var groups: MutableList<Group>) {
fun isEmpty(): Boolean {
return groups.size == 0
}
fun totalSize(): Int {
return groups.sumBy { group -> group.numberOfUnits }
}
fun boostBy(boost: Int) {
groups.forEach { group -> group.attackDamage += boost }
}
}
data class Group(val armyType: ArmyType,
val id: String,
var numberOfUnits: Int,
val numberOfHitPoints: Int,
var attackDamage: Int,
val attackType: Attack,
val initiative: Int,
val weaknesses: List<Attack>,
val immunities: List<Attack>) {
val effectivePower: Int
get() = numberOfUnits * attackDamage
fun damageBy(otherGroup: Group): Int {
return when {
otherGroup.attackType in this.weaknesses -> otherGroup.effectivePower * 2
otherGroup.attackType in this.immunities -> 0
else -> otherGroup.effectivePower
}
}
fun attackBy(otherGroup: Group) {
numberOfUnits = Math.max(0, numberOfUnits - damageBy(otherGroup) / numberOfHitPoints)
}
}
enum class ArmyType {
IMMUNE_SYSTEM, INFECTION;
}
enum class Attack {
BLUDGEONING, COLD, FIRE, RADIATION, SLASHING;
companion object {
fun identify(input: String): List<Attack> {
val result = mutableListOf<Attack>()
if ("bludgeoning" in input) result += BLUDGEONING
if ("cold" in input) result += COLD
if ("fire" in input) result += FIRE
if ("radiation" in input) result += RADIATION
if ("slashing" in input) result += SLASHING
return result
}
}
}
enum class Outcome {
IMMUNE_SYSTEM, INFECTION, STALEMATE;
}
| 0
|
Kotlin
|
0
| 0
|
c404f1c47c9dee266b2330ecae98471e19056549
| 9,760
|
AdventOfCode2018
|
MIT License
|
app/src/main/java/com/jakoon/playground/repository/Repository.kt
|
andreas-borglin
| 186,784,984
| false
| null |
package com.jakoon.playground.repository
import com.jakoon.playground.data.cache.Cache
import com.jakoon.playground.data.network.TypicodeJsonService
import com.jakoon.playground.model.Post
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.supervisorScope
import kotlinx.coroutines.withContext
class Repository(val apiService: TypicodeJsonService, val cache: Cache, val dispatcher: CoroutineDispatcher) {
// TODO is there a race condition between this and getPosts?
fun clearCache() = cache.clear()
suspend fun getPosts(): DataResult<List<Post>> = withContext(dispatcher) {
cache.getCachedPosts()?.let { DataResult.Success(it) }
?: getData(cache = { cache.setCachedPosts(it) }, apiCall = { apiService.getPosts() })
}
suspend fun getPostDetails(post: Post): DataResult<Post> = withContext(dispatcher) {
if (post.hasDetails()) {
DataResult.Success(post)
} else {
// TODO this scope allows us to return failure on exception - but is it the right way?
supervisorScope {
try {
val userCall = async { apiService.getUser(post.userId) }
val commentsCall = async { apiService.getComments(post.id) }
post.user = userCall.await()[0]
post.comments = commentsCall.await()
DataResult.Success(post)
} catch (t: Throwable) {
DataResult.Failure<Post>(t)
}
}
}
}
// TODO unnecessary allocation of lamdba for cache when not used
private inline fun <T> getData(cache: (T) -> Unit = {}, apiCall: () -> T): DataResult<T> {
return try {
val list = apiCall()
cache(list)
DataResult.Success(list)
} catch (t: Throwable) {
DataResult.Failure(t)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d1ab301d2c0b938237721a553138a351f66ea357
| 1,954
|
android-playground
|
Apache License 2.0
|
src/main/kotlin/com/forestvpn/api/client/apis/NotificationsForestVPNAPI.kt
|
forestvpn
| 593,656,292
| false
| null |
/**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package com.forestvpn.api.client.apis
import java.io.IOException
import okhttp3.OkHttpClient
import okhttp3.HttpUrl
import com.forestvpn.api.client.models.Error
import com.forestvpn.api.client.models.NotificationAllList
import com.forestvpn.api.client.models.NotificationUnreadCount
import com.squareup.moshi.Json
import com.forestvpn.api.client.infrastructure.ApiClient
import com.forestvpn.api.client.infrastructure.ApiResponse
import com.forestvpn.api.client.infrastructure.ClientException
import com.forestvpn.api.client.infrastructure.ClientError
import com.forestvpn.api.client.infrastructure.ServerException
import com.forestvpn.api.client.infrastructure.ServerError
import com.forestvpn.api.client.infrastructure.MultiValueMap
import com.forestvpn.api.client.infrastructure.PartConfig
import com.forestvpn.api.client.infrastructure.RequestConfig
import com.forestvpn.api.client.infrastructure.RequestMethod
import com.forestvpn.api.client.infrastructure.ResponseType
import com.forestvpn.api.client.infrastructure.Success
import com.forestvpn.api.client.infrastructure.toMultiValue
class NotificationsForestVPNAPI(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ApiClient.defaultClient) : ApiClient(basePath, client) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty(ApiClient.baseUrlKey, "https://api.forestvpn.com/v2")
}
}
/**
* Get unread notifications count
*
* @return NotificationUnreadCount
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getNotificationsUnreadCount() : NotificationUnreadCount {
val localVarResponse = getNotificationsUnreadCountWithHttpInfo()
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as NotificationUnreadCount
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Get unread notifications count
*
* @return ApiResponse<NotificationUnreadCount?>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class)
fun getNotificationsUnreadCountWithHttpInfo() : ApiResponse<NotificationUnreadCount?> {
val localVariableConfig = getNotificationsUnreadCountRequestConfig()
return request<Unit, NotificationUnreadCount>(
localVariableConfig
)
}
/**
* To obtain the request config of the operation getNotificationsUnreadCount
*
* @return RequestConfig
*/
fun getNotificationsUnreadCountRequestConfig() : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
localVariableHeaders["Accept"] = "application/json"
return RequestConfig(
method = RequestMethod.GET,
path = "/notifications/unread_count/",
query = localVariableQuery,
headers = localVariableHeaders,
body = localVariableBody
)
}
/**
* Get notifications list
*
* @param max (optional)
* @return kotlin.collections.List<NotificationAllList>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun listNotifications(max: kotlin.Int? = null) : kotlin.collections.List<NotificationAllList> {
val localVarResponse = listNotificationsWithHttpInfo(max = max)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List<NotificationAllList>
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Get notifications list
*
* @param max (optional)
* @return ApiResponse<kotlin.collections.List<NotificationAllList>?>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class)
fun listNotificationsWithHttpInfo(max: kotlin.Int?) : ApiResponse<kotlin.collections.List<NotificationAllList>?> {
val localVariableConfig = listNotificationsRequestConfig(max = max)
return request<Unit, kotlin.collections.List<NotificationAllList>>(
localVariableConfig
)
}
/**
* To obtain the request config of the operation listNotifications
*
* @param max (optional)
* @return RequestConfig
*/
fun listNotificationsRequestConfig(max: kotlin.Int?) : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, kotlin.collections.List<kotlin.String>>()
.apply {
if (max != null) {
put("max", listOf(max.toString()))
}
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
localVariableHeaders["Accept"] = "application/json"
return RequestConfig(
method = RequestMethod.GET,
path = "/notifications/all_list/",
query = localVariableQuery,
headers = localVariableHeaders,
body = localVariableBody
)
}
/**
* Mark notification as read by user
*
* @param slug
* @param next
* @return Error
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updateNotificationMarkRead(slug: kotlin.Int, next: kotlin.String) : Error {
val localVarResponse = updateNotificationMarkReadWithHttpInfo(slug = slug, next = next)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Error
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Mark notification as read by user
*
* @param slug
* @param next
* @return ApiResponse<Error?>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class)
fun updateNotificationMarkReadWithHttpInfo(slug: kotlin.Int, next: kotlin.String) : ApiResponse<Error?> {
val localVariableConfig = updateNotificationMarkReadRequestConfig(slug = slug, next = next)
return request<Unit, Error>(
localVariableConfig
)
}
/**
* To obtain the request config of the operation updateNotificationMarkRead
*
* @param slug
* @param next
* @return RequestConfig
*/
fun updateNotificationMarkReadRequestConfig(slug: kotlin.Int, next: kotlin.String) : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
localVariableHeaders["Accept"] = "application/json"
return RequestConfig(
method = RequestMethod.GET,
path = "/notifications/mark_read/{slug}/".replace("{"+"slug"+"}", encodeURIComponent(slug.toString())).replace("{"+"next"+"}", encodeURIComponent(next.toString())),
query = localVariableQuery,
headers = localVariableHeaders,
body = localVariableBody
)
}
/**
* Mark all notifications as read by user
*
* @param next
* @return Error
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun updateNotificationMarkReadAll(next: kotlin.String) : Error {
val localVarResponse = updateNotificationMarkReadAllWithHttpInfo(next = next)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Error
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Mark all notifications as read by user
*
* @param next
* @return ApiResponse<Error?>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class)
fun updateNotificationMarkReadAllWithHttpInfo(next: kotlin.String) : ApiResponse<Error?> {
val localVariableConfig = updateNotificationMarkReadAllRequestConfig(next = next)
return request<Unit, Error>(
localVariableConfig
)
}
/**
* To obtain the request config of the operation updateNotificationMarkReadAll
*
* @param next
* @return RequestConfig
*/
fun updateNotificationMarkReadAllRequestConfig(next: kotlin.String) : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
localVariableHeaders["Accept"] = "application/json"
return RequestConfig(
method = RequestMethod.GET,
path = "/notifications/mark-all-as-read/".replace("{"+"next"+"}", encodeURIComponent(next.toString())),
query = localVariableQuery,
headers = localVariableHeaders,
body = localVariableBody
)
}
private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String =
HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0]
}
| 0
|
Kotlin
|
0
| 0
|
06ee868f1fa748bcdfe96515352c334b91dbe353
| 15,459
|
api-client-kotlin
|
MIT License
|
kotlin-node/src/jsMain/generated/node/process/UncaughtExceptionListener.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 12363456, "JavaScript": 408220}
|
// Generated by Karakum - do not modify it manually!
package node.process
import js.errors.JsError
typealias UncaughtExceptionListener = (error: JsError, origin: UncaughtExceptionOrigin) -> Unit
| 39
|
Kotlin
|
165
| 1,330
|
809b00e4aa9fbaa46d0ebfd82ac2b574b5898dfc
| 198
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/app/airsignal/weather/util/TimberUtil.kt
|
tekken5953
| 611,614,821
| false
|
{"Kotlin": 476575, "Java": 2290}
|
package app.airsignal.weather.util
import timber.log.Timber
class TimberUtil {
fun getInstance() : TimberUtil {
Timber.plant(Timber.DebugTree())
return this
}
fun d(tag: String, msg: String?) {
Timber.tag(tag).d(msg)
}
fun i(tag: String, msg: String?) {
Timber.tag(tag).i(msg)
}
fun w(tag: String, msg: String?) {
Timber.tag(tag).w(msg)
}
fun e(tag: String, msg: String?) {
Timber.tag(tag).e(msg)
}
}
| 0
|
Kotlin
|
0
| 1
|
b6eb47b7d6274e60685161baa8f341a89ec7b0d3
| 495
|
AS_Cloud_App
|
Open Market License
|
sample/src/main/java/com/kkagurazaka/redukt/sample/query/VisibilityFilter.kt
|
k-kagurazaka
| 115,560,556
| false
| null |
package com.kkagurazaka.redukt.sample.query
enum class VisibilityFilter {
ALL,
ACTIVE,
COMPLETED
}
| 0
|
Kotlin
|
0
| 12
|
a13bcdd3d934357a0bb8744765efb104efc362ac
| 112
|
ReduKt
|
Apache License 2.0
|
app/src/main/java/com/uad/portal/Session.kt
|
IRedDragonICY
| 767,423,190
| false
|
{"Kotlin": 44134}
|
package com.uad.portal
data class Session(
var session: String? = null,
var userInfo: UserInfo? = null,
var credentials: Credentials? = null
)
data class ReglabSession(
var session: String? = null,
var credentials: ReglabCredentials? = null
)
| 0
|
Kotlin
|
0
| 0
|
4cea43f906f0e8b804cf72076ae659b359224830
| 264
|
portal-uad
|
MIT License
|
src/main/kotlin/me/drbaxr/spektrum/flexible/adapters/java/model/internal/MethodTreeNodeJava.kt
|
dxworks
| 463,883,061
| false
| null |
package me.drbaxr.spektrum.flexible.adapters.java.model.internal
import me.drbaxr.spektrum.flexible.adapters.java.model.external.ProjectJava
data class MethodTreeNodeJava(
val id: Long,
val callerMethods: Set<MethodTreeNodeJava>
) {
fun toOrderString(project: ProjectJava): String {
val orderMap = getOrderMap()
var orderString = "${project.getMethodHierarchyName(id)}\n"
orderMap.keys.forEach { key ->
orderString = orderString.plus("\tOrder $key:\n")
val callers = orderMap[key] ?: listOf()
callers.forEach { caller ->
orderString = orderString.plus("\t\t${project.getMethodHierarchyName(caller)}\n")
}
}
return orderString
}
fun getCallerMap(project: ProjectJava): Map<String, Int> {
val orderMap = getOrderMap()
val callerMap = mutableMapOf<String, Int>()
orderMap.keys.forEach { order ->
val methodIds = orderMap[order] ?: listOf()
methodIds.forEach { id ->
val fullName = project.getMethodHierarchyName(id)
val currentOrder = callerMap[fullName]
if (currentOrder == null || order < currentOrder) {
callerMap[fullName] = order
}
}
}
return callerMap
}
private fun getOrderMap(): Map<Int, List<Long>> {
val orderMap = mutableMapOf<Int, MutableList<Long>>()
getOrderMap(1, orderMap)
return orderMap
}
// builds the order map in the map param
private fun getOrderMap(currentOrder: Int, map: MutableMap<Int, MutableList<Long>>) {
if (callerMethods.isNotEmpty()) {
if (map[currentOrder] == null) {
map[currentOrder] = mutableListOf()
}
val currentOrderList = map[currentOrder] ?: mutableListOf()
currentOrderList.addAll(callerMethods.map { it.id })
callerMethods.forEach {
it.getOrderMap(currentOrder + 1, map)
}
}
}
}
| 0
|
Kotlin
|
1
| 0
|
14953414b4b303e5278fba6228ed899ffd6ce0f0
| 2,083
|
spektrum
|
MIT License
|
decompiler-gradle-plugin/src/test/kotlin/io/github/iamwent/decompiler/DecompilerPluginTest.kt
|
iamwent
| 778,085,786
| false
|
{"Kotlin": 3545}
|
package io.github.iamwent.decompiler
import org.gradle.testfixtures.ProjectBuilder
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class DecompilerPluginTest {
@Test
fun pluginTest() {
val pluginId = "io.github.iamwent.decompiler"
val project = ProjectBuilder.builder().build()
project.pluginManager.apply(pluginId)
assertTrue(project.pluginManager.hasPlugin(pluginId))
}
}
| 0
|
Kotlin
|
0
| 0
|
c1fb11b5bf4cf3f117b86877c197d72538124330
| 459
|
decompiler-gradle-plugin
|
Apache License 2.0
|
src/main/java/httpclient/entity/HttpMethod.kt
|
shiqos
| 199,397,179
| false
|
{"Kotlin": 2699}
|
package httpclient.entity
enum class HttpMethod(value: String) {
GET("get"),
POST("post"),
PUT("put"),
DELETE("delete")
}
| 0
|
Kotlin
|
0
| 0
|
29f17b14b807756f88cb004cb3570bcf54199d47
| 138
|
HttpClient
|
Apache License 2.0
|
backend/src/test/kotlin/com/denchic45/studiversity/client/role/CapabilitiesTest.kt
|
denchic45
| 435,895,363
| false
|
{"Kotlin": 2110094, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
|
package com.denchic45.studiversity.client.role
import com.denchic45.studiversity.KtorClientTest
import com.denchic45.studiversity.util.assertedResultIsOk
import com.denchic45.studiversity.util.unwrapAsserted
import com.denchic45.studiversity.api.membership.MembershipApi
import com.denchic45.studiversity.api.role.CapabilityApi
import com.denchic45.studiversity.api.role.RoleApi
import com.denchic45.studiversity.api.role.model.Capability
import com.denchic45.studiversity.api.role.model.Role
import com.denchic45.studiversity.api.studygroup.StudyGroupApi
import com.denchic45.studiversity.api.studygroup.model.AcademicYear
import com.denchic45.studiversity.api.studygroup.model.CreateStudyGroupRequest
import com.denchic45.studiversity.api.studygroup.model.StudyGroupResponse
import com.denchic45.studiversity.api.user.UserApi
import com.denchic45.studiversity.api.user.model.CreateUserRequest
import com.denchic45.studiversity.api.user.model.Gender
import com.denchic45.studiversity.api.user.model.UserResponse
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.koin.core.parameter.parametersOf
import org.koin.test.inject
class CapabilitiesTest : KtorClientTest() {
private val capabilityApi: CapabilityApi by inject { parametersOf(client) }
private val roleApi: RoleApi by inject { parametersOf(client) }
private val userApi: UserApi by inject { parametersOf(client) }
private val studyGroupApi: StudyGroupApi by inject { parametersOf(client) }
private val membershipApi: MembershipApi by inject { parametersOf(client) }
private lateinit var user: UserResponse
private lateinit var studyGroup: StudyGroupResponse
@BeforeEach
fun init(): Unit = runBlocking {
user = userApi.create(
CreateUserRequest("Anton", "Ermolin", null, "anton@mail.ru", Gender.MALE, emptyList())
).unwrapAsserted()
studyGroup = studyGroupApi.create(
CreateStudyGroupRequest("Test group", AcademicYear(2023, 2027), null, null)
).unwrapAsserted()
membershipApi.joinToScopeManually(user.id, studyGroup.id, listOf(Role.Student.id))
}
@AfterEach
fun tearDown(): Unit = runBlocking {
userApi.delete(user.id).assertedResultIsOk()
studyGroupApi.delete(studyGroup.id)
}
// TODO: rewrite with other roles and capabilities
@Test
fun test(): Unit = runBlocking {
val response1 = capabilityApi.check(user.id, studyGroup.id, listOf(Capability.BeStudent)).unwrapAsserted()
assertTrue(response1.hasCapability(Capability.BeStudent))
roleApi.deleteRoleFromUserInScope(user.id, studyGroup.id, Role.Student.id).unwrapAsserted()
roleApi.assignRoleToUserInScope(user.id, studyGroup.id, Role.Headman.id).unwrapAsserted()
val response2 = capabilityApi.check(user.id, studyGroup.id, listOf(Capability.BeStudent)).unwrapAsserted()
assertTrue(response2.hasCapability(Capability.BeStudent))
}
}
| 0
|
Kotlin
|
0
| 7
|
293132d2f93ba3e42a3efe9b54deb07d7ff5ecf9
| 3,108
|
Studiversity
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.