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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kotlin-client/src/main/kotlin/io/provenance/bilateral/models/AskOrder.kt
|
provenance-io
| 506,765,156
| false
| null |
package io.provenance.bilateral.models
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.annotation.JsonTypeName
import com.fasterxml.jackson.databind.PropertyNamingStrategies.SnakeCaseStrategy
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.annotation.JsonNaming
import cosmos.base.v1beta1.CoinOuterClass.Coin
import io.provenance.bilateral.models.AskCollateral.CoinTrade
import io.provenance.bilateral.models.AskCollateral.MarkerShareSale
import io.provenance.bilateral.models.AskCollateral.MarkerTrade
import io.provenance.bilateral.models.AskCollateral.ScopeTrade
import io.provenance.bilateral.models.enums.BilateralRequestType
import io.provenance.bilateral.models.enums.ShareSaleType
import io.provenance.bilateral.serialization.CosmWasmUintToBigIntegerDeserializer
import java.math.BigInteger
/**
* Represents the current state of an ask in the smart contract's storage.
*
* @param id The unique identifier for the ask.
* @param askType The
*/
@JsonNaming(SnakeCaseStrategy::class)
data class AskOrder(
val id: String,
val askType: BilateralRequestType,
val owner: String,
val collateral: AskCollateral,
val descriptor: RequestDescriptor?
) {
@JsonIgnore
fun <T> mapCollateral(
coinTrade: (coinTrade: CoinTrade) -> T,
markerTrade: (markerTrade: MarkerTrade) -> T,
markerShareSale: (markerShareSale: MarkerShareSale) -> T,
scopeTrade: (scopeTrade: ScopeTrade) -> T,
): T = when (collateral) {
is CoinTrade -> coinTrade(collateral)
is MarkerTrade -> markerTrade(collateral)
is MarkerShareSale -> markerShareSale(collateral)
is ScopeTrade -> scopeTrade(collateral)
}
}
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
sealed interface AskCollateral {
@JsonNaming(SnakeCaseStrategy::class)
@JsonTypeName("coin_trade")
data class CoinTrade(
val base: List<Coin>,
val quote: List<Coin>,
) : AskCollateral
@JsonNaming(SnakeCaseStrategy::class)
@JsonTypeName("marker_trade")
data class MarkerTrade(
val markerAddress: String,
val markerDenom: String,
@JsonDeserialize(using = CosmWasmUintToBigIntegerDeserializer::class)
val shareCount: BigInteger,
val quotePerShare: List<Coin>,
val removedPermissions: List<MarkerAccessGrant>,
) : AskCollateral
@JsonNaming(SnakeCaseStrategy::class)
@JsonTypeName("marker_share_sale")
data class MarkerShareSale(
val markerAddress: String,
val markerDenom: String,
@JsonDeserialize(using = CosmWasmUintToBigIntegerDeserializer::class)
val totalSharesInSale: BigInteger,
@JsonDeserialize(using = CosmWasmUintToBigIntegerDeserializer::class)
val remainingSharesInSale: BigInteger,
val quotePerShare: List<Coin>,
val removedPermissions: List<MarkerAccessGrant>,
val saleType: ShareSaleType,
) : AskCollateral
@JsonNaming(SnakeCaseStrategy::class)
@JsonTypeName("scope_trade")
data class ScopeTrade(
val scopeAddress: String,
val quote: List<Coin>,
) : AskCollateral
}
data class MarkerAccessGrant(
val address: String,
val permissions: List<String>,
)
| 0
|
Rust
|
0
| 0
|
96043cb5f4cb5a4322609c927038395bc9655363
| 3,393
|
metadata-bilateral-exchange
|
Apache License 2.0
|
src/main/kotlin/io/github/uinnn/serializer/formatter/StrategyStreamFormatter.kt
|
uinnn
| 388,945,281
| false
| null |
/*
MIT License
Copyright (c) 2021 uin
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 io.github.uinnn.serializer.formatter
import io.github.uinnn.serializer.AlterableStreamFormat
import io.github.uinnn.serializer.strategy.DecoderStrategy
import io.github.uinnn.serializer.strategy.DefaultSerialDecoder
import io.github.uinnn.serializer.strategy.DefaultSerialEncoder
import io.github.uinnn.serializer.strategy.EncoderStrategy
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.modules.SerializersModule
import java.io.InputStream
import java.io.OutputStream
/**
* A stream strategy formatter.
* This is used to modify how kotlin serialization
* should encode or decode strings, numbers, chars and booleans.
* This formatter is only able to use with [AlterableStreamFormat]
* serial files, suchs as Named Binaray Tag (NBT) file.
*/
open class StrategyStreamFormatter(
override val model: AlterableStreamFormat,
encoder: EncoderStrategy,
decoder: DecoderStrategy,
) : StrategyFormatter(model, encoder, decoder), AlterableStreamFormat by model {
override fun <T> encodeTo(output: OutputStream, serializer: SerializationStrategy<T>, value: T) {
output.use {
model.encodeTo(it, DefaultSerialEncoder(encoder, serializer), value)
}
}
override fun <T> decodeFrom(input: InputStream, deserializer: DeserializationStrategy<T>): T {
return input.use {
model.decodeFrom(it, DefaultSerialDecoder(decoder, deserializer))
}
}
override var serializersModule: SerializersModule = super.serializersModule
}
| 0
|
Kotlin
|
0
| 2
|
ad4e9dc6fdc184cc8520b92015539cb62928385d
| 2,666
|
serializer-framework
|
MIT License
|
subprojects/test-fixtures/src/main/kotlin/org/gradle/kotlin/dsl/fixtures/AbstractIntegrationTest.kt
|
vdvorak83
| 156,388,201
| true
|
{"Kotlin": 1093450, "Java": 5870, "Shell": 551}
|
package org.gradle.kotlin.dsl.fixtures
import org.gradle.api.JavaVersion
import org.gradle.internal.FileUtils.toSafeFileName
import org.gradle.kotlin.dsl.support.zipTo
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.not
import org.hamcrest.Matcher
import org.junit.Assert.assertThat
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.Rule
import org.junit.rules.TestName
import java.io.File
import java.util.Properties
internal
val isCI by lazy { !System.getenv("CI").isNullOrEmpty() }
open class AbstractIntegrationTest {
@JvmField
@Rule
val testName = TestName()
@JvmField
@Rule
val temporaryFolder = ForcefullyDeletedTemporaryFolder()
@Before
fun withDefaultGradleJvmArguments() =
withGradleJvmArguments("-Xms128m", "-Xmx512m", "-Dfile.encoding=UTF-8")
protected
open val defaultSettingsScript
get() = ""
protected
val repositoriesBlock
get() = """
repositories {
gradlePluginPortal()
}
"""
protected
val projectRoot: File
get() = customProjectRoot ?: defaultProjectRoot
private
var customProjectRoot: File? = null
private
val defaultProjectRoot
get() = File(temporaryFolder.root, toSafeFileName(testName.methodName)).apply { mkdirs() }
protected
fun <T> withProjectRoot(dir: File, action: () -> T): T {
val previousProjectRoot = customProjectRoot
try {
customProjectRoot = dir
return action()
} finally {
customProjectRoot = previousProjectRoot
}
}
protected
fun withDefaultSettings() =
withDefaultSettingsIn(".")
protected
fun withDefaultSettingsIn(baseDir: String) =
withSettingsIn(baseDir, defaultSettingsScript)
protected
fun withSettings(script: String, produceFile: (String) -> File = ::newFile): File =
withSettingsIn(".", script, produceFile)
protected
fun withSettingsIn(baseDir: String, script: String, produceFile: (String) -> File = ::newFile): File =
withFile("$baseDir/settings.gradle.kts", script, produceFile)
protected
fun withBuildScript(script: String, produceFile: (String) -> File = ::newFile): File =
withBuildScriptIn(".", script, produceFile)
protected
fun withBuildScriptIn(baseDir: String, script: String, produceFile: (String) -> File = ::newFile): File =
withFile("$baseDir/build.gradle.kts", script, produceFile)
protected
fun withFile(fileName: String, text: String = "", produceFile: (String) -> File = ::newFile) =
writeFile(produceFile(fileName), text)
protected
fun writeFile(file: File, text: String): File =
file.apply { writeText(text) }
protected
fun withBuildSrc() =
withFile("buildSrc/src/main/groovy/build/Foo.groovy", """
package build
class Foo {}
""")
protected
fun withKotlinBuildSrc() {
withDefaultSettingsIn("buildSrc")
withBuildScriptIn("buildSrc", """
plugins {
`kotlin-dsl`
}
$repositoriesBlock
""")
}
protected
fun withClassJar(fileName: String, vararg classes: Class<*>) =
withZip(fileName, classEntriesFor(*classes))
protected
fun withZip(fileName: String, entries: Sequence<Pair<String, ByteArray>>): File =
newFile(fileName).also {
zipTo(it, entries)
}
protected
fun newFile(fileName: String): File {
return canonicalFile(fileName).apply {
parentFile.mkdirs()
createNewFile()
}
}
protected
fun newDir(relativePath: String): File =
existing(relativePath).apply { assert(mkdirs()) }
protected
fun newOrExisting(fileName: String) =
existing(fileName).let {
when {
it.isFile -> it
else -> newFile(fileName)
}
}
protected
fun existing(relativePath: String): File =
canonicalFile(relativePath)
private
fun canonicalFile(relativePath: String) =
File(projectRoot, relativePath).canonicalFile
fun build(vararg arguments: String): BuildResult =
gradleRunnerForArguments(*arguments)
.build()
protected
fun BuildResult.outcomeOf(taskPath: String): TaskOutcome? =
task(taskPath)?.outcome
protected
fun buildFailureOutput(vararg arguments: String): String =
buildAndFail(*arguments).output
protected
fun buildAndFail(vararg arguments: String): BuildResult =
gradleRunnerForArguments(*arguments)
.buildAndFail()
protected
fun build(rootDir: File, vararg arguments: String): BuildResult =
gradleRunnerFor(rootDir, *arguments)
.build()
protected
fun gradleRunnerForArguments(vararg arguments: String) =
gradleRunnerFor(projectRoot, *arguments)
protected
fun withGradleJvmArguments(vararg jvmArguments: String) =
withGradleProperties("org.gradle.jvmargs" to jvmArguments.joinToString(" "))
protected
fun assumeJavaLessThan9() {
assumeTrue("Test disabled under JDK 9 and higher", JavaVersion.current() < JavaVersion.VERSION_1_9)
}
private
fun withGradleProperties(vararg gradleProperties: Pair<String, String>) =
mergePropertiesInto(gradlePropertiesFile, gradleProperties.asIterable())
private
fun storeGradleProperties(properties: Properties) =
gradlePropertiesFile.outputStream().use { properties.store(it, null) }
private
fun loadGradleProperties() =
loadPropertiesFrom(gradlePropertiesFile)
private
val gradlePropertiesFile by lazy { existing("gradle.properties") }
}
fun AbstractIntegrationTest.canPublishBuildScan() {
assertThat(
build("tasks", "--scan").output,
containsBuildScanPluginOutput())
}
fun containsBuildScanPluginOutput(): Matcher<String> = allOf(
containsString("Publishing build scan..."),
not(containsString("The build scan plugin was applied after other plugins."))
)
private
fun gradleRunnerFor(projectDir: File, vararg arguments: String): GradleRunner = GradleRunner.create().run {
withGradleInstallation(customInstallation())
withProjectDir(projectDir)
withDebug(false)
if (isCI) withArguments(*arguments, "--stacktrace", "-Dkotlin-daemon.verbose=true")
else withArguments(*arguments, "--stacktrace")
return this
}
fun customDaemonRegistry() =
File(customInstallationBuildDir, "daemon-registry")
fun customInstallation() =
customInstallationBuildDir.listFiles()?.let {
it.singleOrNull { it.name.startsWith("gradle") } ?: throw IllegalStateException(
"Expected 1 custom installation but found ${it.size}. Run `./gradlew clean customInstallation`."
)
} ?: throw IllegalStateException("Custom installation not found. Run `./gradlew customInstallation`.")
val rootProjectDir = File("../..").canonicalFile!!
val customInstallationBuildDir = File(rootProjectDir, "build/custom")
inline fun <T> withTestDaemon(block: () -> T) =
withDaemonRegistry(customDaemonRegistry()) {
withDaemonIdleTimeout(1) {
block()
}
}
inline fun <T> withDaemonRegistry(registryBase: File, block: () -> T) =
withSystemProperty("org.gradle.daemon.registry.base", registryBase.absolutePath, block)
inline fun <T> withDaemonIdleTimeout(seconds: Int, block: () -> T) =
withSystemProperty("org.gradle.daemon.idletimeout", (seconds * 1000).toString(), block)
inline fun <T> withSystemProperty(key: String, value: String, block: () -> T): T {
val originalValue = System.getProperty(key)
try {
System.setProperty(key, value)
return block()
} finally {
setOrClearProperty(key, originalValue)
}
}
fun setOrClearProperty(key: String, value: String?) {
when (value) {
null -> System.clearProperty(key)
else -> System.setProperty(key, value)
}
}
fun loadPropertiesFrom(file: File) =
file.takeIf { it.isFile }?.inputStream()?.use { Properties().apply { load(it) } } ?: Properties()
fun mergePropertiesInto(propertiesFile: File, additionalProperties: Iterable<Pair<Any, Any>>) {
loadPropertiesFrom(propertiesFile).let { originalProperties ->
originalProperties.putAll(additionalProperties)
propertiesFile.outputStream().use { originalProperties.store(it, null) }
}
}
| 0
|
Kotlin
|
0
| 1
|
70aca202558f2f6e43cd8ead3ec95d669bfd7b33
| 8,780
|
kotlin-dsl
|
Apache License 2.0
|
src/main/kotlin/fm/force/ui/component/field/QuestionAutocompleteField.kt
|
night-crawler
| 239,825,339
| false
| null |
package fm.force.ui.component.field
import com.ccfraser.muirwik.components.mTextField
import fm.force.ui.client.QuestionSearchCriteria
import fm.force.ui.hook.UseState
import fm.force.ui.hook.useClient
import fm.force.ui.hook.useDebounce
import kotlinext.js.Object
import mu.KotlinLogging
import mui.lab.labAutocompleteField
import react.dom.span
import react.functionalComponent
import redux.form.WrappedFieldProps
private val logger = KotlinLogging.logger("QuestionsAutocompleteField")
interface QuestionsAutocompleteFieldProps : WrappedFieldProps {
var label: String
}
val QuestionAutocompleteField = functionalComponent<QuestionsAutocompleteFieldProps> { props ->
var searchText by UseState("")
val debouncedSearchText = useDebounce(searchText, 500)
val questions = useClient(listOf(debouncedSearchText)) {
findQuestions(
QuestionSearchCriteria(
page = 1,
sort = "title",
query = debouncedSearchText,
pageSize = 100
)
).content.toList()
} ?: listOf()
labAutocompleteField(props.label, questions) {
attrs {
freeSolo = false
value = if (props.input.value == "") null else props.input.value
onInputChange = { _, text, _ -> searchText = text }
renderOption = { option, _ ->
span { +option.title }
}
getOptionLabel = { if (it.asDynamic() == "") "" else it.title }
onChange = { _, value, _ ->
props.input.onChange(value)
}
getOptionSelected = { option, value ->
when {
option == undefined || value == undefined -> false
option.title == value.title -> true
else -> false
}
}
renderInput = { params ->
mTextField(label = props.label) {
Object.assign(attrs, params)
attrs.error = props.meta.error != undefined
}
}
}
}
}
| 0
|
Kotlin
|
0
| 13
|
2088cf140358341cf5a49d0144fb010eb22a9048
| 2,109
|
quiz-frontend
|
MIT License
|
app/src/main/java/com/example/movinsight/API/SearchMovieResponse.kt
|
RaigZ
| 716,618,626
| false
|
{"Kotlin": 80352}
|
package com.example.movinsight.API
data class SearchMovieResponse (
val status: Boolean,
val message: String,
val timestamp: Float,
val data: List<searchItem>
)
data class searchItem(
val id: String,
val qid: String,
val title: String,
val year: Int,
val stars: String,
val q: String,
val image: String
)
| 0
|
Kotlin
|
0
| 0
|
374e9cad2616355a36e96f92ace4771561b4e5fc
| 350
|
MovInsight
|
MIT License
|
app/src/main/java/com/example/i210566/VerifyPhoneNumberActivity.kt
|
MuhammadSaadHasan
| 754,987,730
| false
|
{"Kotlin": 88262}
|
package com.example.i210566
import android.content.Intent
import android.os.Bundle
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.FirebaseException
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.PhoneAuthProvider
import java.util.concurrent.TimeUnit
class VerifyPhoneNumberActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_verify_phone_number)
/*auth = FirebaseAuth.getInstance()
val buttonBack: ImageButton = findViewById(R.id.back)
buttonBack.setOnClickListener {
finish() // Just finish current activity, no need to create new intent for previous activity
}
val phoneNumber = intent.getStringExtra("phoneNumber") ?: run {
Toast.makeText(this, "Phone number is missing.", Toast.LENGTH_SHORT).show()
finish() // Finish activity if phone number is missing
return
}
val formattedPhoneNumber = formatPhoneNumberWithCountryCode(phoneNumber)
if (formattedPhoneNumber.isNotBlank()) {
startPhoneNumberVerification(formattedPhoneNumber)
} else {
Toast.makeText(this, "Invalid phone number.", Toast.LENGTH_SHORT).show()
}*/
}
private fun formatPhoneNumberWithCountryCode(phoneNumber: String?): String {
return if (phoneNumber != null && !phoneNumber.startsWith("+92")) {
"+92$phoneNumber"
} else {
phoneNumber ?: ""
}
}
private fun startPhoneNumberVerification(phoneNumber: String) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
callbacks) // OnVerificationStateChangedCallbacks
}
private val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
signInWithPhoneAuthCredential(credential)
}
override fun onVerificationFailed(e: FirebaseException) {
Toast.makeText(applicationContext, "Verification failed: ${e.localizedMessage}", Toast.LENGTH_LONG).show()
}
override fun onCodeSent(verificationId: String, token: PhoneAuthProvider.ForceResendingToken) {
// Intent to a new Activity where the user can enter the verification code
/*val intent = Intent(this@VerifyPhoneNumberActivity, CodeVerificationActivity::class.java)
intent.putExtra("verificationId", verificationId)
startActivity(intent)*/
}
}
private fun signInWithPhoneAuthCredential(credential: PhoneAuthCredential) {
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Toast.makeText(applicationContext, "Authentication successful.", Toast.LENGTH_SHORT).show()
// Navigate to main part of your application
} else {
Toast.makeText(applicationContext, "Authentication failed: ${task.exception?.message}", Toast.LENGTH_SHORT).show()
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
c88bbc127be78708e1f3676ae2fe4c882aa4bd18
| 3,600
|
MentorMe
|
MIT License
|
auth/app/src/minSdkIcs/java/com/google/firebase/quickstart/auth/FacebookLoginActivity.kt
|
kotlin-korea
| 97,319,520
| true
|
{"Gradle": 38, "Shell": 14, "Java Properties": 26, "Markdown": 15, "Text": 2, "Ignore List": 19, "Batchfile": 13, "YAML": 5, "JSON": 1, "Proguard": 13, "XML": 117, "Kotlin": 16, "Java": 46, "HTML": 1}
|
/**
* Copyright 2016 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.quickstart.auth
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
/**
* Demonstrate Firebase Authentication using a Facebook access token.
*/
class FacebookLoginActivity : AppCompatActivity() {
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_facebook)
}
}
| 1
|
Java
|
2
| 5
|
d548f84c06f77ef08d4565d754bb83a267453947
| 1,025
|
quickstart-android
|
Creative Commons Attribution 4.0 International
|
app/src/main/java/com/alexvoz/tawk_test_task/presentation/users_list/UserListAdapter.kt
|
aleksandrsvozn
| 373,213,314
| false
| null |
package com.alexvoz.tawk_test_task.presentation.users_list
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.alexvoz.tawk_test_task.R
import com.alexvoz.tawk_test_task.data.user.User
import com.alexvoz.tawk_test_task.utils.Util
import com.alexvoz.tawk_test_task.utils.changeVisibility
import com.alexvoz.tawk_test_task.utils.getDrawableImage
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.item_user.view.*
import java.util.*
private const val USER_HOLDER = 1
private const val LAST_LOADING_ITEM_HOLDER = 2
private val LAST_LOADING_ITEM = User(0, "loading_item", "loading_item", "loading_item")
/**
* User list adapter;
* Created by using DiffUtil
*
* Have two Holders: USER_HOLDER and LAST_LOADING_ITEM_HOLDER (For pagination)
*
* @param onClick ([User], ImageView) -> Unit
*/
class UserListAdapter(private val onClick: (user: User, avatarImg: ImageView) -> Unit) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val diffCallback = object : DiffUtil.ItemCallback<User>() {
override fun areItemsTheSame(oldItem: User, newItem: User): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: User, newItem: User): Boolean {
return oldItem == newItem
}
}
private val differ = AsyncListDiffer(this, diffCallback)
var isLastLoadingItemIsShown = false
fun showLastLoadingItem(show: Boolean) {
if (show != isLastLoadingItemIsShown) isLastLoadingItemIsShown = show
}
/**
* Updating the list
* Add/Remove the last loading Item if its required
*/
fun submitList(list: List<User>) {
differ.submitList(
list.toMutableList().apply {
if (isLastLoadingItemIsShown && !list.contains(LAST_LOADING_ITEM))
add(LAST_LOADING_ITEM)
else if (!isLastLoadingItemIsShown && list.contains(LAST_LOADING_ITEM))
remove(LAST_LOADING_ITEM)
}
)
}
/**
* @return 1 (USER_HOLDER) if is user object; Or 2 (LAST_LOADING_ITEM_HOLDER) if is a last position and isLastLoadingItemIsShown = true
*/
override fun getItemViewType(position: Int): Int {
return if (position == differ.currentList.size - 1 && isLastLoadingItemIsShown) LAST_LOADING_ITEM_HOLDER else USER_HOLDER
}
/**
* @return Instance of [UserHolder] or [LAST_LOADING_ITEM_HOLDER]
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
USER_HOLDER -> {
UserHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_user, parent, false
), onClick
)
}
LAST_LOADING_ITEM_HOLDER -> {
LastLoadingItemHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_user_last_loading, parent, false
)
)
}
else -> {
LastLoadingItemHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_user_last_loading, parent, false
)
)
}
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is UserHolder -> {
holder.bind(differ.currentList[position], position)
}
}
}
override fun getItemCount(): Int {
return differ.currentList.size
}
/**
* User Holder
* Every fourth element will be with inverted avatar colors and different background
*/
class UserHolder constructor(
itemView: View,
private val onClick: (user: User, avatarImg: ImageView) -> Unit
) : RecyclerView.ViewHolder(itemView) {
fun bind(item: User, position: Int) = with(itemView) {
itemUserNameTextView.text = item.login.capitalize(Locale.getDefault())
itemUserNoteImg.changeVisibility(item.notes.isNotBlank())
this.itemUserLayout.background = context.getDrawableImage(
if (position % 4 == 0) {
R.drawable.bg_item_user_second_color_ripple
} else {
R.drawable.bg_item_user_ripple
}
)
itemUserAvatarImg.apply {
transitionName = item.avatarUrl
colorFilter = if (position % 4 == 0) Util.getInvertedColorFilter() else null
Glide.with(context)
.load(item.avatarUrl)
.error(context.getDrawableImage(R.drawable.ic_user))
.into(this)
}
setOnClickListener {
onClick(item, itemUserAvatarImg)
}
}
}
class LastLoadingItemHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView)
}
| 0
|
Kotlin
|
1
| 0
|
8b8a4d1501b07c373cdb19f02fc20c25bc466948
| 5,331
|
tawk_test_task
|
Apache License 2.0
|
app/src/main/java/com/gitlab/j_m_hoffmann/meditate/repository/db/Db.kt
|
j-m-hoffmann
| 377,749,254
| false
| null |
package com.gitlab.j_m_hoffmann.meditate.repository.db
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(entities = [Session::class], version = 1, exportSchema = false)
abstract class Db : RoomDatabase() {
abstract val dao: Dao
}
| 0
|
Kotlin
|
0
| 0
|
622a47e0a322cfba16130182eee672e41e8a153d
| 261
|
Meditate
|
Attribution Assurance License
|
libraries/core/src/main/kotlin/io/plastique/core/work/CommonWorkTags.kt
|
plastiqueapp
| 150,879,887
| false
| null |
package io.plastique.core.work
object CommonWorkTags {
const val CANCEL_ON_LOGOUT = "cancel-on-logout"
}
| 0
|
Kotlin
|
2
| 9
|
9271853f3741add18822858cbad9d4f8e8104f54
| 110
|
plastique
|
Apache License 2.0
|
chat-persistence-cassandra/src/main/kotlin/com/demo/chat/persistence/cassandra/impl/MembershipPersistenceCassandra.kt
|
marios-code-path
| 181,180,043
| false
|
{"Kotlin": 924762, "Shell": 36602, "C": 3160, "HTML": 2714, "Starlark": 278}
|
package com.demo.chat.persistence.cassandra.impl
import com.demo.chat.domain.Key
import com.demo.chat.persistence.cassandra.domain.TopicMembershipByKey
import com.demo.chat.persistence.cassandra.repository.TopicMembershipRepository
import com.demo.chat.service.core.IKeyService
import com.demo.chat.service.core.MembershipPersistence
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.util.stream.Collectors
// TODO: Convert me to STREAM
class MembershipPersistenceCassandra<T>(
private val keyService: IKeyService<T>,
private val membershipRepo: TopicMembershipRepository<T>
) : MembershipPersistence<T> {
override fun key(): Mono<out Key<T>> = keyService.key(TopicMembershipByKey::class.java)
override fun add(ent: com.demo.chat.domain.TopicMembership<T>): Mono<Void> = membershipRepo
.save(
TopicMembershipByKey(
ent.key,
ent.member,
ent.memberOf)
)
.then()
override fun rem(key: Key<T>): Mono<Void> {
requireNotNull(key.id)
return membershipRepo.deleteById(key.id)
}
override fun get(key: Key<T>): Mono<out com.demo.chat.domain.TopicMembership<T>> = membershipRepo
.findByKey(key.id)
override fun all(): Flux<out com.demo.chat.domain.TopicMembership<T>> = membershipRepo.findAll()
override fun byIds(keys: List<Key<T>>): Flux<out com.demo.chat.domain.TopicMembership<T>> = membershipRepo
.findByKeyIn(keys.stream().map { it.id }.collect(Collectors.toList()))
}
| 2
|
Kotlin
|
1
| 9
|
2ae59375cd44e8fb58093b0f24596fc3111fd447
| 1,590
|
demo-chat
|
MIT License
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/versions/KotlinJvmMetadataVersionIndex.kt
|
JetBrains
| 2,489,216
| false
| null |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.versions
import com.intellij.ide.highlighter.JavaClassFileType
import com.intellij.util.indexing.DataIndexer
import com.intellij.util.indexing.DefaultFileTypeSpecificInputFilter
import com.intellij.util.indexing.FileContent
import org.jetbrains.kotlin.load.java.JvmAnnotationNames.*
import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion
import org.jetbrains.org.objectweb.asm.AnnotationVisitor
import org.jetbrains.org.objectweb.asm.ClassReader
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
object KotlinJvmMetadataVersionIndex : KotlinMetadataVersionIndexBase<KotlinJvmMetadataVersionIndex, JvmMetadataVersion>(
KotlinJvmMetadataVersionIndex::class.java
) {
override fun createBinaryVersion(versionArray: IntArray, extraBoolean: Boolean?): JvmMetadataVersion =
JvmMetadataVersion(versionArray, isStrictSemantics = extraBoolean!!)
override fun getIndexer() = INDEXER
override fun getInputFilter() = DefaultFileTypeSpecificInputFilter(JavaClassFileType.INSTANCE)
override fun getVersion() = 5
override fun isExtraBooleanNeeded(): Boolean = true
override fun getExtraBoolean(version: JvmMetadataVersion): Boolean = version.isStrictSemantics
private val kindsToIndex: Set<KotlinClassHeader.Kind> by lazy {
setOf(
KotlinClassHeader.Kind.CLASS,
KotlinClassHeader.Kind.FILE_FACADE,
KotlinClassHeader.Kind.MULTIFILE_CLASS
)
}
private val INDEXER: DataIndexer<JvmMetadataVersion, Void, FileContent> by lazy {
DataIndexer<JvmMetadataVersion, Void, FileContent> { inputData: FileContent ->
var versionArray: IntArray? = null
var isStrictSemantics = false
var annotationPresent = false
var kind: KotlinClassHeader.Kind? = null
tryBlock(inputData) {
val classReader = ClassReader(inputData.content)
classReader.accept(object : ClassVisitor(Opcodes.API_VERSION) {
override fun visitAnnotation(desc: String, visible: Boolean): AnnotationVisitor? {
if (desc != METADATA_DESC) return null
annotationPresent = true
return object : AnnotationVisitor(Opcodes.API_VERSION) {
override fun visit(name: String, value: Any) {
when (name) {
METADATA_VERSION_FIELD_NAME -> if (value is IntArray) {
versionArray = value
}
KIND_FIELD_NAME -> if (value is Int) {
kind = KotlinClassHeader.Kind.getById(value)
}
METADATA_EXTRA_INT_FIELD_NAME -> if (value is Int) {
isStrictSemantics = (value and METADATA_STRICT_VERSION_SEMANTICS_FLAG) != 0
}
}
}
}
}
}, ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES)
}
var version =
if (versionArray != null) createBinaryVersion(versionArray!!, isStrictSemantics) else null
if (kind !in kindsToIndex) {
// Do not index metadata version for synthetic classes
version = null
} else if (annotationPresent && version == null) {
// No version at all because the class is too old, or version is set to something weird
version = JvmMetadataVersion.INVALID_VERSION
}
if (version != null) mapOf(version to null) else emptyMap()
}
}
}
| 191
| null |
4372
| 13,319
|
4d19d247824d8005662f7bd0c03f88ae81d5364b
| 4,177
|
intellij-community
|
Apache License 2.0
|
flutter_navigations_2/android/app/src/main/kotlin/com/example/flutter_navigations_2/MainActivity.kt
|
shreyasSarve
| 437,082,913
| false
|
{"Dart": 207367, "HTML": 77327, "C++": 50468, "CMake": 23845, "Swift": 8197, "Kotlin": 2699, "C": 2202, "Objective-C": 769}
|
package com.example.flutter_navigations_2
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
Dart
|
0
| 1
|
a84a91356590e1c9ca2f734565c2d1ece8000cdb
| 138
|
FlutterBeginer
|
Apache License 2.0
|
app/src/main/java/com/salvador/breakingbad/domain/use_case/favorites/DeleteFavorite.kt
|
salvadordeveloper
| 463,598,581
| false
|
{"Kotlin": 50105}
|
package com.salvador.breakingbad.domain.use_case.favorites
import com.salvador.breakingbad.data.local.dto.FavoriteCharacter
import com.salvador.breakingbad.domain.repository.FavoriteCharacterRepository
import javax.inject.Inject
class DeleteFavorite @Inject constructor(private val repository : FavoriteCharacterRepository) {
suspend operator fun invoke(favorite: FavoriteCharacter){
repository.deleteFavorite(favorite)
}
}
| 0
|
Kotlin
|
0
| 4
|
7133b3510edd970e9e4c670479c600bec290febf
| 442
|
android-breaking-bad
|
MIT License
|
app/src/main/kotlin/me/xizzhu/android/joshua/search/result/SearchVerseItem.kt
|
hoc081098
| 424,862,923
| true
|
{"Kotlin": 1016945}
|
/*
* Copyright (C) 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.xizzhu.android.joshua.search.result
import android.annotation.SuppressLint
import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.ColorInt
import me.xizzhu.android.joshua.R
import me.xizzhu.android.joshua.core.Highlight
import me.xizzhu.android.joshua.core.Settings
import me.xizzhu.android.joshua.core.VerseIndex
import me.xizzhu.android.joshua.ui.*
import me.xizzhu.android.joshua.ui.recyclerview.BaseItem
import me.xizzhu.android.joshua.ui.recyclerview.BaseViewHolder
import java.util.*
data class SearchVerseItem(val verseIndex: VerseIndex, private val bookShortName: String,
private val text: String, private val query: String,
@ColorInt private val highlightColor: Int,
val onClicked: (VerseIndex) -> Unit)
: BaseItem(R.layout.item_search_verse, { inflater, parent -> SearchVerseItemViewHolder(inflater, parent) }) {
companion object {
// We don't expect users to change locale that frequently.
@SuppressLint("ConstantLocale")
private val DEFAULT_LOCALE = Locale.getDefault()
private val BOOK_NAME_SIZE_SPAN = createTitleSizeSpan()
private val BOOK_NAME_STYLE_SPAN = createTitleStyleSpan()
private val KEYWORD_SIZE_SPAN = createKeywordSizeSpan()
private val KEYWORD_STYLE_SPAN = createKeywordStyleSpan()
private val SPANNABLE_STRING_BUILDER = SpannableStringBuilder()
}
val textForDisplay: CharSequence by lazy {
// format:
// <short book name> <chapter verseIndex>:<verse verseIndex>
// <verse text>
SPANNABLE_STRING_BUILDER.clearAll()
.append(bookShortName)
.append(' ')
.append(verseIndex.chapterIndex + 1).append(':').append(verseIndex.verseIndex + 1)
.setSpan(BOOK_NAME_SIZE_SPAN, BOOK_NAME_STYLE_SPAN)
.append('\n')
.append(text)
// highlights the keywords
val textStartIndex = SPANNABLE_STRING_BUILDER.length - text.length
val lowerCase = SPANNABLE_STRING_BUILDER.toString().toLowerCase(DEFAULT_LOCALE)
for ((index, keyword) in query.trim().replace("\\s+", " ").split(" ").withIndex()) {
val start = lowerCase.indexOf(keyword.toLowerCase(DEFAULT_LOCALE), textStartIndex)
if (start > 0) {
SPANNABLE_STRING_BUILDER.setSpan(
if (index == 0) KEYWORD_SIZE_SPAN else createKeywordSizeSpan(),
if (index == 0) KEYWORD_STYLE_SPAN else createKeywordStyleSpan(),
start, start + keyword.length)
}
}
// highlights the verse if needed
if (highlightColor != Highlight.COLOR_NONE) {
SPANNABLE_STRING_BUILDER.setSpan(
BackgroundColorSpan(highlightColor),
ForegroundColorSpan(if (highlightColor == Highlight.COLOR_BLUE) Color.WHITE else Color.BLACK),
SPANNABLE_STRING_BUILDER.length - text.length, SPANNABLE_STRING_BUILDER.length
)
}
return@lazy SPANNABLE_STRING_BUILDER.toCharSequence()
}
}
private class SearchVerseItemViewHolder(inflater: LayoutInflater, parent: ViewGroup)
: BaseViewHolder<SearchVerseItem>(inflater.inflate(R.layout.item_search_verse, parent, false)) {
private val text = itemView as TextView
init {
itemView.setOnClickListener { item?.let { it.onClicked(it.verseIndex) } }
}
override fun bind(settings: Settings, item: SearchVerseItem, payloads: List<Any>) {
with(text) {
updateSettingsWithPrimaryText(settings)
text = item.textForDisplay
}
}
}
| 0
| null |
0
| 0
|
db9b681ca744bb9dc4a415cf1dec0de7e3f8fa1a
| 4,557
|
Joshua
|
Apache License 2.0
|
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/focus/FocusObserverTest.kt
|
tikurahul
| 334,969,342
| false
| null |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.focus
import androidx.compose.foundation.Box
import androidx.compose.ui.FocusModifier
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus
import androidx.compose.ui.focus.FocusState.Active
import androidx.compose.ui.focus.FocusState.ActiveParent
import androidx.compose.ui.focus.FocusState.Captured
import androidx.compose.ui.focus.FocusState.Disabled
import androidx.compose.ui.focus.FocusState.Inactive
import androidx.compose.ui.focusObserver
import androidx.compose.ui.focusRequester
import androidx.test.filters.SmallTest
import androidx.ui.test.createComposeRule
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@SmallTest
@OptIn(ExperimentalFocus::class)
@RunWith(JUnit4::class)
class FocusObserverTest {
@get:Rule
val rule = createComposeRule()
@Test
fun active_requestFocus() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
rule.setFocusableContent {
Box(
modifier = Modifier
.focusObserver { focusState = it }
.focusRequester(focusRequester)
.then(FocusModifier(Active))
)
}
rule.runOnIdle {
// Act.
focusRequester.requestFocus()
// Assert.
assertThat(focusState).isEqualTo(Active)
}
}
@Test
fun activeParent_requestFocus() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
val childFocusRequester = FocusRequester()
rule.setFocusableContent {
Box(
modifier = Modifier
.focusObserver { focusState = it }
.focusRequester(focusRequester)
.focus()
) {
Box(
modifier = Modifier
.focusRequester(childFocusRequester)
.focus()
)
}
}
rule.runOnIdle {
childFocusRequester.requestFocus()
assertThat(focusState).isEqualTo(ActiveParent)
}
rule.runOnIdle {
// Act.
focusRequester.requestFocus()
// Assert.
assertThat(focusState).isEqualTo(Active)
}
}
@Test
fun captured_requestFocus() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
rule.setFocusableContent {
Box(
modifier = Modifier
.focusObserver { focusState = it }
.focusRequester(focusRequester)
.then(FocusModifier(Captured))
)
}
rule.runOnIdle {
// Act.
focusRequester.requestFocus()
// Assert.
assertThat(focusState).isEqualTo(Captured)
}
}
@Test
fun disabled_requestFocus() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
rule.setFocusableContent {
Box(
modifier = Modifier
.focusObserver { focusState = it }
.focusRequester(focusRequester)
.then(FocusModifier(Disabled))
)
}
rule.runOnIdle {
// Act.
focusRequester.requestFocus()
// Assert.
assertThat(focusState).isEqualTo(Disabled)
}
}
@Test
fun inactive_requestFocus() {
// Arrange.
lateinit var focusState: FocusState
val focusRequester = FocusRequester()
rule.setFocusableContent {
Box(
modifier = Modifier
.focusObserver { focusState = it }
.focusRequester(focusRequester)
.then(FocusModifier(Inactive))
)
}
rule.runOnIdle {
// Act.
focusRequester.requestFocus()
// Assert.
assertThat(focusState).isEqualTo(Active)
}
}
@Test
fun inactive_requestFocus_multipleObservers() {
// Arrange.
lateinit var focusState1: FocusState
lateinit var focusState2: FocusState
lateinit var focusState3: FocusState
lateinit var focusState4: FocusState
lateinit var focusState5: FocusState
lateinit var focusState6: FocusState
val focusRequester = FocusRequester()
rule.setFocusableContent {
Box(
modifier = Modifier
.focusObserver { focusState1 = it }
.focusObserver { focusState2 = it }
) {
Box {
Box(
modifier = Modifier
.focusObserver { focusState3 = it }
.focusObserver { focusState4 = it }
) {
Box(
modifier = Modifier
.focusObserver { focusState5 = it }
.focusObserver { focusState6 = it }
.focusRequester(focusRequester)
.then(FocusModifier(Inactive))
)
}
}
}
}
rule.runOnIdle {
// Act.
focusRequester.requestFocus()
// Assert.
assertThat(focusState1).isEqualTo(Active)
assertThat(focusState2).isEqualTo(Active)
assertThat(focusState3).isEqualTo(Active)
assertThat(focusState4).isEqualTo(Active)
assertThat(focusState5).isEqualTo(Active)
assertThat(focusState6).isEqualTo(Active)
}
}
@Test
fun active_requestFocus_multipleObserversWithExtraFocusModifierInBetween() {
// Arrange.
var focusState1: FocusState? = null
var focusState2: FocusState? = null
var focusState3: FocusState? = null
var focusState4: FocusState? = null
val focusRequester = FocusRequester()
rule.setFocusableContent {
Box(
modifier = Modifier
.focusObserver { focusState1 = it }
.focusObserver { focusState2 = it }
.focus()
.focusObserver { focusState3 = it }
.focusObserver { focusState4 = it }
.focusRequester(focusRequester)
.focus()
)
}
rule.runOnIdle {
focusRequester.requestFocus()
focusState1 = null
focusState2 = null
focusState3 = null
focusState4 = null
}
rule.runOnIdle {
// Act.
focusRequester.requestFocus()
// Assert.
assertThat(focusState1).isNull()
assertThat(focusState2).isNull()
assertThat(focusState3).isEqualTo(Active)
assertThat(focusState4).isEqualTo(Active)
}
}
}
| 11
| null |
1
| 1
|
fa4711838092061ca02409b998a59f12ef0b7143
| 7,973
|
androidx
|
Apache License 2.0
|
framework-docs/src/main/kotlin/org/springframework/docs/core/aop/ataspectj/aopataspectj/ApplicationConfiguration.kt
|
spring-projects
| 1,148,753
| false
|
{"Java": 48416901, "Kotlin": 969803, "AspectJ": 31773, "FreeMarker": 31129, "Groovy": 6902, "XSLT": 2945, "HTML": 1140, "Ruby": 1060, "CSS": 1019, "Shell": 961, "Smarty": 717, "PLpgSQL": 305, "JavaScript": 280, "Python": 254}
|
/*
* Copyright 2002-2024 the original author or authors.
*
* 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 org.springframework.docs.core.aop.ataspectj.aopataspectj
import org.springframework.context.annotation.Bean
// tag::snippet[]
class ApplicationConfiguration {
@Bean
fun myAspect() = NotVeryUsefulAspect().apply {
// Configure properties of the aspect here
}
}
// end::snippet[]
| 4
|
Java
|
4
| 56,506
|
52e813d0ad2a5d3439c1880b481b6942a138a8dc
| 916
|
spring-framework
|
Apache License 2.0
|
app/src/main/java/com/hms/referenceapp/hifood/adapter/RecipeListAdapter.kt
|
Explore-In-HMS
| 379,893,524
| false
| null |
/* Copyright 2020. Explore in HMS. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* 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.hms.referenceapp.hifood.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hms.referenceapp.hifood.R
import com.hms.referenceapp.hifood.model.RecipeSummary
import com.hms.referenceapp.hifood.utils.RecipeImageGetter
import kotlinx.android.synthetic.main.item_recipes.view.*
class RecipeListAdapter(
var recipes: ArrayList<RecipeSummary>,
var clickListener: OnRecipeClickListener
) : RecyclerView.Adapter<RecipeListAdapter.RecipeViewHolder>() {
fun updateRecipes(newRecipes: List<RecipeSummary>) {
recipes.clear()
recipes.addAll(newRecipes)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = RecipeViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.item_recipes, parent, false)
)
override fun getItemCount() = recipes.size
override fun onBindViewHolder(holder: RecipeListAdapter.RecipeViewHolder, position: Int) {
holder.bind(recipes[position], clickListener)
}
class RecipeViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val recipeName = view.recipe_name
private val recipeImage = view.recipe_image
fun bind(recipe: RecipeSummary, action: OnRecipeClickListener) {
recipeName.text = recipe.name
recipeImage.setImageResource(RecipeImageGetter.getImageSource(recipe.name))
itemView.setOnClickListener {
action.onItemClick(recipe)
}
}
}
}
interface OnRecipeClickListener {
fun onItemClick(item: RecipeSummary)
}
| 0
|
Kotlin
|
0
| 0
|
c8a709e1af8cadd9e7e2862d7879a943da94c2bc
| 2,235
|
Hi-Food
|
Apache License 2.0
|
app/src/main/java/xyz/daijoubuteam/foodshoppingapp/services/AppFirebaseMessagingService.kt
|
dinhlockt02
| 477,610,621
| false
| null |
package xyz.daijoubuteam.foodshoppingapp.services
import android.app.Notification
import android.app.Notification.DEFAULT_SOUND
import android.app.Notification.DEFAULT_VIBRATE
import android.app.NotificationManager
import android.content.ContentResolver
import android.content.Context
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import timber.log.Timber
import xyz.daijoubuteam.foodshoppingapp.R
import java.lang.Exception
import kotlin.math.roundToInt
class AppFirebaseMessagingService : FirebaseMessagingService() {
private val job = SupervisorJob()
private val scope = CoroutineScope(Dispatchers.IO + job)
private val db = Firebase.firestore
override fun onNewToken(token: String) {
super.onNewToken(token)
Timber.i(token)
}
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
Timber.i(message.notification?.body);
scope.launch {
try {
val userId = Firebase.auth.currentUser?.uid
if (userId.isNullOrEmpty()) return@launch
val userRef = db.collection("users").document(userId)
val user = userRef.get().await()
if (!user.exists()) return@launch
val notificationRef = userRef.collection("notifications").document()
val notification = xyz.daijoubuteam.foodshoppingapp.model.Notification(
null,
message.notification?.title ?: "",
message.notification?.body ?: "",
null,
false,
)
Timber.i("notification")
db.runBatch {
batch ->
batch.set(notificationRef, notification)
}.addOnSuccessListener {
startedNotify(message)
}
} catch (e: Exception) {
Timber.e(e);
return@launch
}
}
}
private fun startedNotify(message: RemoteMessage) {
val alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val builder = NotificationCompat.Builder(this, getString(R.string.CHANNEL_ID))
.setSmallIcon(R.drawable.bell_outline)
.setContentTitle(message.notification?.title ?: "")
.setContentText(message.notification?.body ?: "")
.setSound(alarmSound)
.setAutoCancel(true)
.setPriority(NotificationManager.IMPORTANCE_HIGH)
with(NotificationManagerCompat.from(this))
{
notify(0, builder.build());
}
}
}
| 0
|
Kotlin
|
1
| 0
|
be52b08b48f5dd0c5b2786e243288d947219fdfd
| 3,380
|
FoodShoppingApp
|
MIT License
|
DSLs/kubernetes/dsl/src/main/kotlin-gen/dev/forkhandles/k8s/networking/v1/podSelector.kt
|
fork-handles
| 649,794,132
| false
|
{"Kotlin": 575626, "Shell": 2264, "Just": 1042, "Nix": 740}
|
// GENERATED
package dev.forkhandles.k8s.networking.v1
import io.fabric8.kubernetes.api.model.LabelSelector as model_LabelSelector
import io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer as v1_NetworkPolicyPeer
import io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicySpec as v1_NetworkPolicySpec
fun v1_NetworkPolicyPeer.podSelector(block: model_LabelSelector.() -> Unit = {}) {
if (podSelector == null) {
podSelector = model_LabelSelector()
}
podSelector.block()
}
fun v1_NetworkPolicySpec.podSelector(block: model_LabelSelector.() -> Unit = {}) {
if (podSelector == null) {
podSelector = model_LabelSelector()
}
podSelector.block()
}
| 0
|
Kotlin
|
0
| 9
|
68221cee577ea16dc498745606d07b0fb62f5cb7
| 706
|
k8s-dsl
|
MIT License
|
libraries/matrix/api/src/main/kotlin/io/element/android/libraries/matrix/api/poll/PollKind.kt
|
vector-im
| 546,522,002
| false
| null |
/*
* Copyright (c) 2023 New Vector Ltd
*
* 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.element.android.libraries.matrix.api.poll
enum class PollKind {
/** Voters should see results as soon as they have voted. */
Disclosed,
/** Results should be only revealed when the poll is ended. */
Undisclosed
}
| 105
| null |
32
| 287
|
4587b51bd33e8b5a2e2c81c79f3aa70a3ac52923
| 844
|
element-x-android
|
Apache License 2.0
|
src/main/kotlin/com/github/mmauro94/mkvtoolnix_wrapper/json/MkvToolnixLanguageConverter.kt
|
MMauro94
| 173,610,080
| false
| null |
package com.github.mmauro94.mkvtoolnix_wrapper.json
import com.beust.klaxon.Converter
import com.beust.klaxon.JsonValue
import com.beust.klaxon.KlaxonException
import com.github.mmauro94.mkvtoolnix_wrapper.MkvToolnixLanguage
internal object MkvToolnixLanguageConverter : Converter {
override fun canConvert(cls: Class<*>) = cls == MkvToolnixLanguage::class.java
override fun fromJson(jv: JsonValue) =
jv.string?.let { MkvToolnixLanguage.all[it] ?: throw KlaxonException("Invalid language code $it") }
override fun toJson(value: Any): String {
return if (value is MkvToolnixLanguage) "\"" + value.iso639_3 + "\""
else throw KlaxonException("Must be MkvToolnixLanguage")
}
}
| 0
|
Kotlin
|
1
| 2
|
2f87c63e47e5c85f039b6536aeb574bb9e0b3e84
| 717
|
mkvtoolnix-wrapper
|
MIT License
|
kamp-core/src/main/kotlin/ch/leadrian/samp/kamp/core/runtime/data/MutableVector2DImpl.kt
|
Double-O-Seven
| 142,487,686
| false
|
{"Kotlin": 3854710, "C": 23964, "C++": 23699, "Java": 4753, "Dockerfile": 769, "Objective-C": 328, "Batchfile": 189}
|
package ch.leadrian.samp.kamp.core.runtime.data
import ch.leadrian.samp.kamp.core.api.data.MutableVector2D
import ch.leadrian.samp.kamp.core.api.data.Vector2D
internal data class MutableVector2DImpl(
override var x: Float,
override var y: Float
) : MutableVector2D {
override fun toVector2D(): Vector2D = Vector2DImpl(
x = x,
y = y
)
override fun toMutableVector2D(): MutableVector2D = this
override fun plus(other: Vector2D): MutableVector2D = copy(
x = this.x + other.x,
y = this.y + other.y
)
override fun minus(other: Vector2D): MutableVector2D = copy(
x = this.x - other.x,
y = this.y - other.y
)
override fun times(value: Float): MutableVector2D = copy(
x = this.x * value,
y = this.y * value
)
override fun div(value: Float): MutableVector2D = copy(
x = this.x / value,
y = this.y / value
)
}
| 1
|
Kotlin
|
1
| 7
|
af07b6048210ed6990e8b430b3a091dc6f64c6d9
| 988
|
kamp
|
Apache License 2.0
|
vire-engine/src/main/kotlin/net/voxelpi/vire/engine/circuit/CircuitInstance.kt
|
VoxelPi
| 700,036,011
| false
|
{"Kotlin": 336370}
|
package net.voxelpi.vire.engine.circuit
import net.voxelpi.vire.engine.circuit.component.Component
import net.voxelpi.vire.engine.kernel.KernelInstance
import java.util.UUID
public interface CircuitInstance {
public operator fun get(component: Component): KernelInstance
}
public interface MutableCircuitInstance : CircuitInstance {
public operator fun set(component: Component, instance: KernelInstance)
}
internal class MutableCircuitInstanceImpl(
val componentInstances: MutableMap<UUID, KernelInstance>,
) : MutableCircuitInstance {
override fun get(component: Component): KernelInstance {
return componentInstances[component.uniqueId]!!
}
override fun set(component: Component, instance: KernelInstance) {
componentInstances[component.uniqueId] = instance
}
}
internal fun emptyCircuitInstance(): MutableCircuitInstanceImpl {
return MutableCircuitInstanceImpl(mutableMapOf())
}
| 1
|
Kotlin
|
0
| 0
|
d7823aa5aa361a1fa5e5057b10433fa5194a0ffd
| 940
|
Vire
|
MIT License
|
src/main/kotlin/github/samyycx/fisherman/modules/gameconfig/rod/RodManager.kt
|
samyycX
| 742,795,853
| false
|
{"Kotlin": 42404, "Java": 351}
|
package github.samyycx.fisherman.modules.gameconfig.rod
import org.bukkit.configuration.file.YamlConfiguration
import taboolib.module.chat.colored
import java.io.File
object RodManager {
private var defaultRod: Rod? = null
private val rods = mutableMapOf<String, Rod>()
fun setup(folder: File, defaultConfig: YamlConfiguration) {
defaultRod = null
rods.clear()
folder
.listFiles { _, name -> name.endsWith(".yml") }
?.forEach {
val config = YamlConfiguration.loadConfiguration(it)
config.getKeys(false).forEach { it2 ->
rods[it2] = RodParser.parseFromSection(config.getConfigurationSection(it2)!!)
}
}
if (defaultConfig.contains("VanillaRodOverride")) {
defaultRod = RodParser.parseFromSection(defaultConfig.getConfigurationSection("VanillaRodOverride")!!)
}
}
fun getById(id: String): Rod? {
return rods[id]
}
fun getByName(name: String?): Rod? {
if (name == null) return null
return rods.values.firstOrNull { rod -> rod.name.colored() == name }
}
fun vanillaOverrided(): Boolean {
return defaultRod == null
}
// 请先调用vanillaOverrided判断
fun getVanillaOverrideRod(): Rod {
return defaultRod!!
}
}
| 0
|
Kotlin
|
0
| 0
|
8336b73de9e8461612791651aec6ef9f246e92ac
| 1,356
|
Fisherman
|
MIT License
|
app/src/main/java/com/bentrengrove/chess/engine/AI.kt
|
bentrengrove
| 310,423,951
| false
|
{"Kotlin": 42321}
|
package com.bentrengrove.chess
class AI(val color: PieceColor) {
// This AI doesn't work at all currently
fun calculateNextMove(game: Game, player: PieceColor): Move? {
return search(game, 0, player).getOrNull(0)?.first
}
fun search(game: Game, depth: Int, player: PieceColor): List<Pair<Move, Int>> {
return game.allMovesFor(game.turn)
.mapNotNull {
val newGame = game.doMove(it.from, it.to)
if (depth > 0 && game.turn == player) {
val best = search(newGame, depth - 1, player).firstOrNull()?.second ?: return@mapNotNull null
it to best
} else {
it to (newGame.valueFor(player) - newGame.valueFor(player.other()))
}
}
.sortedByDescending { it.second }
.shuffled()
.distinctBy { it.second }
.toList()
}
}
| 1
|
Kotlin
|
6
| 47
|
97f91217f191ea9308d7dff6ebfc7a3d5534d134
| 990
|
chess
|
MIT License
|
app/src/main/java/com/ajce/hostelmate/sickleave/SickLeaveViewModel.kt
|
Jithin-Jude
| 256,905,231
| false
| null |
package com.ajce.hostelmate.sickleave
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import com.ajce.hostelmate.FirebaseQueryLiveData
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.FirebaseDatabase
/**
* Created by JithinJude on 02,May,2020
*/
class SickLeaveViewModel : ViewModel() {
private val SICK_LEAVE_REF = FirebaseDatabase.getInstance().getReference("sickleave")
private val liveData = FirebaseQueryLiveData(SICK_LEAVE_REF)
fun getDataSnapshotLiveData(): LiveData<DataSnapshot?> {
return liveData
}
}
| 0
|
Kotlin
|
1
| 1
|
da95b289d6767dceec57e07718f0ad283ad1dfc4
| 600
|
HostelMate_AJCE
|
MIT License
|
komga_client/src/commonMain/kotlin/io/github/snd_r/komga/collection/KomgaCollectionClient.kt
|
Snd-R
| 775,064,249
| false
|
{"Kotlin": 1035469, "CMake": 18341, "C": 5487, "Dockerfile": 767, "JavaScript": 695, "HTML": 447, "Shell": 238}
|
package io.github.snd_r.komga.collection
import io.github.snd_r.komga.common.KomgaPageRequest
import io.github.snd_r.komga.common.Page
import io.github.snd_r.komga.common.toParams
import io.github.snd_r.komga.library.KomgaLibraryId
import io.github.snd_r.komga.series.KomgaSeries
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
class KomgaCollectionClient internal constructor(private val ktor: HttpClient) {
suspend fun getAll(
search: String? = null,
libraryIds: List<KomgaLibraryId>? = null,
pageRequest: KomgaPageRequest? = null,
): Page<KomgaCollection> {
return ktor.get("api/v1/collections") {
url.parameters.apply {
search?.let { append("search", it) }
libraryIds?.let { ids -> if (ids.isNotEmpty()) append("library_id", ids.joinToString()) }
pageRequest?.let { appendAll(it.toParams()) }
}
}.body()
}
suspend fun getOne(id: KomgaCollectionId): KomgaCollection {
return ktor.get("api/v1/collections/$id").body()
}
suspend fun addOne(request: KomgaCollectionCreateRequest): KomgaCollection {
return ktor.post("api/v1/collections") {
contentType(ContentType.Application.Json)
setBody(request)
}.body()
}
suspend fun updateOne(id: KomgaCollectionId, request: KomgaCollectionUpdateRequest) {
ktor.patch("api/v1/collections/$id") {
contentType(ContentType.Application.Json)
setBody(request)
}
}
suspend fun deleteOne(id: KomgaCollectionId) {
ktor.delete("api/v1/collections/$id")
}
suspend fun getSeriesForCollection(
id: KomgaCollectionId,
query: KomgaCollectionQuery? = null,
pageRequest: KomgaPageRequest? = null,
): Page<KomgaSeries> {
return ktor.get("api/v1/collections/$id/series") {
url.parameters.apply {
query?.libraryIds?.let { append("library_id", it.joinToString()) }
query?.readStatus?.let { append("read_status", it.joinToString()) }
query?.status?.let { append("status", it.joinToString()) }
query?.languages?.let { append("language", it.joinToString()) }
query?.publishers?.let { append("publisher", it.joinToString()) }
query?.tags?.let { append("tag", it.joinToString()) }
query?.genres?.let { append("genre", it.joinToString()) }
query?.ageRatings?.let { append("age_rating", it.joinToString()) }
query?.releaseYears?.let { append("release_year", it.joinToString()) }
query?.authors?.let { authors ->
append("authors", authors.joinToString { "${it.name},${it.role}" })
}
query?.complete?.let { append("complete", it.toString()) }
query?.deleted?.let { append("deleted", it.toString()) }
pageRequest?.let { appendAll(it.toParams()) }
}
}.body()
}
}
| 0
|
Kotlin
|
0
| 3
|
80f52077176665756f62a40ff9f76041e3051c62
| 3,110
|
Komelia
|
Apache License 2.0
|
src/test/kotlin/no/nav/familie/ef/sak/beregning/OmregningServiceTest.kt
|
navikt
| 206,805,010
| false
| null |
package no.nav.familie.ef.sak.beregning
import com.fasterxml.jackson.module.kotlin.readValue
import io.mockk.clearMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import no.nav.familie.ef.sak.OppslagSpringRunnerTest
import no.nav.familie.ef.sak.barn.BarnRepository
import no.nav.familie.ef.sak.barn.BehandlingBarn
import no.nav.familie.ef.sak.behandling.BehandlingRepository
import no.nav.familie.ef.sak.behandling.domain.Behandling
import no.nav.familie.ef.sak.behandling.domain.BehandlingResultat
import no.nav.familie.ef.sak.behandling.domain.BehandlingStatus
import no.nav.familie.ef.sak.fagsak.FagsakService
import no.nav.familie.ef.sak.fagsak.domain.Fagsak
import no.nav.familie.ef.sak.fagsak.domain.PersonIdent
import no.nav.familie.ef.sak.infrastruktur.config.ObjectMapperProvider
import no.nav.familie.ef.sak.iverksett.IverksettClient
import no.nav.familie.ef.sak.opplysninger.personopplysninger.PersonService
import no.nav.familie.ef.sak.opplysninger.personopplysninger.dto.Sivilstandstype
import no.nav.familie.ef.sak.opplysninger.personopplysninger.pdl.PdlIdent
import no.nav.familie.ef.sak.opplysninger.personopplysninger.pdl.PdlIdenter
import no.nav.familie.ef.sak.opplysninger.søknad.SøknadService
import no.nav.familie.ef.sak.repository.behandling
import no.nav.familie.ef.sak.repository.behandlingBarn
import no.nav.familie.ef.sak.repository.fagsak
import no.nav.familie.ef.sak.repository.inntektsperiode
import no.nav.familie.ef.sak.repository.tilkjentYtelse
import no.nav.familie.ef.sak.repository.vedtak
import no.nav.familie.ef.sak.repository.vedtaksperiode
import no.nav.familie.ef.sak.tilkjentytelse.TilkjentYtelseRepository
import no.nav.familie.ef.sak.vedtak.VedtakRepository
import no.nav.familie.ef.sak.vedtak.domain.InntektWrapper
import no.nav.familie.ef.sak.vedtak.domain.PeriodeWrapper
import no.nav.familie.ef.sak.vedtak.domain.VedtaksperiodeType
import no.nav.familie.ef.sak.vilkår.DelvilkårsvurderingWrapper
import no.nav.familie.ef.sak.vilkår.VilkårType
import no.nav.familie.ef.sak.vilkår.Vilkårsresultat
import no.nav.familie.ef.sak.vilkår.Vilkårsvurdering
import no.nav.familie.ef.sak.vilkår.VilkårsvurderingRepository
import no.nav.familie.ef.sak.vilkår.regler.HovedregelMetadata
import no.nav.familie.ef.sak.vilkår.regler.vilkårsreglerForStønad
import no.nav.familie.kontrakter.ef.felles.BehandlingÅrsak
import no.nav.familie.kontrakter.ef.iverksett.IverksettOvergangsstønadDto
import no.nav.familie.kontrakter.ef.søknad.Testsøknad
import no.nav.familie.kontrakter.felles.ef.StønadType
import no.nav.familie.prosessering.domene.TaskRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import java.time.LocalDateTime
import java.util.UUID
internal class OmregningServiceTest : OppslagSpringRunnerTest() {
@Autowired
lateinit var fagsakService: FagsakService
@Autowired
lateinit var omregningService: OmregningService
@Autowired
lateinit var behandlingRepository: BehandlingRepository
@Autowired
lateinit var vedtakRepository: VedtakRepository
@Autowired
lateinit var tilkjentYtelseRepository: TilkjentYtelseRepository
@Autowired
lateinit var taskRepository: TaskRepository
@Autowired
lateinit var iverksettClient: IverksettClient
@Autowired
lateinit var vilkårsvurderingRepository: VilkårsvurderingRepository
@Autowired
lateinit var barnRepository: BarnRepository
@Autowired
lateinit var søknadService: SøknadService
val personService = mockk<PersonService>()
val år = nyesteGrunnbeløpGyldigFraOgMed.year
@BeforeEach
fun setup() {
every { personService.hentPersonIdenter(any()) } returns PdlIdenter(listOf(PdlIdent("321", false)))
clearMocks(iverksettClient, answers = false)
}
/**
* Denne brekker hver gang det kommer nytt G-beløp.
* Beløp må oppdateres i omregnes i expectedIverksettDto.json.
*/
@Test
fun `utførGOmregning kaller iverksettUtenBrev med korrekt iverksettDto `() {
val fagsakId = UUID.fromString("<KEY>")
val behandlingId = UUID.fromString("39c7dc82-adc1-43db-a6f9-64b8e4352ff6")
val fagsak = testoppsettService.lagreFagsak(fagsak(id = fagsakId, identer = setOf(PersonIdent("321"))))
val behandling = behandlingRepository.insert(
behandling(
id = behandlingId,
fagsak = fagsak,
resultat = BehandlingResultat.INNVILGET,
status = BehandlingStatus.FERDIGSTILT
)
)
tilkjentYtelseRepository.insert(tilkjentYtelse(behandling.id, "321", år))
vedtakRepository.insert(vedtak(behandling.id, år = år))
val barn = barnRepository.insert(
behandlingBarn(
behandlingId = behandling.id,
personIdent = "01012067050",
navn = "<NAME>"
)
)
søknadService.lagreSøknadForOvergangsstønad(Testsøknad.søknadOvergangsstønad, behandling.id, fagsak.id, "1L")
val vilkårsvurderinger = lagVilkårsvurderinger(barn, behandlingId)
vilkårsvurderingRepository.insertAll(vilkårsvurderinger)
omregningService.utførGOmregning(fagsakId)
val nyBehandling = behandlingRepository.findByFagsakId(fagsakId).single { it.årsak == BehandlingÅrsak.G_OMREGNING }
assertThat(taskRepository.findAll().find { it.type == "pollerStatusFraIverksett" }).isNotNull
val iverksettDtoSlot = slot<IverksettOvergangsstønadDto>()
verify { iverksettClient.iverksettUtenBrev(capture(iverksettDtoSlot)) }
val iverksettDto = iverksettDtoSlot.captured
val expectedIverksettDto = iverksettMedOppdaterteIder(fagsak, behandling, iverksettDto.vedtak.vedtakstidspunkt)
assertThat(iverksettDto).usingRecursiveComparison()
.ignoringFields("behandling.vilkårsvurderinger")
.isEqualTo(expectedIverksettDto)
assertThat(iverksettDto.behandling.vilkårsvurderinger)
.hasSameElementsAs(expectedIverksettDto.behandling.vilkårsvurderinger)
assertThat(søknadService.hentSøknadsgrunnlag(nyBehandling.id)).isNotNull
assertThat(barnRepository.findByBehandlingId(nyBehandling.id).single().personIdent).isEqualTo(barn.personIdent)
assertThat(
vilkårsvurderingRepository.findByBehandlingId(nyBehandling.id).single { it.type == VilkårType.ALENEOMSORG }.barnId
).isNotNull
}
@Test
fun `utførGOmregning med samordningsfradrag returner og etterlater seg ingen spor i databasen i live run`() {
val fagsak = testoppsettService.lagreFagsak(fagsak(identer = setOf(PersonIdent("321"))))
val behandling = behandlingRepository.insert(
behandling(
fagsak = fagsak,
resultat = BehandlingResultat.INNVILGET,
status = BehandlingStatus.FERDIGSTILT
)
)
tilkjentYtelseRepository.insert(tilkjentYtelse(behandling.id, "321", år, samordningsfradrag = 10))
val inntektsperiode = inntektsperiode(år = år, samordningsfradrag = 100.toBigDecimal())
vedtakRepository.insert(vedtak(behandling.id, år = år, inntekter = InntektWrapper(listOf(inntektsperiode))))
omregningService.utførGOmregning(fagsak.id)
assertThat(taskRepository.findAll().find { it.type == "pollerStatusFraIverksett" }).isNull()
assertThat(behandlingRepository.findByFagsakId(fagsak.id).size).isEqualTo(1)
verify(exactly = 0) { iverksettClient.simuler(any()) }
verify(exactly = 0) { iverksettClient.iverksettUtenBrev(any()) }
}
@Test
fun `utførGOmregning med sanksjon returner og etterlater seg ingen spor i databasen i live run`() {
val fagsak = testoppsettService.lagreFagsak(fagsak(identer = setOf(PersonIdent("321"))))
val behandling = behandlingRepository.insert(
behandling(
fagsak = fagsak,
resultat = BehandlingResultat.INNVILGET,
status = BehandlingStatus.FERDIGSTILT
)
)
tilkjentYtelseRepository.insert(tilkjentYtelse(behandling.id, "321", år, samordningsfradrag = 10))
val inntektsperiode = inntektsperiode(år = år, samordningsfradrag = 100.toBigDecimal())
val vedtaksperiode = vedtaksperiode(år = år, vedtaksperiodeType = VedtaksperiodeType.SANKSJON)
vedtakRepository.insert(
vedtak(
behandlingId = behandling.id,
år = år,
inntekter = InntektWrapper(listOf(inntektsperiode)),
perioder = PeriodeWrapper(listOf(vedtaksperiode))
)
)
omregningService.utførGOmregning(fagsak.id)
assertThat(taskRepository.findAll().find { it.type == "pollerStatusFraIverksett" }).isNull()
assertThat(behandlingRepository.findByFagsakId(fagsak.id).size).isEqualTo(1)
verify(exactly = 0) { iverksettClient.simuler(any()) }
verify(exactly = 0) { iverksettClient.iverksettUtenBrev(any()) }
}
private fun lagVilkårsvurderinger(
barn: BehandlingBarn,
behandlingId: UUID
): List<Vilkårsvurdering> {
val vilkårsvurderinger = vilkårsreglerForStønad(StønadType.OVERGANGSSTØNAD).map { vilkårsregel ->
val delvilkårsvurdering = vilkårsregel.initereDelvilkårsvurdering(
HovedregelMetadata(
sivilstandSøknad = null,
sivilstandstype = Sivilstandstype.UGIFT,
erMigrering = false,
barn = listOf(barn),
søktOmBarnetilsyn = emptyList()
)
)
Vilkårsvurdering(
behandlingId = behandlingId,
resultat = Vilkårsresultat.OPPFYLT,
type = vilkårsregel.vilkårType,
barnId = if (vilkårsregel.vilkårType == VilkårType.ALENEOMSORG) barn.id else null,
delvilkårsvurdering = DelvilkårsvurderingWrapper(
delvilkårsvurdering.map {
it.copy(
resultat = Vilkårsresultat.OPPFYLT,
vurderinger = it.vurderinger.map { vurdering ->
vurdering.copy(begrunnelse = "Godkjent")
}
)
}
)
)
}
return vilkårsvurderinger
}
fun iverksettMedOppdaterteIder(
fagsak: Fagsak,
behandling: Behandling,
vedtakstidspunkt: LocalDateTime
): IverksettOvergangsstønadDto {
val personidenter = fagsak.personIdenter.map { it.ident }.toSet()
val forrigeBehandling = fagsakService.finnFagsak(personidenter, StønadType.OVERGANGSSTØNAD)?.let {
behandlingRepository.findByFagsakId(it.id).maxByOrNull { it.sporbar.opprettetTid }
} ?: error("Finner ikke tidligere iverksatt behandling")
val expectedIverksettDto: IverksettOvergangsstønadDto =
ObjectMapperProvider.objectMapper.readValue(readFile("expectedIverksettDto.json"))
val andelerTilkjentYtelse = expectedIverksettDto.vedtak.tilkjentYtelse?.andelerTilkjentYtelse?.map {
if (it.fraOgMed >= nyesteGrunnbeløpGyldigFraOgMed) {
it.copy(kildeBehandlingId = forrigeBehandling.id)
} else {
it.copy(kildeBehandlingId = behandling.id)
}
} ?: emptyList()
val tilkjentYtelseDto = expectedIverksettDto.vedtak.tilkjentYtelse?.copy(andelerTilkjentYtelse = andelerTilkjentYtelse)
val vedtak = expectedIverksettDto.vedtak.copy(tilkjentYtelse = tilkjentYtelseDto, vedtakstidspunkt = vedtakstidspunkt)
val behandlingsdetaljerDto = expectedIverksettDto.behandling.copy(
behandlingId = forrigeBehandling.id,
eksternId = forrigeBehandling.eksternId.id
)
return expectedIverksettDto.copy(
vedtak = vedtak,
behandling = behandlingsdetaljerDto,
fagsak = expectedIverksettDto.fagsak.copy(eksternId = fagsak.eksternId.id)
)
}
private fun readFile(filnavn: String): String {
return this::class.java.getResource("/omregning/$filnavn")!!.readText()
}
}
| 8
|
Kotlin
|
2
| 0
|
d1d8385ead500c4d24739b970940af854fa5fe2c
| 12,452
|
familie-ef-sak
|
MIT License
|
multisrc/overrides/madara/remangas/src/Remangas.kt
|
lmk1988
| 253,204,269
| true
|
{"Kotlin": 4659131}
|
package eu.kanade.tachiyomi.extension.pt.remangas
import eu.kanade.tachiyomi.multisrc.madara.Madara
import eu.kanade.tachiyomi.network.interceptor.rateLimit
import okhttp3.OkHttpClient
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.TimeUnit
class Remangas : Madara(
"Remangas",
"https://remangas.net",
"pt-BR",
SimpleDateFormat("dd 'de' MMM 'de' yyy", Locale("pt", "BR")),
) {
override val versionId = 2
override val useNewChapterEndpoint = true
override val client: OkHttpClient = super.client.newBuilder()
.rateLimit(1, 2, TimeUnit.SECONDS)
.build()
}
| 605
|
Kotlin
|
1236
| 5
|
3e1df100b87358d8b50ce8dd998e04552db9c91d
| 641
|
tachiyomi-extensions
|
Apache License 2.0
|
core/model/src/main/java/org/expenny/core/model/common/Country.kt
|
expenny-application
| 712,607,222
| false
|
{"Kotlin": 1159524}
|
package org.expenny.core.model.common
data class Country(
val name: String,
val code: String,
)
| 0
|
Kotlin
|
3
| 42
|
7e4b8e1a5dfacf5799d5ace2e72cd21f002d6311
| 105
|
expenny-android
|
Apache License 2.0
|
feature/user/deactivation/src/main/java/com/uragiristereo/mikansei/feature/user/deactivation/navigation/UserDeactivationNavGraph.kt
|
uragiristereo
| 583,834,091
| false
|
{"Kotlin": 978568}
|
package com.uragiristereo.mikansei.feature.user.deactivation.navigation
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.uragiristereo.mikansei.core.ui.animation.translateXFadeIn
import com.uragiristereo.mikansei.core.ui.animation.translateXFadeOut
import com.uragiristereo.mikansei.feature.user.deactivation.UserDeactivationViewModel
import com.uragiristereo.mikansei.feature.user.deactivation.agreement.UserDeactivationAgreementScreen
import com.uragiristereo.mikansei.feature.user.deactivation.in_app.UserDeactivationInAppScreen
import com.uragiristereo.mikansei.feature.user.deactivation.in_web.UserDeactivationInWebScreen
import com.uragiristereo.mikansei.feature.user.deactivation.methods.UserDeactivationMethodsScreen
@Composable
fun UserDeactivationNavGraph(
innerPadding: PaddingValues,
viewModel: UserDeactivationViewModel,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val activeUser by viewModel.activeUser.collectAsState()
AnimatedContent(
targetState = viewModel.currentPage,
transitionSpec = {
val forward = initialState < targetState
val transition = translateXFadeIn(forward) togetherWith
translateXFadeOut(forward)
transition.apply {
targetContentZIndex = when {
forward -> 0f
else -> -1f
}
}
},
label = "UserDeactivationPage",
modifier = modifier.fillMaxSize(),
) { currentPageState ->
when (currentPageState) {
Page.AGREEMENT -> {
UserDeactivationAgreementScreen(
innerPadding = innerPadding,
activeUserId = activeUser.id,
isConfirming = viewModel.isConfirming,
onConfirmingChange = {
viewModel.isConfirming = it
},
onProceedClick = {
viewModel.currentPage = Page.METHODS
},
)
}
Page.METHODS -> {
UserDeactivationMethodsScreen(
innerPadding = innerPadding,
onInAppClick = {
viewModel.currentPage = Page.IN_APP
},
onInWebClick = {
viewModel.currentPage = Page.IN_BROWSER
},
)
}
Page.IN_APP -> {
UserDeactivationInAppScreen(
innerPadding = innerPadding,
isLoading = viewModel.isLoading,
password = viewModel.passwordTextField,
onPasswordChange = {
viewModel.passwordTextField = it
},
onDeactivateClick = {
viewModel.showInAppConfirmationDialog = true
},
)
}
Page.IN_BROWSER -> {
UserDeactivationInWebScreen(
innerPadding = innerPadding,
onOpenWebClick = {
viewModel.openDeactivationWeb(context)
},
onLogoutClick = viewModel::switchToAnonymousAndDelete,
)
}
}
}
}
| 3
|
Kotlin
|
2
| 62
|
4f136b0479ee7772f3d7ba48927cef9389d5c2be
| 3,777
|
Mikansei
|
Apache License 2.0
|
platform/platform-tests/testSrc/com/intellij/openapi/project/impl/navigation/NavigationTestBase.kt
|
ingokegel
| 72,937,917
| false
| null |
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.project.impl.navigation
import com.intellij.navigation.LocationInFile
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.writeAction
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.module.EmptyModuleType
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.RecentProjectManagerListenerRule
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.psi.NavigatablePsiElement
import com.intellij.psi.PsiManager
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testFramework.*
import com.intellij.util.io.sanitizeFileName
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.junit.Rule
import org.junit.rules.TestName
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.io.path.invariantSeparatorsPathString
abstract class NavigationTestBase {
@JvmField @Rule val tempDir = TemporaryDirectory()
@JvmField @Rule val testName = TestName()
@JvmField @Rule val projectTrackingRule = ProjectTrackingRule()
@JvmField @Rule internal val busConnection = RecentProjectManagerListenerRule()
lateinit var project: Project
open val testDataPath: String
get() = "${PlatformTestUtil.getPlatformTestDataPath()}/commands/navigate/"
protected inline fun runNavigationTest(crossinline navigationAction: suspend () -> Unit, crossinline checkAction: () -> Unit) {
runBlocking {
createOrLoadProject(tempDir, useDefaultProjectSettings = false) { project ->
setUpProject(project)
navigationAction()
withContext(Dispatchers.EDT) {
checkAction()
}
}
}
}
protected open suspend fun setUpProject(project: Project) {
this.project = project
val basePath = Path.of(project.basePath!!)
val moduleManager = ModuleManager.getInstance(project)
val projectManager = ProjectRootManagerEx.getInstanceEx(project)
writeAction {
projectManager.mergeRootsChangesDuring {
val newModule = moduleManager.newModule(
basePath.resolve("navigationModule.iml").invariantSeparatorsPathString,
EmptyModuleType.EMPTY_MODULE
)
FileUtil.copyDir(Paths.get(testDataPath, sanitizeFileName(testName.methodName)).toFile(), basePath.toFile())
val baseDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(basePath.invariantSeparatorsPathString)!!
val moduleModel = ModuleRootManager.getInstance(newModule).modifiableModel
moduleModel.addContentEntry(baseDir).addSourceFolder(baseDir, false)
moduleModel.commit()
VfsTestUtil.createDir(baseDir, Project.DIRECTORY_STORE_FOLDER)
}
}
}
protected fun getCurrentCharacterZeroBasedPosition(): LocationInFile {
return FileEditorManager.getInstance(project).allEditors.asSequence().map {
with((it as TextEditor).editor) {
val offsetTotal = caretModel.offset
val line = offsetToLogicalPosition(offsetTotal).line
val offsetOfLine = logicalPositionToOffset(LogicalPosition(line, 0))
LocationInFile(line, offsetTotal - offsetOfLine)
}
}.first()
}
protected fun getCurrentLogicalPosition(): LogicalPosition {
return FileEditorManager.getInstance(project).allEditors.asSequence().map {
(it as TextEditor).editor.offsetToLogicalPosition(it.editor.caretModel.offset)
}.first()
}
protected fun getCurrentElement(): NavigatablePsiElement {
return FileEditorManager.getInstance(project).allEditors.asSequence().map {
val offset = (it as TextEditor).editor.caretModel.offset
val psiFile = PsiManager.getInstance(project).findFile(it.file!!)!!
PsiTreeUtil.findElementOfClassAtOffset(psiFile, offset, NavigatablePsiElement::class.java, false)!!
}.first()
}
}
| 233
| null |
4912
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 4,315
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/wutheringwavesguide/models/api/characterdetail/Cons.kt
|
nikunj3011
| 810,402,672
| false
|
{"Kotlin": 247322}
|
package wutheringwavesguide.models.api.characterdetail
data class Cons(
val raw: String
)
| 0
|
Kotlin
|
0
| 0
|
9bf0e2f5bcae9938c522d9aa604777d791c2a9da
| 94
|
Wuthering.Waves.Android.Kotlin
|
MIT License
|
android/src/test/java/com/adyenreactnativesdk/configuration/GooglePayConfigurationParserTest.kt
|
Adyen
| 419,645,479
| false
| null |
package com.adyenreactnativesdk.configuration
import android.util.Log
import com.adyen.checkout.core.api.Environment
import com.facebook.react.bridge.ReadableArray
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.MockedStatic
import org.mockito.Mockito.anyString
import org.mockito.Mockito.eq
import org.mockito.Mockito.mock
import org.mockito.Mockito.mockStatic
import org.mockito.Mockito.`when`
class GooglePayConfigurationParserTest {
private var mockStatic: MockedStatic<Log>? = null
@Test
fun getShippingAddressParameters() {
}
@Test
fun getBillingAddressParameters() {
}
@Test
fun getAllowedCardNetworks() {
// GIVEN
mockStatic = mockStatic(Log::class.java)
var wrong_cards_count = 0
`when`(Log.w(eq("GooglePayConfigParser"), anyString())).thenReturn(wrong_cards_count++)
val config = WritableMapMock()
val mockArray = mock(ReadableArray::class.java)
`when`(mockArray.toArrayList()).thenReturn(arrayListOf("MASTERCARD", "visa", "Amex", "wrong_value"))
config.putArray(GooglePayConfigurationParser.ALLOWED_CARD_NETWORKS_KEY, mockArray)
// WHEN
val googlepayParser = GooglePayConfigurationParser(config)
// THEN
assertEquals(googlepayParser.allowedCardNetworks, listOf("MASTERCARD", "VISA", "AMEX"))
assertEquals(wrong_cards_count, 1)
// TEAR DOWN
mockStatic?.close()
}
@Test
fun getAllowedAuthMethods() {
// GIVEN
val config = WritableMapMock()
val mockArray = mock(ReadableArray::class.java)
`when`(mockArray.toArrayList()).thenReturn(arrayListOf("PAN_ONLY", "CRYPTOGRAM_3DS"))
config.putArray(GooglePayConfigurationParser.ALLOWED_AUTH_METHODS_KEY, mockArray)
// WHEN
val googlepayParser = GooglePayConfigurationParser(config)
// THEN
assertEquals(googlepayParser.allowedAuthMethods, listOf("PAN_ONLY", "CRYPTOGRAM_3DS"))
}
@Test
fun getGooglePayEnvironment() {
// GIVEN
val config = WritableMapMock()
config.putInt(GooglePayConfigurationParser.GOOGLEPAY_ENVIRONMENT_KEY, 1)
// WHEN
val googlepayParser = GooglePayConfigurationParser(config)
// THEN
assertEquals(googlepayParser.getGooglePayEnvironment(Environment.TEST), 1 )
}
@Test
fun getGooglePayNoEnvironment() {
// GIVEN
val config = WritableMapMock()
// WHEN
val googlepayParser = GooglePayConfigurationParser(config)
// THEN
assertEquals(googlepayParser.getGooglePayEnvironment(Environment.TEST), 3)
}
@Test
fun getConfiguration() {
}
}
| 49
| null |
29
| 37
|
f9c63ffcad510a4526e81f0ffc7929df286a254f
| 2,733
|
adyen-react-native
|
MIT License
|
app/src/main/java/com/yabancikelimedefteri/domain/utils/ImportanceLevelSetter.kt
|
AhmetOcak
| 621,942,001
| false
|
{"Kotlin": 215007}
|
package com.yabancikelimedefteri.domain.utils
import androidx.compose.ui.graphics.Color
import com.yabancikelimedefteri.domain.model.ImportanceLevel
fun Int.setImportanceLevel(): Color {
return when (this) {
ImportanceLevel.Green.ordinal -> Color.Green
ImportanceLevel.Yellow.ordinal -> Color.Yellow
ImportanceLevel.Red.ordinal -> Color.Red
else -> Color.Green
}
}
fun Int.convertImportanceLevel(): ImportanceLevel {
return when(this) {
ImportanceLevel.Green.ordinal -> ImportanceLevel.Green
ImportanceLevel.Yellow.ordinal -> ImportanceLevel.Yellow
ImportanceLevel.Red.ordinal -> ImportanceLevel.Red
else -> ImportanceLevel.Green
}
}
| 1
|
Kotlin
|
0
| 2
|
70b79147500e11ce47657091910d2457df3862b3
| 716
|
YabanciKelimeDefterim
|
MIT License
|
Week2/W2S2_11321051/src/main/kotlin/no16.kt
|
marloxxx
| 563,639,368
| false
|
{"Kotlin": 171819, "PHP": 91686, "C++": 39436, "CMake": 34938, "Blade": 18425, "Dart": 7911, "C": 2850, "Swift": 2316, "HTML": 1830, "Shell": 1069, "JavaScript": 285, "Objective-C": 76}
|
import java.util.*
fun main() {
val fruits = listOf("banana", "avocado", "apple", "kiwifruit") // deklarasi variabel fruits dengan tipe data List<String> dan nilai ["banana", "avocado", "apple", "kiwifruit"]
fruits.filter { it.startsWith("a") } // memfilter nilai dari fruits yang dimulai dengan huruf a
.sortedBy { it } // mengurutkan nilai dari fruits sesuai abjad
.map { it.uppercase(Locale.getDefault()) } // mengubah nilai dari fruits yang dimulai dengan huruf a menjadi huruf besar semua
.forEach{println(it)} // menampilkan nilai dari fruits yang dimulai dengan huruf a dan berurutan sesuai abjad
}
| 0
|
Kotlin
|
0
| 0
|
6c32297cef729b18561591555d5bdbe630562bd0
| 638
|
PAM
|
MIT License
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/search/SearchRepository.kt
|
altaf933
| 122,962,254
| false
|
{"Gradle": 4, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Proguard": 1, "Kotlin": 377, "XML": 225, "Java": 1}
|
package io.github.feelfreelinux.wykopmobilny.api.search
import io.github.feelfreelinux.wykopmobilny.api.UserTokenRefresher
import io.github.feelfreelinux.wykopmobilny.api.errorhandler.ErrorHandlerTransformer
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.AuthorMapper
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.EntryMapper
import io.github.feelfreelinux.wykopmobilny.models.mapper.apiv2.LinkMapper
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.AuthorResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.EntryResponse
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.models.LinkResponse
import io.github.feelfreelinux.wykopmobilny.utils.LinksPreferencesApi
import retrofit2.Retrofit
class SearchRepository(val retrofit: Retrofit, val userTokenRefresher: UserTokenRefresher, val linksPreferencesApi: LinksPreferencesApi) : SearchApi {
private val searchApi by lazy { retrofit.create(SearchRetrofitApi::class.java) }
override fun searchLinks(page: Int, query: String) = searchApi
.searchLinks(page, query)
.retryWhen(userTokenRefresher)
.compose<List<LinkResponse>>(ErrorHandlerTransformer())
.map { it.map { LinkMapper.map(it, linksPreferencesApi) } }
override fun searchEntries(page: Int, query: String) = searchApi
.searchEntries(page, query)
.retryWhen(userTokenRefresher)
.compose<List<EntryResponse>>(ErrorHandlerTransformer())
.map { it.map { EntryMapper.map(it) } }
override fun searchProfiles(query: String) = searchApi
.searchProfiles(query)
.retryWhen(userTokenRefresher)
.compose<List<AuthorResponse>>(ErrorHandlerTransformer())
.map { it.map { AuthorMapper.map(it) } }
}
| 1
| null |
1
| 1
|
63bdf6c1c168b747714a7051f7637dca7e48c88d
| 1,844
|
WykopMobilny
|
MIT License
|
src/main/kotlin/io/kjson/demo2/adapters/provides/KtorProperties.kt
|
pwall567
| 632,757,780
| false
| null |
package io.kjson.demo2.adapters.provides
import io.ktor.server.application.ApplicationEnvironment
import io.kjson.demo2.ports.provides.Properties
class KtorProperties(private val environment: ApplicationEnvironment) : Properties {
override fun get(string: String): String? {
return environment.config.propertyOrNull(string)?.getString()
}
}
| 0
|
Kotlin
|
0
| 0
|
36e83bd44cbec87f6c290f28e395db4d67b4e377
| 362
|
ktor-demo-2
|
MIT License
|
rtron-math/src/main/kotlin/io/rtron/math/geometry/curved/threed/point/CurveRelativeVector3D.kt
|
savenow
| 309,383,785
| false
| null |
/*
* Copyright 2019-2024 Chair of Geoinformatics, Technical University of Munich
*
* 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.rtron.math.geometry.curved.threed.point
import arrow.core.Either
import io.rtron.math.geometry.curved.oned.point.CurveRelativeVector1D
import io.rtron.math.geometry.curved.threed.CurveRelativeAbstractGeometry3D
import io.rtron.math.geometry.curved.twod.point.CurveRelativeVector2D
import io.rtron.math.geometry.euclidean.threed.point.Vector3D
import io.rtron.math.std.fuzzyEquals as doubleFuzzyEquals
/**
* Represents a vector in a curve relative coordinate system in 3D. This means that only points can be referenced which
* are not before the curve's start or after the curve's end within the three-dimensional space.
*
* @param curvePosition distance between the start of the curve and the point to be referenced
* @param lateralOffset lateral offset that is perpendicular to the curve at the [curvePosition]
* @param heightOffset additional height offset to the curve's height
*/
data class CurveRelativeVector3D(
val curvePosition: Double,
val lateralOffset: Double = 0.0,
val heightOffset: Double = 0.0,
) : CurveRelativeAbstractGeometry3D() {
// Properties and Initializers
init {
require(curvePosition.isFinite()) { "Curve position value must be finite." }
require(lateralOffset.isFinite()) { "Lateral offset value must be finite." }
require(heightOffset.isFinite()) { "Height offset value must be finite." }
}
// Operators
/**
* Returns true, if [curvePosition], [lateralOffset] and [heightOffset] are all fuzzily equal with a tolerance
* of [tolerance].
*/
fun fuzzyEquals(
o: CurveRelativeVector3D,
tolerance: Double,
) = doubleFuzzyEquals(this.curvePosition, o.curvePosition, tolerance) &&
doubleFuzzyEquals(this.lateralOffset, o.lateralOffset, tolerance) &&
doubleFuzzyEquals(this.heightOffset, o.heightOffset, tolerance)
fun fuzzyUnequals(
o: CurveRelativeVector3D,
tolerance: Double,
) = !fuzzyEquals(o, tolerance)
// Methods
fun getCartesianCurveOffset() = Vector3D(0.0, lateralOffset, heightOffset)
// Conversions
fun toCurveRelative1D() = CurveRelativeVector1D(curvePosition)
fun toCurveRelative2D() = CurveRelativeVector2D(curvePosition, lateralOffset)
companion object {
val ZERO = CurveRelativeVector3D(0.0, 0.0, 0.0)
/**
* Creates a [CurveRelativeVector3D] by a [curvePosition], [lateralOffset] and [heightOffset]. If one of the
* values is not finite, an error is returned.
*/
fun of(
curvePosition: Double,
lateralOffset: Double,
heightOffset: Double,
): Either<IllegalArgumentException, CurveRelativeVector3D> =
if (!curvePosition.isFinite() || !lateralOffset.isFinite() || !heightOffset.isFinite()) {
Either.Left(IllegalArgumentException("CurvePosition, lateralOffset, heightOffset must be finite."))
} else {
Either.Right(CurveRelativeVector3D(curvePosition, lateralOffset, heightOffset))
}
}
}
| 7
| null |
12
| 5
|
b1538e4d167562b497ba52f13c5cf8fc31dcd818
| 3,721
|
rtron
|
Apache License 2.0
|
app/src/main/kotlin/app/grapheneos/info/ui/donate/cryptocurrency/BitcoinScreen.kt
|
GrapheneOS
| 819,051,378
| false
|
{"Kotlin": 118133}
|
package app.grapheneos.info.ui.donate.cryptocurrency
import android.content.res.Configuration
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.Wallpapers
import app.grapheneos.info.R
import app.grapheneos.info.ui.reusablecomposables.ScreenLazyColumn
@Composable
fun BitcoinScreen(
showSnackbarError: (String) -> Unit,
) {
ScreenLazyColumn(
modifier = Modifier
.fillMaxSize(),
) {
item {
Text(stringResource(R.string.bitcoin_info))
}
item {
AddressInfoItem(
title = "Bech32 (Segwit)",
qrCodePainterResourceId = R.drawable.donate_bitcoin_qr_code,
qrCodeContentDescription = stringResource(R.string.bech32_segwit_qr_code_description),
addressUrl = "bitcoin:bc1q9qw3g8tdxf3dugkv2z8cahd3axehph0mhsqk96?label=GrapheneOS%20Foundation&message=Donation%20to%20GrapheneOS%20Foundation",
address = "bc1q9qw3g8tdxf3dugkv2z8cahd3axehph0mhsqk96",
showSnackbarError = showSnackbarError,
)
}
item {
AddressInfoItem(
title = "Bech32m (Taproot)",
qrCodePainterResourceId = R.drawable.donate_bitcoin_taproot_qr_code,
qrCodeContentDescription = stringResource(R.string.bech32m_taproot_qr_code_description),
addressUrl = "bitcoin:bc1prqf5hks5dnd4j87wxw3djn20559yhj7wvvcv6fqxpwlg96udkzgqtamhry?label=GrapheneOS%20Foundation&message=Donation%20to%20GrapheneOS%20Foundation",
address = "bc1prqf5hks5dnd4j87wxw3djn20559yhj7wvvcv6fqxpwlg96udkzgqtamhry",
showSnackbarError = showSnackbarError
)
}
item {
AddressInfoItem(
title = "BIP47 payment code (stealth address)",
qrCodePainterResourceId = R.drawable.donate_bitcoin_bip47_qr_code,
qrCodeContentDescription = stringResource(R.string.bip47_payment_code_stealth_address_qr_code_description),
addressUrl = "bitcoin:PM8TJKmhJNQX6UTFagyuBk8UGmwKM6yDovEokpHBscPgP3Ac7WdK5zaQKh5XLSawyxiGYZS2a7HkAoeL6oHg7Ahn1VXX888yRG4PwF1dojouPtW7tEHT",
address = "PM8TJKmhJNQX6UTFagyuBk8UGmwKM6yDovEokpHBscPgP3Ac7WdK5zaQKh5XLSawyxiGYZS2a7HkAoeL6oHg7Ahn1VXX888yRG4PwF1dojouPtW7tEHT",
showSnackbarError = showSnackbarError
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
SelectionContainer {
Text(
buildAnnotatedString {
append("PayNym: ")
pushStyle(SpanStyle(fontStyle = FontStyle.Italic))
append("+GrapheneOS")
pop()
}
)
}
}
}
}
item {
Text(stringResource(R.string.bitcoin_fee_notice))
}
}
}
@Preview(
showBackground = true,
wallpaper = Wallpapers.RED_DOMINATED_EXAMPLE,
uiMode = Configuration.UI_MODE_NIGHT_UNDEFINED
)
@Composable
private fun BitcoinScreenPreview() {
MaterialTheme {
BitcoinScreen({})
}
}
| 4
|
Kotlin
|
6
| 8
|
9da623e352625b9b283e1358585d440d9289bce1
| 4,142
|
Info
|
MIT License
|
Code/app/src/main/java/com/istudio/services/modules/started_services/intent_service/IntentServiceScreen.kt
|
devrath
| 534,642,035
| false
|
{"Kotlin": 36755}
|
package com.istudio.services.modules.started_services.intent_service
import android.content.Intent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.istudio.services.modules.started_services.intent_service.services.IntentDownloadService
import com.istudio.services.modules.started_services.normal_service.services.NormalDownloadService
import com.istudio.services.ui.composables.AppButton
import com.istudio.services.utils.toast.toast
@Composable
fun IntentServiceScreen(navController: NavHostController) {
val cxt = LocalContext.current
Column(
modifier = Modifier.fillMaxSize().padding(10.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
AppButton(text = "Start", onClick = {
val intent = Intent(cxt, IntentDownloadService::class.java)
cxt.startService(intent)
})
}
}
| 0
|
Kotlin
|
0
| 0
|
ca2c35af835d09bb991dc1e263aba74f9b7eff46
| 1,420
|
droid-component-services
|
Apache License 2.0
|
app/src/main/kotlin/com/hyphenate/chatdemo/common/PresenceCache.kt
|
easemob
| 785,517,709
| false
|
{"Kotlin": 413442, "HTML": 35978, "Makefile": 917}
|
package com.hyphenate.chatdemo.common
import com.hyphenate.easeui.common.ChatPresence
import java.util.concurrent.ConcurrentHashMap
object PresenceCache {
private val presencesMap: ConcurrentHashMap<String, ChatPresence> = ConcurrentHashMap()
@Synchronized
fun insertPresences(userId: String?,chatPresence: ChatPresence){
presencesMap.let { presence->
userId?.let {
presence[it] = chatPresence
}
}
}
fun getUserPresence(userId: String):ChatPresence?{
if (presencesMap.size > 0 && presencesMap.containsKey(userId)){
return presencesMap[userId]
}
return null
}
var getPresenceInfo:ConcurrentHashMap<String, ChatPresence> = presencesMap
fun clear(){
presencesMap.clear()
}
}
| 1
|
Kotlin
|
4
| 2
|
53eb47fdd15f36bba9ccf093cded74b66eeaf3d3
| 814
|
easemob-demo-android
|
Apache License 2.0
|
compiler/testData/loadJava/compiledKotlin/type/Nothing.kt
|
JakeWharton
| 99,388,807
| true
| null |
package test
fun nothing(): Nothing = throw Exception()
| 179
|
Kotlin
|
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 57
|
kotlin
|
Apache License 2.0
|
app/src/main/java/resonance/http/httpdownloader/implementations/FileIO.kt
|
ajk1889
| 463,805,623
| false
| null |
package resonance.http.httpdownloader.implementations
import android.content.Context
import android.net.Uri
import androidx.core.content.FileProvider
import resonance.http.httpdownloader.core.OutputObj
import resonance.http.httpdownloader.core.otherwise
import resonance.http.httpdownloader.core.silently
import resonance.http.httpdownloader.helpers.toFolder
import resonance.http.httpdownloader.helpers.transferTo
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.RandomAccessFile
class FileIO(private val context: Context, private val task: TransferWrapper) : OutputObj {
private val file: File by lazy {
File(task.outputFolder.toFolder(), task.fileName)
}
private val fileStream: RandomAccessFile by lazy {
RandomAccessFile(file, "rw").apply {
//When error occurred while creating an empty file, the writing should resume from end of file
val written =
if (task.emptyFirstMode && task.transfer?.isCreatingEmptyFile != true) {
task.transfer?.written ?: task.written
} else file.length()
seek(written)
}
}
override fun write(buffer: ByteArray, len: Int) = fileStream.write(buffer, 0, len)
override fun length(): Long = if (file.isFile) file.length() else 0L
override fun close() = silently { fileStream.close() }
override fun reset() = {
!file.exists() || file.delete() || file.length() == 0L
} otherwise false
override fun getUri(): Uri = FileProvider.getUriForFile(
context,
context.applicationContext.packageName + ".provider",
file
)
override fun read(len: Int): ByteArray {
val op = ByteArrayOutputStream()
val ip = FileInputStream(file)
ip.transferTo(op, len)
return op.toByteArray()
}
}
class GenericFileProvider : FileProvider()
| 8
|
Kotlin
|
2
| 5
|
6b4b5147f0f8fd093d0a4d91f1569f6fb73b1675
| 1,924
|
HTTP-Downloader2
|
MIT License
|
src/Day02.kt
|
cisimon7
| 573,872,773
| false
|
{"Kotlin": 41406}
|
fun main() {
fun abcMap(a: String) = when (a) {
"A" -> HandShape.Rock
"B" -> HandShape.Paper
"C" -> HandShape.Scissors
else -> throw Error("$a is not applicable")
}
fun xyzMap(a: String) = when (a) {
"X" -> HandShape.Rock to Outcome.Loose
"Y" -> HandShape.Paper to Outcome.Draw
"Z" -> HandShape.Scissors to Outcome.Win
else -> throw Error("$a is not applicable")
}
fun part1(input: List<String>): Int {
return input
.map { line -> line.split(" ") }
.map { Pair(it[0], it[1]) }
.map { (elf, me) -> abcMap(elf) to xyzMap(me).first }
.sumOf { (elf, me) -> me.play(elf) }
}
fun part2(input: List<String>): Int {
return input
.map { line -> line.split(" ") }
.map { Pair(it[0], it[1]) }
.map { (elfa, mea) ->
val elf = abcMap(elfa)
when (xyzMap(mea).second) {
Outcome.Draw -> elf to elf
Outcome.Loose -> elf to elf.negative()
Outcome.Win -> elf to elf.positive()
}
}
.sumOf { (elf, me) -> me.play(elf) }
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02_input")
println(part1(input))
println(part2(input))
}
sealed interface HandShape {
val point: Int
object Rock : HandShape {
override val point = 1
}
object Paper : HandShape {
override val point = 2
}
object Scissors : HandShape {
override val point = 3
}
}
fun HandShape.positive(): HandShape {
return when (this) {
HandShape.Paper -> HandShape.Scissors
HandShape.Rock -> HandShape.Paper
HandShape.Scissors -> HandShape.Rock
}
}
fun HandShape.negative(): HandShape {
return when (this) {
HandShape.Paper -> HandShape.Rock
HandShape.Rock -> HandShape.Scissors
HandShape.Scissors -> HandShape.Paper
}
}
sealed interface Outcome {
object Win : Outcome
object Draw : Outcome
object Loose : Outcome
}
val winMatrix: List<List<Double>> = listOf(
listOf(0.5, 0.0, 1.0),
listOf(1.0, 0.5, 0.0),
listOf(0.0, 1.0, 0.5)
)
fun HandShape.play(other: HandShape): Int {
val (idx1, idx2) = listOf(this, other).map { shape ->
listOf(HandShape.Rock, HandShape.Paper, HandShape.Scissors).indexOf(shape)
}
val win = winMatrix[idx1][idx2] * 6
return if (win == 0.0) this.point else (win + this.point).toInt()
}
| 0
|
Kotlin
|
0
| 0
|
29f9cb46955c0f371908996cc729742dc0387017
| 2,651
|
aoc-2022
|
Apache License 2.0
|
src/Day02.kt
|
cisimon7
| 573,872,773
| false
|
{"Kotlin": 41406}
|
fun main() {
fun abcMap(a: String) = when (a) {
"A" -> HandShape.Rock
"B" -> HandShape.Paper
"C" -> HandShape.Scissors
else -> throw Error("$a is not applicable")
}
fun xyzMap(a: String) = when (a) {
"X" -> HandShape.Rock to Outcome.Loose
"Y" -> HandShape.Paper to Outcome.Draw
"Z" -> HandShape.Scissors to Outcome.Win
else -> throw Error("$a is not applicable")
}
fun part1(input: List<String>): Int {
return input
.map { line -> line.split(" ") }
.map { Pair(it[0], it[1]) }
.map { (elf, me) -> abcMap(elf) to xyzMap(me).first }
.sumOf { (elf, me) -> me.play(elf) }
}
fun part2(input: List<String>): Int {
return input
.map { line -> line.split(" ") }
.map { Pair(it[0], it[1]) }
.map { (elfa, mea) ->
val elf = abcMap(elfa)
when (xyzMap(mea).second) {
Outcome.Draw -> elf to elf
Outcome.Loose -> elf to elf.negative()
Outcome.Win -> elf to elf.positive()
}
}
.sumOf { (elf, me) -> me.play(elf) }
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02_input")
println(part1(input))
println(part2(input))
}
sealed interface HandShape {
val point: Int
object Rock : HandShape {
override val point = 1
}
object Paper : HandShape {
override val point = 2
}
object Scissors : HandShape {
override val point = 3
}
}
fun HandShape.positive(): HandShape {
return when (this) {
HandShape.Paper -> HandShape.Scissors
HandShape.Rock -> HandShape.Paper
HandShape.Scissors -> HandShape.Rock
}
}
fun HandShape.negative(): HandShape {
return when (this) {
HandShape.Paper -> HandShape.Rock
HandShape.Rock -> HandShape.Scissors
HandShape.Scissors -> HandShape.Paper
}
}
sealed interface Outcome {
object Win : Outcome
object Draw : Outcome
object Loose : Outcome
}
val winMatrix: List<List<Double>> = listOf(
listOf(0.5, 0.0, 1.0),
listOf(1.0, 0.5, 0.0),
listOf(0.0, 1.0, 0.5)
)
fun HandShape.play(other: HandShape): Int {
val (idx1, idx2) = listOf(this, other).map { shape ->
listOf(HandShape.Rock, HandShape.Paper, HandShape.Scissors).indexOf(shape)
}
val win = winMatrix[idx1][idx2] * 6
return if (win == 0.0) this.point else (win + this.point).toInt()
}
| 0
|
Kotlin
|
0
| 0
|
29f9cb46955c0f371908996cc729742dc0387017
| 2,651
|
aoc-2022
|
Apache License 2.0
|
app/src/main/java/de/thomaskuenneth/smsrelay/SmsReceivedBroadcastReceiver.kt
|
tkuenneth
| 857,257,684
| false
|
{"Kotlin": 13169}
|
package de.thomaskuenneth.smsrelay
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Telephony
import android.provider.Telephony.Mms
import android.provider.Telephony.Sms.Intents.getMessagesFromIntent
import android.util.Log
import de.thomaskuenneth.smsrelay.Receiver.Companion.TAG
import java.io.ByteArrayInputStream
import java.lang.Thread.sleep
import java.util.Properties
import javax.activation.DataHandler
import javax.mail.Authenticator
import javax.mail.FolderNotFoundException
import javax.mail.Message
import javax.mail.PasswordAuthentication
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart
import javax.mail.util.ByteArrayDataSource
import kotlin.concurrent.thread
class Receiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
when (intent?.action) {
Telephony.Sms.Intents.SMS_RECEIVED_ACTION -> context.handleSms(intent)
Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION -> context.handleMms()
else -> {
Log.e(TAG, "unexpected action")
}
}
}
private fun Context.handleSms(intent: Intent) {
getMessagesFromIntent(intent)?.forEach { message ->
sendEmail(
subject = getSubject(message.originatingAddress),
text = message.messageBody,
images = emptyList()
)
}
}
private fun Context.handleMms() {
// This is hacky; we need to find a way to connect the id from the intent with
// the content provider
thread {
sleep(3000)
getLatestMMS { subject, text, images ->
sendEmail(
subject = subject, text = text, images = images
)
}
}
}
companion object {
val TAG: String = Receiver::class.java.simpleName
}
}
fun sendEmail(subject: String, text: String, images: List<Pair<ByteArray, String>>) {
thread {
val props = Properties()
props["mail.smtp.host"] = BuildConfig.SMTP_HOST
props["mail.smtp.port"] = BuildConfig.SMTP_PORT
props["mail.smtp.auth"] = true
props["mail.smtp.starttls.enable"] = true
props["mail.smtp.socketFactory.class"] = "javax.net.ssl.SSLSocketFactory"
val auth = object : Authenticator() {
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(
BuildConfig.SMTP_USERNAME, BuildConfig.SMTP_PASSWORD
)
}
}
try {
MimeMessage(Session.getInstance(props, auth)).run {
setFrom(InternetAddress(BuildConfig.SMTP_FROM))
setRecipients(
Message.RecipientType.TO, InternetAddress.parse(BuildConfig.SMTP_TO)
)
setSubject(subject)
val multipart = MimeMultipart()
val bodyPart = MimeBodyPart()
bodyPart.setText(text)
multipart.addBodyPart(bodyPart)
images.forEachIndexed { index, pair ->
ByteArrayInputStream(pair.first).use {stream ->
val messageBodyPart = MimeBodyPart()
val mimeType = pair.second
val ext = mimeType.split("/")[1]
messageBodyPart.setDataHandler(DataHandler(ByteArrayDataSource(stream, mimeType)))
messageBodyPart.fileName = "image_${1 + index}.$ext"
multipart.addBodyPart(messageBodyPart)
}
}
setContent(multipart)
Transport.send(this)
}
} catch (e: Exception) {
Log.e(TAG, "sendEmail()", e)
}
}
}
fun Context.getLatestMMS(callback: (String, String, List<Pair<ByteArray, String>>) -> Unit) {
var text = getString(R.string.unknown)
var subject = getString(R.string.unknown)
val images = mutableListOf<Pair<ByteArray, String>>()
contentResolver.query(
Mms.CONTENT_URI, arrayOf(Mms._ID), null, null, Mms.Inbox.DEFAULT_SORT_ORDER
)?.let { cursorInbox ->
if (cursorInbox.moveToNext()) {
val messageId = cursorInbox.getString(0)
contentResolver.query(
Mms.Part.CONTENT_URI,
arrayOf(Mms.Part.MSG_ID, Mms.Part.CONTENT_TYPE, Mms.Part.TEXT),
"${Mms.Part.MSG_ID} = ? AND ${Mms.Part.CONTENT_TYPE} = ?",
arrayOf(messageId, "text/plain"),
null
)?.let { cursorPart ->
if (cursorPart.moveToNext()) {
val indexText = cursorPart.getColumnIndex(Mms.Part.TEXT)
text = cursorPart.getString(indexText)
}
contentResolver.query(
Mms.Addr.getAddrUriForMessage(messageId),
arrayOf(Mms.Addr.ADDRESS),
null,
null,
null
)?.let { cursorAdr ->
if (cursorAdr.moveToNext()) {
subject = getSubject(cursorAdr.getString(0))
}
contentResolver.query(
Mms.Part.CONTENT_URI,
arrayOf(Mms._ID, Mms.Part.MSG_ID, Mms.Part.CONTENT_TYPE),
"${Mms.Part.MSG_ID} = ? AND ${Mms.Part.CONTENT_TYPE} LIKE ?",
arrayOf(messageId, "image/%"),
null
)?.let { cursorPartImage ->
while (cursorPartImage.moveToNext()) {
val partId = cursorPartImage.getString(0)
val contentType = cursorPartImage.getString(2)
try {
contentResolver.openInputStream(
Uri.withAppendedPath(
Mms.Part.CONTENT_URI, partId
)
).use {
it?.readBytes()
?.let { bytes -> images.add(Pair(bytes, contentType)) }
}
} catch (e: FolderNotFoundException) {
Log.e(TAG, "openInputStream()", e)
}
}
cursorPartImage.close()
}
cursorAdr.close()
}
cursorPart.close()
}
}
cursorInbox.close()
}
callback(subject, text, images)
}
private fun Context.getSubject(address: String?) = getString(
R.string.subject,
if (address?.isNotEmpty() == true) address else getString(R.string.unknown_sender)
)
| 0
|
Kotlin
|
0
| 1
|
f2416618c80c554da1fad27e720ca973223f4c6b
| 7,222
|
SMSRelay
|
MIT License
|
idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/weighers/AbstractCompletionWeigherTest.kt
|
android
| 263,405,600
| false
| null |
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.completion.test.weighers
import com.intellij.codeInsight.completion.CompletionType
import org.jetbrains.kotlin.idea.completion.test.RELATIVE_COMPLETION_TEST_DATA_BASE_PATH
import org.jetbrains.kotlin.idea.completion.test.configureWithExtraFile
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import org.junit.Assert
abstract class AbstractCompletionWeigherTest(val completionType: CompletionType, val relativeTestDataPath: String) : KotlinLightCodeInsightFixtureTestCase() {
fun doTest(path: String) {
val pathPrefix = RELATIVE_COMPLETION_TEST_DATA_BASE_PATH + "/" + relativeTestDataPath
assert(path.startsWith(pathPrefix))
val relativePath = path.removePrefix(pathPrefix)
myFixture.configureWithExtraFile(relativePath, ".Data", ".Data1", ".Data2", ".Data3", ".Data4", ".Data5", ".Data6")
val text = myFixture.editor.document.text
val items = InTextDirectivesUtils.findArrayWithPrefixes(text, "// ORDER:")
Assert.assertTrue("""Some items should be defined with "// ORDER:" directive""", !items.isEmpty())
myFixture.complete(completionType, InTextDirectivesUtils.getPrefixedInt(text, "// INVOCATION_COUNT:") ?: 1)
myFixture.assertPreferredCompletionItems(InTextDirectivesUtils.getPrefixedInt(text, "// SELECTED:") ?: 0, *items)
}
}
abstract class AbstractBasicCompletionWeigherTest() : AbstractCompletionWeigherTest(CompletionType.BASIC, "weighers/basic") {
}
abstract class AbstractSmartCompletionWeigherTest() : AbstractCompletionWeigherTest(CompletionType.SMART, "weighers/smart") {
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
| 1
| null |
37
| 316
|
74126637a097f5e6b099a7b7a4263468ecfda144
| 2,083
|
kotlin
|
Apache License 2.0
|
data/api/src/test/java/com/sobhanmp/golazo/api/ApiUnitTest.kt
|
Sobhan-mp
| 616,851,909
| false
|
{"Kotlin": 19816}
|
package com.sobhanmp.golazo.api
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ApiUnitTest {
}
| 0
|
Kotlin
|
0
| 0
|
8351d248959539ebef66417eb531175a57eba835
| 266
|
golazo
|
Apache License 2.0
|
VehicleUI/src/main/java/com/drivequant/drivekit/vehicle/ui/bluetooth/adapter/BluetoothItemRecyclerViewAdapter.kt
|
DriveQuantPublic
| 216,339,559
| false
|
{"Gradle": 12, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 10, "Batchfile": 1, "Markdown": 1, "INI": 8, "Proguard": 9, "XML": 419, "Kotlin": 478, "Java": 1}
|
package com.drivequant.drivekit.vehicle.ui.bluetooth.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.graphics.drawable.DrawableCompat
import androidx.recyclerview.widget.RecyclerView
import com.drivequant.drivekit.common.ui.DriveKitUI
import com.drivequant.drivekit.common.ui.extension.headLine1
import com.drivequant.drivekit.common.ui.extension.normalText
import com.drivequant.drivekit.common.ui.utils.DKAlertDialog
import com.drivequant.drivekit.common.ui.utils.DKResource
import com.drivequant.drivekit.common.ui.utils.FontUtils
import com.drivequant.drivekit.core.SynchronizationType
import com.drivequant.drivekit.databaseutils.entity.Vehicle
import com.drivequant.drivekit.tripanalysis.bluetooth.BluetoothData
import com.drivequant.drivekit.vehicle.DriveKitVehicle
import com.drivequant.drivekit.vehicle.manager.VehicleListQueryListener
import com.drivequant.drivekit.vehicle.manager.VehicleSyncStatus
import com.drivequant.drivekit.vehicle.ui.R
import com.drivequant.drivekit.vehicle.ui.bluetooth.viewmodel.BluetoothViewModel
class BluetoothItemRecyclerViewAdapter(
var context: Context,
private val viewModel: BluetoothViewModel
) : RecyclerView.Adapter<BluetoothItemRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(viewgroup: ViewGroup, position: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.layout_item_bluetooth_device, viewgroup, false)
FontUtils.overrideFonts(context, view)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentDevice = viewModel.bluetoothDevices[position]
val mainFontColor = DriveKitUI.colors.mainFontColor()
holder.textViewName.normalText(mainFontColor)
holder.textViewName.text = currentDevice.name
DrawableCompat.setTint(holder.arrow.drawable, DriveKitUI.colors.secondaryColor())
if (position == viewModel.bluetoothDevices.indices.last && itemCount > 1){
holder.separator.visibility = View.GONE
} else {
holder.separator.visibility = View.VISIBLE
holder.separator.setBackgroundColor(DriveKitUI.colors.neutralColor())
}
holder.container.setOnClickListener {
it.context?.let { context ->
val bluetoothDevice = viewModel.bluetoothDevices[position]
DriveKitVehicle.getVehiclesOrderByNameAsc(object : VehicleListQueryListener{
override fun onResponse(status: VehicleSyncStatus, vehicles: List<Vehicle>) {
if (viewModel.isBluetoothAlreadyPaired(bluetoothDevice.macAddress, vehicles)) {
showDeviceAlreadyPaired(context, bluetoothDevice)
} else {
viewModel.addBluetoothToVehicle(bluetoothDevice)
}
}
}, SynchronizationType.CACHE)
}
}
}
override fun getItemCount(): Int {
return viewModel.bluetoothDevices.size
}
private fun showDeviceAlreadyPaired(context: Context, bluetoothDevice: BluetoothData){
val alert = DKAlertDialog.LayoutBuilder().init(context)
.layout(com.drivequant.drivekit.common.ui.R.layout.template_alert_dialog_layout)
.cancelable(true)
.positiveButton(context.getString(com.drivequant.drivekit.common.ui.R.string.dk_common_close)) { dialog, _ ->
dialog.dismiss()
}
.show()
val title = alert.findViewById<TextView>(R.id.text_view_alert_title)
val description = alert.findViewById<TextView>(R.id.text_view_alert_description)
val btDeviceName = bluetoothDevice.name ?: bluetoothDevice.macAddress
title?.setText(R.string.app_name)
val text = DKResource.buildString(
context, DriveKitUI.colors.mainFontColor(),
DriveKitUI.colors.mainFontColor(),
R.string.dk_vehicle_bluetooth_already_paired,
btDeviceName,
viewModel.vehicleName
)
description?.text = text
title?.headLine1()
description?.normalText()
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val container: LinearLayout = itemView.findViewById(R.id.container)
val textViewName: TextView = itemView.findViewById(R.id.text_view_title)
val arrow: ImageView = itemView.findViewById(R.id.image_view_arrow)
val separator: View = itemView.findViewById(R.id.view_separator)
}
}
| 1
|
Kotlin
|
3
| 9
|
e7956263157c49aae8d6f993a558ea77d9658ee6
| 4,793
|
drivekit-ui-android
|
Apache License 2.0
|
app/src/main/java/desoft/studio/webpoint/data/Webpoint_Dao.kt
|
JK-IT
| 385,474,689
| false
| null |
package desoft.studio.webpocket.data
import androidx.room.*
/**
*
@Insert - This method will add records. This means a query of type "Insert" will be executed.
@Update - This method will update records.
@Delete - This method to delete a record
@Query - Define the database operations to be performed directly using SQL commands.
*/
@Dao
interface Webpoint_Dao
{
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun AddPoint(point : Wpoint); // suspend -> to use coroutine
@Query("SELECT * FROM webpoint_table ORDER BY Name COLLATE NOCASE ASC")
suspend fun ReadAll() :List<Wpoint>
@Query("SELECT * FROM webpoint_table WHERE Name LIKE :inname")
fun ReadItem(inname: String) : Wpoint
@Delete
fun DeleteItem(point : Wpoint);
@Delete
fun DeleteMulti(polist : List<Wpoint>) // must be collections/array to work, attempt to use set collection ,but failed
}
| 0
|
Kotlin
|
0
| 0
|
0f5eff1d43ad1271bd9861c78d42addcf6aba454
| 914
|
pointbew
|
Apache License 2.0
|
core/remote/food-data-central/src/main/kotlin/org/calamarfederal/messydiet/food/data/central/model/FoundationFoodItem.kt
|
John-Tuesday
| 684,904,664
| false
|
{"Kotlin": 351738}
|
package org.calamarfederal.messydiet.food.data.central.model
import org.calamarfederal.messydiet.food.data.central.remote.schema.FoundationFoodItemSchema
import org.calamarfederal.messydiet.food.data.central.remote.schema.SearchResultFoodSchema
import org.calamarfederal.messydiet.food.data.central.remote.schema.parseResponseDate
data class FDCFoundationFoodItem internal constructor(
override val fdcId: FoundationFdcId,
override val description: String,
override val nutritionalInfo: FDCNutritionInfo?,
val ndbNumber: Int? = null,
val publicationDate: FDCDate? = null,
) : FDCFoodItem
data class FoundationFdcId internal constructor(
override val fdcId: Int,
) : FDCId
internal fun FoundationFoodItemSchema.toModel(): FDCFoundationFoodItem = FDCFoundationFoodItem(
fdcId = FoundationFdcId(fdcId),
description = description,
nutritionalInfo = foodNutrients?.toNutritionInfo()?.chooseBest(),
ndbNumber = ndbNumber,
publicationDate = publicationDate?.let { parseResponseDate(it) },
)
internal fun SearchResultFoodSchema.toFDCFoundationFoodOrNull(): FDCFoundationFoodItem? {
if (dataType?.let { FDCDataType.fromString(it) } != FDCDataType.Foundation)
return null
return FDCFoundationFoodItem(
fdcId = FoundationFdcId(fdcId),
description = description,
nutritionalInfo = foodNutrients?.let { parseNutrients(it) },
ndbNumber = ndbNumber,
publicationDate = publicationDate?.let { parseResponseDate(it) },
)
}
| 0
|
Kotlin
|
0
| 0
|
ab2da78d3cc695aef075143775f6cd9d703f2b8f
| 1,515
|
messy-diet
|
MIT License
|
app/src/main/java/com/ccastro/pokedexapp/di/DataModule.kt
|
Crist-C
| 714,102,815
| false
|
{"Kotlin": 79920}
|
package com.ccastro.pokedexapp.di
import com.ccastro.pokedexapp.data.apis.PokemonsDAO
import com.ccastro.pokedexapp.data.repositories.PokemonRepository
import com.ccastro.pokedexapp.domain.repositories.IPokemonRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Named
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DataModule {
@Provides
@Singleton
@Named("PokeApiUrlBase")
fun provideBaseUrl(): String = "https://pokeapi.co/api/v2/"
@Provides
@Singleton
@Named("RetrofitClient")
fun provideRetrofitClient(@Named("PokeApiUrlBase") urlBase: String): Retrofit {
return Retrofit.Builder()
.baseUrl(urlBase)
.client(
OkHttpClient().newBuilder().build()
)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Provides
@Singleton
@Named("PokemonDao")
fun providePokemonDao(@Named("RetrofitClient")retrofit: Retrofit) : PokemonsDAO =
retrofit.create(PokemonsDAO::class.java)
@Provides
@Singleton
@Named("PokemonRepository")
fun providePokemonRepository(@Named("PokemonDao") pokemonDao: PokemonsDAO) :
IPokemonRepository = PokemonRepository(pokemonDao = pokemonDao)
}
| 0
|
Kotlin
|
0
| 1
|
c402720875317f52acaa6cc8e048d2a9b825c26b
| 1,494
|
Pokedex
|
Apache License 2.0
|
app/src/main/java/com/ismailhakkiaydin/football/model/topscorer/Penalty.kt
|
ihaydinn
| 261,578,497
| false
| null |
package com.ismailhakkiaydin.football.model.topscorer
import androidx.room.Embedded
import com.google.gson.annotations.SerializedName
data class Penalty(
@SerializedName("won")
var won: Int,
@SerializedName("success")
var success: Int,
@SerializedName("missed")
var missed: Int
)
| 0
|
Kotlin
|
7
| 24
|
3d835c53af004d18a1c68e3dee3a252cfb33b16b
| 308
|
football-app
|
MIT License
|
apps/etterlatte-pdltjenester/src/main/kotlin/config/ApplicationContext.kt
|
navikt
| 417,041,535
| false
| null |
package no.nav.etterlatte.config
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import no.nav.etterlatte.libs.ktor.httpClient
import no.nav.etterlatte.libs.ktor.httpClientClientCredentials
import no.nav.etterlatte.pdl.ParallelleSannheterKlient
import no.nav.etterlatte.pdl.PdlKlient
import no.nav.etterlatte.person.PersonService
class ApplicationContext(env: Map<String, String>) {
val config: Config = ConfigFactory.load()
val httpPort = env.getOrDefault("HTTP_PORT", "8080").toInt()
val pdlKlient =
PdlKlient(
httpClient =
httpClientClientCredentials(
azureAppClientId = config.getString("pdl.client_id"),
azureAppJwk = config.getString("pdl.client_jwk"),
azureAppWellKnownUrl = config.getString("pdl.well_known_url"),
azureAppScope = config.getString("pdl.outbound"),
),
apiUrl = config.getString("pdl.url"),
)
val parallelleSannheterKlient =
ParallelleSannheterKlient(
httpClient = httpClient(),
apiUrl = config.getString("pps.url"),
)
val personService: PersonService =
PersonService(
pdlKlient = pdlKlient,
ppsKlient = parallelleSannheterKlient,
)
}
| 15
| null |
0
| 5
|
d0b42ff1df660904897d6869868f440747ce74d5
| 1,341
|
pensjon-etterlatte-saksbehandling
|
MIT License
|
src/test/kotlin/passwordStore/tags/TagTest.kt
|
sciack
| 669,479,977
| false
|
{"Kotlin": 269195, "Dockerfile": 302}
|
package passwordStore.tags
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.createComposeRule
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.isEmpty
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import org.jetbrains.skia.Surface
import org.junit.Rule
import passwordStore.DiInjection
import passwordStore.widget.tagEditor
import kotlin.test.Test
import kotlin.test.assertContains
class TagTests() {
private val di = DiInjection.testDi
@get:Rule
val rule = createComposeRule()
// don't inline, surface controls canvas life time
private val surface = Surface.makeRasterN32Premul(100, 100)
private val canvas = surface.canvas
@Test
fun testEmptyPlainTextNode() {
runBlocking(Dispatchers.Main) {
rule.setContent {
val tags = remember {
mutableStateOf(setOf("tag"))
}
tagEditor(tags, {})
}
rule.awaitIdle()
rule.onNodeWithTag("tags").performTextInput("testLabel,")
rule.awaitIdle()
rule.onNodeWithText("testLabel").assertExists()
}
}
@Test
fun `on value change should add a callback`() {
runBlocking(Dispatchers.Main) {
val collectedTags = mutableListOf<String>()
rule.setContent {
val tags = remember {
mutableStateOf(setOf("tag"))
}
tagEditor(tags) {
collectedTags.clear()
collectedTags.addAll(it)
}
}
rule.awaitIdle()
rule.onNodeWithTag("tags").performTextInput("testLabel,")
rule.awaitIdle()
rule.onNodeWithText("testLabel").assertExists()
assertContains(collectedTags, "testLabel")
}
}
@Test
fun `on click on tag should remove the entry`() {
runBlocking(Dispatchers.Main) {
val collectedTags = mutableListOf("tags")
rule.setContent {
val tags = remember {
mutableStateOf(collectedTags.toSet())
}
tagEditor(tags) {
collectedTags.clear()
collectedTags.addAll(it)
}
}
rule.awaitIdle()
rule.onNodeWithText("tags").performClick()
rule.awaitIdle()
assertThat(collectedTags, isEmpty)
}
}
@OptIn(ExperimentalComposeUiApi::class, ExperimentalTestApi::class)
@Test
fun `on focus loose should notify the value change`() {
runBlocking(Dispatchers.Main) {
val collectedTags = mutableListOf<String>()
rule.setContent {
val tags = remember {
mutableStateOf(setOf("tag"))
}
tagEditor(tags) {
collectedTags.clear()
collectedTags.addAll(it)
}
}
rule.awaitIdle()
rule.onNodeWithTag("tags").performTextInput("testLabel")
rule.awaitIdle()
rule.onNodeWithTag("tags").performKeyInput { this.pressKey(Key.Tab) }
rule.onNodeWithText("testLabel").assertExists()
assertContains(collectedTags, "testLabel")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ee95b4ef7442d1d4f13b3590e22c5e85645cc247
| 3,607
|
kpassword-store
|
The Unlicense
|
simplecloud-api/src/main/kotlin/eu/thesimplecloud/api/config/IConfigLoader.kt
|
theSimpleCloud
| 270,085,977
| false
| null |
/*
* MIT License
*
* Copyright (C) 2020-2022 The SimpleCloud authors
*
* 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 eu.thesimplecloud.api.config
interface IConfigLoader<T : Any> {
/**
* Load the config form the file.
* If the config does not exist it returns a default value without creating the file.
*/
fun loadConfig(): T
/**
* Saves the object to the config file
*/
fun saveConfig(value: T)
/**
* Returns whether the config file exist
*/
fun doesConfigFileExist(): Boolean
}
| 8
| null |
43
| 98
|
8f10768e2be523e9b2e7c170965ca4f52a99bf09
| 1,580
|
SimpleCloud
|
MIT License
|
livechat/src/main/java/com/desk360/livechat/presentation/viewholder/CrMenuButtonViewHolder.kt
|
Teknasyon-Teknoloji
| 394,270,981
| false
| null |
package com.desk360.livechat.presentation.viewholder
import android.view.LayoutInflater
import android.view.ViewGroup
import com.desk360.base.presentation.endDrawable
import com.desk360.livechat.R
import com.desk360.livechat.data.model.cannedresponse.CannedActionType
import com.desk360.livechat.databinding.ItemCrMenuButtonBinding
import com.desk360.livechat.manager.LiveChatHelper
import com.desk360.livechat.presentation.activity.livechat.CannedResponseViewModel
class CrMenuButtonViewHolder(
private val binding: ItemCrMenuButtonBinding,
onClick: OnCannedViewHolderClickListener
) : BaseCannedResponseViewHolder(binding.root, onClick) {
companion object {
const val HOME = "canned-home"
const val SURVEY = "canned-survey"
const val CONNECT = "canned-connect"
fun create(parent: ViewGroup, onClick: OnCannedViewHolderClickListener) =
CrMenuButtonViewHolder(
ItemCrMenuButtonBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
), onClick
)
}
override fun bindTo(response: CannedActionType, position: Int) {
super.bindTo(response, position)
val viewModel = CannedResponseViewModel()
binding.viewModel = viewModel
val hold = response as CannedActionType.CRMenuButton
viewModel.backgroundColor.value =
LiveChatHelper.settings?.data?.config?.chat?.messageBackgroundColor
binding.crMenuButton.text = hold.content
when (hold.icon) {
HOME -> {
binding.crMenuButton.endDrawable(R.drawable.ic_menu_icon_home)
}
SURVEY -> {
binding.crMenuButton.endDrawable(R.drawable.ic_menu_icon_survey)
}
CONNECT -> {
binding.crMenuButton.endDrawable(R.drawable.ic_menu_icon_live_help)
}
}
binding.crMenuButton.setOnClickListener {
if (hold.isClickable) {
onClick(null, hold.id, hold.actionableType)
}
}
if (response.isSelected) {
viewModel.isSelected.value = true
}
}
}
| 0
|
Kotlin
|
1
| 31
|
c7ac17186696305970b622f0c6cd5a2c33dc3688
| 2,223
|
desk360-livechat-android-sdk
|
MIT License
|
src/main/kotlin/net/axay/kspigot/gui/GUIType.kt
|
bluefireoly
| 275,054,909
| false
| null |
@file:Suppress("MemberVisibilityCanBePrivate", "CanBeParameter")
package net.axay.kspigot.gui
import org.bukkit.Bukkit
import org.bukkit.event.inventory.InventoryType
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.InventoryHolder
class GUIType<in T : ForInventory>(
val dimensions: InventoryDimensions,
val bukkitType: InventoryType? = null,
) {
companion object {
val ONE_BY_NINE = GUIType<ForInventoryOneByNine>(InventoryDimensions(9, 1))
val TWO_BY_NINE = GUIType<ForInventoryTwoByNine>(InventoryDimensions(9, 2))
val THREE_BY_NINE = GUIType<ForInventoryThreeByNine>(InventoryDimensions(9, 3))
val FOUR_BY_NINE = GUIType<ForInventoryFourByNine>(InventoryDimensions(9, 4))
val FIVE_BY_NINE = GUIType<ForInventoryFiveByNine>(InventoryDimensions(9, 5))
val SIX_BY_NINE = GUIType<ForInventorySixByNine>(InventoryDimensions(9, 6))
val ONE_BY_FIVE =
GUIType<ForInventoryOneByFive>(InventoryDimensions(5, 1), bukkitType = InventoryType.HOPPER)
val THREE_BY_THREE =
GUIType<ForInventoryThreeByThree>(InventoryDimensions(3, 3), bukkitType = InventoryType.DROPPER)
}
fun createBukkitInv(holder: InventoryHolder? = null, title: String? = null): Inventory {
val realTitle = title ?: ""
return when {
bukkitType != null -> Bukkit.createInventory(holder, bukkitType, realTitle)
else -> Bukkit.createInventory(holder, dimensions.slotAmount, realTitle)
}
}
}
// INVENTORY TYPE SAFETY
interface ForInventory
interface ForInventoryThreeByThree : ForInventoryThreeByNine
interface ForInventoryOneByFive : ForInventoryOneByNine
interface ForInventoryOneByNine : ForInventoryTwoByNine
interface ForInventoryTwoByNine : ForInventoryThreeByNine
interface ForInventoryThreeByNine : ForInventoryFourByNine
interface ForInventoryFourByNine : ForInventoryFiveByNine
interface ForInventoryFiveByNine : ForInventorySixByNine
interface ForInventorySixByNine : ForInventory
interface ForEveryInventory : ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine,
ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine,
ForInventoryThreeByThree, ForInventoryOneByFive
interface ForInventoryWidthThree : ForInventoryThreeByThree
interface ForInventoryWidthFive : ForInventoryOneByFive
interface ForInventoryWidthNine : ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine,
ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine
| 1
|
Kotlin
|
15
| 63
|
47c220f65b4e020275d8deaf92923018332686a1
| 2,554
|
KSpigot
|
Apache License 2.0
|
src/main/kotlin/net/axay/kspigot/gui/GUIType.kt
|
bluefireoly
| 275,054,909
| false
| null |
@file:Suppress("MemberVisibilityCanBePrivate", "CanBeParameter")
package net.axay.kspigot.gui
import org.bukkit.Bukkit
import org.bukkit.event.inventory.InventoryType
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.InventoryHolder
class GUIType<in T : ForInventory>(
val dimensions: InventoryDimensions,
val bukkitType: InventoryType? = null,
) {
companion object {
val ONE_BY_NINE = GUIType<ForInventoryOneByNine>(InventoryDimensions(9, 1))
val TWO_BY_NINE = GUIType<ForInventoryTwoByNine>(InventoryDimensions(9, 2))
val THREE_BY_NINE = GUIType<ForInventoryThreeByNine>(InventoryDimensions(9, 3))
val FOUR_BY_NINE = GUIType<ForInventoryFourByNine>(InventoryDimensions(9, 4))
val FIVE_BY_NINE = GUIType<ForInventoryFiveByNine>(InventoryDimensions(9, 5))
val SIX_BY_NINE = GUIType<ForInventorySixByNine>(InventoryDimensions(9, 6))
val ONE_BY_FIVE =
GUIType<ForInventoryOneByFive>(InventoryDimensions(5, 1), bukkitType = InventoryType.HOPPER)
val THREE_BY_THREE =
GUIType<ForInventoryThreeByThree>(InventoryDimensions(3, 3), bukkitType = InventoryType.DROPPER)
}
fun createBukkitInv(holder: InventoryHolder? = null, title: String? = null): Inventory {
val realTitle = title ?: ""
return when {
bukkitType != null -> Bukkit.createInventory(holder, bukkitType, realTitle)
else -> Bukkit.createInventory(holder, dimensions.slotAmount, realTitle)
}
}
}
// INVENTORY TYPE SAFETY
interface ForInventory
interface ForInventoryThreeByThree : ForInventoryThreeByNine
interface ForInventoryOneByFive : ForInventoryOneByNine
interface ForInventoryOneByNine : ForInventoryTwoByNine
interface ForInventoryTwoByNine : ForInventoryThreeByNine
interface ForInventoryThreeByNine : ForInventoryFourByNine
interface ForInventoryFourByNine : ForInventoryFiveByNine
interface ForInventoryFiveByNine : ForInventorySixByNine
interface ForInventorySixByNine : ForInventory
interface ForEveryInventory : ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine,
ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine,
ForInventoryThreeByThree, ForInventoryOneByFive
interface ForInventoryWidthThree : ForInventoryThreeByThree
interface ForInventoryWidthFive : ForInventoryOneByFive
interface ForInventoryWidthNine : ForInventoryOneByNine, ForInventoryTwoByNine, ForInventoryThreeByNine,
ForInventoryFourByNine, ForInventoryFiveByNine, ForInventorySixByNine
| 1
|
Kotlin
|
15
| 63
|
47c220f65b4e020275d8deaf92923018332686a1
| 2,554
|
KSpigot
|
Apache License 2.0
|
app/src/main/java/ru/spitchenko/githubapp/feature/github/search/domain/FavoritesRepository.kt
|
Onotole1
| 246,505,562
| false
| null |
package ru.spitchenko.githubapp.feature.github.search.domain
import ru.spitchenko.githubapp.feature.github.domain.model.Repository
interface FavoritesRepository {
suspend fun addToFavorite(repository: Repository)
suspend fun removeFromFavorites(repositoryId: Long)
suspend fun getFavorites(repositories: List<Repository>): List<Repository>
}
| 0
|
Kotlin
|
1
| 0
|
74f07b543edbe8fa0bc75a119624b055b5fabb14
| 356
|
GithubApp
|
Apache License 2.0
|
ChatExample/app/src/main/java/com/github/dsrees/chatexample/MessagesAdapter.kt
|
dsrees
| 140,852,184
| false
| null |
package com.github.dsrees.chatexample
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class MessagesAdapter : RecyclerView.Adapter<MessagesAdapter.ViewHolder>() {
private var messages: MutableList<String> = mutableListOf()
fun add(message: String) {
messages.add(message)
notifyItemInserted(messages.size)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_message, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int = messages.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.label.text = messages[position]
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val label: TextView = itemView.findViewById(R.id.item_message_label)
}
}
| 5
|
Kotlin
|
27
| 50
|
52484478caaef77c4e09dbe61e8808b9817b7dd4
| 1,033
|
JavaPhoenixClient
|
MIT License
|
app/src/main/java/com/iamsdt/pssd/ext/ActivityExt.kt
|
uzzal-mondal
| 187,579,574
| true
|
{"Kotlin": 186145}
|
/*
* Developed By <NAME>
* on 8/17/18 10:54 AM
* Copyright (c) 2018 <NAME>.
*/
package com.iamsdt.pssd.ext
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.browser.customtabs.CustomTabsIntent
import androidx.fragment.app.Fragment
import com.iamsdt.pssd.R
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
inline fun <reified T : AppCompatActivity> AppCompatActivity.nextActivity(
extraKey: String = "", extra: Any = "", finish: Boolean = false
) {
val intent = Intent(this, T::class.java)
if (extraKey.isNotEmpty()) {
when (extra) {
is String -> intent.putExtra(extraKey, extra)
is Boolean -> intent.putExtra(extraKey, extra)
is Float -> intent.putExtra(extraKey, extra)
is Long -> intent.putExtra(extraKey, extra)
is Int -> intent.putExtra(extraKey, extra)
is Bundle -> intent.putExtra(extraKey, extra)
else -> intent.putExtra(extraKey, "$extra")
}
}
startActivity(intent)
if (finish) finish()
}
inline fun <reified T : AppCompatActivity> AppCompatActivity.runThreadK(timer: Long = 1000) {
GlobalScope.launch {
delay(timer)
nextActivity<T>()
finish()
}
}
inline fun <reified T : AppCompatActivity> Fragment.nextActivity(
extraKey: String = "", extra: Any = ""
) {
val intent = Intent(activity, T::class.java)
if (extraKey.isNotEmpty()) {
when (extra) {
is String -> intent.putExtra(extraKey, extra)
is Boolean -> intent.putExtra(extraKey, extra)
is Float -> intent.putExtra(extraKey, extra)
is Long -> intent.putExtra(extraKey, extra)
is Int -> intent.putExtra(extraKey, extra)
is Bundle -> intent.putExtra(extraKey, extra)
else -> intent.putExtra(extraKey, "$extra")
}
}
startActivity(intent)
}
fun AppCompatActivity.customTab(link: String) {
val builder = CustomTabsIntent.Builder()
builder.setToolbarColor(R.attr.colorPrimary)
builder.setShowTitle(true)
builder.addDefaultShareMenuItem()
//builder.setCloseButtonIcon(BitmapFactory.decodeResource(
//resources, R.drawable.dialog_back))
val customTabsIntent = builder.build()
customTabsIntent.launchUrl(this, Uri.parse(link))
}
fun AppCompatActivity.sendEmail(
email: String,
subject: String) {
val intent = Intent(Intent.ACTION_SENDTO)
intent.type = "text/plain"
intent.data = Uri.parse("mailto:$email")
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
startActivity(Intent.createChooser(intent, "Send Email"))
}
| 0
|
Kotlin
|
0
| 0
|
9ee1041a5a808f3b3f0a297c7e7aab8c77263e3a
| 2,783
|
SoilScienceDictionary
|
Apache License 2.0
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/api/Argument.kt
|
raymondwdamon
| 157,889,311
| false
| null |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.api
import com.intellij.psi.PsiType
interface Argument {
val type: PsiType?
val topLevelType: PsiType? get() = type
}
| 1
| null |
1
| 1
|
38392d14453bdd788b34c176dcdac7fa5498faab
| 317
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/example/jmb_bms/view/MenuTop3.kt
|
alarm-clock
| 701,783,108
| false
|
{"Kotlin": 868333}
|
/**
* @file: MenuTop3.kt
* @author: <NAME> <<EMAIL>,<EMAIL>>
* Description: File containing menu top and connection state row
*/
package com.example.jmb_bms.view
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Circle
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.LiveData
import com.example.jmb_bms.connectionService.ConnectionState
import com.example.jmb_bms.ui.theme.LocalTheme
import com.example.jmb_bms.viewModel.LiveLocationFromPhone
import com.example.jmb_bms.viewModel.LiveTime
/**
* Not connected top
*
* @param color of the dot
*/
@Composable
fun NotConnectedTop(color: Color)
{
Text("Disconnected", fontSize = 12.sp, color = color)
Icon(Icons.Default.Circle, "", tint = Color.Red, modifier = Modifier.size(12.dp))
}
/**
* Negotiating top
*
* @param color color of the dot
*/
@Composable
fun NegotiatingTop(color: Color)
{
Text("Connecting...", fontSize = 12.sp, color = color)
Icon(Icons.Default.Circle, "", tint = Color.Yellow, modifier = Modifier.size(12.dp))
}
/**
* Connection state row
*
* @param connectionState Live data with connection state
*/
@Composable
fun ConnectionStateRow(connectionState: LiveData<ConnectionState>)
{
val state by connectionState.observeAsState()
val scheme = LocalTheme.current
Row(
modifier = Modifier.background(scheme.primary),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
Spacer(Modifier.width(6.dp))
Text("Connection state: ", fontSize = 12.sp, color = scheme.onPrimary)
when(state)
{
ConnectionState.CONNECTED -> {
Text("Connected", fontSize = 12.sp, color = scheme.onPrimary)
Icon(Icons.Default.Circle,"", tint = Color.Green, modifier = Modifier.size(12.dp))
}
ConnectionState.ERROR -> NotConnectedTop(scheme.onPrimary)
ConnectionState.NOT_CONNECTED -> NotConnectedTop(scheme.onPrimary)
ConnectionState.NONE -> NotConnectedTop(scheme.onPrimary)
ConnectionState.NEGOTIATING -> NegotiatingTop(scheme.onPrimary)
ConnectionState.RECONNECTING -> NegotiatingTop(scheme.onPrimary)
else -> NotConnectedTop(scheme.onPrimary)
}
}
}
/**
* Menu top with connection state
*
* @param currTimeVM VM with time
* @param currLocVM VM with location
* @param connectionState Live data with connection state
*/
@Composable
fun MenuTop3(currTimeVM: LiveTime, currLocVM: LiveLocationFromPhone, connectionState: LiveData<ConnectionState>)
{
val scheme = LocalTheme.current
Column(
modifier = Modifier.fillMaxWidth().background(scheme.primary)
){
ConnectionStateRow(connectionState)
Row( modifier = Modifier.fillMaxWidth())
{
MenuTop1(currTimeVM, currLocVM)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
1e3227abcd299188042ba847e7e4a2153334d51e
| 3,379
|
PERLA_Android_client
|
MIT License
|
codeSnippets/snippets/json-kotlinx/src/test/kotlin/jsonkotlinx/ApplicationTest.kt
|
ktorio
| 278,572,893
| false
|
{"Kotlin": 326650, "HTML": 29275, "JavaScript": 5361, "FreeMarker": 2738, "Dockerfile": 1709, "Swift": 1432, "CSS": 470, "Handlebars": 75, "Pug": 51}
|
package com.example
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.testing.*
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlin.test.*
class CustomerTests {
@Test
fun testGetCustomer() = testApplication {
val response = client.get("/customer/1")
assertEquals(
"""
{
"id": 1,
"firstName": "Jane",
"lastName": "Smith"
}
""".trimIndent(),
response.bodyAsText()
)
assertEquals(HttpStatusCode.OK, response.status)
}
@Test
fun testPostCustomer() = testApplication {
val client = createClient {
install(ContentNegotiation) {
json()
}
}
val response = client.post("/customer") {
contentType(ContentType.Application.Json)
setBody(Customer(3, "Jet", "Brains"))
}
assertEquals("Customer stored correctly", response.bodyAsText())
assertEquals(HttpStatusCode.Created, response.status)
}
@Test
fun testPostCustomerLegacyApi() = withTestApplication(Application::main) {
with(handleRequest(HttpMethod.Post, "/customer"){
addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString())
setBody(Json.encodeToString(Customer(3, "Jet", "Brains")))
}) {
assertEquals("Customer stored correctly", response.content)
assertEquals(HttpStatusCode.Created, response.status())
}
}
}
| 3
|
Kotlin
|
284
| 428
|
a6db611f4fea9a5deb53a571c98891326b24e55f
| 1,775
|
ktor-documentation
|
Apache License 2.0
|
src/main/kotlin/moirai/service/Transport.kt
|
moirai-lang
| 783,108,500
| false
|
{"Kotlin": 22025}
|
package moirai.service
import com.fasterxml.jackson.databind.JsonNode
import moirai.transport.*
fun jsonToMoirai(node: JsonNode, type: TransportType): String {
when (type) {
is TransportBasicType -> {
if (type.name == "Boolean" && node.isValueNode) {
return node.asBoolean().toString()
}
if (type.name == "Int" && node.isValueNode) {
return node.asInt().toString()
}
if (type.name == "Char" && node.isTextual) {
val t = node.toString().trimStart('"').trimEnd('"')
if (t.length == 1) {
return "\'${t}\'"
}
}
jsonFail()
}
is TransportGroundRecordType -> {
if (node.isObject || node.isPojo) {
val fields = type.fields.map { jsonToMoirai(node[it.name], it.type) }.joinToString()
return "${type.name}($fields)"
}
jsonFail()
}
is TransportObjectType -> {
if (node.isTextual && node.asText() == type.name) {
return type.name
}
jsonFail()
}
is TransportParameterizedBasicType -> {
if (type.name == "String" && node.isValueNode) {
val t = node.toString().trimStart('"').trimEnd('"')
return "\"${t}\""
}
if (type.name == "Decimal" && node.isValueNode) {
return node.asDouble().toString()
}
if (type.name == "List" && node.isArray) {
val elements = node.elements().asSequence().toList().map { jsonToMoirai(it, type.typeArgs.first()) }
return "List(${elements.joinToString()})"
}
if (type.name == "Set" && node.isArray) {
val elements = node.elements().asSequence().toList().map { jsonToMoirai(it, type.typeArgs.first()) }
return "Set(${elements.joinToString()})"
}
if (type.name == "Dictionary" && node.isArray) {
val elements = node.elements().asSequence().toList().map {
if (it.isPojo || it.isObject) {
val fn = it.fieldNames().asSequence().toList()
if (fn.size != 2) {
jsonFail()
}
// TODO: Define your semantics for dictionaries
// Sorted field names alphabetically
val s = fn.sorted()
// First is key
val k = it[s[0]]
// Second is value
val v = it[s[1]]
"${jsonToMoirai(k, type.typeArgs[0])} to ${jsonToMoirai(v, type.typeArgs[1])}"
}
jsonFail()
}
return "Dictionary(${elements.joinToString()})"
}
jsonFail()
}
is TransportParameterizedRecordType -> {
if (node.isObject || node.isPojo) {
val fields = type.fields.map { jsonToMoirai(node[it.name], it.type) }.joinToString()
return "${type.name}($fields)"
}
jsonFail()
}
is TransportPlatformObjectType -> {
if (node.isTextual && node.asText() == type.name) {
return type.name
}
jsonFail()
}
is TransportPlatformSumType -> {
if (type.name == "Option") {
if (node.isNull) {
return "None"
} else {
return "Some(${jsonToMoirai(node, type.typeArgs.first())})"
}
}
jsonFail()
}
NonPublicTransportType,
TransportConstantFin,
is TransportFin,
is TransportFinTypeParameter,
is TransportMaxCostExpression,
is TransportProductCostExpression,
is TransportSumCostExpression,
is TransportFunctionType,
is TransportPlatformSumObjectType,
is TransportPlatformSumRecordType,
is TransportStandardTypeParameter -> jsonFail()
}
}
fun jsonFail(): Nothing {
throw MoiraiServiceException("Could not convert JSON to this type")
}
| 0
|
Kotlin
|
0
| 2
|
54fe8809cbbc53fabb80b6ad5757ee2bd3cc4074
| 4,378
|
moirai-service
|
MIT License
|
ekscore/src/main/kotlin/js/node/fs/write/index.kt
|
kazhida
| 141,879,098
| false
| null |
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", "UNUSED")
@file:[JsModule("fs") JsQualifier("write")]
package js.node.fs.write
import kotlin.js.*
external interface `T$65`<TBuffer> {
var bytesWritten: Number
var buffer: TBuffer
}
external fun <TBuffer /* Buffer | Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array | DataView */> __promisify__(fd: Number, buffer: TBuffer? = definedExternally /* null */, offset: Number? = definedExternally /* null */, length: Number? = definedExternally /* null */, position: Number? = definedExternally /* null */): Promise<`T$65`<TBuffer>> = definedExternally
external interface `T$66` {
var bytesWritten: Number
var buffer: String
}
external fun __promisify__(fd: Number, string: Any, position: Number? = definedExternally /* null */, encoding: String? = definedExternally /* null */): Promise<`T$66`> = definedExternally
| 0
|
Kotlin
|
0
| 0
|
0db86fad2dea30ccd8d31916ea9a4fee784e43ee
| 1,099
|
eks
|
Apache License 2.0
|
app/src/main/java/com/aviva/pedro_exercise_compose/ui/Spinner.kt
|
DeveloperJGV
| 803,435,386
| false
|
{"Kotlin": 8731}
|
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.aviva.pedro_exercise_compose.R
@Composable
fun Spinner() {
val infiniteTransition = rememberInfiniteTransition()
val rotation by infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = -360f,
animationSpec = infiniteRepeatable(
animation = tween(6000, easing = LinearEasing),
repeatMode = RepeatMode.Restart
)
)
val scale by animateFloatAsState(
targetValue = 1.1f,
animationSpec = infiniteRepeatable(
animation = tween(3000, easing = LinearEasing),
repeatMode = RepeatMode.Reverse
)
)
val bounce by infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 20f,
animationSpec = infiniteRepeatable(
animation = tween(200, easing = LinearEasing),
repeatMode = RepeatMode.Reverse
)
)
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Box(
modifier = Modifier
.size(200.dp)
.background(Color(0xFFF5DAD8), CircleShape)
.clip(CircleShape)
.rotate(rotation)
.scale(scale)
) {
Image(
painter = painterResource(R.drawable.pedro),
contentDescription = "Spinner Image",
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxSize()
.offset(y = bounce.dp)
)
}
}
}
@Composable
fun SpinnerPreview() {
MaterialTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color(0xFF161616)
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
Spinner()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ae5ac4092c2432ad0f973bf6eca676c01b34907b
| 3,250
|
Pedro-Exercise-Compose
|
MIT License
|
app/src/main/java/id/android/basics/modules/domain/MainUsecase.kt
|
budioktaviyan
| 493,531,782
| false
| null |
package id.android.basics.modules.domain
class MainUsecase(private val repository: MainRepository)
| 0
|
Kotlin
|
0
| 7
|
d1ef2a2522e28853ae05adf405d76bea4319114b
| 99
|
modularization-basics
|
MIT License
|
app/src/main/java/com/connectycube/messenger/ChatConnectionManager.kt
|
ConnectyCube
| 198,286,170
| false
|
{"Kotlin": 396454, "Java": 19119}
|
package com.connectycube.messenger
import android.content.Context
import com.connectycube.messenger.events.EVENT_CHAT_LOGIN
import com.connectycube.messenger.events.EventChatConnection
import com.connectycube.messenger.events.LiveDataBus
import com.connectycube.messenger.helpers.RTCSessionManager
import com.connectycube.messenger.utilities.SharedPreferencesManager
import com.connectycube.ConnectyCube
import com.connectycube.chat.realtime.ConnectycubeConnectionListener
import com.connectycube.users.models.ConnectycubeUser
import timber.log.Timber
import java.util.concurrent.atomic.AtomicBoolean
class ChatConnectionManager {
companion object {
@Volatile
private var instance: ChatConnectionManager? = null
fun getInstance() =
instance ?: synchronized(this) {
instance ?: ChatConnectionManager().also { instance = it }
}
}
private val isPending = AtomicBoolean(false)
private val isInitialized = AtomicBoolean(false)
private val chatAppObserver = ChatAppLifecycleObserver()
fun initWith(context: Context) {
Timber.d("initWith, isPending ${isPending.get()}")
if (isPending.get() || isInitialized.get()) return
if (SharedPreferencesManager.getInstance(context).currentUserExists()
&& !ConnectyCube.chat.isLoggedIn()
) {
isPending.set(true)
Timber.d("Start chat login")
initConnectionListener()
ConnectyCube.chat.login(
SharedPreferencesManager.getInstance(context).getCurrentUser(),
{
isPending.set(false)
isInitialized.set(true)
registerAppLifeCycleObserver()
initCallManager(context)
},
{ ex ->
isPending.set(false)
Timber.d("Error while login to chat, error = ${ex.message}")
notifyErrorLoginToChat(ex)
})
}
}
private fun initConnectionListener() {
ConnectyCube.chat.addConnectionListener(object : ConnectycubeConnectionListener {
override fun onConnected() {
Timber.d("authenticated")
notifySuccessLoginToChat(ConnectyCube.chat.userForLogin!!)
}
override fun onDisconnected() {
Timber.d("onDisconnected")
notifyErrorLoginToChat(Exception("onDisconnected"))
}
})
}
private fun registerAppLifeCycleObserver() {
chatAppObserver.registeredObserver()
}
private fun unregisterAppLifeCycleObserver() {
chatAppObserver.unregisteredObserver()
}
private fun notifyErrorLoginToChat(exception: Exception) {
LiveDataBus.publish(EVENT_CHAT_LOGIN, EventChatConnection.error(exception))
}
private fun notifySuccessLoginToChat(connectycubeUser: ConnectycubeUser) {
LiveDataBus.publish(
EVENT_CHAT_LOGIN,
EventChatConnection.success(connectycubeUser)
)
}
private fun initCallManager(context: Context) {
RTCSessionManager.getInstance().init(context.applicationContext)
}
fun terminate() {
ConnectyCube.chat.logout()
unregisterAppLifeCycleObserver()
isPending.set(false)
isInitialized.set(false)
instance = null
}
}
| 0
|
Kotlin
|
23
| 51
|
1b7a8942692791365a0c28140fd673eb7823b7cb
| 3,425
|
android-messenger-app
|
Apache License 2.0
|
Sample/src/main/java/com/angcyo/dsladapter/demo/LoadMoreActivity.kt
|
angcyo
| 201,440,286
| false
|
{"Kotlin": 409151}
|
package com.angcyo.dsladapter.demo
import android.widget.Toast
import com.angcyo.dsladapter.DslAdapterStatusItem
import com.angcyo.dsladapter.DslLoadMoreItem
/**
*
* Email:<EMAIL>
* @author angcyo
* @date 2019/10/16
* Copyright (c) 2019 ShenZhen O&M Cloud Co., Ltd. All rights reserved.
*/
class LoadMoreActivity : BaseRecyclerActivity() {
override fun getBaseLayoutId(): Int {
return R.layout.activity_load_more
}
override fun onInitBaseLayoutAfter() {
super.onInitBaseLayoutAfter()
dslAdapter.render {
setAdapterStatus(DslAdapterStatusItem.ADAPTER_STATUS_LOADING)
}
dslViewHolder.postDelay(1000) {
dslAdapter.render {
setAdapterStatus(DslAdapterStatusItem.ADAPTER_STATUS_NONE)
来点数据()
setLoadMoreEnable(true)
}
}
initLoadMore()
}
override fun onRefresh() {
super.onRefresh()
dslAdapter.render {
resetItem(listOf())
来点数据()
}
}
var loadPage = 0
private fun initLoadMore() {
dslAdapter.dslLoadMoreItem.onLoadMore = {
Toast.makeText(this, "加载更多", Toast.LENGTH_SHORT).show()
it.postDelay(300L) {
dslAdapter.render {
loadPage++
if (loadPage == 2) {
//模拟加载失败
setLoadMore(DslLoadMoreItem.LOAD_MORE_ERROR)
} else if (loadPage > 3) {
//模拟没有更多
setLoadMore(DslLoadMoreItem.LOAD_MORE_NO_MORE)
} else {
来点数据()
// for (i in 0..0) {
// dslAdapter.dslItem(R.layout.item_text_layout) {
// itemBind = { itemHolder, itemPosition, _ ->
// itemHolder.v<TextView>(R.id.text_view).text =
// "新增的数据! 文本位置:$itemPosition"
// }
// }
// }
setLoadMore(DslLoadMoreItem.LOAD_MORE_NORMAL)
}
}
}
}
dslViewHolder.click(R.id.load_more_enable) {
loadPage = 0
dslAdapter.render {
setLoadMoreEnable(it.isSelected)
}
it.isSelected = !it.isSelected
}
dslViewHolder.click(R.id.load_more_error) {
loadPage = 0
dslAdapter.render {
setLoadMore(DslLoadMoreItem.LOAD_MORE_ERROR)
}
}
dslViewHolder.click(R.id.load_more_no) {
loadPage = 0
dslAdapter.render {
setLoadMore(DslLoadMoreItem.LOAD_MORE_NO_MORE)
}
}
}
}
| 3
|
Kotlin
|
57
| 690
|
d0c5110a1dfeb11a93a9b0e5b9ac353bcb3c08d2
| 2,858
|
DslAdapter
|
MIT License
|
src/co/aospa/sense/activities/FaceBaseActivity.kt
|
AOSPA
| 560,146,398
| false
| null |
package co.aospa.sense.activities
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import co.aospa.sense.R
import co.aospa.sense.util.Constants
import com.google.android.setupdesign.GlifLayout
abstract class FaceBaseActivity : FragmentActivity() {
private var mLaunchedConfirmLock = false
@JvmField
protected var mToken: ByteArray? = null
protected var mUserId = 0
override fun onCreate(bundle: Bundle?) {
super.onCreate(bundle)
setTheme(R.style.SudThemeGlifV4)
mToken = intent.getByteArrayExtra(Constants.EXTRA_KEY_CHALLENGE_TOKEN)
if (bundle != null && mToken == null) {
mLaunchedConfirmLock = bundle.getBoolean(Constants.EXTRA_KEY_LAUNCHED_CONFIRM)
mToken = bundle.getByteArray(Constants.EXTRA_KEY_CHALLENGE_TOKEN)
mUserId = bundle.getInt(Intent.EXTRA_USER_ID)
}
}
override fun onSaveInstanceState(bundle: Bundle) {
super.onSaveInstanceState(bundle)
bundle.putBoolean(Constants.EXTRA_KEY_LAUNCHED_CONFIRM, mLaunchedConfirmLock)
bundle.putByteArray(Constants.EXTRA_KEY_CHALLENGE_TOKEN, mToken)
}
protected fun parseIntent(intent: Intent) {
intent.putExtra(Constants.EXTRA_KEY_CHALLENGE_TOKEN, mToken)
intent.putExtra(Intent.EXTRA_USER_ID, mUserId)
}
abstract fun getLayout(): GlifLayout
open fun setHeaderText(res: Int) {
val header: TextView = getLayout().headerTextView
val previous: CharSequence = header.text
val current = getText(res)
if (previous !== current) {
if (!TextUtils.isEmpty(current)) {
header.accessibilityLiveRegion = 1
}
getLayout().headerText = current
title = current
}
}
}
| 0
| null |
7
| 1
|
f6b6c51961d20b1c0b07484181ca03ba30405178
| 1,890
|
android_packages_apps_ParanoidSense
|
Apache License 2.0
|
test/src/me/anno/tests/image/Webp.kt
|
AntonioNoack
| 456,513,348
| false
| null |
package me.anno.tests.image
import me.anno.gpu.hidden.HiddenOpenGLContext
import me.anno.image.ImageGPUCache
import me.anno.utils.OS.desktop
import me.anno.utils.OS.pictures
import me.anno.utils.OS.videos
fun main() {
// todo why is loading these images within materials not working?
val dst = desktop.getChild("tmp")
dst.mkdirs()
HiddenOpenGLContext.createOpenGL()
for (file in pictures.getChild("Anime").listChildren()!!) {
if (file.lcExtension == "webp" && !file.isDirectory) {
ImageGPUCache[file, false]!!
.write(dst.getChild("${file.nameWithoutExtension}.png"))
}
}
// todo why is video not working there either?
for (file in videos.listChildren()!!) {
if (!file.isDirectory) {
ImageGPUCache[file, false]!!
.write(dst.getChild("${file.nameWithoutExtension}.png"))
}
}
}
| 0
| null |
1
| 7
|
bacd7c79b8b34765d157012a08d728008c4b2d9a
| 900
|
RemsEngine
|
Apache License 2.0
|
libraries/textcomposer/impl/src/main/kotlin/io/element/android/libraries/textcomposer/model/VoiceMessagePlayerEvent.kt
|
element-hq
| 546,522,002
| false
|
{"Kotlin": 8692554, "Python": 57175, "Shell": 39911, "JavaScript": 20399, "Java": 9607, "HTML": 9416, "CSS": 2519, "Ruby": 44}
|
/*
* Copyright (c) 2023 New Vector Ltd
*
* 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.element.android.libraries.textcomposer.model
sealed class VoiceMessagePlayerEvent {
data object Play: VoiceMessagePlayerEvent()
data object Pause: VoiceMessagePlayerEvent()
data class Seek(
val position: Float
): VoiceMessagePlayerEvent()
}
| 263
|
Kotlin
|
65
| 955
|
31d0621fa15fe153bfd36104e560c9703eabe917
| 881
|
element-x-android
|
Apache License 2.0
|
app/src/main/java/com/allever/app/virtual/call/ui/mvp/presenter/AdvancedIncomeSettingPresenter.kt
|
devallever
| 242,982,031
| false
| null |
package com.allever.app.virtual.call.ui.mvp.presenter
import com.allever.app.virtual.call.ui.mvp.view.AdvancedIncomeSettingView
import com.allever.lib.common.mvp.BasePresenter
class AdvancedIncomeSettingPresenter: BasePresenter<AdvancedIncomeSettingView>() {
}
| 3
|
Kotlin
|
7
| 24
|
2881e1d2285d5ee459f40dffeed105c101bcafff
| 262
|
VirtualCallOpenSource
|
Apache License 2.0
|
android/app/src/main/kotlin/io/rebble/fossil/notifications/NotificationListener.kt
|
yamsergey
| 310,554,820
| true
|
{"Dart": 81649, "Kotlin": 34336, "Swift": 404, "Objective-C": 38}
|
package io.rebble.fossil.notifications
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import io.flutter.Log
import io.rebble.fossil.FossilApplication
import io.rebble.libpebblecommon.services.notification.NotificationService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
class NotificationListener : NotificationListenerService() {
private lateinit var coroutineScope: CoroutineScope
private var isListening = false
private val logTag: String = "FossilNotifService"
private var notifStates: MutableMap<NotificationKey, ParsedNotification> = mutableMapOf()
private lateinit var notificationService: NotificationService
override fun onCreate() {
val injectionComponent = (applicationContext as FossilApplication).component
coroutineScope = CoroutineScope(
SupervisorJob() + injectionComponent.createExceptionHandler()
)
notificationService = injectionComponent.createNotificationService()
super.onCreate()
}
override fun onDestroy() {
super.onDestroy()
coroutineScope.cancel()
}
override fun onListenerConnected() {
isListening = true
}
override fun onListenerDisconnected() {
isListening = false
}
private fun sendNotif(parsedNotification: ParsedNotification) {
coroutineScope.launch {
notificationService.send(parsedNotification.toBluetoothPacket())
}
}
override fun onNotificationPosted(sbn: StatusBarNotification?) {
if (isListening) {
if (sbn == null) return
if (sbn.packageName == applicationContext.packageName) return // Don't show a notification if it's us
val parsedNotification = sbn.parseData(applicationContext)
val key = NotificationKey(sbn)
// If the content is the exact same as it was before (and the notif isnt new / previously dismissed), ignore the new notif
val existingNotification = notifStates.put(key, parsedNotification)
if (existingNotification == parsedNotification) {
return
}
sendNotif(parsedNotification)
}
}
override fun onNotificationRemoved(sbn: StatusBarNotification) {
if (isListening) {
Log.d(logTag, "Notification removed: ${sbn.packageName}")
notifStates.remove(NotificationKey(sbn))
//TODO: Dismissing on watch
}
}
}
| 0
| null |
0
| 0
|
9bbeabee83d11eb61faf521000ca1c8ae5d235f4
| 2,634
|
mobile-app
|
Apache License 2.0
|
src/test/kotlin/com/amazon/opendistroforelasticsearch/indexmanagement/indexstatemanagement/runner/ManagedIndexRunnerIT.kt
|
opendistro-for-elasticsearch
| 174,581,847
| false
| null |
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.runner
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.IndexStateManagementRestTestCase
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.model.ManagedIndexMetaData
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.model.Policy
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.model.State
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.model.action.ActionConfig
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.model.action.OpenActionConfig
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.model.managedindexmetadata.PolicyRetryInfoMetaData
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.randomErrorNotification
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.randomPolicy
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.randomReadOnlyActionConfig
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.randomReadWriteActionConfig
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.randomState
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.randomTransition
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.settings.ManagedIndexSettings
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.step.readonly.SetReadOnlyStep
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.step.readwrite.SetReadWriteStep
import com.amazon.opendistroforelasticsearch.indexmanagement.indexstatemanagement.step.transition.AttemptTransitionStep
import com.amazon.opendistroforelasticsearch.indexmanagement.waitFor
import com.amazon.opendistroforelasticsearch.jobscheduler.spi.schedule.IntervalSchedule
import java.time.Instant
import java.time.temporal.ChronoUnit
class ManagedIndexRunnerIT : IndexStateManagementRestTestCase() {
fun `test version conflict fails job`() {
val indexName = "version_conflict_index"
val policyID = "version_conflict_policy"
val actionConfig = OpenActionConfig(0)
val states = listOf(State("OpenState", listOf(actionConfig), listOf()))
val policy = Policy(
id = policyID,
description = "$indexName description",
schemaVersion = 1L,
lastUpdatedTime = Instant.now().truncatedTo(ChronoUnit.MILLIS),
errorNotification = randomErrorNotification(),
defaultState = states[0].name,
states = states
)
createPolicy(policy, policyID)
createIndex(indexName, policyID)
val managedIndexConfig = getExistingManagedIndexConfig(indexName)
// init policy on managed index
updateManagedIndexConfigStartTime(managedIndexConfig)
waitFor { assertEquals(policy.id, getExplainManagedIndexMetaData(indexName).policyID) }
// change policy seqNo on managed index
updateManagedIndexConfigPolicySeqNo(managedIndexConfig.copy(policySeqNo = 17))
// start execution to see if it moves to failed because of version conflict
updateManagedIndexConfigStartTime(managedIndexConfig)
val expectedInfoString = mapOf("message" to "There is a version conflict between your previous execution and your managed index").toString()
waitFor {
assertPredicatesOnMetaData(
listOf(indexName to listOf(
PolicyRetryInfoMetaData.RETRY_INFO to fun(retryInfoMetaDataMap: Any?): Boolean =
assertRetryInfoEquals(PolicyRetryInfoMetaData(true, 0), retryInfoMetaDataMap),
ManagedIndexMetaData.INFO to fun(info: Any?): Boolean = expectedInfoString == info.toString()
)),
getExplainMap(indexName),
strict = false
)
}
}
fun `test job interval changing`() {
val indexName = "job_interval_index_"
val createdPolicy = createRandomPolicy()
createIndex(indexName, createdPolicy.id)
val managedIndexConfig = getExistingManagedIndexConfig(indexName)
assertEquals("Created managed index did not default to ${ManagedIndexSettings.DEFAULT_JOB_INTERVAL}minutes",
ManagedIndexSettings.DEFAULT_JOB_INTERVAL, (managedIndexConfig.jobSchedule as IntervalSchedule).interval)
// init policy
updateManagedIndexConfigStartTime(managedIndexConfig)
waitFor { assertEquals(createdPolicy.id, getManagedIndexConfigByDocId(managedIndexConfig.id)?.policyID) }
// change cluster job interval setting to 2 (minutes)
updateClusterSetting(ManagedIndexSettings.JOB_INTERVAL.key, "2")
// fast forward to next execution where at the end we should change the job interval time
updateManagedIndexConfigStartTime(managedIndexConfig)
waitFor { (getManagedIndexConfigByDocId(managedIndexConfig.id)?.jobSchedule as? IntervalSchedule)?.interval == 2 }
}
fun `test allow list fails execution`() {
val indexName = "allow_list_index"
val firstState = randomState(name = "first_state", actions = listOf(randomReadOnlyActionConfig()),
transitions = listOf(randomTransition(stateName = "second_state", conditions = null)))
val secondState = randomState(name = "second_state", actions = listOf(randomReadWriteActionConfig()),
transitions = listOf(randomTransition(stateName = "first_state", conditions = null)))
val randomPolicy = randomPolicy(id = "allow_policy", states = listOf(firstState, secondState))
val createdPolicy = createPolicy(randomPolicy, "allow_policy")
createIndex(indexName, createdPolicy.id)
val managedIndexConfig = getExistingManagedIndexConfig(indexName)
// init policy
updateManagedIndexConfigStartTime(managedIndexConfig)
waitFor { assertEquals(createdPolicy.id, getExplainManagedIndexMetaData(indexName).policyID) }
// speed up to first execution that should set index to read only
updateManagedIndexConfigStartTime(managedIndexConfig)
waitFor { assertEquals(SetReadOnlyStep.getSuccessMessage(indexName), getExplainManagedIndexMetaData(indexName).info?.get("message")) }
// speed up to second execution that should transition to second_state
updateManagedIndexConfigStartTime(managedIndexConfig)
waitFor { assertEquals(AttemptTransitionStep.getSuccessMessage(indexName, secondState.name), getExplainManagedIndexMetaData(indexName).info?.get("message")) }
// speed up to third execution that should set index back to read write
updateManagedIndexConfigStartTime(managedIndexConfig)
waitFor { assertEquals(SetReadWriteStep.getSuccessMessage(indexName), getExplainManagedIndexMetaData(indexName).info?.get("message")) }
// speed up to fourth execution that should transition to first_state
updateManagedIndexConfigStartTime(managedIndexConfig)
waitFor { assertEquals(AttemptTransitionStep.getSuccessMessage(indexName, firstState.name), getExplainManagedIndexMetaData(indexName).info?.get("message")) }
// remove read_only from the allowlist
val allowedActions = ActionConfig.ActionType.values().toList()
.filter { actionType -> actionType != ActionConfig.ActionType.READ_ONLY }
.joinToString(prefix = "[", postfix = "]") { string -> "\"$string\"" }
updateClusterSetting(ManagedIndexSettings.ALLOW_LIST.key, allowedActions, escapeValue = false)
// speed up to fifth execution that should try to set index to read only and fail because the action is not allowed
updateManagedIndexConfigStartTime(managedIndexConfig)
waitFor { assertEquals("Attempted to execute action=read_only which is not allowed.", getExplainManagedIndexMetaData(indexName).info?.get("message")) }
}
}
| 51
| null |
46
| 117
|
cda0eda35fc5da3816c407ad7a929d746edaf179
| 9,111
|
index-management
|
Apache License 2.0
|
zircon.jvm/src/test/kotlin/org/hexworks/zircon/internal/component/impl/DefaultContainerTest.kt
|
entelente
| 148,384,225
| false
| null |
package org.hexworks.zircon.internal.component.impl
import org.assertj.core.api.Assertions.*
import org.hexworks.zircon.api.AppConfigs
import org.hexworks.zircon.api.builder.component.ComponentStyleSetBuilder
import org.hexworks.zircon.api.builder.component.HeaderBuilder
import org.hexworks.zircon.api.builder.component.LabelBuilder
import org.hexworks.zircon.api.builder.component.PanelBuilder
import org.hexworks.zircon.api.builder.graphics.StyleSetBuilder
import org.hexworks.zircon.api.builder.grid.TileGridBuilder
import org.hexworks.zircon.api.builder.screen.ScreenBuilder
import org.hexworks.zircon.api.color.ANSITileColor
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.event.EventBus
import org.hexworks.zircon.api.resource.BuiltInCP437TilesetResource
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.internal.component.impl.wrapping.BorderComponentDecorationRenderer
import org.hexworks.zircon.internal.component.impl.wrapping.ShadowComponentDecorationRenderer
import org.hexworks.zircon.internal.event.ZirconEvent
import org.hexworks.zircon.api.Modifiers
import org.hexworks.zircon.api.Positions
import org.junit.Before
import org.junit.Test
import java.util.concurrent.atomic.AtomicBoolean
class DefaultContainerTest {
lateinit var target: DefaultContainer
lateinit var goodTileset: TilesetResource
lateinit var badTileset: TilesetResource
@Before
fun setUp() {
goodTileset = GOOD_TILESET
badTileset = BAD_TILESET
target = DefaultContainer(
initialSize = SIZE,
position = POSITION,
componentStyleSet = STYLES,
wrappers = WRAPPERS,
initialTileset = goodTileset)
}
@Test
fun shouldProperlySetUpComponentsWhenNestedComponentsAreAdded() {
val grid = TileGridBuilder.newBuilder()
.size(Size.create(40, 25))
.tileset(BuiltInCP437TilesetResource.REX_PAINT_16X16)
.build()
val screen = ScreenBuilder.createScreenFor(grid)
val panel = PanelBuilder.newBuilder()
.wrapWithBox()
.title("Panel")
.size(Size.create(32, 16))
.position(Position.create(1, 1))
.build()
val panelHeader = HeaderBuilder.newBuilder()
.position(Positions.create(1, 0))
.text("Header")
.build()
val innerPanelHeader = HeaderBuilder.newBuilder()
.position(Position.create(1, 0))
.text("Header2")
.build()
val innerPanel = PanelBuilder.newBuilder()
.wrapWithBox()
.title("Panel2")
.size(Size.create(16, 10))
.position(Positions.create(1, 2))
.build()
assertThat(panel.isAttached()).isFalse()
assertThat(panelHeader.isAttached()).isFalse()
assertThat(innerPanel.isAttached()).isFalse()
assertThat(innerPanelHeader.isAttached()).isFalse()
innerPanel.addComponent(innerPanelHeader)
assertThat(innerPanelHeader.isAttached()).isTrue()
panel.addComponent(panelHeader)
assertThat(panelHeader.isAttached()).isTrue()
panel.addComponent(innerPanel)
assertThat(innerPanel.isAttached()).isTrue()
assertThat(panel.isAttached()).isFalse()
screen.addComponent(panel)
assertThat(panel.isAttached()).isTrue()
assertThat(panel.absolutePosition()).isEqualTo(Positions.create(1, 1))
assertThat(panelHeader.absolutePosition()).isEqualTo(Positions.create(3, 2)) // + 1x1 because of the wrapper
assertThat(innerPanel.absolutePosition()).isEqualTo(Positions.create(3, 4))
assertThat(innerPanelHeader.absolutePosition()).isEqualTo(Positions.create(4, 4))
}
@Test
fun shouldProperlySetUpComponentsWhenAContainerIsAddedThenComponentsAreAddedToIt() {
val grid = TileGridBuilder.newBuilder()
.size(Size.create(40, 25))
.tileset(BuiltInCP437TilesetResource.REX_PAINT_16X16)
.build()
val screen = ScreenBuilder.createScreenFor(grid)
val panel0 = PanelBuilder.newBuilder()
.wrapWithBox()
.title("Panel")
.size(Size.create(32, 16))
.position(Position.offset1x1())
.build()
val panel1 = PanelBuilder.newBuilder()
.wrapWithBox()
.title("Panel2")
.size(Size.create(16, 10))
.position(Positions.create(1, 1))
.build()
val header0 = HeaderBuilder.newBuilder()
.position(Position.create(1, 0))
.text("Header")
.build()
screen.addComponent(panel0)
assertThat(panel0.isAttached()).isTrue()
panel0.addComponent(header0)
assertThat(header0.isAttached()).isTrue()
assertThat(header0.absolutePosition()).isEqualTo(Positions.create(3, 2))
panel0.addComponent(panel1)
assertThat(panel1.isAttached())
assertThat(panel1.absolutePosition()).isEqualTo(Positions.create(3, 3))
}
@Test(expected = IllegalArgumentException::class)
fun shouldThrowExceptionIfComponentWithUnsupportedFontSizeIsAdded() {
AppConfigs.newConfig().disableBetaFeatures().build()
target.addComponent(LabelBuilder.newBuilder()
.text("foo")
.tileset(badTileset)
.build())
}
@Test
fun shouldNotAcceptFocus() {
assertThat(target.acceptsFocus()).isFalse()
}
@Test(expected = IllegalArgumentException::class)
fun shouldNotLetToAddAComponentWhichIntersectsWithAnother() {
AppConfigs.newConfig().disableBetaFeatures().build()
val pos = Position.create(1, 1)
val comp = LabelBuilder.newBuilder().position(pos).text("text").build()
val otherComp = LabelBuilder.newBuilder().position(pos.withRelativeX(1)).text("text").build()
target.addComponent(comp)
target.addComponent(otherComp)
}
@Test
fun shouldNotAcceptGivenFocus() {
assertThat(target.giveFocus()).isFalse()
}
@Test
fun shouldProperlyRemoveComponentFromSelf() {
val comp = LabelBuilder.newBuilder()
.text("xLength")
.position(Position.defaultPosition())
.build()
target.addComponent(comp)
val removalHappened = AtomicBoolean(false)
EventBus.subscribe<ZirconEvent.ComponentRemoval> {
removalHappened.set(true)
}
assertThat(target.removeComponent(comp)).isTrue()
assertThat(removalHappened.get()).isTrue()
}
@Test
fun shouldProperlyRemoveComponentFromChild() {
val comp = LabelBuilder.newBuilder()
.text("xLength")
.position(Position.defaultPosition())
.build()
val panel = PanelBuilder.newBuilder()
.size(SIZE - Size.one())
.position(Position.defaultPosition()).build()
panel.addComponent(comp)
target.addComponent(panel)
val removalHappened = AtomicBoolean(false)
EventBus.subscribe<ZirconEvent.ComponentRemoval> {
removalHappened.set(true)
}
assertThat(target.removeComponent(comp)).isTrue()
assertThat(removalHappened.get()).isTrue()
}
companion object {
val GOOD_TILESET = BuiltInCP437TilesetResource.AESOMATICA_16X16
val BAD_TILESET = BuiltInCP437TilesetResource.BISASAM_20X20
val SIZE = Size.create(4, 4)
val POSITION = Position.create(2, 3)
val NEW_POSITION = Position.create(6, 7)
val DEFAULT_STYLE = StyleSetBuilder.newBuilder()
.backgroundColor(ANSITileColor.BLUE)
.foregroundColor(ANSITileColor.RED)
.build()
val ACTIVE_STYLE = StyleSetBuilder.newBuilder()
.backgroundColor(ANSITileColor.GREEN)
.foregroundColor(ANSITileColor.YELLOW)
.build()
val DISABLED_STYLE = StyleSetBuilder.newBuilder()
.backgroundColor(ANSITileColor.MAGENTA)
.foregroundColor(ANSITileColor.BLUE)
.build()
val FOCUSED_STYLE = StyleSetBuilder.newBuilder()
.backgroundColor(ANSITileColor.YELLOW)
.foregroundColor(ANSITileColor.CYAN)
.build()
val MOUSE_OVER_STYLE = StyleSetBuilder.newBuilder()
.backgroundColor(ANSITileColor.RED)
.foregroundColor(ANSITileColor.CYAN)
.build()
val STYLES = ComponentStyleSetBuilder.newBuilder()
.defaultStyle(DEFAULT_STYLE)
.activeStyle(ACTIVE_STYLE)
.disabledStyle(DISABLED_STYLE)
.focusedStyle(FOCUSED_STYLE)
.mouseOverStyle(MOUSE_OVER_STYLE)
.build()
val WRAPPERS = listOf(
ShadowComponentDecorationRenderer(),
BorderComponentDecorationRenderer(Modifiers.border()))
}
}
| 1
| null |
1
| 1
|
a8320415e949d47f55b316092a29f20469450720
| 9,315
|
zircon
|
MIT License
|
VerifiableCredential/src/main/java/com/merative/watson/healthpass/verifiablecredential/models/jws/JWSHeader.kt
|
digitalhealthpass
| 563,978,682
| false
|
{"Kotlin": 1047923, "HTML": 79495, "Python": 22113, "Java": 1959}
|
package com.merative.watson.healthpass.verifiablecredential.models.jws
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
data class JWSHeader(
@Keep
@SerializedName("alg")
val alg: SignatureAlgorithm,
@Keep
@SerializedName("kid")
val kid: String?,
@Keep
@SerializedName("typ")
val typ: String?,
@Keep
@SerializedName("zip")
val zip: CompressionAlgorithm
)
| 0
|
Kotlin
|
0
| 0
|
2b086f6fad007d1a574f8f0511fff0e65e100930
| 437
|
dhp-android-app
|
Apache License 2.0
|
app/src/main/kotlin/com/rahulografy/axmecomm/ui/main/home/fragment/HomeFragment.kt
|
RahulSDeshpande
| 293,636,598
| false
| null |
package com.rahulografy.axmecomm.ui.main.home.fragment
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.lifecycle.Observer
import com.google.android.material.tabs.TabLayoutMediator
import com.rahulografy.axmecomm.BR
import com.rahulografy.axmecomm.R
import com.rahulografy.axmecomm.databinding.FragmentHomeBinding
import com.rahulografy.axmecomm.ui.base.view.BaseFragment
import com.rahulografy.axmecomm.ui.main.home.fragment.adapter.ProductFragmentAdapter
import com.rahulografy.axmecomm.ui.main.home.productfilter.ProductFilterFragment
import com.rahulografy.axmecomm.util.ext.toast
import kotlinx.android.synthetic.main.fragment_home.*
class HomeFragment : BaseFragment<FragmentHomeBinding, HomeFragmentViewModel>() {
private var productFilterFragment: ProductFilterFragment? = null
override val layoutRes get() = R.layout.fragment_home
override val toolbarId: Int get() = R.id.toolbarHome
override var viewModelClass = HomeFragmentViewModel::class.java
override val bindingVariable = BR.viewModel
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_home, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (viewModel.isDataProcessing.get()) {
toast(getString(R.string.msg_fetching_data_please_wait))
} else {
when (item.itemId) {
R.id.menu_action_search, R.id.menu_action_filter -> openProductFilterFragment()
R.id.menu_action_cart -> toast("WIP")
}
}
return super.onOptionsItemSelected(item)
}
override fun initUi() {
if (isNetworkAvailable()) {
viewModel.getProducts()
}
}
override fun initSharedViewModelObservers() {
viewModel.apply {
productManager
.mapCategoryWiseProductItemListFinal
.observe(
lifecycleOwner = this@HomeFragment,
observer = Observer {
if (it != null) {
initViewPager(categories = it?.keys)
viewModel.isDataProcessing.set(false)
}
}
)
productFilterManager
.productFilterCategoryItemListFinalChangeEvent
.observe(
lifecycleOwner = this@HomeFragment,
observer = Observer {
if (it != null && it) {
productManager.updateProductItemListFinalBasedOnFilter()
}
}
)
}
}
private fun initViewPager(categories: Collection<String>?) {
if (!categories.isNullOrEmpty()) {
val productFragmentAdapter =
ProductFragmentAdapter(
categories = categories.toList(),
childFragmentManager = childFragmentManager,
lifecycle = lifecycle
)
viewPager2Home?.apply {
adapter = productFragmentAdapter
offscreenPageLimit = categories.size
}
TabLayoutMediator(
tabLayoutHome,
viewPager2Home
) { tab, position ->
tab.text = categories.toList()[position]
}.attach()
} else {
toast("API error occurred while fetching products.")
}
}
private fun openProductFilterFragment() {
if (productFilterFragment == null) {
productFilterFragment = ProductFilterFragment()
}
if (productFilterFragment?.isVisible != true) {
productFilterFragment?.show(childFragmentManager, productFilterFragment?.tag)
}
}
}
| 0
|
Kotlin
|
0
| 2
|
bc7c1bb7aabae352bbe567a415b4b6bec1642a28
| 3,955
|
dctk-axm-ecomm-android
|
MIT License
|
labencryptedstorage/src/main/java/mobi/lab/labencryptedstorage/internal/Util.kt
|
LabMobi
| 578,563,766
| false
| null |
package mobi.lab.labencryptedstorage.internal
/**
* when statement only creates a compiler error for sealed classes when used as an expression.
* Use this .exhaustive extensions in other cases to get the compiler error when not all available options are defined.
*
* sealed class A
*
* class B : A()
* class C : A()
*
* // Compiler error
* val y = when(x) {
* is B ->
* }
*
* // No compiler error
* when(x) {
* is B ->
* }
*
* // Compiler error
* when(x) {
* is B ->
* }.exhaustive
*/
internal val <T> T.exhaustive: T
get() = this
| 2
|
Kotlin
|
0
| 1
|
deb2b68b08bbf6eaa994f2e3696f94a0b543c05f
| 565
|
LabEncryptedStorage
|
MIT License
|
sample/src/main/kotlin/com/example/kotlin/InvertIfCondition.kt
|
hendraanggrian
| 556,969,715
| false
|
{"Kotlin": 94835, "Java": 2866, "Groovy": 310}
|
package com.example.kotlin
fun alert(message: String) {
if (message.isEmpty()) {
return
}
val s = message.trim()
println(s)
}
fun alert2(message: String) {
if (message.isNotEmpty()) {
var a = 1 + 2
a += 0
} else if (message.isNotBlank()) {
var b = 3 + 4
b += 0
} else {
var c = 5 + 6
c += 0
}
}
| 0
|
Kotlin
|
0
| 1
|
3e4a3f4458dbf7ba3f0805b6aecdd514a580111c
| 385
|
rulebook
|
Apache License 2.0
|
core/domain/src/main/java/com/mayuresh/domain/util/IntUtils.kt
|
mayureshps21
| 700,256,778
| false
|
{"Kotlin": 215180}
|
package com.mayuresh.domain.util
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
fun Int.toReadable(): String = DecimalFormat("###,###,###.##").apply {
decimalFormatSymbols = DecimalFormatSymbols().apply {
groupingSeparator = ' '
}
}.format(this)
| 0
|
Kotlin
|
0
| 0
|
a761c0cab72ef1bf741fa537440563059f168f7c
| 286
|
EuropeanCountriesSample
|
Apache License 2.0
|
app/src/main/kotlin/dev/patrickgold/florisboard/app/settings/theme/ThemeScreen.kt
|
florisboard
| 254,202,848
| false
| null |
/*
* Copyright (C) 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 dev.patrickgold.florisboard.app.settings.theme
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.BrightnessAuto
import androidx.compose.material.icons.filled.DarkMode
import androidx.compose.material.icons.filled.FormatPaint
import androidx.compose.material.icons.filled.LightMode
import androidx.compose.material.icons.outlined.Palette
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import dev.patrickgold.florisboard.R
import dev.patrickgold.florisboard.app.LocalNavController
import dev.patrickgold.florisboard.app.Routes
import dev.patrickgold.florisboard.ime.theme.ThemeMode
import dev.patrickgold.florisboard.lib.android.launchUrl
import dev.patrickgold.florisboard.lib.compose.FlorisInfoCard
import dev.patrickgold.florisboard.lib.compose.FlorisScreen
import dev.patrickgold.florisboard.lib.compose.stringRes
import dev.patrickgold.jetpref.datastore.model.observeAsState
import dev.patrickgold.jetpref.datastore.ui.ListPreference
import dev.patrickgold.jetpref.datastore.ui.Preference
import dev.patrickgold.jetpref.datastore.ui.PreferenceGroup
import dev.patrickgold.jetpref.datastore.ui.SwitchPreference
@Composable
fun ThemeScreen() = FlorisScreen {
title = stringRes(R.string.settings__theme__title)
previewFieldVisible = true
val context = LocalContext.current
val navController = LocalNavController.current
content {
val themeMode by prefs.theme.mode.observeAsState()
val dayThemeId by prefs.theme.dayThemeId.observeAsState()
val nightThemeId by prefs.theme.nightThemeId.observeAsState()
Card(modifier = Modifier.padding(8.dp)) {
Column(modifier = Modifier.padding(8.dp)) {
Text("If you want to give feedback on the new stylesheet editor and theme engine, please do so in below linked feedback thread:\n")
Button(onClick = {
context.launchUrl("https://github.com/florisboard/florisboard/discussions/1531")
}) {
Text("Open Feedback Thread")
}
}
}
ListPreference(
prefs.theme.mode,
icon = Icons.Default.BrightnessAuto,
title = stringRes(R.string.pref__theme__mode__label),
entries = ThemeMode.listEntries(),
)
if (themeMode == ThemeMode.FOLLOW_TIME) {
FlorisInfoCard(
modifier = Modifier.padding(8.dp),
text = """
The theme mode "Follow time" is not available in this beta release.
""".trimIndent()
)
}
Preference(
icon = Icons.Outlined.Palette,
title = stringRes(R.string.settings__theme_manager__title_manage),
onClick = {
navController.navigate(Routes.Settings.ThemeManager(ThemeManagerScreenAction.MANAGE))
},
)
PreferenceGroup(
title = stringRes(R.string.pref__theme__day),
enabledIf = { prefs.theme.mode isNotEqualTo ThemeMode.ALWAYS_NIGHT },
) {
Preference(
icon = Icons.Default.LightMode,
title = stringRes(R.string.pref__theme__any_theme__label),
summary = dayThemeId.toString(),
onClick = {
navController.navigate(Routes.Settings.ThemeManager(ThemeManagerScreenAction.SELECT_DAY))
},
)
SwitchPreference(
prefs.theme.dayThemeAdaptToApp,
icon = Icons.Default.FormatPaint,
title = stringRes(R.string.pref__theme__any_theme_adapt_to_app__label),
summary = stringRes(R.string.pref__theme__any_theme_adapt_to_app__summary),
visibleIf = { false },
)
}
PreferenceGroup(
title = stringRes(R.string.pref__theme__night),
enabledIf = { prefs.theme.mode isNotEqualTo ThemeMode.ALWAYS_DAY },
) {
Preference(
icon = Icons.Default.DarkMode,
title = stringRes(R.string.pref__theme__any_theme__label),
summary = nightThemeId.toString(),
onClick = {
navController.navigate(Routes.Settings.ThemeManager(ThemeManagerScreenAction.SELECT_NIGHT))
},
)
SwitchPreference(
prefs.theme.nightThemeAdaptToApp,
icon = Icons.Default.FormatPaint,
title = stringRes(R.string.pref__theme__any_theme_adapt_to_app__label),
summary = stringRes(R.string.pref__theme__any_theme_adapt_to_app__summary),
visibleIf = { false },
)
}
}
}
| 526
| null |
377
| 5,573
|
eb50498890796489e8b318ddaa7103f04d8cf766
| 5,725
|
florisboard
|
Apache License 2.0
|
src/main/kotlin/com/jsoizo/phpserialize/Unserializer.kt
|
jsoizo
| 678,068,537
| false
|
{"Kotlin": 20830}
|
package com.jsoizo.phpserialize
import com.jsoizo.phpserialize.error.PhpUnserializeException
import com.jsoizo.phpserialize.error.UncaughtUnserializeException
import com.jsoizo.phpserialize.error.UnexpectedValueException
import com.jsoizo.phpserialize.error.UnknownTypeException
import java.nio.charset.Charset
class Unserializer(private val stringCharset: Charset = Charsets.UTF_8) {
fun unserialize(input: String): PValue {
val iterator = input.iterator()
try {
return parseValue(iterator)
} catch (e: Exception) {
when (e) {
is PhpUnserializeException -> throw e
else -> throw UncaughtUnserializeException(e)
}
}
}
private fun parseValue(iterator: CharIterator): PValue {
val type = iterator.next()
if (type == 'N') return parseNull(iterator)
iterator.next() // skip colon
return when (type) {
's' -> parseString(iterator)
'i' -> parseInt(iterator)
'd' -> parseDouble(iterator)
'b' -> parseBoolean(iterator)
'a' -> parseArray(iterator)
'O' -> parseObject(iterator)
else -> throw UnknownTypeException(type)
}
}
private fun parseString(iterator: CharIterator): PString {
val lengthInBytes = iterator.readUntil(':').toInt()
iterator.next() // Skip opening quote
val value = iterator.readNByte(lengthInBytes, stringCharset)
iterator.next() // Skip closing quote
iterator.next() // Skip semicolon
return PString(value)
}
private fun parseInt(iterator: CharIterator): PInt {
val value = iterator.readUntil(';').toLong()
return PInt(value)
}
private fun parseDouble(iterator: CharIterator): PDouble {
val value = when (val parsed = iterator.readUntil(';')) {
"INF" -> Double.POSITIVE_INFINITY
"-INF" -> Double.NEGATIVE_INFINITY
"NAN" -> Double.NaN
else -> parsed.toDouble()
}
return PDouble(value)
}
private fun parseBoolean(iterator: CharIterator): PBoolean {
val value = iterator.readUntil(';').firstOrNull()
return PBoolean(value == '1')
}
private fun parseArray(iterator: CharIterator): PArray {
val arraySize = iterator.readUntil(':').toInt()
iterator.next() // skip opening brace
val value: PArray = (0 until arraySize).fold(emptyPArray()) { acc, _ ->
val key: PArrayKey = when (val parsed = parseValue(iterator)) {
is PArrayKey -> parsed
else -> throw UnexpectedValueException("Invalid Array Key.", parsed)
}
val value = parseValue(iterator)
acc + (key to value)
}
iterator.next() // skip closing brace
return value
}
private fun parseObject(iterator: CharIterator): PObject {
val name = parseString(iterator).value
val fieldsSize = iterator.readUntil(':').toInt()
iterator.next() // skip opening brace
val value: Map<String, PValue> = (0 until fieldsSize).fold(emptyMap()) { acc, _ ->
val fieldName = when (val parsed = parseValue(iterator)) {
is PString -> parsed.value
else -> throw UnexpectedValueException("Invalid Object field.", parsed)
}
val value = parseValue(iterator)
acc.plus((fieldName to value))
}
iterator.next() // skip closing brace
return PObject(name, value)
}
private fun parseNull(iterator: CharIterator): PNull {
iterator.next() // skip semicolon
return PNull
}
private fun CharIterator.readUntil(char: Char): String {
val sb = StringBuilder()
while (hasNext()) {
val c = next()
if (c == char) break
sb.append(c)
}
return sb.toString()
}
private fun CharIterator.readNByte(n: Int, charset: Charset): String {
tailrec fun _readNByte(count: Int, acc: String): String =
if (count > 0) {
val char = next()
val cur = if (Character.isHighSurrogate(char) && hasNext()) {
char.toString() + next().toString()
} else {
char.toString()
}
val byteCount = cur.toByteArray(charset).size
_readNByte(count - byteCount, acc + cur)
} else acc
return _readNByte(n, "")
}
}
| 0
|
Kotlin
|
0
| 1
|
becbd7ab2ccf6608875541c1033195922c0107c3
| 4,580
|
php-serialize-kt
|
MIT License
|
db-room/src/main/java/com/pyamsoft/tickertape/db/room/converter/PriceAlertIdConverter.kt
|
pyamsoft
| 371,196,339
| false
| null |
/*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.pyamsoft.tickertape.db.room.converter
import androidx.annotation.CheckResult
import androidx.room.TypeConverter
import com.pyamsoft.tickertape.db.symbol.DbSymbol
internal object DbSymbolIdConverter {
@JvmStatic
@TypeConverter
@CheckResult
fun toId(id: String): DbSymbol.Id {
return DbSymbol.Id(id)
}
@JvmStatic
@TypeConverter
@CheckResult
fun fromId(id: DbSymbol.Id): String {
return id.id
}
}
| 5
|
Kotlin
|
0
| 6
|
c5309984f17de290ce2fb82120b4699cc8227b65
| 1,029
|
tickertape
|
Apache License 2.0
|
app/src/main/java/samman/schoter/newsapp/ui/fragments/BreakingNewsFragment.kt
|
Sam7Man
| 510,080,445
| false
|
{"Kotlin": 27040}
|
package samman.schoter.newsapp.ui.fragments
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AbsListView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.fragment_breaking_news.*
import samman.schoter.newsapp.R
import samman.schoter.newsapp.helpers.NewsAdapter
import samman.schoter.newsapp.ui.NewsActivity
import samman.schoter.newsapp.ui.NewsViewModel
import samman.schoter.newsapp.utils.Constants.Companion.QUERY_PAGE_SIZE
import samman.schoter.newsapp.utils.Resource
class BreakingNewsFragment : Fragment(R.layout.fragment_breaking_news) {
lateinit var viewModel: NewsViewModel
lateinit var newsAdapter: NewsAdapter
val TAG = "BreakingNewsFragment"
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = (activity as NewsActivity).viewModel
setupRecyclerView()
// navigate to the clicked article
newsAdapter.setOnItemClickListener {
val bundle = Bundle().apply {
putSerializable("article", it)
}
findNavController().navigate(
R.id.action_breakingNewsFragment_to_articleFragment,
bundle
)
}
viewModel.breakingNews.observe(viewLifecycleOwner, Observer { response ->
when (response) {
is Resource.Success -> {
hideProgressBar()
response.data?.let { newsResponse ->
newsAdapter.differ.submitList(newsResponse.articles.toList())
val totalPages = newsResponse.totalResults / QUERY_PAGE_SIZE + 2
isLastPage = viewModel.breakingNewsPage == totalPages
if (isLastPage) {
rvBreakingNews.setPadding(0, 0, 0, 0)
}
}
}
is Resource.Error -> {
hideProgressBar()
response.message?.let { message ->
Log.e(TAG, "An error accrued: $message")
}
}
is Resource.Loading -> {
showProgressBar()
}
}
})
}
private fun hideProgressBar() {
paginationProgressBar.visibility = View.INVISIBLE
isLoading = false
}
private fun showProgressBar() {
paginationProgressBar.visibility = View.VISIBLE
isLoading = true
}
var isLoading = false
var isLastPage = false
var isScrolling = false
var scrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
val visibleItemCount = layoutManager.childCount
val totalItemCount = layoutManager.itemCount
val isNotLoadingAndNotLastPage = !isLoading && !isLastPage
val isAtLastItem = firstVisibleItemPosition + visibleItemCount >= totalItemCount
val isNotAtBeginning = firstVisibleItemPosition >= 0
val isTotalMoreThanVisible = totalItemCount >= QUERY_PAGE_SIZE
val shouldPaginate =
isNotLoadingAndNotLastPage && isAtLastItem && isNotAtBeginning && isTotalMoreThanVisible && isScrolling
if (shouldPaginate) {
viewModel.getBreakingNews("us")
isScrolling = false
}
}
}
private fun setupRecyclerView() {
newsAdapter = NewsAdapter()
rvBreakingNews.apply {
adapter = newsAdapter
layoutManager = LinearLayoutManager(activity)
addOnScrollListener(this@BreakingNewsFragment.scrollListener)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f0f9a9e0402f6928554fb1001927f3b2f9333e0f
| 4,558
|
NewsApp
|
MIT License
|
app/src/main/java/dev/vitorramos/livequestions/viewmodel/MainViewModel.kt
|
vitor-ramos
| 299,131,104
| false
| null |
package dev.vitorramos.livequestions.viewmodel
import androidx.lifecycle.*
import dev.vitorramos.livequestions.composables.SheetContentEvents
import dev.vitorramos.livequestions.composables.SitesListContentEvents
import dev.vitorramos.livequestions.model.*
import dev.vitorramos.livequestions.moveToFirst
import kotlinx.coroutines.launch
import org.koin.java.KoinJavaComponent.inject
class MainViewModel : ViewModel(), SitesListContentEvents, SheetContentEvents {
private val repository by inject(Repository::class.java)
private val questionsImpl = MediatorLiveData<List<Question>>()
private val sitesImpl = MediatorLiveData<List<SiteData>>()
private val tagsImpl = MediatorLiveData<List<String>>()
private val siteImpl = MutableLiveData<Site>()
private val tagImpl = MutableLiveData(repository.getSelectedTag())
private val sitesSearchImpl = MutableLiveData("")
private val tagsSearchImpl = MutableLiveData("")
private val loadingImpl = MutableLiveData<Boolean>()
val questions: LiveData<List<Question>> = questionsImpl
val sites: LiveData<List<SiteData>> = sitesImpl
val tags: LiveData<List<String>> = tagsImpl
val site: LiveData<Site> = siteImpl
val tag: LiveData<String> = tagImpl
val sitesSearch: LiveData<String> = sitesSearchImpl
val tagsSearch: LiveData<String> = tagsSearchImpl
val loading: LiveData<Boolean> = loadingImpl
// cache controllers - start
private var loadedQuestionsFromSite: String? = null
private var loadedQuestionsWithTag: String? = null
private var loadedTagsFromSite: String? = null
private var loadedTagsFilteredBy: String? = null
private var sitesFilteredBySearch: String? = null
// cache controllers - end
private var allSites = listOf<SiteData>()
private var pageLoaded = 1
init {
questionsImpl.addSource(site) { site ->
if (site is SiteData && site.apiSiteParameter != loadedQuestionsFromSite) {
viewModelScope.launch {
pageLoaded = 1
val list = repository.getQuestions(site.apiSiteParameter, tag.value, 1)
loadedQuestionsFromSite = site.apiSiteParameter
loadedQuestionsWithTag = tag.value
questionsImpl.postValue(list)
}
}
}
questionsImpl.addSource(tag) { tag ->
if (tag != loadedQuestionsWithTag) {
viewModelScope.launch {
pageLoaded = 1
(site.value as? SiteData)?.let {
val list = repository.getQuestions(it.apiSiteParameter, tag, 1)
loadedQuestionsFromSite = it.apiSiteParameter
loadedQuestionsWithTag = tag
questionsImpl.postValue(list)
}
}
}
}
tagsImpl.addSource(site) {
(it as? SiteData)?.apiSiteParameter?.let { siteId ->
if (loadedTagsFromSite != siteId) {
viewModelScope.launch {
pageLoaded = 1
tagsImpl.postValue(repository.getTags(siteId, tagsSearch.value, 1))
loadedTagsFromSite = siteId
loadedTagsFilteredBy = tagsSearch.value
}
}
}
}
sitesImpl.addSource(sitesSearch) { search ->
if (sitesFilteredBySearch != search) {
sitesFilteredBySearch = search
val filtered = allSites.filter { it.name.contains(search, true) }
val movedSelectedToFirst = (site.value as? SiteData)?.let { siteData ->
filtered.moveToFirst { it.apiSiteParameter == siteData.apiSiteParameter }
} ?: filtered
sitesImpl.postValue(movedSelectedToFirst)
}
}
viewModelScope.launch {
repository.getSelectedSiteId().let { siteId ->
if (siteId.isBlank()) siteImpl.postValue(SiteNotSelected())
else siteImpl.postValue(repository.getSite(siteId))
}
}
viewModelScope.launch {
allSites = repository.getSites()
val movedSelectedToFirst = (site.value as? SiteData)?.let { siteData ->
allSites.moveToFirst { it.apiSiteParameter == siteData.apiSiteParameter }
} ?: allSites
sitesImpl.postValue(movedSelectedToFirst)
}
}
override fun onSelectTag(tag: String) {
tagImpl.postValue(tag)
viewModelScope.launch { repository.selectTag(tag) }
}
override fun onChangeTagSearch(value: String) = tagsSearchImpl.postValue(value)
override fun onChangeSitesSearch(value: String) = sitesSearchImpl.postValue(value)
override fun onSelectSite(site: SiteData) {
viewModelScope.launch {
repository.selectSite(site.apiSiteParameter)
tagImpl.postValue("")
siteImpl.postValue(site)
}
}
fun onLoadNextPage() {
val site = site.value
if (site is SiteData) {
loadingImpl.postValue(true)
viewModelScope.launch {
pageLoaded++
questionsImpl.postValue(mutableListOf<Question>().apply {
questions.value?.let { addAll(it) }
addAll(repository.getQuestions(site.apiSiteParameter, tag.value, pageLoaded))
})
loadingImpl.postValue(false)
}
}
}
override fun onClickTagSearch() {
(site.value as? SiteData)?.apiSiteParameter?.let { siteId ->
if (loadedTagsFilteredBy != tagsSearch.value) {
viewModelScope.launch {
tagsImpl.postValue(repository.getTags(siteId, tagsSearch.value, 1))
loadedTagsFromSite = siteId
loadedTagsFilteredBy = tagsSearch.value
}
}
}
}
}
| 6
|
Kotlin
|
0
| 2
|
ba11ad85364bfa945067cf9bac74fb3c797b7a47
| 6,057
|
LiveQuestions
|
MIT License
|
library/modules/ui/src/commonMain/kotlin/com/michaelflisar/toolbox/composables/MyCheckbox.kt
|
MFlisar
| 711,136,467
| false
|
{"Kotlin": 239926}
|
package com.michaelflisar.toolbox.composables
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckBox
import androidx.compose.material.icons.filled.CheckBoxOutlineBlank
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import com.michaelflisar.toolbox.ToolboxDefaults
import com.michaelflisar.toolbox.disabled
@Composable
fun MyCheckbox(
modifier: Modifier = Modifier,
title: String,
checked: MutableState<Boolean>,
color: Color = Color.Unspecified,
colorUnselected: Color = Color.Unspecified,
fontWeight: FontWeight = FontWeight.Normal,
onCheckedChange: (Boolean) -> Unit = {}
) {
MyCheckbox(modifier, title, checked.value, color, colorUnselected, fontWeight) {
checked.value = it
onCheckedChange(it)
}
}
@Composable
fun MyCheckbox(
modifier: Modifier = Modifier,
title: String,
checked: Boolean,
color: Color = Color.Unspecified,
colorUnselected: Color = Color.Unspecified,
fontWeight: FontWeight = FontWeight.Normal,
onCheckedChange: ((Boolean) -> Unit)? = null
) {
Row(
modifier = modifier
.clip(MaterialTheme.shapes.medium)
.then(if (onCheckedChange != null) {
Modifier.clickable { onCheckedChange.invoke(!checked) }
} else Modifier)
.padding(ToolboxDefaults.ITEM_SPACING)
.width(IntrinsicSize.Max),
horizontalArrangement = Arrangement.spacedBy(ToolboxDefaults.ITEM_SPACING),
verticalAlignment = Alignment.CenterVertically
) {
if (title.isNotEmpty()) {
Text(
modifier = Modifier.wrapContentWidth(),
text = title,
fontWeight = fontWeight,
maxLines = 1
)
}
Spacer(Modifier.weight(1f))
Icon(
imageVector = if (checked) Icons.Default.CheckBox else Icons.Default.CheckBoxOutlineBlank,
contentDescription = null,
tint = if (checked) {
(color.takeIf { it != Color.Unspecified } ?: MaterialTheme.colorScheme.primary)
} else {
colorUnselected.takeIf { it != Color.Unspecified }
?: MaterialTheme.colorScheme.onSurface.disabled()
}
)
}
}
| 0
|
Kotlin
|
0
| 0
|
d2ee7999a356902f04cd460101fdad397cce91f2
| 3,081
|
Toolbox
|
Apache License 2.0
|
skrapers/src/main/kotlin/ru/sokomishalov/skraper/Skrapers.kt
|
sokomishalov
| 234,099,582
| false
| null |
/*
* Copyright (c) 2019-present <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("Skrapers")
@file:Suppress("unused", "MemberVisibilityCanBePrivate")
package ru.sokomishalov.skraper
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import ru.sokomishalov.skraper.client.HttpRequest
import ru.sokomishalov.skraper.client.SkraperClient
import ru.sokomishalov.skraper.client.jdk.DefaultBlockingSkraperClient
import ru.sokomishalov.skraper.client.ktor.KtorSkraperClient
import ru.sokomishalov.skraper.client.okhttp.OkHttpSkraperClient
import ru.sokomishalov.skraper.client.spring.SpringReactiveSkraperClient
import ru.sokomishalov.skraper.internal.ffmpeg.FfmpegCliRunner
import ru.sokomishalov.skraper.internal.ffmpeg.FfmpegRunner
import ru.sokomishalov.skraper.internal.net.path
import ru.sokomishalov.skraper.model.*
import ru.sokomishalov.skraper.provider.coub.CoubSkraper
import ru.sokomishalov.skraper.provider.facebook.FacebookSkraper
import ru.sokomishalov.skraper.provider.flickr.FlickrSkraper
import ru.sokomishalov.skraper.provider.ifunny.IFunnySkraper
import ru.sokomishalov.skraper.provider.instagram.InstagramSkraper
import ru.sokomishalov.skraper.provider.ninegag.NinegagSkraper
import ru.sokomishalov.skraper.provider.odnoklassniki.OdnoklassnikiSkraper
import ru.sokomishalov.skraper.provider.pikabu.PikabuSkraper
import ru.sokomishalov.skraper.provider.pinterest.PinterestSkraper
import ru.sokomishalov.skraper.provider.reddit.RedditSkraper
import ru.sokomishalov.skraper.provider.telegram.TelegramSkraper
import ru.sokomishalov.skraper.provider.tiktok.TikTokSkraper
import ru.sokomishalov.skraper.provider.tumblr.TumblrSkraper
import ru.sokomishalov.skraper.provider.twitch.TwitchSkraper
import ru.sokomishalov.skraper.provider.twitter.TwitterSkraper
import ru.sokomishalov.skraper.provider.vimeo.VimeoSkraper
import ru.sokomishalov.skraper.provider.vk.VkSkraper
import ru.sokomishalov.skraper.provider.youtube.YoutubeSkraper
import java.io.File
import java.util.*
object Skrapers {
var client: SkraperClient = initClient()
var providers: List<Skraper> = initSkrapers()
var ffmpegRunner: FfmpegRunner = initFfmpegRunner()
/**
* @return list of all available skrapers
*/
fun available(): List<Skraper> {
return providers
}
/**
* @param url posts/page/media url
* @return skraper which supports this url or null if none of skrapers supports it
*/
fun findSuitable(url: String): Skraper? {
return providers.find { it.supports(url) }
}
/**
* @param url posts url
* @return flow of posts
*/
fun getPosts(url: String): Flow<Post> {
return findSuitable(url)?.getPosts(url.path) ?: emptyFlow()
}
/**
* @param url page url
* @return page info
*/
suspend fun getPageInfo(url: String): PageInfo? {
return findSuitable(url)?.getPageInfo(url.path)
}
/**
* Convert provider relative media to downloadable media
* @param media item to resolve
* @return media with direct link
*/
suspend fun resolve(media: Media): Media {
return when {
// direct media url
media.url
.path
.substringAfterLast("/")
.substringAfterLast(".", "")
.isNotEmpty() -> media
// otherwise
else -> {
findSuitable(media.url)
?.resolve(media)
?.run {
when {
url != media.url -> resolve(media = this)
else -> when (media) {
is Image -> media.copy(url = url)
is Video -> media.copy(url = url)
is Audio -> media.copy(url = url)
is UnknownMedia -> media.copy(url = url)
}
}
}
?: media
}
}
}
/**
* Downloads media
* @param media item to download
* @param destDir destination directory for media
* @param filename custom destination file name without extension
*/
suspend fun download(
media: Media,
destDir: File,
filename: String = media.extractFileNameWithoutExtension()
): File {
val resolved = resolve(media)
val extension = resolved.extractFileExtension()
destDir.mkdirs()
val destFile = File("${destDir.absolutePath}${File.separator}${filename}.${extension}")
return when (extension) {
// m3u8 download and convert to mp4 with ffmpeg
"m3u8" -> {
val destFileMp4Path = destFile.absolutePath.replace("m3u8", "mp4")
val cmd = "-i ${resolved.url} -c copy -bsf:a aac_adtstoasc $destFileMp4Path"
ffmpegRunner.run(cmd)
File(destFileMp4Path)
}
// webm download and convert to mp4 with ffmpeg
"webm" -> {
val destFileMp4Path = destFile.absolutePath.replace("webm", "mp4")
val cmd = "-i ${resolved.url} -strict experimental $destFileMp4Path"
ffmpegRunner.run(cmd)
File(destFileMp4Path)
}
// otherwise try to download as is
else -> {
client.download(HttpRequest(url = resolved.url), destFile = destFile)
destFile
}
}
}
private fun Media.extractFileExtension(): String {
val filename = url.path
return when (this) {
is Image -> filename.substringAfterLast(".", "png")
is Video -> filename.substringAfterLast(".", "mp4")
is Audio -> filename.substringAfterLast(".", "mp3")
is UnknownMedia -> filename.substringAfterLast(".")
}
}
private fun Media.extractFileNameWithoutExtension(): String {
return url
.path
.substringAfterLast("/")
.substringBeforeLast(".")
}
private fun initSkrapers(): List<Skraper> {
val spiSkrapers = spi<Skraper>()
val knownSkrapers = listOf(
FacebookSkraper(client),
InstagramSkraper(client),
TwitterSkraper(client),
YoutubeSkraper(client),
TikTokSkraper(client),
TelegramSkraper(client),
TwitchSkraper(client),
RedditSkraper(client),
NinegagSkraper(client),
PinterestSkraper(client),
FlickrSkraper(client),
TumblrSkraper(client),
IFunnySkraper(client),
VkSkraper(client),
PikabuSkraper(client),
VimeoSkraper(client),
OdnoklassnikiSkraper(client),
CoubSkraper(client),
)
return spiSkrapers + knownSkrapers
}
private fun initClient(): SkraperClient {
val spiClient = spi<SkraperClient>().firstOrNull()
return when {
spiClient != null -> spiClient
classPathCheck("io.ktor.client.HttpClient") -> KtorSkraperClient()
classPathCheck("okhttp3.OkHttpClient") -> OkHttpSkraperClient()
classPathCheck("org.springframework.web.reactive.function.client.WebClient", "kotlinx.coroutines.reactor.ReactorContext") -> SpringReactiveSkraperClient()
else -> DefaultBlockingSkraperClient
}
}
private fun initFfmpegRunner(): FfmpegRunner {
val spiFfmpegRunner = spi<FfmpegRunner>().firstOrNull()
return spiFfmpegRunner ?: FfmpegCliRunner()
}
private inline fun <reified T> spi(): List<T> = ServiceLoader.load(T::class.java)?.toList().orEmpty()
private fun classPathCheck(vararg classes: String): Boolean = runCatching { classes.forEach { Class.forName(it) } }.isSuccess
}
| 9
| null |
42
| 252
|
05d318581f513dc7ed7d19eb1b0422ad992a1c9c
| 8,493
|
skraper
|
Apache License 2.0
|
Movies/app/src/main/java/com/daresay/movies/ui/adapters/MovieTopRatedAdapter.kt
|
Ezzpify
| 346,202,639
| false
| null |
package com.daresay.movies.ui.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.daresay.movies.data.models.movie.Movie
import com.daresay.movies.databinding.AdapterMovieTopRatedItemBinding
import com.daresay.movies.ui.callbacks.MovieOnClickListener
import com.daresay.movies.utils.getGenreList
import com.daresay.movies.utils.getMoviePosterUrl
class MovieTopRatedAdapter(private val onMovieOnClickListener: MovieOnClickListener) : RecyclerView.Adapter<MovieTopRatedAdapter.MovieHolder>() {
private var items: ArrayList<Movie> = arrayListOf()
fun addItems(movies: ArrayList<Movie>) {
val insertPosition = items.size
this.items.addAll(movies)
notifyItemRangeInserted(insertPosition, movies.size)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieTopRatedAdapter.MovieHolder {
val binding = AdapterMovieTopRatedItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MovieHolder(binding)
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: MovieHolder, position: Int) = holder.bind(items[position])
inner class MovieHolder(private val binding: AdapterMovieTopRatedItemBinding) : RecyclerView.ViewHolder(binding.root) {
private lateinit var movie: Movie
fun bind(movie: Movie) {
this.movie = movie
binding.movie = movie
binding.movieTags.text = getGenreList(movie.genre_ids).joinToString()
Glide.with(binding.root)
.load(getMoviePosterUrl(movie.poster_path))
.transform(CenterCrop(), RoundedCorners(25))
.into(binding.movieImage)
binding.root.setOnClickListener {
onMovieOnClickListener.onMovieClicked(movie.id)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9b667638bdf81db4cb4e81d9de3bd561e4d36b30
| 2,187
|
DaresayMovies
|
MIT License
|
library/src/main/java/com/merveylcu/calendarview/model/CalendarDay.kt
|
merveylcu
| 379,375,681
| false
| null |
package com.merveylcu.calendarview.model
import com.merveylcu.calendarview.utils.next
import com.merveylcu.calendarview.utils.previous
import com.merveylcu.calendarview.utils.yearMonth
import java.io.Serializable
import java.time.LocalDate
import java.time.YearMonth
data class CalendarDay internal constructor(val date: LocalDate, val owner: DayOwner) :
Comparable<CalendarDay>, Serializable {
val day = date.dayOfMonth
internal val positionYearMonth: YearMonth
get() = when (owner) {
DayOwner.THIS_MONTH -> date.yearMonth
DayOwner.PREVIOUS_MONTH -> date.yearMonth.next
DayOwner.NEXT_MONTH -> date.yearMonth.previous
}
override fun toString(): String {
return "CalendarDay { date = $date, owner = $owner}"
}
override fun compareTo(other: CalendarDay): Int {
throw UnsupportedOperationException(
"Compare using the `date` parameter instead. " +
"Out and In dates can have the same date values as CalendarDay in another month."
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CalendarDay
return date == other.date && owner == other.owner
}
override fun hashCode(): Int {
return 31 * (date.hashCode() + owner.hashCode())
}
}
| 0
|
Kotlin
|
0
| 0
|
d944fc528ec00614eccd6c15ce415e48330f0d2c
| 1,414
|
CalenderView
|
MIT License
|
plugins/src/main/kotlin/com/github/hotchemi/ExampleExpressionCodegenExtension.kt
|
hotchemi
| 89,169,236
| false
| null |
package com.github.hotchemi
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
class ExampleCodegenExtension : ExpressionCodegenExtension {
override fun applyFunction(receiver: StackValue, resolvedCall: ResolvedCall<*>, c: ExpressionCodegenExtension.Context): StackValue? {
println("applyFunction")
val calleeExpression = resolvedCall.call.calleeExpression
val visitor = ExampleVisitor()
calleeExpression?.acceptChildren(visitor)
return null
}
override fun applyProperty(receiver: StackValue, resolvedCall: ResolvedCall<*>, c: ExpressionCodegenExtension.Context): StackValue? {
println("applyProperty")
return null
}
override fun generateClassSyntheticParts(classBuilder: ClassBuilder, state: GenerationState, classOrObject: KtClassOrObject, descriptor: ClassDescriptor) {
super.generateClassSyntheticParts(classBuilder, state, classOrObject, descriptor)
println("generateClassSyntheticParts")
}
}
| 0
|
Kotlin
|
0
| 14
|
f418b0e10ef0eec5fab73d037467cb7025aae079
| 1,282
|
kotlin-compiler-plugin-example
|
Apache License 2.0
|
imx-core-sdk-kotlin-jvm/generated/src/main/kotlin/com/immutable/sdk/api/model/CreateTradeRequestV1.kt
|
immutable
| 467,767,205
| false
|
{"Kotlin": 668106, "Java": 131024, "Mustache": 29745, "Solidity": 10068}
|
/**
* Immutable X API
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 0.1
* Contact: <EMAIL>
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package com.immutable.sdk.api.model
import com.immutable.sdk.api.model.FeeEntry
import com.squareup.moshi.Json
/**
*
*
* @param amountBuy Amount to buy
* @param amountSell Amount to sell
* @param assetIdBuy ID of the asset to buy
* @param assetIdSell ID of the asset to sell
* @param expirationTimestamp Expiration timestamp for this order
* @param nonce Nonce of the order
* @param starkKey Public stark key of the user creating order
* @param starkSignature Payload signature
* @param vaultIdBuy ID of the vault into which the bought asset will be placed
* @param vaultIdSell ID of the vault to sell from
* @param fees Fee information
* @param includeFees Whether to include fees in order
*/
data class CreateOrderRequest (
/* Amount to buy */
@Json(name = "amount_buy")
val amountBuy: kotlin.String,
/* Amount to sell */
@Json(name = "amount_sell")
val amountSell: kotlin.String,
/* ID of the asset to buy */
@Json(name = "asset_id_buy")
val assetIdBuy: kotlin.String,
/* ID of the asset to sell */
@Json(name = "asset_id_sell")
val assetIdSell: kotlin.String,
/* Expiration timestamp for this order */
@Json(name = "expiration_timestamp")
val expirationTimestamp: kotlin.Int,
/* Nonce of the order */
@Json(name = "nonce")
val nonce: kotlin.Int,
/* Public stark key of the user creating order */
@Json(name = "stark_key")
val starkKey: kotlin.String,
/* Payload signature */
@Json(name = "stark_signature")
val starkSignature: kotlin.String,
/* ID of the vault into which the bought asset will be placed */
@Json(name = "vault_id_buy")
val vaultIdBuy: kotlin.Int,
/* ID of the vault to sell from */
@Json(name = "vault_id_sell")
val vaultIdSell: kotlin.Int,
/* Fee information */
@Json(name = "fees")
val fees: kotlin.collections.List<FeeEntry>? = null,
/* Whether to include fees in order */
@Json(name = "include_fees")
val includeFees: kotlin.Boolean? = null
)
| 2
|
Kotlin
|
2
| 5
|
4a823d30db92356c325140874f5ba708547585ca
| 2,514
|
imx-core-sdk-kotlin-jvm
|
Apache License 2.0
|
container/src/main/java/com/elveum/container/subject/FlowSubject.kt
|
romychab
| 653,113,914
| false
|
{"Kotlin": 124515}
|
package com.elveum.container.subject
import kotlinx.coroutines.flow.Flow
/**
* Represents a finite flow which emissions can be controlled
* by the following methods:
* - [onNext]
* - [onComplete]
* - [onError]
*
* Use [flow] method to obtain the flow itself.
*/
public interface FlowSubject<T> {
/**
* Emit a new value to the flow returned by [flow]
*/
public fun onNext(value: T)
/**
* Complete the flow returned by [flow] call with the provided exception.
* Any further actions will not take effect.
*/
public fun onError(e: Throwable)
/**
* Complete the flow returned by [flow] call with success.
* Any further actions will not take effect.
*/
public fun onComplete()
/**
* The flow controlled by this subject. It emits values sent via
* [onNext] call. The flow can be finished manually by calling
* [onError] or [onComplete] methods. Also
* the flow holds the latest value sent by [onNext] so even if
* the latest value has been sent before starting collecting
* you can still receive it.
*/
public fun flow(): Flow<T>
public companion object {
public fun <T> create(): FlowSubject<T> {
val defaultConfiguration = FlowSubjects.defaultConfiguration
return defaultConfiguration.flowSubjectFactory.create()
}
}
}
| 0
|
Kotlin
|
0
| 3
|
f54b480c42e9e8bac023d036176a94a9e5afe37d
| 1,384
|
container
|
Apache License 2.0
|
app/src/main/java/com/dicoding/habitapp/data/HabitDao.kt
|
ahmaddyd
| 570,970,855
| false
|
{"Kotlin": 46771}
|
package com.dicoding.habitapp.data
import androidx.lifecycle.LiveData
import androidx.paging.DataSource
import androidx.room.*
import androidx.sqlite.db.SupportSQLiteQuery
//TODO 2 : Define data access object (DAO)
@Dao
interface HabitDao {
@RawQuery(observedEntities = [Habit::class])
fun getHabits(query: SupportSQLiteQuery): DataSource.Factory<Int, Habit>
@Query("Select * from habits where id = :habitId")
fun getHabitById(habitId: Int): LiveData<Habit>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertHabit(habit: Habit): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(vararg habits: Habit)
@Delete
fun deleteHabit(habits: Habit)
@Query("Select * from habits where priorityLevel = :level")
fun getRandomHabitByPriorityLevel(level: String): LiveData<Habit>
}
| 0
|
Kotlin
|
0
| 4
|
7a3b3bfce3bc668ebeaca0fcc8b052185c685b03
| 849
|
HabitApp
|
MIT License
|
app/src/test/java/com/sanmidev/mybakingapp/data/remote/mapper/StepModelToEntityMapperTest.kt
|
lastcountr1
| 597,164,844
| true
|
{"Kotlin": 62541}
|
package com.sanmidev.mybakingapp.data.remote.mapper
import com.google.common.truth.Truth
import com.sanmidev.mybakingapp.TestDataUtil
import com.sanmidev.mybakingapp.data.local.StepEntity
import com.sanmidev.mybakingapp.data.remote.model.StepModel
import org.junit.After
import org.junit.Before
import org.junit.Test
class StepModelToEntityMapperTest {
private lateinit var testData: Pair<StepModel, StepEntity>
private lateinit var CUT: StepModelToEntityMapper
@Before
fun setUp() {
CUT = StepModelToEntityMapper()
testData = TestDataUtil.generateStepTestData()
}
@Test
fun mapStepModelToEntity_StepEntity_shouldReturnStepModelWhenSuccessful() {
//GIVEN
val stepModel: StepModel = testData.first
val correctStepEntity: StepEntity = testData.second
//WHEN
val convertedStepEntity: StepEntity = CUT.mapStepModelToEntity(stepModel)
//THEN
Truth.assertThat(convertedStepEntity.description).isEqualTo(correctStepEntity.description)
Truth.assertThat(convertedStepEntity.id).isEqualTo(correctStepEntity.id)
Truth.assertThat(convertedStepEntity.shortDescription)
.isEqualTo(correctStepEntity.shortDescription)
Truth.assertThat(convertedStepEntity.thumbnailURL).isEqualTo(correctStepEntity.thumbnailURL)
Truth.assertThat(convertedStepEntity.videoURL).isEqualTo(correctStepEntity.videoURL)
}
@After
fun tearDown() {
}
}
| 0
| null |
0
| 0
|
56713df516376ec1af54958df35c6bd208288f40
| 1,482
|
MyMyBakingApp
|
Apache License 2.0
|
avd/src/com/android/tools/idea/avd/Dropdown.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.adddevicedialog.localavd
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import kotlinx.collections.immutable.ImmutableCollection
import org.jetbrains.jewel.ui.component.Dropdown
import org.jetbrains.jewel.ui.component.Text
@Composable
internal fun <I> Dropdown(
selectedItem: I,
items: ImmutableCollection<I>,
onSelectedItemChange: (I) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
) {
Dropdown(
modifier,
enabled,
menuContent = {
items.forEach {
selectableItem(selectedItem == it, onClick = { onSelectedItemChange(it) }) {
Text(it.toString())
}
}
},
) {
Text(selectedItem.toString())
}
}
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 1,367
|
android
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.