path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/h5190059/zenpirlanta/ui/kategori/KategoriViewModel.kt
|
busealkan
| 377,198,412
| false
| null |
package com.h5190059.zenpirlanta.ui
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.h5190059.zenpirlanta.data.KategoriResponseItem
import com.h5190059.zenpirlanta.data.KategoriRepository
import com.h5190059.zenpirlanta.util.ResourceStatus
import kotlinx.coroutines.launch
class KategoriViewModel : ViewModel() {
private val kategoriRepository: KategoriRepository =KategoriRepository()
init {
kategorileriGetir()
}
var loading : MutableLiveData<Boolean>? = MutableLiveData()
var kategorilerLiveData = MutableLiveData<List<KategoriResponseItem>>()
var error = MutableLiveData<Throwable>()
fun kategorileriGetir() = viewModelScope.launch {
kategoriRepository.kategorileriGetir()
.asLiveData(viewModelScope.coroutineContext).observeForever {
when(it.status) {
ResourceStatus.LOADING -> {
loading?.postValue(true)
}
ResourceStatus.SUCCESS -> {
kategorilerLiveData.postValue(it.data!!)
loading?.postValue(false)
}
ResourceStatus.ERROR -> {
error.postValue(it.throwable!!)
loading?.postValue(false)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a90e780e0afc1fdccc589028191413c8a7ef856c
| 1,486
|
ZenPirlantaApp
|
Apache License 2.0
|
kotlin-source/src/main/kotlin/com/example/state/LandTitleState.kt
|
nitesh7sid
| 161,622,560
| false
|
{"Java": 40050, "Kotlin": 34814, "HTML": 11524}
|
package com.example.state
import com.example.contract.LandTitleContract
import net.corda.core.contracts.CommandAndState
import net.corda.core.contracts.ContractState
import net.corda.core.contracts.OwnableState
import net.corda.core.identity.AbstractParty
import net.corda.core.identity.Party
/**
* The state object recording IOU agreements between two parties.
*
* A state must implement [ContractState] or one of its descendants.
*
* @param value the value of the IOU.
* @param lender the party issuing the IOU.
* @param borrower the party receiving and approving the IOU.
*/
data class LandTitleState(val titleID: String,
override val owner: AbstractParty,
override val participants: List<AbstractParty> = listOf(owner)): OwnableState {
override fun withNewOwner(newOwner: AbstractParty) = CommandAndState(LandTitleContract.Commands.Move(), copy(owner = newOwner))
fun withOwner(newOwner: AbstractParty): LandTitleState = copy(owner = newOwner)
}
| 0
|
Java
|
0
| 0
|
bd18330f47bb267e2d07f5b384a31ab914f17499
| 1,026
|
digital-street-hackathon-20181213-cordapp
|
Apache License 2.0
|
core/src/main/kotlin/neekle/BindingType.kt
|
neyb
| 110,265,948
| false
| null |
package neekle
import neekle.inject.api.Injector
interface BindingType {
fun <T> createProvider(init: (Injector) -> T): ComponentProvider<T>
}
| 0
|
Kotlin
|
0
| 0
|
ffe1bc7f6fc501486941539a1fea9cac9184c18e
| 149
|
neekle
|
MIT License
|
Fundamental Android Submission 1/app/src/main/java/com/example/percobaanke5/Data.kt
|
ArkanRidhwan
| 505,269,115
| false
|
{"Kotlin": 79527}
|
package com.example.percobaanke5
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Data(
var gambar: Int,
var nama: String,
var username: String,
var follower:String,
var following: String,
var company: String,
var location: String,
var repository: String
) : Parcelable
| 0
|
Kotlin
|
0
| 0
|
d7a5866c9004854b0d60ccdc087190856bfd8fab
| 342
|
Bangkit
|
MIT License
|
server/src/main/kotlin/org/kryptonmc/krypton/encryption/Encryption.kt
|
Esophose
| 347,235,978
| true
|
{"Kotlin": 421806, "Dockerfile": 139}
|
package org.kryptonmc.krypton.encryption
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.PublicKey
import javax.crypto.Cipher
class Encryption {
private val keyPair = generateKeyPair()
val publicKey: PublicKey = keyPair.public
private fun generateKeyPair(): KeyPair {
val generator = KeyPairGenerator.getInstance(PAIR_ALGORITHM)
generator.initialize(1024)
return generator.generateKeyPair()
}
fun decrypt(encryptedData: ByteArray): ByteArray {
val cipher = Cipher.getInstance(PAIR_ALGORITHM)
cipher.init(Cipher.DECRYPT_MODE, keyPair.private)
return cipher.doFinal(encryptedData)
}
companion object {
const val SHARED_SECRET_ALGORITHM = "AES/CFB8/NoPadding"
const val PAIR_ALGORITHM = "RSA"
}
}
| 0
|
Kotlin
|
0
| 0
|
76528024a0ec0e9b51ef9a77ca1ee613ffd1a9d6
| 837
|
Krypton
|
MIT License
|
example/app_example/android/app/src/main/kotlin/com/example/app_example/MainActivity.kt
|
SandroMaglione
| 235,799,500
| false
| null |
package com.example.app_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 10
|
Dart
|
30
| 141
|
90803369404d5d78e9f2f9d50414a2a84c84356c
| 128
|
step-progress-indicator
|
MIT License
|
coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/BridgeLogs.kt
|
Consensys
| 681,656,806
| false
|
{"Go": 3732756, "Kotlin": 2036043, "TypeScript": 1677629, "Solidity": 1011831, "Java": 190613, "Shell": 25336, "Python": 25050, "Jupyter Notebook": 14509, "Makefile": 13574, "Dockerfile": 8023, "JavaScript": 7341, "C": 5181, "Groovy": 2557, "CSS": 787, "Nix": 315, "Batchfile": 117}
|
package net.consensys.zkevm.domain
data class RlpBridgeLogsData(val rlp: String, val bridgeLogs: List<BridgeLogsData>)
data class BridgeLogsData(
val removed: Boolean,
val logIndex: String,
val transactionIndex: String,
val transactionHash: String,
val blockHash: String,
val blockNumber: String,
val address: String,
val data: String,
val topics: List<String>
)
data class L2RollingHashUpdatedEvent(val messageNumber: ULong, val messageRollingHash: ByteArray) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as L2RollingHashUpdatedEvent
if (messageNumber != other.messageNumber) return false
if (!messageRollingHash.contentEquals(other.messageRollingHash)) return false
return true
}
override fun hashCode(): Int {
var result = messageNumber.hashCode()
result = 31 * result + messageRollingHash.contentHashCode()
return result
}
}
| 27
|
Go
|
2
| 26
|
48547c9f3fb21e9003d990c9f62930f4facee0dd
| 985
|
linea-monorepo
|
Apache License 2.0
|
gcloud-storage-utils/src/main/java/com/evolveasia/aws/Util.kt
|
nawinkhatiwada
| 395,263,679
| false
| null |
/*
* Copyright 2015 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://aws.amazon.com/apache2.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.evolveasia.aws
import android.content.Context
import android.net.ConnectivityManager
import android.net.Uri
import com.amazonaws.auth.CognitoCachingCredentialsProvider
import com.amazonaws.mobile.config.AWSConfiguration
import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver
import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility
import com.amazonaws.regions.Region
import com.amazonaws.regions.Regions
import com.amazonaws.services.s3.AmazonS3Client
import com.evolveasia.initializer.ContextProviderImpl.Companion.getInstance
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*
/*
* Handles basic helper functions used throughout the app.
*/
object Util {
// We only need one instance of the clients and credentials provider
private var sS3Client: AmazonS3Client? = null
private var sCredProvider: CognitoCachingCredentialsProvider? = null
private var sTransferUtility: TransferUtility? = null
/**
* Gets an instance of CognitoCachingCredentialsProvider which is
* constructed using the given Context.
*
* @param
* @return A default credential provider.
*/
private fun getCredProvider(awsMetaInfo: AwsMetaInfo.AWSConfig): CognitoCachingCredentialsProvider? {
if (sCredProvider == null) {
sCredProvider = CognitoCachingCredentialsProvider(
getInstance().getAppCtx(),
awsMetaInfo.cognitoPoolId,
Regions.fromName(awsMetaInfo.region))
}
return sCredProvider
}
/**
* Gets an instance of a S3 client which is constructed using the given
* Context.
*
* @param
* @return A default S3 client.
*/
fun getS3Client(awsMetaInfo: AwsMetaInfo.AWSConfig): AmazonS3Client {
if (sS3Client == null) {
sS3Client = AmazonS3Client(getCredProvider(awsMetaInfo), Region.getRegion(awsMetaInfo.region))
}
return sS3Client!!
}
/**
* Gets an instance of the TransferUtility which is constructed using the
* given Context
*
* @return a TransferUtility instance
*/
@JvmStatic
fun getTransferUtility(awsMetaInfo: AwsMetaInfo): TransferUtility? {
if (sTransferUtility == null) {
sTransferUtility = TransferUtility.builder()
.context(getInstance().getAppCtx())
.s3Client(getS3Client(awsMetaInfo.serviceConfig))
.awsConfiguration(AWSConfiguration(awsMetaInfo.serviceConfig.awsConfiguration))
.build()
}
return sTransferUtility
}
/**
* Converts number of bytes into proper scale.
*
* @param bytes number of bytes to be converted.
* @return A string that represents the bytes in a proper scale.
*/
private fun getBytesString(bytes: Long): String {
val quantifiers = arrayOf(
"KB", "MB", "GB", "TB"
)
var speedNum = bytes.toDouble()
var i = 0
while (true) {
if (i >= quantifiers.size) {
return ""
}
speedNum /= 1024.0
if (speedNum < 512) {
return String.format("%.2f", speedNum) + " " + quantifiers[i]
}
i++
}
}
/*
* Fills in the map with information in the observer so that it can be used
* with a SimpleAdapter to populate the UI
*/
fun fillMap(map: MutableMap<String?, Any?>, observer: TransferObserver, isChecked: Boolean) {
val progress = (observer.bytesTransferred.toDouble() * 100 / observer
.bytesTotal).toInt()
map["id"] = observer.id
map["checked"] = isChecked
map["fileName"] = observer.absoluteFilePath
map["progress"] = progress
map["bytes"] = (getBytesString(observer.bytesTransferred) + "/"
+ getBytesString(observer.bytesTotal))
map["state"] = observer.state
map["percentage"] = "$progress%"
}
@JvmStatic
fun isNetworkAvailable(context: Context): Boolean {
val cm = context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
?: return false
val activeNetwork = cm.activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnected
}
}
| 0
|
Kotlin
|
0
| 1
|
5d7944360dfe5bc5f47e0f4b4ee210e0db274a90
| 5,013
|
CloudStorageUtil
|
Apache License 2.0
|
app/src/main/java/com/example/kitchen/MainActivity2.kt
|
sputnick01
| 584,093,940
| false
| null |
package com.example.kitchen
import android.R
import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main. *
import kotlinx.android.synthetic.main.activity_main2.*
class MainActivity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(com.example.kitchen.R.layout.activity_main2)
overridePendingTransition(0, 0)
val animation: Animation = AnimationUtils.loadAnimation(this, R.anim.fade_in)
activity_main_id.startAnimation(animation)
}
}
| 0
|
Kotlin
|
0
| 2
|
cdf58c5027486f9a90d9b173344b367de79f5443
| 738
|
kitchen
|
MIT License
|
src/commonMain/kotlin/com/shimmermare/stuffiread/ui/components/story/importing/PonyfictionImportForm.kt
|
Shimmermare
| 605,765,511
| false
|
{"Kotlin": 591299}
|
package com.shimmermare.stuffiread.ui.components.story.importing
import androidx.compose.runtime.Composable
import com.shimmermare.stuffiread.i18n.Strings
import com.shimmermare.stuffiread.importer.ImportSource.PONYFICTION
import com.shimmermare.stuffiread.importer.ImportedStory
import com.shimmermare.stuffiread.importer.ponyfiction.PonyfictionImportSettings
import com.shimmermare.stuffiread.importer.ponyfiction.PonyfictionImporter
import com.shimmermare.stuffiread.importer.ponyfiction.PonyfictionUrlParser
import com.shimmermare.stuffiread.ui.components.form.LeanBoolFormField
import com.shimmermare.stuffiread.ui.components.form.TextFormField
import com.shimmermare.stuffiread.ui.components.form.ValidationResult
import com.shimmermare.stuffiread.ui.util.remember
@Composable
fun PonyfictionImportForm(
onImported: (ImportedStory) -> Unit
) {
BaseSourceImportForm(
source = PONYFICTION,
defaultData = { PonyfictionFormData() },
importer = { formData ->
val settings = PonyfictionImportSettings(
storyId = PonyfictionUrlParser.parse(formData.storyUrl),
downloadFb2 = formData.downloadFb2,
downloadTxt = formData.downloadTxt,
)
PonyfictionImporter.import(settings)
},
onImported = onImported
) { state ->
TextFormField(
id = "storyUrl",
state = state,
name = Strings.components_importing_ponyfictionImportForm_storyUrl.remember(),
description = Strings.components_importing_ponyfictionImportForm_storyUrl_description
.remember("https://ponyfiction.org/story/1321"),
getter = { it.storyUrl },
setter = { formData, value -> formData.copy(storyUrl = value.trim()) },
singleLine = true,
maxLength = 120,
validator = {
if (PonyfictionUrlParser.matches(it)) {
ValidationResult.Valid
} else {
ValidationResult(false, Strings.components_importing_ponyfictionImportForm_invalid())
}
}
)
LeanBoolFormField(
id = "downloadFb2",
state = state,
name = Strings.components_importing_ponyfictionImportForm_downloadType.remember(".fb2"),
getter = { it.downloadFb2 },
setter = { formData, value -> formData.copy(downloadFb2 = value) },
)
LeanBoolFormField(
id = "downloadTxt",
state = state,
name = Strings.components_importing_ponyfictionImportForm_downloadType.remember(".txt"),
getter = { it.downloadTxt },
setter = { formData, value -> formData.copy(downloadTxt = value) },
)
}
}
private data class PonyfictionFormData(
val storyUrl: String = "",
val downloadFb2: Boolean = true,
val downloadTxt: Boolean = false
)
| 7
|
Kotlin
|
0
| 0
|
a5cd268c46494cc3e6ad17405f9013680f9ae240
| 2,952
|
StuffIRead
|
MIT License
|
kjob-core/src/main/kotlin/it/justwrote/kjob/dsl/ErrorJobContext.kt
|
justwrote
| 260,458,357
| false
| null |
package it.justwrote.kjob.dsl
import it.justwrote.kjob.job.ScheduledJob
import org.slf4j.Logger
@JobDslMarker
class ErrorJobContext internal constructor(scheduledJob: ScheduledJob, val error: Throwable, val logger: Logger) {
val jobName = scheduledJob.settings.name
val jobId = scheduledJob.settings.id
}
| 2
|
Kotlin
|
9
| 67
|
880b175516ce5f3e9edbb0b6fe7b50820c332026
| 314
|
kjob
|
Apache License 2.0
|
app/src/main/java/com/example/housepick/ui/addads/AddAdsFragment.kt
|
danialtavakoli
| 840,497,470
| false
|
{"Kotlin": 131082}
|
package com.example.housepick.ui.addads
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Base64
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Switch
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.housepick.R
import com.example.housepick.classes.Housing
import com.example.housepick.databinding.FragmentAddAdsBinding
import com.example.housepick.ui.utils.showSnackBar
import java.io.ByteArrayOutputStream
import java.io.InputStream
class AddAdsFragment : Fragment() {
private lateinit var editTextTitle: EditText
private lateinit var editTextStreet: EditText
private lateinit var editTextPostalCode: EditText
private lateinit var editTextCity: EditText
private lateinit var editTextCountry: EditText
private lateinit var editTextEstateType: EditText
private lateinit var editTextDescription: EditText
private lateinit var editTextEstatePrice: EditText
private lateinit var editTextNumberBathroom: EditText
private lateinit var editTextNumberBed: EditText
private lateinit var editTextNumberParking: EditText
private lateinit var editTextEmail: EditText
private lateinit var editTextPhone: EditText
private lateinit var imgToUpload: ImageView
private lateinit var createAdsButton: Button
private lateinit var addAdsViewModel: AddAdsViewModel
private var _binding: FragmentAddAdsBinding? = null
private lateinit var latitude: String
private lateinit var longitude: String
private var uri: Uri? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
addAdsViewModel = ViewModelProvider(this).get(AddAdsViewModel::class.java)
_binding = FragmentAddAdsBinding.inflate(inflater, container, false)
val root: View = binding.root
createAdsButton = binding.createAdsButton
createAdsButton.isEnabled = false
val switchRent: Switch = binding.switchRent
editTextTitle = binding.editTextTitle
editTextStreet = binding.editTextStreet
editTextPostalCode = binding.editTextPostalCode
editTextCountry = binding.editTextCountry
editTextCity = binding.editTextCity
editTextDescription = binding.editTextDescription
editTextEstateType = binding.editTextEstateType
editTextEstatePrice = binding.editTextEstatePrice
editTextNumberBathroom = binding.editTextNumberBathroom
editTextNumberBed = binding.editTextNumberBed
editTextNumberParking = binding.editTextNumberGarage
editTextEmail = binding.editTextEmail
editTextPhone = binding.editTextPhone
imgToUpload = binding.imgToUpload
editTextTitle.addTextChangedListener(textWatcher)
editTextStreet.addTextChangedListener(textWatcher)
editTextCity.addTextChangedListener(textWatcher)
editTextPostalCode.addTextChangedListener(textWatcher)
editTextCountry.addTextChangedListener(textWatcher)
editTextDescription.addTextChangedListener(textWatcher)
editTextEstateType.addTextChangedListener(textWatcher)
editTextEstatePrice.addTextChangedListener(textWatcher)
editTextNumberBathroom.addTextChangedListener(textWatcher)
editTextNumberBed.addTextChangedListener(textWatcher)
editTextEmail.addTextChangedListener(textWatcher)
editTextPhone.addTextChangedListener(textWatcher)
addAdsViewModel.getAction().observe(
viewLifecycleOwner
) { action -> action?.let { handleAction(it) } }
createAdsButton.setOnClickListener {
val title = editTextTitle.text.toString()
val street = editTextStreet.text.toString()
val city = editTextCity.text.toString()
val postalCode = editTextPostalCode.text.toString()
val country = editTextCountry.text.toString()
val desc = editTextDescription.text.toString()
val estateType = editTextEstateType.text.toString()
val estatePrice = editTextEstatePrice.text.toString()
val numberBath = editTextNumberBathroom.text.toString()
val numberBed = editTextNumberBed.text.toString()
val numberParking = editTextNumberParking.text.toString()
val email = editTextEmail.text.toString()
val phone = editTextPhone.text.toString()
val rent = switchRent.isChecked
val housing = Housing(
title,
street,
city,
postalCode,
country,
estatePrice,
estateType,
rent,
numberBath,
numberBed,
numberParking,
email,
phone,
desc,
latitude,
longitude,
null
)
if (uri != null) {
val imageStream: InputStream? = context?.contentResolver?.openInputStream(uri!!)
if (imageStream != null) {
val selectedImage = BitmapFactory.decodeStream(imageStream)
val encodedImage: String? = encodeImage(selectedImage)
if (encodedImage != null) {
binding.createAdsButton.isEnabled = false
//housing.imgPath = uri.toString()
housing.imgPath = encodedImage
addAdsViewModel.createAd(housing)
}
}
} else {
showSnackBar(binding.root, R.string.no_image_selected, R.drawable.mail_box_icon)
//Toast.makeText(context, "No image selected", Toast.LENGTH_SHORT).show()
}
}
binding.imgAddButton.setOnClickListener {
openActivityForResult()
}
binding.locationButton.setOnClickListener {
findNavController().navigate(R.id.action_addAdsFragment_to_locationPickerFragment)
}
parentFragmentManager.setFragmentResultListener("requestKey", this) { key, bundle ->
val latitudeBundle = bundle.getDouble("latitude")
val longitudeBundle = bundle.getDouble("longitude")
// Update latitude and longitude variables on the UI thread
latitude = latitudeBundle.toString()
longitude = longitudeBundle.toString()
}
binding.imageButtonBed.setOnClickListener {
binding.editTextNumberBed.requestFocus()
}
binding.imageButtonBathroom.setOnClickListener {
binding.editTextNumberBathroom.requestFocus()
}
binding.imageButtonGarage.setOnClickListener {
binding.editTextNumberGarage.requestFocus()
}
return root
}
private fun handleAction(action: Action) {
when (action.value) {
Action.SHOW_AD_CREATED -> {
binding.createAdsButton.isEnabled = true
editTextTitle.setText("")
editTextStreet.setText("")
editTextCity.setText("")
editTextPostalCode.setText("")
editTextCountry.setText("")
editTextDescription.setText("")
editTextEstateType.setText("")
editTextEstatePrice.setText("")
editTextNumberBathroom.setText("")
editTextNumberBed.setText("")
editTextEmail.setText("")
editTextPhone.setText("")
showSnackBar(binding.root, R.string.ad_created, R.drawable.mail_box_icon)
//Toast.makeText(context, "Ad created", Toast.LENGTH_SHORT).show()
findNavController().navigate(R.id.navigation_ads)
}
Action.SHOW_INVALID_FORM -> {
binding.createAdsButton.isEnabled = true
showSnackBar(binding.root, R.string.invalid_form, R.drawable.mail_box_icon)
//Toast.makeText(context, "Invalid form", Toast.LENGTH_SHORT).show()
}
Action.SHOW_BAD_ADDRESS -> {
binding.createAdsButton.isEnabled = true
showSnackBar(binding.root, R.string.address_doesnt_exist, R.drawable.mail_box_icon)
//Toast.makeText(context, "This address doesn't exist", Toast.LENGTH_SHORT).show()
}
}
}
private fun encodeImage(bm: Bitmap): String? {
val os = ByteArrayOutputStream()
bm.compress(Bitmap.CompressFormat.JPEG, 100, os)
val b: ByteArray = os.toByteArray()
return Base64.encodeToString(b, Base64.DEFAULT)
}
private val textWatcher: TextWatcher = object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
checkFieldsForEmptyValues()
}
override fun afterTextChanged(editable: Editable) {}
}
private fun checkFieldsForEmptyValues() {
val s1: String = editTextTitle.text.toString()
val s2: String = editTextStreet.text.toString()
val s10: String = editTextCity.text.toString()
val s11: String = editTextPostalCode.text.toString()
val s12: String = editTextCountry.text.toString()
val s3: String = editTextDescription.text.toString()
val s4: String = editTextEstateType.text.toString()
val s5: String = editTextEstatePrice.text.toString()
val s6: String = editTextNumberBathroom.text.toString()
val s7: String = editTextNumberBed.text.toString()
val s8: String = editTextEmail.text.toString()
val s9: String = editTextPhone.text.toString()
createAdsButton.isEnabled = s1.isNotEmpty() && s2.isNotEmpty() &&
s3.isNotEmpty() && s4.isNotEmpty() && s5.isNotEmpty()
&& s6.isNotEmpty() && s7.isNotEmpty() && s8.isNotEmpty()
&& s9.isNotEmpty() && s10.isNotEmpty() && s11.isNotEmpty()
&& s12.isNotEmpty()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private val startForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val res: Intent? = result.data
if (res != null) {
val extra = res.data
uri = extra
val takeFlags: Int =
res.flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
requireContext().contentResolver.takePersistableUriPermission(uri!!, takeFlags)
imgToUpload.setImageURI(extra)
}
}
}
private fun openActivityForResult() {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true)
startForResult.launch(intent)
}
}
| 0
|
Kotlin
|
0
| 6
|
34c17fdc7cb6d6b1aa7706abb605dd8f260503b0
| 11,993
|
HousePick
|
MIT License
|
feature-account-impl/src/main/java/io/novafoundation/nova/feature_account_impl/data/signer/proxy/SignerPayloadModifierExt.kt
|
novasamatech
| 415,834,480
| false
|
{"Kotlin": 9662409, "Java": 16389, "Rust": 15215, "JavaScript": 425}
|
package io.novafoundation.nova.feature_account_impl.data.signer.proxy
import io.novafoundation.nova.common.utils.Modules
import io.novafoundation.nova.feature_proxy_api.domain.model.ProxyType
import io.novafoundation.nova.runtime.extrinsic.multi.SimpleCallBuilder
import io.novasama.substrate_sdk_android.runtime.AccountId
import io.novasama.substrate_sdk_android.runtime.RuntimeSnapshot
import io.novasama.substrate_sdk_android.runtime.definitions.types.composite.DictEnum
import io.novasama.substrate_sdk_android.runtime.definitions.types.generics.DefaultSignedExtensions
import io.novasama.substrate_sdk_android.runtime.definitions.types.generics.Extrinsic.EncodingInstance.CallRepresentation
import io.novasama.substrate_sdk_android.runtime.definitions.types.instances.AddressInstanceConstructor
import io.novasama.substrate_sdk_android.runtime.extrinsic.encodeNonce
import io.novasama.substrate_sdk_android.runtime.extrinsic.replaceBaseNone
import io.novasama.substrate_sdk_android.runtime.extrinsic.signer.SignerPayloadExtrinsic
import java.math.BigInteger
fun SignerPayloadExtrinsic.wrapIntoProxyPayload(
proxyAccountId: AccountId,
currentProxyNonce: BigInteger,
proxyType: ProxyType,
callInstance: CallRepresentation.Instance
): SignerPayloadExtrinsic {
val proxiedAccountId = accountId
val callBuilder = SimpleCallBuilder(runtime)
callBuilder.addCall(
moduleName = Modules.PROXY,
callName = "proxy",
arguments = mapOf(
"real" to AddressInstanceConstructor.constructInstance(runtime.typeRegistry, proxiedAccountId),
"force_proxy_type" to DictEnum.Entry(proxyType.name, null),
"call" to callInstance.call
)
)
val newNonce = nonce.replaceBaseNone(currentProxyNonce)
return copy(
accountId = proxyAccountId,
call = CallRepresentation.Instance(callBuilder.calls.first()),
signedExtras = signedExtras.modifyNonce(runtime, newNonce.nonce),
nonce = newNonce
)
}
fun Map<String, Any?>.modifyNonce(runtimeSnapshot: RuntimeSnapshot, newNonce: BigInteger): Map<String, Any?> {
return buildMap {
putAll(this@modifyNonce)
put(DefaultSignedExtensions.CHECK_NONCE, runtimeSnapshot.encodeNonce(newNonce))
}
}
| 18
|
Kotlin
|
26
| 32
|
26d530400c30d00b08b23f9d69411f1719566930
| 2,275
|
nova-wallet-android
|
Apache License 2.0
|
backend/mandalore-express-domain/src/main/kotlin/com/beyondxscratch/mandaloreexpress/domain/booking/CannotBookAPartialSelection.kt
|
davidaparicio
| 761,161,576
| false
|
{"Kotlin": 198124, "JavaScript": 37294, "HTML": 1661, "CSS": 365}
|
package com.beyondxscratch.mandaloreexpress.domain.booking
class CannotBookAPartialSelection : RuntimeException("cannot book a partial selection")
| 8
|
Kotlin
|
0
| 0
|
05dc41e2a5a5ea47ef5d688177631ffa9923fe11
| 148
|
model-mitosis
|
Apache License 2.0
|
system_monitor/src/main/kotlin/com/cobox/vulture/systemserver/SystemServer.kt
|
Mysterious-organization
| 336,003,139
| false
| null |
package com.cobox.vulture.systemserver
import com.cobox.utilites.log.Log
import com.cobox.vulture.busniess.framework.VultureServer
import com.cobox.vulture.system.SystemMonitor
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
class SystemServer : VultureServer() {
companion object {
const val TAG = "SystemServer"
}
private var gatewayName: String? = null
private val systemModel by lazy {
SystemModel(
vertx,
config().getJsonObject(VultureConfig.Key.SERVER)
)
}
override fun onServicePrepare() {
systemModel.prepareCache()
createHttpGateway(SystemGateway::class.java.name, config()) { result ->
if (result.succeeded()) {
gatewayName = result.result()
} else {
Log.error(TAG, "[onServicePrepare] register gateway failed, caused by ${result.cause()}", result.cause())
}
}
}
private fun generateTempInfo(monitor: SystemMonitor): JsonObject =
JsonObject().put(
"temperatures",
JsonArray().apply {
val sensorCount = monitor.getTemperatureCount()
for (slot in 0 until sensorCount) {
add(JsonObject().put("temperature", monitor.getTemperature(slot)))
}
}
)
private fun generateMemInfo(monitor: SystemMonitor): JsonObject =
JsonObject()
.put("totalMem", monitor.getTotalRam())
.put("availableMem", monitor.getAvailableRam())
.put("freeMem", monitor.getFreeRam())
.put("totalSwap", monitor.getTotalSwap())
.put("freeSwap", monitor.getFreeSwap())
private fun generateCpuInfo(monitor: SystemMonitor): JsonObject =
JsonObject().let { json ->
val coreCount = monitor.getCoreSize()
json.put("coreCount", coreCount)
json.put("totalUsage", monitor.getTotalCpuUsage())
json.put("avgTotalUsage", monitor.getTotalCpuAvgUsage())
json.put("systemUsage", monitor.getSystemCpuUsage())
json.put("avgSystemUsage", monitor.getSystemCpuAvgUsage())
json.put("userUsage", monitor.getUserCpuUsage())
json.put("avgUserUsage", monitor.getUserCpuAvgUsage())
json.put("freeUsage", monitor.getFreeCpuUsage())
json.put("avgFreeUsage", monitor.getFreeCpuAvgUsage())
if (coreCount > 0) {
json.put(
"cores",
JsonArray().apply {
for (slot in 1..coreCount) {
add(
JsonObject()
.put("coreId", slot)
.put("totalUsage", monitor.getTotalCpuUsage(slot))
.put("avgTotalUsage", monitor.getTotalCpuAvgUsage(slot))
.put("systemUsage", monitor.getSystemCpuUsage(slot))
.put("avgSystemUsage", monitor.getSystemCpuAvgUsage(slot))
.put("userUsage", monitor.getUserCpuUsage(slot))
.put("avgUserUsage", monitor.getUserCpuAvgUsage(slot))
.put("freeUsage", monitor.getFreeCpuUsage(slot))
.put("avgFreeUsage", monitor.getFreeCpuAvgUsage(slot))
)
}
}
)
}
json
}
override fun onRegisterService() {
eventBus.consumer<String>("/system/cpuinfo") { msg ->
val result = generateCpuInfo(systemModel.systemMonitor).toString()
msg.reply(result)
Log.info(TAG, "[consumer] /system/cpuinfo: $result")
}
Log.info(TAG, "[onRegisterService] listener '/system/cpuinfo' on event bus")
eventBus.consumer<String>("/system/meminfo") { msg ->
val result = generateMemInfo(systemModel.systemMonitor).toString()
msg.reply(result)
Log.info(TAG, "[consumer] /system/meminfo: $result")
}
Log.info(TAG, "[onRegisterService] listener '/system/meminfo' on event bus")
eventBus.consumer<String>("/system/tempinfo") { msg ->
val result = generateTempInfo(systemModel.systemMonitor).toString()
msg.reply(result)
Log.info(TAG, "[consumer] /system/tempinfo: $result")
}
Log.info(TAG, "[onRegisterService] listener '/system/tempinfo' on event bus")
eventBus.consumer<String>("/system/summary") { msg ->
val monitor = systemModel.systemMonitor
val result = JsonObject()
.put("cpuinfo", generateCpuInfo(monitor))
.put("meminfo", generateMemInfo(monitor))
.put("tempinfo", generateTempInfo(monitor))
.toString()
msg.reply(result)
Log.info(TAG, "[consumer] /system/summary: $result")
}
Log.info(TAG, "[onRegisterService] listener '/system/summary' on event bus")
}
override fun onServiceStart() {
}
override fun onServiceStop() {
}
override fun onUnregisterService() {
}
override fun onServiceDestroy() {
gatewayName?.let {
destroyHttpGateway(it) { result ->
if (result.failed()) {
Log.error(TAG, "[onServiceDestroy] unregister gateway failed, caused by ${result.cause()}", result.cause())
}
}
}
systemModel.clearCache()
}
}
| 0
|
Kotlin
|
0
| 3
|
ae0c4a9b7f12bc556a5e9a674ab5a14b6a581ce4
| 5,720
|
Vulture-Station
|
MIT License
|
app/src/main/kotlin/com/flxrs/dankchat/preferences/screens/DeveloperSettingsFragment.kt
|
flex3r
| 186,238,019
| false
| null |
package com.flxrs.dankchat.preferences.screens
import android.content.Intent
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.text.util.Linkify
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.text.util.LinkifyCompat
import androidx.core.view.updateLayoutParams
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import com.flxrs.dankchat.R
import com.flxrs.dankchat.databinding.SettingsFragmentBinding
import com.flxrs.dankchat.databinding.UploaderBottomsheetBinding
import com.flxrs.dankchat.main.MainActivity
import com.flxrs.dankchat.preferences.DankChatPreferenceStore
import com.google.android.material.bottomsheet.BottomSheetDialog
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class DeveloperSettingsFragment : PreferenceFragmentCompat() {
@Inject
lateinit var dankChatPreferenceStore: DankChatPreferenceStore
private val requestCheckTTSData = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
when (it.resultCode) {
TextToSpeech.Engine.CHECK_VOICE_DATA_PASS -> (activity as? MainActivity)?.setTTSEnabled(true)
else -> startActivity(Intent(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA))
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = SettingsFragmentBinding.bind(view)
(requireActivity() as MainActivity).apply {
setSupportActionBar(binding.settingsToolbar)
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
title = getString(R.string.preference_developer_header)
}
findPreference<SwitchPreferenceCompat>(getString(R.string.preference_tts_key))?.apply {
setOnPreferenceChangeListener { _, value ->
when (value as Boolean) {
true -> requestCheckTTSData.launch(Intent(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA))
else -> setTTSEnabled(false)
}
true
}
}
}
findPreference<Preference>(getString(R.string.preference_uploader_key))?.apply {
setOnPreferenceClickListener { showImageUploaderPreference(view) }
}
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.developer_settings, rootKey)
}
private fun showImageUploaderPreference(root: View): Boolean {
val customUploader = dankChatPreferenceStore.customImageUploader
val context = root.context
val binding = UploaderBottomsheetBinding.inflate(LayoutInflater.from(context), root as? ViewGroup, false).apply {
uploader = customUploader
uploaderReset.setOnClickListener {
uploader = dankChatPreferenceStore.resetImageUploader()
}
uploaderSheet.updateLayoutParams {
height = (resources.displayMetrics.heightPixels * 0.6f).toInt()
}
LinkifyCompat.addLinks(uploaderDescription, Linkify.WEB_URLS)
}
BottomSheetDialog(context).apply {
setContentView(binding.root)
setOnDismissListener {
val copy = customUploader.copy(
headers = customUploader.headers?.takeIf { it.isNotBlank() },
imageLinkPattern = customUploader.imageLinkPattern?.takeIf { it.isNotBlank() },
deletionLinkPattern = customUploader.deletionLinkPattern?.takeIf { it.isNotBlank() },
)
dankChatPreferenceStore.customImageUploader = copy
}
behavior.peekHeight = (resources.displayMetrics.heightPixels * 0.6f).toInt()
show()
}
return true
}
}
| 29
|
Kotlin
|
31
| 91
|
e895c6ff999672ad203875f6a4aa033d9c8bb3bf
| 4,185
|
DankChat
|
MIT License
|
app/src/main/java/com/tommunyiri/dvtweatherapp/domain/usecases/favorites/GetFavoriteLocationsUseCase.kt
|
TomMunyiri
| 745,177,252
| false
|
{"Kotlin": 215965}
|
package com.tommunyiri.dvtweatherapp.domain.usecases.favorites
import com.tommunyiri.dvtweatherapp.core.utils.Result
import com.tommunyiri.dvtweatherapp.domain.model.FavoriteLocation
import com.tommunyiri.dvtweatherapp.domain.repository.WeatherRepository
/**
* Created by <NAME> on 25/02/2024.
* Company: Eclectics International Ltd
* Email: <EMAIL>
*/
class GetFavoriteLocationsUseCase(private val weatherRepository: WeatherRepository) {
suspend operator fun invoke(): Result<List<FavoriteLocation>?> {
return weatherRepository.getFavoriteLocations()
}
}
| 0
|
Kotlin
|
0
| 0
|
a1523e156b74949391aed59df2a48fc375b0ad8a
| 578
|
DVTWeatherApp
|
The Unlicense
|
river/src/main/kotlin/no/nav/k9/rapid/river/JsonNodeRequirements.kt
|
ramrock93
| 319,294,766
| true
|
{"Kotlin": 83510}
|
package no.nav.k9.rapid.river
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ObjectNode
fun JsonNode.requireText() = require(isTextual) { "Må være tekst." }
fun JsonNode.requireInt() = require(isIntegralNumber) { "Må være int." }
fun JsonNode.requireBoolean() = require(isBoolean) { "Må være boolean." }
fun JsonNode.requireArray(predicate: (JsonNode) -> Boolean = { true }) = require(isArray && all { predicate(it) }) { "Må være array." }
fun JsonNode.requireObject(predicate: (ObjectNode) -> Boolean = { true }) = require(isObject && predicate(this as ObjectNode))
| 0
| null |
0
| 0
|
3265f25acfe9b842d9105f5ff995f5857b4e0cca
| 611
|
k9-rapid
|
MIT License
|
demo/src/main/java/me/daemon/infrastructure/application/demo/MainActivity.kt
|
daemon369
| 402,693,381
| false
|
{"Kotlin": 9305}
|
package me.daemon.infrastructure.application.demo
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.e("MainActivity", Test.getString(R.string.app_name))
}
}
| 0
|
Kotlin
|
0
| 0
|
65778ec3ff1a1c6cd7ff7c11a8752afc7e9cc556
| 411
|
android-infrastructure-application
|
Apache License 2.0
|
zircon.core/jvm/src/test/kotlin/org/hexworks/zircon/integration/RadioButtonGroupIntegrationTest.kt
|
jmedinaJBM
| 178,613,075
| true
|
{"Kotlin": 1311631, "Java": 128163}
|
package org.hexworks.zircon.integration
import org.hexworks.zircon.api.Components
import org.hexworks.zircon.api.Positions
import org.hexworks.zircon.api.Sizes
import org.hexworks.zircon.api.graphics.BoxType
import org.hexworks.zircon.api.screen.Screen
class RadioButtonGroupIntegrationTest : ComponentIntegrationTestBase() {
override fun buildScreenContent(screen: Screen) {
val panel = Components.panel()
.wrapWithBox(true)
.withSize(Sizes.create(28, 28))
.withPosition(Positions.create(31, 1))
.build()
screen.addComponent(panel)
val simpleRadioButtonGroup0 = Components.radioButtonGroup()
.withPosition(Positions.create(2, 2))
.withSize(Sizes.create(14, 3))
.build()
val simpleRadioButtonGroup1 = Components.radioButtonGroup()
.withPosition(Positions.create(0, 0))
.withSize(Sizes.create(14, 3))
.build()
listOf(simpleRadioButtonGroup0, simpleRadioButtonGroup1).forEach {
it.addOption("key0", "First")
it.addOption("key1", "Second")
it.addOption("key2", "Third")
}
screen.addComponent(simpleRadioButtonGroup0)
panel.addComponent(simpleRadioButtonGroup1)
val decoratedRadioButtonGroup0 = Components.radioButtonGroup()
.withBoxType(BoxType.DOUBLE)
.wrapWithShadow(true)
.wrapWithBox(true)
.withSize(Sizes.create(14, 3))
.withPosition(Positions.create(2, 8))
.build()
val decoratedRadioButtonGroup1 = Components.radioButtonGroup()
.withBoxType(BoxType.DOUBLE)
.wrapWithShadow(true)
.wrapWithBox(true)
.withSize(Sizes.create(14, 3))
.withPosition(Positions.create(0, 6))
.build()
screen.addComponent(decoratedRadioButtonGroup0)
panel.addComponent(decoratedRadioButtonGroup1)
listOf(decoratedRadioButtonGroup0, decoratedRadioButtonGroup1).forEach {
it.addOption("key0", "First")
it.addOption("key1", "Second")
it.addOption("key2", "Third")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
700f7542c1d59f5561f2aec084f9b6a1f50649b0
| 2,298
|
zircon
|
MIT License
|
src/main/kotlin/fr/jhelp/kotlinLight/DispatchQueue.kt
|
jhelpgg
| 298,575,283
| false
| null |
package fr.jhelp.kotlinLight
import fr.jhelp.kotlinLight.tasks.delay
import fr.jhelp.kotlinLight.tasks.parallel
// @ImportSwift("Dispatch")
// =>
// import Dispatch
class DispatchQueue private constructor()
{
companion object
{
private val dispatchQueue = DispatchQueue()
fun global() = DispatchQueue.dispatchQueue
}
// DispatchQueue.global().async { something() }
// =>
// DispatchQueue.global().async { something() }
// ---
// DispatchQueue.global().async(task)
// =>
// DispatchQueue.global().async(execute : task)
fun async(execute: () -> Unit) =
parallel(execute)
// DispatchQueue.global().asyncAfter(DispatchTime.now()+DispatchTimeInterval.milliseconds(128)) { something() }
// =>
// DispatchQueue.global().asyncAfter(deadline: DispatchTime.now()+DispatchTimeInterval.milliseconds(128)) { something() }
// ---
// DispatchQueue.global().asyncAfter(DispatchTime.now()+DispatchTimeInterval.milliseconds(128), task)
// =>
// DispatchQueue.global().asyncAfter(deadline: DispatchTime.now()+DispatchTimeInterval.milliseconds(128), execute : task)
fun asyncAfter(deadline: DispatchTime, execute: () -> Unit) =
delay(deadline.timeMilliseconds - System.currentTimeMillis(), execute)
}
| 0
|
Kotlin
|
0
| 0
|
e20628f09b56e2faca1c46a9c11898d0d9f7f906
| 1,293
|
KotlinLight
|
Apache License 2.0
|
CalculadoraImc/app/src/main/java/com/vinilazzeri/calculadoraimc/MainActivity.kt
|
vinilazzeri
| 828,618,327
| false
|
{"Kotlin": 102298, "Java": 13121}
|
package com.vinilazzeri.calculadoraimc
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
private lateinit var btnCalcular: Button
private lateinit var editPeso: EditText
private lateinit var editAltura: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
btnCalcular = findViewById(R.id.btn_calcular)
editPeso =findViewById(R.id.edit_peso)
editAltura =findViewById(R.id.edit_altura)
btnCalcular.setOnClickListener {
val intent = Intent(this, ResultadoActivity::class.java)
val peso = editPeso.text.toString()
val altura = editAltura.text.toString()
if (peso.isNotEmpty() && altura.isNotEmpty()){
intent.putExtra("peso", peso.toDouble())
intent.putExtra("altura", altura.toDouble())
}
startActivity(intent)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
2cf0c00588d6a1d3ac00dce1b5cdb5985883dba6
| 1,515
|
android-studies
|
MIT License
|
app/src/main/java/id/uinjkt/salaamustadz/ui/home/ViewPagerAdapterUstadz.kt
|
Teguhmr
| 848,863,621
| false
|
{"Kotlin": 556881, "Java": 799, "JavaScript": 174}
|
package id.uinjkt.salaamustadz.ui.home
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import id.uinjkt.salaamustadz.ui.home.ustadz.UstadzFragment
import id.uinjkt.salaamustadz.ui.home.ustadz.UstadzahFragment
private const val NUM_TABS = 2
class ViewPagerAdapterUstadz (fragmentManager: FragmentManager, lifecycle: Lifecycle): FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount(): Int {
return NUM_TABS
}
override fun createFragment(position: Int): Fragment {
return if(position == 0){
UstadzFragment()
} else {
UstadzahFragment()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
305c5c91e2d065342778ac556dbbdcb957e1f71e
| 765
|
Salaam-Ustadz
|
Apache License 2.0
|
features/library/src/main/java/taiwan/no/one/feat/library/presentation/viewmodels/MyHomeViewModel.kt
|
pokk
| 263,073,196
| false
| null |
/*
* MIT License
*
* Copyright (c) 2021 Jieyi
*
* 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 taiwan.no.one.feat.library.presentation.viewmodels
import android.app.Application
import androidx.annotation.WorkerThread
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.kodein.di.instance
import taiwan.no.one.core.presentation.viewmodel.ResultLiveData
import taiwan.no.one.dropbeat.core.PlaylistConstant
import taiwan.no.one.dropbeat.core.viewmodel.BehindAndroidViewModel
import taiwan.no.one.dropbeat.domain.usecases.AddAccountCase
import taiwan.no.one.dropbeat.domain.usecases.AddAccountReq
import taiwan.no.one.dropbeat.domain.usecases.AddPlaylistCase
import taiwan.no.one.dropbeat.domain.usecases.SyncPlaylistCase
import taiwan.no.one.dropbeat.domain.usecases.SyncPlaylistReq
import taiwan.no.one.dropbeat.provider.LibraryMethodsProvider
import taiwan.no.one.entity.SimpleTrackEntity
import taiwan.no.one.entity.UserInfoEntity
import taiwan.no.one.feat.library.data.entities.local.LibraryEntity.PlayListEntity
import taiwan.no.one.feat.library.data.mappers.EntityMapper
import taiwan.no.one.feat.library.domain.usecases.FetchAllPlaylistsCase
import taiwan.no.one.feat.library.domain.usecases.UpdatePlaylistCase
import taiwan.no.one.feat.library.domain.usecases.UpdatePlaylistReq
import taiwan.no.one.feat.library.domain.usecases.UpdateSongCase
import taiwan.no.one.feat.library.domain.usecases.UpdateSongReq
import taiwan.no.one.ktx.livedata.toLiveData
internal class MyHomeViewModel(
application: Application,
override val handle: SavedStateHandle,
) : BehindAndroidViewModel(application) {
private val fetchAllPlaylistsCase by instance<FetchAllPlaylistsCase>()
private val addAccountCase by instance<AddAccountCase>()
private val addPlaylistCase by instance<AddPlaylistCase>()
private val syncPlaylistCase by instance<SyncPlaylistCase>()
private val updatePlaylistCase by instance<UpdatePlaylistCase>()
private val updateSongCase by instance<UpdateSongCase>()
private val libraryProvider by instance<LibraryMethodsProvider>()
private val _playlists by lazy { ResultLiveData<List<PlayListEntity>>() }
val playlists get() = _playlists.toLiveData()
private val _nonDefaultPlaylist by lazy { MutableLiveData<List<PlayListEntity>>() }
val nonDefaultPlaylist get() = _nonDefaultPlaylist.toLiveData()
private val _favorites by lazy { MutableLiveData<List<SimpleTrackEntity>>() }
val favorites get() = _favorites.toLiveData()
private val _downloaded by lazy { MutableLiveData<List<SimpleTrackEntity>>() }
val downloaded get() = _downloaded.toLiveData()
private val _histories by lazy { MutableLiveData<List<SimpleTrackEntity>>() }
val histories get() = _histories.toLiveData()
private val _resultOfFavorite by lazy { MutableLiveData<Boolean>() }
val resultOfFavorite get() = _resultOfFavorite.toLiveData()
private val _resultOfAddAccount by lazy { MutableLiveData<Boolean>() }
val resultOfAddAccount get() = _resultOfAddAccount.toLiveData()
fun getAllPlaylists() = viewModelScope.launch {
_playlists.value = kotlin.runCatching { fetchAllPlaylistsCase.execute() }
}
@WorkerThread
fun eliminateDefaultPlaylist(list: List<PlayListEntity>) = launchBehind(Dispatchers.Default) {
_nonDefaultPlaylist.postValue(list.filter { it.id !in PlaylistConstant.fixedPlaylistIds() })
}
@WorkerThread
fun extractDefaultPlaylist(list: List<PlayListEntity>) = launchBehind(Dispatchers.Default) {
listOf(_downloaded, _favorites, _histories)
.zip(PlaylistConstant.fixedPlaylistIds())
.forEach { (livedata, index) ->
// [index - 1] because the id and index with different 1.
val playlist = list[index - 1]
livedata.postValue(getSongs(playlist))
}
}
fun updateSong(song: SimpleTrackEntity, isFavorite: Boolean) = viewModelScope.launch {
_resultOfFavorite.value = libraryProvider.updateSongWithFavorite(song, isFavorite)
}
fun createAccountOnRemote(entity: UserInfoEntity) = viewModelScope.launch {
_resultOfAddAccount.value = addAccountCase.execute(AddAccountReq(entity))
}
fun createPlaylistOnRemote(userInfo: UserInfoEntity) = viewModelScope.launch {
val playlists = _playlists.value?.getOrNull().orEmpty()
// NOTE(jieyi): Will have a list of pair <playlist <-> songs>.
val simplePlaylists = playlists.map(EntityMapper::playlistToSimplePlaylistEntity)
val songsOfPlaylists = playlists.map { it.songs.map(EntityMapper::songToSimpleEntity) }
kotlin.runCatching {
syncPlaylistCase.execute(SyncPlaylistReq(userInfo, simplePlaylists, songsOfPlaylists))
}.onSuccess {
// Update the local database.
simplePlaylists.filter { it.refPath.isNotEmpty() } // for playlists
.forEach {
updatePlaylistCase.execute(
UpdatePlaylistReq(it.id, refPath = it.refPath, syncStamp = it.syncedStamp)
)
}
// for songs
simplePlaylists.forEachIndexed { index, playlist ->
playlist.refOfSongs.zip(playlists[index].songs).forEach { (ref, song) ->
val track = EntityMapper.songToSimpleEntity(song.copy(isFavorite = song.isFavorite, refPath = ref))
updateSongCase.execute(UpdateSongReq(track))
}
}
// Refresh the view's data.
getAllPlaylists()
}
}
fun syncPlaylistOnRemote(userInfo: UserInfoEntity) = viewModelScope.launch {
}
private fun getSongs(playlist: PlayListEntity) = playlist.songs
.map(EntityMapper::songToSimpleEntity)
.let { songs -> if (songs.size <= 4) songs else songs.subList(0, 4) }
}
| 2
|
Kotlin
|
3
| 16
|
6d173194dcd3c44db46dfe6b0ef691b9322da975
| 7,073
|
DropBeat
|
MIT License
|
src/main/kotlin/no/nav/tms/brannslukning/setup/database/Flyway.kt
|
navikt
| 743,413,887
| false
|
{"Kotlin": 96190, "CSS": 8486, "Dockerfile": 148}
|
package no.nav.tms.brannslukning.setup.database
import org.flywaydb.core.Flyway
import org.flywaydb.core.api.configuration.FluentConfiguration
object Flyway {
fun runFlywayMigrations() {
val flyway = configure().load()
flyway.migrate()
}
private fun configure(): FluentConfiguration {
val configBuilder = Flyway.configure().connectRetries(5)
val dataSource = PostgresDatabase.hikariFromLocalDb()
configBuilder.dataSource(dataSource)
return configBuilder
}
}
| 5
|
Kotlin
|
1
| 0
|
f13174022d1bf03097aa639c4f48a4ec1a400f06
| 528
|
tms-brannslukning
|
MIT License
|
src/main/kotlin/no/nav/tms/brannslukning/setup/database/Flyway.kt
|
navikt
| 743,413,887
| false
|
{"Kotlin": 96190, "CSS": 8486, "Dockerfile": 148}
|
package no.nav.tms.brannslukning.setup.database
import org.flywaydb.core.Flyway
import org.flywaydb.core.api.configuration.FluentConfiguration
object Flyway {
fun runFlywayMigrations() {
val flyway = configure().load()
flyway.migrate()
}
private fun configure(): FluentConfiguration {
val configBuilder = Flyway.configure().connectRetries(5)
val dataSource = PostgresDatabase.hikariFromLocalDb()
configBuilder.dataSource(dataSource)
return configBuilder
}
}
| 5
|
Kotlin
|
1
| 0
|
f13174022d1bf03097aa639c4f48a4ec1a400f06
| 528
|
tms-brannslukning
|
MIT License
|
app/src/main/java/com/deverick/marvelousheroes/MarvelousHeroesApplication.kt
|
ErickLuizA
| 336,352,400
| false
| null |
package com.deverick.marvelousheroes
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class MarvelousHeroesApplication : Application()
| 0
|
Kotlin
|
0
| 0
|
8669ec0fe87b9fd30cd8b2442b62b66a8bae6188
| 176
|
MarvelousHeroes
|
MIT License
|
cliffhanger/shared-views/src/main/kotlin/com/github/charbgr/cliffhanger/shared/views/imageview/BaseImageView.kt
|
charbgr
| 74,907,427
| false
| null |
package com.github.charbgr.cliffhanger.shared.views.imageview
import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
import com.bumptech.glide.Glide
open class BaseImageView : ImageView {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs,
defStyleAttr)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(
context, attrs, defStyleAttr, defStyleRes)
protected fun loadImage(url: String) {
Glide.with(context)
.load(url)
.into(this)
}
fun clear() {
Glide.clear(this)
}
}
| 8
|
Kotlin
|
0
| 0
|
88e0737f2818f9c45fab052008f7a81f0a51dc86
| 783
|
CliffHanger
|
MIT License
|
src/main/kotlin/no/nav/arbeidsgiver/iatjenester/metrikker/config/FlywayConfigProperties.kt
|
navikt
| 338,342,215
| false
|
{"Kotlin": 157528, "Dockerfile": 150}
|
package no.nav.arbeidsgiver.iatjenester.metrikker.config
import org.springframework.boot.context.properties.ConfigurationProperties
@ConfigurationProperties(prefix = "spring.flyway")
data class FlywayConfigProperties(
var locations: Array<String>
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as FlywayConfigProperties
if (!locations.contentEquals(other.locations)) return false
return true
}
override fun hashCode(): Int {
return locations.contentHashCode()
}
}
| 1
|
Kotlin
|
0
| 0
|
bd376a1bced4585c35eb544599f8cee80e8dda59
| 626
|
ia-tjenester-metrikker
|
MIT License
|
app/src/main/java/com/bngel/bcy/fragment/SearchQaFragment.kt
|
Bngel
| 389,700,084
| false
| null |
package com.bngel.bcy.fragment
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.bngel.bcy.R
import com.bngel.bcy.service.CosControllerService
import com.bngel.bcy.service.QAControllerService
import com.bngel.bcy.utils.ConstantRepository
import com.bngel.bcy.utils.InfoRepository
import com.bngel.bcy.utils.MyUtils
import com.bngel.bcy.widget.HomeFragment.DiscussCardHomeFragment
import com.bngel.bcy.widget.others.QAndACardView
import kotlinx.android.synthetic.main.fragment_search_cos.*
import kotlinx.android.synthetic.main.fragment_search_qa.*
class SearchQaFragment : Fragment() {
private val qaService = QAControllerService()
private var keyword = ""
private var detailLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
val data = result.data
}
var parentContext: Context? = null
val COS_COUNT = 10
var pageNow = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
registerLaunch()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_search_qa, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
parentContext = context?.applicationContext
initWidget()
}
private fun registerLaunch() {
detailLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
val data = result.data
}
}
private fun initWidget() {
cosEvent()
}
private fun cosEvent() {
ConstantRepository.searchConfirm.observe(viewLifecycleOwner, Observer {
if (it) {
val keyword = activity?.intent?.getStringExtra("keyword")?:""
val postEsSearchCos = qaService.postEsSearchQa(
COS_COUNT,
keyword,
pageNow,
if (ConstantRepository.loginStatus) InfoRepository.user.id else "0"
)
if (postEsSearchCos != null && postEsSearchCos.msg == "success") {
cards_SearchQaFragment.removeAllViews()
val qas = postEsSearchCos.data.qaList
for (qa in qas) {
val view = QAndACardView(parentContext!!, qa.number, 0, qa.title, qa.description, qa.createTime, MyUtils.fromStringToList(qa.label), detailLauncher)
cards_SearchQaFragment.addView(view)
}
}
}
})
}
}
| 0
|
Kotlin
|
0
| 0
|
f8091bdbb9d4b7720587def7411b72a9c2d6fe35
| 2,988
|
bcy
|
Apache License 2.0
|
src/main/kotlin/dev/cbyrne/kdiscordipc/core/event/impl/ActivityJoinEvent.kt
|
caoimhebyrne
| 379,862,700
| false
|
{"Kotlin": 61658}
|
package dev.cbyrne.kdiscordipc.core.event.impl
import dev.cbyrne.kdiscordipc.core.event.Event
import dev.cbyrne.kdiscordipc.core.event.data.ActivityJoinEventData
data class ActivityJoinEvent(val data: ActivityJoinEventData) : Event
| 2
|
Kotlin
|
8
| 37
|
b136b267d146544c49d80b4c9a046d66324a601b
| 233
|
KDiscordIPC
|
MIT License
|
app/src/main/java/com/newbiechen/nbreader/ui/component/adapter/base/SimpleBindingAdapter.kt
|
newbiechen1024
| 239,496,581
| false
| null |
package com.newbiechen.nbreader.ui.component.adapter.base
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
typealias OnItemClickListener<T> = (pos: Int, value: T) -> Unit
/**
* 简单封装基于 DataBinding 的 Adapter
*/
abstract class SimpleBindingAdapter<T> : RecyclerView.Adapter<WrapViewHolder<T>>() {
private val mItemList: ArrayList<T> = ArrayList()
abstract fun createViewHolder(type: Int): IViewHolder<T>
open fun bindViewHolder(binding: ViewDataBinding, position: Int) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WrapViewHolder<T> {
val holder = createViewHolder(viewType)
// 创建 binding
val binding = holder.createBinding(parent)
return WrapViewHolder(binding, holder)
}
override fun getItemCount(): Int = mItemList.size
final override fun onBindViewHolder(holder: WrapViewHolder<T>, position: Int) {
holder.holder.onBind(getItem(position)!!, position)
bindViewHolder(holder.binding, position)
}
fun getItem(pos: Int): T? {
return if (pos < mItemList.size) mItemList[pos] else null
}
fun refreshItems(items: List<T>?) {
if (items == null || items.isEmpty()) {
return
}
mItemList.clear()
mItemList.addAll(items)
notifyDataSetChanged()
}
}
| 5
|
Kotlin
|
8
| 37
|
e423b13915578ab95c1683bfa7a70e59f19f2eab
| 1,410
|
NBReader
|
Apache License 2.0
|
src/main/java/com/dystopia/sketch/element/LayersElement.kt
|
tseylerd
| 120,107,315
| false
| null |
package com.dystopia.sketch.element
import com.dystopia.sketch.api.SketchElement
import com.dystopia.sketch.model.SketchModelBuilder
class LayersElement(id: String, child: SketchElement) : IdBasedSketchElement(id, child) {
override fun reproduce(child: SketchElement): IdBasedSketchElement {
return LayersElement(id, child)
}
override fun buildModel(builder: SketchModelBuilder) {
child.buildModel(builder)
}
}
| 0
|
Kotlin
|
0
| 0
|
b85deba8b0517f1a32a6770225384d48651fc534
| 445
|
dystopia-model
|
Apache License 2.0
|
av/FFmpegAndroid-master/app/src/main/java/com/frank/ffmpeg/format/VideoLayout.kt
|
wangpengfei1992
| 444,720,156
| false
|
{"C": 15356987, "Kotlin": 1926516, "Java": 1439280, "Makefile": 697532, "Shell": 397449, "C++": 160245, "GLSL": 104693, "CMake": 58126, "M4": 43504, "Assembly": 40776, "CSS": 20448, "Perl": 10762, "Groovy": 9011, "HTML": 2612, "Batchfile": 789}
|
package com.frank.ffmpeg.format
/**
* layout of video
* Created by frank on 2018/6/18.
*/
object VideoLayout {
//horizontal join
const val LAYOUT_HORIZONTAL = 1
//vertical join
const val LAYOUT_VERTICAL = 2
}
| 0
|
C
|
0
| 0
|
2e078f0c510515be47e6713357fa87089af8fdae
| 232
|
TestDemoList
|
Apache License 2.0
|
infrastructure/src/main/kotlin/com/example/infrastructure/persistence/entity/management/ManagementEntity.kt
|
PARKPARKWOO
| 737,782,254
| false
|
{"Kotlin": 285620}
|
package com.example.infrastructure.persistence.entity.management
import com.example.core.managemnet.model.Management
import com.example.core.managemnet.model.ManagementStatus
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.Table
import org.hibernate.annotations.DynamicUpdate
import org.hibernate.annotations.SQLDelete
import org.jetbrains.annotations.NotNull
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.annotation.LastModifiedDate
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.UUID
const val MANAGEMENT_TABLE_NAME = "management"
@Entity
@Table(name = MANAGEMENT_TABLE_NAME)
@DynamicUpdate
@SQLDelete(sql = "update $MANAGEMENT_TABLE_NAME set deleted_at = now(), status = 'REJECT' WHERE id = ?")
class ManagementEntity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0L,
@Column(name = "trainer_id")
val trainerId: UUID,
@Column(name = "member_id")
val memberId: UUID,
@Column(name = "status")
@Enumerated(EnumType.STRING)
var status: ManagementStatus,
@Column(name = "ended_at")
var endDate: LocalDate,
) {
@Column(name = "created_at")
@CreatedDate
@NotNull
lateinit var createdAt: LocalDateTime
@Column(name = "updated_at")
@LastModifiedDate
@NotNull
lateinit var updatedAt: LocalDateTime
@Column(name = "deleted_at", nullable = true)
var deletedAt: LocalDateTime? = null
fun toDomain() = Management(
id = id,
trainerId = trainerId,
memberId = memberId,
status = status,
updatedAt = updatedAt,
endDate = endDate,
)
fun update(management: Management) {
this.status = management.status
this.endDate = management.endDate
}
}
| 15
|
Kotlin
|
0
| 0
|
3ada73884b3b6fc4b0a011f0c5b3615c248fe14a
| 2,029
|
barbellrobot-backend
|
Apache License 2.0
|
app/src/main/java/com/bao/iu/fragment/f_Article/ArticleFragment.kt
|
oops-iu
| 105,001,861
| false
|
{"Kotlin": 33380, "Java": 1112}
|
package com.bao.iu.fragment.f_Article
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.net.ConnectivityManager
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.UpdateListener
import com.bao.iu.pojo.Article
import com.bao.iu.R
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_article.*
/**
* Created by Administrator on 2017/9/21.
*/
class ArticleFragment : Fragment() ,View.OnClickListener{
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater?.inflate(R.layout.fragment_article,container,false)
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
title = arguments.getString("title")
val imgUrl = arguments.getString("imgUrl")
val contents = arguments.getString("contents")
objectId = arguments.getString("objectId")
Glide.with(this).load(imgUrl).into(new_a_img)
new_a_title.setText(title)
new_a_contents.setText(contents)
new_fab.setOnClickListener(this)
}
var title: String? = null
var objectId: String? = null
var handler = object: Handler(){
override fun handleMessage(msg: Message?) {
when (msg?.what) {
2 -> {
//删除
//获取网络连接
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val nt = cm.activeNetworkInfo
var flagNetwork = (nt != null && nt.isAvailable)
if (flagNetwork) {
//有网
var a = Article()
a.code = 0
Log.i("@@@","执行删除")
a.update(objectId,object: UpdateListener(){
override fun done(e: BmobException?) {
if(e == null){
Toast.makeText(activity,"删除成功",Toast.LENGTH_SHORT).show()
activity.onBackPressed()
}else{
Toast.makeText(activity,"删除成功 message: ${e.message}",Toast.LENGTH_SHORT).show()
}
}
})
}else{
Toast.makeText(activity,"请打开网络。。。",Toast.LENGTH_SHORT).show()
}
}
else -> {
}
}
}
}
override fun onClick(view: View?) {
when (view?.id) {
R.id.new_fab -> {
var dialog = AlertDialog.Builder(activity)
dialog.setTitle("是否要删除 ${title}").setCancelable(false)
.setPositiveButton("删除",object:DialogInterface.OnClickListener{
override fun onClick(p0: DialogInterface?, p1: Int) {
var message = Message()
message.what = 2
handler.sendMessage(message)
}
})
.setNegativeButton("取消",object: DialogInterface.OnClickListener{
override fun onClick(p0: DialogInterface?, p1: Int) {
Toast.makeText(activity,"谢谢你放过我-。-",Toast.LENGTH_SHORT).show()
}
})
.show()
}
else -> {
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5dbd4bf3c7c6db1e8eb058e85eae1211ec8db589
| 4,087
|
Eason
|
Apache License 2.0
|
shell/src/main/kotlin/matt/kjlib/shell/proc/proc.kt
|
mgroth0
| 365,604,330
| false
| null |
package matt.kjlib.shell.proc
import matt.kjlib.shell.ExecReturner
import matt.kjlib.shell.NonZeroShellResult
import matt.kjlib.shell.PrintInSeq.CHARS
import matt.kjlib.shell.PrintInSeq.LINES
import matt.kjlib.shell.PrintInSeq.NO
import matt.kjlib.shell.ShellResult
import matt.kjlib.shell.ShellVerbosity
import matt.kjlib.shell.proc.ProcessKillSignal.SIGINT
import matt.kjlib.shell.proc.ProcessKillSignal.SIGKILL
import matt.kjlib.shell.proc.ProcessKillSignal.SIGTERM
import matt.lang.RUNTIME
import matt.lang.function.Op
import matt.lang.shutdown.duringShutdown
import matt.log.DefaultLogger
import matt.log.logger.Logger
import matt.log.warn.warn
import matt.model.data.file.IDFile
import matt.model.op.prints.Prints
import matt.prim.str.joinWithSpaces
import matt.stream.forEachChar
import matt.stream.onEachChar
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import kotlin.concurrent.thread
fun proc(
wd: IDFile?, vararg args: String, env: Map<String, String> = mapOf()
): Process {
val envP = env.map {
it.key + "=" + it.value
}.toTypedArray()
try {
return if (wd == null) RUNTIME.exec(
args, envP
) else RUNTIME.exec(
args, envP, wd.idFile
)
} catch (e: IOException) {
var fullCommand = ""
if (wd != null) {
fullCommand += "cd ${wd.filePath}; "
}
env.forEach {
fullCommand += "${it.key}=${it.value} "
}
fullCommand += args.joinWithSpaces()
println("COPY AND PASTE THIS TO REPLICATE IN TERMINAL: $fullCommand")
throw e
}
}
internal fun Process.allStdOutAndStdErr(verbosity: ShellVerbosity, logger: Prints = DefaultLogger): ShellResult {
var err =
""/*MUST USE THREAD. IF IS TRY TO DO THIS SEQUENTIALLY, SOMETIMES EITHER ERR OR STDOUT IS SO LARGE THAT IT PREVENTS THE OTHER ONE FROM COMING THROUGH, CAUSING BLOCKING IF I TRY TO GET EACH IN SEQUENCE.*/
fun inputOp(reader: BufferedReader) = when (verbosity.printInSequence) {
NO -> reader.readText()
LINES -> reader.lineSequence().onEach {
logger.println(it)
}.joinToString("\n")
CHARS -> reader.onEachChar {
logger.print(it)
}
}
val t = thread {
err = inputOp(errorReader())
}
val out = inputOp(inputReader())
t.join()
val code = waitFor()
return ShellResult(code = code, std = out, err = err)
// return out + err
/*
streams.joinToString("") {
it.bufferedReader().lines().toList().joinToString("\n")
}
*/
}
val Process.streams: List<InputStream> get() = listOf(inputStream, errorStream)
fun Process.forEachOutChar(op: (String)->Unit) = inputStream.bufferedReader().forEachChar {
op(it)
}
fun Process.forEachErrChar(op: (String)->Unit) = errorStream.bufferedReader().forEachChar {
op(it)
}
fun Process.scheduleShutdownKill() {
val processPid = pid()
duringShutdown {
if (isAlive) {
/*IntelliJ seems to kill Sys.out or stop reading it or whatever during the shutdown process, so this won't be seen in the console if run through an IntelliJ Gradle Run Action*/
println("killing process ($processPid)")
kill(SIGKILL)
println("killed process")
} else {
println("blender process ($processPid) is already dead")
}
}
}
fun Process.whenDead(daemon: Boolean = true, op: Op) {
thread(isDaemon = daemon) {
waitFor()
op()
}
}
enum class ProcessKillSignal {
SIGTERM, SIGINT, SIGKILL
}
@JvmInline value class Pid(internal val id: Long) {
fun kill(
signal: ProcessKillSignal = SIGKILL,
doNotThrowIfNoSuchProcess: Boolean = false
) {
fun op() = ExecReturner.SILENT.kill(this, signal)
if (doNotThrowIfNoSuchProcess) {
try {
op()
} catch (e: NonZeroShellResult) {
if (e.code == 47202) {
warn("\"no such process\" when trying to kill $id")
} else {
throw e
}
}
} else {
op()
}
}
fun obliterate() {
println("obliterating $this")
kill(SIGTERM)
kill(SIGINT)
kill(SIGKILL)
}
}
fun Process.myPid() = Pid(pid())
fun Process.kill(signal: ProcessKillSignal = SIGKILL) = myPid().kill(signal)
| 0
|
Kotlin
|
0
| 0
|
3f7b657c2e69a9d59248f1e8b6940f4913dbb376
| 3,945
|
kjlib
|
MIT License
|
src/main/kotlin/pl/dmichalski/algorithms/_9_sorting/SortService.kt
|
johnblack123
| 304,328,757
| true
|
{"Kotlin": 24904, "Groovy": 14140}
|
package pl.dmichalski.algorithms._9_sorting
interface SortService {
fun sort(values: IntArray): IntArray
}
| 0
| null |
0
| 1
|
f27b57b1f3c8a8ab838524a3c087f8febb4eb29c
| 114
|
algorithms-and-data-structures-in-kotlin
|
MIT License
|
app/src/test/java/com/jeanca/mapsapp/PlacesViewModelTest.kt
|
hajc1294
| 745,624,364
| false
|
{"Kotlin": 41854}
|
package com.jeanca.mapsapp
import android.content.Context
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.jeanca.mapsapp.api.ApiProvider
import com.jeanca.mapsapp.commons.Status
import com.jeanca.mapsapp.database.SearchDatabase
import com.jeanca.mapsapp.models.AutocompleteFormat
import com.jeanca.mapsapp.models.AutocompletePlace
import com.jeanca.mapsapp.utils.JsonReader
import com.jeanca.mapsapp.viewmodels.PlacesViewModel
import io.reactivex.android.plugins.RxAndroidPlugins
import io.reactivex.plugins.RxJavaPlugins
import io.reactivex.schedulers.Schedulers
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.mock
import org.mockito.Mockito.`when`
import java.net.HttpURLConnection
class PlacesViewModelTest {
private lateinit var mockWebServer: MockWebServer
private lateinit var placesViewModel: PlacesViewModel
@Mock
private val mockContext: Context = mock(Context::class.java)
@get:Rule
val rule = InstantTaskExecutorRule()
init {
val synchronousScheduler = Schedulers.from { obj: Runnable -> obj.run() }
RxJavaPlugins.setNewThreadSchedulerHandler { synchronousScheduler }
RxAndroidPlugins.setInitMainThreadSchedulerHandler { synchronousScheduler }
}
@Before
fun before() {
`when`(mockContext.applicationContext).thenReturn(mockContext)
mockWebServer = MockWebServer()
ApiProvider.url = mockWebServer.url("/")
val database = SearchDatabase.getDatabase(mockContext)
placesViewModel = PlacesViewModel(database.searchDao())
}
@After
fun after() {
mockWebServer.shutdown()
RxJavaPlugins.reset()
RxAndroidPlugins.reset()
}
@Test
fun autocompletePlacesRequestTest() {
mockWebServer.enqueue(
MockResponse()
.setResponseCode(HttpURLConnection.HTTP_OK)
.setBody(JsonReader.readDataFromJsonFile("autocomplete.json")))
placesViewModel.autocompletePlacesRequest("place")
Assert.assertEquals(placesViewModel.getAutocompleteStatus().value, Status.DONE)
Assert.assertEquals(placesViewModel.isEmpty(), false)
Assert.assertEquals(placesViewModel.getLoadFromHistory(), false)
Assert.assertEquals(placesViewModel.getAutocompletePlaces().count(), 5)
val place = placesViewModel.getAutocompletePlaces()[0]
Assert.assertEquals(place.placeId, "ChIJtRkkqIKyCVMRno6bQJpHqbA")
Assert.assertEquals(place.description, "Alberta, Canada")
Assert.assertEquals(place.structuredFormatting.mainText, "Alberta")
}
@Test
fun placeDetailRequestTest() {
mockWebServer.enqueue(
MockResponse()
.setResponseCode(HttpURLConnection.HTTP_OK)
.setBody(JsonReader.readDataFromJsonFile("detail.json")))
val place = AutocompletePlace("id", "description",
AutocompleteFormat("mainText", "secondaryText"))
placesViewModel.placeDetailRequest(place)
Assert.assertEquals(placesViewModel.getDetailStatus().value, Status.DONE)
val detail = placesViewModel.getPlaceDetail()
Assert.assertEquals(detail.name, "Alberta")
Assert.assertEquals(detail.formattedAddress, "Alberta, Canada")
}
@Test
fun autocompletePlacesRequestErrorTest() {
mockWebServer.enqueue(
MockResponse()
.setResponseCode(HttpURLConnection.HTTP_BAD_REQUEST)
.setBody(JsonReader.readDataFromJsonFile("autocomplete.json")))
placesViewModel.autocompletePlacesRequest("place")
Assert.assertEquals(placesViewModel.getAutocompleteStatus().value, Status.ERROR)
Assert.assertEquals(placesViewModel.isEmpty(), true)
}
@Test
fun placeDetailRequestErrorTest() {
mockWebServer.enqueue(
MockResponse()
.setResponseCode(HttpURLConnection.HTTP_BAD_REQUEST)
.setBody(JsonReader.readDataFromJsonFile("detail.json")))
val place = AutocompletePlace("id", "description",
AutocompleteFormat("mainText", "secondaryText"))
placesViewModel.placeDetailRequest(place)
Assert.assertEquals(placesViewModel.getDetailStatus().value, Status.ERROR)
}
}
| 0
|
Kotlin
|
0
| 0
|
3de4c6abf062938317c704e70c07d9b0b5b16520
| 4,484
|
KotlinMapsApp
|
MIT License
|
src/test/kotlin/no/nav/helse/testdata/LocalApp.kt
|
navikt
| 232,072,714
| false
|
{"TypeScript": 97487, "CSS": 14146, "Shell": 4901, "JavaScript": 947, "HTML": 717, "Dockerfile": 193}
|
package no.nav.helse.testdata
import io.ktor.server.application.Application
import io.ktor.server.engine.embeddedServer
import io.ktor.server.engine.stop
import io.ktor.server.netty.Netty
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.*
import no.nav.helse.rapids_rivers.RapidsConnection
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import java.time.LocalDate
import java.time.YearMonth
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
fun main() {
val rapidsConnection = TestRapid()
val inntektRestClientMock = mockk<InntektRestClient> {
every { runBlocking { hentInntektsliste(any(), any(), any(), any(), any()) } }.returns(
Result.Ok(
(1..12).map {
Måned(
YearMonth.of(2019, it), listOf(
Inntekt(30000.0, Inntektstype.LOENNSINNTEKT, "123456789"),
Inntekt(30000.0, Inntektstype.LOENNSINNTEKT, "987654321")
)
)
}
)
)
}
val aaregClient = mockk<AaregClient> {
every {
runBlocking { hentArbeidsforhold(any(), any()) }
} returns listOf(
AaregArbeidsforhold(
type = Arbeidsforholdkode.ORDINÆRT,
arbeidssted = Arbeidssted(Arbeidsstedtype.Underenhet, listOf(Ident(Identtype.ORGANISASJONSNUMMER, "111111111"))),
ansettelsesperiode = Ansettelsesperiode(LocalDate.EPOCH, null),
ansettelsesdetaljer = listOf(
Ansettelsesdetaljer(100, Yrke("10000", "UTVIKLER"), Ansettelseform("fast", "Fast stilling"), Rapporteringsmåneder(YearMonth.of(1970, 1), null))
)
)
)
}
val eregClient = mockk<EregClient>() {
every {
runBlocking { hentOrganisasjon(any(), any()) }
} returns EregResponse("Testnavn", emptyList())
}
val pdlClient = mockk<PdlClient>() {
every {
runBlocking { hentNavn(any(), any()) }
} returns objectMapper.readTree("""{
"data": {
"hentPerson": {
"navn": [
{
"fornavn": "NORMAL",
"mellomnavn": null,
"etternavn": "MUFFINS"
}
]
}
}
}""")
}
val rapidsMediator = RapidsMediator(rapidsConnection)
LocalApplicationBuilder(
subscriptionService = LocalSubscriptionService,
inntektRestClient = inntektRestClientMock,
aaregClient = aaregClient,
eregClient = eregClient,
pdlClient = pdlClient,
rapidsMediator = rapidsMediator,
).start()
}
internal class LocalApplicationBuilder(
private val subscriptionService: SubscriptionService,
private val inntektRestClient: InntektRestClient,
private val aaregClient: AaregClient,
private val eregClient: EregClient,
private val pdlClient: PdlClient,
private val rapidsMediator: RapidsMediator,
) : RapidsConnection.StatusListener {
fun start() = runLocalServer {
installKtorModule(
subscriptionService = subscriptionService,
inntektRestClient = inntektRestClient,
aaregClient = aaregClient,
eregClient = eregClient,
pdlClient = pdlClient,
rapidsMediator = rapidsMediator,
)
}
}
internal fun runLocalServer(applicationBlock: Application.() -> Unit) {
val applicationContext = Executors.newFixedThreadPool(4).asCoroutineDispatcher()
val exceptionHandler = CoroutineExceptionHandler { context, e ->
log.error("Feil i lytter", e)
context.cancel(CancellationException("Feil i lytter", e))
}
runBlocking(exceptionHandler + applicationContext) {
val port = 8080
log.info("Starter backend på port $port")
val server = embeddedServer(Netty, port) {
applicationBlock()
}.start(wait = false)
Runtime.getRuntime().addShutdownHook(Thread {
server.stop(10, 10, TimeUnit.SECONDS)
applicationContext.close()
})
}
}
| 0
|
TypeScript
|
0
| 0
|
8b1141e37e9ee6b7f412abb1f4215d95ebe9abb5
| 4,206
|
helse-spleis-testdata
|
MIT License
|
app/src/main/java/com/foobarust/android/rating/RatingViewModel.kt
|
foobar-UST
| 285,792,732
| false
| null |
package com.foobarust.android.rating
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.foobarust.domain.models.order.OrderDetail
import com.foobarust.domain.models.order.OrderRating
import com.foobarust.domain.states.Resource
import com.foobarust.domain.usecases.order.GetOrderDetailUseCase
import com.foobarust.domain.usecases.order.SubmitOrderRatingUseCase
import com.foobarust.domain.utils.cancelIfActive
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Created by kevin on 2/24/21
*/
@HiltViewModel
class RatingViewModel @Inject constructor(
private val getOrderDetailUseCase: GetOrderDetailUseCase,
private val submitOrderRatingUseCase: SubmitOrderRatingUseCase
) : ViewModel() {
private var _orderDetail = MutableStateFlow<OrderDetail?>(null)
val orderDetail: StateFlow<OrderDetail?> = _orderDetail.asStateFlow()
private val _ratingUiLoadState = MutableStateFlow<RatingUiState>(RatingUiState.Loading)
val ratingUiLoadState: StateFlow<RatingUiState> = _ratingUiLoadState.asStateFlow()
private val _ratingUiSubmitState = MutableStateFlow<RatingUiState?>(null)
val ratingUiSubmitState: SharedFlow<RatingUiState?> = _ratingUiSubmitState.asSharedFlow()
private val _ratingCompleted = Channel<Unit>()
val ratingCompleted: Flow<Unit> = _ratingCompleted.receiveAsFlow()
private val _currentDestination = MutableStateFlow(-1)
private var fetchOrderDetailJob: Job? = null
var orderRatingInput: Int? = null
var deliveryRatingInput: Boolean? = null
var commentInput: String? = null
fun onFetchOrderDetail(orderId: String) {
fetchOrderDetailJob?.cancelIfActive()
fetchOrderDetailJob = viewModelScope.launch {
getOrderDetailUseCase(orderId).collect {
when (it) {
is Resource.Success -> {
_orderDetail.value = it.data
_ratingUiLoadState.value = RatingUiState.Success
}
is Resource.Error -> {
_ratingUiLoadState.value = RatingUiState.Error(it.message)
}
is Resource.Loading -> {
_ratingUiLoadState.value = RatingUiState.Loading
}
}
}
}
}
fun onUpdateOrderRating(rating: Int) {
orderRatingInput = rating
}
fun onUpdateDeliveryRating(rating: Boolean) {
deliveryRatingInput = rating
}
fun onUpdateComment(comment: String?) {
commentInput = comment
}
fun onSubmitRating() = viewModelScope.launch {
val orderDetail = _orderDetail.value ?: return@launch
orderRatingInput?.let { rating ->
val orderRating = OrderRating(
orderId = orderDetail.id,
orderRating = rating,
deliveryRating = deliveryRatingInput,
comment = commentInput
)
submitOrderRatingUseCase(orderRating).collect {
_ratingUiSubmitState.value = when (it) {
is Resource.Success -> RatingUiState.Success
is Resource.Error -> RatingUiState.Error(it.message)
is Resource.Loading -> RatingUiState.Loading
}
}
}
}
fun onUpdateCurrentDestination(destinationId: Int) {
_currentDestination.value = destinationId
}
fun onCompleteRating() {
_ratingCompleted.offer(Unit)
}
}
sealed class RatingUiState {
object Success : RatingUiState()
data class Error(val message: String?) : RatingUiState()
object Loading : RatingUiState()
}
| 0
|
Kotlin
|
2
| 2
|
b4358ef0323a0b7a95483223496164e616a01da5
| 3,887
|
foobar-android
|
MIT License
|
back-end/src/authentication/auth/AuthenticationService.kt
|
SrGaabriel
| 312,651,398
| false
| null |
package com.gabriel.kspanel.project.rest.authentication.auth
import com.gabriel.kspanel.project.rest.authentication.auth.entity.Authentication
import com.gabriel.kspanel.project.rest.services.AccountService
import io.ktor.http.*
class AuthenticationService(private val accountService: AccountService) {
suspend fun handle(authentication: Authentication): HttpStatusCode {
val account = accountService.findById(authentication.id)
val password = account?.password ?: HttpStatusCode.NotFound
return if (password.toString() != authentication.password)
HttpStatusCode.Unauthorized
else HttpStatusCode.Accepted
}
}
| 0
|
Kotlin
|
0
| 2
|
d67b3dda809b5b73a29f4fc754a69559eaac2bc4
| 665
|
ksp
|
MIT License
|
src/main/kotlin/com/github/ake2255/jean/services/MyApplicationService.kt
|
ake2255
| 508,367,610
| false
| null |
package com.github.ake2255.jean.services
import com.github.ake2255.jean.MyBundle
class MyApplicationService {
init {
println(MyBundle.message("applicationService"))
}
}
| 7
|
Kotlin
|
0
| 0
|
50d20c42cbcebe065c1834f697ef4e1ee948d6d7
| 188
|
jean
|
Apache License 2.0
|
app/src/main/java/com/ihfazh/simpleattendanceexample/ui/home/HomeFragment.kt
|
ihfazhillah
| 377,525,659
| false
| null |
package com.ihfazh.simpleattendanceexample.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupMenu
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.ihfazh.simpleattendanceexample.R
import com.ihfazh.simpleattendanceexample.databinding.FragmentHomeBinding
class HomeFragment: Fragment() {
private var _binding: FragmentHomeBinding? = null
private val binding
get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.buttonMore.setOnClickListener {
openMoreMenu(it)
}
binding.eventsCard.setOnClickListener {
Toast.makeText(requireContext(), "Events Card Clicked", Toast.LENGTH_SHORT).show()
}
binding.studentsCard.setOnClickListener {
Toast.makeText(requireContext(), "Students Card Clicked", Toast.LENGTH_SHORT).show()
}
}
private fun openMoreMenu(view: View) {
PopupMenu(requireContext(), view).apply {
inflate(R.menu.more_button)
setOnMenuItemClickListener { menuItem ->
when(menuItem.itemId){
R.id.menu_event -> {
Toast.makeText(requireContext(), "Create event menu clicked", Toast.LENGTH_SHORT).show()
}
R.id.menu_student -> {
val destination = HomeFragmentDirections.homeToStudentView()
findNavController().navigate(destination)
}
}
true
}
show()
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
bf5698641461ae8f4a0ef80d1fbf34a2c8b17d8b
| 2,169
|
Simple-Attendance-Example
|
MIT License
|
app/src/main/java/se/umu/ad/anpa0292/voxelsculpter/World.kt
|
tehAndrew
| 850,690,052
| false
|
{"Kotlin": 32061, "GLSL": 1629}
|
package se.umu.ad.anpa0292.voxelsculpter
import kotlin.math.max
import kotlin.math.min
data class Ray(val origin: Vector3D, val direction: Vector3D) {
val invDirection = Vector3D(1 / direction.x, 1 / direction.y, 1 / direction.z)
}
data class AABB(val min: Vector3D, val max: Vector3D)
class World(viewportWidth: Int, viewportHeight: Int) {
val camera: PerspectiveCamera = PerspectiveCamera(
Vector3D(0f, 0f, 0f),
60f,
viewportWidth, viewportHeight
)
val voxels = arrayOf(
Voxel(Vector3D(0f, 0f, 0f)),
Voxel(Vector3D(1f, 0f, 0f)),
Voxel(Vector3D(-1f, 0f, 0f)),
Voxel(Vector3D(0f, -1f, 0f)),
Voxel(Vector3D(0f, 1f, 0f)),
Voxel(Vector3D(0f, 0f, -1f)),
Voxel(Vector3D(0f, 0f, 1f))
)
var selectedVoxel = voxels[0]
fun getVoxelAtScreenPos(screenPos: Vector3D) {
val ray = camera.screenPosToWorldRay(screenPos)
val tVals = mutableListOf<Pair<Float, Voxel>>()
for (voxel in voxels) {
val aabb = calculateVoxelAABB(voxel)
intersectRayAABB(ray, aabb)?.let {
tVals.add(it to voxel)
}
}
if (tVals.isNotEmpty()) {
val (value, voxel) = tVals.minBy { it.first }
selectedVoxel = voxel
}
}
// Uses the fast branchless check here: https://tavianator.com/2015/ray_box_nan.html
private fun intersectRayAABB(ray: Ray, aabb: AABB): Float? {
var tmin = Float.NEGATIVE_INFINITY
var tmax = Float.POSITIVE_INFINITY
for (i in 0 until 3) {
val t1 = (aabb.min[i] - ray.origin[i]) * ray.invDirection[i]
val t2 = (aabb.max[i] - ray.origin[i]) * ray.invDirection[i]
tmin = max(tmin, min(t1, t2))
tmax = min(tmin, max(t1, t2))
}
val isIntersecting = tmax > maxOf(tmin, 0f)
return if (isIntersecting) tmin else null
}
private fun calculateVoxelAABB(voxel: Voxel): AABB {
val center = voxel.pos
val halfSideVec = Vector3D(Voxel.HALF_SIDE, Voxel.HALF_SIDE, Voxel.HALF_SIDE)
return AABB(
center - halfSideVec,
center + halfSideVec
)
}
}
| 0
|
Kotlin
|
0
| 0
|
b0b35a8fa92cbf07415a14f248466354d5855c5d
| 2,219
|
VoxelSculpter
|
MIT License
|
solar/src/main/java/com/chiksmedina/solar/outline/essentionalui/Help.kt
|
CMFerrer
| 689,442,321
| false
|
{"Kotlin": 36591890}
|
package com.chiksmedina.solar.outline.essentionalui
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.outline.EssentionalUiGroup
val EssentionalUiGroup.Help: ImageVector
get() {
if (_help != null) {
return _help!!
}
_help = Builder(
name = "Help", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(12.0f, 1.25f)
curveTo(6.0629f, 1.25f, 1.25f, 6.0629f, 1.25f, 12.0f)
curveTo(1.25f, 17.9371f, 6.0629f, 22.75f, 12.0f, 22.75f)
curveTo(17.9371f, 22.75f, 22.75f, 17.9371f, 22.75f, 12.0f)
curveTo(22.75f, 6.0629f, 17.9371f, 1.25f, 12.0f, 1.25f)
close()
moveTo(2.75f, 12.0f)
curveTo(2.75f, 9.7157f, 3.578f, 7.6248f, 4.9503f, 6.011f)
lineTo(8.1528f, 9.2135f)
curveTo(7.5849f, 9.9962f, 7.25f, 10.959f, 7.25f, 12.0f)
curveTo(7.25f, 13.041f, 7.5849f, 14.0038f, 8.1528f, 14.7865f)
lineTo(4.9503f, 17.989f)
curveTo(3.578f, 16.3753f, 2.75f, 14.2843f, 2.75f, 12.0f)
close()
moveTo(9.2135f, 8.1528f)
lineTo(6.011f, 4.9503f)
curveTo(7.6248f, 3.578f, 9.7157f, 2.75f, 12.0f, 2.75f)
curveTo(14.2843f, 2.75f, 16.3753f, 3.578f, 17.989f, 4.9503f)
lineTo(14.7865f, 8.1528f)
curveTo(14.0038f, 7.5849f, 13.041f, 7.25f, 12.0f, 7.25f)
curveTo(10.959f, 7.25f, 9.9962f, 7.5849f, 9.2135f, 8.1528f)
close()
moveTo(6.011f, 19.0497f)
curveTo(7.6247f, 20.422f, 9.7157f, 21.25f, 12.0f, 21.25f)
curveTo(14.2843f, 21.25f, 16.3753f, 20.422f, 17.989f, 19.0497f)
lineTo(14.7865f, 15.8472f)
curveTo(14.0038f, 16.4151f, 13.041f, 16.75f, 12.0f, 16.75f)
curveTo(10.959f, 16.75f, 9.9962f, 16.4151f, 9.2135f, 15.8472f)
lineTo(6.011f, 19.0497f)
close()
moveTo(15.8472f, 14.7865f)
lineTo(19.0497f, 17.989f)
curveTo(20.422f, 16.3753f, 21.25f, 14.2843f, 21.25f, 12.0f)
curveTo(21.25f, 9.7157f, 20.422f, 7.6248f, 19.0497f, 6.011f)
lineTo(15.8472f, 9.2135f)
curveTo(16.4151f, 9.9962f, 16.75f, 10.959f, 16.75f, 12.0f)
curveTo(16.75f, 13.041f, 16.4151f, 14.0038f, 15.8472f, 14.7865f)
close()
moveTo(8.75f, 12.0f)
curveTo(8.75f, 10.2051f, 10.2051f, 8.75f, 12.0f, 8.75f)
curveTo(13.7949f, 8.75f, 15.25f, 10.2051f, 15.25f, 12.0f)
curveTo(15.25f, 13.7949f, 13.7949f, 15.25f, 12.0f, 15.25f)
curveTo(10.2051f, 15.25f, 8.75f, 13.7949f, 8.75f, 12.0f)
close()
}
}
.build()
return _help!!
}
private var _help: ImageVector? = null
| 0
|
Kotlin
|
0
| 0
|
3414a20650d644afac2581ad87a8525971222678
| 3,761
|
SolarIconSetAndroid
|
MIT License
|
puzzles/src/test/kotlin/com/kotlinground/puzzles/search/binarysearch/successfulpairsspellspotions/SuccessfulPairsTest.kt
|
BrianLusina
| 113,182,832
| false
|
{"Kotlin": 472727, "Shell": 7283, "Python": 1725}
|
package com.kotlinground.puzzles.search.binarysearch.successfulpairsspellspotions
import org.junit.jupiter.api.Test
import kotlin.test.assertContentEquals
class SuccessfulPairsTest {
@Test
fun `spells = (5,1,3), potions = (1,2,3,4,5), success = 7 should return (4,0,3)`() {
val spells = intArrayOf(5, 1, 3)
val potions = intArrayOf(1, 2, 3, 4, 5)
val success = 7L
val expected = intArrayOf(4, 0, 3)
val actual = successfulPairs(spells, potions, success)
assertContentEquals(expected, actual)
}
@Test
fun `spells = (3, 1, 2), potions = (8,5,8), success = 16 should return (2,0,2)`() {
val spells = intArrayOf(3, 1, 1)
val potions = intArrayOf(8, 5, 8)
val success = 16L
val expected = intArrayOf(2, 0, 2)
val actual = successfulPairs(spells, potions, success)
assertContentEquals(expected, actual)
}
}
class SuccessfulPairs2Test {
@Test
fun `spells = (5,1,3), potions = (1,2,3,4,5), success = 7 should return (4,0,3)`() {
val spells = intArrayOf(5, 1, 3)
val potions = intArrayOf(1, 2, 3, 4, 5)
val success = 7L
val expected = intArrayOf(4, 0, 3)
val actual = successfulPairs2(spells, potions, success)
assertContentEquals(expected, actual)
}
@Test
fun `spells = (3, 1, 2), potions = (8,5,8), success = 16 should return (2,0,2)`() {
val spells = intArrayOf(3, 1, 2)
val potions = intArrayOf(8, 5, 8)
val success = 16L
val expected = intArrayOf(2, 0, 2)
val actual = successfulPairs2(spells, potions, success)
assertContentEquals(expected, actual)
}
}
| 1
|
Kotlin
|
1
| 0
|
b014649c5647442bbbc4d2060cca86c45af40917
| 1,695
|
KotlinGround
|
MIT License
|
app/src/main/java/org/freeandroidtools/trendinggithub/model/GithubRepo.kt
|
surengrig
| 122,894,253
| false
| null |
package org.freeandroidtools.trendinggithub.model
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverter
import com.google.gson.annotations.SerializedName
import java.util.Date
data class SearchResult(
@SerializedName("items") val repos: List<GithubRepo>
)
@Entity(tableName = "starredRepo")
class StarredRepo : BaseRepo()
@Entity(tableName = "repo")
class GithubRepo : BaseRepo()
open class BaseRepo(
@PrimaryKey
var id: String = "",
var name: String = "",
var fullName: String = "",
var private: Boolean = false,
var htmlUrl: String = "", // "https://github.com/hmkcode/Android",
var description: String? = "", // "Android related examples",
var fork: Boolean = false,
var url: String = "", // "https://api.github.com/repos/hmkcode/Android",
var forksUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/forks",
var keysUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/keys{/keyId}",
var collaboratorsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/collaborators{/collaborator}",
var teamsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/teams",
var hooksUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/hooks",
var issueEventsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/issues/events{/number}",
var eventsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/events",
var assigneesUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/assignees{/user}",
var branchesUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/branches{/branch}",
var tagsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/tags",
var blobsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/git/blobs{/sha}",
var gitTagsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/git/tags{/sha}",
var gitRefsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/git/refs{/sha}",
var treesUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/git/trees{/sha}",
var statusesUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/statuses/{sha}",
var languagesUrl: String? = "", // "https://api.github.com/repos/hmkcode/Android/languages",
var stargazersUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/stargazers",
var contributorsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/contributors",
var subscribersUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/subscribers",
var subscriptionUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/subscription",
var commitsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/commits{/sha}",
var gitCommitsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/git/commits{/sha}",
var commentsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/comments{/number}",
var issueCommentUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/issues/comments{/number}",
var contentsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/contents/{+path}",
var compareUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/compare/{base}...{head}",
var mergesUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/merges",
var archiveUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/{archiveFormat}{/ref}",
var downloadsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/downloads",
var issuesUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/issues{/number}",
var pullsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/pulls{/number}",
var milestonesUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/milestones{/number}",
var notificationsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/notifications{?since,all,participating}",
var labelsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/labels{/name}",
var releasesUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/releases{/id}",
var deploymentsUrl: String = "", // "https://api.github.com/repos/hmkcode/Android/deployments",
var createdAt: Date? = null, //:"2013-09-02T16:12:28Z",
var updatedAt: Date? = null, //:"2018-02-23T10:56:14Z",
var pushedAt: Date? = null, //:"2017-12-22T20:53:43Z",
var gitUrl: String = "", // "git://github.com/hmkcode/Android.git",
var sshUrl: String = "", // "git@github.com:hmkcode/Android.git",
var cloneUrl: String = "", // "https://github.com/hmkcode/Android.git",
var svnUrl: String = "", // "https://github.com/hmkcode/Android",
var homepage: String? = null,
var size: Int = 0,
var stargazersCount: Int = 0,
var watchersCount: Int = 0,
var language: String? = "Java",
var hasIssues: Boolean = true,
var hasProjects: Boolean = true,
var hasDownloads: Boolean = true,
var hasWiki: Boolean = true,
var hasPages: Boolean = false,
var forksCount: Int = 0,
var mirrorUrl: String? = "",
var archived: Boolean = false,
var openIssuesCount: Int = 0,
// @SerializedName("license") val license: String, //:null,
var forks: Int = 0,
var openIssues: Int = 0,
var watchers: Int = 0,
var defaultBranch: String = "",
var score: Double = 0.0,
@Embedded(prefix = "owner_")
var owner: Owner = Owner()
)
data class Owner(
var login: String = "", //"hmkcode",
var id: String = "", //3790597,
var avatarUrl: String = "", //"https://avatars3.githubusercontent.com/u/3790597?v=4",
var gravatarId: String = "", //"",
var url: String = "", //"https://api.github.com/users/hmkcode",
var htmlUrl: String = "", //"https://github.com/hmkcode",
var followersUrl: String = "", //"https://api.github.com/users/hmkcode/followers",
var followingUrl: String = "", //"https://api.github.com/users/hmkcode/following{/otherUser}",
var gistsUrl: String = "", //"https://api.github.com/users/hmkcode/gists{/gistId}",
var starredUrl: String = "", //"https://api.github.com/users/hmkcode/starred{/owner}{/repo}",
var subscriptionsUrl: String = "", //"https://api.github.com/users/hmkcode/subscriptions",
var organizationsUrl: String = "", //"https://api.github.com/users/hmkcode/orgs",
var reposUrl: String = "", //"https://api.github.com/users/hmkcode/repos",
var eventsUrl: String = "", //"https://api.github.com/users/hmkcode/events{/privacy}",
var receivedEventsUrl: String = "" //"https://api.github.com/users/hmkcode/receivedEvents",
)
class DateConverter {
@TypeConverter
fun toDate(timestamp: Long?): Date? {
return if (timestamp == null) null else Date(timestamp)
}
@TypeConverter
fun toTimestamp(date: Date?): Long? {
return date?.time
}
}
| 3
|
Kotlin
|
0
| 0
|
2dd85880f5f050dd50f95f631a8a4c8d2c10720b
| 7,206
|
github_trending
|
Apache License 2.0
|
app/src/main/java/com/example/al4t_claco/model/Activity.kt
|
nsamelson
| 414,991,130
| false
|
{"Kotlin": 51217}
|
package com.example.al4t_claco.model
import java.io.Serializable
class Activity (name: String, code: String, teachers: List<String> , description :String): Serializable{
val name = name
val code = code
val teachers = teachers
lateinit var resources: List<File>
var description = description
//var Events: List<Event> = // TODO: an activity has events (implement if calendar API works like that)
}
| 0
|
Kotlin
|
4
| 1
|
f1a96b709dbdcbcfc68816c273891392f82f5f46
| 426
|
AL4T_Claco
|
MIT License
|
sms-persistence/src/main/kotlin/team/msg/sms/persistence/authentication/repository/AuthenticationFieldJpaRepository.kt
|
GSM-MSG
| 625,717,097
| false
|
{"Kotlin": 474594, "Shell": 1480, "Dockerfile": 288}
|
package team.msg.sms.persistence.authentication.repository
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
import team.msg.sms.persistence.authentication.entity.AuthenticationFieldJpaEntity
import java.util.UUID
@Repository
interface AuthenticationFieldJpaRepository: CrudRepository<AuthenticationFieldJpaEntity, UUID> {
fun findAllBySectionId(sectionId: UUID): List<AuthenticationFieldJpaEntity>
}
| 7
|
Kotlin
|
0
| 9
|
beeb18cce9264bdeab081717b23a22ed2ac4a31f
| 463
|
SMS-BackEnd
|
MIT License
|
src/test/kotlin/com/asdacap/ea4k/gp/Utils.kt
|
asdacap
| 338,637,903
| false
| null |
package com.asdacap.ea4k.gp
import com.fasterxml.jackson.databind.ObjectMapper
import org.junit.jupiter.api.Assertions.assertTrue
fun <R> testCommonNodeBehaviour(factory: TreeNodeFactory<R>, sampleChildren: List<TreeNode<*>>) {
val node = factory.createNode(sampleChildren)
val cloned = factory.createNode(node.children, node.state)
assertTrue(node.isSubtreeEffectivelySame(cloned))
}
| 0
|
Kotlin
|
0
| 1
|
2e941fb84eda944aa5d838deb92ec5c95ba96bd3
| 400
|
ea4k
|
MIT License
|
KotlinMail/ordercenter/src/main/java/cn/xwj/order/data/repository/OrderRepository.kt
|
jxiaow
| 123,389,640
| false
|
{"Java": 270055, "Kotlin": 243645}
|
package cn.xwj.order.data.repository
import cn.xwj.baselibrary.data.net.RetrofitFactory
import cn.xwj.baselibrary.ext.convert
import cn.xwj.baselibrary.ext.convertBoolean
import cn.xwj.order.data.api.OrderApi
import cn.xwj.order.data.protocol.*
import io.reactivex.Observable
import javax.inject.Inject
/**
* Author: xw
* Date: 2018-06-06 15:52:13
* Description: OrderRepository: .
*/
class OrderRepository @Inject constructor() : OrderDataSource {
override fun getOrderById(orderId: Int): Observable<Order> {
return RetrofitFactory.instance.create(OrderApi::class.java)
.getOrderById(GetOrderByIdReq(orderId))
.convert()
}
override fun submitOrder(order: Order): Observable<Boolean> {
return RetrofitFactory.instance.create(OrderApi::class.java)
.submitOrder(SubmitOrderReq(order))
.convertBoolean()
}
override fun getOrderList(orderStatus: Int): Observable<MutableList<Order>?> {
return RetrofitFactory.instance.create(OrderApi::class.java)
.getOrderList(GetOrderListReq(orderStatus))
.convert()
}
override fun cancelOrder(orderId: Int): Observable<Boolean> {
return RetrofitFactory.instance.create(OrderApi::class.java)
.cancelOrder(CancelOrderReq(orderId))
.convertBoolean()
}
override fun confirmOrder(orderId: Int): Observable<Boolean> {
return RetrofitFactory.instance.create(OrderApi::class.java)
.confirmOrder(ConfirmOrderReq(orderId))
.convertBoolean()
}
}
| 1
| null |
1
| 1
|
2796496ebb7d279ad0f405102c107db9085545e7
| 1,616
|
AndroidProjectStudio
|
Apache License 2.0
|
slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/VideoBlockBuilder.kt
|
slackapi
| 62,449,869
| false
|
{"Java": 6165956, "Kotlin": 361122, "Shell": 7287, "Batchfile": 3120, "Dockerfile": 249}
|
package com.slack.api.model.kotlin_extension.block
import com.slack.api.model.block.VideoBlock
import com.slack.api.model.block.composition.PlainTextObject
import com.slack.api.model.kotlin_extension.block.composition.container.SinglePlainTextObjectContainer
import com.slack.api.model.kotlin_extension.block.composition.dsl.PlainTextObjectDsl
// same name with the object + "Builder" suffix
@BlockLayoutBuilder
class VideoBlockBuilder : Builder<VideoBlock> {
private var _blockId: String? = null
private var _title: PlainTextObject? = null
private var _titleUrl: String? = null
private var _description: PlainTextObject? = null
private var _altText: String? = null
private var _videoUrl: String? = null
private var _thumbnailUrl: String? = null
private var _authorName: String? = null
private var _providerName: String? = null
private var _providerIconUrl: String? = null
/**
* A string acting as a unique identifier for a block. You can use this block_id when you receive an interaction
* payload to identify the source of the action. If not specified, one will be generated. Maximum length for
* this field is 255 characters. block_id should be unique for each message and each iteration of a message.
* If a message is updated, use a new block_id.
*
* @see <a href="https://api.slack.com/reference/block-kit/blocks#video">Section Block Documentation</a>
*/
fun blockId(blockId: String) {
_blockId = blockId
}
fun title(title: PlainTextObject) {
_title = title
}
fun title(builder: PlainTextObjectDsl.() -> Unit) {
_title = SinglePlainTextObjectContainer().apply(builder).underlying
}
fun titleUrl(titleUrl: String) {
_titleUrl = titleUrl
}
fun description(description: PlainTextObject) {
_description = description
}
fun description(builder: PlainTextObjectDsl.() -> Unit) {
_description = SinglePlainTextObjectContainer().apply(builder).underlying
}
fun altText(altText: String) {
_altText = altText
}
fun videoUrl(videoUrl: String) {
_videoUrl = videoUrl
}
fun thumbnailUrl(thumbnailUrl: String) {
_thumbnailUrl = thumbnailUrl
}
fun authorName(authorName: String) {
_authorName = authorName
}
fun providerName(providerName: String) {
_providerName = providerName
}
fun providerIconUrl(providerIconUrl: String) {
_providerIconUrl = providerIconUrl
}
override fun build(): VideoBlock {
return VideoBlock.builder()
.blockId(_blockId)
.title(_title)
.titleUrl(_titleUrl)
.description(_description)
.altText(_altText)
.videoUrl(_videoUrl)
.thumbnailUrl(_thumbnailUrl)
.authorName(_authorName)
.providerName(_providerName)
.providerIconUrl(_providerIconUrl)
.build()
}
}
| 22
|
Java
|
214
| 577
|
52b04eb7ec1e97832d333e4ee96b7032b0203764
| 3,010
|
java-slack-sdk
|
MIT License
|
performance/src/main/java/io/github/xanderwang/performance/Utils.kt
|
xanderwang
| 255,372,682
| false
|
{"Java": 422257, "Kotlin": 108656}
|
package io.github.xanderwang.performance
/**
* 工具类
* @author xanderwang
*/
internal object Utils {
/** 完整类名白名单 */
private val ignoreClassWhiteSet = HashSet<String>()
/** 类名白名单,可能是完整类名,也可能是简单类名 */
private val ignoreClassWhiteList = ArrayList<String>()
init {
ignoreClassWhiteSet.add(BitmapTool::class.java.name)
ignoreClassWhiteSet.add(IPCTool::class.java.name)
ignoreClassWhiteSet.add(ThreadTool::class.java.name)
ignoreClassWhiteSet.add(UIBlockTool::class.java.name)
ignoreClassWhiteSet.add(Utils::class.java.name)
ignoreClassWhiteList.add(BitmapTool::class.java.name)
ignoreClassWhiteList.add(IPCTool::class.java.name)
ignoreClassWhiteList.add(ThreadTool::class.java.name)
ignoreClassWhiteList.add(UIBlockTool::class.java.name)
ignoreClassWhiteList.add("io.github.xanderwang.hook")
ignoreClassWhiteList.add("de.robv.android")
ignoreClassWhiteList.add("me.weishu.epic")
ignoreClassWhiteList.add("com.swift.sandhook")
ignoreClassWhiteList.add("SandHookerNew_")
}
/**
* 是否是应该忽略的 class
*
* @param className
* @return
*/
fun isIgnoreClass(className: String?): Boolean {
if (null == className) {
return false
}
if (!Config.FILTER_CLASS_NAME) {
return false
}
if (ignoreClassWhiteSet.contains(className)) {
return true
}
for (i in 0 until ignoreClassWhiteList.size) {
if (className.startsWith(ignoreClassWhiteList[i])) {
return true
}
}
return false
}
fun list(): List<String> {
val stackTraceElements = Throwable().stackTrace
return list(stackTraceElements)
}
fun list(thread: Thread): List<String> {
val stackTraceElements = thread.stackTrace
return list(stackTraceElements)
}
fun list(stackTraceElements: Array<StackTraceElement>): List<String> {
return stackTraceElements.strings()
}
}
internal fun Array<StackTraceElement>.strings(): List<String> {
val list: MutableList<String> = ArrayList(this.size)
val sb = StringBuilder()
this.forEach { element ->
element.string(sb, true)?.let {
list.add(it)
}
}
return list
}
internal fun StackTraceElement.string(stringBuilder: StringBuilder?, cleanCache: Boolean = true): String? {
val sb = stringBuilder ?: StringBuilder()
if (cleanCache && sb.isNotEmpty()) {
sb.delete(0, sb.length)
}
if (Utils.isIgnoreClass(className)) {
return null
}
sb
.append(className).append('.')
.append(methodName)
.append('(').append(fileName).append(':').append(lineNumber).append(')')
return sb.toString()
}
| 2
|
Java
|
44
| 294
|
d24f468283cc17ca5e841495c0c88e7f2ebe9c7d
| 2,847
|
performance
|
Apache License 2.0
|
app/src/main/java/com/telenav/osv/data/collector/datatype/datatypes/ClientAppNameObject.kt
|
kartaview
| 63,806,526
| false
| null |
package com.telenav.osv.data.collector.datatype.datatypes
import com.telenav.osv.data.collector.datatype.util.LibraryUtil
/**
* Class used for returning the name of this application's package.
*/
class ClientAppNameObject(clientAppName: String?, statusCode: Int) : BaseObject<String?>(clientAppName, statusCode, LibraryUtil.CLIENT_APP_NAME) {
/**
* Returns client app name
* @return
*/
val clientAppName: String
get() = actualValue!!
init {
dataSource = LibraryUtil.PHONE_SOURCE
}
}
| 76
| null |
30
| 130
|
66eb0ee1ab093562e2867087084b26803fe58174
| 534
|
android
|
MIT License
|
compiler/testData/diagnostics/tests/scopes/variantProjections/interdependentStarProjections.kt
|
JetBrains
| 3,432,266
| false
| null |
// ISSUE: KT-54764
interface A<out T : B<F, E>, F, out E : B<T, F>> {
fun copy(t: @UnsafeVariance T, f: F, e: @UnsafeVariance E): A<T, F, E>
}
interface B<out X, out Y>
fun foo(a: A<*, String, B<*, String>>, b1: B<*, String>, b2: B<*, *>, b3: B<String, B<*, String>>) {
<!DEBUG_INFO_EXPRESSION_TYPE("A<B<*, *>, kotlin.String, B<kotlin.Any?, kotlin.String>>")!>a.copy(b2, "", b1)<!>
<!DEBUG_INFO_EXPRESSION_TYPE("A<B<*, *>, kotlin.String, B<kotlin.Any?, kotlin.String>>")!>a.copy(b1, "", b1)<!>
<!DEBUG_INFO_EXPRESSION_TYPE("A<B<*, *>, kotlin.String, B<kotlin.Any?, kotlin.String>>")!>a.copy(b3, "", b1)<!>
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 627
|
kotlin
|
Apache License 2.0
|
mobile_app1/module994/src/main/java/module994packageKt0/Foo369.kt
|
uber-common
| 294,831,672
| false
| null |
package module994packageKt0;
annotation class Foo369Fancy
@Foo369Fancy
class Foo369 {
fun foo0(){
module994packageKt0.Foo368().foo3()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
}
| 6
|
Java
|
6
| 72
|
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
| 237
|
android-build-eval
|
Apache License 2.0
|
app/src/main/java/com/smlnskgmail/jaman/cryptotracker/model/api/currency/CurrencyApi.kt
|
alirezanazari
| 245,361,832
| true
|
{"Gradle": 6, "INI": 2, "Markdown": 4, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "XML": 45, "Kotlin": 47, "JSON": 2, "Java": 1}
|
package com.smlnskgmail.jaman.cryptotracker.model.api.currency
interface CurrencyApi {
fun currencies(
currenciesLoadResult: CurrenciesLoadResult
)
fun currencyListing(
currency: Currency,
currencyListingLoadResult: CurrencyListingLoadResult
)
interface CurrenciesLoadResult {
fun loaded(
currencies: List<Currency>
)
}
interface CurrencyListingLoadResult {
fun loaded(
currencyListing: CurrencyListing?
)
}
}
| 0
|
Kotlin
|
0
| 1
|
11c890671cad36503c08978cd59afdf35154d24b
| 532
|
crypto-tracker
|
Apache License 2.0
|
libnavigation-copilot/src/main/java/com/mapbox/navigation/copilot/DriveEnds.kt
|
mapbox
| 87,455,763
| false
| null |
package com.mapbox.navigation.copilot
import androidx.annotation.Keep
@Keep
internal data class DriveEnds(
val type: String,
val realDuration: Long,
) : EventDTO
| 505
| null |
319
| 621
|
ad73c6011348cb9b24b92a369024ca06f48845ab
| 172
|
mapbox-navigation-android
|
Apache License 2.0
|
app/src/androidTest/java/com/gmail/fattazzo/meteo/data/RadarServiceTest.kt
|
fattazzo
| 182,333,126
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 278, "Kotlin": 219, "Java": 1, "JSON": 4}
|
/*
* Project: meteo
* File: RadarServiceTest.kt
*
* Created by fattazzo
* Copyright © 2019 Gianluca Fattarsi. All rights reserved.
*
* MIT License
* 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 com.gmail.fattazzo.meteo.data
import androidx.test.espresso.matcher.ViewMatchers.assertThat
import com.gmail.fattazzo.meteo.app.services.RadarService
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert
import org.hamcrest.Matchers
import org.junit.Test
import java.net.URL
/**
* @author fattazzo
* <p/>
* date: 11/10/19
*/
class RadarServiceTest {
@Test
fun checkDuplicatedId() {
val radarService = RadarService()
val radars = radarService.loadRadars()
val distinctIds = radars.map { it.id }.distinct()
assertThat(distinctIds.size, `is`(radars.size))
}
@Test
fun checkConnectionAvaliable() {
RadarService().loadRadars().forEach {
try {
val radarUrl = URL(it.url)
val connection = radarUrl.openConnection()
connection.connectTimeout = 30000
connection.connect()
println("Radar: ${it.title}. Connection OK")
} catch (e: Exception) {
MatcherAssert.assertThat("No connection for radar ${it.title}", false)
}
}
}
@Test
fun loadRadars() {
assertThat(RadarService().loadRadars().size, `is`(Matchers.greaterThan(0)))
}
}
| 1
| null |
1
| 1
|
8345a9a1b0d0dcb87922262c1691cd6ec8d058fc
| 2,526
|
meteo
|
MIT License
|
android-kotlin/idea-android/src/org/jetbrains/kotlin/android/wizard/AndroidSdkProviderImpl.kt
|
JetBrains
| 60,701,247
| false
|
{"Kotlin": 49550960, "Java": 35837871, "HTML": 1217714, "Starlark": 909188, "C++": 357481, "Python": 106384, "C": 71782, "Lex": 66732, "NSIS": 58538, "AIDL": 35382, "Shell": 26938, "CMake": 26798, "JavaScript": 18437, "Smali": 7580, "Batchfile": 6951, "RenderScript": 4411, "Makefile": 2495, "IDL": 269, "QMake": 18}
|
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.android.wizard
import com.android.tools.idea.welcome.config.FirstRunWizardMode
import com.android.tools.idea.welcome.install.getInitialSdkLocation
import org.jetbrains.kotlin.tools.projectWizard.plugins.AndroidSdkProvider
import java.nio.file.Path
class AndroidSdkProviderImpl : AndroidSdkProvider {
override fun getSdkPath(): Path {
return getInitialSdkLocation(FirstRunWizardMode.MISSING_SDK).toPath()
}
}
| 3
|
Kotlin
|
219
| 921
|
dbd9aeae0dc5b8c56ce2c7d51208ba26ea0f169b
| 567
|
android
|
Apache License 2.0
|
customwidgetpack/src/main/java/com/allenxuan/xuanyihuang/customwidgetpack/utils/DimensUtils.kt
|
allenxuan
| 164,084,792
| false
|
{"Java": 23744, "Kotlin": 10972}
|
package com.allenxuan.xuanyihuang.customwidgetpack.utils
import android.content.Context
object DimensUtils {
@JvmStatic
fun dip2pixel(context: Context, dpValue: Float): Int {
val scale = context.resources.displayMetrics.density
return (dpValue * scale + 0.5f).toInt()
}
@JvmStatic
fun pixel2dip(context: Context, pxValue: Float): Int {
val scale = context.resources.displayMetrics.density
return (pxValue / scale + 0.5f).toInt()
}
@JvmStatic
fun sp2pixel(context: Context, spValue: Float): Int {
val fontScale = context.resources.displayMetrics.scaledDensity
return (spValue * fontScale + 0.5f).toInt()
}
@JvmStatic
fun pixel2sp(context: Context, pxValue: Float): Int {
val fontScale = context.resources.displayMetrics.scaledDensity
return (pxValue / fontScale + 0.5f).toInt()
}
@JvmStatic
fun getStatusBarHeight(context: Context): Int {
var result = 0
val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
result = context.resources.getDimensionPixelSize(resourceId)
}
return result
}
}
| 1
| null |
1
| 1
|
b44cc4c0e86e38c1bb6d774d3b671a803641870d
| 1,227
|
CustomWidgetPack
|
Apache License 2.0
|
TestAndroidAll/src/main/java/com/lorenwang/test/android/activity/customView/video/VideoPlayActivity.kt
|
Loren-Wang
| 164,838,761
| false
|
{"Java": 3140552, "Kotlin": 581207, "JavaScript": 23273, "HTML": 1721, "CSS": 930}
|
package com.lorenwang.test.android.activity.customView.video
import android.os.Bundle
import android.os.PersistableBundle
import com.lorenwang.test.android.R
import com.lorenwang.test.android.base.BaseActivity
/**
* 功能作用:视频播放页面
* 创建时间:2021-01-20 4:14 下午
* 创建人:王亮(Loren)
* 思路:
* 方法:
* 注意:
* 修改人:
* 修改时间:
* 备注:
*
* @author 王亮(Loren)
*/
class VideoPlayActivity : BaseActivity() {
override fun setContentViewConfig(resId: Int?) {
super.setContentViewConfig(R.layout.item_custom_view_list_video_play)
}
override fun initData(savedInstanceState: Bundle?) {
super.initData(savedInstanceState)
// VideoPlayViewHolder(showContentView!!).setViewData(this,"https://vd4.bdstatic.com/mda-kk0nypaib3ih5tvz/sc/cae_h264_clips/1604218626/mda-kk0nypaib3ih5tvz.mp4?auth_key=1611204555-0-0-3a28571b930310122f39c1b033cd38f1&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=4_1-6_1",0)
}
override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
super.onSaveInstanceState(outState, outPersistentState)
}
}
| 5
|
Java
|
1
| 4
|
3669d165ef0b1667b37155978de4c1dd9660b903
| 1,091
|
LorenWangCustomTools
|
Apache License 2.0
|
compiler/daemon/src/org/jetbrains/kotlin/daemon/report/experimental/CompileServicesFacadeMessageCollector.kt
|
prasenjitghose36
| 258,198,392
| 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/LICENSE.txt file.
*/
package org.jetbrains.kotlin.daemon.report.experimental
import kotlinx.coroutines.*
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
import org.jetbrains.kotlin.daemon.KotlinCompileDaemon.log
import org.jetbrains.kotlin.daemon.common.CompilationOptions
import org.jetbrains.kotlin.daemon.common.ReportCategory
import org.jetbrains.kotlin.daemon.common.ReportSeverity
import org.jetbrains.kotlin.daemon.common.CompilerServicesFacadeBaseAsync
import org.jetbrains.kotlin.daemon.common.report
internal class CompileServicesFacadeMessageCollector(
private val servicesFacade: CompilerServicesFacadeBaseAsync,
compilationOptions: CompilationOptions
) : MessageCollector {
private val mySeverity = compilationOptions.reportSeverity
private var hasErrors = false
override fun clear() {
hasErrors = false
}
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
GlobalScope.async {
log.info("Message: " + MessageRenderer.WITHOUT_PATHS.render(severity, message, location))
when (severity) {
CompilerMessageSeverity.OUTPUT -> {
servicesFacade.report(ReportCategory.OUTPUT_MESSAGE, ReportSeverity.ERROR, message)
}
CompilerMessageSeverity.EXCEPTION -> {
servicesFacade.report(ReportCategory.EXCEPTION, ReportSeverity.ERROR, message)
}
else -> {
val reportSeverity = when (severity) {
CompilerMessageSeverity.ERROR -> ReportSeverity.ERROR
CompilerMessageSeverity.WARNING, CompilerMessageSeverity.STRONG_WARNING -> ReportSeverity.WARNING
CompilerMessageSeverity.INFO -> ReportSeverity.INFO
else -> ReportSeverity.DEBUG
}
if (reportSeverity.code <= mySeverity) {
servicesFacade.report(ReportCategory.COMPILER_MESSAGE, reportSeverity, message, location)
}
}
}
hasErrors = hasErrors || severity.isError
}
}
override fun hasErrors(): Boolean = hasErrors
}
| 0
| null |
0
| 2
|
acced52384c00df5616231fa5ff7e78834871e64
| 2,633
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/android/dessertclicker/ClickerApplication.kt
|
TrangTrang862
| 610,864,441
| false
|
{"Java": 14855, "Kotlin": 8618}
|
package com.example.android.dessertclicker
import android.app.Application
class ClickerApplication : Application() {
override fun onCreate() {
super.onCreate()
}
}
| 1
| null |
1
| 1
|
8a067a004cdd547208c6e43dd403c55af5d0e4a7
| 181
|
DessertClicker-Starter
|
Apache License 2.0
|
navigation/src/main/java/com/trodar/navigation/presentation/screen/MainScreen.kt
|
trodar
| 788,273,590
| false
|
{"Kotlin": 279609}
|
package com.trodar.navigation.presentation.screen
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.navigation.NavController
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavHostController
import com.trodar.navigation.presentation.navigation.BottomNav
import com.trodar.navigation.presentation.navigation.NavGraph
import com.trodar.navigation.presentation.route.BottomRoute
@Composable
fun MainScreen(
navController: NavHostController,
bottomScreenProvider: Map<String, ScreenProvider>,
) {
val currentSelectedScreen by navController.currentScreenAsState()
Scaffold(
modifier = Modifier,
bottomBar = {
BottomNav(
modifier = Modifier,
navController = navController,
currentSelectedScreen = currentSelectedScreen,
)
},
) { paddingValues ->
Box(
modifier = Modifier.fillMaxSize()
)
{
NavGraph(
navHostController = navController,
bottomScreenProvider = bottomScreenProvider,
paddingValues = paddingValues,
onShowBottomBar = {
}
)
}
}
}
@Stable
@Composable
private fun NavController.currentScreenAsState(): State<BottomRoute> {
val selectedItem = remember { mutableStateOf<BottomRoute>(BottomRoute.Preach) }
DisposableEffect(key1 = this) {
val listener = NavController.OnDestinationChangedListener { _, destination, _ ->
when {
destination.hierarchy.any { it.route == BottomRoute.Preach.route } -> {
selectedItem.value = BottomRoute.Preach
}
destination.hierarchy.any { it.route == BottomRoute.Territory.route } -> {
selectedItem.value = BottomRoute.Territory
}
destination.hierarchy.any { it.route == BottomRoute.Report.route } -> {
selectedItem.value = BottomRoute.Report
}
destination.hierarchy.any { it.route == BottomRoute.Notepad.route } -> {
selectedItem.value = BottomRoute.Notepad
}
}
}
addOnDestinationChangedListener(listener)
onDispose {
removeOnDestinationChangedListener(listener)
}
}
return selectedItem
}
| 0
|
Kotlin
|
0
| 0
|
b172bbcc5decf3e5d161b8024fbf35da4effb226
| 2,879
|
Partner
|
Apache License 2.0
|
src/main/kotlin/no/nav/helse/Sykepengedager.kt
|
navikt
| 164,105,390
| false
|
{"Kotlin": 10921}
|
package no.nav.helse
import no.nav.helse.Yrkesstatus.*
import java.time.*
import java.time.temporal.ChronoUnit.*
fun maksdato(grunnlag: Grunnlagsdata): MaksdatoResult {
val (antallDagerTilgode, hvorfor) = dagerTilgode(grunnlag)
val datoen = nWeekdaysFrom(antallDagerTilgode - 1, grunnlag.førsteSykepengedag)
val begrunnelsen = "§ 8-12: $hvorfor"
return MaksdatoResult(datoen, begrunnelsen)
}
fun dagerTilgode(grunnlag: Grunnlagsdata): Pair<Int, String> {
val maxTilgjengeligeDager = maxTilgjengeligeDager(grunnlag.personensAlder, grunnlag.yrkesstatus)
val forbrukt = dagerForbrukt(grunnlag.førsteFraværsdag, grunnlag.tidligerePerioder.sortedByDescending { it.tom })
val tilgode = maxTilgjengeligeDager - forbrukt
val begrunnelse = "${grunnlag.yrkesstatus} på ${grunnlag.personensAlder} år gir maks $maxTilgjengeligeDager dager. " +
"$forbrukt av disse er forbrukt"
return Pair(tilgode, begrunnelse)
}
internal fun maxTilgjengeligeDager(personensAlder: Int, yrkesstatus: Yrkesstatus) =
when {
personensAlder in (67..70) -> 60
yrkesstatus == IKKE_I_ARBEID -> 250
else -> 248
}
private fun dagerForbrukt(førsteFraværsdag: LocalDate, tidligerePerioder: List<Tidsperiode>): Int {
if (tidligerePerioder.isEmpty()) return 0
val sisteTreÅr = Tidsperiode(førsteFraværsdag.minusYears(3), førsteFraværsdag)
val første26UkersMellomrom =
første26UkersMellomrom(førsteFraværsdag, tidligerePerioder)
return tidligerePerioder.subList(0, første26UkersMellomrom)
.flatMap { it.days() }
.filterNot(::isWeekend)
.filter{ it.isWithin(sisteTreÅr) }
.count()
}
private fun første26UkersMellomrom(førsteFravøærsdag: LocalDate, tidligerePerioder: List<Tidsperiode>): Int {
return tidligerePerioder.withIndex()
.filter {
val førsteDagNestePeriode = if (it.index == 0) førsteFravøærsdag else tidligerePerioder[it.index - 1].fom
val sisteDagForrigePeriode = tidligerePerioder[it.index].tom
WEEKS.between(sisteDagForrigePeriode, førsteDagNestePeriode) >= 26 }
.map { it.index }
.firstOrNull() ?:tidligerePerioder.size
}
data class Tidsperiode(val fom: LocalDate, val tom: LocalDate) {
init {
if (tom.isBefore(fom)) throw IllegalArgumentException("tom cannot be before fom, $tom is before $fom")
}
fun contains(day: LocalDate): Boolean = !(day.isBefore(fom) || day.isAfter(tom))
fun days(): List<LocalDate> = (0 until nrOfDays()).map(fom::plusDays)
private fun nrOfDays() = if (fom == tom ) 1 else DAYS.between(fom, tom) + 1
}
fun LocalDate.isWithin(period: Tidsperiode) = period.contains(this)
| 0
|
Kotlin
|
0
| 0
|
7accec0237f5038a55c825ada91aaaf46d7593f9
| 2,649
|
helse-maksdato
|
MIT License
|
app/src/main/java/com/company_name/wallpaperx/SaveImages/ImgEntity.kt
|
pratyaksh1610
| 546,574,430
| false
| null |
package com.company_name.wallpaperx.SaveImages
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class ImgEntity(
@PrimaryKey(autoGenerate = true)
val id: Int?,
val url:String,
val date:String
)
| 0
|
Kotlin
|
0
| 0
|
e1fb9b324616858d6b55a28d0b99411357a5f81f
| 236
|
WallpaperX
|
The Unlicense
|
src/jvmMain/java/it/krzeminski/snakeyaml/engine/kmp/api/YamlOutputStreamWriter.kt
|
krzema12
| 642,543,787
| false
|
{"Kotlin": 533013, "Java": 387275}
|
/*
* Copyright (c) 2018, SnakeYAML
*
* 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 it.krzeminski.snakeyaml.engine.kmp.api
import java.io.IOException
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.nio.charset.Charset
/**
* Provide an example of implementation of [StreamDataWriter] interface which does not throw [IOException]
*
* @param out the output
* @param cs encoding to use to translate String to bytes
*/
open class YamlOutputStreamWriter(
out: OutputStream,
cs: Charset,
) : OutputStreamWriter(out, cs), StreamDataWriter {
/** Handle [IOException]s thrown while writing. */
open fun processIOException(e: IOException) {
throw e
}
override fun flush() {
try {
super<StreamDataWriter>.flush()
} catch (e: IOException) {
processIOException(e)
}
}
override fun write(str: String, off: Int, len: Int) {
try {
super.write(str, off, len)
} catch (e: IOException) {
processIOException(e)
}
}
override fun write(str: String) {
try {
super.write(str)
} catch (e: IOException) {
processIOException(e)
}
}
}
| 16
|
Kotlin
|
5
| 26
|
b61dcf0cc334d7508615e47568ee11845cf6ccdd
| 1,751
|
snakeyaml-engine-kmp
|
Apache License 2.0
|
src/main/kotlin/dev/wigger/mood/shareing/Sharing.kt
|
LukasW01
| 796,396,744
| false
|
{"Kotlin": 39268, "HTML": 26923, "Dockerfile": 318, "Shell": 221}
|
package dev.wigger.mood.shareing
import dev.wigger.mood.entry.Entry
import dev.wigger.mood.user.Users
import dev.wigger.mood.util.enums.Permissions
import io.quarkus.hibernate.orm.panache.PanacheEntityBase
import jakarta.persistence.*
import org.hibernate.annotations.CreationTimestamp
import org.hibernate.annotations.OnDelete
import org.hibernate.annotations.OnDeleteAction
import org.hibernate.annotations.UpdateTimestamp
import org.jetbrains.annotations.NotNull
import java.time.ZonedDateTime
@Entity
@Table(name = "sharing")
class Sharing : PanacheEntityBase() {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = 0
@CreationTimestamp
var createdAt: ZonedDateTime? = null
@UpdateTimestamp
var updatedAt: ZonedDateTime? = null
@Transient
var entry: List<Entry>? = null
@NotNull @Enumerated(EnumType.ORDINAL)
lateinit var permissions: Permissions
@ManyToOne(fetch = FetchType.LAZY, targetEntity = Users::class)
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "user_id")
lateinit var user: Users
@ManyToOne(fetch = FetchType.LAZY, targetEntity = Users::class)
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "delegator_id")
lateinit var delegator: Users
}
| 0
|
Kotlin
|
0
| 0
|
b7740253a3f976bf1f5d19776cc94e33043f4f11
| 1,294
|
mood
|
MIT License
|
app/src/main/java/com/ohuji/cardsNmonsters/ui/theme/Color.kt
|
ohuji
| 598,587,284
| false
| null |
package com.ohuji.cardsNmonsters.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF3d4b41)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFCFE5FF)
val md_theme_light_onPrimaryContainer = Color(0xFF001D34)
val md_theme_light_secondary = Color(0xFF526070)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFD5E4F7)
val md_theme_light_onSecondaryContainer = Color(0xFF0E1D2A)
val md_theme_light_tertiary = Color(0xFF006878)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFA6EEFF)
val md_theme_light_onTertiaryContainer = Color(0xFF001F25)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFF42474E)
val md_theme_light_onBackground = Color(0xFF1A1C1E)
val md_theme_light_surface = Color(0xFF42474E)
val md_theme_light_onSurface = Color(0xFF1A1C1E)
val md_theme_light_surfaceVariant = Color(0xFFDEE3EB)
val md_theme_light_onSurfaceVariant = Color(0xFFf6f7fc)
val md_theme_light_outline = Color(0xFF72777F)
val md_theme_light_inverseOnSurface = Color(0xFFF1F0F4)
val md_theme_light_inverseSurface = Color(0xFF2F3033)
val md_theme_light_inversePrimary = Color(0xFF99CBFF)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF00629D)
val md_theme_light_outlineVariant = Color(0xFFC2C7CF)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFF3d4b41)
val md_theme_dark_onPrimary = Color(0xFFFFFFFF)
val md_theme_dark_primaryContainer = Color(0xFF004A78)
val md_theme_dark_onPrimaryContainer = Color(0xFF001D34)
val md_theme_dark_secondary = Color(0xFF526070)
val md_theme_dark_onSecondary = Color(0xFFFFFFFF)
val md_theme_dark_secondaryContainer = Color(0xFF3A4857)
val md_theme_dark_onSecondaryContainer = Color(0xFFD5E4F7)
val md_theme_dark_tertiary = Color(0xFF53D7F1)
val md_theme_dark_onTertiary = Color(0xFF00363F)
val md_theme_dark_tertiaryContainer = Color(0xFF004E5B)
val md_theme_dark_onTertiaryContainer = Color(0xFFA6EEFF)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF42474E)
val md_theme_dark_onBackground = Color(0xFF1A1C1E)
val md_theme_dark_surface = Color(0xFF42474E)
val md_theme_dark_onSurface = Color(0xFF1A1C1E)
val md_theme_dark_surfaceVariant = Color(0xFFDEE3EB)
val md_theme_dark_onSurfaceVariant = Color(0xFFf6f7fc)
val md_theme_dark_outline = Color(0xFF8C9199)
val md_theme_dark_inverseOnSurface = Color(0xFF1A1C1E)
val md_theme_dark_inverseSurface = Color(0xFFE2E2E5)
val md_theme_dark_inversePrimary = Color(0xFF00629D)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFF99CBFF)
val md_theme_dark_outlineVariant = Color(0xFF42474E)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFFF6F7FC)
| 0
|
Kotlin
|
1
| 3
|
41f7c3e794d73b28582e3d0fde36f353083003ef
| 3,204
|
Cards-Monsters
|
MIT License
|
sample/src/main/kotlin/com/kronos/android/startup/sample/task/generate/SampleGenerate1Task.kt
|
Leifzhang
| 431,806,948
| false
| null |
package com.kronos.android.startup.sample.task.generate
import android.content.Context
import com.kronos.android.startup.sample.AsyncTask1Provider
import com.kronos.android.startup.sample.SimpleTask2Provider
import com.kronos.android.startup.sample.task.info
import com.kronos.lib.startup.TaskRunner
import com.kronos.startup.annotation.Lifecycle
import com.kronos.startup.annotation.Process
import com.kronos.startup.annotation.Step
import com.kronos.startup.annotation.startup.Async
import com.kronos.startup.annotation.startup.Await
import com.kronos.startup.annotation.startup.DependOn
import com.kronos.startup.annotation.startup.Startup
/**
*
* @Author LiABao
* @Since 2021/12/31
*
*/
@Async
@Await
@DependOn(
dependOn = [AsyncTask1Provider::class, SimpleTask2Provider::class],
dependOnTag = ["taskB"]
)
@Startup(strategy = Process.MAIN)
@Step(Lifecycle.AttachApplication)
class SampleGenerate1Task : TaskRunner {
override fun run(context: Context) {
info("MyAnchorTask")
}
}
| 0
|
Kotlin
|
8
| 47
|
883e2be9c1c6b19714fa74c803bd517fad081944
| 1,016
|
AndroidStartup
|
Apache License 2.0
|
common_utils/src/main/java/com/yaman/common_utils/helpers/single_clicklistener/setSafeOnClickListener.kt
|
Yamanaswal
| 685,417,811
| false
|
{"Kotlin": 83009}
|
package com.yaman.common_utils.helpers.single_clicklistener
import android.view.View
fun View.setSingleOnClickListener(onSingleClick: (View) -> Unit) {
val safeClickListener = SafeClickListener {
onSingleClick(it)
}
setOnClickListener(safeClickListener)
}
| 0
|
Kotlin
|
0
| 0
|
7498a31a82b28bdd37bc7f5faca551e86bac03ee
| 277
|
MultipleModuleApp
|
MIT License
|
core/src/androidMain/kotlin/Utils.kt
|
composablehorizons
| 792,741,661
| false
|
{"Kotlin": 216854, "HTML": 4427, "Shell": 2324, "Swift": 538}
|
@file:JvmName("AndroidUtilsKt")
package com.composables.core
import android.view.KeyEvent
import android.view.View.OnKeyListener
import androidx.activity.compose.BackHandler
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.platform.LocalView
@Composable
internal actual fun KeyDownHandler(onEvent: (KeyDownEvent) -> Boolean) {
val view = LocalView.current
BackHandler {
onEvent(KeyDownEvent(Key.Back))
}
DisposableEffect(Unit) {
val listener = OnKeyListener { _, keyCode, event ->
if (event.action == KeyEvent.ACTION_DOWN) {
onEvent(KeyDownEvent(Key(keyCode)))
} else {
false
}
}
view.setOnKeyListener(listener)
onDispose {
view.setOnKeyListener(null)
}
}
}
| 5
|
Kotlin
|
11
| 288
|
5366a4ca80f433a00b03af170dca9a4b6846dee7
| 920
|
compose-unstyled
|
MIT License
|
features/agents_list/src/main/java/com/ahmedvargos/agents_list/di/AgentsListModule.kt
|
sarnav98
| 337,487,137
| true
|
{"Kotlin": 248520}
|
package com.ahmedvargos.agents_list.di
import com.ahmedvargos.agents_list.data.AgentsListRepoImpl
import com.ahmedvargos.agents_list.data.data_sources.local.AgentsListLocalSource
import com.ahmedvargos.agents_list.data.data_sources.local.AgentsListLocalSourceImpl
import com.ahmedvargos.agents_list.data.data_sources.remote.AgentsListApi
import com.ahmedvargos.agents_list.data.data_sources.remote.AgentsListRemoteSource
import com.ahmedvargos.agents_list.data.data_sources.remote.AgentsListRemoteSourceImpl
import com.ahmedvargos.agents_list.domain.repo.AgentsListRepo
import com.ahmedvargos.agents_list.domain.usecase.AgentsListUseCase
import com.ahmedvargos.agents_list.presentation.AgentsListViewModel
import com.ahmedvargos.base.utils.ApplicationDispatchersProvider
import com.ahmedvargos.base.utils.SchedulerProvider
import com.ahmedvargos.uicomponents.view_models.AgentCellViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
import retrofit2.Retrofit
@ExperimentalCoroutinesApi
fun getAgentsListModule() = module {
single {
get<Retrofit>().create(AgentsListApi::class.java)
}
factory<AgentsListLocalSource> {
AgentsListLocalSourceImpl(get(), get())
}
factory<AgentsListRemoteSource> {
AgentsListRemoteSourceImpl(get())
}
factory<SchedulerProvider> { ApplicationDispatchersProvider() }
single<AgentsListRepo> {
AgentsListRepoImpl(get(), get(), get(), get())
}
factory {
AgentsListUseCase(get())
}
viewModel {
AgentCellViewModel()
}
viewModel {
AgentsListViewModel(get())
}
}
| 0
| null |
0
| 0
|
e9695488c63b336b07dcb6d209f21326457c4ea3
| 1,692
|
Valorant-Agents
|
Apache License 2.0
|
app/src/main/java/com/example/mypraticecomposedictionary/component/ResultCard.kt
|
vytran0710
| 636,748,040
| false
| null |
package com.example.mypraticecomposedictionary.component
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.mypraticecomposedictionary.R
import com.example.mypraticecomposedictionary.model.Data
@Composable
fun ResultCard(modifier: Modifier, data: Data) {
Box(modifier = Modifier.border(BorderStroke(2.dp, color = Color.Black))) {
val elementPadding = dimensionResource(R.dimen.element_padding)
Column(
modifier = modifier.padding(
elementPadding
)
) {
Row {
val subheadSize = dimensionResource(R.dimen.subhead_size).value.sp
Text(
text = data.slug,
fontWeight = FontWeight.Bold,
fontSize = subheadSize,
modifier = Modifier.weight(1F)
)
Column(modifier = Modifier.weight(1F)) {
if (data.isCommon) {
val isCommonString = stringResource(R.string.common_word)
Text(text = isCommonString)
}
for (jlpt in data.jlpt) {
Text(text = jlpt)
}
}
}
val definitionString = stringResource(R.string.definitions_)
Text(text = definitionString)
for (sense in data.senses)
{
Text(text = "\t-\t${sense.englishDefinitions.joinToString(", ")} (${sense.partsOfSpeech.joinToString(", ")})")
}
val formString = stringResource(R.string.forms_)
Text(text = "$formString ${data.japanese.joinToString(", ") { japanese -> "${japanese.word} (${japanese.reading})" }}")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
252be66eefc53e55f3c0de141afe9bf8689a28bb
| 2,383
|
Practice-Compose-Dictionary-App
|
MIT License
|
app/src/main/java/com/theathletic/interview/articles/data/Mapper.kt
|
Nniheke
| 641,885,034
| false
| null |
package com.theathletic.interview.articles.data
import com.theathletic.interview.articles.domain.model.Article
import com.theathletic.interview.articles.data.remote.model.ArticleApiModel
import com.theathletic.interview.articles.data.remote.model.AuthorsApiModel
import com.theathletic.interview.articles.domain.model.ArticleUiModel
import com.theathletic.interview.articles.domain.model.AuthorDetails
/**
* Converts an [ArticleApiModel] to a domain model [Article].
*
* @return The converted domain model [Article].
*/
fun ArticleApiModel.toDomain() = Article(
author = author,
body = body,
id = id,
imageUrlString = imageUrlString,
title = title
)
/**
* Converts an [ArticleUiModel] to another [ArticleUiModel].
*
* @return The converted [ArticleUiModel].
*/
fun ArticleUiModel.toUiModel() = ArticleUiModel(
article = article,
authorDetails = authorDetails
)
/**
* Converts an [AuthorsApiModel] to a domain model [AuthorDetails].
*
* @return The converted domain model [AuthorDetails].
*/
fun AuthorsApiModel.toDomain() = AuthorDetails(
id = id,
imageUrlString = imageUrlString,
name = name,
title = title,
updatedAt = updatedAt
)
| 0
|
Kotlin
|
0
| 0
|
e37579188c3cd8e84adffaf07bfc4f72a4291272
| 1,197
|
Athletic
|
Apache License 2.0
|
app/src/main/java/com/cocktailbar/presentation/cocktails/IngredientDialogComponent.kt
|
olegaches
| 680,145,725
| false
|
{"Kotlin": 98906}
|
package com.cocktailbar.presentation.cocktails
import com.arkivanov.decompose.ComponentContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
class IngredientDialogComponent(
componentContext: ComponentContext,
private val dismissDialog: () -> Unit,
private val saveIngredient: (String) -> Unit
) : ComponentContext by componentContext, IIngredientDialogComponent {
private val _state = MutableStateFlow(IngredientDialogState())
override val state = _state.asStateFlow()
override fun dispatch(ingredientDialogEvent: IngredientDialogEvent) {
reduce(ingredientDialogEvent)
}
private fun reduce(event: IngredientDialogEvent) {
val stateFlow = _state
when (event) {
IngredientDialogEvent.OnDismiss -> {
dismissDialog()
}
is IngredientDialogEvent.OnIngredientTextChanged -> {
stateFlow.update {
it.copy(ingredientText = event.value)
}
}
IngredientDialogEvent.OnSaveIngredient -> {
saveIngredient(stateFlow.value.ingredientText)
dismissDialog()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b6eab221523ed3330099f5445f140848cfe2cf06
| 1,273
|
cocktail-recipes
|
Apache License 2.0
|
app/src/main/java/org/listenbrainz/android/model/user/UserFeedback.kt
|
metabrainz
| 550,726,972
| false
|
{"Kotlin": 1481175, "Ruby": 423}
|
package org.listenbrainz.android.model.user
import com.google.gson.annotations.SerializedName
data class UserFeedback(
@SerializedName("count") val count: Int? = null,
@SerializedName("feedback") val feedback: List<UserFeedbackEntry>? = null,
)
| 25
|
Kotlin
|
31
| 99
|
573ab0ec6c5b87ea963f013174159ddfcd123976
| 258
|
listenbrainz-android
|
Apache License 2.0
|
src/main/kotlin/br/com/rest/core/item/ChangeItemName.kt
|
tomasouza
| 339,713,351
| false
|
{"Kotlin": 3160}
|
package br.com.rest.core.item
class ChangeItemName {
}
| 0
|
Kotlin
|
0
| 0
|
9911007bc866d66f7fe011bf9cf511546ea5fcfb
| 55
|
http-RESTful-kotlin-api
|
MIT License
|
Kernl.Runtime/src/main/kotlin/org/mattshoe/shoebox/kernl/runtime/session/DefaultKernlResourceManager.kt
|
mattshoe
| 825,957,770
| false
|
{"Kotlin": 344588, "Shell": 1045}
|
package org.mattshoe.shoebox.kernl.runtime.session
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.mattshoe.shoebox.kernl.NEVER
import org.mattshoe.shoebox.kernl.internal.logger.KernlLogger
import org.mattshoe.shoebox.kernl.runtime.cache.invalidation.CountdownFlow
import org.mattshoe.shoebox.kernl.runtime.cache.util.MonotonicStopwatch
import org.mattshoe.shoebox.kernl.runtime.dsl.DEFAULT_RESOURCE_MONITOR_INTERVAL
import org.mattshoe.shoebox.kernl.runtime.ext.conflatingChannelFlow
import java.lang.ref.WeakReference
import java.util.*
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
internal object DefaultKernlResourceManager: KernlResourceManager {
internal lateinit var coroutineScope: CoroutineScope
private var currentPollingJob: Job? = null
private val activeKernlsMutex = Mutex()
private val activeKernls = mutableMapOf<UUID, KernlResource>()
init {
startSession(Dispatchers.Default, DEFAULT_RESOURCE_MONITOR_INTERVAL)
}
override fun startSession(dispatcher: CoroutineDispatcher, resourceMonitorInterval: Duration) {
stopSession()
coroutineScope = buildCoroutineScope(dispatcher)
coroutineScope.launch {
monitorKernlsForDisposal(resourceMonitorInterval)
}
KernlLogger.debug("session started")
}
override fun stopSession() {
KernlLogger.debug("Stopping Previous Session")
currentPollingJob?.cancel()
if (::coroutineScope.isInitialized) {
KernlLogger.debug("Cancelling previous coroutine scope")
coroutineScope.cancel()
}
KernlLogger.debug("clearing active kernels")
activeKernls.clear()
}
override fun registerKernl(kernl: Any): KernlRegistration {
val uuid = UUID.randomUUID()
val internalTimeToLiveCountdownFlow = CountdownFlow("CountdownFlow:${kernl::class.simpleName}:${System.identityHashCode(kernl).toString(16)}")
// We need a COLD flow that will consume events from the "global" ttl countdown flow
val publicTimeToLiveFlow = conflatingChannelFlow {
internalTimeToLiveCountdownFlow.events
.onEach {
send(it)
}.launchIn(this)
}
val timeToLiveStopwatch = MonotonicStopwatch()
val kernlData = KernlResource(
kernlReference = WeakReference(kernl),
countdownFlow = internalTimeToLiveCountdownFlow,
timeToLiveJob = null,
timeToLiveStopwatch
)
coroutineScope.launch {
activeKernlsMutex.withLock {
activeKernls[uuid] = kernlData
}
}
return KernlRegistration(
uuid,
publicTimeToLiveFlow,
timeToLiveStopwatch
)
}
override fun resetTimeToLive(uuid: UUID, duration: Duration) {
KernlLogger.debug("resetTimeToLive(${uuid}, ${duration.inWholeMilliseconds})")
coroutineScope.launch {
KernlLogger.debug("acquiring mutex lock for reset")
activeKernlsMutex.withLock {
KernlLogger.debug("reset lock acquired.")
activeKernls[uuid]?.apply {
KernlLogger.debug("resetting countdown flow")
countdownFlow.reset(duration)
KernlLogger.debug("resetting stopwatch")
timeToLiveStopwatch.reset()
} ?: KernlLogger.debug("no reset entry found for $uuid!!!!!!")
}
KernlLogger.debug("reset lock released.")
}
}
override fun stopTimeToLive(uuid: UUID) {
KernlLogger.debug("stopTimeToLive($uuid)")
coroutineScope.launch {
KernlLogger.debug("acquiring stop lock")
activeKernlsMutex.withLock {
KernlLogger.debug("stop lock acquired")
activeKernls[uuid]?.apply {
countdownFlow.stop()
timeToLiveStopwatch.stop()
KernlLogger.debug("all stopped")
} ?: KernlLogger.debug("no stop entry found for $uuid!!!!!")
}
KernlLogger.debug("lock released")
}
}
internal fun isCoroutineScopeInitialized() = ::coroutineScope.isInitialized
private fun monitorKernlsForDisposal(interval: Duration) {
currentPollingJob = coroutineScope.launch {
if (interval != NEVER && interval.isPositive()) {
while (isActive) {
delay(interval.inWholeMilliseconds)
activeKernlsMutex.withLock {
KernlLogger.debug("cleaning up references....")
val garbageCollectedKernls = mutableSetOf<UUID>()
activeKernls.keys.forEach {
if (activeKernls[it]?.kernlReference?.get() == null) {
garbageCollectedKernls.add(it)
}
}
KernlLogger.debug("${garbageCollectedKernls.size} Kernls have been garbage collected.")
garbageCollectedKernls.forEach {
activeKernls[it]?.countdownFlow?.stop()
activeKernls[it]?.timeToLiveJob?.cancel()
activeKernls.remove(it)
}
}
}
}
}
}
private fun buildCoroutineScope(dispatcher: CoroutineDispatcher) = CoroutineScope(
SupervisorJob()
+ dispatcher
+ CoroutineName(this::class.simpleName!!)
)
}
| 10
|
Kotlin
|
1
| 9
|
9682fcafeb1dccd468443e1265eab55c05757e52
| 5,824
|
kernl
|
Apache License 2.0
|
src/main/kotlin/org/goodmath/pica/scopes.kt
|
MarkChuCarroll
| 538,268,815
| false
|
{"Kotlin": 211625, "ANTLR": 10218}
|
package org.goodmath.pica
import org.goodmath.pica.ast.AstNode
import org.goodmath.pica.ast.defs.Definition
import org.goodmath.pica.ast.Identifier
import org.goodmath.pica.ast.defs.HadronDefinition
import org.goodmath.pica.util.Symbol
import org.goodmath.pica.util.twist.Twist
import org.goodmath.pica.util.twist.Twistable
abstract class Scope: Twistable {
abstract fun getDefinition(name: Identifier): Definition?
}
object RootScope: Scope() {
private val defs = HashMap<Symbol, Definition>()
private val scopes = HashMap<Identifier, HadronScope>()
fun getHadronScope(id: Identifier): HadronScope? {
return scopes[id]
}
override fun getDefinition(name: Identifier): Definition? {
if (name.hadronId == null) {
return defs[name.name]
} else {
return scopes[name.hadronId]?.getDefinition(name)
}
}
override fun twist(): Twist =
Twist.obj("RootScope",
Twist.arr("Hadrons",
scopes.values.toList()
),
Twist.arr("DefinedNames",
defs.values.toList()
)
)
fun setHadronScope(id: Identifier, scope: HadronScope) {
this.scopes[id] = scope
}
}
class HadronScope(val id: Identifier, val hadron: HadronDefinition): Scope() {
val defs = HashMap<Symbol, Definition>()
val imports = HashMap<Symbol, Identifier>()
init {
// Add the imports to the namespace.
for (imp in hadron.imports) {
for (name in imp.names) {
imports[name] = Identifier(hadron.id, name, imp.loc)
}
}
for (def in hadron.defs) {
defs.put(def.name, def)
}
}
override fun getDefinition(name: Identifier): Definition? {
return when (name.hadronId) {
null -> {
imports[name.name]
?.let { getDefinition(it) }
?: defs[name.name]
}
id -> {
defs[name.name]
}
else -> {
RootScope.getDefinition(name)
}
}
}
override fun twist(): Twist =
Twist.obj("Scope::Hadron",
Twist.arr("Imports",
imports.values.toList()
),
Twist.arr("Definitions",
defs.values.toList()
)
)
private fun addImportedId(name: Symbol, referencedId: Identifier) {
imports[name] = referencedId
}
}
class LocalScope(val parent: Scope, val origin: AstNode): Scope() {
val definitions = HashMap<Symbol, Definition>()
override fun getDefinition(name: Identifier): Definition? {
return if (name.hadronId == null) {
if (name.name in definitions) {
definitions[name.name]
} else {
parent.getDefinition(name)
}
} else {
parent.getDefinition(name)
}
}
override fun twist(): Twist =
Twist.leaf("LocalScope")
}
| 0
|
Kotlin
|
0
| 0
|
1ed984ca0557aac61d368e74387b36ca64dcca5d
| 3,064
|
pica
|
Apache License 2.0
|
src/main/kotlin/com/blitzoffline/alphamusic/console/command/Command.kt
|
BlitzOffline
| 434,279,924
| false
|
{"Kotlin": 122890}
|
package com.blitzoffline.alphamusic.console.command
import com.blitzoffline.alphamusic.utils.extension.printHelp
import org.apache.commons.cli.HelpFormatter
import org.apache.commons.cli.Options
import org.slf4j.Logger
import org.slf4j.event.Level
abstract class Command(val name: String, options: Options) : CommandParser(options), CommandExecutor {
private val helpFormatter = HelpFormatter()
fun printHelp(logger: Logger, level: Level = Level.INFO) {
helpFormatter.printHelp(name, this.options, logger, level)
}
}
| 7
|
Kotlin
|
0
| 0
|
84dbaceb761a9749eaff58d5cffcd3664eaf0dd4
| 539
|
AlphaMusic
|
MIT License
|
api-dev/src/main/kotlin/io/qalipsis/api/messaging/LoopTopic.kt
|
qalipsis
| 428,742,260
| false
| null |
/*
* Copyright 2022 AERIS IT Solutions GmbH
*
* 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.qalipsis.api.messaging
import io.qalipsis.api.logging.LoggerHelper.logger
import io.qalipsis.api.sync.ImmutableSlot
import kotlinx.coroutines.sync.withLock
import java.time.Duration
/**
* [LoopTopic] is a special implementation of [Topic] providing the data as an infinite loop: once the consumer polled
* all the values from the topic, values are provided from the beginning.
*
* @param idleTimeout idle time of a subscription: once a subscription passed this duration without record, it is cancelled.
*
* @author <NAME>
*/
internal open class LoopTopic<T>(
idleTimeout: Duration
) : AbstractLinkedSlotsBasedTopic<T>(idleTimeout) {
private var shouldComplete = false
private var complete = false
override suspend fun updateSubscriptionSlot(lastSetSlot: ImmutableSlot<LinkedRecord<T>>) {
// If the topic was tried to be completed but failed because it was empty, it is done now.
if (shouldComplete != complete) {
complete()
}
}
override suspend fun complete() {
if (!complete) {
shouldComplete = true
writeMutex.withLock {
// If there is at least on item, the chain is closed to form the loop.
if (writeSlot !== subscriptionSlot) {
writeSlot.set(subscriptionSlot.get())
complete = true
}
}
}
}
companion object {
@JvmStatic
private val log = logger()
}
}
| 0
|
Kotlin
|
0
| 0
|
0481631343ace487b8b1bdd8dfd8ebe2725ffc7e
| 2,112
|
qalipsis-api
|
Apache License 2.0
|
packages/base/src/commonMain/kotlin/elide/struct/AbstractTreeMap.kt
|
elide-dev
| 506,113,888
| false
|
{"Kotlin": 4544382, "JavaScript": 1201497, "Java": 302542, "Protocol Buffer": 276092, "Shell": 84860, "Dockerfile": 51144, "Cap'n Proto": 35188, "Makefile": 30147, "CSS": 14730, "Python": 5989, "C": 4348, "Batchfile": 3016, "Ruby": 2474, "Handlebars": 1954, "HTML": 1010, "Rust": 525, "Swift": 23}
|
/*
* Copyright (c) 2024 Elide Technologies, Inc.
*
* Licensed under the MIT license (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://opensource.org/license/mit/
*
* 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 elide.struct
import kotlin.concurrent.Volatile
import kotlin.jvm.JvmField
import kotlin.jvm.JvmInline
import kotlin.jvm.JvmStatic
import kotlin.jvm.Transient
import elide.struct.api.SortedMap
/**
*
*/
public abstract class AbstractTreeMap<Key, Value> @Suppress("UNUSED_PARAMETER") protected constructor (
pairs: Iterable<Pair<Key, Value>>,
presorted: Boolean = false,
) : SortedMap<Key, Value> where Key : Comparable<Key> {
/** */
internal companion object {
/**
*
*/
internal val RED: NodeColor = NodeColor.RED
/**
*
*/
internal val BLACK: NodeColor = NodeColor.BLACK
}
/**
*
*/
internal enum class NodeColor {
RED,
BLACK
}
/**
*
*/
internal class TreeNode<Key: Comparable<Key>, Value>(
/**
*
*/
@Volatile @JvmField var key: Key,
/**
*
*/
@Volatile @JvmField var value: Value,
/**
*
*/
@Volatile @JvmField var left: TreeNode<Key, Value>? = null,
/**
*
*/
@Volatile @JvmField var right: TreeNode<Key, Value>? = null,
/**
*
*/
@Volatile @JvmField var parent: TreeNode<Key, Value>? = null,
/**
*
*/
@Volatile @JvmField var color: NodeColor = RED,
) {
internal companion object {
fun <Key: Comparable<Key>, Value> of(parent: TreeNode<Key, Value>, pair: Pair<Key, Value>): TreeNode<Key, Value> =
TreeNode(
pair.first,
pair.second,
parent = parent,
)
fun <Key: Comparable<Key>, Value> root(pair: Pair<Key, Value>): TreeNode<Key, Value> =
TreeNode(pair.first, pair.second)
}
internal fun child(direction: Boolean): TreeNode<Key, Value>? = if (direction) right else left
internal fun direction(child: TreeNode<Key, Value>): Boolean = right?.key == child.key
internal fun setLeft(child: TreeNode<Key, Value>?) {
left = child
child?.parent = this
}
internal fun setRight(child: TreeNode<Key, Value>?) {
right = child
child?.parent = this
}
override fun toString(): String {
return "Node(key=$key, value=$value, color=${if (color == RED) "RED" else "BLACK"})"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TreeNode<*, *>) return false
if (key != other.key) return false
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
var result = key.hashCode()
result = 31 * result + value.hashCode()
return result
}
}
/**
*
*/
@JvmInline public value class Entry<Key, Value> private constructor (
private val node: TreeNode<Key, Value>
) : Map.Entry<Key, Value>, Comparable<Key> where Key : Comparable<Key> {
override val key: Key get() = node.key
override val value: Value get() = node.value
override fun compareTo(other: Key): Int = key.compareTo(other)
/** */
public companion object {
/**
*
*/
@JvmStatic internal fun <Key: Comparable<Key>, Value> of(node: TreeNode<Key, Value>): Entry<Key, Value> = Entry(
node
)
/**
*
*/
@JvmStatic internal fun <Key: Comparable<Key>, Value> mutable(
node: TreeNode<Key, Value>
): MutableEntry<Key, Value> = MutableEntry(node)
}
}
/**
*
*/
@JvmInline public value class MutableEntry<Key, Value> internal constructor (
private val node: TreeNode<Key, Value>
) : MutableMap.MutableEntry<Key, Value>, Comparable<Key> where Key : Comparable<Key> {
override val key: Key get() = node.key
override val value: Value get() = node.value
override fun compareTo(other: Key): Int = key.compareTo(other)
override fun setValue(newValue: Value): Value {
val oldValue = node.value
node.value = newValue
return oldValue
}
}
/**
*
*/
@Transient private var root: TreeNode<Key, Value>? = null
//
@Transient @Volatile private var innerSize: UInt = 0u
init {
// skip first; it's the root
pairs.forEach { addNode(it.first, it.second) }
}
/**
*
*/
internal fun applyRoot(root: TreeNode<Key, Value>) {
root.parent = null
root.color = BLACK
this.root = root
if (innerSize == 0u) {
innerSize++
}
}
/**
*
*/
private fun <R> withRoot(op: (TreeNode<Key, Value>?) -> R): R = op(root)
/**
*
*/
protected fun addNode(key: Key, value: Value): Value? = withRoot { root ->
// if there is no root on the tree (it's empty), install it
if (root == null) {
applyRoot(TreeNode.root(key to value))
return@withRoot value
}
// find the insertion point and add the new node.
fun walkTree(): Pair<TreeNode<Key, Value>?, Value?> {
var current: TreeNode<Key, Value> = root
while (true) {
val comparison = key.compareTo(current.key)
current = when {
comparison < 0 -> when (val left = current.left) {
null -> TreeNode.of(current, key to value).let { node ->
current.setLeft(node)
innerSize++
return node to value
}
else -> left
}
comparison > 0 -> when (val right = current.right) {
null -> TreeNode.of(current, key to value).let { node ->
current.setRight(node)
innerSize++
return node to value
}
else -> right
}
else -> current.value.let { oldValue ->
current.value = value
return current to oldValue
}
}
}
}
walkTree().also { pair ->
pair.first?.let { node -> maybeRebalance(node) }
}.second
}
//
private fun maybeRebalance(node: TreeNode<Key, Value>) {
when (val parent = node.parent) {
// if the node is the root, color it black and return
null -> {
node.color = BLACK
return
}
// if the parent is black, color it red and return
else -> if (parent.color == BLACK) {
node.color = RED
return
} else {
// if the parent is red, and the uncle is red, color the parent and uncle black and the grandparent red
val uncle = parent.parent?.child(parent == parent.parent?.left)
if (uncle?.color == RED) {
parent.color = BLACK
uncle.color = BLACK
parent.parent?.color = RED
maybeRebalance(parent.parent!!)
return
}
// if the parent is red, and the uncle is black, rotate the parent and grandparent
val direction = parent.parent?.direction(parent) ?: false
if (parent.child(node == parent.left) != node) {
if (parent.child(node == parent.left) == parent) {
rotateLeft(parent)
} else {
rotateRight(parent)
}
maybeRebalance(parent)
return
}
if (direction) {
rotateRight(parent.parent!!)
} else {
rotateLeft(parent.parent!!)
}
parent.color = BLACK
parent.parent?.color = RED
}
}
}
// Rotate the red/black tree graph leftward, taking care to preserve child nodes.
private fun rotateLeft(node: TreeNode<Key, Value>) {
val pivot = node.right ?: return
node.setRight(pivot.left)
pivot.setLeft(node)
pivot.parent = node.parent
node.parent = pivot
pivot.parent?.child(node == pivot.parent?.left)?.let { direction ->
pivot.parent?.setRight(pivot)
}
}
// Rotate the red/black tree graph rightward, taking care to preserve child nodes.
private fun rotateRight(node: TreeNode<Key, Value>) {
val pivot = node.left ?: return
node.setLeft(pivot.right)
pivot.setRight(node)
pivot.parent = node.parent
node.parent = pivot
pivot.parent?.child(node == pivot.parent?.left)?.let { direction ->
pivot.parent?.setRight(pivot)
}
}
/**
*
*/
private fun findNodeByKey(key: Key): TreeNode<Key, Value>? {
// if there is no root on the tree (it's empty), there's nothing to find
if (root == null) return null
// find the node with the given key
var node = root
while (node != null) {
when (val comparison = key.compareTo(node.key)) {
0 -> return node
else -> if (key == node.key) return node else {
node = if (comparison < 0) node.left else node.right
}
}
}
return null
}
/**
*
*/
internal fun findNodeByValue(value: Value): TreeNode<Key, Value>? {
// locate a node by matching a value
val stack = mutableListOf<TreeNode<Key, Value>>()
var node = root
while (node != null || stack.isNotEmpty()) {
while (node != null) {
stack.add(node)
node = node.left
}
node = stack.removeAt(stack.lastIndex)
if (value == node.value) return node
node = node.right
}
return null
}
/**
* Remove a node by [key].
*
* @param key Key for the node to remove.
* @return The removed node, if any.
*/
internal fun removeNodeByKey(key: Key): TreeNode<Key, Value>? {
// if there is no root on the tree (it's empty), there's nothing to remove
val tip = root ?: return null
// if the node is the root node, we need to un-mount the root to remove it
if (tip.key == key) return removeNode(tip)
// find the node with the given key
return findNodeByKey(key)?.let {
removeNode(it)
}
}
/**
*
*/
internal fun removeNodeByValue(value: Value): TreeNode<Key, Value>? {
// locate a node by matching a value
val stack = mutableListOf<TreeNode<Key, Value>>()
var node = root
while (node != null || stack.isNotEmpty()) {
while (node != null) {
stack.add(node)
node = node.left
}
node = stack.removeAt(stack.lastIndex)
if (value == node.value) return removeNode(node)
node = node.right
}
return null
}
/**
*
*/
private fun removeNode(node: TreeNode<Key, Value>, replace: Boolean = false): TreeNode<Key, Value> = withRoot {
// if the node has no children, remove it and return
if (node.left == null && node.right == null) {
(node == node.parent?.left).let { direction ->
if (direction) {
node.parent?.setRight(null)
} else {
node.parent?.setLeft(null)
}
}
// node has no children and is root = evict the root, empty the map entirely
if (root?.key == node.key && !replace) {
evictRoot()
} else if (!replace) {
innerSize--
}
return@withRoot node
}
when (val parent = node.parent) {
null -> {
val child = node.right ?: node.left
child?.parent = null
root = child
}
else -> when {
// if the node has one child, replace it with the child and return
node.left == null || node.right == null -> {
val direction = parent.direction(node)
val child = listOf(
node.left,
node.right,
).first {
it != null
}
when (direction) {
true -> parent.setRight(child)
false -> parent.setLeft(child)
}
innerSize--
return@withRoot node
}
// if the node has two children, replace it with the in-order predecessor or successor and return
else -> {
val successor = node.right?.let { right ->
var current = right
while (current.left != null) current = current.left!!
current
}
successor?.let { replacement ->
node.key = replacement.key
node.value = replacement.value
innerSize--
removeNode(replacement, replace = true)
}
}
}
}
return@withRoot node
}
/**
*
*/
protected fun evictRoot() {
// walk the root, clearing all left/right references
fun walkTree(node: TreeNode<Key, Value>?) {
if (node == null) return
walkTree(node.left)
walkTree(node.right)
node.left = null
node.right = null
}
walkTree(root)
root = null
innerSize = 0u
}
override fun containsKey(key: Key): Boolean = findNodeByKey(key) != null
override fun containsValue(value: Value): Boolean = findNodeByValue(value) != null
override operator fun get(key: Key): Value? = findNodeByKey(key)?.value
override val size: Int get() = innerSize.toInt()
override fun isEmpty(): Boolean = root == null
override val entries: MutableSet<
MutableMap.MutableEntry<Key, Value>
> get() = mutableSetOf<MutableMap.MutableEntry<Key, Value>>().apply {
val stack = mutableListOf<TreeNode<Key, Value>>()
var node = root
while (node != null || stack.isNotEmpty()) {
while (node != null) {
stack.add(node)
node = node.left
}
node = stack.removeAt(stack.lastIndex)
add(Entry.mutable(node))
node = node.right
}
}
override val keys: MutableSet<Key> get() = mutableSetOf<Key>().apply {
val stack = mutableListOf<TreeNode<Key, Value>>()
var node = root
while (node != null || stack.isNotEmpty()) {
while (node != null) {
stack.add(node)
node = node.left
}
node = stack.removeAt(stack.lastIndex)
add(node.key)
node = node.right
}
}
override val values: MutableCollection<Value> get() = mutableSetOf<Value>().apply {
val stack = mutableListOf<TreeNode<Key, Value>>()
var node = root
while (node != null || stack.isNotEmpty()) {
while (node != null) {
stack.add(node)
node = node.left
}
node = stack.removeAt(stack.lastIndex)
add(node.value)
node = node.right
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Map<*, *>) return false
if (size != other.size) return false
return entries.zip(other.entries).all { (a, b) -> a == b }
}
override fun hashCode(): Int {
var result = root?.hashCode() ?: 0
result = 31 * result + innerSize.toInt()
result = 31 * result + entries.sumOf { it.hashCode() }
return result
}
}
| 45
|
Kotlin
|
15
| 86
|
bd9f5aed8523648256c9e9a29d87bd3c2b09ac54
| 14,889
|
elide
|
MIT License
|
app/src/test/java/com/anhvt/weathersearch/data/WeatherRepositoryImplTest.kt
|
anhvt52
| 376,900,467
| false
| null |
package com.anhvt.weathersearch.data
import com.anhvt.weathersearch.data.datasource.LocalDatasource
import com.anhvt.weathersearch.data.datasource.RemoteDataSource
import com.anhvt.weathersearch.domain.entity.WeatherDetails
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.times
import java.time.LocalDate
@RunWith(JUnit4::class)
class WeatherRepositoryImplTest {
private val mockRemoteData = listOf(WeatherDetails(LocalDate.now(), 10f, 10, 10f, "Desc1"))
private val mockLocalData = listOf(WeatherDetails(LocalDate.now(), 100f, 100, 100f, "Desc2"))
@Mock
lateinit var mockLocalDatasource: LocalDatasource
@Mock
lateinit var mockRemoteDataSource: RemoteDataSource
lateinit var weatherRepositoryImpl: WeatherRepositoryImpl
private val cityName = "test"
@Before
fun setUp() {
mockLocalDatasource = Mockito.mock(LocalDatasource::class.java)
mockRemoteDataSource = Mockito.mock(RemoteDataSource::class.java)
weatherRepositoryImpl = WeatherRepositoryImpl(mockRemoteDataSource, mockLocalDatasource)
}
@Test
fun `when local data is valid then return local data`() = runBlockingTest {
launch {
Mockito.`when`(mockLocalDatasource.searchByCityName(cityName)).thenReturn(mockLocalData)
val result = weatherRepositoryImpl.searchByCityName(cityName).first()
assert(result == mockLocalData)
}
}
@Test
fun `when local data is not valid then get data from remote source and update local data`() =
runBlocking {
val job = launch {
Mockito.`when`(mockLocalDatasource.searchByCityName(cityName)).thenReturn(emptyList())
Mockito.`when`(mockRemoteDataSource.searchByCityName(cityName))
.thenReturn(mockRemoteData)
val result = weatherRepositoryImpl.searchByCityName(cityName).first()
assert(result == mockRemoteData)
Mockito.verify(mockLocalDatasource, times(1)).update(cityName, mockRemoteData)
}
job.join()
}
}
| 0
|
Kotlin
|
0
| 4
|
ed6d186b20c4210187bc383e53f9a2b482c4776c
| 2,385
|
weathersearch
|
Apache License 2.0
|
kommons-test/src/jvmMain/kotlin/com/bkahlert/kommons/test/junit/testEach.kt
|
bkahlert
| 323,048,013
| false
| null |
package com.bkahlert.kommons.test.junit
import com.bkahlert.kommons.test.junit.DynamicTestDisplayNameGenerator.displayNameFor
import org.junit.jupiter.api.DynamicTest
import org.junit.jupiter.api.function.Executable
import java.util.stream.Stream
/**
* Builds a single test
* that [softly] checks the specified [assertions]
* for each of the specified [subjects].
*
* The name for each container is heuristically derived but can also be explicitly specified using [testNamePattern]
* which supports curly placeholders `{}` like [SLF4J] does.
*/
public fun <T> testEach(
vararg subjects: T,
testNamePattern: String? = null,
softly: Boolean = true,
assertions: Assertions<T>,
): Stream<DynamicTest> = subjects.asList().testEach(testNamePattern, softly, assertions)
/**
* Builds a single test
* that [softly] checks the specified [assertions]
* for each subject of this [Collection].
*
* The name for each container is heuristically derived but can also be explicitly specified using [testNamePattern]
* which supports curly placeholders `{}` like [SLF4J] does.
*/
public fun <T> Iterable<T>.testEach(
testNamePattern: String? = null,
softly: Boolean = true,
assertions: Assertions<T>,
): Stream<DynamicTest> {
val testSourceUri = PathSource.currentUri
return toList()
.also { require(it.isNotEmpty()) { "At least one subject must be provided for testing." } }
.map { subject: T ->
DynamicTest.dynamicTest(
displayNameFor(subject, testNamePattern),
testSourceUri,
if (softly) {
Executable { com.bkahlert.kommons.test.testAll { assertions(subject) } }
} else {
Executable { assertions(subject) }
},
)
}.stream()
}
/**
* Builds a single test
* that [softly] checks the specified [assertions]
* for each subject of this [Sequence].
*
* The name for each container is heuristically derived but can also be explicitly specified using [testNamePattern]
* which supports curly placeholders `{}` like [SLF4J] does.
*/
public fun <T> Sequence<T>.testEach(
testNamePattern: String? = null,
softly: Boolean = true,
assertions: Assertions<T>,
): Stream<DynamicTest> = toList().testEach(testNamePattern, softly, assertions)
/**
* Builds a single test
* that [softly] checks the specified [assertions]
* for each entry of this [Map].
*
* The name for each container is heuristically derived but can also be explicitly specified using [testNamePattern]
* which supports curly placeholders `{}` like [SLF4J] does.
*/
public fun <K, V> Map<K, V>.testEach(
testNamePattern: String? = null,
softly: Boolean = true,
assertions: Assertions<Map.Entry<K, V>>,
): Stream<DynamicTest> = entries.testEach(testNamePattern, softly, assertions)
| 5
| null |
0
| 18
|
747cb51cf6e6b729d574396a4938eabafbdac1fe
| 2,874
|
kommons
|
MIT License
|
app/src/main/java/com/example/quizapp/QuestionModel.kt
|
raj-tyagi
| 789,742,149
| false
|
{"Kotlin": 10279}
|
package com.example.quizapp
class QuestionModel {
var question:String?=null
var option1:String?=null
var option2:String?=null
var option3:String?=null
var option4:String?=null
var ans:String?=null
constructor()
constructor(
question: String?,
option1: String?,
option2: String?,
option3: String?,
option4: String?,
ans: String?
) {
this.question = question
this.option1 = option1
this.option2 = option2
this.option3 = option3
this.option4 = option4
this.ans = ans
}
}
| 0
|
Kotlin
|
0
| 2
|
bc5ccf5cc1c2c1b9edd13b88f06e74c11aec8f0c
| 607
|
Quizzer-An-online-quiz-app
|
MIT License
|
src/main/kotlin/org/wfanet/measurement/reporting/deploy/v2/postgres/writers/CreateReport.kt
|
world-federation-of-advertisers
| 349,561,061
| false
|
{"Kotlin": 8289739, "Starlark": 874737, "C++": 488532, "CUE": 150756, "HCL": 143493, "TypeScript": 92086, "Shell": 21505, "Go": 8099, "CSS": 6969, "JavaScript": 5275, "HTML": 2188}
|
/*
* Copyright 2023 The Cross-Media Measurement 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wfanet.measurement.reporting.deploy.v2.postgres.writers
import com.google.protobuf.util.Timestamps
import java.time.Instant
import java.time.ZoneOffset
import java.util.UUID
import kotlinx.coroutines.flow.toList
import org.wfanet.measurement.common.db.r2dbc.BoundStatement
import org.wfanet.measurement.common.db.r2dbc.boundStatement
import org.wfanet.measurement.common.db.r2dbc.postgres.PostgresWriter
import org.wfanet.measurement.common.identity.InternalId
import org.wfanet.measurement.common.toInstant
import org.wfanet.measurement.common.toJson
import org.wfanet.measurement.common.toProtoTime
import org.wfanet.measurement.internal.reporting.v2.CreateReportRequest
import org.wfanet.measurement.internal.reporting.v2.Report
import org.wfanet.measurement.internal.reporting.v2.copy
import org.wfanet.measurement.reporting.deploy.v2.postgres.readers.MeasurementConsumerReader
import org.wfanet.measurement.reporting.deploy.v2.postgres.readers.MetricCalculationSpecReader
import org.wfanet.measurement.reporting.deploy.v2.postgres.readers.ReportReader
import org.wfanet.measurement.reporting.deploy.v2.postgres.readers.ReportScheduleReader
import org.wfanet.measurement.reporting.deploy.v2.postgres.readers.ReportingSetReader
import org.wfanet.measurement.reporting.service.internal.MeasurementConsumerNotFoundException
import org.wfanet.measurement.reporting.service.internal.MetricCalculationSpecNotFoundException
import org.wfanet.measurement.reporting.service.internal.ReportAlreadyExistsException
import org.wfanet.measurement.reporting.service.internal.ReportScheduleNotFoundException
import org.wfanet.measurement.reporting.service.internal.ReportingSetNotFoundException
/**
* Inserts a Report into the database.
*
* Throws the following on [execute]:
* * [ReportingSetNotFoundException] ReportingSet not found
* * [MeasurementConsumerNotFoundException] MeasurementConsumer not found
* * [MetricCalculationSpecNotFoundException] MetricCalculationSpec not found
* * [ReportScheduleNotFoundException] ReportSchedule not found
* * [ReportAlreadyExistsException] Report already exists
*/
class CreateReport(private val request: CreateReportRequest) : PostgresWriter<Report>() {
private data class ReportingMetricEntriesAndBinders(
val metricCalculationSpecReportingMetricsBinders: List<BoundStatement.Binder.() -> Unit>,
val updatedReportingMetricEntries: Map<String, Report.ReportingMetricCalculationSpec>,
)
override suspend fun TransactionScope.runTransaction(): Report {
val measurementConsumerId =
(MeasurementConsumerReader(transactionContext)
.getByCmmsId(request.report.cmmsMeasurementConsumerId)
?: throw MeasurementConsumerNotFoundException())
.measurementConsumerId
val createReportRequestId = request.requestId
val report = request.report
// Request IDs take precedence
if (createReportRequestId.isNotBlank()) {
val existingReportResult: ReportReader.Result? =
ReportReader(transactionContext)
.readReportByRequestId(measurementConsumerId, createReportRequestId)
if (existingReportResult != null) {
return existingReportResult.report
}
}
// If we can't find a report given the request ID but found a report given the external ID,
// return Already Exists exception.
if (
ReportReader(transactionContext)
.readReportByExternalId(report.cmmsMeasurementConsumerId, request.externalReportId) != null
) {
throw ReportAlreadyExistsException()
}
val externalReportingSetIds: Set<String> = buildSet {
report.reportingMetricEntriesMap.entries.forEach { add(it.key) }
}
val reportingSetMap: Map<String, InternalId> =
ReportingSetReader(transactionContext)
.readIds(measurementConsumerId, externalReportingSetIds)
.toList()
.associateBy({ it.externalReportingSetId }, { it.reportingSetId })
if (reportingSetMap.size < externalReportingSetIds.size) {
throw ReportingSetNotFoundException()
}
val externalMetricCalculationSpecIds: Set<String> = buildSet {
for (reportingMetricCalculationSpec in report.reportingMetricEntriesMap.values) {
reportingMetricCalculationSpec.metricCalculationSpecReportingMetricsList.forEach {
add(it.externalMetricCalculationSpecId)
}
}
}
val metricCalculationSpecMap: Map<String, InternalId> =
MetricCalculationSpecReader(transactionContext)
.batchReadByExternalIds(
request.report.cmmsMeasurementConsumerId,
externalMetricCalculationSpecIds
)
.associateBy(
{ it.metricCalculationSpec.externalMetricCalculationSpecId },
{ it.metricCalculationSpecId }
)
if (metricCalculationSpecMap.size < externalMetricCalculationSpecIds.size) {
externalMetricCalculationSpecIds.forEach {
if (!metricCalculationSpecMap.containsKey(it)) {
throw MetricCalculationSpecNotFoundException(
cmmsMeasurementConsumerId = report.cmmsMeasurementConsumerId,
externalMetricCalculationSpecId = it
)
}
}
}
val reportId = idGenerator.generateInternalId()
val externalReportId = request.externalReportId
val createTime = Instant.now().atOffset(ZoneOffset.UTC)
val statement =
boundStatement(
"""
INSERT INTO Reports
(
MeasurementConsumerId,
ReportId,
ExternalReportId,
CreateReportRequestId,
CreateTime,
Periodic,
ReportDetails,
ReportDetailsJson
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
"""
) {
bind("$1", measurementConsumerId)
bind("$2", reportId)
bind("$3", externalReportId)
if (createReportRequestId.isNotEmpty()) {
bind("$4", createReportRequestId)
} else {
bind<String?>("$4", null)
}
bind("$5", createTime)
bind("$6", report.timeCase == Report.TimeCase.PERIODIC_TIME_INTERVAL)
bind("$7", report.details)
bind("$8", report.details.toJson())
}
val reportTimeIntervalsStatement =
boundStatement(
"""
INSERT INTO ReportTimeIntervals
(
MeasurementConsumerId,
ReportId,
TimeIntervalStart,
TimeIntervalEndExclusive
)
VALUES ($1, $2, $3, $4)
"""
) {
createReportTimeIntervalsBindings(measurementConsumerId, reportId, report).forEach {
addBinding(it)
}
}
val reportingMetricEntriesAndBinders =
createMetricCalculationSpecBindings(
measurementConsumerId,
reportId,
report,
reportingSetMap,
metricCalculationSpecMap
)
val metricCalculationSpecReportingMetricsStatement =
boundStatement(
"""
INSERT INTO MetricCalculationSpecReportingMetrics
(
MeasurementConsumerId,
ReportId,
ReportingSetId,
MetricCalculationSpecId,
CreateMetricRequestId,
ReportingMetricDetails,
ReportingMetricDetailsJson
)
VALUES ($1, $2, $3, $4, $5, $6, $7)
"""
) {
reportingMetricEntriesAndBinders.metricCalculationSpecReportingMetricsBinders.forEach {
addBinding(it)
}
}
transactionContext.run {
executeStatement(statement)
executeStatement(reportTimeIntervalsStatement)
executeStatement(metricCalculationSpecReportingMetricsStatement)
if (request.externalReportScheduleId.isNotEmpty()) {
val reportScheduleId =
(ReportScheduleReader(transactionContext)
.readReportScheduleByExternalId(
request.report.cmmsMeasurementConsumerId,
request.externalReportScheduleId
)
?: throw ReportScheduleNotFoundException(
cmmsMeasurementConsumerId = request.report.cmmsMeasurementConsumerId,
externalReportScheduleId = request.externalReportScheduleId
))
.reportScheduleId
val reportsReportSchedulesStatement =
boundStatement(
"""
INSERT INTO ReportsReportSchedules
(
MeasurementConsumerId,
ReportId,
ReportScheduleId
)
VALUES ($1, $2, $3)
"""
) {
bind("$1", measurementConsumerId)
bind("$2", reportId)
bind("$3", reportScheduleId)
}
executeStatement(reportsReportSchedulesStatement)
}
}
return request.report.copy {
this.createTime = createTime.toInstant().toProtoTime()
this.externalReportId = externalReportId
externalReportScheduleId = request.externalReportScheduleId
reportingMetricEntries.clear()
reportingMetricEntries.putAll(reportingMetricEntriesAndBinders.updatedReportingMetricEntries)
}
}
private fun createReportTimeIntervalsBindings(
measurementConsumerId: InternalId,
reportId: InternalId,
report: Report,
): List<BoundStatement.Binder.() -> Unit> {
val reportTimeIntervalsBinders = mutableListOf<BoundStatement.Binder.() -> Unit>()
if (report.hasTimeIntervals()) {
report.timeIntervals.timeIntervalsList.forEach {
reportTimeIntervalsBinders.add {
bind("$1", measurementConsumerId)
bind("$2", reportId)
bind("$3", it.startTime.toInstant().atOffset(ZoneOffset.UTC))
bind("$4", it.endTime.toInstant().atOffset(ZoneOffset.UTC))
}
}
} else if (report.hasPeriodicTimeInterval()) {
val periodicTimeInterval = report.periodicTimeInterval
var startTime = periodicTimeInterval.startTime
var endTime = Timestamps.add(startTime, periodicTimeInterval.increment)
for (i in 1..periodicTimeInterval.intervalCount) {
val intervalStartTime = startTime.toInstant().atOffset(ZoneOffset.UTC)
val intervalEndTime = endTime.toInstant().atOffset(ZoneOffset.UTC)
reportTimeIntervalsBinders.add {
bind("$1", measurementConsumerId)
bind("$2", reportId)
bind("$3", intervalStartTime)
bind("$4", intervalEndTime)
}
startTime = endTime
endTime = Timestamps.add(startTime, periodicTimeInterval.increment)
}
}
return reportTimeIntervalsBinders
}
private fun TransactionScope.createMetricCalculationSpecBindings(
measurementConsumerId: InternalId,
reportId: InternalId,
report: Report,
// Map of external id to internal id.
reportingSetMap: Map<String, InternalId>,
// Map of external id to internal id.
metricCalculationSpecMap: Map<String, InternalId>,
): ReportingMetricEntriesAndBinders {
val metricCalculationSpecReportingMetricsBinders =
mutableListOf<BoundStatement.Binder.() -> Unit>()
val updatedReportingMetricEntries =
mutableMapOf<String, Report.ReportingMetricCalculationSpec>()
for (entry in report.reportingMetricEntriesMap.entries) {
val updatedMetricCalculationSpecReportingMetricsList =
mutableListOf<Report.MetricCalculationSpecReportingMetrics>()
for (metricCalculationSpecReportingMetrics in
entry.value.metricCalculationSpecReportingMetricsList) {
val metricCalculationSpecId =
metricCalculationSpecMap[
metricCalculationSpecReportingMetrics.externalMetricCalculationSpecId]
val updatedReportingMetricsList = mutableListOf<Report.ReportingMetric>()
metricCalculationSpecReportingMetrics.reportingMetricsList.forEach {
val createMetricRequestId = UUID.randomUUID()
metricCalculationSpecReportingMetricsBinders.add {
bind("$1", measurementConsumerId)
bind("$2", reportId)
bind("$3", reportingSetMap[entry.key])
bind("$4", metricCalculationSpecId)
bind("$5", createMetricRequestId)
bind("$6", it.details)
bind("$7", it.details.toJson())
}
updatedReportingMetricsList.add(
it.copy { this.createMetricRequestId = createMetricRequestId.toString() }
)
}
updatedMetricCalculationSpecReportingMetricsList.add(
metricCalculationSpecReportingMetrics.copy {
reportingMetrics.clear()
reportingMetrics.addAll(updatedReportingMetricsList)
}
)
}
updatedReportingMetricEntries[entry.key] =
entry.value.copy {
metricCalculationSpecReportingMetrics.clear()
metricCalculationSpecReportingMetrics.addAll(
updatedMetricCalculationSpecReportingMetricsList
)
}
}
return ReportingMetricEntriesAndBinders(
metricCalculationSpecReportingMetricsBinders = metricCalculationSpecReportingMetricsBinders,
updatedReportingMetricEntries = updatedReportingMetricEntries,
)
}
}
| 86
|
Kotlin
|
10
| 31
|
3dfc0e996ede62cdf5e690f6119c2596169864ef
| 13,698
|
cross-media-measurement
|
Apache License 2.0
|
sdk/src/test/kotlin/trade/repositories/dw_user_portfolio_repo_test.kt
|
Laplace-Analytics
| 673,237,581
| false
|
{"Kotlin": 499822}
|
package trade.repositories
import MockStorage
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.fail
import sdk.api.AuthApiProvider
import sdk.api.CoreApiProvider
import sdk.api.LoginResponse
import sdk.api.LoginResponseData
import sdk.api.LoginResponseTypes
import sdk.base.network.HTTPHandler
import sdk.models.data.assets.Region
import sdk.models.core.AssetProvider
import sdk.repositories.AssetRepo
import sdk.trade.generic_api.DriveWealthPortfolioApiProvider
import sdk.trade.models.portfolio.UserPortfolio
import sdk.trade.repositories.drivewealth_repos.DriveWealthUserPortfolioRepo
class DriveWealthUserPortfolioRepoTests {
private lateinit var authApiProvider: AuthApiProvider
private lateinit var baseHttpHandler: HTTPHandler
private lateinit var assetProvider: AssetProvider
private lateinit var coreApiProvider: CoreApiProvider
private lateinit var assetRepo: AssetRepo
private lateinit var driveWealthHttpHandler: HTTPHandler
private lateinit var driveWealthPortfolioApiProvider: DriveWealthPortfolioApiProvider
private lateinit var driveWealthUserPortfolioRepo: DriveWealthUserPortfolioRepo
@BeforeEach
fun setup() {
baseHttpHandler = HTTPHandler(httpURL = "finfree.app")
driveWealthHttpHandler = HTTPHandler(httpURL = "uat.drivewealth.finfree.app")
authApiProvider = AuthApiProvider(baseHttpHandler)
coreApiProvider = CoreApiProvider(baseHttpHandler)
assetRepo = AssetRepo(MockStorage(),coreApiProvider)
assetProvider = AssetProvider(assetRepo = assetRepo)
driveWealthPortfolioApiProvider = DriveWealthPortfolioApiProvider(driveWealthHttpHandler, "api/v1/tr")
driveWealthUserPortfolioRepo = DriveWealthUserPortfolioRepo(
MockStorage(),
driveWealthPortfolioApiProvider,
assetProvider,
)
}
@Nested
inner class GetPortfolioTests{
@Test
fun `Fetch data test`() = runBlocking {
val loginResponse: LoginResponse = authApiProvider.postLogin("KereM", "Kfener2002.")
if (loginResponse.responseType != LoginResponseTypes.SUCCESS) {
fail("Could not login to Finfree Account")
}
val loginData: LoginResponseData = loginResponse.data!!
baseHttpHandler.token = loginData.accessToken
driveWealthHttpHandler.token = loginData.accessToken
driveWealthHttpHandler.constantHeaders["GEDIK-ACCOUNT-ID"] = "928607"
assetProvider.init(setOf(Region.American, Region.Turkish))
val userPortfolio: UserPortfolio? = driveWealthUserPortfolioRepo.fetchData(null)
assertNotNull(userPortfolio)
}
@Test
fun `Fetch after token expire scenario`() = runBlocking {
driveWealthHttpHandler.token =
"<KEY>"
var userPortfolio: UserPortfolio? = driveWealthUserPortfolioRepo.fetchData(null)
assertNull(userPortfolio)
val loginResponse: LoginResponse = authApiProvider.postLogin("KereM", "Kfener2002.")
if (loginResponse.responseType != LoginResponseTypes.SUCCESS) {
fail("Could not login to Finfree Account")
}
val loginData: LoginResponseData = loginResponse.data!!
baseHttpHandler.token = loginData.accessToken
driveWealthHttpHandler.token = loginData.accessToken
driveWealthHttpHandler.constantHeaders["GEDIK-ACCOUNT-ID"] = "928607"
assetProvider.init(setOf(Region.American, Region.Turkish))
val userPortfolio2: UserPortfolio? = driveWealthUserPortfolioRepo.fetchData(null)
assertNotNull(userPortfolio2)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
0e8609bfd4124ef684466868ceaf4c19612fb4d4
| 3,959
|
finfree-kotlin-sdk
|
Apache License 2.0
|
android/app/src/main/java/com/esptimer/config/PreferencesHelper.kt
|
antoinebou12
| 757,034,050
| false
|
{"Kotlin": 62877, "C++": 42693, "C": 2350}
|
package com.esptimer.config
import android.content.Context
class PreferencesHelper(context: Context) {
private val sharedPreferences = context.getSharedPreferences("ESP32Preferences", Context.MODE_PRIVATE)
var espIpAddress: String
get() = sharedPreferences.getString("espIpAddress", "http://esptimer.local") ?: "http://esptimer.local"
set(value) = sharedPreferences.edit().putString("espIpAddress", value).apply()
}
| 8
|
Kotlin
|
0
| 0
|
6cac20eed8dc6293d011a0c8a8341654e0870b80
| 442
|
ESP32-7SEG
|
MIT License
|
app/src/main/java/com/lianyi/paimonsnotebook/common/extension/request/SetDynamicSecret.kt
|
QooLianyi
| 435,314,581
| false
|
{"Kotlin": 1942953}
|
package com.lianyi.paimonsnotebook.common.extension.request
import com.lianyi.paimonsnotebook.common.util.hoyolab.DynamicSecret
import okhttp3.Request
fun Request.Builder.setDynamicSecret(
saltType: DynamicSecret.SaltType,
version: DynamicSecret.Version = DynamicSecret.Version.Gen1,
includeChars: Boolean = false,
query: String = "",
body: String = "",
) {
val build = this.build()
val urls = build.url.toString().split("?")
val b = if (saltType == DynamicSecret.SaltType.PROD) "{}" else body
if (urls.size > 1) {
val parameters = urls.last().split("&").sortedBy { it }.joinToString(separator = "&") { it }
this.addHeader("DS",
DynamicSecret.getDynamicSecret(version,
saltType,
includeChars,
parameters,
b))
} else {
this.addHeader("DS",
DynamicSecret.getDynamicSecret(version,
saltType,
includeChars,
query,
b))
}
}
| 1
|
Kotlin
|
2
| 36
|
692b93b7e712903c795e1a2ce79859af14e2c197
| 1,041
|
PaimonsNotebook
|
MIT License
|
app/src/main/java/com/example/myinstagram/register/data/RegisterDataSource.kt
|
iguleal
| 679,004,940
| false
|
{"Kotlin": 42648}
|
package com.example.myinstagram.register.data
interface RegisterDataSource {
fun create(email: String, callback: RegisterCallback)
fun create(email: String, name:String, password: String, callback: RegisterCallback)
}
| 0
|
Kotlin
|
0
| 2
|
3b0149acc9fb0cb4855d0fc0649100be4923c223
| 228
|
my_instagram
|
MIT License
|
app/src/main/java/com/example/guidemodernapparchitecture/data/models/BaseResponse.kt
|
alexjoy001
| 512,629,489
| false
|
{"Kotlin": 38916}
|
package com.example.guidemodernapparchitecture.data.models
import com.google.gson.annotations.SerializedName
data class BaseResponse<T: Any>(
@SerializedName("status")
var status: String,
@SerializedName("totalResults")
var totalResults: Int,
@SerializedName("articles")
var articles: T? = null
)
| 0
|
Kotlin
|
0
| 7
|
95e5998cee1faca24cbda97d36db4314801a2e5b
| 322
|
GuideToAndroidModernAppArchitecture
|
MIT License
|
app/src/main/java/com/geofriend/ecommercesampleapp/view/BaseFragment.kt
|
vkvashistha
| 504,568,423
| false
|
{"Kotlin": 41871}
|
package com.geofriend.ecommercesampleapp.view
import androidx.fragment.app.Fragment
open class BaseFragment : Fragment() {
}
| 0
|
Kotlin
|
0
| 0
|
db00bbbd6ec44c184937b31f58827915230fd607
| 126
|
EcommerceSampleApp
|
MIT License
|
kotlin-electron/src/jsMain/generated/electron/common/ProductSubscriptionPeriod.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 11411371, "JavaScript": 154302}
|
package electron.common
typealias ProductSubscriptionPeriod = electron.core.ProductSubscriptionPeriod
| 28
|
Kotlin
|
173
| 1,250
|
9e9dda28cf74f68b42a712c27f2e97d63af17628
| 104
|
kotlin-wrappers
|
Apache License 2.0
|
ViewInterop/app/src/main/java/com/halcyonmobile/viewinterop/example/dynamic_compose_view/DynamicComposeViewActivity.kt
|
halcyonmobile
| 340,389,463
| false
| null |
package com.halcyonmobile.viewinterop.example.dynamic_compose_view
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import com.halcyonmobile.viewinterop.R
import com.halcyonmobile.viewinterop.databinding.ActivityDynamicComposeViewBinding
/**
* You can add ComposeView dynamically like any other view.
* You only need to give it a unique id.
*/
class DynamicComposeViewActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityDynamicComposeViewBinding.inflate(layoutInflater)
setContentView(binding.root)
with(binding.content) {
addView(ComposeView(this@DynamicComposeViewActivity).apply {
id = R.id.compose_view_1
setContent { ComposeContent("You can add ComposeView dynamically in XML") }
})
addView(ComposeView(this@DynamicComposeViewActivity).apply {
id = R.id.compose_view_2
setContent { ComposeContent("Make sure to give it a unique ID") }
})
addView(ComposeView(this@DynamicComposeViewActivity).apply {
id = R.id.compose_view_3
setContent { DocLink() }
})
}
}
}
@Composable
fun ComposeContent(text: String) {
MaterialTheme {
Box(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
Text(text = text, style = MaterialTheme.typography.body1)
}
}
}
@Composable
fun DocLink() {
val uriHandler = LocalUriHandler.current
MaterialTheme {
Box(
Modifier
.clickable { uriHandler.openUri("https://developer.android.com/jetpack/compose/interop/interop-apis#compose-in-views") }
.padding(horizontal = 16.dp, vertical = 8.dp)) {
Text(text = "See docs", style = MaterialTheme.typography.body1.copy(textDecoration = TextDecoration.Underline))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f9eaf5ebf1cd7d4da6dcc9194dfe7abfe1bb0448
| 2,433
|
compose-playground
|
Apache License 2.0
|
app/src/test/java/com/sonder/newdemoapp/di/TestDispatcherProvider.kt
|
gazeing
| 218,930,232
| false
| null |
package com.sonder.newdemoapp.di
import kotlinx.coroutines.Dispatchers
class TestDispatcherProvider : DispatcherProvider {
override fun io() = Dispatchers.Unconfined
override fun ui() = Dispatchers.Unconfined
override fun computation() = Dispatchers.Unconfined
}
| 0
|
Kotlin
|
0
| 0
|
7ad51e42556c8db9b59be852e21d5c1012d56cb3
| 278
|
NewAndDemoApp
|
Apache License 2.0
|
app/src/main/java/com/philips/bleclient/extensions/BluetoothExtensions.kt
|
philips-labs
| 384,088,968
| false
| null |
/*
* Copyright (c) <NAME> 2021.
* All rights reserved.
*/
package com.philips.bleclient
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattCharacteristic.PROPERTY_NOTIFY
import android.bluetooth.BluetoothGattCharacteristic.PROPERTY_INDICATE
import android.bluetooth.BluetoothGattCharacteristic.PROPERTY_READ
import android.bluetooth.BluetoothGattCharacteristic.PROPERTY_WRITE
fun BluetoothGattCharacteristic.isRead(): Boolean = properties and PROPERTY_READ > 0
fun BluetoothGattCharacteristic.isWrite(): Boolean = properties and PROPERTY_WRITE > 0
fun BluetoothGattCharacteristic.isNotify(): Boolean = properties and PROPERTY_NOTIFY > 0
fun BluetoothGattCharacteristic.isIndicate(): Boolean = properties and PROPERTY_INDICATE > 0
| 0
|
Kotlin
|
0
| 1
|
4850963c522645978bae0c752ee67bf39e4b5d06
| 778
|
BLE-GHS-Client-Example
|
MIT License
|
data/src/main/java/com/mohaeyo/data/handler/QAErrorHandlerImpl.kt
|
mohae-team
| 203,272,746
| false
| null |
package com.mohaeyo.data.handler
import com.mohaeyo.domain.base.ErrorHandlerEntity
import com.mohaeyo.domain.handler.QAErrorHandler
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
class QAErrorHandlerImpl: QAErrorHandler {
override fun getQuestionListErrorHandle(throwable: Throwable): ErrorHandlerEntity
= when (throwable) {
is HttpException -> when(throwable.code()) {
200 -> ErrorHandlerEntity(isSuccess = true)
404 -> ErrorHandlerEntity(message = "아직 질문이 없습니다")
403 -> ErrorHandlerEntity(message = "권한이 없습니다")
500 -> ErrorHandlerEntity(message = "서버 에러가 발생했습니다")
else -> ErrorHandlerEntity(message = "알 수 없는 오류가 발생했습니다")
}
is ConnectException -> ErrorHandlerEntity(message = "인터넷 연결이 되지 않았습니다")
is SocketTimeoutException -> ErrorHandlerEntity(message = "인터넷 연결이 불안정합니다")
else -> ErrorHandlerEntity()
}
override fun getQuestionDetailErrorHandle(throwable: Throwable): ErrorHandlerEntity
= when (throwable) {
is HttpException -> when(throwable.code()) {
200 -> ErrorHandlerEntity(isSuccess = true)
404 -> ErrorHandlerEntity(message = "존재하지 않는 질문입니다")
403 -> ErrorHandlerEntity(message = "권한이 없습니다")
500 -> ErrorHandlerEntity(message = "서버 에러가 발생했습니다")
else -> ErrorHandlerEntity(message = "알 수 없는 오류가 발생했습니다")
}
is ConnectException -> ErrorHandlerEntity(message = "인터넷 연결이 되지 않았습니다")
is SocketTimeoutException -> ErrorHandlerEntity(message = "인터넷 연결이 불안정합니다")
else -> ErrorHandlerEntity()
}
override fun createQuestionErrorHandle(throwable: Throwable): ErrorHandlerEntity
= when (throwable) {
is HttpException -> when(throwable.code()) {
200 -> ErrorHandlerEntity(isSuccess = true)
404 -> ErrorHandlerEntity(message = "존재하지 않는 유저입니다")
403 -> ErrorHandlerEntity(message = "권한이 없습니다")
500 -> ErrorHandlerEntity(message = "서버 에러가 발생했습니다")
else -> ErrorHandlerEntity(message = "알 수 없는 오류가 발생했습니다")
}
is ConnectException -> ErrorHandlerEntity(message = "인터넷 연결이 되지 않았습니다")
is SocketTimeoutException -> ErrorHandlerEntity(message = "인터넷 연결이 불안정합니다")
else -> ErrorHandlerEntity()
}
override fun getAnswerListErrorHandle(throwable: Throwable): ErrorHandlerEntity
= when (throwable) {
is HttpException -> when(throwable.code()) {
200 -> ErrorHandlerEntity(isSuccess = true)
404 -> ErrorHandlerEntity(message = "아직 답변이 없습니다")
403 -> ErrorHandlerEntity(message = "권한이 없습니다")
500 -> ErrorHandlerEntity(message = "서버 에러가 발생했습니다")
else -> ErrorHandlerEntity(message = "알 수 없는 오류가 발생했습니다")
}
is ConnectException -> ErrorHandlerEntity(message = "인터넷 연결이 되지 않았습니다")
is SocketTimeoutException -> ErrorHandlerEntity(message = "인터넷 연결이 불안정합니다")
else -> ErrorHandlerEntity()
}
override fun createAnswerErrorHandle(throwable: Throwable): ErrorHandlerEntity
= when (throwable) {
is HttpException -> when(throwable.code()) {
200 -> ErrorHandlerEntity(isSuccess = true)
404 -> ErrorHandlerEntity(message = "존재하지 않는 답변이 입니다")
403 -> ErrorHandlerEntity(message = "권한이 없습니다")
500 -> ErrorHandlerEntity(message = "서버 에러가 발생했습니다")
else -> ErrorHandlerEntity(message = "알 수 없는 오류가 발생했습니다")
}
is ConnectException -> ErrorHandlerEntity(message = "인터넷 연결이 되지 않았습니다")
is SocketTimeoutException -> ErrorHandlerEntity(message = "인터넷 연결이 불안정합니다")
else -> ErrorHandlerEntity()
}
}
| 0
|
Kotlin
|
0
| 7
|
8cb78fbb241fce9c6fbbbbf1ea22a7b9102c475d
| 3,804
|
MoHae-Android
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.