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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/linc/com/getmeexample/fragments/StartFragment.kt | lincollincol | 262,124,997 | false | null | package linc.com.getmeexample.fragments
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import linc.com.getmeexample.ExampleGetMeActivity
import linc.com.getmeexample.MainActivity
import linc.com.getmeexample.R
class StartFragment : Fragment(), View.OnClickListener {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_start, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<Button>(R.id.defaultGetMe).setOnClickListener(this)
view.findViewById<Button>(R.id.customGetMeItemLayout).setOnClickListener(this)
view.findViewById<Button>(R.id.customGetMeStyle).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeMainContent).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeExceptContent).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeOnlyDirectories).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeSingleSelection).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeFromPath).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeMaximumSelectionSize).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeAdapterAnimation).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeOverScroll).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeFromActivity).setOnClickListener(this)
}
override fun onClick(p0: View?) {
when(p0?.id) {
R.id.defaultGetMe -> openFragment(ExampleGetMeFragment.DEFAULT_GETME)
R.id.customGetMeItemLayout -> openFragment(ExampleGetMeFragment.CUSTOM_ITEM_LAYOUT_GETME)
R.id.customGetMeStyle -> openFragment(ExampleGetMeFragment.CUSTOM_STYLE_GETME)
R.id.getMeMainContent -> openFragment(ExampleGetMeFragment.MAIN_CONTENT_GETME)
R.id.getMeExceptContent -> openFragment(ExampleGetMeFragment.EXCEPT_CONTENT_GETME)
R.id.getMeOnlyDirectories -> openFragment(ExampleGetMeFragment.ONLY_DIRECTORIES_GETME)
R.id.getMeSingleSelection -> openFragment(ExampleGetMeFragment.SINGLE_SELECTION_GETME)
R.id.getMeFromPath -> openFragment(ExampleGetMeFragment.FROM_PATH_GETME)
R.id.getMeMaximumSelectionSize -> openFragment(ExampleGetMeFragment.MAX_SELECTION_SIZE_GETME)
R.id.getMeAdapterAnimation -> openFragment(ExampleGetMeFragment.ADAPTER_ANIMATION_GETME)
R.id.getMeOverScroll -> openFragment(ExampleGetMeFragment.OVERSCROLL_GETME)
R.id.getMeFromActivity -> {
startActivity(Intent(this.context, ExampleGetMeActivity::class.java))
}
}
}
private fun openFragment(type: Int) {
fragmentManager?.beginTransaction()
?.replace(
R.id.fragmentContainer,
ExampleGetMeFragment.newInstance(type)
)
?.addToBackStack(null)
?.commit()
}
}
| 1 | Kotlin | 1 | 3 | a1166012cb9f64104e4b7037470f6afd9ce579ac | 3,340 | GetMe | Apache License 2.0 |
src/test/polkauction/core/service/sidecar/SidecarClientServiceTest.kt | CrommVardek | 366,623,025 | false | null | package polkauction.core.service.sidecar
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import polkauction.core.exception.NoSuchChainException
class SidecarClientServiceTest {
@Test
fun initSidecarClientWithUnknownRelayChainShouldThrowNoSuchChainException() {
val unknownChain = "Ethereum"
Assertions.assertThrows(NoSuchChainException::class.java) {
SidecarClient(unknownChain)
}
}
} | 0 | Kotlin | 2 | 2 | 58edc8e99c8cd148100497142af3f831664d796a | 461 | polk-auction-core | Apache License 2.0 |
src/main/kotlin/io/usoamic/commons/crossplatform/exceptions/PreferenceKeyNotFoundThrowable.kt | usoamic | 328,202,010 | false | null | package io.usoamic.commons.crossplatform.exceptions
class PreferenceKeyNotFoundThrowable(key: String) : Throwable("$key not found") | 0 | Kotlin | 0 | 0 | 7d3e9d2d3cb3127c61d43a02909c014df3a23973 | 132 | usoamic-commons-crossplatform | MIT License |
tools/plugins/network/src/main/kotlin/net/corda/cli/plugins/network/BaseOnboard.kt | corda | 346,070,752 | false | {"Kotlin": 19951814, "Java": 320782, "Smarty": 115647, "Shell": 54666, "Groovy": 30254, "PowerShell": 6509, "TypeScript": 5826, "Solidity": 2024} | @file:Suppress("DEPRECATION")
package net.corda.cli.plugins.network
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import net.corda.cli.plugins.common.RestCommand
import net.corda.cli.plugins.packaging.signing.SigningOptions
import net.corda.crypto.cipher.suite.schemes.RSA_TEMPLATE
import net.corda.crypto.core.CryptoConsts.Categories.KeyCategory
import net.corda.crypto.test.certificates.generation.CertificateAuthorityFactory
import net.corda.crypto.test.certificates.generation.toFactoryDefinitions
import net.corda.crypto.test.certificates.generation.toPem
import net.corda.data.certificates.CertificateUsage
import net.corda.libs.configuration.endpoints.v1.ConfigRestResource
import net.corda.libs.configuration.endpoints.v1.types.ConfigSchemaVersion
import net.corda.libs.configuration.endpoints.v1.types.UpdateConfigParameters
import net.corda.libs.cpiupload.endpoints.v1.CpiUploadRestResource
import net.corda.libs.virtualnode.endpoints.v1.VirtualNodeRestResource
import net.corda.libs.virtualnode.endpoints.v1.types.CreateVirtualNodeRequestType.JsonCreateVirtualNodeRequest
import net.corda.membership.rest.v1.CertificatesRestResource
import net.corda.membership.rest.v1.HsmRestResource
import net.corda.membership.rest.v1.KeysRestResource
import net.corda.membership.rest.v1.MemberRegistrationRestResource
import net.corda.membership.rest.v1.NetworkRestResource
import net.corda.membership.rest.v1.types.request.HostedIdentitySessionKeyAndCertificate
import net.corda.membership.rest.v1.types.request.HostedIdentitySetupRequest
import net.corda.membership.rest.v1.types.response.KeyPairIdentifier
import net.corda.rest.json.serialization.JsonObjectAsString
import net.corda.schema.configuration.ConfigKeys.RootConfigKey
import net.corda.sdk.config.ClusterConfig
import net.corda.sdk.network.ClientCertificates
import net.corda.sdk.network.Keys
import net.corda.sdk.network.RegistrationRequester
import net.corda.sdk.network.RegistrationsLookup
import net.corda.sdk.network.VirtualNode
import net.corda.sdk.packaging.CpiUploader
import net.corda.sdk.packaging.KeyStoreHelper
import net.corda.sdk.rest.RestClientUtils.createRestClient
import picocli.CommandLine.Option
import picocli.CommandLine.Parameters
import java.io.File
import java.net.URI
import java.security.KeyStore
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
@Suppress("TooManyFunctions")
abstract class BaseOnboard : Runnable, RestCommand() {
private companion object {
const val P2P_TLS_CERTIFICATE_ALIAS = "p2p-tls-cert"
const val SIGNING_KEY_ALIAS = "signing key 1"
const val SIGNING_KEY_STORE_PASSWORD = "<PASSWORD>"
const val GRADLE_PLUGIN_DEFAULT_KEY_ALIAS = "gradle-plugin-default-key"
}
@Parameters(
description = ["The X500 name of the virtual node."],
arity = "1",
index = "0",
)
lateinit var name: String
@Option(
names = ["--mutual-tls", "-m"],
description = ["Enable mutual TLS"],
)
var mtls: Boolean = false
@Option(
names = ["--tls-certificate-subject", "-c"],
description = [
"The TLS certificate subject. Leave empty to use random certificate subject." +
"Will only be used on the first onboard to the cluster.",
],
)
var tlsCertificateSubject: String? = null
@Option(
names = ["--p2p-gateway-url", "-g"],
description = ["P2P Gateway URL. Multiple URLs may be provided. Defaults to https://localhost:8080."],
)
var p2pGatewayUrls: List<String> = listOf("https://localhost:8080")
protected val json by lazy {
ObjectMapper()
}
private val caHome: File = File(File(File(System.getProperty("user.home")), ".corda"), "ca")
internal class OnboardException(message: String) : Exception(message)
protected fun uploadCpi(cpi: File, cpiName: String): String {
val restClient = createRestClient(
CpiUploadRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
// Cpi upload can take longer than the default 10 seconds, wait for minimum of 30
val longerWaitValue = getLongerWait()
val uploadId = CpiUploader().uploadCPI(restClient, cpi.inputStream(), cpiName, longerWaitValue).id
return checkCpiStatus(uploadId)
}
private fun getLongerWait(): Duration {
return if (waitDurationSeconds.seconds > 30.seconds) {
waitDurationSeconds.seconds
} else {
30.seconds
}
}
private fun checkCpiStatus(id: String): String {
val restClient = createRestClient(
CpiUploadRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
return CpiUploader().cpiChecksum(restClient = restClient, uploadRequestId = id, wait = waitDurationSeconds.seconds)
}
protected abstract val cpiFileChecksum: String
protected abstract val registrationContext: Map<String, String>
protected val holdingId: String by lazy {
val restClient = createRestClient(
VirtualNodeRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val request = JsonCreateVirtualNodeRequest(
x500Name = name,
cpiFileChecksum = cpiFileChecksum,
vaultDdlConnection = null,
vaultDmlConnection = null,
cryptoDdlConnection = null,
cryptoDmlConnection = null,
uniquenessDdlConnection = null,
uniquenessDmlConnection = null,
)
val longerWait = getLongerWait()
val shortHashId = VirtualNode().createAndWaitForActive(restClient, request, longerWait)
println("Holding identity short hash of '$name' is: '$shortHashId'")
shortHashId
}
protected fun assignSoftHsmAndGenerateKey(category: KeyCategory): KeyPairIdentifier {
val hsmRestClient = createRestClient(
HsmRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val keyRestClient = createRestClient(
KeysRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
return Keys().assignSoftHsmAndGenerateKey(
hsmRestClient = hsmRestClient,
keysRestClient = keyRestClient,
holdingIdentityShortHash = holdingId,
category = category,
wait = waitDurationSeconds.seconds
)
}
protected val sessionKeyId by lazy {
assignSoftHsmAndGenerateKey(KeyCategory.SESSION_INIT_KEY)
}
protected val ecdhKeyId by lazy {
assignSoftHsmAndGenerateKey(KeyCategory.PRE_AUTH_KEY)
}
protected val certificateSubject by lazy {
tlsCertificateSubject ?: "O=P2P Certificate, OU=$p2pHosts, L=London, C=GB"
}
private val p2pHosts = extractHostsFromUrls(p2pGatewayUrls)
private fun extractHostsFromUrls(urls: List<String>): List<String> {
return urls.map { extractHostFromUrl(it) }.distinct()
}
private fun extractHostFromUrl(url: String): String {
return URI.create(url).host ?: throw IllegalArgumentException("Invalid URL: $url")
}
protected val ca by lazy {
caHome.parentFile.mkdirs()
CertificateAuthorityFactory
.createFileSystemLocalAuthority(
RSA_TEMPLATE.toFactoryDefinitions(),
caHome,
).also { it.save() }
}
protected fun createTlsKeyIdNeeded() {
val keyRestClient = createRestClient(
KeysRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val keys = Keys()
val hasKeys = keys.hasTlsKey(restClient = keyRestClient, wait = waitDurationSeconds.seconds)
if (hasKeys) return
val tlsKeyId = keys.generateTlsKey(restClient = keyRestClient, wait = waitDurationSeconds.seconds)
val certificateRestClient = createRestClient(
CertificatesRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val clientCertificates = ClientCertificates()
val csrCertRequest = clientCertificates.generateP2pCsr(
certificateRestClient,
tlsKeyId,
certificateSubject,
p2pHosts,
waitDurationSeconds.seconds
)
val certificate = ca.signCsr(csrCertRequest).toPem().byteInputStream()
clientCertificates.uploadTlsCertificate(certificateRestClient, certificate, P2P_TLS_CERTIFICATE_ALIAS, waitDurationSeconds.seconds)
}
protected fun setupNetwork() {
val restClient = createRestClient(
NetworkRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val request = HostedIdentitySetupRequest(
p2pTlsCertificateChainAlias = P2P_TLS_CERTIFICATE_ALIAS,
useClusterLevelTlsCertificateAndKey = true,
sessionKeysAndCertificates = listOf(
HostedIdentitySessionKeyAndCertificate(
sessionKeyId = sessionKeyId.id,
preferred = true,
),
),
)
RegistrationRequester().configureAsNetworkParticipant(
restClient = restClient,
request = request,
holdingId = holdingId,
wait = waitDurationSeconds.seconds
)
}
protected fun register(waitForFinalStatus: Boolean = true) {
val restClient = createRestClient(
MemberRegistrationRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val response = RegistrationRequester().requestRegistration(
restClient = restClient,
registrationContext = registrationContext,
holdingId = holdingId
)
val registrationId = response.registrationId
val submissionStatus = response.registrationStatus
if (submissionStatus != "SUBMITTED") {
throw OnboardException("Could not submit registration request: ${response.memberInfoSubmitted}")
}
println("Registration ID for '$name' is '$registrationId'")
// Registrations can take longer than the default 10 seconds, wait for minimum of 30
val longerWaitValue = getLongerWait()
if (waitForFinalStatus) {
RegistrationsLookup().waitForRegistrationApproval(
restClient = restClient,
registrationId = registrationId,
holdingId = holdingId,
wait = longerWaitValue
)
}
}
protected fun configureGateway() {
val restClient = createRestClient(
ConfigRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val clusterConfig = ClusterConfig()
val currentConfig = clusterConfig.getCurrentConfig(restClient, RootConfigKey.P2P_GATEWAY, waitDurationSeconds.seconds)
val rawConfig = currentConfig.configWithDefaults
val rawConfigJson = json.readTree(rawConfig)
val sslConfig = rawConfigJson["sslConfig"]
val currentMode = sslConfig["revocationCheck"]?.get("mode")?.asText()
val currentTlsType = sslConfig["tlsType"]?.asText()
val tlsType = if (mtls) {
"MUTUAL"
} else {
"ONE_WAY"
}
if ((currentMode != "OFF") || (currentTlsType != tlsType)) {
val objectMapper = ObjectMapper()
val newConfig = objectMapper.createObjectNode()
newConfig.set<ObjectNode>(
"sslConfig",
objectMapper.createObjectNode()
.put("tlsType", tlsType.uppercase())
.set<ObjectNode>(
"revocationCheck",
json.createObjectNode().put("mode", "OFF"),
),
)
val payload = UpdateConfigParameters(
section = "corda.p2p.gateway",
version = currentConfig.version,
config = JsonObjectAsString(objectMapper.writeValueAsString(newConfig)),
schemaVersion = ConfigSchemaVersion(major = currentConfig.schemaVersion.major, minor = currentConfig.schemaVersion.minor),
)
clusterConfig.updateConfig(restClient = restClient, updateConfig = payload, wait = waitDurationSeconds.seconds)
}
}
private val keyStoreFile by lazy {
File(File(File(System.getProperty("user.home")), ".corda"), "signingkeys.pfx")
}
protected fun createDefaultSingingOptions(): SigningOptions {
val options = SigningOptions()
options.keyAlias = SIGNING_KEY_ALIAS
options.keyStorePass = <PASSWORD>
options.keyStoreFileName = keyStoreFile.absolutePath
val keyStoreHelper = KeyStoreHelper()
if (!keyStoreFile.canRead()) {
keyStoreHelper.generateKeyStore(
keyStoreFile = keyStoreFile,
alias = SIGNING_KEY_ALIAS,
password = <PASSWORD>
)
val defaultGradleCert = keyStoreHelper.getDefaultGradleCertificateStream()
KeyStoreHelper().importCertificateIntoKeyStore(
keyStoreFile = keyStoreFile,
keyStorePassword = <PASSWORD>,
certificateInputStream = defaultGradleCert,
certificateAlias = GRADLE_PLUGIN_DEFAULT_KEY_ALIAS,
certificateFactoryType = "X.509"
)
}
return options
}
protected fun uploadSigningCertificates() {
val restClient = createRestClient(
CertificatesRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val keyStore = KeyStore.getInstance(
keyStoreFile,
SIGNING_KEY_STORE_PASSWORD.toCharArray(),
)
keyStore.getCertificate(GRADLE_PLUGIN_DEFAULT_KEY_ALIAS)
?.toPem()
?.byteInputStream()
?.use { certificate ->
ClientCertificates().uploadCertificate(
restClient = restClient,
certificate = certificate,
usage = CertificateUsage.CODE_SIGNER,
alias = GRADLE_PLUGIN_DEFAULT_KEY_ALIAS,
wait = waitDurationSeconds.seconds
)
}
keyStore.getCertificate(SIGNING_KEY_ALIAS)
?.toPem()
?.byteInputStream()
?.use { certificate ->
ClientCertificates().uploadCertificate(
restClient = restClient,
certificate = certificate,
usage = CertificateUsage.CODE_SIGNER,
alias = "signingkey1-2022",
wait = waitDurationSeconds.seconds
)
}
}
}
| 32 | Kotlin | 25 | 56 | dd139d8da25a3c52ae17ca8d0debc3da4067f158 | 16,673 | corda-runtime-os | Apache License 2.0 |
tools/plugins/network/src/main/kotlin/net/corda/cli/plugins/network/BaseOnboard.kt | corda | 346,070,752 | false | {"Kotlin": 19951814, "Java": 320782, "Smarty": 115647, "Shell": 54666, "Groovy": 30254, "PowerShell": 6509, "TypeScript": 5826, "Solidity": 2024} | @file:Suppress("DEPRECATION")
package net.corda.cli.plugins.network
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import net.corda.cli.plugins.common.RestCommand
import net.corda.cli.plugins.packaging.signing.SigningOptions
import net.corda.crypto.cipher.suite.schemes.RSA_TEMPLATE
import net.corda.crypto.core.CryptoConsts.Categories.KeyCategory
import net.corda.crypto.test.certificates.generation.CertificateAuthorityFactory
import net.corda.crypto.test.certificates.generation.toFactoryDefinitions
import net.corda.crypto.test.certificates.generation.toPem
import net.corda.data.certificates.CertificateUsage
import net.corda.libs.configuration.endpoints.v1.ConfigRestResource
import net.corda.libs.configuration.endpoints.v1.types.ConfigSchemaVersion
import net.corda.libs.configuration.endpoints.v1.types.UpdateConfigParameters
import net.corda.libs.cpiupload.endpoints.v1.CpiUploadRestResource
import net.corda.libs.virtualnode.endpoints.v1.VirtualNodeRestResource
import net.corda.libs.virtualnode.endpoints.v1.types.CreateVirtualNodeRequestType.JsonCreateVirtualNodeRequest
import net.corda.membership.rest.v1.CertificatesRestResource
import net.corda.membership.rest.v1.HsmRestResource
import net.corda.membership.rest.v1.KeysRestResource
import net.corda.membership.rest.v1.MemberRegistrationRestResource
import net.corda.membership.rest.v1.NetworkRestResource
import net.corda.membership.rest.v1.types.request.HostedIdentitySessionKeyAndCertificate
import net.corda.membership.rest.v1.types.request.HostedIdentitySetupRequest
import net.corda.membership.rest.v1.types.response.KeyPairIdentifier
import net.corda.rest.json.serialization.JsonObjectAsString
import net.corda.schema.configuration.ConfigKeys.RootConfigKey
import net.corda.sdk.config.ClusterConfig
import net.corda.sdk.network.ClientCertificates
import net.corda.sdk.network.Keys
import net.corda.sdk.network.RegistrationRequester
import net.corda.sdk.network.RegistrationsLookup
import net.corda.sdk.network.VirtualNode
import net.corda.sdk.packaging.CpiUploader
import net.corda.sdk.packaging.KeyStoreHelper
import net.corda.sdk.rest.RestClientUtils.createRestClient
import picocli.CommandLine.Option
import picocli.CommandLine.Parameters
import java.io.File
import java.net.URI
import java.security.KeyStore
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
@Suppress("TooManyFunctions")
abstract class BaseOnboard : Runnable, RestCommand() {
private companion object {
const val P2P_TLS_CERTIFICATE_ALIAS = "p2p-tls-cert"
const val SIGNING_KEY_ALIAS = "signing key 1"
const val SIGNING_KEY_STORE_PASSWORD = "<PASSWORD>"
const val GRADLE_PLUGIN_DEFAULT_KEY_ALIAS = "gradle-plugin-default-key"
}
@Parameters(
description = ["The X500 name of the virtual node."],
arity = "1",
index = "0",
)
lateinit var name: String
@Option(
names = ["--mutual-tls", "-m"],
description = ["Enable mutual TLS"],
)
var mtls: Boolean = false
@Option(
names = ["--tls-certificate-subject", "-c"],
description = [
"The TLS certificate subject. Leave empty to use random certificate subject." +
"Will only be used on the first onboard to the cluster.",
],
)
var tlsCertificateSubject: String? = null
@Option(
names = ["--p2p-gateway-url", "-g"],
description = ["P2P Gateway URL. Multiple URLs may be provided. Defaults to https://localhost:8080."],
)
var p2pGatewayUrls: List<String> = listOf("https://localhost:8080")
protected val json by lazy {
ObjectMapper()
}
private val caHome: File = File(File(File(System.getProperty("user.home")), ".corda"), "ca")
internal class OnboardException(message: String) : Exception(message)
protected fun uploadCpi(cpi: File, cpiName: String): String {
val restClient = createRestClient(
CpiUploadRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
// Cpi upload can take longer than the default 10 seconds, wait for minimum of 30
val longerWaitValue = getLongerWait()
val uploadId = CpiUploader().uploadCPI(restClient, cpi.inputStream(), cpiName, longerWaitValue).id
return checkCpiStatus(uploadId)
}
private fun getLongerWait(): Duration {
return if (waitDurationSeconds.seconds > 30.seconds) {
waitDurationSeconds.seconds
} else {
30.seconds
}
}
private fun checkCpiStatus(id: String): String {
val restClient = createRestClient(
CpiUploadRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
return CpiUploader().cpiChecksum(restClient = restClient, uploadRequestId = id, wait = waitDurationSeconds.seconds)
}
protected abstract val cpiFileChecksum: String
protected abstract val registrationContext: Map<String, String>
protected val holdingId: String by lazy {
val restClient = createRestClient(
VirtualNodeRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val request = JsonCreateVirtualNodeRequest(
x500Name = name,
cpiFileChecksum = cpiFileChecksum,
vaultDdlConnection = null,
vaultDmlConnection = null,
cryptoDdlConnection = null,
cryptoDmlConnection = null,
uniquenessDdlConnection = null,
uniquenessDmlConnection = null,
)
val longerWait = getLongerWait()
val shortHashId = VirtualNode().createAndWaitForActive(restClient, request, longerWait)
println("Holding identity short hash of '$name' is: '$shortHashId'")
shortHashId
}
protected fun assignSoftHsmAndGenerateKey(category: KeyCategory): KeyPairIdentifier {
val hsmRestClient = createRestClient(
HsmRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val keyRestClient = createRestClient(
KeysRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
return Keys().assignSoftHsmAndGenerateKey(
hsmRestClient = hsmRestClient,
keysRestClient = keyRestClient,
holdingIdentityShortHash = holdingId,
category = category,
wait = waitDurationSeconds.seconds
)
}
protected val sessionKeyId by lazy {
assignSoftHsmAndGenerateKey(KeyCategory.SESSION_INIT_KEY)
}
protected val ecdhKeyId by lazy {
assignSoftHsmAndGenerateKey(KeyCategory.PRE_AUTH_KEY)
}
protected val certificateSubject by lazy {
tlsCertificateSubject ?: "O=P2P Certificate, OU=$p2pHosts, L=London, C=GB"
}
private val p2pHosts = extractHostsFromUrls(p2pGatewayUrls)
private fun extractHostsFromUrls(urls: List<String>): List<String> {
return urls.map { extractHostFromUrl(it) }.distinct()
}
private fun extractHostFromUrl(url: String): String {
return URI.create(url).host ?: throw IllegalArgumentException("Invalid URL: $url")
}
protected val ca by lazy {
caHome.parentFile.mkdirs()
CertificateAuthorityFactory
.createFileSystemLocalAuthority(
RSA_TEMPLATE.toFactoryDefinitions(),
caHome,
).also { it.save() }
}
protected fun createTlsKeyIdNeeded() {
val keyRestClient = createRestClient(
KeysRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val keys = Keys()
val hasKeys = keys.hasTlsKey(restClient = keyRestClient, wait = waitDurationSeconds.seconds)
if (hasKeys) return
val tlsKeyId = keys.generateTlsKey(restClient = keyRestClient, wait = waitDurationSeconds.seconds)
val certificateRestClient = createRestClient(
CertificatesRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val clientCertificates = ClientCertificates()
val csrCertRequest = clientCertificates.generateP2pCsr(
certificateRestClient,
tlsKeyId,
certificateSubject,
p2pHosts,
waitDurationSeconds.seconds
)
val certificate = ca.signCsr(csrCertRequest).toPem().byteInputStream()
clientCertificates.uploadTlsCertificate(certificateRestClient, certificate, P2P_TLS_CERTIFICATE_ALIAS, waitDurationSeconds.seconds)
}
protected fun setupNetwork() {
val restClient = createRestClient(
NetworkRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val request = HostedIdentitySetupRequest(
p2pTlsCertificateChainAlias = P2P_TLS_CERTIFICATE_ALIAS,
useClusterLevelTlsCertificateAndKey = true,
sessionKeysAndCertificates = listOf(
HostedIdentitySessionKeyAndCertificate(
sessionKeyId = sessionKeyId.id,
preferred = true,
),
),
)
RegistrationRequester().configureAsNetworkParticipant(
restClient = restClient,
request = request,
holdingId = holdingId,
wait = waitDurationSeconds.seconds
)
}
protected fun register(waitForFinalStatus: Boolean = true) {
val restClient = createRestClient(
MemberRegistrationRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val response = RegistrationRequester().requestRegistration(
restClient = restClient,
registrationContext = registrationContext,
holdingId = holdingId
)
val registrationId = response.registrationId
val submissionStatus = response.registrationStatus
if (submissionStatus != "SUBMITTED") {
throw OnboardException("Could not submit registration request: ${response.memberInfoSubmitted}")
}
println("Registration ID for '$name' is '$registrationId'")
// Registrations can take longer than the default 10 seconds, wait for minimum of 30
val longerWaitValue = getLongerWait()
if (waitForFinalStatus) {
RegistrationsLookup().waitForRegistrationApproval(
restClient = restClient,
registrationId = registrationId,
holdingId = holdingId,
wait = longerWaitValue
)
}
}
protected fun configureGateway() {
val restClient = createRestClient(
ConfigRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val clusterConfig = ClusterConfig()
val currentConfig = clusterConfig.getCurrentConfig(restClient, RootConfigKey.P2P_GATEWAY, waitDurationSeconds.seconds)
val rawConfig = currentConfig.configWithDefaults
val rawConfigJson = json.readTree(rawConfig)
val sslConfig = rawConfigJson["sslConfig"]
val currentMode = sslConfig["revocationCheck"]?.get("mode")?.asText()
val currentTlsType = sslConfig["tlsType"]?.asText()
val tlsType = if (mtls) {
"MUTUAL"
} else {
"ONE_WAY"
}
if ((currentMode != "OFF") || (currentTlsType != tlsType)) {
val objectMapper = ObjectMapper()
val newConfig = objectMapper.createObjectNode()
newConfig.set<ObjectNode>(
"sslConfig",
objectMapper.createObjectNode()
.put("tlsType", tlsType.uppercase())
.set<ObjectNode>(
"revocationCheck",
json.createObjectNode().put("mode", "OFF"),
),
)
val payload = UpdateConfigParameters(
section = "corda.p2p.gateway",
version = currentConfig.version,
config = JsonObjectAsString(objectMapper.writeValueAsString(newConfig)),
schemaVersion = ConfigSchemaVersion(major = currentConfig.schemaVersion.major, minor = currentConfig.schemaVersion.minor),
)
clusterConfig.updateConfig(restClient = restClient, updateConfig = payload, wait = waitDurationSeconds.seconds)
}
}
private val keyStoreFile by lazy {
File(File(File(System.getProperty("user.home")), ".corda"), "signingkeys.pfx")
}
protected fun createDefaultSingingOptions(): SigningOptions {
val options = SigningOptions()
options.keyAlias = SIGNING_KEY_ALIAS
options.keyStorePass = <PASSWORD>
options.keyStoreFileName = keyStoreFile.absolutePath
val keyStoreHelper = KeyStoreHelper()
if (!keyStoreFile.canRead()) {
keyStoreHelper.generateKeyStore(
keyStoreFile = keyStoreFile,
alias = SIGNING_KEY_ALIAS,
password = <PASSWORD>
)
val defaultGradleCert = keyStoreHelper.getDefaultGradleCertificateStream()
KeyStoreHelper().importCertificateIntoKeyStore(
keyStoreFile = keyStoreFile,
keyStorePassword = <PASSWORD>,
certificateInputStream = defaultGradleCert,
certificateAlias = GRADLE_PLUGIN_DEFAULT_KEY_ALIAS,
certificateFactoryType = "X.509"
)
}
return options
}
protected fun uploadSigningCertificates() {
val restClient = createRestClient(
CertificatesRestResource::class,
insecure = insecure,
minimumServerProtocolVersion = minimumServerProtocolVersion,
username = username,
password = <PASSWORD>,
targetUrl = targetUrl
)
val keyStore = KeyStore.getInstance(
keyStoreFile,
SIGNING_KEY_STORE_PASSWORD.toCharArray(),
)
keyStore.getCertificate(GRADLE_PLUGIN_DEFAULT_KEY_ALIAS)
?.toPem()
?.byteInputStream()
?.use { certificate ->
ClientCertificates().uploadCertificate(
restClient = restClient,
certificate = certificate,
usage = CertificateUsage.CODE_SIGNER,
alias = GRADLE_PLUGIN_DEFAULT_KEY_ALIAS,
wait = waitDurationSeconds.seconds
)
}
keyStore.getCertificate(SIGNING_KEY_ALIAS)
?.toPem()
?.byteInputStream()
?.use { certificate ->
ClientCertificates().uploadCertificate(
restClient = restClient,
certificate = certificate,
usage = CertificateUsage.CODE_SIGNER,
alias = "signingkey1-2022",
wait = waitDurationSeconds.seconds
)
}
}
}
| 32 | Kotlin | 25 | 56 | dd139d8da25a3c52ae17ca8d0debc3da4067f158 | 16,673 | corda-runtime-os | Apache License 2.0 |
test-toolkit/unit/src/main/kotlin/com/aoodax/platform/helper/unit/contract/dto/UpdateTagDtoUnitTestHelper.kt | gerasghulyan | 682,102,509 | false | {"Java": 64558, "Kotlin": 41740} | package com.aoodax.platform.helper.unit.contract.dto
import com.aoodax.jvm.common.test.toolkit.Randomizer.Companion.generateRandomString
import com.aoodax.jvm.common.test.toolkit.Randomizer.Companion.generateRandomUid
import com.aoodax.platform.contract.input.tag.dto.UpdateTagDto
class UpdateTagDtoUnitTestHelper {
companion object {
fun buildUpdateTagDto(
uid: String? = generateRandomUid(),
name: String? = generateRandomString()
): UpdateTagDto = UpdateTagDto.builder().uid(uid).name(name).build()
}
} | 1 | null | 1 | 1 | f18bece7c9af4bc64b7257c90b0a6ef1fefc67a8 | 557 | aoodax-clean-architecture | Apache License 2.0 |
src/main/kotlin/me/elgregos/reakteves/infrastructure/projection/ProjectionEntity.kt | GregoryBevan | 414,496,977 | false | {"Gradle Kotlin DSL": 6, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Markdown": 3, "INI": 1, "Java": 4, "Kotlin": 74, "YAML": 3, "XML": 1, "SQL": 2, "SVG": 4} | package me.elgregos.reakteves.infrastructure.projection
import com.fasterxml.jackson.databind.JsonNode
import me.elgregos.reakteves.domain.JsonConvertible
import me.elgregos.reakteves.domain.entity.DomainEntity
import org.springframework.data.annotation.Id
import org.springframework.data.annotation.Transient
import org.springframework.data.domain.Persistable
import java.time.LocalDateTime
import kotlin.reflect.KClass
import kotlin.reflect.full.primaryConstructor
open class ProjectionEntity<DE : DomainEntity<ID, UserID>, ID, UserID>(
@Id private val id: ID,
open val sequenceNum: Long? = null,
open val version: Int,
open val createdAt: LocalDateTime,
open val createdBy: UserID,
open val updatedAt: LocalDateTime,
open val updatedBy: UserID,
open val details: JsonNode
) : Persistable<ID> {
@Transient
private var isNew = false
override fun getId() = id
@Transient
override fun isNew() = isNew
fun markNew() {
isNew = true
}
fun toDomainEntity(type: KClass<DE>) =
JsonConvertible.fromJson(details, type.java)
companion object {
fun <DE : DomainEntity<ID, UserID>, PE : ProjectionEntity<DE, ID, UserID>, ID, UserID> fromDomainEntity(
domainEntity: DE,
projectionEntityClass: KClass<PE>,
sequenceNum: Long? = null,
): PE = projectionEntityClass.primaryConstructor?.call(
domainEntity.id,
sequenceNum,
domainEntity.version,
domainEntity.createdAt,
domainEntity.createdBy,
domainEntity.updatedAt,
domainEntity.updatedBy,
domainEntity.toJson()
) as PE
}
}
| 10 | Kotlin | 0 | 1 | 3281651b5d527269f672be24afed7fdab46c6e54 | 1,710 | event-sourcing-lib | MIT License |
src/main/kotlin/io/repseq/core/VDJCLibraryId.kt | antigenomics | 610,775,690 | true | {"Gradle Kotlin DSL": 2, "Shell": 2, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "Git Config": 1, "Kotlin": 15, "Java": 158, "JSON": 2, "XML": 1, "YAML": 1, "INI": 1} | /*
* Copyright (c) 2022 MiLaboratories 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 io.repseq.core
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import io.repseq.core.IO.VDJCLibraryIdJSONDeserializer
import io.repseq.core.IO.VDJCLibraryIdJSONSerializer
import org.apache.commons.codec.DecoderException
import org.apache.commons.codec.binary.Hex
import java.util.*
/**
* Taxon id and library name and optional library checksum
*/
@JsonSerialize(using = VDJCLibraryIdJSONSerializer::class)
@JsonDeserialize(using = VDJCLibraryIdJSONDeserializer::class)
class VDJCLibraryId @JvmOverloads constructor(
/**
* Library name
*
* @return library name
*/
val libraryName: String,
/**
* Taxon id
*
* @return taxon id
*/
val taxonId: Long,
/**
* Return checksum
*
* @return checksum
*/
val checksum: ByteArray? = null
) : Comparable<VDJCLibraryId> {
/**
* Returns copy of this VDJCLibraryId with checksum set to null
*/
fun withoutChecksum(): VDJCLibraryId = when (checksum) {
null -> this
else -> VDJCLibraryId(libraryName, taxonId, null)
}
/**
* Returns whether this id also contain checksum information
*/
fun requireChecksumCheck(): Boolean = checksum != null
/**
* Return new instance of VDJCLibraryId with different library name
*
* @param newLibraryName new library name
* @return new instance of VDJCLibraryId with different library name
*/
fun setLibraryName(newLibraryName: String): VDJCLibraryId {
return VDJCLibraryId(libraryName = newLibraryName, taxonId = taxonId, checksum = checksum)
}
override fun compareTo(o: VDJCLibraryId): Int {
var c: Int
if (libraryName.compareTo(o.libraryName).also { c = it } != 0) return c
if (taxonId.compareTo(o.taxonId).also { c = it } != 0) return c
if (checksum == null && o.checksum == null) return 0
if (checksum == null) return -1
if (o.checksum == null) return 1
for (i in checksum.indices) if (checksum[i].compareTo(o.checksum[i]).also { c = it } != 0) return c
return 0
}
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o !is VDJCLibraryId) return false
if (taxonId != o.taxonId) return false
return if (libraryName != o.libraryName) false else Arrays.equals(
checksum,
o.checksum
)
}
override fun hashCode(): Int {
var result = libraryName.hashCode()
result = 31 * result + (taxonId xor (taxonId ushr 32)).toInt()
result = 31 * result + Arrays.hashCode(checksum)
return result
}
override fun toString(): String {
return libraryName + ":" + taxonId +
if (checksum == null) "" else ":" + String(Hex.encodeHex(checksum)) + ""
}
companion object {
/**
* Return VDJCLibraryId object from string representation returned by [.toString].
*
* Format:
* `libraryName:taxonId[:checksum]`
*
* @param str string representation
* @return VDJCLibraryId object
* @throws IllegalArgumentException if string has wrong format
*/
@JvmStatic
fun decode(str: String): VDJCLibraryId {
val split = str.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
return if (split.size > 3 || split.size < 2) throw IllegalArgumentException("Wrong string format: $str") else if (split.size == 2) VDJCLibraryId(
split[0], split[1].toLong()
) else try {
VDJCLibraryId(split[0], split[1].toLong(), Hex.decodeHex(split[2].toCharArray()))
} catch (e: DecoderException) {
throw IllegalArgumentException("Wrong string format:$str. Can't decode checksum.")
}
}
}
}
| 0 | null | 0 | 0 | 80f1711ea7c9374edc7b195c53494ed62c7998a1 | 4,559 | repseqio | Apache License 2.0 |
app/src/main/java/com/jooloo/android/mdc/kotlin/shrine/ProductGridItemDecoration.kt | jooloo | 167,384,706 | false | null | package com.jooloo.android.mdc.kotlin.shrine
import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View
/**
* Custom item decoration for a vertical [ProductGridFragment] [RecyclerView]. Adds a small
* amount of padding to the left of grid items, and a large amount of padding to the right.
*/
class ProductGridItemDecoration(private val largePadding: Int, private val smallPadding: Int) :
RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
outRect.apply {
left = smallPadding
right = smallPadding
top = largePadding
bottom = largePadding
}
}
} | 0 | Kotlin | 0 | 0 | 2898ea1a9a5a2ac442f30eb7ee261fe2d2a3d136 | 757 | Shrine | Apache License 2.0 |
src/main/kotlin/com/github/shmvanhouten/adventofcode/day2/BathroomCodeCalculator.kt | SHMvanHouten | 109,886,692 | false | {"Kotlin": 616528} | package com.github.shmvanhouten.adventofcode.day2
class BathroomCodeCalculator (private val finger: Finger){
fun calculateCodeFromInstructions(instructions: List<String>): String {
val stringBuilder = StringBuilder()
for (instructionStep in instructions) {
for (instruction in instructionStep) {
followInstruction(instruction)
}
stringBuilder.append(finger.location)
}
return stringBuilder.toString()
}
private fun followInstruction(instruction: Char) {
when(instruction){
'R' -> finger.moveToTheRight()
'L' -> finger.moveToTheLeft()
'U' -> finger.moveUp()
'D' -> finger.moveDown()
}
}
} | 0 | Kotlin | 0 | 0 | a8abc74816edf7cd63aae81cb856feb776452786 | 754 | adventOfCode2016 | MIT License |
protocol/osrs-223/src/main/kotlin/net/rsprox/protocol/game/outgoing/model/clan/VarClanDisable.kt | blurite | 822,339,098 | false | {"Kotlin": 1453055} | package net.rsprox.protocol.game.outgoing.model.clan
import net.rsprox.protocol.game.outgoing.model.IncomingServerGameMessage
/**
* Var clan disable packet is used to clear out a var domain
* in the client, intended to be sent as the player leaves a clan.
*/
public data object VarClanDisable : IncomingServerGameMessage
| 2 | Kotlin | 4 | 9 | 41535908e6ccb633c8f2564e8961efa771abd6de | 326 | rsprox | MIT License |
app/src/main/java/com/inflames/bloom/screens/loginscreen/LoginScreenViewModel.kt | tolgaprm | 466,419,836 | false | {"Kotlin": 52247} | package com.inflames.bloom.screens.loginscreen
import android.util.Patterns
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
class LoginScreenViewModel : ViewModel() {
private val _loginScreenState = mutableStateOf<LoginViewState>(LoginViewState())
val loginScreenState: State<LoginViewState> get() = _loginScreenState
private val _viewEvents = mutableStateOf<Boolean>(false)
val viewEvents: State<Boolean> get() = _viewEvents
fun onChangeEmail(value: String) {
_loginScreenState.value = _loginScreenState.value.copy(
email = value,
emailAddressError = false
)
}
fun onChangePassword(value: String) {
_loginScreenState.value = _loginScreenState.value.copy(
password = value,
passwordError = false
)
}
fun onLoginClick() {
val isValidEmail = validateEmail()
val isValidPassword = validatePassword()
if (isValidEmail && isValidPassword) {
_viewEvents.value = true
}
}
fun navigatedFinish() {
_viewEvents.value = false
}
private fun validateEmail(): Boolean {
val email = _loginScreenState.value.email
val isValidEmail = Patterns.EMAIL_ADDRESS.matcher(email).matches()
if (isValidEmail.not()) {
_loginScreenState.value = _loginScreenState.value.copy(
emailAddressError = true
)
}
return isValidEmail
}
private fun validatePassword(): Boolean {
val password = _loginScreenState.value.password
val passwordValid = password.length >= 8
if (passwordValid) {
_loginScreenState.value = _loginScreenState.value.copy(
passwordError = false
)
} else {
_loginScreenState.value = _loginScreenState.value.copy(
passwordError = true
)
}
return passwordValid
}
} | 0 | Kotlin | 0 | 0 | 14f156a48e95105828a33bd076239a233a46f751 | 2,043 | Bloom | Apache License 2.0 |
app/src/main/java/com/example/nav/ui/progress/ProgressViewModel.kt | Steelbylss | 801,101,837 | false | {"Kotlin": 151173} | package com.example.nav.ui.progress
import androidx.lifecycle.ViewModel
class ProgressViewModel : ViewModel() {
// TODO: Implement the ViewModel
} | 0 | Kotlin | 0 | 0 | 5921a17ee96d1f682a993c734f0a80866a2a0479 | 152 | codes-unleash-frontend | MIT License |
ParentOnly/src/main/java/com/contoso/nestedscrollingparent/items/PageItem.kt | xingda920813 | 299,796,785 | false | null | package com.contoso.nestedscrollingparent.items
import com.contoso.nestedscrollingparent.ViewType
import com.contoso.nestedscrollingparent.common.AdapterItem
import com.contoso.nestedscrollingparent.model.PageVO
data class PageItem(override val dataModel: List<PageVO>) : AdapterItem<List<PageVO>> {
override val viewType = ViewType.TYPE_PAGER
}
| 0 | Kotlin | 0 | 0 | 7f9d22569f10b625301a9e85f8e8991fcda50078 | 353 | NestedScrolling | MIT License |
app/src/main/java/com/javieramado/centrodeidiomassanmartn/AboutFragment.kt | KamiKeys | 276,455,611 | false | null | package com.javieramado.centrodeidiomassanmartn
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.vansuita.materialabout.builder.AboutBuilder
class AboutFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return AboutBuilder.with(context)
.setPhoto(R.drawable.perfil)
.setCover(R.drawable.bannerdev)
.setName("C. <NAME>")
.setSubTitle("Android Developer")
.setAppIcon(R.mipmap.ic_launcher_round)
.setAppName(R.string.app_name)
.addGitHubLink("KamiKeys")
.addTwitterLink("JavierAmadoM")
.addInstagramLink("javieramadom")
.addLinkedInLink("https://www.linkedin.com/in/javier-miguel-amado/")
.addFiveStarsAction()
.setVersionNameAsAppSubTitle()
.addShareAction(R.string.app_name)
.setWrapScrollView(true)
.setLinksAnimated(true)
.setShowAsCard(true)
.build()
}
} | 0 | Kotlin | 0 | 0 | c1874efa30aee5d2f48fea0fedc6ffdcbb08ae68 | 1,278 | Centro-de-Idiomas-San-Martin | Creative Commons Attribution 4.0 International |
data/src/main/java/com/bottlerocketstudios/brarchitecture/data/network/BitbucketPagedResponse.kt | BottleRocketStudios | 323,985,026 | false | null | package com.bottlerocketstudios.brarchitecture.data.network
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Common wrapper for bitbucket api responses.
* Example api docs showing definitions of below values at https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/src#get
*/
@JsonClass(generateAdapter = true)
internal data class BitbucketPagedResponse<T>(
/** Current number of objects on the existing page. The default value is 10 with 100 being the maximum allowed value. Individual APIs may enforce different values. */
@Json(name = "pagelen") val pageLength: Int = 0,
/** Page number of the current results */
@Json(name = "page") val page: Int = 0,
/** Total number of objects in the response. This is an optional element that is not provided in all responses, as it can be expensive to compute. */
@Json(name = "size") val size: Int = 0,
/** Api result */
@Json(name = "values") val values: T? = null,
/** Link to the next page if it exists */
@Json(name = "next") val next: String? = null,
/**
* Link to previous page if it exists. A collections first page does not have this value. This is an optional element that is not provided in all responses.
* Some result sets strictly support forward navigation and never provide previous links. Clients must anticipate that backwards navigation is not always available.
* Use this link to navigate the result set and refrain from constructing your own URLs.
*/
@Json(name = "previous") val previous: String? = null
)
| 1 | Kotlin | 1 | 9 | e3014001732516e9feab58c862e0d84de9911c83 | 1,625 | Android-ArchitectureDemo | Apache License 2.0 |
ktor-core/src/org/jetbrains/ktor/util/Reflection.kt | hallefy | 94,839,121 | true | {"Kotlin": 1099285, "Java": 61833, "FreeMarker": 6356, "CSS": 5404, "HTML": 1999, "JavaScript": 1451} | package org.jetbrains.ktor.util
import kotlin.reflect.*
import kotlin.reflect.jvm.*
fun KFunction<*>.qualifiedName(): String = javaMethod?.declaringClass?.name + name
| 0 | Kotlin | 0 | 1 | b5dcbe5b740c2d25c7704104e01e0a01bf53d675 | 169 | ktor | Apache License 2.0 |
src/main/kotlin/me/camdenorrb/kspigotbasics/cache/KBasicPlayerCache.kt | camdenorrb | 111,553,094 | false | null | package me.camdenorrb.kspigotbasics.cache
import me.camdenorrb.kspigotbasics.player.KBasicPlayer
import me.camdenorrb.kspigotbasics.struct.server
import me.camdenorrb.kspigotbasics.types.modules.ListeningModule
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
object KBasicPlayerCache : ListeningModule() {
val basicPlayers = mutableMapOf<Player, KBasicPlayer>()
override fun onStart() = server.onlinePlayers.forEach { join(it) }
override fun onStop() = basicPlayers.clear()
fun join(player: Player) {
basicPlayers[player] = KBasicPlayer(player)
}
fun leave(player: Player) {
basicPlayers.remove(player)
}
@EventHandler(ignoreCancelled = true)
fun onJoin(event: PlayerJoinEvent) = join(event.player)
@EventHandler(ignoreCancelled = true)
fun onLeave(event: PlayerQuitEvent) = leave(event.player)
} | 0 | Kotlin | 0 | 2 | 754a361904d368427aa240bbb55a0b36471f4216 | 941 | KSpigotBasics | Apache License 2.0 |
foundation/src/test/kotlin/com/walletconnect/foundation/UtilsTest.kt | WalletConnect | 435,951,419 | false | null | package com.walletconnect.foundation
import com.walletconnect.util.generateId
import com.walletconnect.util.generateClientToServerId
import org.junit.jupiter.api.Test
import kotlin.test.assertTrue
class UtilsTest {
@Test
fun `generate client to client id test`() {
val id = generateId()
println(id)
assertTrue { id > 0 }
assertTrue { id.toString().length == 16 }
}
@Test
fun `generate client to server id test`() {
val id = generateClientToServerId()
println(id)
assertTrue { id > 0 }
assertTrue { id.toString().length == 19 }
}
} | 129 | Kotlin | 50 | 148 | a55e8516e8763b485655e091a091797f75cb461f | 622 | WalletConnectKotlinV2 | Apache License 2.0 |
src/Day03.kt | morris-j | 573,197,835 | false | {"Kotlin": 7085} | fun main() {
fun getRank(value: Char): Int {
if(value.isUpperCase()) {
return value.code - 64 + 26
}
return value.code - 96
}
fun findCommon(first: String, second: String): Char {
first.forEach {
if(second.contains(it)) {
return it
}
}
return 'a'
}
fun findCommonGroup(first: String, second: String, third: String): Char {
first.forEach {
if(second.contains(it) && third.contains(it)) {
return it
}
}
return 'a'
}
fun processInput(input: List<String>): List<Triple<String, String, Char>> {
return input.map {
val mid = it.length / 2
val first = it.substring(0, mid)
val second = it.substring(mid)
val common = findCommon(first, second)
Triple(first, second, common)
}
}
fun processInputGroup(input: List<String>): List<Char> {
return input.chunked(3).map {
findCommonGroup(it[0], it[1], it[2])
}
}
fun part1(input: List<String>): Int {
var sum = 0
val processedInput = processInput(input)
processedInput.forEach {
sum += getRank(it.third)
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
val processedInput = processInputGroup(input)
processedInput.forEach {
sum += getRank(it)
}
return sum
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e3f2d02dad432dbc1b15c9e0eefa7b35ace0e316 | 1,633 | kotlin-advent-of-code-2022 | Apache License 2.0 |
base-kotlin-compiler/src/main/java/com/izikode/izilib/basekotlincompiler/source/enclosure/EnclosureSource.kt | iFanie | 149,670,426 | false | null | package com.izikode.izilib.basekotlincompiler.source.enclosure
import com.izikode.izilib.basekotlincompiler.CompilationUtilities
import com.izikode.izilib.basekotlincompiler.source.AbstractSource
import javax.lang.model.element.PackageElement
class EnclosureSource(
protected val packageElement: PackageElement,
compilationUtilities: CompilationUtilities
) : AbstractSource(packageElement, compilationUtilities) {
val info by lazy { Info(packageElement) }
class Info(private val packageElement: PackageElement) {
val name: String
get() = packageElement.qualifiedName.toString()
}
override fun toString(): String = packageElement.toString()
} | 0 | Kotlin | 0 | 0 | 524a42ba3d339bf75fc5a33e61bb7758451eb0f4 | 703 | BaseKotlinCompiler | Apache License 2.0 |
runtime/src/main/kotlin/konan/internal/Undefined.kt | mano7onam | 122,908,795 | true | {"Kotlin": 4630329, "C++": 803727, "Groovy": 137600, "C": 119742, "Objective-C++": 66838, "Swift": 29084, "JavaScript": 19411, "Shell": 11621, "Batchfile": 7004, "Python": 4775, "Objective-C": 3532, "Pascal": 1698, "Java": 782, "HTML": 185} | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.native.internal
/**
* Returns undefined value of type `T`.
* This method is unsafe and should be used with care.
*/
@SymbolName("Kotlin_native_internal_undefined")
internal external fun <T> undefined(): T | 0 | Kotlin | 0 | 12 | d5169f2370a6b20ae91fc31999fe5ebefcb4344d | 825 | kotlin-native | Apache License 2.0 |
src/main/kotlin/ru/coding4fun/intellij/database/model/property/agent/MsNotifyLevel.kt | scrappyCoco | 201,919,288 | false | null | package ru.coding4fun.intellij.database.model.property.agent
enum class MsNotifyLevel(val id: Byte, val actionDescription: String, val whenDescription: String) {
Success(1, "Quit the job reporting success", "When the job fails"),
Failure(2, "Quit the job reporting failure", "When the job success"),
Completes(3, "Go to the next step", "When the job completed")
} | 0 | Kotlin | 2 | 1 | 1408f2a9229dbdf9ad99966faa5e7a5b74786270 | 367 | SQL-Server-Administration-Tool | Apache License 2.0 |
core/src/main/kotlin/org/eduardoleolim/organizadorpec660/shared/domain/bus/command/CommandHandler.kt | eduardoleolim | 673,214,659 | false | {"Kotlin": 832185, "Shell": 2116} | package org.eduardoleolim.organizadorpec660.shared.domain.bus.command
import org.eduardoleolim.organizadorpec660.shared.domain.Either
interface CommandHandler<L, R, T : Command<L, R>> {
fun handle(command: T): Either<L, R>
}
| 0 | Kotlin | 0 | 0 | 53b907727b83302043a89693c0c825edc91262b3 | 231 | organizador-pec-6-60 | Creative Commons Attribution 4.0 International |
shared/src/commonMain/kotlin/com/juagri/shared/data/local/dao/dealer/DealerLedgerDao.kt | juagrideveloper | 699,804,299 | false | {"Kotlin": 1302992, "Swift": 6001, "Shell": 615} | package com.juagri.shared.data.local.dao.dealer
import com.juagri.shared.DealerDetailsQueries
import com.juagri.shared.domain.model.ledger.DealerLedgerItem
import com.juagri.shared.domain.model.ledger.LedgerItem
import com.juagri.shared.domain.model.ledger.LedgerOpeningBalance
import com.juagri.shared.utils.isDeleted
import com.juagri.shared.utils.toTimeStamp
import com.juagri.shared.utils.toYYYYMMDD
import com.juagri.shared.utils.value
class DealerLedgerDao(private val queries: DealerDetailsQueries) {
fun insertLedger(ledgerItems:List<LedgerItem>){
ledgerItems.forEach {
if(it.status.isDeleted()){
queries.deleteLedger(it.id.value())
}else {
queries.insertLedger(
id = it.id.value(),
post_date = it.postDate.value(),
ccode = it.custCode,
doc_no = it.docNo,
cheque_no = it.chequeNo,
debit_amt = it.debitAmt,
credit_amt = it.creditAmt,
updatedTime = it.updatedTime.value()
)
}
}
}
fun insertOpeningBalance(ledgerItems:List<LedgerOpeningBalance>){
ledgerItems.forEach {
if(it.status.isDeleted()){
queries.deleteOpeningBalance(it.id.value())
}else {
queries.insertOpeningBalance(
id = it.id.value(),
month = it.month.value(),
ccode = it.cCode.value(),
open_balance = it.openingBalance.value(),
updatedTime = it.updatedTime.value()
)
}
}
}
fun getLedgerItems(cCode: String, startDate: Double, endDate: Double): DealerLedgerItem? =
try {
val openingBalance =
queries.getOpeningBalance(cCode, startDate.toTimeStamp().toYYYYMMDD())
.executeAsOne().open_balance.value()
var closingBalance = openingBalance
var debitAmount = 0.0
var creditAmount = 0.0
val ledgerItems =
queries.getLedgerItems(cCode, startDate, endDate).executeAsList().map {
closingBalance = (closingBalance + it.credit_amt.value()) - it.debit_amt.value()
debitAmount = it.debit_amt.value()
creditAmount = it.credit_amt.value()
LedgerItem(
id = it.id.value(),
postDate = it.post_date.toTimeStamp(),
custCode = it.ccode,
docNo = it.doc_no,
chequeNo = it.cheque_no,
debitAmt = it.debit_amt,
creditAmt = it.credit_amt,
balanceAmt = closingBalance,
updatedTime = it.updatedTime.toTimeStamp()
)
}
DealerLedgerItem(
ledgerItems = ledgerItems,
openingBalance = openingBalance,
closingBalance = closingBalance,
totalDebit = debitAmount,
totalCredit = creditAmount
)
}catch (e: Exception) {
null
}
fun getLedgerLastUpdatedTime(cCode: String): Double= queries.getLedgerLastUpdatedTime(cCode).executeAsOne().max.value()
fun getOpeningBalanceLastUpdatedTime(cCode: String): Double= queries.getOpeningBalanceLastUpdatedTime(cCode).executeAsOne().max.value()
} | 0 | Kotlin | 0 | 0 | dfb433421930bbf970fae303f5e496698f9d9e09 | 3,589 | juagriapp | Apache License 2.0 |
src/main/kotlin/main.kt | cubuspl42 | 451,099,116 | false | null | import bia.interpreter.evaluateProgram
import bia.Prelude
import bia.model.asFunctionValue
import bia.parser.parseProgram
import java.lang.IllegalStateException
const val sourceName = "test.bia"
fun main() {
val preludeSource = getResourceAsText("prelude.bia") ?: throw RuntimeException("Couldn't load the prelude")
val prelude = Prelude.load(preludeSource = preludeSource)
val source = getResourceAsText(sourceName) ?: throw RuntimeException("Couldn't load the source file")
val program = parseProgram(
prelude = prelude,
sourceName = sourceName,
source = source,
)
program.validate()
val scope = evaluateProgram(
program = program,
)
val mainValue = scope.getValue("main") ?: throw IllegalStateException("There's no value named main")
val mainFunction = mainValue.asFunctionValue("main is not a function")
val result = mainFunction.call(emptyList())
println("Result: $result")
}
private fun getResourceAsText(path: String): String? =
object {}.javaClass.getResource(path)?.readText()
| 0 | Kotlin | 0 | 4 | 16fef1cc3eba846601f626bcd74b4e8d8407862d | 1,082 | bia | Apache License 2.0 |
plot-builder/src/jvmTest/kotlin/org/jetbrains/letsPlot/core/plot/builder/tooltip/GeomTargetInteractionUnivariateFunctionTest.kt | JetBrains | 176,771,727 | false | {"Kotlin": 7616680, "Python": 1299756, "Shell": 3453, "C": 3039, "JavaScript": 931, "Dockerfile": 94} | /*
* Copyright (c) 2023. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package org.jetbrains.letsPlot.core.plot.builder.tooltip
import org.jetbrains.letsPlot.core.plot.base.Aes
import org.jetbrains.letsPlot.core.plot.builder.tooltip.TestUtil.assertNoTooltips
import org.jetbrains.letsPlot.core.plot.builder.tooltip.TestUtil.assertText
import org.jetbrains.letsPlot.core.plot.builder.tooltip.TestUtil.continuous
import org.jetbrains.letsPlot.core.plot.builder.tooltip.TestUtil.discrete
import kotlin.test.Test
class GeomTargetInteractionUnivariateFunctionTest {
@Test
fun withNoMappings_ShouldAddEmptyTooltipText() {
val targetTooltipSpec = createUnivariateFunctionBuilder(null)
.build()
assertNoTooltips(targetTooltipSpec)
}
@Test
fun whenPositionalXVar_ShouldAddTooltipText() {
val mapping = continuous(Aes.X)
val targetTooltipSpec = createUnivariateFunctionBuilder(mapping.aes)
.variable(mapping)
.build()
assertText(targetTooltipSpec, mapping.shortTooltipText())
}
@Test
fun whenPositionalDiscreteXVar_ShouldAddTooltipText() {
val mapping = discrete(Aes.X)
val targetTooltipSpec = createUnivariateFunctionBuilder(mapping.aes)
.variable(mapping)
.build()
assertText(targetTooltipSpec, mapping.shortTooltipText())
}
@Test
fun whenPositionalYVar_ShouldAddTooltipText() {
val mapping = continuous(Aes.Y)
val targetTooltipSpec = createUnivariateFunctionBuilder(mapping.aes)
.variable(mapping)
.build()
assertText(targetTooltipSpec, mapping.shortTooltipText())
}
@Test
fun whenPositionalDiscreteYVar_ShouldAddTooltipText() {
val mapping = discrete(Aes.Y)
val targetTooltipSpec = createUnivariateFunctionBuilder(mapping.aes)
.variable(mapping)
.build()
assertText(targetTooltipSpec, mapping.shortTooltipText())
}
@Test
fun whenWidthVar_ShouldAddTooltipText() {
val mapping = continuous(Aes.WIDTH)
val targetTooltipSpec = createUnivariateFunctionBuilder(mapping.aes)
.variable(mapping)
.build()
assertText(targetTooltipSpec, mapping.longTooltipText())
}
@Test
fun whenDiscreteWidthVar_ShouldAddTooltipText() {
val mapping = discrete(Aes.WIDTH)
val targetTooltipSpec = createUnivariateFunctionBuilder(mapping.aes)
.variable(mapping)
.build()
assertText(targetTooltipSpec, mapping.longTooltipText())
}
private fun createUnivariateFunctionBuilder(displayableAes: Aes<*>?): TestingTooltipSpecsBuilder {
return TestingTooltipSpecsBuilder.univariateFunctionBuilder(
listOfNotNull(displayableAes)
)
}
}
| 150 | Kotlin | 51 | 1,561 | c8db300544974ddd35a82a90072772b788600ac6 | 2,919 | lets-plot | MIT License |
src/main/kotlin/io/github/gaming32/mckt/commands/arguments/typeExtensions.kt | mckt-Minecraft | 532,076,162 | false | null | package io.github.gaming32.mckt.commands.arguments
import com.mojang.brigadier.arguments.IntegerArgumentType
import com.mojang.brigadier.arguments.LongArgumentType
import com.mojang.brigadier.arguments.StringArgumentType
import com.mojang.brigadier.context.CommandContext
fun CommandContext<*>.getString(name: String) = StringArgumentType.getString(this, name)!!
fun CommandContext<*>.getInt(name: String) = IntegerArgumentType.getInteger(this, name)
fun CommandContext<*>.getLong(name: String) = LongArgumentType.getLong(this, name)
| 0 | Kotlin | 0 | 2 | 98e88af4f54a12faeea2543c4bbdc950dd744092 | 536 | mckt | MIT License |
sample/src/main/java/eu/kevin/sample/samples/accountlinking/AccountLinkingUiState.kt | getkevin | 375,151,388 | false | {"Kotlin": 238202} | package eu.kevin.sample.samples.accountlinking
internal data class AccountLinkingUiState(
val isLoading: Boolean = false,
val accountLinkingState: String? = null,
val userMessage: String? = null
) | 0 | Kotlin | 2 | 7 | b18fb946b900a0db5632bd81db620d2153603d14 | 209 | kevin-android | MIT License |
app/src/main/java/com/memorya/framework/room/entities/UserEntity.kt | matteofabris | 347,469,835 | false | null | package com.memorya.framework.room.entities
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.memorya.domain.User
@Entity(tableName = "user")
data class UserEntity(
@PrimaryKey(autoGenerate = true)
override val id: Int,
@ColumnInfo(name = "user_id")
override var userId: String
) : User {
constructor (userId: String) : this(0, userId)
constructor (user: User) : this(user.id, user.userId)
} | 0 | Kotlin | 0 | 0 | 729555be7398007dbab49fd1a53d599e4346dcc9 | 471 | WordsMemory | MIT License |
domain/src/main/java/com/begines/chistian/domain/models/ui/WorkerUiModel.kt | christianbegines | 544,189,847 | false | {"Kotlin": 29231} | package com.begines.chistian.domain.models.ui
data class WorkerUiModel(
var firstName: String,
var lastName: String,
var favorite: FavoriteUiModel,
var gender: String,
var image: String,
var profession: String,
var email: String,
var age: Int,
var country: String,
var height: Int,
var id: Int,
var quote: String?,
var description: String?
)
| 0 | Kotlin | 0 | 0 | b5fdbf58c036b83f81c35320c9ab21803e4779bd | 395 | WonkaManagementJetpackComposeMVVMHilt | Apache License 2.0 |
layer_presentation/src/main/java/dev/eastar/main/MultiFr.kt | teamtuna | 355,517,555 | true | {"Kotlin": 69325, "Batchfile": 117} | package dev.eastar.main
import android.log.Log
import android.log.LogFragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
import dev.eastar.ktx.alert
import dev.eastar.ktx.hideKeyboard
import dev.eastar.ktx.negativeButton
import dev.eastar.ktx.positiveButton
import dev.eastar.presentation.databinding.MultiFrBinding
@AndroidEntryPoint
class MultiFr : LogFragment() {
private lateinit var bb: MultiFrBinding
private val viewModel: MultiViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
bb = MultiFrBinding.inflate(inflater, container, false)
bb.viewmodel = viewModel
bb.lifecycleOwner = this
return bb.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// viewModel.signumTest(1)
onLoadOnce()
}
private fun onLoadOnce() {
viewModel.memberInput.observe(viewLifecycleOwner) {
alert("참가자를 입력해주세요") {
val edit = EditText(context)
setView(edit)
positiveButton("OK") {
viewModel.setMembers(edit.text.toString())
}
negativeButton("CANCEL") {
parentFragmentManager.popBackStack()
}
}
}
viewModel.members1Player.observe(viewLifecycleOwner) {
alert(it) {
positiveButton("OK")
}
}
viewModel.gameEnd.observe(viewLifecycleOwner) {
hideKeyboard()
alert(it) {
positiveButton("OK")
setOnDismissListener { parentFragmentManager.popBackStack() }
}
}
bb.tryingNumber.setOnEditorActionListener { v, actionId, event ->
Log.e(v, actionId, event)
viewModel.tryNumber()
bb.tryingNumber.setSelection(0, bb.tryingNumber.text.toString().length)
true
}
}
} | 0 | Kotlin | 2 | 1 | d35524312179bb9b8c85be7c63ba84e31a8fbb6e | 2,278 | NumberQuiz | Apache License 2.0 |
app/src/main/java/com/flurry/android/sample/marketing/di/module/NetworkModule.kt | flurry | 471,077,299 | false | {"Kotlin": 19953} | package com.flurry.android.sample.marketing.di.module
import com.flurry.android.sample.marketing.api.service.FcmPushService
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
class NetworkModule {
@Singleton
@Provides
fun provideFcmPushService(): FcmPushService {
val client = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.connectTimeout(CLIENT_TIME_OUT_SECS, TimeUnit.SECONDS)
.writeTimeout(CLIENT_TIME_OUT_SECS, TimeUnit.SECONDS)
.readTimeout(CLIENT_TIME_OUT_SECS, TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build()
return retrofit.create(FcmPushService::class.java)
}
companion object {
private const val BASE_URL = "https://fcm.googleapis.com"
private const val CLIENT_TIME_OUT_SECS = 60L
}
} | 0 | Kotlin | 1 | 0 | c2f9494907997244c75f6d97f7a81f71470de723 | 1,395 | FlurryMarketingSampleApp-Android | Apache License 2.0 |
sample/src/main/java/ru/haroncode/aquarius/utils/DisplayExtensions.kt | HaronCode | 296,919,440 | false | null | package ru.haroncode.aquarius.utils
import android.content.res.Resources
val Int.dp: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt() | 0 | Kotlin | 0 | 4 | 5ec7e67f6559e057eb7227e485438f03d3cb334f | 164 | Aquarius | The Unlicense |
forge/src/main/kotlin/com/ciarandg/soundbounds/forge/client/ForgeClientEvents.kt | ciarandg | 369,932,695 | false | {"Kotlin": 186812} | package com.ciarandg.soundbounds.forge.client
import com.ciarandg.soundbounds.client.audio.GameMusicVolume
import com.ciarandg.soundbounds.client.regions.ClientWorldRegions
import com.ciarandg.soundbounds.client.render.MarkerSelectionRenderer
import com.ciarandg.soundbounds.client.render.RegionVisualizationRenderer
import com.ciarandg.soundbounds.client.ui.ClientPlayerModel
import com.ciarandg.soundbounds.forge.common.item.Baton
import me.shedaniel.architectury.utils.GameInstance
import net.minecraft.client.MinecraftClient
import net.minecraft.client.gui.screen.options.SoundOptionsScreen
import net.minecraft.sound.SoundCategory
import net.minecraftforge.client.event.GuiScreenEvent
import net.minecraftforge.client.event.RenderWorldLastEvent
import net.minecraftforge.client.event.sound.PlaySoundEvent
import net.minecraftforge.eventbus.api.SubscribeEvent
class ForgeClientEvents {
@SubscribeEvent
fun disableVanillaMusic(event: PlaySoundEvent) {
// menu music doesn't trigger PlaySoundEvent for some reason, but it works in-game
if (event.sound.category == SoundCategory.MUSIC)
event.resultSound = null
}
@SubscribeEvent
fun updateGameMusicVolume(event: GuiScreenEvent) {
if (GameInstance.getClient().currentScreen is SoundOptionsScreen)
GameMusicVolume.update()
}
@SubscribeEvent
fun render(event: RenderWorldLastEvent) {
val player = MinecraftClient.getInstance().player ?: return
if (!player.itemsHand.any { it.item is Baton }) return
// Offset by camera position, since it is reset by RenderWorldLastEvent
val matrixStack = event.matrixStack
val cameraPos = MinecraftClient.getInstance().gameRenderer.camera.pos
matrixStack.translate(-cameraPos.x, -cameraPos.y, -cameraPos.z)
// Render player's bounds selection
MarkerSelectionRenderer.renderPlayerMarkerSelection(matrixStack)
// Render region visualization
val visualizationRegion = ClientWorldRegions[ClientPlayerModel.visualizationRegion]
if (visualizationRegion == null) ClientPlayerModel.visualizationRegion = null
else RegionVisualizationRenderer.renderRegionVisualization(matrixStack, visualizationRegion)
}
} | 4 | Kotlin | 0 | 0 | 0702d75981c0799d180bc2cf648b7dba392d2268 | 2,266 | SoundBounds | MIT License |
app/src/main/java/com/personal/tmdb/core/di/RepositoryModule.kt | Avvami | 755,489,313 | false | {"Kotlin": 656155} | package com.personal.tmdb.core.di
import com.personal.tmdb.core.data.repository.LocalCacheImpl
import com.personal.tmdb.core.data.repository.LocalRepositoryImpl
import com.personal.tmdb.core.domain.repository.LocalCache
import com.personal.tmdb.core.domain.repository.LocalRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds
@Singleton
abstract fun bindLocalRepository(
localRepositoryImpl: LocalRepositoryImpl
): LocalRepository
@Binds
@Singleton
abstract fun bindLocalCache(
localCacheImpl: LocalCacheImpl
): LocalCache
} | 0 | Kotlin | 0 | 2 | d5b4d2ee9eb9616ab0e217f8d6fff45723bf5e58 | 770 | TMDB | MIT License |
src/main/kotlin/org/jaqpot/api/entity/ModelOrganizationAssociationType.kt | ntua-unit-of-control-and-informatics | 790,773,279 | false | {"Kotlin": 176168, "FreeMarker": 2174} | package org.jaqpot.api.entity
import java.io.Serializable
enum class ModelOrganizationAssociationType : Serializable {
AFFILIATION, SHARE
}
| 0 | Kotlin | 0 | 0 | 5707aed75155d3955865b68f6b5678c451b0cd93 | 146 | jaqpot-api | MIT License |
cloud/nurupoga-common-dependency/src/main/kotlin/cn/enaium/nurupoga/mapper/PostMapper.kt | Enaium-Archive | 614,270,450 | false | null | /*
* Copyright (c) 2023 Enaium
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package cn.enaium.nurupoga.mapper
import cn.enaium.nurupoga.model.entity.PostEntity
import cn.enaium.nurupoga.model.entity.TagEntity
import com.baomidou.mybatisplus.core.conditions.Wrapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import com.baomidou.mybatisplus.core.metadata.IPage
import com.baomidou.mybatisplus.core.toolkit.Constants
import org.apache.ibatis.annotations.Mapper
import org.apache.ibatis.annotations.Param
import org.apache.ibatis.annotations.Select
@Mapper
interface PostMapper : BaseMapper<PostEntity> {
@Select(
"""
select *
from (select table_post.*, tpa.create_time as answered_time
from table_post
left join table_post_answer tpa on table_post.id = tpa.post_id) as t ${"$"}{ew.customSqlSegment}
"""
)
fun selectNoTag(
page: IPage<Map<String, Any>>,
@Param(Constants.WRAPPER) wrapper: Wrapper<Map<String, Any>>
): IPage<PostEntity>
@Select(
"""
select *
from (select table_post.*, tt.id as tag_id, tt.name as tag_name, tpa.create_time as answered_time
from table_post
left join table_post_answer tpa on table_post.id = tpa.post_id
left join table_post_tag tpt on table_post.id = tpt.post_id
left join table_tag tt on tpt.tag_id = tt.id) as t ${"$"}{ew.customSqlSegment}
"""
)
fun selectHasTag(
page: IPage<Map<String, Any>>,
@Param(Constants.WRAPPER) wrapper: Wrapper<Map<String, Any>>
): IPage<PostEntity>
@Select(
"""
select t.*
from table_post_tag pt
left join table_post p on pt.post_id = p.id
left join table_tag t on pt.tag_id = t.id
where p.id = #{postId}
""")
fun selectAllTag(postId: Long): List<TagEntity>
} | 0 | Kotlin | 0 | 2 | 68e4f244ff3242f34e5ee30009ce5061b6ac076d | 2,995 | nurupoga | MIT License |
src/main/kotlin/16.kts | reitzig | 318,492,753 | false | null | import java.io.File
data class Rule(val name: String, val ranges: List<IntRange>) {
fun admits(value: Int): Boolean =
ranges.any { it.contains(value) }
companion object {
operator fun invoke(ruleLine: String): Rule {
val (name, rangesString) = ruleLine.split(":")
val ranges = rangesString
.split("or")
.map { rangeString ->
rangeString.split("-")
.map { it.trim().toInt() }
.let { IntRange(it[0], it[1]) }
}
return Rule(name, ranges)
}
}
}
data class Ticket(val fields: List<Int>) {
companion object {
operator fun invoke(ticketLine: String): Ticket =
ticketLine
.split(",")
.map { it.toInt() }
.let { Ticket(it) }
}
}
fun possibleRulesForField(fieldIndex: Int, tickets: List<Ticket>, rules: List<Rule>): List<Rule> =
rules.filter { rule ->
tickets.all { ticket ->
rule.admits(ticket.fields[fieldIndex])
}
}
fun disambiguateRuleAssignments(possibleRules: List<Pair<Int, List<Rule>>>): Map<Int, Rule> {
fun disambiguate(possibleAssignments: List<Pair<Int, List<Rule>>>): List<Pair<Int, List<Rule>>> =
when (possibleAssignments.size) {
0 -> listOf()
else -> {
val agreedAssignments = possibleAssignments
.filter { (_, rules) -> rules.size == 1 }
val agreedRules = agreedAssignments
.flatMap { it.second }
.distinct()
agreedAssignments +
possibleAssignments.subtract(agreedAssignments)
.map { (fieldIndex, rules) ->
Pair(fieldIndex, rules.subtract(agreedRules).toList())
}
.let { disambiguate(it) }
}
}
return disambiguate(possibleRules)
.map { (fieldIndex, rules) ->
Pair(fieldIndex, rules.first())
}
.toMap()
}
val input = File(args[0]).readLines()
val rules = input
.takeWhile { it.isNotBlank() }
.map { Rule(it) }
val myTicket = input
.dropWhile { it.trim() != "your ticket:" }
.drop(1)
.first()
.let { Ticket(it) }
val nearbyTickets = input
.dropWhile { it.trim() != "nearby tickets:" }
.drop(1)
.map { Ticket(it) }
// Part 1:
nearbyTickets
.flatMap { ticket ->
ticket.fields.filterNot { value ->
rules.any { it.admits(value) }
}
}
.sum()
.let { println(it) }
// Part 2:
val validTickets = nearbyTickets
.filter { ticket ->
ticket.fields.all { value ->
rules.any { it.admits(value) }
}
}
(0..validTickets.first().fields.lastIndex)
.map { Pair(it, possibleRulesForField(it, validTickets, rules)) }
.let { disambiguateRuleAssignments(it) }
.filter { (_, rule) -> rule.name.startsWith("departure") }
.map { (fieldIndex, _) -> myTicket.fields[fieldIndex] }
.fold(1L, Long::times)
.let { println(it) } | 0 | Kotlin | 0 | 0 | f17184fe55dfe06ac8897c2ecfe329a1efbf6a09 | 3,194 | advent-of-code-2020 | The Unlicense |
korim/src/commonMain/kotlin/com/soywiz/korim/font/FontOrigin.kt | dandanx | 257,100,686 | true | {"Kotlin": 606339, "C": 13764, "Shell": 1701, "Batchfile": 1531} | package com.soywiz.korim.font
enum class FontOrigin {
TOP, BASELINE
}
| 0 | Kotlin | 0 | 0 | 43d2591c7136545d6ad61fea4ee73ea82c04a2cf | 75 | korim | Apache License 2.0 |
sdk/src/main/java/com/exponea/sdk/manager/InAppMessageManagerImpl.kt | exponea | 134,699,893 | false | null | package com.exponea.sdk.manager
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.os.Looper
import com.exponea.sdk.Exponea
import com.exponea.sdk.models.Constants
import com.exponea.sdk.models.DeviceProperties
import com.exponea.sdk.models.EventType
import com.exponea.sdk.models.ExponeaConfiguration
import com.exponea.sdk.models.InAppMessage
import com.exponea.sdk.models.InAppMessageButtonType
import com.exponea.sdk.models.InAppMessagePayloadButton
import com.exponea.sdk.repository.CustomerIdsRepository
import com.exponea.sdk.repository.InAppMessageBitmapCache
import com.exponea.sdk.repository.InAppMessageDisplayStateRepository
import com.exponea.sdk.repository.InAppMessagesCache
import com.exponea.sdk.util.Logger
import com.exponea.sdk.util.logOnException
import com.exponea.sdk.view.InAppMessagePresenter
import java.util.Date
import java.util.concurrent.atomic.AtomicInteger
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
internal data class InAppMessageShowRequest(
val eventType: String,
val properties: Map<String, Any?>,
val timestamp: Double?,
val trackingDelegate: InAppMessageTrackingDelegate,
val requestedAt: Long
)
internal class InAppMessageManagerImpl(
private val configuration: ExponeaConfiguration,
private val customerIdsRepository: CustomerIdsRepository,
private val inAppMessagesCache: InAppMessagesCache,
private val fetchManager: FetchManager,
private val displayStateRepository: InAppMessageDisplayStateRepository,
private val bitmapCache: InAppMessageBitmapCache,
private val presenter: InAppMessagePresenter
) : InAppMessageManager {
companion object {
const val REFRESH_CACHE_AFTER = 1000 * 60 * 30 // when session is started and cache is older than this, refresh
const val MAX_PENDING_MESSAGE_AGE = 1000 * 3 // time window to show pending message after preloading
}
private var preloaded = false
private var preloadInProgress = false
private var pendingShowRequests: List<InAppMessageShowRequest> = arrayListOf()
private var sessionStartDate = Date()
@Synchronized
override fun preloadIfNeeded(timestamp: Double) {
if (shouldPreload(timestamp)) {
preloadStarted()
preload()
}
}
override fun preload(callback: ((Result<Unit>) -> Unit)?) {
fetchManager.fetchInAppMessages(
exponeaProject = configuration.mainExponeaProject,
customerIds = customerIdsRepository.get(),
onSuccess = { result ->
inAppMessagesCache.set(result.results)
Logger.i(this, "In-app messages preloaded successfully, preloading images.")
preloadImageAndShowPending(result.results, callback)
},
onFailure = {
Logger.e(this, "Preloading in-app messages failed. ${it.results.message}")
preloadFinished()
showPendingMessage()
callback?.invoke(Result.failure(Exception("Preloading in-app messages failed.")))
}
)
}
private fun preloadStarted() {
preloaded = false
preloadInProgress = true
}
private fun preloadFinished() {
preloaded = true
preloadInProgress = false
}
private fun shouldPreload(timestamp: Double): Boolean {
if (preloadInProgress) {
return false
}
return !preloaded || inAppMessagesCache.getTimestamp() + REFRESH_CACHE_AFTER < timestamp
}
override fun sessionStarted(sessionStartDate: Date) {
this.sessionStartDate = sessionStartDate
}
private fun preloadImageAndShowPending(
messages: List<InAppMessage>,
callback: ((Result<Unit>) -> Unit)?
) = runCatching {
bitmapCache.clearExcept(
messages.mapNotNull { it.payload }
.mapNotNull { it.imageUrl }
.filter { it.isNotBlank() }
)
var shouldWaitWithPreload = false
if (pendingShowRequests.isNotEmpty()) {
Logger.i(this, "Attempt to show pending in-app message before loading all images.")
val message = pickPendingMessage(false)
if (message != null) {
val imageUrl = message.second.payload?.imageUrl
if (imageUrl.isNullOrEmpty()) {
showPendingMessage(message)
} else {
shouldWaitWithPreload = true
Logger.i(this, "First preload pending in-app message image, load rest later.")
bitmapCache.preload(imageUrl) {
showPendingMessage(message)
preloadImagesAfterPendingShown(messages.filter { it != message.second }, callback)
}
}
}
}
if (!shouldWaitWithPreload) {
preloadImagesAfterPendingShown(messages, callback)
}
}.logOnException()
private fun preloadImagesAfterPendingShown(
messages: List<InAppMessage>,
callback: ((Result<Unit>) -> Unit)?
) = runCatching {
val onPreloaded = {
preloadFinished()
showPendingMessage()
Logger.i(this, "All in-app message images loaded.")
callback?.invoke(Result.success(Unit))
}
var toPreload = AtomicInteger(messages.size)
messages.forEach {
val imageUrl = it.payload?.imageUrl
if (!imageUrl.isNullOrEmpty()) {
bitmapCache.preload(imageUrl) {
toPreload.getAndDecrement()
if (toPreload.get() == 0) {
onPreloaded()
}
}
} else {
toPreload.getAndDecrement()
}
}
if (toPreload.get() == 0) {
onPreloaded()
}
}.logOnException()
private fun pickPendingMessage(requireImageLoaded: Boolean): Pair<InAppMessageShowRequest, InAppMessage>? {
var pendingMessages: List<Pair<InAppMessageShowRequest, InAppMessage>> = arrayListOf()
pendingShowRequests
.filter { it.requestedAt + MAX_PENDING_MESSAGE_AGE > System.currentTimeMillis() }
.forEach { request ->
getFilteredMessages(request.eventType, request.properties, request.timestamp, requireImageLoaded)
.forEach { message ->
pendingMessages += request to message
}
}
val highestPriority = pendingMessages.mapNotNull { it.second.priority }.max() ?: 0
pendingMessages = pendingMessages.filter { it.second.priority ?: 0 >= highestPriority }
return if (pendingMessages.isNotEmpty()) pendingMessages.random() else null
}
private fun showPendingMessage(pickedMessage: Pair<InAppMessageShowRequest, InAppMessage>? = null) {
val message = pickedMessage ?: pickPendingMessage(true)
if (message != null) {
show(message.second, message.first.trackingDelegate)
}
pendingShowRequests = arrayListOf()
}
private fun hasImageFor(message: InAppMessage): Boolean {
val imageUrl = message.payload?.imageUrl
val result = imageUrl.isNullOrEmpty() || bitmapCache.has(imageUrl)
if (!result) {
Logger.i(this, "Image not available for ${message.name}")
}
return result
}
override fun getFilteredMessages(
eventType: String,
properties: Map<String, Any?>,
timestamp: Double?,
requireImageLoaded: Boolean
): List<InAppMessage> {
var messages = inAppMessagesCache.get()
Logger.i(
this,
"Picking in-app message for eventType $eventType. " +
"${messages.size} messages available: ${messages.map { it.name } }."
)
messages = messages.filter {
(!requireImageLoaded || hasImageFor(it)) &&
it.applyDateFilter(System.currentTimeMillis() / 1000) &&
it.applyEventFilter(eventType, properties, timestamp) &&
it.applyFrequencyFilter(displayStateRepository.get(it), sessionStartDate)
}
Logger.i(this, "${messages.size} messages available after filtering. Picking highest priority message.")
val highestPriority = messages.mapNotNull { it.priority }.max() ?: 0
messages = messages.filter { it.priority ?: 0 >= highestPriority }
Logger.i(this, "Got ${messages.size} messages with highest priority. ${messages.map { it.name } }")
return messages
}
override fun getRandom(
eventType: String,
properties: Map<String, Any?>,
timestamp: Double?,
requireImageLoaded: Boolean
): InAppMessage? {
val messages = getFilteredMessages(eventType, properties, timestamp, requireImageLoaded)
if (messages.size > 1) {
Logger.i(this, "Multiple candidate messages found, picking at random.")
}
return if (messages.isNotEmpty()) messages.random() else null
}
override fun showRandom(
eventType: String,
properties: Map<String, Any?>,
timestamp: Double?,
trackingDelegate: InAppMessageTrackingDelegate
): Job? {
Logger.i(this, "Requesting to show in-app message for event type $eventType")
if (preloaded) {
return GlobalScope.launch {
Logger.i(this, "In-app message data preloaded, picking a message to display")
val message = getRandom(eventType, properties, timestamp)
if (message != null) {
show(message, trackingDelegate)
}
}
} else {
Logger.i(this, "Add pending in-app message to be shown after data is loaded")
pendingShowRequests += InAppMessageShowRequest(
eventType,
properties,
timestamp,
trackingDelegate,
System.currentTimeMillis()
)
return null
}
}
private fun show(message: InAppMessage, trackingDelegate: InAppMessageTrackingDelegate) {
if (message.variantId == -1 && message.payload == null) {
Logger.i(this, "Only logging in-app message for control group '${message.name}'")
trackShowEvent(message, trackingDelegate)
return
}
if (message.payload == null) {
Logger.i(this, "Not showing message with empty payload '${message.name}'")
return
}
Logger.i(this, "Attempting to show in-app message '${message.name}'")
val imageUrl = message.payload.imageUrl
val bitmap = if (!imageUrl.isNullOrBlank())
bitmapCache.get(imageUrl) ?: return
else null
Logger.i(this, "Posting show to main thread with delay ${message.delay ?: 0}ms.")
Handler(Looper.getMainLooper()).postDelayed(
{
val presented = presenter.show(
messageType = message.messageType,
payload = message.payload,
image = bitmap,
timeout = message.timeout,
actionCallback = { activity, button ->
displayStateRepository.setInteracted(message, Date())
trackingDelegate.track(message, "click", true, button.buttonText)
Logger.i(this, "In-app message button clicked!")
processInAppMessageAction(activity, button)
},
dismissedCallback = {
trackingDelegate.track(message, "close", false)
}
)
if (presented != null) {
trackShowEvent(message, trackingDelegate)
}
},
message.delay ?: 0
)
}
private fun trackShowEvent(message: InAppMessage, trackingDelegate: InAppMessageTrackingDelegate) {
displayStateRepository.setDisplayed(message, Date())
trackingDelegate.track(message, "show", false)
Exponea.telemetry?.reportEvent(
com.exponea.sdk.telemetry.model.EventType.SHOW_IN_APP_MESSAGE,
hashMapOf("messageType" to message.rawMessageType)
)
}
private fun processInAppMessageAction(activity: Activity, button: InAppMessagePayloadButton) {
if (button.buttonType == InAppMessageButtonType.DEEPLINK) {
try {
activity.startActivity(
Intent(Intent.ACTION_VIEW).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
data = Uri.parse(button.buttonLink)
}
)
} catch (e: ActivityNotFoundException) {
Logger.e(this, "Unable to perform deeplink", e)
}
}
}
}
internal class EventManagerInAppMessageTrackingDelegate(
context: Context,
private val eventManager: EventManager
) : InAppMessageTrackingDelegate {
private val deviceProperties = DeviceProperties(context)
override fun track(message: InAppMessage, action: String, interaction: Boolean, text: String?) {
val properties = hashMapOf(
"action" to action,
"banner_id" to message.id,
"banner_name" to message.name,
"banner_type" to message.messageType,
"interaction" to interaction,
"os" to "Android",
"type" to "in-app message",
"variant_id" to message.variantId,
"variant_name" to message.variantName
)
properties.putAll(deviceProperties.toHashMap())
if (text != null) {
properties["text"] = text
}
eventManager.track(
eventType = Constants.EventTypes.banner,
properties = properties,
type = EventType.BANNER
)
}
}
| 5 | null | 17 | 11 | 04a1f9ecc84501b95f314aa15e98e7a246c673ce | 14,246 | exponea-android-sdk | Apache License 2.0 |
app/src/main/java/org/hierax/hsaplanner/balance/BalanceRecyclerViewAdapter.kt | halcyon22 | 355,036,648 | false | null | package org.hierax.hsaplanner.balance
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import org.hierax.hsaplanner.R
import org.hierax.hsaplanner.balance.BalanceLine.Companion.CONTRIBUTION
import org.hierax.hsaplanner.balance.BalanceLine.Companion.REIMBURSEMENT
import org.hierax.hsaplanner.balance.BalanceLine.Companion.STARTING_BALANCE
import org.hierax.hsaplanner.balance.ContributionBalanceLine.Companion.EMPLOYER
import org.hierax.hsaplanner.balance.ContributionBalanceLine.Companion.PERSONAL
import java.text.NumberFormat
import java.time.format.DateTimeFormatter
class BalanceRecyclerViewAdapter(
private val lines: List<BalanceLine>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
// TODO MDP add click handler for starting balance, reimbursement lines
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
STARTING_BALANCE -> {
val itemLayout = LayoutInflater.from(parent.context)
.inflate(R.layout.starting_balance_line, parent, false)
StartingBalanceLineViewHolder(itemLayout)
}
CONTRIBUTION -> {
val itemLayout = LayoutInflater.from(parent.context)
.inflate(R.layout.contribution_line, parent, false)
ContributionLineViewHolder(itemLayout)
}
REIMBURSEMENT -> {
val itemLayout = LayoutInflater.from(parent.context)
.inflate(R.layout.reimbursement_balance_line, parent, false)
ReimbursementLineViewHolder(itemLayout)
}
else -> {
throw IllegalArgumentException("Unknown viewType value: $viewType")
}
}
}
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
when (lines[position].getViewType()) {
STARTING_BALANCE -> {
val it = viewHolder as StartingBalanceLineViewHolder
val balanceLine = lines[position] as StartingBalanceLine
it.updateContent(balanceLine)
}
CONTRIBUTION -> {
val contributionLine = lines[position] as ContributionBalanceLine
val it = viewHolder as ContributionLineViewHolder
it.updateContent(contributionLine)
}
REIMBURSEMENT -> {
val reimbursementLine = lines[position] as ReimbursementBalanceLine
val it = viewHolder as ReimbursementLineViewHolder
it.updateContent(reimbursementLine)
}
else -> {
throw IllegalArgumentException("Unknown viewType value: ${lines[position].getViewType()}")
}
}
}
override fun getItemViewType(position: Int): Int {
return lines[position].getViewType()
}
override fun getItemCount(): Int {
return lines.size
}
class StartingBalanceLineViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val dateView: TextView = itemView.findViewById(R.id.date)
private val descriptionView: TextView = itemView.findViewById(R.id.description)
private val balanceView: TextView = itemView.findViewById(R.id.balance)
fun updateContent(startingBalanceLine: StartingBalanceLine) {
dateView.text = dateFormatter.format(startingBalanceLine.date)
descriptionView.text = itemView.context.getString(R.string.starting_balance)
balanceView.text = NumberFormat.getCurrencyInstance().format(startingBalanceLine.balance)
}
}
class ContributionLineViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val dateView: TextView = itemView.findViewById(R.id.date)
private val descriptionView: TextView = itemView.findViewById(R.id.description)
private val balanceView: TextView = itemView.findViewById(R.id.balance)
fun updateContent(contributionLine: ContributionBalanceLine) {
val formattedAmount = NumberFormat.getCurrencyInstance().format(contributionLine.amount)
dateView.text = dateFormatter.format(contributionLine.date)
descriptionView.text = when (contributionLine.source) {
PERSONAL -> itemView.context.getString(R.string.personal_contribution, formattedAmount)
EMPLOYER -> itemView.context.getString(R.string.employer_contribution, formattedAmount)
else -> {
throw IllegalArgumentException("Unknown contribution source: ${contributionLine.source}")
}
}
balanceView.text = NumberFormat.getCurrencyInstance().format(contributionLine.balance)
}
}
class ReimbursementLineViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val descriptionView: TextView = itemView.findViewById(R.id.description)
private val balanceView: TextView = itemView.findViewById(R.id.balance)
private val expenseDescriptionView: TextView = itemView.findViewById(R.id.expense_description)
private val expenseAmountView: TextView = itemView.findViewById(R.id.expense_amounts)
fun updateContent(reimbursementLine: ReimbursementBalanceLine) {
val formattedReimbursementAmount = NumberFormat.getCurrencyInstance().format(reimbursementLine.reimbursementAmount)
val formattedExpenseStartingAmount = NumberFormat.getCurrencyInstance().format(reimbursementLine.expenseStartingBalance)
val formattedExpenseEndingAmount = NumberFormat.getCurrencyInstance().format(reimbursementLine.expenseEndingBalance)
val monthName = monthFormatter.format(reimbursementLine.date)
descriptionView.text = itemView.context.getString(R.string.reimbursement_description, formattedReimbursementAmount, monthName)
balanceView.text = NumberFormat.getCurrencyInstance().format(reimbursementLine.balance)
expenseDescriptionView.text = reimbursementLine.expenseDescription
expenseAmountView.text =
itemView.context.getString(R.string.expense_amounts, formattedExpenseStartingAmount, formattedExpenseEndingAmount)
}
}
companion object {
private val dateFormatter = DateTimeFormatter.ofPattern("yyyy MMM")
private val monthFormatter = DateTimeFormatter.ofPattern("MMMM")
}
} | 0 | Kotlin | 0 | 0 | 0c135d17bd69a8c2d584e35f80949c6c1c94e17f | 6,619 | hsa-planner | MIT License |
src/test/kotlin/day02/GameTests.kt | jankase | 573,187,696 | false | null | package day02
import readTestResourceFile
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
class GameTests {
private lateinit var lines: List<String>
@BeforeTest
fun setup() {
lines = readTestResourceFile("Day02")
}
@Test
fun testTotalGameScoreTwoPlays() {
val game = Game(lines.map { Round.fromOpponentAndYourPlay(it) })
assertEquals(15, game.totalScore())
}
@Test
fun testTotalGameScoreOpponentPlayAndDesiredResult() {
val game = Game(lines.map { Round.fromOpponentPlayAndDesiredResult(it) })
assertEquals(12, game.totalScore())
}
}
| 0 | Kotlin | 0 | 0 | 0dac4ec92c82a5ebb2179988fb91fccaed8f800a | 658 | adventofcode2022 | Apache License 2.0 |
app/src/main/java/com/tutorials/mypets/components/Indicators.kt | Rynxiao | 467,004,092 | false | {"Kotlin": 48527} | // copy from https://github.com/karimsinouh/On-Boarding
package com.tutorials.mypets.components
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
@Composable
fun Indicators(size: Int, index: Int) {
Row(
modifier = Modifier.padding(12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
repeat(size) {
Indicator(isSelected = it == index)
}
}
}
@Composable
fun Indicator(isSelected: Boolean) {
val width = animateDpAsState(
targetValue = if (isSelected) 15.dp else 6.dp,
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy)
)
Box(
modifier = Modifier
.height(6.dp)
.width(width.value)
.clip(CircleShape)
.background(
if (isSelected) MaterialTheme.colors.primary
else MaterialTheme.colors.onBackground.copy(alpha = 0.5f)
)
) {
}
} | 0 | Kotlin | 0 | 0 | 6644cc45e9ae828b1e6774a2a65e7468df0ab4af | 1,485 | PetGallery | MIT License |
kotlin-shell-core/src/main/kotlin/eu/jrie/jetbrains/kotlinshell/processes/pipeline/Pipeline.kt | jakubriegel | 201,264,963 | false | null | package eu.jrie.jetbrains.kotlinshellextension.processes.pipeline
import eu.jrie.jetbrains.kotlinshellextension.processes.ProcessCommander
import eu.jrie.jetbrains.kotlinshellextension.processes.execution.ExecutionContext
import eu.jrie.jetbrains.kotlinshellextension.processes.execution.ProcessExecutable
import eu.jrie.jetbrains.kotlinshellextension.processes.execution.ProcessExecutionContext
import eu.jrie.jetbrains.kotlinshellextension.processes.process.Process
import eu.jrie.jetbrains.kotlinshellextension.processes.process.ProcessChannelUnit
import eu.jrie.jetbrains.kotlinshellextension.processes.process.ProcessReceiveChannel
import eu.jrie.jetbrains.kotlinshellextension.processes.process.ProcessSendChannel
import eu.jrie.jetbrains.kotlinshellextension.shell.piping.ShellPiping
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.launch
import kotlinx.io.core.BytePacketBuilder
import kotlinx.io.core.ByteReadPacket
import kotlinx.io.streams.writePacket
import org.jetbrains.annotations.TestOnly
import org.slf4j.LoggerFactory
import java.io.OutputStream
typealias PipelineContextLambda = suspend (context: ExecutionContext) -> Unit
/**
* The entity representing pipeline.
* Should be used with piping DSL
*
* @see ShellPiping
*/
@ExperimentalCoroutinesApi
class Pipeline @TestOnly internal constructor (
private val context: ProcessExecutionContext,
private val channelBufferSize: Int
) {
/**
* Indicates wheater this [Pipeline] has ending element.
* If `true` [Pipeline] cannot be appended.
*
* @see Pipeline.toEndLambda
* @see Pipeline.toEndChannel
* @see Pipeline.toEndPacket
* @see Pipeline.toEndStream
* @see Pipeline.toEndStringBuilder
*/
var closed = false
private set
private val processLine = mutableListOf<Process>()
private lateinit var lastOut: ProcessReceiveChannel
private val asyncJobs = mutableListOf<Job>()
/**
* Read only list of [Process]es added to this [Pipeline].
* Most recent [Process] is at the end of the list
*/
val processes: List<Process>
get() = processLine.toList()
/**
* Adds [process] to this [Pipeline]
*
* @see ShellPiping
* @return this [Pipeline]
*/
suspend fun throughProcess(process: ProcessExecutable) = apply {
addProcess(process.updateContext(newIn = lastOut))
}
private suspend fun addProcess(executable: ProcessExecutable) = ifNotEnded {
executable.updateContext(newOut = channel())
.apply {
init()
exec()
}
launch {
executable.join()
executable.context.stdout.close()
}
processLine.add(executable.process)
}
/**
* Adds [lambda] to this [Pipeline]
*
* @see ShellPiping
* @return this [Pipeline]
*/
suspend fun throughLambda(end: Boolean = false, closeOut: Boolean = true, lambda: PipelineContextLambda) = apply {
addLambda(lambda, context.updated(newIn = lastOut), end, closeOut)
}
private suspend fun addLambda(
lambda: PipelineContextLambda,
lambdaContext: PipelineExecutionContext = PipelineExecutionContext(context),
end: Boolean,
closeOut: Boolean
) = ifNotEnded {
lambdaContext
.let { if (!end) it.updated(newOut = channel()) else it }
.let { ctx ->
launch {
lambda(ctx)
if (closeOut) ctx.stdout.close()
}
}
}
private suspend fun toEndLambda(
closeOut: Boolean = false, lambda: suspend (ByteReadPacket) -> Unit
) = toEndLambda(closeOut, lambda, {})
private suspend fun toEndLambda(
closeOut: Boolean = false, lambda: suspend (ByteReadPacket) -> Unit, finalize: () -> Unit
) = apply {
throughLambda(end = true, closeOut = closeOut) { ctx ->
ctx.stdin.consumeEach { lambda(it) }
finalize()
}
closed = true
}
/**
* Ends this [Pipeline] with [channel]
*
* @see ShellPiping
* @return this [Pipeline]
*/
suspend fun toEndChannel(channel: ProcessSendChannel) = toEndLambda (
false,
{ channel.send(it) },
{ channel.close() }
)
internal suspend fun toDefaultEndChannel(channel: ProcessSendChannel) = toEndLambda { channel.send(it) }
/**
* Ends this [Pipeline] with [packetBuilder]
*
* @see ShellPiping
* @return this [Pipeline]
*/
suspend fun toEndPacket(packetBuilder: BytePacketBuilder) = toEndLambda { packetBuilder.writePacket(it) }
/**
* Ends this [Pipeline] with [stream]
*
* @see ShellPiping
* @return this [Pipeline]
*/
suspend fun toEndStream(stream: OutputStream) = toEndLambda { stream.writePacket(it) }
/**
* Ends this [Pipeline] with [stringBuilder]
*
* @see ShellPiping
* @return this [Pipeline]
*/
suspend fun toEndStringBuilder(stringBuilder: StringBuilder) = toEndLambda { stringBuilder.append(it.readText()) }
/**
* Awaits all processes and jobs in this [Pipeline]
*
* @see ShellPiping
* @return this [Pipeline]
*/
suspend fun join() = apply {
logger.debug("awaiting pipeline $this")
processLine.forEach { context.commander.awaitProcess(it) }
asyncJobs.forEach { it.join() }
logger.debug("awaited pipeline $this")
}
/**
* Kills all processes in this [Pipeline]
*
* @see ShellPiping
* @return this [Pipeline]
*/
suspend fun kill() = apply {
logger.debug("killing pipeline $this")
processLine.forEach { context.commander.killProcess(it) }
asyncJobs.forEach { it.cancelAndJoin() }
logger.debug("killed pipeline $this")
}
/**
* Returns new [ProcessSendChannel] and sets it as [lastOut]
*/
private fun channel(): ProcessSendChannel = Channel<ProcessChannelUnit>(channelBufferSize).also { lastOut = it }
private fun launch(block: suspend CoroutineScope.() -> Unit) {
asyncJobs.add(context.commander.scope.launch(block = block))
}
private suspend fun ifNotEnded(block: suspend () -> Unit) {
if (closed) throw Exception("Pipeline closed")
else block()
}
companion object {
/**
* Starts new [Pipeline] with process specified by given [ProcessExecutable]
*
* @see ShellPiping
*/
internal suspend fun fromProcess(
process: ProcessExecutable, context: ProcessExecutionContext, channelBufferSize: Int
) = Pipeline(context, channelBufferSize)
.apply { addProcess(process) }
/**
* Starts new [Pipeline] with [lambda]
*
* @see ShellPiping
*/
internal suspend fun fromLambda(
lambda: PipelineContextLambda, context: ProcessExecutionContext, channelBufferSize: Int
) = Pipeline(context, channelBufferSize)
.apply { addLambda(lambda, end = false, closeOut = true) }
/**
* Starts new [Pipeline] with [channel]
*
* @see ShellPiping
*/
internal fun fromChannel(
channel: ProcessReceiveChannel, context: ProcessExecutionContext, channelBufferSize: Int
) = Pipeline(context, channelBufferSize)
.apply { lastOut = channel }
private val logger = LoggerFactory.getLogger(Pipeline::class.java)
}
private class PipelineExecutionContext (
override val stdin: ProcessReceiveChannel,
override val stdout: ProcessSendChannel,
override val stderr: ProcessSendChannel,
override val commander: ProcessCommander
) : ProcessExecutionContext {
constructor(context: ProcessExecutionContext)
: this(context.stdin, context.stdout, context.stderr, context.commander)
}
private fun ProcessExecutable.updateContext(
newIn: ProcessReceiveChannel = this.context.stdin,
newOut: ProcessSendChannel = this.context.stdout
) = apply {
context = PipelineExecutionContext(
newIn, newOut, context.stderr, (this.context as ProcessExecutionContext).commander
)
}
private fun ProcessExecutionContext.updated(
newIn: ProcessReceiveChannel = this.stdin,
newOut: ProcessSendChannel = this.stdout
) = PipelineExecutionContext(newIn, newOut, stderr, commander)
}
| 4 | Kotlin | 6 | 96 | 0325ae97c364aa0d5d496cd520f536f11614f443 | 8,781 | kotlin-shell | Apache License 2.0 |
src/main/kotlin/com/gluigip/gipinsight/base/ui/extensions/LayoutExtensiosn.kt | jforge | 137,042,312 | false | null | package com.gluigip.gipinsight.base.ui.extensions
import com.vaadin.flow.component.HasComponents
import com.vaadin.flow.component.dialog.Dialog
import com.vaadin.flow.component.formlayout.FormLayout
import com.vaadin.flow.component.html.Div
import com.vaadin.flow.component.orderedlayout.HorizontalLayout
import com.vaadin.flow.component.orderedlayout.ThemableLayout
import com.vaadin.flow.component.orderedlayout.VerticalLayout
import com.vaadin.flow.component.splitlayout.SplitLayout
infix fun <LAYOUT : ThemableLayout> LAYOUT.hasMargin(hasMargin: Boolean): LAYOUT {
isMargin = hasMargin
return this
}
//infix fun <COMPONENT : Layout.MarginHandler> COMPONENT.margin(margin: MarginInfo): COMPONENT {
// setMargin(margin)
// return this
//}
infix fun <COMPONENT : ThemableLayout> COMPONENT.hasSpacing(hasSpacing: Boolean): COMPONENT {
isSpacing = hasSpacing
return this
}
infix fun <COMPONENT : ThemableLayout> COMPONENT.hasPadding(hasPadding: Boolean): COMPONENT {
isPadding = hasPadding
return this
}
fun HasComponents.verticalLayout(addToParent: Boolean = true): VerticalLayout {
return add(VerticalLayout(), addToParent)
}
fun HasComponents.formLayout(addToParent: Boolean = true): FormLayout {
return add(FormLayout(), addToParent)
}
fun HasComponents.horizontalLayout(addToParent: Boolean = true): HorizontalLayout {
return add(HorizontalLayout(), addToParent)
}
fun HasComponents.div(addToParent: Boolean = true): Div {
return add(Div(), addToParent)
}
fun HasComponents.splitLayout(addToParent: Boolean = true): SplitLayout {
return add(SplitLayout(), addToParent)
}
fun HasComponents.dialog(addToParent: Boolean = false): Dialog {
return add(Dialog(), addToParent)
} | 0 | Kotlin | 0 | 0 | 7f37f3f3ab021c16ababea828fdf12c036fdcd33 | 1,740 | GipInsight | Apache License 2.0 |
androidApp/src/main/java/com/mrebollob/loteria/android/presentation/home/ui/HomeEmptyView.kt | mrebollob | 46,619,950 | false | {"Kotlin": 142333, "Swift": 29488, "Ruby": 1908} | package com.mrebollob.loteria.android.presentation.home.ui
import android.content.res.Configuration
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mrebollob.loteria.android.R
import com.mrebollob.loteria.android.presentation.platform.ui.theme.LotteryTheme
import com.mrebollob.loteria.domain.entity.Ticket
@Composable
fun HomeEmptyView(
modifier: Modifier = Modifier,
onCreateTicketClick: (() -> Unit),
) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
modifier = Modifier.padding(top = 72.dp),
text = stringResource(id = R.string.home_screen_empty_title),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h5
)
Box(
modifier = Modifier.padding(top = 32.dp, start = 32.dp, end = 32.dp)
) {
TicketItemView(
ticket = Ticket(
id = 1,
name = stringResource(id = R.string.home_screen_empty_ticket_sample_name),
number = 0,
bet = 2.5f
),
totalPrize = null
)
}
Button(
modifier = Modifier
.clipToBounds()
.padding(top = 56.dp),
shape = RoundedCornerShape(24.dp),
onClick = onCreateTicketClick
) {
Icon(
imageVector = Icons.Default.Add,
tint = MaterialTheme.colors.onPrimary,
contentDescription = stringResource(R.string.home_screen_empty_cta)
)
Text(
modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
text = stringResource(R.string.home_screen_empty_cta),
style = MaterialTheme.typography.subtitle1
)
}
}
}
@Preview("Home empty view")
@Preview("Home empty view (dark)", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PreviewHomeEmptyView() {
LotteryTheme {
HomeEmptyView(
onCreateTicketClick = {}
)
}
}
| 0 | Kotlin | 0 | 0 | 2fe351ceaa6a3fc40faf2d57e32325bff6d5235b | 2,915 | LoteriadeNavidad | Apache License 2.0 |
playtest-core/src/test/kotlin/com/uzabase/playtest2/core/AssertionStepsTest.kt | uzabase | 723,558,469 | false | {"Kotlin": 34808} | package com.uzabase.playtest2.core
import com.thoughtworks.gauge.datastore.ScenarioDataStore
import com.uzabase.playtest2.core.DefaultAssertableProxy.Companion.defaults
import com.uzabase.playtest2.core.assertion.AssertableProxy
import com.uzabase.playtest2.core.assertion.PlaytestException
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.data.forAll
import io.kotest.data.row
import io.kotest.matchers.shouldBe
data class FullName(val firstName: String, val lastName: String)
fun fromFullName(x: Any): AssertableProxy? =
(x as? FullName)?.let {
object : AssertableProxy {
override val self: Any = x
override fun asString(): String = "${x.firstName} ${x.lastName} :)"
}
}
class AssertionStepsTest : FunSpec({
val sut = AssertionSteps()
beforeEach {
ScenarioDataStore.items().forEach { ScenarioDataStore.remove(it) }
}
context("Assertions") {
context("happy path") {
test("long value") {
ScenarioDataStore.put("AssertionTarget", 200L)
sut.shouldBeLongValue(200L)
}
test("string value") {
ScenarioDataStore.put("AssertionTarget", "Hello, world")
sut.shouldBeStringValue("Hello, world")
}
}
}
context("failed scenarios") {
context("assertion target not found") {
test("long value") {
shouldThrow<PlaytestException> {
sut.shouldBeLongValue(200L)
}.message.shouldBe("Assertion target is not found")
}
test("string value") {
shouldThrow<PlaytestException> {
sut.shouldBeStringValue("Hello, world")
}.message.shouldBe("Assertion target is not found")
}
}
}
context("Any value should assert as string value") {
forAll(
row(FullName("John", "Doe"), listOf(::fromFullName, *defaults.toTypedArray()), "<NAME> :)"),
row("Hello, world", defaults, "Hello, world")
) { origin, factories, expected ->
ScenarioDataStore.put("AssertableProxyFactories", factories)
ScenarioDataStore.put("AssertionTarget", origin)
sut.shouldBeStringValue(expected)
}
}
})
| 0 | Kotlin | 0 | 4 | b92f992d5987ee87a0e3ae3e22887b43f5a14287 | 2,379 | playtest2 | MIT License |
ChoiceSDK/choicesdk-maps/src/main/java/at/bluesource/choicesdk/maps/gms/GmsMapOptions.kt | bluesource | 342,192,341 | false | null | package at.bluesource.choicesdk.maps.gms
import android.os.Parcelable
import at.bluesource.choicesdk.maps.common.MapOptions
import com.google.android.gms.maps.GoogleMapOptions
import kotlinx.parcelize.Parcelize
@Parcelize
internal class GmsMapOptions(
private val mapOptions: GoogleMapOptions = GoogleMapOptions()
) : MapOptions, Parcelable {
override val liteMode: Boolean?
get() = mapOptions.liteMode
override val mapToolbarEnabled: Boolean?
get() = mapOptions.mapToolbarEnabled
override fun liteMode(enable: Boolean) {
mapOptions.liteMode(enable)
}
override fun mapToolbarEnabled(enable: Boolean) {
mapOptions.mapToolbarEnabled(enable)
}
} | 11 | Kotlin | 19 | 85 | 4c70f2711f9ee71aa7ae73ab4d6eaa5a3fa81274 | 710 | ChoiceSDK | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/MyApp.kt | kinnerapriyap | 344,350,384 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.example.androiddevchallenge.ui.theme.MyTheme
@Composable
fun MyApp() {
Scaffold {
StretchableSquare()
}
}
@Preview
@Composable
fun MyAppPreview() {
MyTheme {
MyApp()
}
}
| 0 | Kotlin | 0 | 2 | abbc480d5a69fcbdc5754ca494f7c79b44c75e98 | 1,008 | do-you-wanna-build-a-countdown-timer | Apache License 2.0 |
service-query/src/main/kotlin/org/veupathdb/service/mblast/query/sql/queries/select-query-config.kt | VEuPathDB | 303,794,401 | false | {"Kotlin": 1601655, "Java": 404589, "RAML": 120840, "Dockerfile": 3585, "Shell": 2218, "SQL": 2160} | package org.veupathdb.service.mblast.query.sql.queries
import org.intellij.lang.annotations.Language
import org.veupathdb.lib.blast.Blast
import org.veupathdb.lib.blast.common.BlastQueryBase
import org.veupathdb.lib.hash_id.HashID
import org.veupathdb.lib.jackson.Json
import org.veupathdb.service.mblast.query.model.BasicQueryConfig
import org.veupathdb.service.mblast.query.model.BasicQueryConfigImpl
import org.veupathdb.service.mblast.query.model.QueryUserMetaImpl
import org.veupathdb.service.mblast.query.model.UserQueryConfigImpl
import org.veupathdb.service.mblast.query.sql.util.clobToFile
import org.veupathdb.service.mblast.query.sql.util.fetchList
import org.veupathdb.service.mblast.query.sql.util.fetchOpt
import java.sql.Connection
import java.sql.ResultSet
import java.time.OffsetDateTime
// ---------------------------------------------------------------------------------------------------------------------
//
// -- Select Job By Job ID
//
// ---------------------------------------------------------------------------------------------------------------------
private const val SQL_BY_ID = """
SELECT
${Column.QueryJobID}
, ${Column.ProjectID}
, ${Column.Config}
, ${Column.Query}
, ${Column.CreatedOn}
FROM
${Schema.MBlast}.${Table.QueryConfigs}
WHERE
${Column.QueryJobID} = ?
"""
/**
* Retrieves a target BLAST query configuration from the database.
*
* @param jobID ID of the job whose query configuration should be fetched.
*
* @return Either the query configuration with the given job ID, or null if no
* matching record exists.
*/
fun Connection.selectQueryConfigByID(jobID: HashID) =
prepareStatement(SQL_BY_ID).use { ps ->
ps.setString(1, jobID.string)
ps.fetchOpt { parseQueryConfig() }
}
// ---------------------------------------------------------------------------------------------------------------------
//
// -- Select Jobs By User ID and Site
//
// ---------------------------------------------------------------------------------------------------------------------
private const val SQL_BY_USER_AND_SITE = """
SELECT
a.${Column.QueryJobID}
, a.${Column.ProjectID}
, a.${Column.Config}
, a.${Column.Query}
, a.${Column.CreatedOn}
, b.${Column.UserID}
, b.${Column.Summary}
, b.${Column.Description}
FROM
${Schema.MBlast}.${Table.QueryConfigs} a
INNER JOIN ${Schema.MBlast}.${Table.QueryToUsers} b
ON a.${Column.QueryJobID} = b.${Column.QueryJobID}
WHERE
b.${Column.UserID} = ?
AND a.${Column.ProjectID} = ?
"""
/**
* Retrieves a list of configurations for BLAST queries that are linked to a
* target user.
*
* @param userID ID of the user whose query configs should be fetched.
*
* @return A list of zero or more query configurations.
*/
fun Connection.selectQueriesByUserAndSite(userID: Long, site: String) =
prepareStatement(SQL_BY_USER_AND_SITE).use { ps ->
ps.setLong(1, userID)
ps.setString(2, site)
ps.fetchList { parseUserQueryRecord() }
}
// ---------------------------------------------------------------------------------------------------------------------
//
// -- Select Jobs By User ID
//
// ---------------------------------------------------------------------------------------------------------------------
private const val SQL_BY_USER = """
SELECT
a.${Column.QueryJobID}
, a.${Column.ProjectID}
, a.${Column.Config}
, a.${Column.Query}
, a.${Column.CreatedOn}
, b.${Column.UserID}
, b.${Column.Summary}
, b.${Column.Description}
FROM
${Schema.MBlast}.${Table.QueryConfigs} a
INNER JOIN ${Schema.MBlast}.${Table.QueryToUsers} b
ON a.${Column.QueryJobID} = b.${Column.QueryJobID}
WHERE
b.${Column.UserID} = ?
"""
/**
* Retrieves a list of configurations for BLAST queries that are linked to a
* target user.
*
* @param userID ID of the user whose query configs should be fetched.
*
* @return A list of zero or more query configurations.
*/
fun Connection.selectQueriesByUser(userID: Long) =
prepareStatement(SQL_BY_USER).use { ps ->
ps.setLong(1, userID)
ps.fetchList { parseUserQueryRecord() }
}
// ---------------------------------------------------------------------------------------------------------------------
//
// -- Select Jobs By User ID and Job ID
//
// ---------------------------------------------------------------------------------------------------------------------
private const val SQL_BY_ID_AND_USER = """
SELECT
a.${Column.QueryJobID}
, a.${Column.ProjectID}
, a.${Column.Config}
, a.${Column.Query}
, a.${Column.CreatedOn}
, b.${Column.UserID}
, b.${Column.Summary}
, b.${Column.Description}
FROM
${Schema.MBlast}.${Table.QueryConfigs} a
INNER JOIN ${Schema.MBlast}.${Table.QueryToUsers} b
ON a.${Column.QueryJobID} = b.${Column.QueryJobID}
WHERE
b.${Column.UserID} = ?
AND a.${Column.QueryJobID} = ?
"""
/**
* Retrieves a target job that is linked to a target user.
*
* If the target job does not exist, or is not linked to the target user, this
* method returns `null`.
*
* @param queryJobID ID of the job whose query config should be fetched.
*
* @param userID ID of the user who must be linked to the target job.
*
* @return Either the target job query configuration or `null`.
*/
fun Connection.selectQueryConfigByJobAndUser(queryJobID: HashID, userID: Long) =
prepareStatement(SQL_BY_ID_AND_USER).use { ps ->
ps.setLong(1, userID)
ps.setString(2, queryJobID.string)
ps.fetchOpt { parseUserQueryRecord() }
}
// ---------------------------------------------------------------------------------------------------------------------
//
// -- Select Jobs By Parent ID
//
// ---------------------------------------------------------------------------------------------------------------------
/**
* Query to select child blast job configurations by user ID.
*
* This query gets the set of parent jobs by user ID from the user links table
* then uses that set to get the list of blast configurations that are marked as
* children under the set of parent jobs.
*/
@Language("Oracle")
private const val SQL_CHILDREN_BY_USER = """
SELECT
a.${Column.QueryJobID}
, a.${Column.ProjectID}
, a.${Column.Config}
, a.${Column.Query}
, a.${Column.CreatedOn}
, b.${Column.ParentJobID}
FROM
${Schema.MBlast}.${Table.QueryConfigs} a
INNER JOIN ${Schema.MBlast}.${Table.QueryToQueries} b
ON a.${Column.QueryJobID} = b.${Column.ChildJobID}
WHERE
b.${Column.ParentJobID} IN (
SELECT
${Column.QueryJobID}
FROM
${Schema.MBlast}.${Table.QueryToUsers}
WHERE
${Column.UserID} = ?
)
ORDER BY
${Column.Position}
"""
/**
* Retrieves a map of job ID to list of child job query configurations attached
* to a target user.
*
* @param userID ID of the user whose total child job set should be retrieved.
*
* @return A map of parent job ID to list of child query job configs under that
* parent job.
*/
fun Connection.selectChildQueriesByUser(userID: Long) =
prepareStatement(SQL_CHILDREN_BY_USER).use { ps ->
ps.setLong(1, userID)
ps.executeQuery().use { it.parseChildConfigMap() }
}
// ---------------------------------------------------------------------------------------------------------------------
//
// -- Select Jobs By Parent ID
//
// ---------------------------------------------------------------------------------------------------------------------
@Language("Oracle")
private const val SQL_CHILDREN_BY_PARENT = """
SELECT
a.${Column.QueryJobID}
, a.${Column.ProjectID}
, a.${Column.Config}
, a.${Column.Query}
, a.${Column.CreatedOn}
FROM
${Schema.MBlast}.${Table.QueryConfigs} a
INNER JOIN ${Schema.MBlast}.${Table.QueryToQueries} b
ON a.${Column.QueryJobID} = b.${Column.ChildJobID}
WHERE
b.${Column.ParentJobID} = ?
ORDER BY
b.${Column.Position}
"""
/**
* Retrieves a list of child job query configurations for a target parent job.
*
* If no job exists with the given job ID, an empty list will be returned.
*
* @param queryJobID ID of the target parent job whose child jobs should be
* fetched.
*
* @return A list of zero or more child jobs linked to the given parent job ID.
*/
fun Connection.selectChildQueriesByParent(queryJobID: HashID) =
prepareStatement(SQL_CHILDREN_BY_PARENT).use { ps ->
ps.setString(1, queryJobID.string)
ps.fetchList { parseQueryConfig() }
}
// ---------------------------------------------------------------------------------------------------------------------
//
// -- Result Parsing
//
// ---------------------------------------------------------------------------------------------------------------------
/**
* Parses a [BasicQueryConfig] instance from the receiver [ResultSet].
*
* This method requires that the `ResultSet` cursor is already on a row that can
* be parsed.
*
* @receiver ResultSet from which a row will be parsed.
*
* @return A parsed `BasicQueryConfig` instance.
*/
private fun ResultSet.parseQueryConfig(): BasicQueryConfig =
BasicQueryConfigImpl(
HashID(getString(Column.QueryJobID)),
getString(Column.ProjectID),
Blast.of(Json.parse(getString(Column.Config))) as BlastQueryBase,
clobToFile(Column.Query),
getObject(Column.CreatedOn, OffsetDateTime::class.java),
)
private fun ResultSet.parseUserQueryRecord() =
UserQueryConfigImpl(
parseQueryConfig(),
QueryUserMetaImpl(
getLong(Column.UserID),
getString(Column.Summary),
getString(Column.Description)
)
)
private fun ResultSet.parseChildConfigMap(): Map<HashID, List<BasicQueryConfig>> =
HashMap<HashID, MutableList<BasicQueryConfig>>(8).also {
while (next())
it.computeIfAbsent(HashID(getString(Column.ParentJobID))) { ArrayList(8) }
.add(parseQueryConfig())
}
| 17 | Kotlin | 0 | 0 | 05bd8da81d7dc5eb34e200dedf7cac7d1f32a4b4 | 9,695 | service-multi-blast | Apache License 2.0 |
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress1040010.kt | qwewqa | 390,928,568 | false | null | package xyz.qwewqa.relive.simulator.core.presets.dress.generated
import xyz.qwewqa.relive.simulator.core.stage.actor.ActType
import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute
import xyz.qwewqa.relive.simulator.core.stage.actor.StatData
import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters
import xyz.qwewqa.relive.simulator.core.stage.dress.ActBlueprint
import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint
import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost
import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType
import xyz.qwewqa.relive.simulator.stage.character.Character
import xyz.qwewqa.relive.simulator.stage.character.DamageType
import xyz.qwewqa.relive.simulator.stage.character.Position
/*
import xyz.qwewqa.relive.simulator.core.presets.condition.*
import xyz.qwewqa.relive.simulator.core.presets.dress.generated.dress1040010
import xyz.qwewqa.relive.simulator.core.stage.Act
import xyz.qwewqa.relive.simulator.core.stage.actor.ActType
import xyz.qwewqa.relive.simulator.core.stage.actor.CountableBuff
import xyz.qwewqa.relive.simulator.core.stage.dress.DressCategory
import xyz.qwewqa.relive.simulator.core.stage.autoskill.new
import xyz.qwewqa.relive.simulator.core.stage.dress.blueprint
import xyz.qwewqa.relive.simulator.core.stage.buff.*
import xyz.qwewqa.relive.simulator.core.stage.passive.*
import xyz.qwewqa.relive.simulator.core.stage.stageeffect.*
val dress = dress1040010(
name = "怪人二十面相",
acts = listOf(
ActType.Act1.blueprint("怪人からの予告状") {
Act {
/*
%attr%属性攻撃(威力%value%)
target: 前から1番目の敵役
hit_rate1: 100
values1: [88, 92, 96, 101, 105]
times1: 1
刻印
target: 前から1番目の敵役
hit_rate2: 100
values2: [0, 0, 0, 0, 0]
times2: [3, 3, 3, 3, 3]
*/
}
},
ActType.Act2.blueprint("怪人の手腕") {
Act {
/*
%attr%属性攻撃(威力%value%)
target: 敵役全体
hit_rate1: 100
values1: [54, 56, 59, 62, 64]
times1: 1
継続プラス効果解除
target: 敵役全体
hit_rate2: 100
values2: [0, 0, 0, 0, 0]
times2: [0, 0, 0, 0, 0]
*/
}
},
ActType.Act3.blueprint("キラめきの風") {
Act {
/*
キラめき回復(%value%)
target: 味方全体
hit_rate1: 100
values1: [15, 16, 17, 18, 20]
times1: [0, 0, 0, 0, 0]
*/
}
},
ActType.ClimaxAct.blueprint("華麗なる美技") {
Act {
/*
%attr%属性攻撃(威力%value%)
target: ACTパワーが1番高い敵役
hit_rate1: 100
values1: [328, 345, 361, 378, 394]
times1: 5
継続マイナス効果解除
target: 味方全体
hit_rate2: 100
values2: [0, 0, 0, 0, 0]
times2: [0, 0, 0, 0, 0]
*/
}
}
),
autoSkills = listOf(
listOf(
/*
auto skill 1:
回避
target: 自身
hit_rate: 100
value: 0
time: 1
*/
),
listOf(
/*
auto skill 2:
クリティカル率アップ(%value%)
target: 自身
values: [8, 9, 10, 11, 12]
*/
),
listOf(
/*
auto skill 3:
回避
target: 自身
hit_rate: 100
value: 0
time: 1
*/
),
),
unitSkill = null /* 立ち位置後の舞台少女の最大HPアップ %opt1_value%%(MAX50%) 通常防御力アップ %opt2_value%%(MAX30%) 特殊防御力アップ %opt3_value%%(MAX30%) */,
multipleCA = false,
categories = setOf(),
)
*/
val dress1040010 = PartialDressBlueprint(
id = 1040010,
name = "怪人二十面相",
baseRarity = 4,
cost = 12,
character = Character.Claudine,
attribute = Attribute.Flower,
damageType = DamageType.Normal,
position = Position.Back,
positionValue = 33050,
stats = StatData(
hp = 1206,
actPower = 167,
normalDefense = 99,
specialDefense = 43,
agility = 168,
dexterity = 5,
critical = 50,
accuracy = 0,
evasion = 0,
),
growthStats = StatData(
hp = 39750,
actPower = 2750,
normalDefense = 1630,
specialDefense = 710,
agility = 2780,
),
actParameters = mapOf(
ActType.Act1 to ActBlueprint(
name = "怪人からの予告状",
type = ActType.Act1,
apCost = 2,
icon = 150,
parameters = listOf(
actParameters0,
actParameters23,
actParameters1,
actParameters1,
actParameters1,
),
),
ActType.Act2 to ActBlueprint(
name = "怪人の手腕",
type = ActType.Act2,
apCost = 3,
icon = 10006,
parameters = listOf(
actParameters21,
actParameters30,
actParameters1,
actParameters1,
actParameters1,
),
),
ActType.Act3 to ActBlueprint(
name = "キラめきの風",
type = ActType.Act3,
apCost = 3,
icon = 89,
parameters = listOf(
actParameters34,
actParameters1,
actParameters1,
actParameters1,
actParameters1,
),
),
ActType.ClimaxAct to ActBlueprint(
name = "華麗なる美技",
type = ActType.ClimaxAct,
apCost = 2,
icon = 10005,
parameters = listOf(
actParameters164,
actParameters30,
actParameters1,
actParameters1,
actParameters1,
),
),
),
autoSkillRanks = listOf(1, 4, 9, null),
autoSkillPanels = listOf(0, 0, 5, 0),
rankPanels = growthBoard4,
friendshipPanels = friendshipPattern0,
remakeParameters = listOf(
StatData(
hp = 6000,
actPower = 450,
normalDefense = 300,
specialDefense = 180,
agility = 240,
),
StatData(
hp = 10000,
actPower = 750,
normalDefense = 500,
specialDefense = 300,
agility = 400,
),
StatData(
hp = 16000,
actPower = 1200,
normalDefense = 800,
specialDefense = 480,
agility = 640,
),
StatData(
hp = 20000,
actPower = 1500,
normalDefense = 1000,
specialDefense = 600,
agility = 800,
),
),
)
| 0 | Kotlin | 11 | 7 | 70e1cfaee4c2b5ab4deff33b0e4fd5001c016b74 | 6,532 | relight | MIT License |
app/src/main/java/com/damai/helper/DamaiHelperService.kt | zjutcaicai | 678,843,163 | false | null | package com.damai.helper
import android.accessibilityservice.AccessibilityService
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.PixelFormat
import android.util.TypedValue
import android.view.Gravity
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import androidx.core.app.NotificationCompat
import java.lang.Thread.sleep
class DamaiHelperService : AccessibilityService() {
companion object {
// 首页-我的
const val ME_UI = "cn.damai.mine.activity.MineMainActivity"
// 演唱会详情页
const val LIVE_DETAIL_UI = "cn.damai.trade.newtradeorder.ui.projectdetail.ui.activity.ProjectDetailActivity"
// 票档选择页
const val TICKET_PRICE_UI = "cn.damai.commonbusiness.seatbiz.sku.qilin.ui.NcovSkuActivity"
// 订单提交页
const val ORDER_SUBMIT_UI = "cn.damai.ultron.view.activity.DmOrderActivity"
const val ID_LIVE_DETAIL_BUY = "tv_left_main_text" // 详情页-开抢
const val ID_PLUS_TICKET = "img_jia" // 选择票数
const val ID_CONFIRM_BUY = "btn_buy" // 确定购买
const val STEP_FIRST = 1
const val STEP_SECOND = 2
const val STEP_THIRD = 3
const val SERVER_STOPPED = 0
const val SERVER_STARTED = 1
lateinit var time: String // 场次
lateinit var ticket: String // 票档
@SuppressLint("StaticFieldLeak")
var instance: DamaiHelperService? = null
fun start() {
instance?.startServer()
}
fun stop() {
instance?.stopServer()
}
fun isStarted(): Boolean {
return instance?.status == SERVER_STARTED
}
}
private var isStop = true
private var step = STEP_FIRST
private var status = SERVER_STOPPED
private var windowManager: WindowManager? = null
private var floatButton: FloatButton? = null
private lateinit var aboutToStartStr: String
private lateinit var submitOrderStr: String
override fun onCreate() {
super.onCreate()
instance = this
windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
floatButton = FloatButton(this)
aboutToStartStr = getString(R.string.about_to_start)
submitOrderStr = getString(R.string.submit_order)
}
/**
* 监听窗口变化的回调
*/
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
if (isStop || event == null) {
return
}
if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
when (event.className.toString()) {
LIVE_DETAIL_UI -> step = STEP_FIRST
TICKET_PRICE_UI -> step = STEP_SECOND
ORDER_SUBMIT_UI -> step = STEP_THIRD
}
}
when (step) {
STEP_FIRST -> placeOrder(event)
STEP_SECOND -> confirmOrder(event)
STEP_THIRD -> submitOrder(event)
}
}
/**
* 第一步:抢票下单
*/
private fun placeOrder(event: AccessibilityEvent) {
event.source?.let { source ->
source.getNodeById(dmNodeId(ID_LIVE_DETAIL_BUY))?.let { node ->
if (node.text() != aboutToStartStr) {
sleep(100)
node.click()
}
}
}
}
/**
* 第二步:确认订单
*/
private fun confirmOrder(event: AccessibilityEvent) {
event.source?.let { source ->
source.getNodeByText(time)?.let { node ->
sleep(100)
node.click()
}
source.getNodeByText(ticket)?.let { node ->
sleep(100)
node.click()
}
source.getNodeById(dmNodeId(ID_CONFIRM_BUY))?.let { node ->
sleep(100)
node.click()
}
}
}
/**
* 第三步:提交订单
*/
private fun submitOrder(event: AccessibilityEvent) {
event.source?.let { source ->
source.getNodeByText(submitOrderStr, true)?.let { node ->
sleep(100)
node.click()
stopServer()
}
}
}
/**
* 创建通知
*/
private fun createForegroundNotification(): Notification {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
// 创建通知渠道,一定要写在创建显示通知之前,创建通知渠道的代码只有在第一次执行才会创建
// 以后每次执行创建代码检测到该渠道已存在,因此不会重复创建
val channelId = "damai"
notificationManager?.createNotificationChannel(NotificationChannel(
channelId,
getString(R.string.app_name),
NotificationManager.IMPORTANCE_HIGH
))
return NotificationCompat.Builder(this, channelId)
// 设置点击notification跳转,比如跳转到设置页
.setContentIntent(PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java),
FLAG_IMMUTABLE
))
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.desc))
.build()
}
/**
* 显示开抢/暂停按钮
*/
@SuppressLint("InflateParams", "ResourceAsColor", "ClickableViewAccessibility")
private fun showFloatButton() {
// 设置悬浮按钮样式
floatButton?.setText(R.string.start_check)
floatButton?.setTextColor(Color.WHITE)
floatButton?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24F)
floatButton?.setBackgroundResource(R.drawable.float_start_button_background)
floatButton?.stateListAnimator = null
// 设置悬浮按钮参数
val flag = (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
or WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
val params = WindowManager.LayoutParams(
150,
150,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
flag,
PixelFormat.TRANSPARENT
).apply { gravity = Gravity.CENTER_VERTICAL or Gravity.START }
// 将悬浮按钮添加到 WindowManager 中
windowManager?.addView(floatButton, params)
// 设置悬浮按钮监听
floatButton?.setOnClickListener {
if (isStop) {
floatButton?.setText(R.string.stop_check)
floatButton?.setBackgroundResource(R.drawable.float_stop_button_background)
} else {
floatButton?.setText(R.string.start_check)
floatButton?.setBackgroundResource(R.drawable.float_start_button_background)
}
isStop = !isStop
}
}
/**
* 开启服务
*/
private fun startServer() {
if (status == SERVER_STOPPED) {
// 显示浮动按钮
showFloatButton()
// 创建Notification渠道,并开启前台服务
startForeground(1, createForegroundNotification())
step = STEP_FIRST
status = SERVER_STARTED
}
}
/**
* 停止服务
*/
private fun stopServer() {
if (status == SERVER_STARTED) {
stopForeground(STOP_FOREGROUND_REMOVE)
windowManager?.removeView(floatButton)
isStop = true
step = STEP_FIRST
status = SERVER_STOPPED
stopSelf()
}
}
override fun onInterrupt() {
}
override fun onDestroy() {
stopServer()
super.onDestroy()
}
} | 0 | Kotlin | 0 | 2 | 1d66cb747c52ecb2f79708e2efbb2a2cf11e89c1 | 7,921 | damaiTick | MIT License |
kmp/remote/mock/src/commonMain/kotlin/io/github/reactivecircus/kstreamlined/kmp/remote/MockFeedService.kt | ReactiveCircus | 513,535,591 | false | {"Kotlin": 534298} | package io.github.reactivecircus.kstreamlined.kmp.remote
import io.github.reactivecircus.kstreamlined.kmp.remote.model.FeedEntry
import io.github.reactivecircus.kstreamlined.kmp.remote.model.FeedSource
import io.github.reactivecircus.kstreamlined.kmp.remote.model.KotlinWeeklyIssueEntry
public class MockFeedService : FeedService {
override suspend fun fetchFeedOrigins(): List<FeedSource> {
return MockFeedSources
}
override suspend fun fetchFeedEntries(filters: List<FeedSource.Key>?): List<FeedEntry> {
return MockFeedEntries
}
override suspend fun fetchFeedEntriesAndOrigins(
filters: List<FeedSource.Key>?
): Pair<List<FeedEntry>, List<FeedSource>> {
return MockFeedEntries to MockFeedSources
}
override suspend fun fetchKotlinWeeklyIssue(url: String): List<KotlinWeeklyIssueEntry> {
return MockKotlinWeeklyIssueEntries
}
}
| 2 | Kotlin | 0 | 4 | 221816769d7b9533220f944d623cd4997a25df35 | 911 | kstreamlined-mobile | Apache License 2.0 |
app/src/main/java/com/example/audioshopinventorymanagement/room/repositories/ProductDatabaseRepository.kt | galmihaly | 791,479,562 | false | {"Kotlin": 328184} | package com.example.audioshopinventorymanagement.room.repositories
import com.example.audioshopinventorymanagement.room.entities.BrandEntity
import com.example.audioshopinventorymanagement.room.entities.CategoryEntity
import com.example.audioshopinventorymanagement.room.entities.ModelEntity
import com.example.audioshopinventorymanagement.room.entities.ProductEntity
interface ProductDatabaseRepository {
suspend fun insertProduct(product : ProductEntity)
suspend fun insertBrand(brand : BrandEntity)
suspend fun insertCategory(category : CategoryEntity)
suspend fun insertModel(model : ModelEntity)
suspend fun deleteProduct(product : ProductEntity)
suspend fun deleteBrand(brand: BrandEntity)
suspend fun deleteCategory(category: CategoryEntity)
suspend fun deleteModel(model: ModelEntity)
suspend fun deleteAllProduct()
suspend fun deleteAllBrand()
suspend fun deleteAllCategory()
suspend fun deleteAllModel()
suspend fun getAllProducts() : MutableList<ProductEntity>
suspend fun getAllBrands() : MutableList<BrandEntity>
suspend fun getAllCategories() : MutableList<CategoryEntity>
suspend fun getAllModels() : MutableList<ModelEntity>
suspend fun getProductByBarcode(barcode: String) : ProductEntity
suspend fun getBrandById(brandId: String) : BrandEntity
suspend fun getBrandByName(brandName: String) : BrandEntity
suspend fun getCategoryById(categoryId: String) : CategoryEntity
suspend fun getCategoryByName(categoryName: String) : CategoryEntity
suspend fun getModelById(modelId: String) : ModelEntity
suspend fun getModelByName(modelName: String) : ModelEntity
suspend fun updateProductId(barcode: String, productId: String)
suspend fun updateProductName(barcode: String, productName: String)
suspend fun updateBrandId(barcode: String, brandId: String)
suspend fun updateBrandName(barcode: String, brandName: String)
suspend fun updateCategoryId(barcode: String, categoryId: String)
suspend fun updateCategoryName(barcode: String, categoryName: String)
suspend fun updateModelId(barcode: String, modelId: String)
suspend fun updateModelName(barcode: String, modelName: String)
suspend fun updateBasePrice(barcode: String, basePrice: String)
suspend fun updateWholeSalePrice(barcode: String, wholeSalePrice: String)
suspend fun updateWarehouseId(barcode: String, warehouseId: String)
suspend fun updateStorageId(barcode: String, storageId: String)
suspend fun updateBarcode(oldBarcode: String, newBarcode: String)
suspend fun updateRecorderName(barcode: String, recorderName: String)
suspend fun updateDeviceId(barcode: String, deviceId: String)
} | 0 | Kotlin | 0 | 0 | 5e4b330d80e64af6dae4b4e1435be42bd20a0e5d | 2,712 | AudioShopInventoryManagement | Apache License 2.0 |
shared/src/androidMain/kotlin/io/ashdavies/playground/Platform.kt | ashdavies | 36,688,248 | false | null | package io.ashdavies.playground
import android.os.Build.VERSION.SDK_INT
actual object Platform {
actual val platform: String get() = "Android $SDK_INT"
}
| 10 | Kotlin | 32 | 107 | bed73969ca5ec5ec76bdac04592994f847ee2991 | 160 | data-binding | Apache License 2.0 |
db-pg/src/test/kotlin/PgDbUserRepositoryTest.kt | crowdproj | 543,982,440 | false | {"Kotlin": 563021, "JavaScript": 68945, "HTML": 25088, "Dockerfile": 1197, "Batchfile": 876, "Shell": 842} | package com.gitlab.sszuev.flashcards.dbpg
import com.gitlab.sszuev.flashcards.dbcommon.DbUserRepositoryTest
internal class PgDbUserRepositoryTest : DbUserRepositoryTest() {
override val repository = PgDbUserRepository(PgTestContainer.config)
} | 2 | Kotlin | 0 | 2 | 2aa0680a64e4cf2f9bb6353309358e1008423c85 | 249 | opentutor | Apache License 2.0 |
src/main/kotlin/cn/yyxx/apklink/internal/IChannel.kt | Suyghur | 470,003,377 | false | {"Kotlin": 14276, "Shell": 2598} | package cn.yyxx.apklink.internal
import cn.yyxx.apklink.bean.TaskBean
interface IChannel {
fun execChannelExtraScript(bean: TaskBean): Boolean
} | 0 | Kotlin | 0 | 0 | fd95c74a13ab4837ed21fca640542ae73e839c8f | 150 | apklink | Apache License 2.0 |
app/src/main/java/com/ns/rickandmortyinviochallenge/MainActivity.kt | enesarisoy | 680,023,259 | false | null | package com.ns.rickandmortyinviochallenge
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.ns.rickandmortyinviochallenge.presentation.screens.characters.CharacterScreen
import com.ns.rickandmortyinviochallenge.presentation.screens.characters.CharactersViewModel
import com.ns.rickandmortyinviochallenge.presentation.screens.characters.components.chips.LocationChips
import com.ns.rickandmortyinviochallenge.presentation.screens.detail.CharacterDetailScreen
import com.ns.rickandmortyinviochallenge.presentation.screens.splash.SplashScreen
import com.ns.rickandmortyinviochallenge.ui.theme.RickAndMortyInvioChallengeTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val viewModel: CharactersViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RickAndMortyInvioChallengeTheme {
Surface {
Column {
NavigationView()
}
}
}
}
}
}
@Composable
fun NavigationView() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "splash") {
composable("splash") {
SplashScreen(navController = navController)
}
composable("home") {
CharacterScreen(navController = navController)
}
composable(
"detail/{id}",
arguments = listOf(navArgument("id") { type = NavType.StringType })
) {
val id = it.arguments?.getString("id")
id?.let {idd ->
CharacterDetailScreen(navController = navController, characterId = idd.toInt())
}
}
}
}
| 0 | Kotlin | 0 | 0 | ab20b9a6939415304c4da1bdeb12275e1d42dd01 | 2,292 | Rick-And-Morty | Apache License 2.0 |
src/main/kotlin/theme/colors.kt | vipulasri | 326,957,116 | false | null | package theme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.ui.graphics.Color
val graySurface = Color(0xFF2A2A2A)
val lightGray = Color(0xFFD3D3D3)
val green700 = Color(0xff388e3c)
val slackBlack = Color(0xff1E2228)
val darkGray = Color(0xFF565656)
val divider = Color(0xff35383D)
object SlackColors {
val online = Color(0xffA7E476)
val onlineDark = Color(0xff34785C)
val grey = Color(0xffABABAD)
val black = Color(0xff1E2228)
val reactionBg = Color(0xff232529)
val optionSelected = Color(0xff5B7AA2)
val detailsBg = Color(0xff1B1D21)
val linkBg = Color(0xff1D2A32)
val link = Color(0xff489ACC)
val emptyThread = Color(0xff8CBD58)
val emptyMention = Color(0xffCE5838)
val emptySaved = Color(0xffCE375C)
}
val DarkColorPalette = darkColors(
primary = green700,
primaryVariant = green700,
secondary = graySurface,
background = slackBlack,
surface = slackBlack,
onPrimary = slackBlack,
onSecondary = lightGray,
onBackground = Color.White,
onSurface = Color.White,
error = Color.Red,
)
val LightColorPalette = lightColors(
primary = green700,
primaryVariant = green700,
secondary = lightGray,
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = graySurface,
onBackground = slackBlack,
onSurface = slackBlack
) | 0 | Kotlin | 14 | 264 | aa250c650654168378cf055b6024f0fdb2b18ee9 | 1,437 | ComposeSlackDesktop | Apache License 2.0 |
common/src/main/kotlin/tech/sethi/pebbles/pokeplushie/PM.kt | navneetset | 655,828,969 | false | null | package tech.sethi.pebbles.pokeplushie
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.TextDecoration
import net.kyori.adventure.text.minimessage.MiniMessage
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NbtList
import net.minecraft.nbt.NbtString
import net.minecraft.text.Text
object PM {
fun parseMessageWithStyles(text: String, placeholder: String): Component {
var mm = MiniMessage.miniMessage();
return mm.deserialize(text.replace("{placeholder}", placeholder)).decoration(TextDecoration.ITALIC, false)
}
fun returnStyledText(text: String): Text {
val component = parseMessageWithStyles(text, "placeholder")
val gson = GsonComponentSerializer.gson()
val json = gson.serialize(component)
return Text.Serializer.fromJson(json) as Text
}
fun returnStyledJson(text: String): String {
val component = parseMessageWithStyles(text, "placeholder")
val gson = GsonComponentSerializer.gson()
val json = gson.serialize(component)
return json
}
fun setLore(itemStack: ItemStack, lore: List<String>) {
val itemNbt = itemStack.getOrCreateSubNbt("display")
val loreNbt = NbtList()
for (line in lore) {
loreNbt.add(NbtString.of(returnStyledJson(line)))
}
itemNbt.put("Lore", loreNbt)
}
} | 0 | Kotlin | 0 | 0 | 76846c7d0d3673313d45c40e18896fdde3165b37 | 1,468 | pokeplushies | MIT License |
widget/src/main/java/com/uploadcare/android/widget/fragment/UploadcareChunkFragment.kt | uploadcare | 45,728,119 | false | {"Gradle Kotlin DSL": 5, "Markdown": 7, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "YAML": 5, "TOML": 1, "INI": 1, "Proguard": 3, "Java": 4, "XML": 43, "Kotlin": 100} | package com.uploadcare.android.widget.fragment
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.get
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.uploadcare.android.library.exceptions.UploadcareApiException
import com.uploadcare.android.widget.R
import com.uploadcare.android.widget.adapter.FilesAdapter
import com.uploadcare.android.widget.adapter.FilesGridAdapter
import com.uploadcare.android.widget.adapter.FilesLinearAdapter
import com.uploadcare.android.widget.controller.FileType
import com.uploadcare.android.widget.controller.SocialNetwork
import com.uploadcare.android.widget.data.Action
import com.uploadcare.android.widget.data.Chunk
import com.uploadcare.android.widget.data.SocialSource
import com.uploadcare.android.widget.data.Thing
import com.uploadcare.android.widget.databinding.UcwFragmentChunkBinding
import com.uploadcare.android.widget.utils.RecyclerViewOnScrollListener
import com.uploadcare.android.widget.viewmodels.UploadcareChunkViewModel
class UploadcareChunkFragment : Fragment(), SearchView.OnQueryTextListener {
private lateinit var binding: UcwFragmentChunkBinding
private lateinit var viewModel: UploadcareChunkViewModel
private lateinit var mOnFileActionsListener: OnFileActionsListener
private var mAdapter: FilesAdapter<*>? = null
private var mOnScrollListener: RecyclerViewOnScrollListener? = null
override fun onAttach(context: Context) {
super.onAttach(context)
mOnFileActionsListener = try {
if (parentFragment != null) {
parentFragment as OnFileActionsListener
} else {
context as OnFileActionsListener
}
} catch (e: ClassCastException) {
throw ClassCastException("Parent must implement OnFileActionsListener")
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
binding = UcwFragmentChunkBinding.inflate(inflater, container, false)
viewModel = ViewModelProvider(this).get()
binding.viewModel = viewModel
val socialSource = arguments?.getParcelable("socialSource") as SocialSource
binding.ucwRecyclerView.apply {
if (socialSource.name == SocialNetwork.SOCIAL_NETWORK_BOX.rawValue
|| socialSource.name == SocialNetwork.SOCIAL_NETWORK_DROPBOX.rawValue
|| socialSource.name == SocialNetwork.SOCIAL_NETWORK_EVERNOTE.rawValue
|| socialSource.name == SocialNetwork.SOCIAL_NETWORK_SKYDRIVE.rawValue
|| socialSource.name == SocialNetwork.SOCIAL_NETWORK_GDRIVE.rawValue) {
layoutManager = LinearLayoutManager(context)
mAdapter = FilesLinearAdapter(FileType.any) { thing ->
itemSelected(thing)
}
val pad = resources.getDimensionPixelSize(R.dimen.ucw_list_linear_padding)
setPadding(0, pad, 0, pad)
} else {
layoutManager = GridLayoutManager(context, resources.getInteger(R.integer.columns))
mAdapter = FilesGridAdapter(FileType.any) { thing ->
itemSelected(thing)
}
val pad = resources.getDimensionPixelSize(R.dimen.ucw_list_grid_padding)
setPadding(pad, pad, pad, pad)
}
adapter = mAdapter
}
binding.ucwSearchView.setOnQueryTextListener(this)
binding.ucwRecyclerView.layoutManager?.let {
mOnScrollListener = RecyclerViewOnScrollListener(it) {
viewModel.loadMore()
}
}
viewModel.things.observe(this.viewLifecycleOwner, Observer { things ->
mAdapter?.updateItems(things)
})
viewModel.allowLoadMore.observe(this.viewLifecycleOwner, Observer { allowLoadMore ->
if (allowLoadMore) {
mOnScrollListener?.let {
it.clear()
binding.ucwRecyclerView.addOnScrollListener(it)
}
} else {
binding.ucwRecyclerView.clearOnScrollListeners()
}
})
viewModel.errorCommand.observe(this.viewLifecycleOwner, Observer { exception ->
exception?.let { mOnFileActionsListener.onError(it) }
})
viewModel.needAuthCommand.observe(this.viewLifecycleOwner, Observer { loginLink ->
loginLink?.let { mOnFileActionsListener.onAuthorizationNeeded(loginLink) }
})
arguments?.let { viewModel.start(it) }
return binding.root
}
override fun onQueryTextSubmit(query: String?): Boolean {
viewModel.search(query)
return false
}
override fun onQueryTextChange(newText: String?) = false
fun getTitle(): String? {
return viewModel.title
}
fun changeChunk(position: Int) {
viewModel.changeChunk(position)
}
private fun itemSelected(thing: Thing) {
when (thing.objectType) {
Thing.TYPE_ALBUM,
Thing.TYPE_FOLDER,
Thing.TYPE_FRIEND -> {
thing.action?.path?.chunks?.let {
mOnFileActionsListener.onChunkSelected(it, thing.title ?: "")
}
}
Thing.TYPE_PHOTO,
Thing.TYPE_FILE -> {
thing.action?.url?.let {
if (thing.action.action == Action.ACTION_SELECT_FILE) {
mOnFileActionsListener.onFileSelected(it)
}
}
}
else -> {
Log.d("UploadcareChunkFragment", "Unknown thing type: ${thing.objectType}")
}
}
}
companion object {
/**
* Create a new instance of UploadcareChunkFragment, initialized to
* show the provided Chunk content.
*/
fun newInstance(currentRootChunk: Int,
socialSource: SocialSource,
chunks: List<Chunk>,
title: String? = null,
isRoot: Boolean = false): UploadcareChunkFragment {
return UploadcareChunkFragment().apply {
val args = Bundle().apply {
putInt("currentChunk", currentRootChunk)
putParcelable("socialSource", socialSource)
putParcelableArrayList("chunks", ArrayList(chunks))
putString("title", title)
putBoolean("isRoot", isRoot)
}
arguments = args
}
}
}
}
interface OnFileActionsListener {
fun onError(exception: UploadcareApiException)
fun onFileSelected(fileUrl: String)
fun onAuthorizationNeeded(loginLink: String)
fun onChunkSelected(chunks: List<Chunk>, title: String)
} | 1 | null | 1 | 1 | b55c3657d71b60c29ad46bc4ac5d64d336b8875d | 7,306 | uploadcare-android | Apache License 2.0 |
vk-api-base/src/main/kotlin/name/anton3/vkapi/vktypes/VkError.kt | Anton3 | 159,801,334 | true | {"Kotlin": 1382186} | package name.anton3.vkapi.vktypes
data class VkError(
val errorCode: Int,
val errorMsg: String,
val requestParams: List<MapEntry> = emptyList(),
val method: String? = null,
val errorText: String? = null,
val captchaSid: String? = null,
val captchaImg: String? = null,
val confirmationText: String? = null
) {
data class MapEntry(val key: String, val value: String)
override fun toString(): String = "$errorCode: $errorMsg"
}
| 2 | Kotlin | 0 | 8 | 773c89751c4382a42f556b6d3c247f83aabec625 | 467 | kotlin-vk-api | MIT License |
core/src/test/kotlin/com/expediagroup/sdk/core/model/ResponseTest.kt | ExpediaGroup | 527,522,338 | false | {"Kotlin": 2451817, "Mustache": 57012, "Shell": 715, "JavaScript": 606, "Makefile": 73} | /*
* Copyright (C) 2022 Expedia, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.expediagroup.sdk.core.model
import org.junit.jupiter.api.Test
class ResponseTest {
@Test
fun `test toHeadersMap`() {
val headers: Set<Map.Entry<String, List<String>>> =
setOf(
mapOf("key1" to listOf("value1")).entries.first(),
mapOf("key2" to listOf("value2")).entries.first()
)
val result = Response.toHeadersMap(headers)
assert(result.size == 2)
assert(result["key1"] == listOf("value1"))
assert(result["key2"] == listOf("value2"))
}
@Test
fun `test toString`() {
val response = Response(200, "body", mapOf("key" to listOf("value")))
val result = response.toString()
assert(result == "Response(statusCode=200, body=body, headers={key=[value]})")
}
@Test
fun `test EmptyResponse toString`() {
val response = EmptyResponse(200, mapOf("key" to listOf("value")))
val result = response.toString()
assert(result == "EmptyResponse(statusCode=200, headers={key=[value]})")
}
}
| 5 | Kotlin | 6 | 3 | eae5a990c2d7357cd4d3b92b8b486733ac2c0506 | 1,670 | expediagroup-java-sdk | Apache License 2.0 |
runtime/runtime-core/common/src/aws/smithy/kotlin/runtime/retries/delay/AdaptiveRateLimiter.kt | smithy-lang | 294,823,838 | false | null | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package aws.smithy.kotlin.runtime.retries.delay
import aws.smithy.kotlin.runtime.retries.policy.RetryErrorType
import aws.smithy.kotlin.runtime.util.DslFactory
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.math.*
import kotlin.time.*
import kotlin.time.Duration.Companion.seconds
/**
* A client-side rate limiter backed by a token bucket. This limiter adaptively updates the refill rate of the bucket
* based on the number of successful transactions vs throttling errors. This limiter applies a smoothing function in an
* attempt to converge on the ideal transaction rate feasible for downstream systems.
*/
@OptIn(ExperimentalTime::class)
public class AdaptiveRateLimiter internal constructor(
public override val config: Config = Config.Default,
private val timeSource: TimeSource,
private val rateMeasurer: AdaptiveRateMeasurer,
private val rateCalculator: CubicRateCalculator,
) : RateLimiter {
/**
* Initializes a new [AdaptiveRateLimiter]
* @param config The configuration parameters for this limiter
*/
public constructor(config: Config = Config.Default) : this(
config,
TimeSource.Monotonic,
AdaptiveRateMeasurer(config, TimeSource.Monotonic),
CubicRateCalculator(config, TimeSource.Monotonic),
)
public companion object : DslFactory<Config.Builder, AdaptiveRateLimiter> {
/**
* Initializes a new [AdaptiveRateLimiter]
* @param block A DSL block which sets the configuration parameters for this limiter
*/
public override operator fun invoke(block: Config.Builder.() -> Unit): AdaptiveRateLimiter =
AdaptiveRateLimiter(Config(Config.Builder().apply(block)))
}
private var capacity = 0.0
private var lastTimeMark: TimeMark? = null
internal var refillUnitsPerSecond = 0.0
private var maxCapacity = 0.0
private val mutex = Mutex()
override suspend fun acquire(cost: Int): Unit = mutex.withLock {
if (rateCalculator.throttlingEnabled) {
refillCapacity()
if (cost <= capacity) {
capacity -= cost
} else {
val extraRequiredCapacity = cost - capacity
val delayDuration = (extraRequiredCapacity / refillUnitsPerSecond).seconds
delay(delayDuration)
capacity = 0.0
}
}
}
private fun refillCapacity() {
lastTimeMark?.let {
val refillSeconds = it.elapsedNow().toDouble(DurationUnit.SECONDS)
val refillCapacity = refillUnitsPerSecond * refillSeconds
capacity = min(maxCapacity, capacity + refillCapacity)
}
lastTimeMark = timeSource.markNow()
}
override suspend fun update(errorType: RetryErrorType?): Unit = mutex.withLock {
val measuredTxRate = rateMeasurer.updateMeasuredRate()
val calculatedRate = rateCalculator.calculate(errorType, measuredTxRate, refillUnitsPerSecond)
val newRate = min(calculatedRate, 2 * measuredTxRate)
updateRefillRate(newRate)
}
private fun updateRefillRate(newRate: Double) {
refillCapacity()
refillUnitsPerSecond = max(newRate, config.minFillRate)
maxCapacity = max(newRate, config.minCapacity)
capacity = min(capacity, maxCapacity)
}
/**
* The configuration for an adaptive client-side rate limiter
*/
public class Config(builder: Builder) : RateLimiter.Config {
public companion object {
/**
* The default configuration
*/
public val Default: Config = Config(Builder())
}
/**
* How much to scale back after receiving a throttling response. Ranges from 0.0 (do not scale back) to 1.0
* (scale back completely). Defaults to 0.7 (scale back 70%).
*
* **Note**: This is an advanced parameter and modifying it is not recommended.
*/
public val beta: Double = builder.beta
/**
* The duration of individual measurement buckets used in measuring the effective transaction rate. Defaults to
* 0.5 seconds.
*/
public val measurementBucketDuration: Duration = builder.measurementBucketDuration
/**
* The minimum capacity of permits. Defaults to 1.
*/
public val minCapacity: Double = builder.minCapacity
/**
* The minimum refill rate (per second) of permits. Defaults to 0.5.
*/
public val minFillRate: Double = builder.minFillRate
/**
* How much to scale up after receiving a successful response. Ranges from 0.0 (do not scale up) to 1.0 (scale
* up completely). Defaults to 0.4 (scale up 40%).
*
* **Note**: This is an advanced parameter and modifying it is not recommended.
*/
public val scaleConstant: Double = builder.scaleConstant
/**
* The exponential smoothing factor to apply when measuring the effective rate of transactions. Ranges from 0.0
* (do not accept new rate updates) to 1.0 (immediately accept new rates with no smoothing). Defaults to 0.8
* (new rates are factored into the measured rate at 80%).
*
* **Note**: This is an advanced parameter and modifying it is not recommended.
*/
public val smoothing: Double = builder.smoothing
override fun toBuilderApplicator(): RateLimiter.Config.Builder.() -> Unit = {
if (this is Builder) {
beta = [email protected]
measurementBucketDuration = [email protected]
minCapacity = [email protected]
minFillRate = [email protected]
scaleConstant = [email protected]
smoothing = [email protected]
}
}
public class Builder : RateLimiter.Config.Builder {
/**
* How much to scale back after receiving a throttling response. Ranges from 0.0 (do not scale back) to 1.0
* (scale back completely). Defaults to 0.7 (scale back 70%).
*
* **Note**: This is an advanced parameter and modifying it is not recommended.
*/
public var beta: Double = 0.7
/**
* The duration of individual measurement buckets used in measuring the effective transaction rate. Defaults
* to 0.5 seconds.
*/
public var measurementBucketDuration: Duration = 0.5.seconds
/**
* The minimum capacity of permits. Defaults to 1.
*/
public var minCapacity: Double = 1.0
/**
* The minimum refill rate (per second) of permits. Defaults to 0.5.
*/
public var minFillRate: Double = 0.5
/**
* How much to scale up after receiving a successful response. Ranges from 0.0 (do not scale up) to 1.0
* (scale up completely). Defaults to 0.4 (scale up 40%).
*
* **Note**: This is an advanced parameter and modifying it is not recommended.
*/
public var scaleConstant: Double = 0.4
/**
* The exponential smoothing factor to apply when measuring the effective rate of transactions. Ranges from
* 0.0 (do not accept new rate updates) to 1.0 (immediately accept new rates with no smoothing). Defaults to
* 0.8 (new rates are factored into the measured rate at 80%).
*
* **Note**: This is an advanced parameter and modifying it is not recommended.
*/
public var smoothing: Double = 0.8
}
}
}
@OptIn(ExperimentalTime::class)
internal class CubicRateCalculator(
private val config: AdaptiveRateLimiter.Config,
private val timeSource: TimeSource = TimeSource.Monotonic,
internal var lastMaxRate: Double = 0.0,
internal var lastThrottleTime: TimeMark = timeSource.markNow(),
) {
var throttlingEnabled: Boolean = false
private set
internal var timeWindow: Double = calculateTimeWindow()
fun calculate(
errorType: RetryErrorType?,
measuredTxRate: Double,
refillUnitsPerSecond: Double,
): Double {
val calculatedRate = if (errorType == RetryErrorType.Throttling) {
lastMaxRate = if (throttlingEnabled) min(measuredTxRate, refillUnitsPerSecond) else measuredTxRate
timeWindow = calculateTimeWindow()
lastThrottleTime = timeSource.markNow()
throttlingEnabled = true
cubicThrottle(lastMaxRate)
} else {
cubicSuccess()
}
return calculatedRate
}
internal fun calculateTimeWindow() = cbrt((lastMaxRate * (1 - config.beta)) / config.scaleConstant)
internal fun cubicSuccess(): Double {
val deltaSeconds = lastThrottleTime.elapsedNow().toDouble(DurationUnit.SECONDS)
return (config.scaleConstant * (deltaSeconds - timeWindow).pow(3) + lastMaxRate)
}
internal fun cubicThrottle(rate: Double) = rate * config.beta
}
@OptIn(ExperimentalTime::class)
internal class AdaptiveRateMeasurer(
private val config: AdaptiveRateLimiter.Config,
private val timeSource: TimeSource,
private var lastTxBucketMark: TimeMark = timeSource.markNow(),
internal var measuredTxRate: Double = 0.0,
private var requestCount: Int = 0,
) {
private val bucketsPerSecond = 1 / config.measurementBucketDuration.toDouble(DurationUnit.SECONDS)
fun updateMeasuredRate(): Double {
requestCount++
val delta = lastTxBucketMark.elapsedNow()
val bucketDelta = floor(delta / config.measurementBucketDuration)
if (bucketDelta >= 1.0) {
val currentRate = requestCount / bucketDelta * bucketsPerSecond
measuredTxRate = (currentRate * config.smoothing) + (measuredTxRate * (1 - config.smoothing))
lastTxBucketMark = lastTxBucketMark + bucketDelta * config.measurementBucketDuration
requestCount = 0
}
return measuredTxRate
}
}
| 36 | null | 26 | 82 | ad18e2fb043f665df9add82083c17877a23f8610 | 10,431 | smithy-kotlin | Apache License 2.0 |
app/src/main/java/com/steve_md/cryptocurrency/presentation/screens/coins_screen/CoinsViewModel.kt | MuindiStephen | 637,714,830 | false | null | package com.steve_md.cryptocurrency.presentation.screens.coins_screen
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.steve_md.cryptocurrency.common.Resource
import com.steve_md.cryptocurrency.domain.model.Coin
import com.steve_md.cryptocurrency.domain.usecases.coin.CoinUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
@HiltViewModel
class CoinsViewModel @Inject constructor(
private val coinUseCase: CoinUseCase
) : ViewModel() {
private val _coinState = mutableStateOf(CoinsState())
val coinState:State<CoinsState>
get() = _coinState
init {
getAllCoins()
}
private fun getAllCoins() {
coinUseCase().onEach { response ->
when(response) {
is Resource.Loading -> {
_coinState.value = CoinsState(loading = true)
}
is Resource.Error -> {
// _coinState.value = response.message?.let { CoinsState(error = it) }!!
_coinState.value = CoinsState(error = response.message ?: "An unexpected error occurred!")
}
is Resource.Success -> {
_coinState.value = CoinsState(listOfCoins = response.data ?: emptyList())
}
}
}.launchIn(viewModelScope)
}
}
data class CoinsState(
val listOfCoins: List<Coin> = emptyList(),
val loading: Boolean = false,
val error: String = ""
) | 0 | Kotlin | 0 | 0 | d40cb8831fb24e03b00ccaa17287c310804c7c4f | 1,667 | Crypto.com | MIT License |
support/rabbit-support/src/main/kotlin/io.initialcapacity.rabbitsupport/Listener.kt | patat | 793,524,335 | false | {"Kotlin": 54775, "CSS": 8759, "FreeMarker": 7381, "JavaScript": 848, "Shell": 556, "Dockerfile": 214, "Procfile": 90} | package io.initialcapacity.rabbitsupport
import com.rabbitmq.client.Channel
import com.rabbitmq.client.Delivery
import kotlinx.coroutines.runBlocking
data class RabbitQueue(val name: String)
fun listen(channel: Channel, queue: RabbitQueue, handler: suspend (String) -> Unit): String {
val delivery = { _: String, message: Delivery -> runBlocking { handler(message.body.decodeToString()) } }
val cancel = { _: String -> }
return channel.basicConsume(queue.name, true, delivery, cancel)
}
| 0 | Kotlin | 0 | 0 | dff454ac1190cdf5ae14a2cf61d0371cc9f96881 | 503 | mbapp | Apache License 2.0 |
support/rabbit-support/src/main/kotlin/io.initialcapacity.rabbitsupport/Listener.kt | patat | 793,524,335 | false | {"Kotlin": 54775, "CSS": 8759, "FreeMarker": 7381, "JavaScript": 848, "Shell": 556, "Dockerfile": 214, "Procfile": 90} | package io.initialcapacity.rabbitsupport
import com.rabbitmq.client.Channel
import com.rabbitmq.client.Delivery
import kotlinx.coroutines.runBlocking
data class RabbitQueue(val name: String)
fun listen(channel: Channel, queue: RabbitQueue, handler: suspend (String) -> Unit): String {
val delivery = { _: String, message: Delivery -> runBlocking { handler(message.body.decodeToString()) } }
val cancel = { _: String -> }
return channel.basicConsume(queue.name, true, delivery, cancel)
}
| 0 | Kotlin | 0 | 0 | dff454ac1190cdf5ae14a2cf61d0371cc9f96881 | 503 | mbapp | Apache License 2.0 |
app/src/main/java/com/linuxluigi/staticwebsitekioskapp/MainActivity.kt | linuxluigi | 113,499,713 | false | null | package com.linuxluigi.staticwebsitekioskapp
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
WebViewBtn.setOnClickListener {
// Handler code here.
val intent = Intent(this@MainActivity, WebBrowserActivity::class.java)
startActivity(intent)
}
}
}
| 0 | Kotlin | 0 | 1 | 07388e44c686d5081af1515610d50a4316dc7ed1 | 605 | StaticWebsiteKioskApp | MIT License |
LeetCode/ReverseInteger.kt | EngincanCicek | 644,035,976 | false | null | class Solution {
fun reverse(n: Int): Int {
var isNegative: Boolean = false
var text: String = n.toString();
if (text.contains("-")) {
text = text.replace("-", "")
isNegative = true
}
try {
var reversedInt: Int = text.reversed().toInt()
if (isNegative) return (reversedInt * -1)
else return reversedInt
} catch (e: Exception) {
return 0
}
}
} | 2 | Kotlin | 0 | 0 | 62f56657cd440f7abc110004ac53b4ebcdc3b4a0 | 431 | LeetCode-HackerRank-Solutions | MIT License |
backend/services/attendee-service/src/main/kotlin/com/puconvocation/plugins/Routing.kt | mihirpaldhikar | 796,559,467 | false | {"Kotlin": 75366, "TypeScript": 17969, "JavaScript": 1235, "CSS": 559} | /*
* Copyright (c) PU Convocation Management System Authors
*
* This software is owned by PU Convocation Management System Authors.
* No part of the software is allowed to be copied or distributed
* in any form. Any attempt to do so will be considered a violation
* of copyright law.
*
* This software is protected by copyright law and international
* treaties. Unauthorized copying or distribution of this software
* is a violation of these laws and could result in severe penalties.
*/
package com.puconvocation.plugins
import com.puconvocation.controllers.AttendeeController
import com.puconvocation.routes.attendeesRoute
import io.ktor.server.application.*
import io.ktor.server.routing.*
import org.koin.java.KoinJavaComponent
fun Application.configureRouting() {
val attendeeController by KoinJavaComponent.inject<AttendeeController>(AttendeeController::class.java)
routing {
attendeesRoute(attendeeController = attendeeController)
}
}
| 0 | Kotlin | 0 | 0 | 8ef52093dd1d48daae4f261e6c599d3e332f79f2 | 976 | pu-convocation | Freetype Project License |
app/src/main/java/com/frogobox/wallpaper/mvvm/wallpaper/WallpaperPixabayViewModel.kt | amirisback | 247,242,834 | false | null | package com.frogobox.wallpaper.mvvm.wallpaper
import android.app.Application
import com.frogobox.api.pixabay.model.PixabayImage
import com.frogobox.api.pixabay.response.Response
import com.frogobox.sdk.core.FrogoLiveEvent
import com.frogobox.sdk.core.FrogoViewModel
import com.frogobox.wallpaper.model.Wallpaper
import com.frogobox.wallpaper.source.FrogoDataRepository
import com.frogobox.wallpaper.source.FrogoDataSource
import com.frogobox.wallpaper.util.ConstHelper
/**
* Created by <NAME>
* FrogoBox Inc License
* =========================================
* BaseWallpaperApp
* Copyright (C) 22/12/2019.
* All rights reserved
* -----------------------------------------
* Name : <NAME>
* E-mail : <EMAIL>
* Github : github.com/amirisback
* LinkedIn : linkedin.com/in/faisalamircs
* -----------------------------------------
* FrogoBox Software Industries
* com.frogobox.wallpaper.viewmodel
*
*/
class WallpaperPixabayViewModel(
private val context: Application,
private val repository: FrogoDataRepository
) :
FrogoViewModel(context) {
private val TOPIC_WALLPAPER = "Nature"
var wallpaperListLive = FrogoLiveEvent<MutableList<Wallpaper>>()
private fun arrayFanArt(pixabayApi: Response<PixabayImage>): MutableList<Wallpaper> {
val arrayWallpaper = mutableListOf<Wallpaper>()
for (i in pixabayApi.hits!!.indices) {
arrayWallpaper.add(
Wallpaper(
(ConstHelper.Const.TYPE_MAIN_WALLPAPER + i),
pixabayApi.hits!![i].largeImageURL
)
)
}
return arrayWallpaper
}
fun searchImage() {
repository.searchImage(
TOPIC_WALLPAPER,
object : FrogoDataSource.GetResponseDataCallback<Response<PixabayImage>> {
override fun onShowProgressDialog() {
eventShowProgress.postValue(true)
}
override fun onHideProgressDialog() {
eventShowProgress.postValue(false)
}
override fun onSuccess(data: Response<PixabayImage>) {
val listWallpaper = arrayFanArt(data)
wallpaperListLive.postValue(listWallpaper)
}
override fun onEmpty() {
eventEmptyData.postValue(true)
}
override fun onFinish() {}
override fun onFailed(statusCode: Int, errorMessage: String?) {
eventFailed.postValue(errorMessage)
}
})
}
}
| 0 | Kotlin | 1 | 7 | 52ccbf4198279ee8f39cab40ae3a5e23ec904821 | 2,614 | wallpaper | Apache License 2.0 |
app/src/main/java/com/kirakishou/photoexchange/mvp/viewmodel/factory/TakePhotoActivityViewModelFactory.kt | chanyaz | 143,974,243 | true | {"Kotlin": 639219} | package com.kirakishou.photoexchange.mvp.viewmodel.factory
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import com.kirakishou.photoexchange.helper.concurrency.rx.scheduler.SchedulerProvider
import com.kirakishou.photoexchange.helper.database.repository.TakenPhotosRepository
import com.kirakishou.photoexchange.mvp.viewmodel.TakePhotoActivityViewModel
import javax.inject.Inject
/**
* Created by kirakishou on 11/7/2017.
*/
class TakePhotoActivityViewModelFactory
@Inject constructor(
val takenPhotosRepository: TakenPhotosRepository,
val schedulerProvider: SchedulerProvider
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return TakePhotoActivityViewModel(schedulerProvider, takenPhotosRepository) as T
}
} | 0 | Kotlin | 0 | 0 | 078a56b34b84f7121cac7ffac5ac7d6a0e39fb9a | 860 | photoexchange-android | Do What The F*ck You Want To Public License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/ClockFive.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
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.rounded.Icons
public val Icons.Filled.ClockFive: ImageVector
get() {
if (_clockFive != null) {
return _clockFive!!
}
_clockFive = Builder(name = "ClockFive", 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.0f, 0.0f)
curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f)
reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f)
close()
moveTo(14.5f, 16.33f)
curveToRelative(-0.157f, 0.091f, -0.329f, 0.134f, -0.499f, 0.134f)
curveToRelative(-0.346f, 0.0f, -0.682f, -0.179f, -0.867f, -0.5f)
lineToRelative(-2.0f, -3.464f)
curveToRelative(-0.088f, -0.152f, -0.134f, -0.324f, -0.134f, -0.5f)
lineTo(11.0f, 6.0f)
curveToRelative(0.0f, -0.552f, 0.447f, -1.0f, 1.0f, -1.0f)
reflectiveCurveToRelative(1.0f, 0.448f, 1.0f, 1.0f)
verticalLineToRelative(5.732f)
lineToRelative(1.866f, 3.232f)
curveToRelative(0.276f, 0.478f, 0.112f, 1.09f, -0.366f, 1.366f)
close()
}
}
.build()
return _clockFive!!
}
private var _clockFive: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,256 | icons | MIT License |
core/android/src/androidTest/kotlin/com/reown/android/test/activity/WCInstrumentedActivityScenario.kt | reown-com | 851,466,242 | false | null | package com.walletconnect.android.test.activity
import androidx.lifecycle.Lifecycle
import androidx.test.core.app.ActivityScenario
import com.walletconnect.android.BuildConfig
import com.walletconnect.android.internal.common.scope
import com.walletconnect.android.test.utils.TestClient
import com.walletconnect.foundation.network.model.Relay
import junit.framework.TestCase.assertTrue
import junit.framework.TestCase.fail
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import timber.log.Timber
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.time.Duration.Companion.seconds
class WCInstrumentedActivityScenario : TestRule {
private var scenario: ActivityScenario<InstrumentedTestActivity>? = null
private var scenarioLaunched: Boolean = false
private val latch = CountDownLatch(1)
private val testScope: CoroutineScope = CoroutineScope(Dispatchers.Default)
override fun apply(base: Statement, description: Description): Statement {
return object : Statement() {
override fun evaluate() {
beforeAll()
base.evaluate()
afterAll()
}
}
}
private fun initLogging() {
if (Timber.treeCount == 0) {
Timber.plant(
object : Timber.DebugTree() {
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
super.log(priority, "WalletConnectV2", message, t)
}
}
)
}
}
private fun beforeAll() {
runBlocking(testScope.coroutineContext) {
initLogging()
Timber.d("init")
val isDappRelayReady = MutableStateFlow(false)
val isWalletRelayReady = MutableStateFlow(false)
val timeoutDuration = BuildConfig.TEST_TIMEOUT_SECONDS.seconds
val dappRelayJob = TestClient.Secondary.Relay.eventsFlow.onEach { event ->
when (event) {
is Relay.Model.Event.OnConnectionOpened<*> -> isDappRelayReady.compareAndSet(expect = false, update = true)
else -> {}
}
}.launchIn(scope)
val walletRelayJob = TestClient.Primary.Relay.eventsFlow.onEach { event ->
when (event) {
is Relay.Model.Event.OnConnectionOpened<*> -> isWalletRelayReady.compareAndSet(expect = false, update = true)
else -> {}
}
}.launchIn(scope)
runCatching {
withTimeout(timeoutDuration) {
while (!(isDappRelayReady.value && isWalletRelayReady.value && TestClient.Primary.isInitialized.value && TestClient.Secondary.isInitialized.value)) {
delay(100)
}
}
}.fold(
onSuccess = { Timber.d("Connection established with successfully") },
onFailure = { fail("Unable to establish connection within $timeoutDuration") }
)
dappRelayJob.cancel()
walletRelayJob.cancel()
}
}
private fun afterAll() {
Timber.d("afterAll")
scenario?.close()
}
fun launch(timeoutSeconds: Long = 1, testCodeBlock: suspend (scope: CoroutineScope) -> Unit) {
require(!scenarioLaunched) { "Scenario has already been launched!" }
scenario = ActivityScenario.launch(InstrumentedTestActivity::class.java)
scenarioLaunched = true
scenario?.moveToState(Lifecycle.State.RESUMED)
assert(scenario?.state?.isAtLeast(Lifecycle.State.RESUMED) == true)
testScope.launch { testCodeBlock(testScope) }
try {
assertTrue(latch.await(timeoutSeconds, TimeUnit.SECONDS))
} catch (exception: Exception) {
fail(exception.message)
}
}
fun closeAsSuccess() {
latch.countDown()
}
} | 78 | null | 71 | 8 | 893084b3df91b47daa77f8f964e37f84a02843b1 | 4,403 | reown-kotlin | Apache License 2.0 |
projects/prisoner-profile-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/api/model/ProbationDocumentsResponse.kt | ministryofjustice | 500,855,647 | false | {"Kotlin": 4354937, "HTML": 70066, "D2": 44286, "Ruby": 25921, "Shell": 19356, "SCSS": 6370, "HCL": 2712, "Dockerfile": 2447, "JavaScript": 1372, "Python": 268} | package uk.gov.justice.digital.hmpps.api.model
data class ProbationDocumentsResponse(
val crn: String,
val name: Name,
val documents: List<Document>,
val convictions: List<Conviction>
)
| 4 | Kotlin | 0 | 2 | bafb32470fd72f96026e8e8c53a636778c6abacf | 203 | hmpps-probation-integration-services | MIT License |
kotlin/2022/day01/Day01Tests.kt | nathanjent | 48,783,324 | false | {"Rust": 147170, "Go": 52936, "Kotlin": 49570, "Shell": 966} | import org.junit.Test
import org.junit.Assert.*
import java.io.File
class Day01Tests {
private val inputFile = "day01/input.txt"
private val day = Day01()
private val exampleInput = """
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
""".split("\n")
@Test
fun example1Test() {
val expected = 24000
assertEquals(expected, day.part1(exampleInput))
}
@Test
fun part1Test() {
val input = File(inputFile).readLines()
val expected = 66487
assertEquals(expected, day.part1(input))
}
@Test
fun example2Test() {
val expected = 45000
assertEquals(expected, day.part2(exampleInput))
}
@Test
fun part2Test() {
val input = File(inputFile).readLines()
val expected = 197301
assertEquals(expected, day.part2(input))
}
} | 0 | Rust | 0 | 0 | 7e1d66d2176beeecaac5c3dde94dccdb6cfeddcf | 799 | adventofcode | MIT License |
src/main/java/it/smartphonecombo/uecapabilityparser/model/combo/ComboNr.kt | HandyMenny | 539,436,833 | false | null | package it.smartphonecombo.uecapabilityparser.model.combo
import it.smartphonecombo.uecapabilityparser.extension.populateCsvStringBuilders
import it.smartphonecombo.uecapabilityparser.model.BCS
import it.smartphonecombo.uecapabilityparser.model.EmptyBCS
import it.smartphonecombo.uecapabilityparser.model.component.ComponentNr
import it.smartphonecombo.uecapabilityparser.model.component.IComponent
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
@Serializable
data class ComboNr(
@SerialName("components") override val masterComponents: List<ComponentNr>,
@Transient override val featureSet: Int = 0,
override val bcs: BCS = EmptyBCS
) : ICombo {
override val secondaryComponents
get() = emptyList<IComponent>()
val componentsNr: List<ComponentNr>
get() = masterComponents
override fun toCompactStr(): String {
val nr =
componentsNr.joinToString(
separator = "-",
transform = IComponent::toCompactStr,
)
val bcsString = if (bcs == EmptyBCS) "" else "-${bcs.toCompactStr()}"
return "$nr$bcsString"
}
override fun toCsv(
separator: String,
lteDlCC: Int,
lteUlCC: Int,
nrDlCC: Int,
nrUlCC: Int,
nrDcDlCC: Int,
nrDcUlCC: Int
): String {
val compact = this.toCompactStr() + separator
val nrBandBwScs = StringBuilder()
val nrUlBwMod = StringBuilder()
val nrMimoDl = StringBuilder()
val nrMimoUl = StringBuilder()
componentsNr.populateCsvStringBuilders(
nrBandBwScs,
nrMimoDl,
nrUlBwMod,
nrMimoUl,
nrDlCC,
nrUlCC,
separator
)
return "$compact$nrBandBwScs$nrUlBwMod$nrMimoDl$nrMimoUl$bcs"
}
}
| 2 | Kotlin | 7 | 9 | 503c209f73411095ae0a413bb719bc760db871d8 | 1,909 | uecapabilityparser | MIT License |
app/src/main/java/org/nekomanga/presentation/components/AppBarActions.kt | androiddevnotesforks | 388,576,956 | true | {"Kotlin": 3018671} | package org.nekomanga.presentation.components
import ToolTipIconButton
import androidx.compose.foundation.layout.Row
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.ViewList
import androidx.compose.material.icons.filled.ViewModule
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import eu.kanade.tachiyomi.R
import org.nekomanga.presentation.theme.NekoTheme
@Composable
fun ListGridActionButton(isList: Boolean, buttonClicked: () -> Unit) {
when (isList.not()) {
true -> ToolTipIconButton(
toolTipLabel = stringResource(id = R.string.display_as_, "list"),
icon = Icons.Filled.ViewList,
buttonClicked = buttonClicked,
)
false -> ToolTipIconButton(
toolTipLabel = stringResource(id = R.string.display_as_, "grid"),
icon = Icons.Filled.ViewModule,
buttonClicked = buttonClicked,
)
}
}
@Preview
@Composable
private fun ListGridActionButton() {
Row {
NekoTheme {
ListGridActionButton(isList = false) {}
}
NekoTheme {
ListGridActionButton(isList = true) {}
}
}
}
@Composable
fun AppBarActions(
actions: List<AppBar.AppBarAction>,
) {
var showMenu by remember { mutableStateOf(false) }
actions.filterIsInstance<AppBar.Action>().map {
ToolTipIconButton(
toolTipLabel = it.title,
icon = it.icon,
isEnabled = it.isEnabled,
buttonClicked = it.onClick,
)
}
val overflowActions = actions.filterIsInstance<AppBar.OverflowAction>()
if (overflowActions.isNotEmpty()) {
ToolTipIconButton(
toolTipLabel = stringResource(R.string.more),
icon = Icons.Filled.MoreVert,
buttonClicked = { showMenu = !showMenu },
)
SimpleDropdownMenu(
expanded = showMenu,
onDismiss = { showMenu = false },
dropDownItems =
overflowActions.map { appBarAction ->
appBarAction.toSimpleAction()
},
)
}
}
object AppBar {
interface AppBarAction
data class Action(
val title: String,
val icon: ImageVector,
val onClick: () -> Unit,
val isEnabled: Boolean = true,
) : AppBarAction
data class OverflowAction(
val title: String,
val onClick: (() -> Unit?)? = null,
val children: List<OverflowAction>? = null,
) : AppBarAction {
fun toSimpleAction(): SimpleDropDownItem {
return if (children == null) {
SimpleDropDownItem.Action(title, onClick = { onClick?.invoke() })
} else {
SimpleDropDownItem.Parent(title, children = children.map { it.toSimpleAction() })
}
}
}
object Empty : AppBarAction
}
| 1 | Kotlin | 0 | 0 | 4925e28fdf4490004372eae120b738470fbeea58 | 3,253 | Neko | Apache License 2.0 |
app/src/main/java/com/blaccoder/travelmantics/FirebaseUtils.kt | odaridavid | 200,026,560 | false | null | package com.blaccoder.travelmantics
import android.content.Context
import android.content.Intent
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.blaccoder.travelmantics.model.TravelDealTimestamped
import com.blaccoder.travelmantics.ui.showShortMessage
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
/**
* Created By <NAME>
* On 01/08/19
*
**/
const val RC_SIGN_IN = 1000
val providers = mutableListOf(
AuthUI.IdpConfig.EmailBuilder().build(),
AuthUI.IdpConfig.PhoneBuilder().build(),
AuthUI.IdpConfig.GoogleBuilder().build()
)
fun authUiIntent(): Intent {
return AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setIsSmartLockEnabled(true)
.build()
}
object FirebaseRoles {
//TODO Move to viewmodel
private const val ADMIN_COLLECTION = "admin"
private val _isAdmin: MutableLiveData<Boolean> by lazy { MutableLiveData<Boolean>() }
val isAdmin: LiveData<Boolean>
get() = _isAdmin
fun isAdmin(db: FirebaseFirestore, uid: String) {
db.collection(ADMIN_COLLECTION)
.get()
.addOnCompleteListener { querySnapshot ->
for (docs in querySnapshot.result!!.documents) {
_isAdmin.value = uid == docs.id
}
}
}
}
fun logOut(context: Context) {
AuthUI.getInstance()
.signOut(context)
.addOnCompleteListener {
showShortMessage(context, context.getString(R.string.message_signed_out))
}
}
fun getTravelDeals(query: Query): FirestoreRecyclerOptions<TravelDealTimestamped> {
return FirestoreRecyclerOptions.Builder<TravelDealTimestamped>()
.setQuery(query) { docSnapshot ->
TravelDealTimestamped(
docSnapshot["title"] as String?,
docSnapshot["description"] as String?,
docSnapshot["price"] as String?,
docSnapshot["imageUrl"] as String?,
docSnapshot.id,
docSnapshot["timeStamp"] as String?
)
}
.build()
}
val query = FirebaseFirestore.getInstance().collection(DEALS_COLLECTION).orderBy(TRAVEL_DEAL_PRICE_FIELD)
| 5 | Kotlin | 1 | 5 | 2f17c16b0eb87af05bd768a3a9de3f0fadd5ae08 | 2,393 | Travelmantics | Apache License 2.0 |
ui-common/src/main/java/sk/kasper/ui_common/theme/Typography.kt | BME-MIT-IET | 484,162,194 | false | {"Kotlin": 310878, "JavaScript": 10504, "Shell": 251} | package sk.kasper.ui_common.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import sk.kasper.ui_common.R
val Montserrat = FontFamily(
Font(R.font.montserrat_regular),
Font(R.font.montserrat_medium, FontWeight.Medium),
Font(R.font.montserrat_bold, FontWeight.Bold),
Font(R.font.montserrat_semibold, FontWeight.SemiBold),
)
val SourceSansPro = FontFamily(
Font(R.font.source_sans_pro_regular),
Font(R.font.source_sans_pro_semibold, FontWeight.SemiBold),
Font(R.font.source_sans_pro_bold, FontWeight.Bold),
)
val SpaceTypography = Typography(
h1 = TextStyle(
fontFamily = Montserrat,
fontSize = 96.sp
),
h2 = TextStyle(
fontFamily = Montserrat,
fontSize = 60.sp
),
h3 = TextStyle(
fontFamily = Montserrat,
fontSize = 48.sp
),
h4 = TextStyle(
fontFamily = Montserrat,
fontWeight = FontWeight.Medium,
fontSize = 32.sp
),
h5 = TextStyle(
fontFamily = Montserrat,
fontWeight = FontWeight.Medium,
fontSize = 24.sp
),
h6 = TextStyle(
fontFamily = Montserrat,
fontWeight = FontWeight.Normal,
fontSize = 22.sp
),
subtitle1 = TextStyle(
fontFamily = Montserrat,
fontWeight = FontWeight.Normal,
fontSize = 18.sp,
letterSpacing = 0.15.sp
),
subtitle2 = TextStyle(
fontFamily = Montserrat,
fontSize = 16.sp,
fontWeight = FontWeight.Medium,
),
body1 = TextStyle(
fontFamily = SourceSansPro,
fontSize = 18.sp,
letterSpacing = 0.5.sp
),
body2 = TextStyle(
fontFamily = SourceSansPro,
fontSize = 16.sp,
letterSpacing = 0.25.sp
),
button = TextStyle(
fontFamily = SourceSansPro,
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp,
letterSpacing = 1.25.sp
),
caption = TextStyle(
fontFamily = SourceSansPro,
fontSize = 14.sp
),
overline = TextStyle(
fontFamily = SourceSansPro,
fontSize = 12.sp,
letterSpacing = 1.5.sp
)
)
val section: TextStyle
get() = TextStyle(
fontWeight = FontWeight.Medium,
fontFamily = Montserrat,
fontSize = 22.sp
)
| 10 | Kotlin | 0 | 2 | d53a13dde49828c5ec473774408aab1ecae26952 | 2,502 | iet-hf-2022-houston | Apache License 2.0 |
app/src/main/java/com/alexandros/e_health/activities/DiagnosesShareFragment.kt | alexioan7 | 409,163,653 | false | null | package com.alexandros.e_health.activities
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ArrayAdapter
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.alexandros.e_health.R
import com.alexandros.e_health.api.responseModel.HospitalsDetails
import com.alexandros.e_health.api.responseModel.HospitalsUserResponse
import com.alexandros.e_health.databinding.FragmentDiagnosesShareBinding
import com.alexandros.e_health.repositories.AuthRepository
import com.alexandros.e_health.utils.toast
import com.alexandros.e_health.viewmodels.AuthFunctionsHospitalByPresc
import com.alexandros.e_health.viewmodels.AuthFunctionsShareDiagnoses
import com.alexandros.e_health.viewmodels.DiagnosesShareViewModel
import com.alexandros.e_health.viewmodels.ViewModelFactory
class DiagnosesShareFragment: Fragment(R.layout.fragment_diagnoses_share) ,AuthFunctionsShareDiagnoses, AuthFunctionsHospitalByPresc{
private lateinit var binding: FragmentDiagnosesShareBinding
private lateinit var viewmodel: DiagnosesShareViewModel
private val hosp = mutableListOf<HospitalsDetails>()
private lateinit var arrayAdapterShared: ArrayAdapter<*>
private val arrayOfSharedDiagnoses = mutableListOf<HospitalsDetails>()
private lateinit var arrayAdapter: ArrayAdapter<*>
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
hosp.clear()
arrayOfSharedDiagnoses.clear()
arrayAdapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_checked, hosp)
arrayAdapterShared = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, arrayOfSharedDiagnoses)
arrayAdapter.notifyDataSetChanged()
arrayAdapterShared.notifyDataSetChanged()
val diagid = arguments?.getString("diagnosisID")
Log.d("Diagnosis id:", "$diagid")
binding = FragmentDiagnosesShareBinding.bind(view)
viewmodel = ViewModelProvider(requireActivity(), ViewModelFactory(AuthRepository)).get(DiagnosesShareViewModel::class.java)
var myHospitalByDiagList = binding.hospitalsByDiagList
myHospitalByDiagList.adapter = arrayAdapterShared
var myHospitalList= binding.hospitalsList
myHospitalList.adapter = arrayAdapter
if(diagid != null){
viewmodel.requestHospitalsBySharedDiagnoses(diagid)
}
viewmodel.authListenerdiag=this
viewmodel.authHospitalListenerpresc=this
viewmodel.getHospitalsFromRepo().observe(viewLifecycleOwner, {
Log.d("HOSPITALS", it.data.hospitals.toString())
var tempHosp = mutableListOf<HospitalsDetails>()
tempHosp.addAll(it.data.hospitals)
if(arrayOfSharedDiagnoses.size != 0) {
tempHosp.removeAll(arrayOfSharedDiagnoses)
}
hosp.clear()
arrayAdapter.notifyDataSetChanged()
hosp.addAll(tempHosp)
arrayAdapter.notifyDataSetChanged()
})
viewmodel.getHospitalsByDiag().observe(viewLifecycleOwner,{
viewmodel.requestHospitals()
arrayOfSharedDiagnoses.clear()
arrayAdapterShared.notifyDataSetChanged()
arrayOfSharedDiagnoses.addAll(it.data.hospitals)
arrayAdapterShared.notifyDataSetChanged()
})
viewmodel.getErrorFromRepo().observe(viewLifecycleOwner, {
viewmodel.requestHospitals()
})
binding.sharebutton.setOnClickListener {
val position = binding.hospitalsList.checkedItemPosition
if(hosp.size != 0 && position != -1) {
var hospital_id = hosp[position]._id
var diagnosis_id = diagid
var hospital_name = hosp[position].name
viewmodel.onShareButtonClick(hospital_name, hospital_id, diagnosis_id.toString())
}
}
binding.backToDiagnoses.setOnClickListener {
findNavController().navigate(R.id.action_diagnosesShareFragment_to_diagnosesFragment)
}
}
override fun onSuccessDiagnosesShare(hospitalName: String) {
Log.d("In success","In onsuccssPrescriptionShare")
toast("You have successfully shared your diagnosis with $hospitalName", activity)
//Toast.makeText(activity, "You successfully shared your prescription with $hospitalName", Toast.LENGTH_SHORT).show()
for(hospital in hosp) {
if(hospitalName.contains(hospital.name)) {
arrayOfSharedDiagnoses.add(hospital)
hosp.remove(hospital)
break
}
}
arrayAdapter.notifyDataSetChanged()
arrayAdapterShared.notifyDataSetChanged()
}
override fun onFailureDiagnosesShare(failuremessage: String){
toast("$failuremessage",activity)
}
override fun onSuccessHospitalsByPresc(responseList: MutableLiveData<HospitalsUserResponse>) {
}
override fun onResume() {
super.onResume()
hosp.clear()
arrayOfSharedDiagnoses.clear()
arrayAdapter.notifyDataSetChanged()
arrayAdapterShared.notifyDataSetChanged()
}
} | 0 | Kotlin | 0 | 2 | 284c942fa352e0e22919ca6821a59c352c9fc354 | 5,371 | E-Health | MIT License |
utils/times/src/test/kotlin/io/bluetape4k/times/AbstractTimesTest.kt | debop | 625,161,599 | false | {"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82} | package io.bluetape4k.times
import io.bluetape4k.logging.KLogging
import java.time.temporal.ChronoUnit
abstract class AbstractTimesTest {
companion object: KLogging()
val chronoUnits = listOf(
ChronoUnit.YEARS,
ChronoUnit.MONTHS,
ChronoUnit.WEEKS,
ChronoUnit.DAYS,
ChronoUnit.HOURS,
ChronoUnit.MINUTES,
ChronoUnit.SECONDS,
ChronoUnit.MILLIS
)
}
| 0 | Kotlin | 0 | 1 | ce3da5b6bddadd29271303840d334b71db7766d2 | 425 | bluetape4k | MIT License |
owntracks-android-2.4/project/app/src/main/java/org/owntracks/android/ui/preferences/editor/EditorActivityModule.kt | wir3z | 737,346,188 | false | {"Kotlin": 577231, "Groovy": 303581, "Java": 233010, "Python": 1535, "Shell": 959} | package org.owntracks.android.ui.preferences.editor
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ActivityComponent
@InstallIn(ActivityComponent::class)
@Module
abstract class EditorActivityModule {
@Binds
abstract fun bindViewModel(viewModel: EditorViewModel): EditorMvvm.ViewModel<EditorMvvm.View>
}
| 0 | Kotlin | 3 | 4 | a515ba358d3467267e9d662564152f5d7613991a | 374 | hubitat | Apache License 2.0 |
Kotiln/payment-service/src/main/kotlin/core/paymentservice/service/dto/PaymentConfirmCommand.kt | bekurin | 558,176,225 | false | {"Git Config": 1, "Text": 12, "Ignore List": 96, "Markdown": 58, "YAML": 55, "JSON with Comments": 2, "JSON": 46, "HTML": 104, "robots.txt": 6, "SVG": 10, "TSX": 15, "CSS": 64, "Gradle Kotlin DSL": 107, "Shell": 72, "Batchfile": 71, "HTTP": 15, "INI": 112, "Kotlin": 682, "EditorConfig": 1, "Gradle": 40, "Java": 620, "JavaScript": 53, "Go": 8, "XML": 38, "Go Module": 1, "SQL": 7, "Dockerfile": 1, "Gherkin": 1, "Python": 153, "SCSS": 113, "Java Properties": 3, "AsciiDoc": 5, "Java Server Pages": 6, "Unity3D Asset": 451, "C#": 48, "Objective-C": 51, "C": 8, "Objective-C++": 1, "Smalltalk": 1, "OpenStep Property List": 12, "Dart": 17, "Swift": 8, "Ruby": 1} | package core.paymentservice.service.dto
data class PaymentConfirmCommand(
val paymentKey: String,
val orderId: String,
val amount: Long
)
| 0 | Java | 0 | 2 | ede7cdb0e164ed1d3d2ee91c7770327b2ee71e4d | 151 | blog_and_study | MIT License |
IIAM/app/src/main/java/com/app/iiam/splash/SplashActivity.kt | mallardj | 347,413,960 | false | {"Text": 1, "Ignore List": 4, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "JSON": 1, "Proguard": 1, "Kotlin": 91, "XML": 104, "Java": 5} | package com.app.iiam.splash
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import com.app.iiam.R
import com.app.iiam.base.BaseActivity
import com.app.iiam.main.MainActivity
import com.app.iiam.preference.SharedPrefsManager
import com.app.iiam.utils.Const
import com.app.iiam.welcome.WelcomeActivity
class SplashActivity : BaseActivity() {
private lateinit var handler: Handler
private lateinit var runnable: Runnable
companion object {
const val SPLASH_TIME_OUT: Long = 2000
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
initView()
}
private fun initView() {
handler = Handler()
runnable = Runnable {
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
if (SharedPrefsManager.getLong(Const.USER_ID).toString().equals("0")) {
val intent = Intent(this@SplashActivity, WelcomeActivity::class.java)
startActivity(intent)
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
} else {
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
val intent = Intent(this@SplashActivity, MainActivity::class.java)
startActivity(intent)
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
}
finish()
}
}
override fun onResume() {
super.onResume()
if (::handler.isInitialized) {
if (::runnable.isInitialized) {
handler.postDelayed(
runnable,
SPLASH_TIME_OUT
)
}
}
}
override fun onPause() {
super.onPause()
if (::handler.isInitialized) {
if (::runnable.isInitialized) {
handler.removeCallbacks(runnable)
}
}
}
} | 0 | JavaScript | 0 | 0 | c41276fd8b7c2708cac541ffcf0aecf1767feb57 | 2,155 | iiam | MIT License |
thunder-internal/src/main/java/com/jeremy/thunder/thunder_internal/cache/BaseValve.kt | jaeyunn15 | 671,450,093 | false | {"Kotlin": 101726} | package com.jeremy.thunder.thunder_internal.cache
import com.jeremy.thunder.thunder_state.ConnectState
import kotlinx.coroutines.flow.Flow
interface BaseValve<T> {
fun onUpdateValve(state: ConnectState)
fun requestToValve(request: T)
fun emissionOfValveFlow(): Flow<List<T>>
interface BaseValveFactory<T> {
fun create(): BaseValve<T>
}
} | 0 | Kotlin | 1 | 12 | 583bc775b792ea4f8630d69137d89e594abbbedc | 369 | Thunder | MIT License |
utils/src/main/java/com/yww/utils/stragedy/brand/phones/Xiaomi.kt | wavening | 180,977,597 | false | {"Gradle": 14, "Java Properties": 4, "Shell": 1, "Text": 9, "Ignore List": 12, "Batchfile": 1, "Markdown": 1, "Proguard": 11, "XML": 65, "Kotlin": 113, "Java": 2, "JSON": 12, "SQL": 2, "Motorola 68K Assembly": 3, "Unix Assembly": 1} | package com.yww.utils.stragedy.brand.phones
import android.content.ComponentName
import android.content.Intent
import com.yww.utils.extension.packageName
import com.yww.utils.extension.settingIntent
import com.yww.utils.impl.IBrand
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
/**
* @Author WAVENING
* @Date 2019/4/25-18:05
*/
internal class Xiaomi : IBrand.IManager {
private val extraname = ""
private val xiaomiAction = "miui.intent.action.APP_PERM_EDITOR"
private val manager = "com.miui.securitycenter"
private val managerMainApp = "com.miui.permcenter.permissions.AppPermissionsEditorActivity"
private val managerMain = "com.miui.permcenter.permissions.PermissionsEditorActivity"
private val MIUI_V6 = "V6"
private val MIUI_V7 = "V7"
private val MIUI_V8 = "V8"
private val MIUI_V9 = "V9"
override val managerIntent: Intent by lazy {
when (getMiuiVersion()) {
MIUI_V6 -> packV6V7
MIUI_V7 -> packV6V7
MIUI_V8 -> packV8V9
MIUI_V9 -> packV8V9
else -> settingIntent()
}
}
private val packV6V7: Intent by lazy {
val intent = Intent()
intent.action = xiaomiAction
intent.component = ComponentName(manager, managerMainApp)
intent.putExtra("extra_pkgname", packageName)
intent
}
private val packV8V9: Intent by lazy {
val intent = Intent()
intent.action = xiaomiAction
intent.component = ComponentName(manager, managerMain)
intent.putExtra("extra_pkgname", packageName)
intent
}
private fun getMiuiVersion(): String {
val propName = "ro.miui.ui.version.name"
val line: String
var input: BufferedReader? = null
try {
val p: Process = Runtime.getRuntime().exec("getprop $propName")
input = BufferedReader(InputStreamReader(p.inputStream), 1024)
line = input.readLine()
input.close()
} catch (ex: IOException) {
ex.printStackTrace()
return ""
} finally {
try {
input?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
return line
}
} | 1 | null | 1 | 1 | 964e3eaa52e2aefdc10b883394910e61fdb2e467 | 2,322 | KotlinLibs | Apache License 2.0 |
core/src/com/broll/voxeldungeon/VoxelDungeon.kt | Rolleander | 476,822,126 | false | {"Kotlin": 97514, "GLSL": 3666, "Java": 1305} | package com.broll.voxeldungeon
import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.physics.bullet.Bullet
import com.broll.voxeldungeon.resource.ResourceManager
import com.broll.voxeldungeon.scenes.SceneManager
import com.broll.voxeldungeon.scenes.impl.MainMenuScene
class VoxelDungeon : ApplicationAdapter() {
private var resourceManager: ResourceManager? = null
private var sceneManager: SceneManager? = null
override fun create() {
Gdx.app.log("Init", "Init Bullet Engine...")
Bullet.init()
Gdx.app.log("Init", "Start loading resources...")
resourceManager = ResourceManager()
resourceManager!!.startLoading()
Gdx.app.log("Init", "Start creating scenes...")
sceneManager = SceneManager()
sceneManager!!.initScenes(resourceManager!!)
Gdx.app.log("Init", "Finished loading!")
Gdx.app.log("Init", "Start Game...")
sceneManager!!.showStartScene(MainMenuScene::class.java)
Gdx.app.log("Init", "Game started!")
}
override fun render() {
sceneManager!!.currentScene!!.render()
}
override fun dispose() {}
override fun resize(width: Int, height: Int) {}
override fun pause() {}
override fun resume() {}
} | 0 | Kotlin | 0 | 0 | 6bce2fb21620d91c171d82e5a5db6dc1fb3a5a7c | 1,290 | voxel-dungeon | MIT License |
runtime-permission-kotlin/src/main/java/com/github/florent37/runtimepermission/kotlin/kotlin-runtimepermissions.kt | florent37 | 125,537,016 | false | null | package com.github.florent37.runtimepermission.kotlin
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.github.florent37.runtimepermission.RuntimePermission
import com.github.florent37.runtimepermission.PermissionResult
fun androidx.fragment.app.Fragment.askPermission(vararg permissions: String, acceptedblock: (PermissionResult) -> Unit): KotlinRuntimePermission {
return KotlinRuntimePermission(RuntimePermission.askPermission(activity)
.request(permissions.toList())
.onAccepted(acceptedblock))
}
fun androidx.fragment.app.FragmentActivity.askPermission(vararg permissions: String, acceptedblock: (PermissionResult) -> Unit): KotlinRuntimePermission {
return KotlinRuntimePermission(RuntimePermission.askPermission(this)
.request(permissions.toList())
.onAccepted(acceptedblock))
}
class KotlinRuntimePermission(var runtimePermission: RuntimePermission) {
init {
runtimePermission.ask()
}
fun onDeclined(block: ((PermissionResult) -> Unit)) : KotlinRuntimePermission {
runtimePermission.onResponse{
if(it.hasDenied() || it.hasForeverDenied()){
block(it)
}
}
return this
}
}
| 8 | Java | 67 | 870 | 124c63455b39dc6cfe15e8fcad45b82b14abf6ae | 1,273 | RuntimePermission | Apache License 2.0 |
src/test/kotlin/de/richargh/sandbox/kt/mvn/concurrency/coroutines/samples/app/shared_kernel/LocalNotifierTest.kt | Richargh | 193,774,705 | false | null | package de.richargh.sandbox.kt.mvn.concurrency.coroutines.samples.app.shared_kernel
import kotlinx.coroutines.Dispatchers
class LocalNotifierTest: NotifierContract(
LocalNotifier(Dispatchers.Default)) | 0 | Kotlin | 0 | 0 | aed25fe3f7e04c1e1e1cf48aa1e8e554298ba078 | 210 | concurrency-mvn-kt-sandbox | MIT License |
FirstProjectInfnet/app/src/main/java/com/poc/firstprojectinfnet/login/presentation/LoginViewModel.kt | OsvaldoAironInfnet | 614,215,531 | false | null | package com.poc.firstprojectinfnet.login.presentation
import android.content.Intent
import android.os.Handler
import androidx.lifecycle.ViewModel
import com.poc.commom.base.auth.GoogleLoginSingInDTO
import com.poc.commom.base.auth.RemoteAuth
import com.poc.commom.base.views.BaseActivity
class LoginViewModel(private val remoteAuth: RemoteAuth) :
ViewModel() {
private var loginView: LoginContract.View? = null
fun init(view: LoginContract.View) {
loginView = view
}
fun redirectToLoginPage() {
Handler().postDelayed(
Runnable {
loginView?.redirectToLogin()
}, DELAY_TIME_SLEEP_SPLASH_SCREEN
)
}
fun authenticateWithGoogle(baseActivity: BaseActivity, requestCode: Int) {
remoteAuth.onLoginGoogle(baseActivity, requestCode)
}
fun proccessSingInGoogle(requestCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_LOGIN_GOOGLE) {
if (data != null) {
remoteAuth.onGetDataIntentSignIn(data, onSuccess = {
loginView?.showMessage("Login realizado com sucesso!")
Handler().postDelayed({
redirectToHomeApp(it)
}, 300)
}, onFailure = {
loginView?.showMessage("Não foi possivel realizar o login, tente novamente!")
})
}
}
}
fun authenticateLoginFirebase(email: String, password: String) {
remoteAuth.onLoginFirebaseCredentials(email, password, onSuccess = {
loginView?.showMessage("Login realizado com sucesso!")
Handler().postDelayed({
redirectToHomeApp(GoogleLoginSingInDTO(null, it, "firebase"))
}, 1000)
}, onFailure = {
loginView?.showMessage(it)
})
}
private fun redirectToHomeApp(data: GoogleLoginSingInDTO) {
loginView?.redirectToHome(data)
}
companion object {
private const val DELAY_TIME_SLEEP_SPLASH_SCREEN = 3000L
const val REQUEST_CODE_LOGIN_GOOGLE = 3004
}
} | 0 | Kotlin | 0 | 0 | 7ea9f5daf0d64374c29b6054db166f92ae2d4c76 | 2,120 | Tasks | MIT License |
smartdoc-dashboard/src/main/kotlin/smartdoc/dashboard/repository/HttpDocumentRepository.kt | Maple-mxf | 283,354,797 | false | {"Kotlin": 3578500, "Java": 741741, "Dockerfile": 1079, "Shell": 1000, "Python": 714} | package smartdoc.dashboard.repository
import org.springframework.stereotype.Repository
import smartdoc.dashboard.model.doc.http.HttpDocument
@Repository
interface HttpDocumentRepository : smartdoc.dashboard.base.mongo.BaseRepository<HttpDocument, String> | 21 | Kotlin | 2 | 2 | 3cdf9de7593c78c819b3dadc9b583e736041d55f | 256 | rest-doc | Apache License 2.0 |
applications/demokafka-producer/src/main/kotlin/org/amidukr/demokafka/producer/config/SwaggerConfig.kt | amidukr | 255,240,189 | false | null | package org.amidukr.demokafka.producer.config
import org.springframework.context.annotation.Configuration
import springfox.documentation.swagger2.annotations.EnableSwagger2
@Configuration
@EnableSwagger2
class SwaggerConfig | 8 | Kotlin | 0 | 1 | 4111c70f0ae5d6dcfac0094110d320b4e69340b9 | 225 | demo-kafka | Apache License 2.0 |
app/src/main/java/com/dev/ahoyweatherapp/repo/ForecastRepository.kt | binokbenny77 | 497,718,307 | false | {"Kotlin": 180545, "Shell": 537} | package com.dev.ahoyweatherapp.repo
import androidx.lifecycle.LiveData
import com.dev.ahoyweatherapp.core.Constants.NetworkService.RATE_LIMITER_TYPE
import com.dev.ahoyweatherapp.db.entity.ForecastEntity
import com.dev.ahoyweatherapp.domain.datasource.forecast.ForecastLocalDataSource
import com.dev.ahoyweatherapp.domain.datasource.forecast.ForecastRemoteDataSource
import com.dev.ahoyweatherapp.domain.model.ForecastResponse
import com.dev.ahoyweatherapp.utils.domain.RateLimiter
import com.dev.ahoyweatherapp.utils.domain.Resource
import io.reactivex.Single
import java.util.concurrent.TimeUnit
import javax.inject.Inject
/**
* Created by Bino on 2022-05-30
*/
class ForecastRepository @Inject constructor(
private val forecastRemoteDataSource: ForecastRemoteDataSource,
private val forecastLocalDataSource: ForecastLocalDataSource
) {
private val forecastListRateLimit = RateLimiter<String>(30, TimeUnit.SECONDS)
fun loadForecastByCoord(lat: Double, lon: Double, fetchRequired: Boolean, units: String): LiveData<Resource<ForecastEntity>> {
return object : NetworkBoundResource<ForecastEntity, ForecastResponse>() {
override fun saveCallResult(item: ForecastResponse) = forecastLocalDataSource.insertForecast(
item
)
override fun shouldFetch(data: ForecastEntity?): Boolean = fetchRequired
override fun loadFromDb(): LiveData<ForecastEntity> = forecastLocalDataSource.getForecast()
override fun createCall(): Single<ForecastResponse> = forecastRemoteDataSource.getForecastByGeoCords(
lat,
lon,
units
)
override fun onFetchFailed() = forecastListRateLimit.reset(RATE_LIMITER_TYPE)
}.asLiveData
}
}
| 0 | Kotlin | 0 | 0 | 68614eba0d137ec63d15cdd940b92947969e3a66 | 1,795 | WeatherApp | MIT License |
src/main/kotlin/no/vingaas/pokermanager/entities/notification/Notification.kt | tomandreaskv | 810,388,706 | false | {"Kotlin": 143404} | package no.vingaas.pokermanager.entities.notification
import jakarta.persistence.*
import no.vingaas.pokermanager.entities.user.User
import java.time.LocalDateTime
@Entity
@Table(name = "notifications")
data class Notification(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
val user: User,
@Column(nullable = false)
val message: String,
@Column(nullable = false)
val isRead: Boolean,
@Column(nullable = false)
val sentAt: LocalDateTime
) | 0 | Kotlin | 0 | 1 | 76245f712deb230f6369d236fa6b440ac4e6553e | 578 | pokermanager-backend | Apache License 2.0 |
WordShuffler/Word-Shuffler-Game/app/src/main/java/com/example/wordshuffle/GameFragmentViewModel.kt | aadityamp01 | 275,898,636 | false | null | package com.example.wordshuffle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class GameFragmentViewModel : ViewModel() {
val name: String = "randomname"
var score: Int = 0
private val livescore= MutableLiveData<Int>()
fun score_return():LiveData<Int>{
return livescore
}
var randomword: String = "start"
var scrambled: String = "sartt"
fun addnum(){
score += 10
livescore.value = score
}
fun subnum_five(){
score -= 5
livescore.value = score
}
fun subnum_one(){
score-=1
livescore.value = score
}
} | 1 | null | 57 | 76 | d047d5b4c3321df85c6523c0725028986c898b14 | 676 | Androapps | MIT License |
aasexplorer-core/src/main/java/com/ficture7/aasexplorer/model/ResourceRepository.kt | FICTURE7 | 123,935,332 | false | null | package com.ficture7.aasexplorer.model
import com.ficture7.aasexplorer.Loader
import com.ficture7.aasexplorer.Saver
import java.util.ArrayList
import java.util.Collections
import java.util.HashMap
/**
* Represents a repository of [Resource].
*
* @author FICTURE7
*/
class ResourceRepository : Repository<String, Resource>, Iterable<Resource> {
//TODO: Create a custom collection for resources to filter them by getDate and stuff.
private var _isLoaded: Boolean = false
private val subject: Subject
private val loader: Loader
private val saver: Saver
// Maps resource getName to resource instances.
private val resources: MutableMap<String, Resource>
// Pre-sorted lists of resources.
private val internalMarkingSchemes: MutableList<MarkingScheme>
private val internalQuestionPapers: MutableList<QuestionPaper>
private val internalOthers: MutableList<Resource>
// Read-only collections to prevent leaks.
private val readOnlyMarkingSchemes: Collection<MarkingScheme>
private val readOnlyQuestionPapers: Collection<QuestionPaper>
private val readOnlyOthers: Collection<Resource>
/**
* Constructs a new instance of th e[ResourceRepository] with the specified [Subject]
* instance which owns this [ResourceRepository], [Loader] and [Saver].
*
* @param subject [Subject] instance which owns this [ResourceRepository].
* @param loader [Loader] instance.
* @param saver [Saver] instance.
*/
internal constructor(subject: Subject, loader: Loader, saver: Saver) {
this.subject = subject
this.loader = loader
this.saver = saver
resources = HashMap()
internalMarkingSchemes = ArrayList()
internalQuestionPapers = ArrayList()
internalOthers = ArrayList()
readOnlyMarkingSchemes = Collections.unmodifiableCollection(internalMarkingSchemes)
readOnlyQuestionPapers = Collections.unmodifiableCollection(internalQuestionPapers)
readOnlyOthers = Collections.unmodifiableCollection(internalOthers)
}
/**
* Returns a boolean value indicating weather the [ResourceRepository] is loaded.
*
* @return A boolean value indicating weather the [ResourceRepository] is loaded.
*/
override val isLoaded: Boolean
get() = _isLoaded
/**
* Returns an iterable which contains only [MarkingScheme]s.
*
* @return An iterable which contains only [MarkingScheme]s.
*/
val markingSchemes: Iterable<MarkingScheme>
get() = readOnlyMarkingSchemes
/**
* Returns an iterable which contains only [QuestionPaper]s.
*
* @return An iterable which contains only [QuestionPaper]s.
*/
val questionPapers: Iterable<QuestionPaper>
get() = readOnlyQuestionPapers
/**
* Returns an iterable which contains other unidentified [Resource]s.
*
* @return An iterable which contains other unidentified [Resource]s.
*/
val others: Iterable<Resource>
get() = readOnlyOthers
/**
* Returns the number of [Resource] which is in the repository.
*
* @return Number of [Resource] which is in the repository.
*/
fun size(): Int {
return resources.size
}
/**
* Returns the [Resource] with the specified getName.
* Returns null if no [Resource] with the specified getName is in the repository.
*
* @param resourceName Resource getName.
* @return [Resource] with the specified getName.
*/
override fun get(resourceName: String): Resource? {
return resources[resourceName]
}
/**
* Puts the specified [Resource] to the repository.
*
* @param resource [Resource] to put in the repository.
*/
override fun put(resource: Resource) {
// Add the Resource instance to the Map
// mapping resource names to resource instances.
resources.put(resource.name, resource)
// Add the Resource instance to the corresponding list.
when (resource) {
is MarkingScheme -> internalMarkingSchemes.add(resource)
is QuestionPaper -> internalQuestionPapers.add(resource)
else -> internalOthers.add(resource)
}
}
/**
* Loads the [Repository].
*
* @throws Exception When an exception is thrown.
*/
@Throws(Exception::class)
override fun load() {
unload()
val sources = loader.loadResources(subject)
for (source in sources) {
var resource = get(source.name)
if (resource == null) {
// Turn the resource source to the resource type.
// E.G: MarkingScheme, QuestionPaper or Resource it self if
// unable to identified.
resource = resourceSourceToResource(source)
resource.sources.add(source)
put(resource)
} else {
resource.sources.add(source)
}
}
_isLoaded = true
}
/**
* Loads the [ResourceRepository] asynchronously.
*
* @param callback Callback initializer.
*/
override fun loadAsync(callback: Repository.LoadCallback.() -> Unit) {
val loadCallback = Repository.LoadCallback()
loadCallback.callback()
unload()
loader.executor.execute {
try {
val sources = loader.loadResources(subject)
for (source in sources) {
var resource = get(source.name)
if (resource == null) {
// Turn the resource source to the resource type.
// E.G: MarkingScheme, QuestionPaper or Resource it self if
// unable to identified.
resource = resourceSourceToResource(source)
resource.sources.add(source)
put(resource)
} else {
resource.sources.add(source)
}
}
_isLoaded = true
loader.executor.callbackExecutor.execute {
loadCallback.onLoadCallback?.invoke()
}
} catch (e: Exception) {
loader.executor.callbackExecutor.execute {
loadCallback.onErrorCallback?.invoke(e)
}
}
}
}
/**
* Unloads the [Repository].
*/
override fun unload() {
resources.clear()
_isLoaded = false
}
/**
* Saves the [Repository].
*
* @throws Exception When an exception is thrown.
*/
@Throws(Exception::class)
override fun save() {
val resourceSources = ArrayList<ResourceSource>()
for (resource in this) {
for (source in resource.sources) {
resourceSources.add(source)
}
}
saver.saveResources(subject, resourceSources)
}
/**
* Loads the [ResourceRepository] asynchronously.
*
* @param callback Callback initializer.
*/
override fun saveAsync(callback: Repository.SaveCallback.() -> Unit) {
val saveCallback = Repository.SaveCallback()
saveCallback.callback()
val resourceSources = ArrayList<ResourceSource>()
for (resource in this) {
for (source in resource.sources) {
resourceSources.add(source)
}
}
saver.executor.execute {
try {
saver.saveResources(subject, resourceSources)
saver.executor.execute {
saveCallback.onSaveCallback?.invoke()
}
}catch (e: Exception) {
saver.executor.callbackExecutor.execute {
saveCallback.onErrorCallback?.invoke(e)
}
}
}
}
/**
* Returns an iterator over the [Resource] of the repository.
*
* @return An iterator over the [Resource] of the repository.
*/
override fun iterator(): Iterator<Resource> {
return resources.values.iterator()
}
private fun resourceSourceToResource(source: ResourceSource): Resource {
//TODO: Improve the logic n stuff. Defensive stuff.
val name = source.name
try {
val index1: Int
val index2: Int
val index3: Int
val index4: Int
index1 = name.indexOf('_')
index2 = name.indexOf('_', index1 + 1)
index3 = name.indexOf('_', index2 + 1)
index4 = name.indexOf('.', index3 + 1)
if (index1 == -1 || index2 == -1 || index3 == -1 || index4 == -1) {
return Resource(name)
}
val id = name.substring(0, index1)
val session = name.substring(index1 + 1, index2)
val type = name.substring(index2 + 1, index3)
val number = name.substring(index3 + 1, index4)
return when (type) {
"qp" -> QuestionPaper(name, Session.parse(session), Integer.parseInt(number))
"ms" -> MarkingScheme(name, Session.parse(session))
else -> Resource(name)
}
} catch (e: Exception) {
// Fallback to a Resource instance if we fail to parse the getName.
return Resource(name)
}
}
}
| 1 | null | 1 | 1 | 07dca30e5fb2d62930859ae7e76cc5aac05a9f13 | 9,495 | aasexplorer | MIT License |
game/src/main/kotlin/gg/rsmod/game/model/droptable/NpcDropTableDef.kt | superbmyte | 188,611,973 | false | null | package gg.rsmod.game.model.droptable
data class NpcDropTableDef(
val rolls: Int,
val always_table: DropTable,
val common_table: DropTable,
val uncommon_table: DropTable,
val rare_table: DropTable,
val veryrare_table: DropTable
) {
companion object {
private val DEFAULT_ALWAYS_TABLE = DropTable("""
{
"percentage": 0.0,
"items": []
}
""".trimIndent())
private val DEFAULT_ROLLS = 0
private val DEFAULT_COMMON_TABLE = DropTable("""
{
"percentage": 0.0,
"items": []
}
""".trimIndent())
private val DEFAULT_UNCOMMON_TABLE = DropTable("""
{
"percentage": 0.0,
"items": []
}
""".trimIndent())
private val DEFAULT_RARE_TABLE = DropTable("""
{
"percentage": 0.0,
"items": []
}
""".trimIndent())
private val DEFAULT_VERYRARE_TABLE = DropTable("""
{
"percentage": 0.0,
"items": []
}
""".trimIndent())
val DEFAULT = NpcDropTableDef(
rolls = DEFAULT_ROLLS,
always_table = DEFAULT_ALWAYS_TABLE,
common_table = DEFAULT_COMMON_TABLE,
uncommon_table = DEFAULT_UNCOMMON_TABLE,
rare_table = DEFAULT_RARE_TABLE,
veryrare_table = DEFAULT_VERYRARE_TABLE
)
}
} | 0 | null | 0 | 1 | 8f34b0c5408bb07ba54c0be4f5f35fb9e85abb30 | 1,479 | rsmod | Apache License 2.0 |
base/src/main/java/com/dvpermyakov/base/extensions/FragmentExtenstions.kt | dvpermyakov | 132,182,615 | false | {"Kotlin": 105301} | package com.dvpermyakov.base.extensions
import android.content.Intent
import androidx.fragment.app.Fragment
/**
* Created by dmitrypermyakov on 30/04/2018.
*/
fun Fragment.requestPermission(permission: String, requestCode: Int) {
requestPermissions(arrayOf(permission), requestCode)
}
fun Fragment.startActivityForImageFromGallery(requestCode: Int) {
val intent = Intent(Intent.ACTION_PICK).apply { type = "image/*" }
startActivityForResult(intent, requestCode)
} | 8 | Kotlin | 0 | 2 | cc6e712acd5febac079a031c4a16cacd073b290d | 481 | image-post-android | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.