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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
plugins/kotlin/idea/tests/testData/inspectionsLocal/simplifyWhenWithBooleanConstantCondition/trueIsTop3.kt | ingokegel | 72,937,917 | true | null | // WITH_STDLIB
fun test() {
wh<caret>en {
true -> {
println(1)
}
else -> {
println(2)
}
}
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 155 | intellij-community | Apache License 2.0 |
lib-screensharing/src/main/java/io/agora/rtc/screenshare/AgentListActivity.kt | livestorehub | 371,293,114 | false | {"Java": 303933, "Kotlin": 79680} | package io.agora.rtc.screenshare
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.iid.FirebaseInstanceId
import io.agora.rtc.MyApplication
import io.agora.rtc.MyApplication.Companion.apiInterface
import io.agora.rtc.screenshare.Constants.Companion.sscontext
import io.agora.rtc.screenshare.adapter.UsersAdapter
import io.agora.rtc.screenshare.callback.OnItemClick
import io.agora.rtc.screenshare.model.CommonData
import io.agora.rtc.screenshare.model.ResponseCommon
import io.agora.rtc.screenshare.utils.CustomToast
import io.agora.rtc.screenshare.utils.LoggerClass
import io.agora.rtc.screenshare.utils.SharedPref
import io.agora.rtc.screenshare.utils.retrofit.RetrofitCallInterface
import io.agora.rtc.screenshare.utils.retrofit.RetrofitClass
import io.agora.rtc.ss.R
import io.agora.rtc.ss.databinding.ActivityAgentListBinding
import retrofit2.Call
import retrofit2.Response
import java.io.IOException
import java.util.*
import kotlin.collections.ArrayList
class AgentListActivity : AppCompatActivity(), OnItemClick {
private lateinit var binding: ActivityAgentListBinding
private var mDelayHandler: Handler? = null
private val SPLASH_DELAY: Long = 1000 //3 seconds
var list : ArrayList<Any> = ArrayList()
lateinit var dialog: AlertDialog
override fun onCreate(savedInstanceState: Bundle?) {
//window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR // for status bar text black
super.onCreate(savedInstanceState)
binding = ActivityAgentListBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.llProgress.visibility = View.VISIBLE
SharedPref.saveBoolean(Constants.stop, false)
// getAuthToken()
if (SharedPref.contains(Constants.TOKEN)) {
if (SharedPref.getString(Constants.TOKEN) != null) {
mDelayHandler = Handler(Looper.getMainLooper())
mDelayHandler!!.postDelayed(mRunnable, SPLASH_DELAY)
}
else
getAuthToken()
}
else {
getAuthToken()
}
}
private fun getAuthToken() {
val call3: Call<ResponseCommon?> = apiInterface!!.getAuthToken(
intent.getStringExtra(Constants.ENTERPRISEAPIKEY),
encode(intent.getStringExtra(Constants.ENTERPRISEKEY)!!),
encode(intent.getStringExtra(Constants.ENTERPRISESECRET)!!),
intent.getStringExtra(Constants.CUSTOMERID),
intent.getStringExtra(Constants.CUSTOMERFIRSTNAME),
intent.getStringExtra(Constants.CUSTOMERLASTNAME),
intent.getStringExtra(Constants.CUSTOMEREMAIL),
intent.getStringExtra(Constants.CUSTOMERPHONE),
)
RetrofitClass().retroCall(call3, object : RetrofitCallInterface {
override fun onSuccess(response: Response<ResponseCommon?>?) {
if (response?.body()?.status?.code.equals("200")) {
LoggerClass.d("dfdkfhd", response!!.body()!!.data!!.token)
SharedPref.saveString(Constants.TOKEN, "Bearer " + response.body()!!.data!!.token)
mDelayHandler = Handler(Looper.getMainLooper())
mDelayHandler!!.postDelayed(mRunnable, SPLASH_DELAY)
} else {
binding.llProgress.visibility = View.GONE
binding.rvAgentList.visibility = View.GONE
binding.tvNoData.visibility = View.VISIBLE
binding.tvNoData.text = response?.body()?.data?.errorMsg
// CustomToast(this@AgentListActivity).toast(response?.body()?.data?.errorMsg, 0)
}
}
override fun onFailure(response: Response<*>?) {
binding.llProgress.visibility = View.GONE
binding.rvAgentList.visibility = View.GONE
binding.tvNoData.visibility = View.VISIBLE
binding.tvNoData.text = "Something went wrong"
}
override fun onError(error: String?) {
binding.llProgress.visibility = View.GONE
binding.rvAgentList.visibility = View.GONE
binding.tvNoData.visibility = View.VISIBLE
binding.tvNoData.text = "Something went wrong"
}
}, this)
}
private val mRunnable: Runnable = Runnable {
if (!isFinishing) {
getToken()
}
}
private fun getToken() {
Thread {
try {
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(
this@AgentListActivity
) {
val mToken = it.token
LoggerClass.e("dkgsjfgsfdf", mToken)
saveAppToken(mToken)
}
} catch (e: IOException) {
e.printStackTrace()
}
}.start()
}
private fun saveAppToken(token: String) {
val call3: Call<ResponseCommon?>?
call3 = apiInterface!!.saveAppToken(
SharedPref.getString(Constants.TOKEN)!!, token, "android"
)
RetrofitClass().retroCall(call3, object : RetrofitCallInterface {
override fun onSuccess(response: Response<ResponseCommon?>?) {
//Constants.hideProgressDialog()
// CustomToast(this@AgentListActivity).toast("success", 1)
getAgentList()
}
override fun onFailure(response: Response<*>?) {
//Constants.hideProgressDialog()
saveAppToken(token)
}
override fun onError(error: String?) {
//Constants.hideProgressDialog()
saveAppToken(token)
}
},this)
}
private fun getAgentList() {
val call3: Call<ResponseCommon?> = apiInterface!!.getSalesAgents(
SharedPref.getString(Constants.TOKEN)!!
)
RetrofitClass().retroCall(call3, object : RetrofitCallInterface {
override fun onSuccess(response: Response<ResponseCommon?>?) {
if (response?.body()?.status?.code.equals("200")) {
LoggerClass.d("dfdkfhd", response!!.body().toString())
list.clear()
list.addAll(response.body()!!.data!!.users!!)
if (list.size>0) {
val mdAdapter = UsersAdapter(
this@AgentListActivity,
list,
"",
this@AgentListActivity
)
/*var mdAdapter = SalesUserAdapter(
this@AgentListActivity!!,
list, "Sales", this@AgentListActivity, "salesPerson"
)
*/
binding.rvAgentList.layoutManager = LinearLayoutManager(
this@AgentListActivity,
LinearLayoutManager.VERTICAL,
false
)
binding.rvAgentList.itemAnimator = DefaultItemAnimator()
binding.rvAgentList.isNestedScrollingEnabled = false
binding.rvAgentList.adapter = mdAdapter
binding.llProgress.visibility = View.GONE
binding.rvAgentList.visibility = View.VISIBLE
binding.tvNoData.visibility = View.GONE
}
else {
binding.llProgress.visibility = View.GONE
binding.rvAgentList.visibility = View.GONE
binding.tvNoData.visibility = View.VISIBLE
binding.tvNoData.text = "Agents are not available at this movement"
}
} else {
binding.llProgress.visibility = View.GONE
binding.rvAgentList.visibility = View.GONE
binding.tvNoData.visibility = View.VISIBLE
binding.tvNoData.text = response?.body()?.data?.errorMsg
}
}
override fun onFailure(response: Response<*>?) {
binding.llProgress.visibility = View.GONE
binding.rvAgentList.visibility = View.GONE
binding.tvNoData.visibility = View.VISIBLE
binding.tvNoData.text = "Something went wrong"
}
override fun onError(error: String?) {
binding.llProgress.visibility = View.GONE
binding.rvAgentList.visibility = View.GONE
binding.tvNoData.visibility = View.VISIBLE
binding.tvNoData.text = "Something went wrong"
}
}, this)
}
private fun encode(text: String) : String{
var authkey: String? = ""
Log.d("ffffffff", Build.VERSION.SDK_INT.toString())
if (Build.VERSION.SDK_INT >= 26)
authkey = Base64.getEncoder().encodeToString(text.toByteArray())
else
authkey = android.util.Base64.encodeToString(text.toByteArray(), android.util.Base64.NO_WRAP)
return authkey!!
}
fun onBack(view: View) {}
override fun onItemClickCallBack(data: Any, screen: String, pos: Int) {
if (screen == "share") {
data as CommonData.Customer
callProgressDailog(this@AgentListActivity, "Please wait")
getConnectionRoom(data.id!!)
}
}
private fun getConnectionRoom(agent_id : String) {
val call3: Call<ResponseCommon?> = apiInterface!!.getConnectioRoom(
SharedPref.getString(Constants.TOKEN)!!, agent_id
)
RetrofitClass().retroCall(call3, object : RetrofitCallInterface {
override fun onSuccess(response: Response<ResponseCommon?>?) {
hideProgressDialog()
if (response?.body()?.status?.code.equals("200")) {
LoggerClass.d("dfdkfhd", response!!.body()!!.data?.toString())
LoggerClass.d("dfdkfhd", response!!.body()!!.data?.agoraConfig!!.appId)
LoggerClass.d("dfdkfhd", response!!.body()!!.data?.room!!.channel_name!!)
SharedPref.saveObject(response.body()!!.data, this@AgentListActivity, Constants.CONNECTION_DATA)
Share(sscontext!!,response.body()!!.data)
finish()
} else {
CustomToast(this@AgentListActivity).toast(response?.body()?.data?.errorMsg, 0)
}
}
override fun onFailure(response: Response<*>?) {
CustomToast(this@AgentListActivity).toast("Something went wrong", 0)
hideProgressDialog()
}
override fun onError(error: String?) {
CustomToast(this@AgentListActivity).toast("Something went wrong", 0)
hideProgressDialog()
}
}, this)
}
private fun callProgressDailog(activity: Activity, msg: String) {
val builder: AlertDialog.Builder = AlertDialog.Builder(activity)
val customLayout: View = activity.layoutInflater.inflate(R.layout.progress, null)
val tv = customLayout.findViewById<TextView>(R.id.loading_msg)
tv.text = msg
builder.setView(customLayout)
dialog = builder.create()
dialog.setCanceledOnTouchOutside(false)
dialog.setCancelable(false)
dialog.show()
}
fun hideProgressDialog() {
dialog.dismiss()
}
} | 1 | null | 1 | 1 | 2579615334b4dd4a7231fdd67f934724db02dfec | 12,070 | screenshare | Apache License 2.0 |
android/AMP/app/src/main/java/io/streamroot/dna/samples/amp/PlayerActivity.kt | streamroot | 131,867,507 | false | null | package io.streamroot.dna.samples.amp
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.akamai.amp.media.VideoPlayerContainer
import com.akamai.amp.media.VideoPlayerView
import android.view.WindowManager
import com.akamai.amp.media.elements.MediaResource
import kotlinx.android.synthetic.main.content_player.*
import com.akamai.amp.media.errors.ErrorType
import io.streamroot.dna.samples.amp.impl.AMPSRModule
class PlayerActivity : AppCompatActivity(), VideoPlayerContainer.VideoPlayerContainerCallback {
data class PlayerActivityArgs(val url:String?)
companion object {
private const val ARG_STREAM_URL = "streamUrl"
fun makeIntent(ctx: Context, args: PlayerActivityArgs) : Intent {
return Intent(ctx, PlayerActivity::class.java).apply {
putExtra(ARG_STREAM_URL, args.url)
}
}
fun extractArgs(i: Intent) : PlayerActivityArgs {
return PlayerActivityArgs(
i.getStringExtra(ARG_STREAM_URL)
)
}
}
private var srModule: AMPSRModule? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_player)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
videoPlayerContainer.addVideoPlayerContainerCallback(this)
val args = extractArgs(intent)
val url = args.url?.takeUnless { it.isEmpty() } ?: AMPSRConfig.DEFAULT_VIDEO_URL
start(AMPSRConfig.DNA_ENABLED, url)
}
fun start(srEnabled: Boolean, url: String) = with (if (srEnabled) {
val loadControl = videoPlayerContainer.setBufferDimensions(5000, 30000, 2500,5000)
srModule = AMPSRModule(this, videoPlayerContainer, loadControl, url)
srModule?.enableStats(streamrootDnaStatsView)
srModule?.finalUrl()?.toString() ?: url
} else {
streamrootDnaStatsView.visibility = View.GONE
url
}) { videoPlayerContainer.prepareResource(this) }
fun videoPlayer() : VideoPlayerView? { return videoPlayerContainer.videoPlayer }
override fun onResourceReady(mediaResource: MediaResource?) {
videoPlayer()?.let {
srModule?.setPlayerView(it)
initPlayer(it)
it.play(mediaResource)
}
}
private fun initPlayer(player: VideoPlayerView) = player.apply {
progressBarControl = progressBar
setLicense(AMPSRConfig.AMP_LICENSE(applicationContext))
setLogEnabled(true)
isFullScreen = true
fullScreenMode = VideoPlayerView.FULLSCREEN_MODE_KEEP_ASPECT_RATIO
}
override fun onVideoPlayerCreated() {}
override fun onResourceError(errorType: ErrorType, exception: Exception) {}
override fun onResume() {
super.onResume()
videoPlayer()?.onResume()
}
override fun onPause() {
videoPlayer()?.onPause()
super.onPause()
}
override fun onDestroy() {
videoPlayer()?.onDestroy()
srModule?.terminate()
super.onDestroy()
}
} | 0 | null | 13 | 5 | ade409a4f7e4f1a29c78b13204521004b312e4ae | 3,204 | dna-integration-samples | Apache License 2.0 |
lib_common/src/main/java/com/quyunshuo/wanandroid/common/helper/ResponseException.kt | Quyunshuo | 389,148,840 | false | null | package com.quyunshuo.wanandroid.common.helper
import com.quyunshuo.wanandroid.common.helper.ResponseExceptionEnum as ExceptionType
/**
* 请求响应异常,主要为各种code码专门定义的异常
*
* @property type ResponseExceptionEnum 异常类型枚举,用于标记该异常的类型
* @param msg String 异常信息
*
* @author <NAME>
* @since 2021/7/9 2:57 下午
*/
class ResponseException(val type: ExceptionType, val msg: String) : Exception()
/**
* 空异常,表示该异常已经被处理过了,不需要再做额外处理了
*
* @author <NAME>
* @since 2021/7/9 3:11 下午
*/
class ResponseEmptyException : Exception() | 1 | Kotlin | 7 | 34 | b00274fb9ad349dc8b9d2f32ed1af5e2864246c6 | 515 | WanAndroidMVVM | Apache License 2.0 |
app/src/main/java/com/github/andiim/orchidscan/app/ui/common/snackbar/SnackbarMessage.kt | Andi-IM | 661,461,799 | false | null | package com.github.andiim.orchidscan.app.ui.common.snackbar
import android.content.res.Resources
import androidx.annotation.StringRes
import com.github.andiim.orchidscan.app.R.string as AppText
sealed class SnackbarMessage {
class StringSnackbar(val message: String) : SnackbarMessage()
class ResourceSnackbar(@StringRes val message: Int) : SnackbarMessage()
companion object {
fun SnackbarMessage.toMessage(resources: Resources): String {
return when (this){
is StringSnackbar -> this.message
is ResourceSnackbar -> resources.getString(this.message)
}
}
fun Throwable.toSnackbarMessage(): SnackbarMessage {
val message = this.message.orEmpty()
return if (message.isNotBlank()) StringSnackbar(message)
else ResourceSnackbar(AppText.generic_error)
}
}
} | 0 | Kotlin | 0 | 0 | 306fa7cc5aeae54cef0140817ec7a18a070aada2 | 896 | OrchidScan | MIT License |
ParallaxPagerDemo/app/src/main/java/com/example/parallaxpager/LoginFragment.kt | caojiying002 | 188,341,686 | false | {"Java": 43306, "Kotlin": 14103, "C++": 1659, "CMake": 1590} | package com.example.parallaxpager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_login.*
class LoginFragment : Fragment() {
companion object {
const val LOGIN = 0
const val SIGN_UP = 1
private const val TYPE_TAG = "type"
fun newInstance(type: Int): LoginFragment {
val loginFragment = LoginFragment()
val bundle = Bundle()
bundle.putInt(TYPE_TAG, type)
loginFragment.arguments = bundle
return loginFragment
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_login, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val type = arguments?.getInt(TYPE_TAG)
if (type == LOGIN) {
switchButton.text = getString(R.string.label_login_new_account)
commandButton.text = getString(R.string.label_login_button)
commandButton.setBackgroundResource(R.drawable.ripple_login)
} else {
switchButton.text = getString(R.string.label_login_registered)
commandButton.text = getString(R.string.label_login_sign_up)
commandButton.setBackgroundResource(R.drawable.ripple_sign_up)
//googleButton.visibility = View.GONE
//facebookButton.visibility = View.GONE
optionTextView.visibility = View.GONE
leftLineView.visibility = View.GONE
rightLineView.visibility = View.GONE
}
//progressDialog.isIndeterminate = true
}
} | 0 | Java | 0 | 0 | 94356b5262ffde27286790b9c836aa0ae326d721 | 1,885 | MyAndroidDemos | MIT License |
app/src/main/java/com/stormbirdmedia/dailygenerator/screen/main/MainScreen.kt | Ailelame | 594,734,373 | false | null | @file:OptIn(ExperimentalFoundationApi::class)
package com.stormbirdmedia.dailygenerator.screen.main
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AddCircle
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.outlined.AddCircle
import androidx.compose.material.icons.outlined.Warning
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import com.airbnb.lottie.compose.*
import com.stormbirdmedia.dailygenerator.MainDestination
import com.stormbirdmedia.dailygenerator.OnClickHandler
import com.stormbirdmedia.dailygenerator.R
import com.stormbirdmedia.dailygenerator.domain.models.User
import org.koin.androidx.compose.koinViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
navController: NavController,
viewmodel: MainViewModel = koinViewModel()
) {
val uiState = viewmodel.state.collectAsStateWithLifecycle().value
Scaffold(
topBar = {
TopAppBar(
title = { Text("Daily Generator") },
actions = {
IconButton(onClick = {
navController.navigate(MainDestination.Joke.route)
}) {
val composition: LottieCompositionResult =
rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.cat))
val progress = animateLottieCompositionAsState(
composition.value,
iterations = LottieConstants.IterateForever
)
LottieAnimation(
composition = composition.value,
progress = progress.value
)
}
IconButton(onClick = {
navController.navigate(MainDestination.AddUser.route)
}) {
Icon(Icons.Outlined.AddCircle, "")
}
}
)
}
) { innerPadding ->
ParticipantsLayout(
userList = uiState.userList,
setSelectedForUser = { userName, isSelected ->
viewmodel.setUserSelected(
userName,
isSelected
)
},
randomize = { navController.navigate(MainDestination.Randomizer.route) },
modifier = Modifier.padding(innerPadding)
)
}
}
@Composable
fun ParticipantsLayout(
userList: List<User>,
setSelectedForUser: (userName: String, isSelected: Boolean) -> Unit,
randomize: OnClickHandler,
modifier: Modifier = Modifier
) {
ConstraintLayout(
modifier = Modifier
.fillMaxSize()
.then(modifier)
) {
val (title, list, validateButton) = createRefs()
Text(
text = "${userList.filter { it.isSelected }.size}/${userList.size} participants",
style = MaterialTheme.typography.labelLarge,
modifier = Modifier.constrainAs(title) {
top.linkTo(parent.top)
start.linkTo(parent.start)
})
LazyColumn(
modifier = Modifier.constrainAs(list) {
top.linkTo(title.bottom, 8.dp)
start.linkTo(parent.start)
end.linkTo(parent.end)
bottom.linkTo(validateButton.top)
height = Dimension.fillToConstraints
width = Dimension.fillToConstraints
}) {
items(userList.size,
key = { userList[it].name }) {
UserCardLayout(
userList[it],
setSelectedForUser,
Modifier.animateItemPlacement()
)
}
}
Button(onClick = { randomize() }, modifier = Modifier.constrainAs(validateButton) {
top.linkTo(list.bottom, 8.dp)
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}) {
Text(text = "Randomize")
}
}
}
@Composable
fun UserCardLayout(
currentUser: User,
setSelectedForUser: (userName: String, isSelected: Boolean) -> Unit,
modifier: Modifier = Modifier
) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
.then(modifier),
) {
val checkedState = remember { mutableStateOf(currentUser.isSelected) }
ConstraintLayout(
modifier = Modifier.fillMaxWidth()
) {
val (icon, name, checkbox) = createRefs()
Icon(
imageVector = Icons.Default.Person,
contentDescription = "${currentUser.name}",
modifier = Modifier
.padding(start = 8.dp)
.constrainAs(icon) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
start.linkTo(parent.start, 8.dp)
}
)
Text(
text = currentUser.name.uppercase(),
style = MaterialTheme.typography.labelLarge,
modifier = Modifier.constrainAs(name) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
start.linkTo(icon.end, 8.dp)
end.linkTo(checkbox.start, 8.dp)
width = Dimension.fillToConstraints
})
Checkbox(checked = currentUser.isSelected, onCheckedChange = {
setSelectedForUser(currentUser.name, it)
checkedState.value = it
}, modifier = Modifier.constrainAs(checkbox) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
end.linkTo(parent.end, 8.dp)
})
}
}
}
@Preview
@Composable
fun MainScreenPreview() {
MainScreen(navController = NavController(LocalContext.current))
}
| 0 | Kotlin | 0 | 0 | bc6cd3f008132c78c8d22f6ea271bf78f3aa1e2d | 6,946 | DailyGenerator | MIT License |
runtime/common/src/test/kotlin/kotlinx/serialization/UpdateTest.kt | percula | 162,062,538 | true | {"Kotlin": 490967, "HTML": 2948, "Java": 1372} | /*
* Copyright 2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlinx.serialization
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class UpdateTest {
@Serializable
data class Updatable1(val l: List<Int>)
@Serializable
data class Data(val a: Int)
@Serializable
data class Updatable2(val l: List<Data>)
@Serializable
data class NotUpdatable(val d: Data)
@Serializable
data class NullableInnerIntList(val data: List<Int?>)
@Serializable
data class NullableUpdatable(val data: List<Data>?)
@Test
fun canUpdatePrimitiveList() {
val parsed =
Json(unquoted = true, strictMode = false, updateMode = UpdateMode.UPDATE)
.parse<Updatable1>("""{l:[1,2],f:foo,l:[3,4]}""")
assertEquals(Updatable1(listOf(1,2,3,4)), parsed)
}
@Test
fun canUpdateObjectList() {
val parsed =
Json(unquoted = true, strictMode = false, updateMode = UpdateMode.UPDATE)
.parse<Updatable2>("""{f:bar,l:[{a:42}],l:[{a:43}]}""")
assertEquals(Updatable2(listOf(Data(42), Data(43))), parsed)
}
@Test
fun cantUpdateNotUpdatable() {
assertFailsWith<UpdateNotSupportedException> {
Json(unquoted = true, strictMode = false, updateMode = UpdateMode.UPDATE).parse<NotUpdatable>("""{d:{a:42},d:{a:43}}""")
}
}
@Test
fun canUpdateNullableValuesInside() {
val json = Json(updateMode = UpdateMode.UPDATE)
val a1 = json.parse<NullableInnerIntList>("""{data:[null],data:[1]}""")
assertEquals(NullableInnerIntList(listOf(null, 1)), a1)
val a2 = json.parse<NullableInnerIntList>("""{data:[42],data:[null]}""")
assertEquals(NullableInnerIntList(listOf(42, null)), a2)
val a3 = json.parse<NullableInnerIntList>("""{data:[31],data:[1]}""")
assertEquals(NullableInnerIntList(listOf(31, 1)), a3)
}
@Test
fun canUpdateNullableValues() {
val json = Json(updateMode = UpdateMode.UPDATE)
val a1 = json.parse<NullableUpdatable>("""{data:null,data:[{a:42}]}""")
assertEquals(NullableUpdatable(listOf(Data(42))), a1)
val a2 = json.parse<NullableUpdatable>("""{data:[{a:42}],data:null}""")
assertEquals(NullableUpdatable(listOf(Data(42))), a2)
val a3 = json.parse<NullableUpdatable>("""{data:[{a:42}],data:[{a:43}]}""")
assertEquals(NullableUpdatable(listOf(Data(42), Data(43))), a3)
}
} | 0 | Kotlin | 0 | 0 | 4cec5ee08cb0c782e39b9ca4454f27ad86591156 | 3,110 | kotlinx.serialization | Apache License 2.0 |
odinclient/src/main/kotlin/me/odinclient/features/impl/skyblock/ChocolateFactory.kt | odtheking | 657,580,559 | false | {"Kotlin": 929255, "Java": 107402, "GLSL": 17728} | package me.odinclient.features.impl.skyblock
import me.odinmain.events.impl.GuiEvent
import me.odinmain.features.Category
import me.odinmain.features.Module
import me.odinmain.features.settings.impl.BooleanSetting
import me.odinmain.features.settings.impl.NumberSetting
import me.odinmain.utils.name
import me.odinmain.utils.noControlCodes
import me.odinmain.utils.skyblock.PlayerUtils.windowClick
import me.odinmain.utils.skyblock.lore
import me.odinmain.utils.skyblock.modMessage
import net.minecraft.inventory.Container
import net.minecraft.inventory.ContainerChest
import net.minecraftforge.client.event.sound.PlaySoundEvent
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
object ChocolateFactory : Module(
"Chocolate Factory",
description = "Automatically clicks the cookie in the Chocolate Factory menu.",
category = Category.SKYBLOCK
) {
private val clickFactory: Boolean by BooleanSetting("Click Factory", false, description = "Click the cookie in the Chocolate Factory menu.")
private val autoUpgrade: Boolean by BooleanSetting("Auto Upgrade", false, description = "Automatically upgrade the worker.")
private val delay: Long by NumberSetting("Delay", 150, 50, 300, 5)
private val upgradeDelay: Long by NumberSetting("Upgrade delay", 500, 300, 2000, 100)
private val cancelSound: Boolean by BooleanSetting("Cancel Sound")
private val upgradeMessage: Boolean by BooleanSetting("Odin Upgrade Message", false, description = "Prints a message when upgrading.")
private var chocolate = 0
private var chocoProduction = 0f
val indexToName = mapOf(29 to "Bro", 30 to "Cousin", 31 to "Sis", 32 to "Daddy", 33 to "Granny")
init {
execute(delay = { delay }) {
val container = mc.thePlayer?.openContainer as? ContainerChest ?: return@execute
if (container.name != "Chocolate Factory") return@execute
if (clickFactory) windowClick(13, 1,0)
}
execute(delay = {upgradeDelay}) {
val container = mc.thePlayer.openContainer as? ContainerChest ?: return@execute
if (container.name != "Chocolate Factory") return@execute
val choco = container.getSlot(13)?.stack ?: return@execute
chocolate = choco.displayName.noControlCodes.replace(Regex("\\D"), "").toInt()
chocoProduction = choco.lore.find { it.endsWith("§8per second") }?.noControlCodes?.replace(",", "")?.toFloatOrNull() ?: 0f
findWorker(container)
if(!found) return@execute
if (chocolate > bestCost && autoUpgrade) {
windowClick(bestWorker, 2, 3)
if(upgradeMessage) modMessage("Trying to upgrade: Rabbit " + indexToName[bestWorker] + " with " + bestCost + " chocolate.")
}
}
}
private var bestWorker = 29
private var bestCost = 0
private var found = false
private fun findWorker(container: Container) {
val items = container.inventory ?: return
val workers = mutableListOf<List<String?>>()
for (i in 29 until 34) {
workers.add(items[i]?.lore ?: return)
}
found = false
var maxValue = 0;
for (i in 0 until 5) {
val worker = workers[i]
if (worker.contains("climbed as far")) continue
val index = worker.indexOfFirst { it?.contains("Cost") == true }.takeIf { it != -1} ?: continue
val cost = worker[index + 1]?.noControlCodes?.replace(Regex("\\D"), "")?.toIntOrNull() ?: continue
val value = cost / (i + 1).toFloat()
if (value < maxValue || !found){
bestWorker = 29 + i
maxValue = value.toInt()
bestCost = cost
found = true
}
}
}
@SubscribeEvent
fun guiLoad(event: GuiEvent.GuiLoadedEvent) {
if (event.name == "Chocolate Factory") findWorker(event.gui)
}
@SubscribeEvent
fun onSoundPlay(event: PlaySoundEvent) {
if (!cancelSound) return
if (event.name == "random.eat") event.result = null // This should cancel the sound event
}
} | 4 | Kotlin | 17 | 40 | 14f8c6508757e5aa325d60382f6c01c4c481e91a | 4,158 | Odin | MIT License |
adapty/src/main/java/com/adapty/internal/data/models/ValidateProductInfo.kt | adaptyteam | 238,537,754 | false | null | package com.adapty.internal.data.models
import androidx.annotation.RestrictTo
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
internal class ValidateProductInfo(
val variationId: String?,
val priceLocale: String?,
val originalPrice: String?,
) | 4 | Kotlin | 9 | 26 | 7a8bef605a3a68eb2f725fe8e79b312c28226615 | 253 | AdaptySDK-Android | MIT License |
MvvmBasicAAC/app/src/main/java/us/bojie/mvvmbasicaac/ui/quotes/QuotesActivity.kt | jbj88817 | 182,032,719 | true | {"Kotlin": 461827, "Java": 261198, "Shell": 2979, "RenderScript": 2642} | package us.bojie.mvvmbasicaac.ui.quotes
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import kotlinx.android.synthetic.main.activity_quotes.*
import us.bojie.mvvmbasicaac.R
import us.bojie.mvvmbasicaac.data.Quote
import us.bojie.mvvmbasicaac.utils.InjectorUtils
import java.lang.StringBuilder
class QuotesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quotes)
initializeUi()
}
private fun initializeUi() {
val factory = InjectorUtils.provideQuotesViewModelFactory()
val viewModel = ViewModelProviders.of(this, factory)
.get(QuotesViewModel::class.java)
viewModel.getQuotes().observe(this, Observer { quotes ->
val stringBuilder = StringBuilder()
quotes.forEach { quote ->
stringBuilder.append("$quote\n\n")
}
textView_quotes.text = stringBuilder.toString()
})
button_add_quote.setOnClickListener {
val quote = Quote(editText_quote.text.toString(), editText_author.text.toString())
viewModel.addQuote(quote)
editText_quote.setText("")
editText_author.setText("")
}
}
}
| 0 | Kotlin | 0 | 0 | 27f0ec0b9737e1bb767b41633bda60d473784fec | 1,461 | android-architecture-components | Apache License 2.0 |
app/src/main/java/com/yassineabou/clock/data/manager/WorkRequestManager.kt | yassineAbou | 603,165,906 | false | {"Kotlin": 166506} | package com.yassineabou.clock.data.manager
import android.content.Context
import androidx.work.Data
import androidx.work.ListenableWorker
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
class WorkRequestManager @Inject constructor(
@ApplicationContext val applicationContext: Context,
) {
inline fun <reified T : ListenableWorker> enqueueWorker(tag: String, inputData: Data? = null) {
val workRequest = OneTimeWorkRequestBuilder<T>().addTag(tag)
inputData?.let {
workRequest.setInputData(it)
}
WorkManager.getInstance(applicationContext).enqueue(workRequest.build())
}
fun cancelWorker(tag: String) {
WorkManager.getInstance(applicationContext).cancelAllWorkByTag(tag)
}
}
| 1 | Kotlin | 1 | 4 | 7eb70533931fd4f3d2e827e6b072d6cae0a1a210 | 867 | Clock | Apache License 2.0 |
buildSrc/src/main/kotlin/Scopes.kt | open-toast | 236,028,544 | false | null | /*
* Copyright (c) 2020. Toast Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
object Scopes {
const val generator = "generator"
const val sdk = "sdk"
const val standardSugar = "sugar"
const val exerciseStandardSugar = "exerciseStandardSugar"
const val coreLibSugar = "coreLibSugar"
} | 0 | Kotlin | 1 | 3 | 237e7d30cdac06bffa54ddd1e7b3eea51a6ea2a3 | 818 | gummy-bears | Apache License 2.0 |
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/editor/RoundedCorner.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.remix.remix.editor
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.remix.remix.EditorGroup
public val EditorGroup.RoundedCorner: ImageVector
get() {
if (_roundedCorner != null) {
return _roundedCorner!!
}
_roundedCorner = Builder(name = "RoundedCorner", 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 = NonZero) {
moveTo(21.0f, 19.0f)
verticalLineTo(21.0f)
horizontalLineTo(19.0f)
verticalLineTo(19.0f)
horizontalLineTo(21.0f)
close()
moveTo(17.0f, 19.0f)
verticalLineTo(21.0f)
horizontalLineTo(15.0f)
verticalLineTo(19.0f)
horizontalLineTo(17.0f)
close()
moveTo(13.0f, 19.0f)
verticalLineTo(21.0f)
horizontalLineTo(11.0f)
verticalLineTo(19.0f)
horizontalLineTo(13.0f)
close()
moveTo(9.0f, 19.0f)
verticalLineTo(21.0f)
horizontalLineTo(7.0f)
verticalLineTo(19.0f)
horizontalLineTo(9.0f)
close()
moveTo(5.0f, 19.0f)
verticalLineTo(21.0f)
horizontalLineTo(3.0f)
verticalLineTo(19.0f)
horizontalLineTo(5.0f)
close()
moveTo(21.0f, 15.0f)
verticalLineTo(17.0f)
horizontalLineTo(19.0f)
verticalLineTo(15.0f)
horizontalLineTo(21.0f)
close()
moveTo(5.0f, 15.0f)
verticalLineTo(17.0f)
horizontalLineTo(3.0f)
verticalLineTo(15.0f)
horizontalLineTo(5.0f)
close()
moveTo(5.0f, 11.0f)
verticalLineTo(13.0f)
horizontalLineTo(3.0f)
verticalLineTo(11.0f)
horizontalLineTo(5.0f)
close()
moveTo(16.0f, 3.0f)
curveTo(18.687f, 3.0f, 20.882f, 5.124f, 20.995f, 7.783f)
lineTo(21.0f, 8.0f)
verticalLineTo(13.0f)
horizontalLineTo(19.0f)
verticalLineTo(8.0f)
curveTo(19.0f, 6.409f, 17.745f, 5.097f, 16.176f, 5.005f)
lineTo(16.0f, 5.0f)
horizontalLineTo(11.0f)
verticalLineTo(3.0f)
horizontalLineTo(16.0f)
close()
moveTo(5.0f, 7.0f)
verticalLineTo(9.0f)
horizontalLineTo(3.0f)
verticalLineTo(7.0f)
horizontalLineTo(5.0f)
close()
moveTo(5.0f, 3.0f)
verticalLineTo(5.0f)
horizontalLineTo(3.0f)
verticalLineTo(3.0f)
horizontalLineTo(5.0f)
close()
moveTo(9.0f, 3.0f)
verticalLineTo(5.0f)
horizontalLineTo(7.0f)
verticalLineTo(3.0f)
horizontalLineTo(9.0f)
close()
}
}
.build()
return _roundedCorner!!
}
private var _roundedCorner: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 4,161 | compose-icon-collections | MIT License |
app/src/main/java/ke/co/svs/mykrypto/network/CoinGeckoService.kt | Wamae | 428,778,929 | false | {"Kotlin": 25476} | package ke.co.svs.mykrypto.network
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import ke.co.svs.mykrypto.network.responses.CryptoResponse
import kotlinx.coroutines.flow.Flow
import retrofit2.http.GET
import retrofit2.http.Query
import retrofit2.http.Url
interface CoinGeckoService {
@GET("ticker")
fun getMyCryptos(@Query("limit") limit: Int):
Flow<List<CryptoResponse>>
@GET("coins/markets")
fun getCryptoInfo(@Query("per_page") perPage: Int,
@Query("vs_currency") currency: String,
@Query("sparkline") sparkLine: Boolean): Flow<JsonArray>
@GET
fun getCryptoDetails(@Url url: String): Flow<JsonObject>
@GET
fun getCurrencies(@Url url: String): Flow<JsonObject>
} | 5 | Kotlin | 0 | 0 | edb383788eaf2c9ccfeebbdd97b3cf58129899db | 779 | krypto | MIT License |
demo/src/main/java/de/check24/compose/demo/features/button/chip/ComposableChipActivity.kt | check24-profis | 469,706,312 | false | null | package de.check24.compose.demo.features.button.chip
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Cancel
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Circle
import androidx.compose.material.icons.filled.MyLocation
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import de.check24.compose.demo.R
import de.check24.compose.demo.theme.DemoTheme
import de.check24.compose.demo.theme.Gray300
import de.check24.compose.demo.theme.Gray400
import de.check24.compose.demo.theme.Gray700
import de.check24.compose.demo.theme.Gray800
import de.check24.compose.demo.theme.Green
import de.check24.compose.demo.theme.Purple100
import de.check24.compose.demo.theme.Purple200
import de.check24.compose.demo.theme.Purple500
import de.check24.compose.demo.theme.Red
import de.check24.compose.demo.theme.White
class ComposableChipActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DemoTheme {
Scaffold(
topBar = {
TopAppBar(
title = { Text(text = "Chip ") }
)
},
content = {
ChipExample()
}
)
}
}
}
}
@Composable
private fun ChipExample() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
ActionChip()
OutlinedActionChip()
ActionChip("Chip With Icon", icon = rememberVectorPainter(image = Icons.Default.Circle))
InputChip(icon = rememberVectorPainter(image = Icons.Default.MyLocation))
ChipWithToggleIcon()
}
}
@Composable
fun ActionChip(
name: String = "Action Chip",
icon: Painter? = null,
onToggle: ((String) -> Unit)? = null
) {
var isSelected by remember { mutableStateOf(false) }
val modifier = if (icon == null) {
Modifier.padding(horizontal = 12.dp)
} else Modifier.padding(start = 4.dp, end = 12.dp)
Surface(
modifier = Modifier.padding(4.dp),
shape = CircleShape,
color = if (isSelected) Purple100 else Gray300,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.height(32.dp)
.toggleable(
value = isSelected,
onValueChange = {
isSelected = !isSelected
onToggle?.invoke(name)
}
)
) {
if (icon != null) {
Icon(
icon,
"",
tint = if (isSelected) Green else Red,
modifier = Modifier
.padding(horizontal = 4.dp)
.width(24.dp)
)
}
Text(
text = name,
color = if (isSelected) Purple500 else Gray700,
style = MaterialTheme.typography.body2,
modifier = modifier
)
}
}
}
@Composable
private fun OutlinedActionChip(
name: String = "Outlined Chip",
onToggle: ((String) -> Unit)? = null
) {
var isSelected by remember { mutableStateOf(false) }
Surface(
modifier = Modifier
.padding(4.dp)
.hoverable(interactionSource = MutableInteractionSource(), true),
shape = CircleShape,
color = if (isSelected) Purple100 else White,
border = if (isSelected)
BorderStroke(width = 1.dp, Purple200) else {
BorderStroke(width = 1.dp, Gray400)
}
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.height(32.dp)
.toggleable(
value = isSelected,
onValueChange = {
isSelected = !isSelected
onToggle?.invoke(name)
}
)
) {
Text(
text = name,
color = if (isSelected) Purple500 else Gray800,
style = MaterialTheme.typography.body2,
modifier = Modifier
.padding(horizontal = 12.dp)
)
}
}
}
@Composable
fun InputChip(
name: String = "Input Chip",
icon: Painter? = null,
) {
var isVisible by remember { mutableStateOf(true) }
val modifier = if (icon == null) {
Modifier.padding(start = 12.dp, end = 4.dp)
} else Modifier.padding(horizontal = 4.dp)
if (isVisible) {
Surface(
modifier = Modifier.padding(4.dp),
shape = CircleShape,
color = Gray300,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.height(32.dp)
.toggleable(
value = true,
onValueChange = { }
)
) {
if (icon != null) {
Icon(
icon,
"",
tint = Gray700,
modifier = Modifier
.padding(horizontal = 4.dp)
.width(24.dp)
)
}
Text(
text = name,
color = Gray700,
style = MaterialTheme.typography.body2,
modifier = modifier
)
Icon(
Icons.Filled.Cancel,
"",
tint = Gray700,
modifier = Modifier
.clickable { isVisible = !isVisible }
.padding(
start = 4.dp,
end = 8.dp
)
.width(18.dp)
)
}
}
}
}
@Composable
private fun ChipWithToggleIcon(
name: String = "Chip With toggleable Icon",
icon: Painter = rememberVectorPainter(image = Icons.Default.Check),
onToggle: ((String) -> Unit)? = null
) {
var isSelected by remember { mutableStateOf(false) }
Surface(
modifier = Modifier.padding(4.dp),
shape = CircleShape,
color = if (isSelected) Gray400 else Gray300,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.height(32.dp)
.toggleable(
value = isSelected,
onValueChange = {
isSelected = !isSelected
onToggle?.invoke(name)
}
)
) {
if (isSelected) {
Icon(
icon,
"",
modifier = Modifier
.padding(start = 4.dp)
.width(24.dp)
)
}
Text(
text = name,
color = if (isSelected) Gray800 else Gray700,
style = MaterialTheme.typography.body2,
modifier = Modifier
.padding(
start = 8.dp,
end = 12.dp
)
)
}
}
}
@Composable
fun ActionChipSingleSelection(
selectedChip: String,
currentItem: String,
onToggle: (String) -> Unit
) {
Surface(
modifier = Modifier.padding(4.dp),
shape = CircleShape,
color = if (selectedChip == currentItem) {
colorResource(id = R.color.purple_100)
} else colorResource(id = R.color.gray_300)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.height(32.dp)
.clickable {
onToggle(currentItem)
}
) {
Text(
text = currentItem,
color = if (selectedChip == currentItem) colorResource(id = R.color.purple_500) else colorResource(
id = R.color.gray_700
),
style = MaterialTheme.typography.body2,
modifier = Modifier.padding(horizontal = 12.dp)
)
}
}
}
@Preview(showSystemUi = true, showBackground = true, device = Devices.PIXEL_4)
@Composable
private fun ChipPreview() {
DemoTheme {
ChipExample()
}
}
@Preview(showSystemUi = true, showBackground = true, device = Devices.PIXEL_4)
@Composable
private fun ActionChipPreview() {
DemoTheme {
ActionChip()
}
}
@Preview(showSystemUi = true, showBackground = true, device = Devices.PIXEL_4)
@Composable
private fun InputChipPreview() {
DemoTheme {
InputChip()
}
}
@Preview(showSystemUi = true, showBackground = true, device = Devices.PIXEL_4)
@Composable
private fun OutlinedChipPreview() {
DemoTheme {
OutlinedActionChip()
}
}
@Preview(showSystemUi = true, showBackground = true, device = Devices.PIXEL_4)
@Composable
private fun ToggleChipPreview() {
DemoTheme {
ChipWithToggleIcon()
}
} | 0 | Kotlin | 3 | 11 | abd64a7d2edac0dbedb4d67d3c0f7b49d9173b88 | 11,305 | jetpack-compose-is-like-android-view | MIT License |
lib/src/integrationTest/kotlin/com/lemonappdev/konsist/core/declaration/koparameterdeclaration/KoParameterDeclarationForNoParameterTest.kt | LemonAppDev | 621,181,534 | false | null | package com.lemonappdev.konsist.core.declaration.koparameterdeclaration
import com.lemonappdev.konsist.TestSnippetProvider.getSnippetKoScope
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
class KoParameterDeclarationForNoParameterTest {
@Test
fun `class-has-no-parameters`() {
// given
val sut = getSnippetFile("class-has-no-parameters")
.classes()
.first()
// then
sut.primaryConstructor shouldBeEqualTo null
}
@Test
fun `class-has-empty-primary-constructor`() {
// given
val sut = getSnippetFile("class-has-empty-primary-constructor")
.classes()
.first()
.primaryConstructor
?.parameters
// then
sut shouldBeEqualTo emptyList()
}
private fun getSnippetFile(fileName: String) =
getSnippetKoScope("core/declaration/koparameterdeclaration/snippet/fornoparameter/", fileName)
}
| 9 | Kotlin | 0 | 5 | 2c029ca448d24acad1cc0473e69b78130be86193 | 983 | konsist | Apache License 2.0 |
Manga/app/src/main/java/nhdphuong/com/manga/views/DialogHelper.kt | duyphuong5126 | 140,096,962 | false | null | package nhdphuong.com.manga.views
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import nhdphuong.com.manga.R
import nhdphuong.com.manga.supports.ImageUtils
import nhdphuong.com.manga.views.customs.MyButton
import nhdphuong.com.manga.views.customs.MyTextView
private const val DEFAULT_LOADING_INTERVAL = 700L
@SuppressLint("InflateParams", "SetTextI18n")
fun Activity.createLoadingDialog(loadingStringId: Int = R.string.loading): Dialog {
val loadingString = getString(loadingStringId)
val dotsArray = resources.getStringArray(R.array.dots)
var currentPos = 0
val dialog = Dialog(this)
val layoutInflater = LayoutInflater.from(this)
val contentView = layoutInflater.inflate(
R.layout.layout_loading_dialog,
null,
false
)
val tvLoading: TextView = contentView.findViewById(R.id.tvLoading)
val ivLoading: ImageView = contentView.findViewById(R.id.ivLoading)
dialog.setContentView(contentView)
dialog.setCancelable(false)
ImageUtils.loadGifImage(R.raw.ic_loading_cat_transparent, ivLoading)
val taskHandler = Handler(Looper.getMainLooper())
val dotsUpdatingTask = Runnable {
tvLoading.text = loadingString + dotsArray[currentPos]
if (currentPos < dotsArray.size - 1) currentPos++ else currentPos = 0
}
val updateTask = object : Runnable {
override fun run() {
dotsUpdatingTask.run()
taskHandler.postDelayed(this, DEFAULT_LOADING_INTERVAL)
}
}
dialog.setOnShowListener {
taskHandler.post(updateTask)
}
dialog.setOnDismissListener {
taskHandler.removeCallbacksAndMessages(null)
}
dialog.setCanceledOnTouchOutside(false)
dialog.window?.let { window ->
window.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
window.setGravity(Gravity.CENTER)
window.decorView.setBackgroundResource(android.R.color.transparent)
}
return dialog
}
fun Activity.showDoNotRecommendBookDialog(
bookId: String,
onOk: () -> Unit,
onCancel: () -> Unit = {}
) {
showOkDismissDialog(
this,
getString(R.string.do_not_recommend_book_title),
getString(R.string.do_not_recommend_book_message, bookId),
getString(R.string.yes),
getString(R.string.no),
onOk,
onCancel,
false
)
}
fun Activity.showSuggestionRemovalConfirmationDialog(
suggestion: String,
onOk: () -> Unit,
onCancel: () -> Unit = {}
) {
showOkDismissDialog(
this,
getString(R.string.suggestion_removal_title),
getString(R.string.suggestion_removal_message, suggestion),
getString(R.string.yes),
getString(R.string.no),
onOk,
onCancel,
false
)
}
fun Activity.showBookDownloadingFailureDialog(bookId: String, onOk: () -> Unit = {}) {
showOkDialog(
this,
getString(R.string.downloading_failure),
getString(R.string.downloading_book_failed_message, bookId),
onOk
)
}
fun Activity.showTagsDownloadingDialog(onOk: () -> Unit = {}) {
val message = getString(R.string.is_downloading_tags)
showOkDialog(
this,
getString(R.string.are_tags_being_downloaded),
message,
onOk
)
}
fun Activity.showTagsNotAvailable(onOk: () -> Unit = {}) {
showOkDialog(
this,
getString(R.string.under_construction_title),
getString(R.string.feature_under_construction_description),
onOk
)
}
fun Activity.showThisBookDownloadingDialog(onOk: () -> Unit = {}) {
val message = getString(R.string.is_downloading_this_book)
showOkDialog(
this,
getString(R.string.is_book_being_downloaded),
message,
onOk
)
}
fun Activity.showBookListRefreshingDialog(onOk: () -> Unit = {}) {
showOkDialog(
this,
getString(R.string.book_list_refreshing_title),
getString(R.string.book_list_refreshing_description),
onOk
)
}
fun Activity.showInternetRequiredDialog(onOk: () -> Unit = {}) {
showOkDialog(
this,
getString(R.string.no_network_title),
getString(R.string.no_network_description),
onOk
)
}
fun Activity.showTagDataBeingDownloadedDialog(onOk: () -> Unit = {}, onDismiss: () -> Unit = {}) {
val title = getString(R.string.downloading_tags_already_started_title)
val message = getString(R.string.downloading_tags_already_started_message)
val cancelButton = getString(R.string.ok)
val okButton = getString(R.string.stop_downloading_tags)
showOkDismissDialog(this, title, message, okButton, cancelButton, onOk, onDismiss)
}
fun Activity.showUnSeenBookConfirmationDialog(onOk: () -> Unit = {}, onDismiss: () -> Unit = {}) {
val title = getString(R.string.un_seen_book_title)
val message = getString(R.string.un_seen_book_description)
val okButton = getString(R.string.yes)
val cancelButton = getString(R.string.no)
showOkDismissDialog(this, title, message, okButton, cancelButton, onOk, onDismiss)
}
fun Activity.showCancelDownloadingBookConfirmationDialog(
bookId: String,
onOk: () -> Unit = {},
onDismiss: () -> Unit = {}
) {
val title = getString(R.string.cancel_downloading)
val message = getString(R.string.cancel_downloading_message, bookId)
val okButton = getString(R.string.yes)
val cancelButton = getString(R.string.no)
showOkDismissDialog(this, title, message, okButton, cancelButton, onOk, onDismiss)
}
fun Activity.showAdminEntryDialog(onOk: () -> Unit = {}, onDismiss: () -> Unit = {}) {
val title = getString(R.string.enter_admin_page_title)
val message = getString(R.string.enter_admin_page_description)
val okString = getString(R.string._continue)
val dismissString = getString(R.string.exit)
showOkDismissDialog(this, title, message, okString, dismissString, onOk, onDismiss)
}
fun Activity.showBookDownloadingDialog(
bookId: String,
onOk: () -> Unit = {}
) {
val title = getString(R.string.is_book_being_downloaded)
val message = String.format(
getString(R.string.is_downloading_another_book),
bookId
)
showOkDialog(this, title, message, onOk)
}
fun Activity.showDownloadingFinishedDialog(
bookId: String,
onOk: () -> Unit = {}
) {
val title = getString(R.string.book_downloading_finished_title)
val message = getString(R.string.book_downloading_finished_message, bookId)
showOkDialog(this, title, message, onOk)
}
fun Activity.showBookDeletingConfirmationDialog(
bookId: String,
onOk: () -> Unit = {},
onCancel: () -> Unit = {}
) {
val title = getString(R.string.book_deleting_confirmation_title)
val message = getString(R.string.book_deleting_confirmation_message, bookId)
val okButton = getString(R.string.yes)
val cancelButton = getString(R.string.no)
showOkDismissDialog(this, title, message, okButton, cancelButton, onOk, onCancel, true)
}
fun Activity.showGoToPageDialog(
minimum: Int,
maximum: Int,
onOk: (number: Int) -> Unit = {},
onDismiss: () -> Unit = {}
) {
val title = getString(R.string.jump_to_page)
val errorMessage = getString(R.string.invalid_page)
val okButton = getString(R.string.ok)
val cancelButton = getString(R.string.cancel)
val inputHint = getString(R.string.page_number_hint) + " ($minimum - $maximum)"
showOkDismissInputNumberDialog(
this,
title,
errorMessage,
minimum,
maximum,
okButton,
cancelButton,
inputHint,
onOk,
onDismiss
)
}
fun Activity.showInstallationConfirmDialog(
versionCode: String,
onOk: () -> Unit = {},
onDismiss: () -> Unit = {}
) {
val title = getString(R.string.installation_confirm_title)
val message = getString(R.string.installation_confirm_message, versionCode)
val okButton = getString(R.string.ok)
val cancelButton = getString(R.string.cancel)
showOkDismissDialog(this, title, message, okButton, cancelButton, onOk, onDismiss)
}
fun Activity.showFailedToUpgradeAppDialog(
versionCode: String,
onOk: () -> Unit = {},
onCancel: () -> Unit = {}
) {
val title = getString(R.string.app_upgrade_failed_title)
val message = getString(R.string.app_upgrade_failed_message, versionCode)
val retry = getString(R.string.retry)
val installManually = getString(R.string.install_manually)
showOkDismissDialog(this, title, message, retry, installManually, onOk, onCancel, true)
}
fun Activity.showRestartAppDialog(
onOk: () -> Unit = {},
onCancel: () -> Unit = {}
) {
val title = getString(R.string.restart_app_title)
val message = getString(R.string.restart_app_message)
val ok = getString(R.string.restart_button)
val cancel = getString(R.string.cancel)
showOkDismissDialog(this, title, message, ok, cancel, onOk, onCancel, false)
}
fun Activity.showTryAlternativeDomainsDialog(
onOk: () -> Unit = {},
onCancel: () -> Unit = {}
) {
val title = getString(R.string.try_alter_native_domain_title)
val message = getString(R.string.try_alter_native_domain_message)
val ok = getString(R.string.try_it)
val cancel = getString(R.string.cancel)
showOkDismissDialog(this, title, message, ok, cancel, onOk, onCancel, false)
}
fun Activity.showGlobalMessage(
title: String,
description: String,
ok: String,
cancel: String,
onOk: () -> Unit = {},
onCancel: () -> Unit = {}
) {
showOkDismissDialog(this, title, description, ok, cancel, onOk, onCancel)
}
@SuppressLint("InflateParams")
private fun showOkDismissDialog(
activity: Activity,
title: String,
description: String,
ok: String,
dismiss: String,
onOk: () -> Unit,
onDismiss: () -> Unit,
canceledOnTouchOutside: Boolean = false
) {
val contentView = activity.layoutInflater.inflate(
R.layout.dialog_ok_dismiss,
null,
false
)
val dialog = Dialog(activity)
val mtvTitle: MyTextView = contentView.findViewById(R.id.mtvDialogTitle)
val mtvDescription: MyTextView = contentView.findViewById(R.id.mtvDialogDescription)
val mbOk: MyButton = contentView.findViewById(R.id.mbOkButton)
val mbDismiss: MyButton = contentView.findViewById(R.id.mbDismissButton)
mbOk.text = ok
mbDismiss.text = dismiss
mtvTitle.text = title
mtvDescription.text = description
contentView.findViewById<MyButton>(R.id.mbOkButton).setOnClickListener {
dialog.dismiss()
onOk()
}
contentView.findViewById<MyButton>(R.id.mbDismissButton).setOnClickListener {
dialog.dismiss()
onDismiss()
}
dialog.setCanceledOnTouchOutside(canceledOnTouchOutside)
dialog.setContentView(contentView)
dialog.show()
dialog.window?.let { window ->
window.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
window.setGravity(Gravity.CENTER)
window.decorView.setBackgroundResource(android.R.color.transparent)
}
}
@SuppressLint("InflateParams")
private fun showOkDismissInputNumberDialog(
activity: Activity,
title: String,
errorMessage: String,
minimum: Int,
maximum: Int,
ok: String,
dismiss: String,
inputHint: String,
onOk: (number: Int) -> Unit,
onDismiss: () -> Unit
) {
val contentView = activity.layoutInflater.inflate(
R.layout.dialog_ok_dismiss_input_number,
null,
false
)
val dialog = Dialog(activity)
val mtvTitle: MyTextView = contentView.findViewById(R.id.mtvDialogTitle)
val mtvError: MyTextView = contentView.findViewById(R.id.mtvError)
val edtInputNumber: EditText = contentView.findViewById(R.id.edtInputNumber)
val mbOk: MyButton = contentView.findViewById(R.id.mbOkButton)
val mbDismiss: MyButton = contentView.findViewById(R.id.mbDismissButton)
mbOk.text = ok
mbDismiss.text = dismiss
mtvTitle.text = title
mtvError.text = errorMessage
edtInputNumber.hint = inputHint
contentView.findViewById<MyButton>(R.id.mbOkButton).setOnClickListener {
try {
val number = edtInputNumber.text.toString().toInt()
if (number in minimum..maximum) {
mtvError.gone()
dialog.dismiss()
onOk.invoke(number)
} else {
mtvError.becomeVisible()
}
} catch (error: Throwable) {
mtvError.becomeVisible()
}
}
contentView.findViewById<MyButton>(R.id.mbDismissButton).setOnClickListener {
dialog.dismiss()
onDismiss()
}
dialog.setCanceledOnTouchOutside(false)
dialog.setContentView(contentView)
dialog.show()
dialog.window?.let { window ->
window.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
window.setGravity(Gravity.CENTER)
window.decorView.setBackgroundResource(android.R.color.transparent)
}
}
@SuppressLint("InflateParams")
private fun showOkDialog(
activity: Activity,
title: String,
description: String,
onOk: () -> Unit
) {
val contentView = activity.layoutInflater.inflate(
R.layout.dialog_ok,
null,
false
)
val dialog = Dialog(activity)
val mtvPermissionTitle: MyTextView = contentView.findViewById(R.id.mtvDialogTitle)
mtvPermissionTitle.text = title
val mtvDescription: MyTextView = contentView.findViewById(R.id.mtvDialogDescription)
mtvDescription.text = description
contentView.findViewById<MyButton>(R.id.mbOkButton).setOnClickListener {
dialog.dismiss()
onOk()
}
dialog.setCanceledOnTouchOutside(false)
dialog.setContentView(contentView)
dialog.show()
dialog.window?.let { window ->
window.setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
window.setGravity(Gravity.CENTER)
window.decorView.setBackgroundResource(android.R.color.transparent)
}
}
| 4 | Kotlin | 0 | 3 | 8cbd6b2246726944e8cde96be8a4124feabe1baf | 14,522 | H-Manga | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/consumer/isdialogmelding/IsdialogmeldingConsumer.kt | navikt | 650,618,614 | false | {"Kotlin": 112825, "Dockerfile": 132} | package no.nav.syfo.consumer.isdialogmelding
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.coroutines.runBlocking
import no.nav.syfo.api.util.httpClient
import no.nav.syfo.consumer.NAV_CALL_ID_HEADER
import no.nav.syfo.consumer.azuread.AzureAdTokenConsumer
import no.nav.syfo.consumer.createBearerToken
import no.nav.syfo.consumer.createCallId
import no.nav.syfo.environment.UrlEnv
import org.slf4j.LoggerFactory
class IsdialogmeldingConsumer(
private val urls: UrlEnv,
private val azureAdTokenConsumer: AzureAdTokenConsumer,
) {
private val log = LoggerFactory.getLogger(IsdialogmeldingConsumer::class.qualifiedName)
private val client = httpClient()
suspend fun sendPlanToFastlege(
sykmeldtFnr: String,
planAsPdf: ByteArray,
): Boolean {
val requestUrl = "${urls.isdialogmeldingUrl}/$SEND_LPS_PDF_TO_FASTLEGE_PATH"
val rsOppfoelgingsplan = RSOppfoelgingsplan(sykmeldtFnr, planAsPdf)
val token = azureAdTokenConsumer.getToken(urls.isdialogmeldingClientId)
val response = try {
client.post(requestUrl) {
headers {
append(HttpHeaders.ContentType, ContentType.Application.Json)
append(HttpHeaders.Authorization, createBearerToken(token))
append(NAV_CALL_ID_HEADER, createCallId())
}
setBody(rsOppfoelgingsplan)
}
} catch (e: Exception) {
log.error("Exception while sending altinn-LPS to fastlege", e)
throw e
}
return when (response.status) {
HttpStatusCode.OK -> {
log.info("Successfully sent PDF to fastlege")
true
}
HttpStatusCode.NotFound -> {
log.warn("Unable to determine fastlege, or lacking appropiate" +
"'partnerinformasjon'-data")
false
}
else -> {
log.error("Unable to send altinn-LPS to fastlege (HTTP error code: ${response.status}")
false
}
}
}
companion object {
private const val SEND_LPS_PDF_TO_FASTLEGE_PATH = "api/v2/send/oppfolgingsplan"
}
}
| 2 | Kotlin | 0 | 0 | 5db87a0421831cb90c84bb2c6bdc8ef5df154013 | 2,309 | lps-oppfolgingsplan-mottak | MIT License |
examples/index/src/main/kotlin/io/github/andrewk2112/kjsbox/examples/frontend/app.kt | andrew-k-21-12 | 497,585,003 | false | null | package io.github.andrewk2112.kjsbox.examples.frontend
import io.github.andrewk2112.kjsbox.frontend.Environment
import io.github.andrewk2112.kjsbox.frontend.dinjection.di
import io.github.andrewk2112.kjsbox.frontend.hooks.useInjected
import io.github.andrewk2112.kjsbox.frontend.redux.StoreFactory
import io.github.andrewk2112.kjsbox.frontend.redux.reducers.ContextReducer
import io.github.andrewk2112.kjsbox.frontend.routes.MaterialDesignRoute
import js.import.Module
import js.import.import
import js.promise.toPromise
import org.kodein.di.direct
import org.kodein.di.instance
import react.*
import react.redux.Provider
import react.router.*
import react.router.dom.BrowserRouter
/** The React application's entry point component: all basic React configurations and its rendering start here. */
val app = VFC {
Provider {
store = di.direct.instance<StoreFactory>().create() // setting the global app state and its processing reducers,
BrowserRouter { // enabling routing features,
Suspense { // configuring the app with its loading placeholder
fallback = appLoadingPlaceholder.create()
initializations()
routes()
}
}
}
}
/** A placeholder to be shown while the application itself is loading. */
private val appLoadingPlaceholder = VFC {
+"⌛ Loading / Загрузка"
}
/** All required initializations to be done before loading of any actual contents. */
private val initializations = VFC {
useInjected<ContextReducer>().useScreenSizeMonitor() // monitoring the screen size to update the context
}
/** All the actual contents available in the app bound to the corresponding routes. */
private val routes = VFC {
// All pages of the app: the root (serves as a fallback also) one,
// the first example page and the fallback configuration.
// React processes its routes in some special way which differs from the web's canonical one:
// in the context of the routes below it is only important
// that trailing slashes path variants are included automatically
// (i.e. declaring "/material-design" will also include "/material-design/")
// and for nested routes relative paths should be used to join a segment to its parent,
// or we need to qualify a full absolute (starting with a slash) path for this nested route.
// More details here: https://reactrouter.com/docs/en/v6/upgrading/v5#note-on-link-to-values.
Routes {
PathRoute {
path = "/"
element = exercisesOnDemandComponent.create()
}
PathRoute {
path = MaterialDesignRoute.path
element = materialDesignOnDemandComponent.create()
}
PathRoute {
path = "*"
element = VFC {
val navigate = useNavigate()
useEffect {
navigate("/")
}
}.create()
}
}
}
private val exercisesOnDemandComponent: ExoticComponent<Props> = lazy {
// Such references (also, references to resources - fonts, icons, images)
// are included from the compilation root (from the root resources directory):
// their paths are totally unrelated to browser locations.
// Therefore, we should use simple relative paths instead of the absolute ones.
// It's a webpack requirement for requests that should resolve in the current directory to start with "./".
import<Module<dynamic>>("./${Environment.projectName}-exercises")
.then { it.default }
.toPromise()
}
private val materialDesignOnDemandComponent: ExoticComponent<Props> = lazy {
import<Module<dynamic>>("./${Environment.projectName}-material-design")
.then { it.default }
.toPromise()
}
| 0 | Kotlin | 0 | 2 | 40921196b5a7184b68160ca1ffa40812dec831b0 | 3,851 | kjs-box | MIT License |
app/src/main/java/com/weathermap/utils/SharedPrefUtils.kt | xuanqh | 507,506,257 | false | null | package com.restaff.wordle.utils
import android.content.Context
import android.content.SharedPreferences
class SharedPrefUtils private constructor() {
companion object {
private const val PREF_APP = "WordleApp"
fun getBooleanData(context: Context, key: String?, defValue: Boolean = false): Boolean {
return context.getSharedPreferences(PREF_APP, Context.MODE_PRIVATE)
.getBoolean(key, defValue)
}
fun getIntData(context: Context, key: String?): Int {
return context.getSharedPreferences(PREF_APP, Context.MODE_PRIVATE).getInt(key, 0)
}
fun getLongData(context: Context, key: String?): Long {
return context.getSharedPreferences(PREF_APP, Context.MODE_PRIVATE).getLong(key, 0)
}
fun getStringData(context: Context, key: String?): String? {
return context.getSharedPreferences(PREF_APP, Context.MODE_PRIVATE).getString(key, null)
}
fun saveData(context: Context, key: String?, value: String?) {
context.getSharedPreferences(PREF_APP, Context.MODE_PRIVATE).edit()
.putString(key, value).apply()
}
fun saveData(context: Context, key: String?, value: Int) {
context.getSharedPreferences(PREF_APP, Context.MODE_PRIVATE).edit().putInt(key, value)
.apply()
}
fun saveData(context: Context, key: String?, value: Long) {
context.getSharedPreferences(PREF_APP, Context.MODE_PRIVATE).edit().putLong(key, value)
.apply()
}
fun saveData(context: Context, key: String?, value: Boolean) {
context.getSharedPreferences(PREF_APP, Context.MODE_PRIVATE)
.edit()
.putBoolean(key, value)
.apply()
}
fun getSharedPrefEditor(context: Context, pref: String?): SharedPreferences.Editor {
return context.getSharedPreferences(pref, Context.MODE_PRIVATE).edit()
}
fun saveData(editor: SharedPreferences.Editor) {
editor.apply()
}
}
} | 0 | Kotlin | 0 | 0 | 93ccd5a6e8a8f6192a2adcb99e9483bfd8bdb175 | 2,126 | wordle | MIT License |
app/src/main/java/com/example/githubperson/di/module/AppModule.kt | barimans | 286,974,438 | false | null | package com.example.githubperson.di.module
import android.app.Application
import android.content.Context
import com.example.githubperson.GithubPersonApplication
import com.example.githubperson.data.db.UsersDatabase
import com.example.githubperson.data.remote.RemoteRepository
import com.example.githubperson.data.repository.impl.DetailUsersRepositoryImpl
import com.example.githubperson.data.repository.impl.FollowTabRepositoryImpl
import com.example.githubperson.data.repository.impl.UsersRepositoryImpl
import com.example.githubperson.ui.detail_ui.DetailUsersInteractor
import com.example.githubperson.ui.detail_ui.followtab_ui.FollowTabInteractor
import com.example.githubperson.ui.main_ui.MainUsersInteractor
import com.example.githubperson.utils.PreferencesHelper
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class AppModule {
@Provides
@Singleton
fun providesContext(app: GithubPersonApplication): Context = app
@Provides
@Singleton
fun provideApplication(app: GithubPersonApplication): Application = app
@Provides
@Singleton
fun provideRoomDB(app: Application) = UsersDatabase.getInstance(app)
@Provides
@Singleton
fun providePlayerDao(db: UsersDatabase) = db.userFavoriteDao()
@Provides
@Singleton
fun providePreference() = PreferencesHelper.getInstance()
@Provides
@Singleton
fun providesUsersRepository(remote: RemoteRepository) = UsersRepositoryImpl(remote)
@Provides
@Singleton
fun providesDetailUsersRepository(remote: RemoteRepository) = DetailUsersRepositoryImpl(remote)
@Provides
@Singleton
fun providesFollowTabRepository(remote: RemoteRepository) = FollowTabRepositoryImpl(remote)
@Provides
@Singleton
fun providesUsersInteractor(repositoryImpl: UsersRepositoryImpl) = MainUsersInteractor(repositoryImpl)
@Provides
@Singleton
fun providesDetailUsersInteractor(repositoryImpl: DetailUsersRepositoryImpl) = DetailUsersInteractor(repositoryImpl)
@Provides
@Singleton
fun providesFollowTabInteractor(repositoryImpl: FollowTabRepositoryImpl) = FollowTabInteractor(repositoryImpl)
} | 0 | Kotlin | 0 | 0 | 361ac200f21933d0801f881486da6ea379b03f28 | 2,177 | GithubApp-MVVM-Dagger2 | Apache License 2.0 |
buildSrc/src/main/kotlin/ConfigData.kt | HaidyAbuGom3a | 805,534,454 | false | {"Kotlin": 702248} | import org.gradle.api.JavaVersion
object ConfigData {
const val COMPILE_SDK_VERSION = 34
const val MIN_SDK_VERSION = 24
const val TARGET_SDK_VERSION = 34
const val VERSION_CODE = 1
const val VERSION_NAME = "1.0"
val JAVA_VERSIONS_CODE = JavaVersion.VERSION_17
const val TEST_INSTRUMENTATION_RUNNER = "androidx.test.runner.AndroidJUnitRunner"
} | 0 | Kotlin | 0 | 2 | 8c2ba73cea5d29cc2ef7048d832f8ecea13f34ee | 372 | Servify | Apache License 2.0 |
app/src/main/java/com/github/guilhe/zoocompose/presentation/theme/Theme.kt | GuilhE | 342,691,825 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.guilhe.zoocompose.presentation.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val DarkColorPalette = darkColors(
primary = teal700,
primaryVariant = teal700_alt,
secondary = teal700,
onPrimary = Color.White
)
private val LightColorPalette = lightColors(
primary = red900,
primaryVariant = red700,
secondary = red900,
background = yellow900,
surface = yellow900_alt,
onPrimary = Color.White,
onSecondary = Color.White
)
private val lightOverlayColorPalette = lightColors(
primary = yellow900_alt_70_alpha,
onPrimary = Color.Black,
)
private val darkOverlayColorPalette = lightColors(
primary = black_70_alpha,
onPrimary = Color.Black,
)
private val lightButtonColorPalette = lightColors(
primary = red900,
onPrimary = Color.White,
)
private val darkButtonColorPalette = darkColors(
primary = teal700,
onPrimary = Color.White,
)
@Composable
fun AppTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
MaterialTheme(
colors = if (darkTheme) DarkColorPalette else LightColorPalette,
typography = mainTypography,
shapes = shapes,
content = content
)
}
@Composable
fun OverlayTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
MaterialTheme(
colors = if (darkTheme) darkOverlayColorPalette else lightOverlayColorPalette,
typography = mainTypography,
shapes = shapes,
content = content
)
}
@Composable
fun ButtonTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
MaterialTheme(
colors = if (darkTheme) darkButtonColorPalette else lightButtonColorPalette,
typography = mainTypography,
shapes = shapes,
content = content
)
}
| 0 | Kotlin | 0 | 8 | 93be994c5e6620ea142b81851c0e1a0915bb9c82 | 2,700 | Zoo-Compose | Apache License 2.0 |
Olebo/src/jvmMain/kotlin/viewModel/home/HomeContent.kt | TristanBoulesteix | 158,809,102 | false | null | package jdr.exia.viewModel.home
import jdr.exia.model.act.Act
sealed class HomeContent
object ActsView : HomeContent()
object ElementsView : HomeContent()
class ActEditor(val act: Act) : HomeContent()
object ActCreator : HomeContent() | 0 | Kotlin | 0 | 1 | a80419a07c37b546a9496e653de3f158632ab47b | 240 | Olebo | Apache License 2.0 |
src/commonMain/kotlin/br/com/gamemods/nbtmanipulator/nbt.kt | Koterite | 251,167,787 | true | {"Kotlin": 131278, "Java": 949} | @file:Suppress("unused")
package br.com.gamemods.nbtmanipulator
import br.com.gamemods.koterite.annotation.JvmThrows
import br.com.gamemods.koterite.annotation.Throws
import kotlin.jvm.JvmStatic
/**
* The root component of a file, it contains a hint for the file name and the first tag in the file.
* @property name The key for the file name. Empty in most cases.
* @property tag The first tag in the file. A [NbtCompound] in most cases.
* @property compound A shortcut to read or write [NbtFile.tag] as a [NbtCompound].
* Will throw a [ClassCastException] if the tag value is not a [NbtCompound]
*/
data class NbtFile(var name: String, var tag: NbtTag) {
var compound: NbtCompound
@JvmThrows(ClassCastException::class)
get() = tag as NbtCompound
set(value) {
tag = value
}
}
/**
* The base class for Nbt Tags. All tag values are mutable.
*
* Do not create new classes extending it.
*/
sealed class NbtTag {
/**
* Returns a string representation of the tag's value.
*
* The [NbtList] and the array types will have an output similar to a normal [List] and [NbtCompound] to a normal [Map].
*
* The class names of the [NbtList]'s and [NbtCompound]'s children will exposed.
*
* The returned string is compatible with string constructors of the same type.
*
* Be aware that this may be a slow operation on big lists, arrays or compounds.
*/
abstract val stringValue: String
/**
* Copies all this and all nested NbtTags into new objects.
*/
abstract fun deepCopy(): NbtTag
/**
* A technical string representation of this tag, containing the tag type and it's value,
* appropriated for developer inspections.
*
* The [NbtList] and the array types will have an output similar to a normal [List] and [NbtCompound] to a normal [Map].
*
* Be aware that this may be a slow operation on big lists, arrays or compounds.
*/
protected open fun toTechnicalString() = "${this::class.simpleName}($stringValue)"
/**
* A technical string representation of this tag, containing the tag type and it's value,
* appropriated for developer inspections.
*
* The [NbtList] and the array types will have an output similar to a normal [List] and [NbtCompound] to a normal [Map].
*
* Be aware that this may be a slow operation on big lists, arrays or compounds.
*/
final override fun toString() = toTechnicalString()
}
/**
* A special tag which indicates the end of a compound stream or empty lists.
*
* Should not be used directly.
*/
object NbtEnd : NbtTag() {
/**
* Returns an empty string.
*/
override val stringValue: String
get() = ""
/**
* Returns `"NbtEnd"`.
*/
override fun toTechnicalString(): String {
return "NbtEnd"
}
/**
* Returns itself.
*/
override fun deepCopy() = NbtEnd
}
/**
* A tag which wraps a byte value.
* @property signed A signed byte from `-128` to `127`
*/
data class NbtByte(var signed: Byte) : NbtTag() {
/**
* Read or write the [signed] as a signed byte from `0` to `255`.
*/
var unsigned: Int
get() = signed.toInt() and 0xFF
set(value) {
this.signed = (value and 0xFF).toByte()
}
/**
* A signed byte from `-128` to `127`.
*/
@Deprecated(
"Deprecated in favor of signed and unsigned flavours. Replace with the signed property.",
ReplaceWith("signed")
)
inline var value: Byte
get() = signed
set(value) {
signed = value
}
/**
* Returns a string representation of the tag's signed value.
*
* The returned string is compatible with string constructors of the same type.
*/
override val stringValue: String
get() = signed.toString()
/**
* Wraps a byte `1` if the value is `true` and `0` otherwise.
* @param value The value to be checked
*/
constructor(value: Boolean): this(if (value) BYTE_TRUE else 0)
/**
* Converts the int value to an unsigned byte and wraps it.
* @param unsigned Unsigned value from `0` to `255`.
* @throws NumberFormatException if the number is not within the 0..255 range
*/
@Throws(NumberFormatException::class)
constructor(unsigned: Int): this(unsigned.let {
if(it < 0 || it > 255) {
throw NumberFormatException("Expected an unsigned byte of range 0 to 255. Got $it.")
}
it.toByte()
})
/**
* Parses the string value as a signed byte and wraps it.
* @param signed Signed value from `-128` to `127`.
* @throws NumberFormatException if the number is not within a valid range or if the string does not contains a valid number.
*/
@Throws(NumberFormatException::class)
constructor(signed: String): this(signed.toByte())
/**
* Returns a new wrapper with the current value.
*/
override fun deepCopy() = copy()
/**
* A technical string representation of this tag, containing the tag type and it's [signed] value,
* appropriated for developer inspections.
*/
override fun toTechnicalString(): String {
return "NbtByte($signed)"
}
companion object {
/**
* Parses the string value as an unsigned byte and wraps it.
* @param unsigned Unsigned value from `0` to `255`.
* @throws NumberFormatException if the number is not within a valid range or if the string does not contains a valid number.
*/
@JvmStatic fun unsigned(unsigned: String) = NbtByte(unsigned = unsigned.toInt())
}
}
/**
* A tag which wraps a short value.
* @property value The wrapped value
*/
data class NbtShort(var value: Short) : NbtTag() {
/**
* Returns a string representation of the tag's value.
*
* The returned string is compatible with string constructors of the same type.
*/
override val stringValue: String
get() = value.toString()
/**
* Parses the string value as a signed short and wraps it.
* @param signed Signed value from `-32768` to `32767`.
* @throws NumberFormatException if the number is not within a valid range or if the string does not contains a valid number.
*/
@Throws(NumberFormatException::class)
constructor(signed: String): this(signed.toShort())
/**
* Returns a new wrapper with the current value.
*/
override fun deepCopy() = copy()
}
/**
* A tag which wraps an int value.
* @property value The wrapped value
*/
data class NbtInt(var value: Int) : NbtTag() {
/**
* Returns a string representation of the tag's value.
*
* The returned string is compatible with string constructors of the same type.
*/
override val stringValue: String
get() = value.toString()
/**
* Parses the string value as a signed int and wraps it.
* @param signed Signed value from `-2147483648` to `2147483647`.
* @throws NumberFormatException if the number is not within a valid range or if the string does not contains a valid number.
*/
@Throws(NumberFormatException::class)
constructor(signed: String): this(signed.toInt())
/**
* Returns a new wrapper with the current value.
*/
override fun deepCopy() = copy()
}
/**
* A tag which wraps a long value.
* @property value The wrapped value
*/
data class NbtLong(var value: Long) : NbtTag() {
/**
* Returns a string representation of the tag's value.
*
* The returned string is compatible with string constructors of the same type.
*/
override val stringValue: String
get() = value.toString()
/**
* Parses the string value as a signed long and wraps it.
* @param signed Signed value from `-9223372036854775808` to `9223372036854775807`.
* @throws NumberFormatException if the number is not within a valid range or if the string does not contains a valid number.
*/
@Throws(NumberFormatException::class)
constructor(signed: String): this(signed.toLong())
/**
* Returns a new wrapper with the current value.
*/
override fun deepCopy() = copy()
}
/**
* A tag which wraps a float value.
* @property value The wrapped value
*/
data class NbtFloat(var value: Float) : NbtTag() {
/**
* Returns a string representation of the tag's value.
*
* The returned string is compatible with string constructors of the same type.
*/
override val stringValue: String
get() = value.toString()
/**
* Parses the string value as a signed float and wraps it.
* @param signed Signed value from `1.4e-45` to `3.4028235e+38`. NaN and Infinity are also accepted.
* @throws NumberFormatException if the number is not within a valid range or if the string does not contains a valid number.
*/
@Throws(NumberFormatException::class)
constructor(signed: String): this(signed.toFloat())
/**
* Returns a new wrapper with the current value.
*/
override fun deepCopy() = copy()
}
/**
* A tag which wraps a double value.
* @property value The wrapped value
*/
data class NbtDouble(var value: Double) : NbtTag() {
/**
* Returns a string representation of the tag's value.
*
* The returned string is compatible with string constructors of the same type.
*/
override val stringValue: String
get() = value.toString()
/**
* Parses the string value as a signed double and wraps it.
* @param signed Signed value from `4.9e-324` to `1.7976931348623157e+308`. NaN and Infinity are also accepted.
* @throws NumberFormatException if the number is not within a valid range or if the string does not contains a valid number.
*/
@Throws(NumberFormatException::class)
constructor(signed: String): this(signed.toDouble())
/**
* Returns a new wrapper with the current value.
*/
override fun deepCopy() = copy()
}
/**
* A tag which wraps a mutable byte array.
* @property value The wrapped value
*/
data class NbtByteArray(var value: ByteArray): NbtTag() {
/**
* Returns a string representation of the tag's value with a structure similar to a normal [List].
*
* The returned string is compatible with string constructors of the same type.
*
* Like [NbtByte], the bytes returned are signed, ranging from `-128` to `127`.
*
* Be aware that this may be a slow operation on big arrays.
*/
override val stringValue: String
get() = value.takeIf { it.isNotEmpty() }?.joinToString(prefix = "[", postfix = "]") ?: "[]"
/**
* Creates a new tag with an empty array.
*/
constructor(): this(byteArrayOf())
/**
* Parses the string using the same structure which is returned by [stringValue].
*
* The bytes should signed, ranging from `-127` to `127`.
*
* @param value A string with a structure like `[0, -32, 48, 127]`
*
* @throws IllegalArgumentException if the string does not have the exact format outputted by [stringValue]
*/
@Throws(IllegalArgumentException::class)
constructor(value: String): this(value
.removeSurrounding("[", "]")
.split(", ")
.takeIf { it.size > 1 || it.firstOrNull()?.isNotEmpty() == true }
?.map { it.toByte() }
?.toByteArray()
?: byteArrayOf()
)
override fun toTechnicalString(): String {
return "NbtByteArray$stringValue"
}
/**
* Properly checks the equality of the array.
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as NbtByteArray
if (!value.contentEquals(other.value)) return false
return true
}
/**
* Properly calculates the hashcode of the array.
*/
override fun hashCode(): Int {
return value.contentHashCode()
}
/**
* Returns a new wrapper with a copy of the current value.
*/
override fun deepCopy() = copy(value = value.copyOf())
}
/**
* A tag which wraps a [String] value.
* @property value The wrapped value
*/
data class NbtString(var value: String): NbtTag() {
/**
* Returns a string which is wrapped by this tag.
*/
override val stringValue: String
get() = value
override fun toTechnicalString(): String {
return buildString {
append("NbtString(\"")
append(
value.replace("\\", "\\\\")
.replace("\"", "\\\"")
)
append("\")")
}
}
/**
* Returns a new wrapper with the current value.
*/
override fun deepCopy() = copy()
}
/**
* A tag which contains a [MutableList] structure of [NbtTag]s. All children must have the same class.
*
* @param T The type of the tag that will be wrapped. [NbtEnd] and [NbtTag] are not valid.
*/
@Suppress("UNCHECKED_CAST")
class NbtList<T: NbtTag> private constructor(private val tags: ArrayList<T>): NbtTag(), MutableList<T> by tags, RandomAccess {
/**
* Returns a string representation of the tag's value.
*
* The output will be similar to a normal [List].
*
* The class names of the children tags will exposed.
*
* The returned string is compatible with string constructors of the same type.
*
* Be aware that this may be a slow operation on big lists, arrays or compounds.
*/
override val stringValue: String
get() = tags.toString()
/**
* Constructs a [NbtList] with the same contents of the given [Collection].
*
* All items in the list must have the same class.
*
* Null values in the list are not allowed.
*
* The tags in the list will be linked so any modification will also change this tag contents.
*/
constructor(tags: Collection<T>): this(ArrayList(tags))
/**
* Creates a empty list.
*/
constructor(): this(emptyList())
/**
* Uses all tags as initial value of this list. Make sure to use the same class in all values.
*/
constructor(vararg tags: T): this(tags.toList())
/**
* Uses all tags as initial value of this list. Make sure to use the same class in all values.
*/
constructor(tags: Iterable<T>): this(tags.toList())
/**
* Uses all tags as initial value of this list. Make sure to use the same class in all values.
*/
constructor(tags: Sequence<T>): this(tags.toList())
/**
* Uses all tags as initial value of this list. Make sure to use the same class in all values.
*/
constructor(tags: NbtList<T>): this(tags as Collection<T>)
/**
* Parses the string using the same structure which is returned by [stringValue].
*
* @param value A string with a structure like `[NbtInt(0), NbtInt(-32), NbtInt(48), NbtInt(127)]`
*
* @throws IllegalArgumentException if the string does not have the exact format outputted by [stringValue]
*/
@Throws(IllegalArgumentException::class)
constructor(value: String): this(NbtListStringParser(value).parseList() as ArrayList<T>)
override fun add(element: T): Boolean {
checkTagType(element)
return tags.add(element)
}
override fun add(index: Int, element: T) {
checkTagType(element)
return tags.add(index, element)
}
override fun set(index: Int, element: T): T {
if (size > 1) {
checkTagType(element)
}
return tags.set(index, element)
}
override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> {
val subList = tags.subList(fromIndex, toIndex)
return object : MutableList<T> by subList, RandomAccess {
override fun set(index: Int, element: T): T {
checkTagType(element)
return subList.set(index, element)
}
override fun toString(): String {
return tags.toString()
}
override fun equals(other: Any?): Boolean {
return subList == other
}
override fun hashCode(): Int {
return subList.hashCode()
}
}
}
private fun checkTagType(tag: NbtTag) {
val childrenType = (firstOrNull() ?: return)::class
require(childrenType == tag::class) {
"NbtList must have all children tags of the same type. \n" +
"Tried to add a ${tag::class.simpleName} tag in a NbtList of ${childrenType::class.simpleName}"
}
}
/**
* Returns a new NbtList with all nested values copied deeply.
*/
override fun deepCopy() = NbtList(map { it.deepCopy() as T })
/**
* A technical string representation of this tag, containing the tag type and it's value,
* appropriated for developer inspections.
*
* The output will have be similar to a normal [List].
*
* Be aware that this may be a slow operation on big lists, arrays or compounds.
*/
override fun toTechnicalString(): String {
if (tags.isEmpty()) {
return "NbtList[]"
}
return tags.joinToString(prefix = "NbtList[", postfix = "]")
}
override fun equals(other: Any?): Boolean {
return tags == other
}
override fun hashCode(): Int {
return tags.hashCode()
}
/**
* Contains useful methods to create [NbtList]s from Java.
*
* Kotlin users may call `list(1,2,3).toNbtList()` or similar methods.
*/
companion object {
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: Byte) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: Short) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: Int) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: Long) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: Float) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: Double) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: String) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: ByteArray) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: IntArray) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: LongArray) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: Map<String, NbtTag>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun create(vararg tags: Iterable<NbtTag>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createByteSublist(vararg tags: Iterable<Byte>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createByteSublist(vararg tags: Array<Byte>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createByteSublist(vararg tags: ByteArray) = tags.map { it.asIterable() }.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createShortSublist(vararg tags: Iterable<Short>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createShortSublist(vararg tags: Array<Short>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createShortSublist(vararg tags: ShortArray) = tags.map { it.asIterable() }.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createIntSublist(vararg tags: Iterable<Int>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createIntSublist(vararg tags: Array<Int>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createIntSublist(vararg tags: IntArray) = tags.map { it.asIterable() }.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createFloatSublist(vararg tags: Iterable<Float>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createFloatSublist(vararg tags: Array<Float>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createFloatSublist(vararg tags: FloatArray) = tags.map { it.asIterable() }.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createDoubleSublist(vararg tags: Iterable<Double>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createDoubleSublist(vararg tags: Array<Double>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createDoubleSublist(vararg tags: DoubleArray) = tags.map { it.asIterable() }.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createStringSublist(vararg tags: Iterable<String>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createStringSublist(vararg tags: Array<String>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createCompoundSublist(vararg tags: Iterable<Map<String, NbtTag>>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createCompoundSublist(vararg tags: Array<Map<String, NbtTag>>) = tags.toNbtList()
/**
* Returns a [NbtList] contained all elements wrapped in the appropriated [NbtTag].
*/
@JvmStatic fun createSublist(vararg tags: Iterable<Iterable<NbtTag>>) = tags.toNbtList()
}
}
/**
* A tag which contains a [MutableMap] structure associating [String]s to [NbtTag]s.
*
* It's the main heart of NBT files and usually contains complex structures.
*
* The returned tags by this class will be linked, so modifications to it will also affects the compound value.
*
* All get functions which are not prefixed with `Nullable` and `get` will throw a [ClassCastException]
* if the tag is mapped to a different class then the method used. For example if a given compound
* have a example=NbtInt(2) and you try to read it using [NbtCompound.getShort], an exception will be thrown.
*
* All get functions which are not prefixed with `Nullable` and `get` will throw [NoSuchElementException]
* if no value is mapped to the given name. This will change in future.
*
* All get list functions which returns lists of specific types will throw [IllegalStateException] if the list content
* does not match the requested type.
*
* @param value A [Map] which contains all key-value mappings.
*/
class NbtCompound private constructor(private val value: LinkedHashMap<String, NbtTag>) : NbtTag(), MutableMap<String, NbtTag> by value {
/**
* Returns a string representation of the tag's value.
*
* The output will be similar to a normal [Map].
*
* The class names of the children will exposed.
*
* The returned string is compatible with string constructors of the same type.
*
* Be aware that this may be a slow operation on compounds.
*/
override val stringValue: String
get() = value.takeIf { it.isNotEmpty() }?.entries?.joinToString(prefix = "{", postfix = "}") { (key, tag) ->
'"' + key.replace("\\", "\\\\").replace("\"", "\\\"") + "\"=" + tag
} ?: "{}"
/**
* Creates a new compound containing the same mappings as the given [Map].
*
* The tags in the map will be linked so any modification will also change this tag contents.
*/
constructor(value: Map<String, NbtTag>): this(LinkedHashMap(value))
/**
* Creates an empty compound.
*/
constructor(): this(emptyMap())
/**
* Creates a compound which maps the [Pair.first] value to the [Pair.second] tag initially.
*
* The given tags will be linked, so modifications to them will also affects the compound value.
*/
constructor(vararg tags: Pair<String, NbtTag>): this(mapOf(*tags))
/**
* Creates a compound which maps the [Pair.first] value to the [Pair.second] tag initially.
*
* The given tags will be linked, so modifications to them will also affects the compound value.
*/
constructor(tags: Iterable<Pair<String, NbtTag>>): this(tags.toMap())
/**
* @throws IllegalArgumentException if the string does not have the exact format outputted by [stringValue]
*/
@Throws(IllegalArgumentException::class)
constructor(value: String): this(NbtCompoundStringParser(value).parseCompound())
/**
* Directly maps a [NbtTag] to a key. The value must not be [NbtEnd].
* The given tag will be linked, so modifications to it will also affects the compound value.
*/
operator fun set(key: String, value: NbtTag) {
put(key, value)
}
/**
* Maps a [NbtByte] `1` if the value is `true` and `0` otherwise.
*/
operator fun set(key: String, value: Boolean) = set(key, if (value) BYTE_TRUE else 0)
/**
* Maps a [NbtByte] with the given value.
*/
operator fun set(key: String, value: Byte) = set(key, NbtByte(value))
/**
* Maps a [NbtShort] with the given value.
*/
operator fun set(key: String, value: Short) = set(key, NbtShort(value))
/**
* Maps a [NbtInt] with the given value.
*/
operator fun set(key: String, value: Int) = set(key, NbtInt(value))
/**
* Maps a [NbtLong] with the given value.
*/
operator fun set(key: String, value: Long) = set(key, NbtLong(value))
/**
* Maps a [NbtFloat] with the given value.
*/
operator fun set(key: String, value: Float) = set(key, NbtFloat(value))
/**
* Maps a [NbtDouble] with the given value.
*/
operator fun set(key: String, value: Double) = set(key, NbtDouble(value))
/**
* Maps a [NbtByteArray] with the given value. The array instance will be linked so any modification will also
* change the tag value.
*/
operator fun set(key: String, value: ByteArray) = set(key, NbtByteArray(value))
/**
* Maps a [NbtDouble] with the given value.
*/
operator fun set(key: String, value: String) = set(key, NbtString(value))
/**
* Maps a [NbtByteArray] with the given value. The array instance will be linked so any modification will also
* change the tag value.
*/
operator fun set(key: String, value: IntArray) = set(key, NbtIntArray(value))
/**
* Maps a [NbtByteArray] with the given value. The array instance will be linked so any modification will also
* change the tag value.
*/
operator fun set(key: String, value: LongArray) = set(key, NbtLongArray(value))
/**
* Returns `true` if [getByte] returns `1`, `false` otherwise.
* Will also return `false` if the value is not mapped.
* @throws ClassCastException If the [NbtTag] is not a [NbtByte]
*/
@Throws(ClassCastException::class)
fun getNullableBooleanByte(key: String) = getNullableByte(key) == BYTE_TRUE
/**
* Returns `true` if [getByte] returns `1`, `false` otherwise.
* @throws ClassCastException If the [NbtTag] is not a [NbtByte]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getBooleanByte(key: String) = getByte(key) == BYTE_TRUE
/**
* Returns the value corresponding to the given [key], or throw an exception if such a key is not present in the compound.
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(NoSuchElementException::class)
fun require(key: String) = get(key) ?: throw NoSuchElementException(key)
/**
* Returns the unwrapped byte value.
* @throws ClassCastException If the [NbtTag] is not a [NbtByte]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getByte(key: String) = (require(key) as NbtByte).signed
/**
* Returns the unwrapped short value.
* @throws ClassCastException If the [NbtTag] is not a [NbtShort]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getShort(key: String) = (require(key) as NbtShort).value
/**
* Returns the unwrapped int value.
* @throws ClassCastException If the [NbtTag] is not a [NbtInt]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getInt(key: String) = (require(key) as NbtInt).value
/**
* Returns the unwrapped long value.
* @throws ClassCastException If the [NbtTag] is not a [NbtLongArray]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getLong(key: String) = (require(key) as NbtLong).value
/**
* Returns the unwrapped float value.
* @throws ClassCastException If the [NbtTag] is not a [NbtFloat]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getFloat(key: String) = (require(key) as NbtFloat).value
/**
* Returns the unwrapped double value.
* @throws ClassCastException If the [NbtTag] is not a [NbtDouble]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getDouble(key: String) = (require(key) as NbtDouble).value
/**
* Returns the unwrapped byte array value. The array will be linked and any modification will
* also change wrapper and the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtByteArray]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getByteArray(key: String) = (require(key) as NbtByteArray).value
/**
* Returns the unwrapped string value.
* @throws ClassCastException If the [NbtTag] is not a [NbtString]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getString(key: String) = (require(key) as NbtString).value
/**
* Returns the unwrapped int array value. The array will be linked and any modification will
* also change wrapper and the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtIntArray]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getIntArray(key: String) = (require(key) as NbtIntArray).value
/**
* Returns the unwrapped long array value. The array will be linked and any modification will
* also change wrapper and the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtLongArray]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getLongArray(key: String) = (require(key) as NbtLongArray).value
/**
* Returns the [NbtCompound] mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtCompound]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getCompound(key: String) = require(key) as NbtCompound
/**
* Returns the [NbtList] mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
*/
@Throws(ClassCastException::class, NoSuchElementException::class)
fun getList(key: String) = require(key) as NbtList<*>
/**
* Returns the [NbtList] of bytes mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtByte]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getByteList(key: String) = getList(key).cast<NbtByte>()
/**
* Returns the [NbtList] of shorts mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtShort]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getShortList(key: String) = getList(key).cast<NbtShort>()
/**
* Returns the [NbtList] of integers mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtIntArray]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getIntList(key: String) = getList(key).cast<NbtInt>()
/**
* Returns the [NbtList] of longs mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtLong]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getLongList(key: String) = getList(key).cast<NbtLong>()
/**
* Returns the [NbtList] of floats mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtFloat]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getFloatList(key: String) = getList(key).cast<NbtFloat>()
/**
* Returns the [NbtList] of doubles mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtDouble]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getDoubleList(key: String) = getList(key).cast<NbtDouble>()
/**
* Returns the [NbtList] of byte arrays mapped to that key. The tag and it's value will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtByteArray]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getByteArrayList(key: String) = getList(key).cast<NbtByteArray>()
/**
* Returns the [NbtList] of strings mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtString]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getStringList(key: String) = getList(key).cast<NbtString>()
/**
* Returns the [NbtList] of int arrays mapped to that key. The tag and it's value will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtIntArray]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getIntArrayList(key: String) = getList(key).cast<NbtIntArray>()
/**
* Returns the [NbtList] of long arrays mapped to that key. The tag and it's values will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtLongArray]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getLongArrayList(key: String) = getList(key).cast<NbtLongArray>()
/**
* Returns the [NbtList] of compounds mapped to that key. The tag and it's values will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtCompound]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getCompoundList(key: String) = getList(key).cast<NbtCompound>()
/**
* Returns the [NbtList] of lists mapped to that key. The tag and it's values will be linked and any modification will
* also change the mapped value.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws NoSuchElementException If the key is not present on the compound
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtList]
*/
@Throws(ClassCastException::class, NoSuchElementException::class, IllegalStateException::class)
fun getListOfList(key: String) = getList(key).cast<NbtList<*>>()
/**
* Returns the unwrapped byte value or null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtByte]
*/
@Throws(ClassCastException::class)
fun getNullableByte(key: String) = this[key]?.let { it as NbtByte }?.signed
/**
* Returns the unwrapped short value or null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtShort]
*/
@Throws(ClassCastException::class)
fun getNullableShort(key: String) = this[key]?.let { it as NbtShort }?.value
/**
* Returns the unwrapped int value or null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtInt]
*/
@Throws(ClassCastException::class)
fun getNullableInt(key: String) = this[key]?.let { it as NbtInt }?.value
/**
* Returns the unwrapped long value or null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtLong]
*/
@Throws(ClassCastException::class)
fun getNullableLong(key: String) = this[key]?.let { it as NbtLong }?.value
/**
* Returns the unwrapped float value or null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtFloat]
*/
@Throws(ClassCastException::class)
fun getNullableFloat(key: String) = this[key]?.let { it as NbtFloat }?.value
/**
* Returns the unwrapped double value or null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtDouble]
*/
@Throws(ClassCastException::class)
fun getNullableDouble(key: String) = this[key]?.let { it as NbtDouble }?.value
/**
* Returns the unwrapped byte array value. The array will be linked and any modification will
* also change wrapper and the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtByteArray]
*/
@Throws(ClassCastException::class)
fun getNullableByteArray(key: String) = this[key]?.let { it as NbtByteArray }?.value
/**
* Returns the unwrapped string value or null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtString]
*/
@Throws(ClassCastException::class)
fun getNullableString(key: String) = this[key]?.let { it as NbtString }?.value
/**
* Returns the unwrapped int array value. The array will be linked and any modification will
* also change wrapper and the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtIntArray]
*/
@Throws(ClassCastException::class)
fun getNullableIntArray(key: String) = this[key]?.let { it as NbtIntArray }?.value
/**
* Returns the unwrapped long array value. The array will be linked and any modification will
* also change wrapper and the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtLongArray]
*/
@Throws(ClassCastException::class)
fun getNullableLongArray(key: String) = this[key]?.let { it as NbtLongArray }?.value
/**
* Returns the [NbtCompound] mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtCompound]
*/
@Throws(ClassCastException::class)
fun getNullableCompound(key: String) = this[key]?.let { it as NbtCompound }
/**
* Returns the [NbtList] mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
*/
@Throws(ClassCastException::class)
fun getNullableList(key: String) = this[key]?.let { it as NbtList<*> }
/**
* Returns the [NbtList] of bytes mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtByte]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableByteList(key: String) = getNullableList(key)?.cast<NbtByte>()
/**
* Returns the [NbtList] of shorts mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtShort]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableShortList(key: String) = getNullableList(key)?.cast<NbtShort>()
/**
* Returns the [NbtList] of integers mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtIntArray]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableIntList(key: String) = getNullableList(key)?.cast<NbtInt>()
/**
* Returns the [NbtList] of longs mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtLong]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableLongList(key: String) = getNullableList(key)?.cast<NbtLong>()
/**
* Returns the [NbtList] of floats mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtFloat]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableFloatList(key: String) = getNullableList(key)?.cast<NbtFloat>()
/**
* Returns the [NbtList] of doubles mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtDouble]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableDoubleList(key: String) = getNullableList(key)?.cast<NbtDouble>()
/**
* Returns the [NbtList] of byte arrays mapped to that key. The tag and it's value will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtByteArray]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableByteArrayList(key: String) = getNullableList(key)?.cast<NbtByteArray>()
/**
* Returns the [NbtList] of strings mapped to that key. The tag will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtString]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableStringList(key: String) = getNullableList(key)?.cast<NbtString>()
/**
* Returns the [NbtList] of int arrays mapped to that key. The tag and it's value will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtIntArray]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableIntArrayList(key: String) = getNullableList(key)?.cast<NbtIntArray>()
/**
* Returns the [NbtList] of long arrays mapped to that key. The tag and it's values will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtLongArray]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableLongArrayList(key: String) = getNullableList(key)?.cast<NbtLongArray>()
/**
* Returns the [NbtList] of compounds mapped to that key. The tag and it's values will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtCompound]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableCompoundList(key: String) = getNullableList(key)?.cast<NbtCompound>()
/**
* Returns the [NbtList] of lists mapped to that key. The tag and it's values will be linked and any modification will
* also change the mapped value.
*
* Will return null if no value is mapped or it is mapped to an other type tag.
* @throws ClassCastException If the [NbtTag] is not a [NbtList]
* @throws IllegalStateException If the list is not empty and contains any tag with class different then [NbtList]
*/
@Throws(ClassCastException::class, IllegalStateException::class)
fun getNullableListOfList(key: String) = getNullableList(key)?.cast<NbtList<*>>()
/**
* Checks if the other compound have a given tag, if it has then place it in this compound.
*
* The tag will be linked, so any change in the tag will also affect both compounds.
* @param other The compound that will be checked
* @param tagKey The name of the tag that will be mapped
* @param default If the other compound doesn't have the tag then this parameter will be used.
*/
fun copyFrom(other: NbtCompound, tagKey: String, default: NbtTag? = null) {
val tag = other[tagKey] ?: default
if (tag != null) {
this[tagKey] = tag
}
}
/**
* Checks if the this compound have a given tag, if it has then place it in the other compound.
*
* The tag will be linked, so any change in the tag will also affect both compounds.
* @param other The compound that will be modified
* @param tagKey The name of the tag that will be mapped
* @param default If the this compound doesn't have the tag then this parameter will be used.
*/
fun copyTo(other: NbtCompound, tagKey: String, default: NbtTag? = null) {
val tag = this[tagKey] ?: default
if (tag != null) {
other[tagKey] = tag
}
}
/**
* Returns a new NbtCompound with all nested values copied deeply.
*/
override fun deepCopy() = NbtCompound(mapValues { it.value.deepCopy() })
/**
* A technical string representation of this tag, containing the tag type and it's value,
* appropriated for developer inspections.
*
* The output will be similar to a normal [Map].
*
* Be aware that this may be a slow operation on compounds.
*/
override fun toTechnicalString(): String {
if (value.isEmpty()) {
return "NbtCompound{}"
}
return "NbtCompound$stringValue"
/*return buildString {
append("NbtCompound{")
val iterator = value.iterator()
while (iterator.hasNext()) {
val (key, tag) = iterator.next()
append(key).append('=').append(tag)
if (iterator.hasNext()) {
append(", ")
}
}
append('}')
}*/
}
override fun equals(other: Any?): Boolean {
return value == other
}
override fun hashCode(): Int {
return value.hashCode()
}
}
/**
* A tag which wraps a mutable int array.
* @property value The wrapped value
*/
data class NbtIntArray(var value: IntArray): NbtTag() {
/**
* Returns a string representation of the tag's value with a structure similar to a normal [List].
*
* The returned string is compatible with string constructors of the same type.
*
* Be aware that this may be a slow operation on big arrays.
*/
override val stringValue: String
get() = value.takeIf { it.isNotEmpty() }?.joinToString(prefix = "[", postfix = "]") ?: "[]"
/**
* Creates a new tag with an empty array.
*/
constructor(): this(intArrayOf())
/**
* Parses the string using the same structure which is returned by [stringValue].
*
* @param value A string with a structure like `[0, -32, 48, 127]`
*
* @throws IllegalArgumentException if the string does not have the exact format outputted by [stringValue]
*/
@Throws(IllegalArgumentException::class)
constructor(value: String): this(value
.removeSurrounding("[", "]")
.split(", ")
.takeIf { it.size > 1 || it.firstOrNull()?.isNotEmpty() == true }
?.map { it.toInt() }
?.toIntArray()
?: intArrayOf()
)
/**
* A technical string representation of this tag, containing the tag type and it's value,
* appropriated for developer inspections.
*
* The output will be similar to a normal [List].
*
* Be aware that this may be a slow operation on big arrays.
*/
override fun toTechnicalString(): String {
return "NbtIntArray$stringValue"
}
/**
* Properly checks the equality of the array.
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as NbtIntArray
if (!value.contentEquals(other.value)) return false
return true
}
/**
* Properly calculates the hashcode of the array.
*/
override fun hashCode(): Int {
return value.contentHashCode()
}
/**
* Returns a new wrapper with a copy of the current value.
*/
override fun deepCopy() = copy(value = value.copyOf())
}
/**
* A tag which wraps a mutable long array.
* @property value The wrapped value
*/
data class NbtLongArray(var value: LongArray) : NbtTag() {
/**
* Returns a string representation of the tag's value with a structure similar to a normal [List].
*
* The returned string is compatible with string constructors of the same type.
*
* Be aware that this may be a slow operation on big arrays.
*/
override val stringValue: String
get() = value.takeIf { it.isNotEmpty() }?.joinToString(prefix = "[", postfix = "]") ?: "[]"
/**
* Creates a new tag with an empty array.
*/
constructor(): this(longArrayOf())
/**
* Parses the string using the same structure which is returned by [stringValue].
*
* @param value A string with a structure like `[0, -32, 48, 127]`
*
* @throws IllegalArgumentException if the string does not have the exact format outputted by [stringValue]
*/
@Throws(IllegalArgumentException::class)
constructor(value: String): this(value
.removeSurrounding("[", "]")
.split(", ")
.takeIf { it.size > 1 || it.firstOrNull()?.isNotEmpty() == true }
?.map { it.toLong() }
?.toLongArray()
?: longArrayOf()
)
/**
* A technical string representation of this tag, containing the tag type and it's value,
* appropriated for developer inspections.
*
* The output will be similar to a normal [List].
*
* Be aware that this may be a slow operation on big arrays.
*/
override fun toTechnicalString(): String {
return "NbtLongArray$stringValue"
}
/**
* Properly checks the equality of the array.
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as NbtLongArray
if (!value.contentEquals(other.value)) return false
return true
}
/**
* Properly calculates the hashcode of the array.
*/
override fun hashCode(): Int {
return value.contentHashCode()
}
/**
* Returns a new wrapper with a copy of the current value.
*/
override fun deepCopy() = copy(value = value.copyOf())
}
| 0 | Kotlin | 0 | 0 | 77e79d52dbd9fe07ec40a02d6463bd75b3a86366 | 61,068 | Koterite-NBT | MIT License |
src/main/kotlin/io/kanro/idea/plugin/protobuf/lang/psi/primitive/structure/ProtobufScope.kt | yuxin-zhao | 359,704,598 | true | {"Kotlin": 311223, "Lex": 6288, "Java": 730} | package io.kanro.idea.plugin.protobuf.lang.psi.primitive.structure
import com.intellij.psi.util.QualifiedName
import io.kanro.idea.plugin.protobuf.lang.psi.ProtobufReservedName
import io.kanro.idea.plugin.protobuf.lang.psi.findChildren
import io.kanro.idea.plugin.protobuf.lang.psi.primitive.stratify.ProtobufBodyOwner
interface ProtobufScope : ProtobufScopeItemContainer, ProtobufScopeItem {
@JvmDefault
fun scope(): QualifiedName? {
return qualifiedName()
}
@JvmDefault
fun reservedNames(): Array<ProtobufReservedName> {
return if (this is ProtobufBodyOwner) {
this.body()?.findChildren() ?: arrayOf()
} else {
findChildren()
}
}
}
| 0 | null | 0 | 0 | 43fd148d80b7d11c17b12fb2be7df5b1fd68dba4 | 717 | intellij-protobuf-plugin | Apache License 2.0 |
app/src/main/java/com/travelbackintime/buybitcoin/impl/remoteconfig/RemoteConfigServiceImpl.kt | vase4kin | 121,007,217 | false | null | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.travelbackintime.buybitcoin.impl.remoteconfig
import com.github.vase4kin.coindesk.remoteconfig.RemoteConfigService
import com.github.vase4kin.crashlytics.Crashlytics
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
class RemoteConfigServiceImpl(
private val firebaseRemoteConfig: FirebaseRemoteConfig,
private val crashlytics: Crashlytics,
private val cacheSecs: Long
) : RemoteConfigService {
override val isAdsEnabled: Boolean
get() = firebaseRemoteConfig.getBoolean(RemoteConfigService.CONFIG_VALUE_ADS_ENABLED)
init {
fetch()
}
private fun fetch() {
firebaseRemoteConfig.fetch(cacheSecs).addOnCompleteListener { task ->
if (task.isSuccessful) {
firebaseRemoteConfig.activate()
} else {
task.exception?.let {
crashlytics.recordException(it)
}
}
}
}
}
| 0 | Kotlin | 6 | 5 | 0602649fe39b1f0c066adeeaaa2c007d5936d745 | 1,542 | Travel-back-in-time-Invest-in-Bitcoin | Apache License 2.0 |
network/twitter/src/main/kotlin/br/pedroso/tweetsentiment/network/twitter/interceptors/TwitterCredentialsAuthInterceptor.kt | felipepedroso | 124,307,018 | true | null | package br.pedroso.tweetsentiment.network.twitter.retrofit.interceptors
import okhttp3.Credentials
import okhttp3.Interceptor
import okhttp3.Response
class TwitterCredentialsAuthInterceptor(
private val twitterConsumerKey: String,
private val twitterConsumerSecret: String) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val authorization = Credentials.basic(twitterConsumerKey, twitterConsumerSecret)
val modifiedRequest = originalRequest.newBuilder()
.addHeader("Authorization", authorization)
.build()
return chain.proceed(modifiedRequest)
}
} | 0 | Kotlin | 1 | 10 | 32b675c791302861bfad8049ab1c4650b554b689 | 708 | tweet-sentiment | MIT License |
src/main/kotlin/com/cognifide/gradle/aem/instance/provision/Action.kt | gitter-badger | 221,784,747 | true | {"Kotlin": 637755, "Shell": 5281, "Java": 2130, "Batchfile": 267} | package com.cognifide.gradle.aem.instance.provision
class Action(val step: InstanceStep, val status: Status)
| 0 | null | 0 | 0 | 7620beac0ee16e265251f951d7101c30b2075157 | 110 | gradle-aem-plugin | Apache License 2.0 |
domain/src/commonMain/kotlin/kosh/domain/usecases/wc/WcSessionService.kt | niallkh | 855,100,709 | false | {"Kotlin": 1813876, "Swift": 594} | package kosh.domain.usecases.wc
import arrow.core.Either
import arrow.core.raise.Raise
import arrow.core.raise.either
import arrow.core.raise.recover
import co.touchlab.kermit.Logger
import kosh.domain.failure.WcFailure
import kosh.domain.failure.logFailure
import kosh.domain.models.Address
import kosh.domain.models.ChainAddress
import kosh.domain.models.ChainId
import kosh.domain.models.wc.WcSession
import kosh.domain.models.wc.WcSessionAggregated
import kosh.domain.repositories.WcRepo
import kosh.domain.serializers.ImmutableList
import kosh.domain.state.AppState
import kosh.domain.state.AppStateProvider
import kosh.domain.state.accounts
import kosh.domain.state.networks
import kosh.domain.utils.optic
import kotlinx.collections.immutable.toImmutableList
import kotlinx.collections.immutable.toPersistentHashSet
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
class WcSessionService(
private val applicationScope: CoroutineScope,
private val wcRepo: WcRepo,
private val appStateProvider: AppStateProvider,
) {
private val logger = Logger.withTag("[K]WcSessionService")
val sessions: Flow<ImmutableList<WcSession>>
get() = wcRepo.sessions.map { it.toImmutableList() }
suspend fun get(
id: WcSession.Id,
): Either<WcFailure, WcSessionAggregated> = either {
wcSessionAggregated(
session = wcRepo.getSession(id).bind(),
)
}
suspend fun update(
id: WcSession.Id,
approvedAccounts: List<Address>,
approvedChains: List<ChainId>,
): Either<WcFailure, Unit> {
return wcRepo.updateSession(
id = id,
approvedAccounts = approvedChains.flatMap { chainId ->
approvedAccounts.map { account -> ChainAddress(chainId, account) }
}
)
}
suspend fun addNetwork(
id: WcSession.Id,
chainId: ChainId,
): Either<WcFailure, Unit> = either {
val namespace = wcRepo.getNamespace(id).bind()
if (chainId !in namespace.approvedChainIds) {
val approvedAccounts = namespace.approvedAccounts
val newAccounts = approvedAccounts.distinctBy { it.address }
.map { ChainAddress(chainId, it.address) }
wcRepo.updateSession(
id = id,
approvedAccounts = approvedAccounts + newAccounts,
)
}
}
fun disconnect(
id: WcSession.Id,
) = applicationScope.launch {
recover({
wcRepo.disconnect(id).bind()
}) {
logger.logFailure(it)
}
}
private suspend fun Raise<WcFailure>.wcSessionAggregated(
session: WcSession,
): WcSessionAggregated {
val namespace = wcRepo.getNamespace(session.id).bind()
val networks = appStateProvider.optic(AppState.networks).value.values
val accounts = appStateProvider.optic(AppState.accounts).value.values
val approvedAccounts = namespace.approvedAccounts.map { it.address }.distinct()
return WcSessionAggregated(
session = session,
availableNetworks = networks
.filter { it.chainId in namespace.requiredChains || it.chainId in namespace.optionalChains }
.map { it.id }
.toPersistentHashSet(),
requiredNetworks = networks
.filter { it.chainId in namespace.requiredChains }
.map { it.id }
.toPersistentHashSet(),
approvedAccounts = accounts
.filter { it.address in approvedAccounts }
.map { it.id }
.toPersistentHashSet(),
approvedNetworks = networks
.filter { it.chainId in namespace.approvedChainIds }
.map { it.id }
.toPersistentHashSet(),
)
}
}
| 0 | Kotlin | 0 | 3 | f48555a563dfee5b07184771a6c94c065765d570 | 3,960 | kosh | MIT License |
app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadCache.kt | AriaMoradi | 391,623,094 | true | {"Kotlin": 2487091} | package eu.kanade.tachiyomi.data.download
import android.content.Context
import androidx.core.net.toUri
import com.hippo.unifile.UniFile
import eu.kanade.domain.download.service.DownloadPreferences
import eu.kanade.domain.manga.model.Manga
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.extension.ExtensionManager
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.lang.launchNonCancellable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.withTimeout
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import kotlin.time.Duration.Companion.seconds
/**
* Cache where we dump the downloads directory from the filesystem. This class is needed because
* directory checking is expensive and it slows down the app. The cache is invalidated by the time
* defined in [renewInterval] as we don't have any control over the filesystem and the user can
* delete the folders at any time without the app noticing.
*/
class DownloadCache(
private val context: Context,
private val provider: DownloadProvider = Injekt.get(),
private val sourceManager: SourceManager = Injekt.get(),
private val extensionManager: ExtensionManager = Injekt.get(),
private val downloadPreferences: DownloadPreferences = Injekt.get(),
) {
private val _changes: Channel<Unit> = Channel(Channel.UNLIMITED)
val changes = _changes.receiveAsFlow().onStart { emit(Unit) }
private val scope = CoroutineScope(Dispatchers.IO)
private val notifier by lazy { DownloadNotifier(context) }
/**
* The interval after which this cache should be invalidated. 1 hour shouldn't cause major
* issues, as the cache is only used for UI feedback.
*/
private val renewInterval = TimeUnit.HOURS.toMillis(1)
/**
* The last time the cache was refreshed.
*/
private var lastRenew = 0L
private var renewalJob: Job? = null
private var rootDownloadsDir = RootDirectory(getDirectoryFromPreference())
init {
downloadPreferences.downloadsDirectory().changes()
.onEach {
rootDownloadsDir = RootDirectory(getDirectoryFromPreference())
// Invalidate cache
lastRenew = 0L
}
.launchIn(scope)
}
/**
* Returns true if the chapter is downloaded.
*
* @param chapterName the name of the chapter to query.
* @param chapterScanlator scanlator of the chapter to query
* @param mangaTitle the title of the manga to query.
* @param sourceId the id of the source of the chapter.
* @param skipCache whether to skip the directory cache and check in the filesystem.
*/
fun isChapterDownloaded(
chapterName: String,
chapterScanlator: String?,
mangaTitle: String,
sourceId: Long,
skipCache: Boolean,
): Boolean {
if (skipCache) {
val source = sourceManager.getOrStub(sourceId)
return provider.findChapterDir(chapterName, chapterScanlator, mangaTitle, source) != null
}
renewCache()
val sourceDir = rootDownloadsDir.sourceDirs[sourceId]
if (sourceDir != null) {
val mangaDir = sourceDir.mangaDirs[provider.getMangaDirName(mangaTitle)]
if (mangaDir != null) {
return provider.getValidChapterDirNames(chapterName, chapterScanlator).any { it in mangaDir.chapterDirs }
}
}
return false
}
/**
* Returns the amount of downloaded chapters for a manga.
*
* @param manga the manga to check.
*/
fun getDownloadCount(manga: Manga): Int {
renewCache()
val sourceDir = rootDownloadsDir.sourceDirs[manga.source]
if (sourceDir != null) {
val mangaDir = sourceDir.mangaDirs[provider.getMangaDirName(manga.title)]
if (mangaDir != null) {
return mangaDir.chapterDirs.size
}
}
return 0
}
/**
* Adds a chapter that has just been download to this cache.
*
* @param chapterDirName the downloaded chapter's directory name.
* @param mangaUniFile the directory of the manga.
* @param manga the manga of the chapter.
*/
@Synchronized
fun addChapter(chapterDirName: String, mangaUniFile: UniFile, manga: Manga) {
// Retrieve the cached source directory or cache a new one
var sourceDir = rootDownloadsDir.sourceDirs[manga.source]
if (sourceDir == null) {
val source = sourceManager.get(manga.source) ?: return
val sourceUniFile = provider.findSourceDir(source) ?: return
sourceDir = SourceDirectory(sourceUniFile)
rootDownloadsDir.sourceDirs += manga.source to sourceDir
}
// Retrieve the cached manga directory or cache a new one
val mangaDirName = provider.getMangaDirName(manga.title)
var mangaDir = sourceDir.mangaDirs[mangaDirName]
if (mangaDir == null) {
mangaDir = MangaDirectory(mangaUniFile)
sourceDir.mangaDirs += mangaDirName to mangaDir
}
// Save the chapter directory
mangaDir.chapterDirs += chapterDirName
notifyChanges()
}
/**
* Removes a chapter that has been deleted from this cache.
*
* @param chapter the chapter to remove.
* @param manga the manga of the chapter.
*/
@Synchronized
fun removeChapter(chapter: Chapter, manga: Manga) {
val sourceDir = rootDownloadsDir.sourceDirs[manga.source] ?: return
val mangaDir = sourceDir.mangaDirs[provider.getMangaDirName(manga.title)] ?: return
provider.getValidChapterDirNames(chapter.name, chapter.scanlator).forEach {
if (it in mangaDir.chapterDirs) {
mangaDir.chapterDirs -= it
}
}
notifyChanges()
}
/**
* Removes a list of chapters that have been deleted from this cache.
*
* @param chapters the list of chapter to remove.
* @param manga the manga of the chapter.
*/
@Synchronized
fun removeChapters(chapters: List<Chapter>, manga: Manga) {
val sourceDir = rootDownloadsDir.sourceDirs[manga.source] ?: return
val mangaDir = sourceDir.mangaDirs[provider.getMangaDirName(manga.title)] ?: return
chapters.forEach { chapter ->
provider.getValidChapterDirNames(chapter.name, chapter.scanlator).forEach {
if (it in mangaDir.chapterDirs) {
mangaDir.chapterDirs -= it
}
}
}
notifyChanges()
}
/**
* Removes a manga that has been deleted from this cache.
*
* @param manga the manga to remove.
*/
@Synchronized
fun removeManga(manga: Manga) {
val sourceDir = rootDownloadsDir.sourceDirs[manga.source] ?: return
val mangaDirName = provider.getMangaDirName(manga.title)
if (sourceDir.mangaDirs.containsKey(mangaDirName)) {
sourceDir.mangaDirs -= mangaDirName
}
notifyChanges()
}
@Synchronized
fun removeSourceIfEmpty(source: Source) {
val sourceDir = provider.findSourceDir(source)
if (sourceDir?.listFiles()?.isEmpty() == true) {
sourceDir.delete()
rootDownloadsDir.sourceDirs -= source.id
}
notifyChanges()
}
/**
* Returns the downloads directory from the user's preferences.
*/
private fun getDirectoryFromPreference(): UniFile {
val dir = downloadPreferences.downloadsDirectory().get()
return UniFile.fromUri(context, dir.toUri())
}
/**
* Renews the downloads cache.
*/
private fun renewCache() {
// Avoid renewing cache if in the process nor too often
if (lastRenew + renewInterval >= System.currentTimeMillis() || renewalJob?.isActive == true) {
return
}
renewalJob = scope.launchIO {
try {
notifier.onCacheProgress()
var sources = getSources()
// Try to wait until extensions and sources have loaded
withTimeout(30.seconds) {
while (!extensionManager.isInitialized) {
delay(2.seconds)
}
while (sources.isEmpty()) {
delay(2.seconds)
sources = getSources()
}
}
val sourceDirs = rootDownloadsDir.dir.listFiles().orEmpty()
.associate { it.name to SourceDirectory(it) }
.mapNotNullKeys { entry ->
sources.find {
provider.getSourceDirName(it).equals(entry.key, ignoreCase = true)
}?.id
}
rootDownloadsDir.sourceDirs = sourceDirs
sourceDirs.values
.map { sourceDir ->
async {
val mangaDirs = sourceDir.dir.listFiles().orEmpty()
.filterNot { it.name.isNullOrBlank() }
.associate { it.name!! to MangaDirectory(it) }
sourceDir.mangaDirs = ConcurrentHashMap(mangaDirs)
mangaDirs.values.forEach { mangaDir ->
val chapterDirs = mangaDir.dir.listFiles().orEmpty()
.mapNotNull { chapterDir ->
chapterDir.name
?.replace(".cbz", "")
?.takeUnless { it.endsWith(Downloader.TMP_DIR_SUFFIX) }
}
.toMutableSet()
mangaDir.chapterDirs = chapterDirs
}
}
}
.awaitAll()
lastRenew = System.currentTimeMillis()
notifyChanges()
} finally {
notifier.dismissCacheProgress()
}
}
}
private fun getSources(): List<Source> {
return sourceManager.getOnlineSources() + sourceManager.getStubSources()
}
private fun notifyChanges() {
scope.launchNonCancellable {
_changes.send(Unit)
}
}
/**
* Returns a new map containing only the key entries of [transform] that are not null.
*/
private inline fun <K, V, R> Map<out K, V>.mapNotNullKeys(transform: (Map.Entry<K?, V>) -> R?): ConcurrentHashMap<R, V> {
val mutableMap = ConcurrentHashMap<R, V>()
forEach { element -> transform(element)?.let { mutableMap[it] = element.value } }
return mutableMap
}
}
/**
* Class to store the files under the root downloads directory.
*/
private class RootDirectory(
val dir: UniFile,
var sourceDirs: ConcurrentHashMap<Long, SourceDirectory> = ConcurrentHashMap(),
)
/**
* Class to store the files under a source directory.
*/
private class SourceDirectory(
val dir: UniFile,
var mangaDirs: ConcurrentHashMap<String, MangaDirectory> = ConcurrentHashMap(),
)
/**
* Class to store the files under a manga directory.
*/
private class MangaDirectory(
val dir: UniFile,
var chapterDirs: MutableSet<String> = mutableSetOf(),
)
| 0 | Kotlin | 0 | 1 | ba00d9e5d2c00b9cf415932bb2821bf9914fe248 | 12,102 | tachiyomi | Apache License 2.0 |
feature/src/main/java/com/viswa/feature/list/FeatureListFragment.kt | Vissonabe | 298,525,049 | false | null | package com.viswa.feature.list
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.navGraphViewModels
import com.viswa.core.DFMSavedStateViewModelFactory
import com.viswa.core.UserModel
import com.viswa.core.di.UserModelSingletonQualifier
import com.viswa.feature.FeatureActivityViewModel
import com.viswa.feature.FeatureSharedNavViewModel
import com.viswa.feature.R
import com.viswa.feature.model.MovieItem
import timber.log.Timber
import javax.inject.Inject
/**
* @author kienht
* @since 15/09/2020
*/
class FeatureListFragment : Fragment() {
@Inject
@UserModelSingletonQualifier
lateinit var singletonUserModel: UserModel
@Inject
lateinit var savedStateViewModelFactory: DFMSavedStateViewModelFactory
private val featureActivityViewModel by activityViewModels<FeatureActivityViewModel> { savedStateViewModelFactory }
private val featureListViewModel by viewModels<FeatureListViewModel> { savedStateViewModelFactory }
private val featureSharedNavViewModel
by navGraphViewModels<FeatureSharedNavViewModel>(R.id.feature_nav_graph) { savedStateViewModelFactory }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.feature_list_fragment,
container,
false
).apply {
findViewById<ComposeView>(R.id.compose_list).setContent {
featureListViewModel.getMovieCollectionData().observeAsState().value.let {
if (it != null) {
moviesList(items = it.items, ::onClickAction)
} else {
movieListNoContent()
}
}
}
}
}
private fun onClickAction(item: MovieItem) {
findNavController().navigate(FeatureListFragmentDirections.goToFeatureDetailFragment(movieItem = item))
}
override fun onAttach(context: Context) {
super.onAttach(context)
inject(context)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Timber.e("singleton userModel = $singletonUserModel")
singletonUserModel.value += " => FeatureListFragment"
Timber.e("userModel of Activity= ${featureActivityViewModel.userModel}")
Timber.e("userModel of Fragment = ${featureListViewModel.userModel}")
}
}
| 1 | Kotlin | 0 | 0 | 6d963c5d2c3db7eedeb7a7a84456d66029d03c1a | 2,909 | DaggerHiltDFM | Apache License 2.0 |
bitgouel-api/src/main/kotlin/team/msg/domain/student/service/StudentActivityServiceImpl.kt | GSM-MSG | 700,741,727 | false | {"Kotlin": 98835, "Dockerfile": 193} | package team.msg.domain.student.service
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import team.msg.common.enum.ApproveStatus
import team.msg.common.util.UserUtil
import team.msg.domain.student.exception.StudentNotFoundException
import team.msg.domain.student.model.StudentActivity
import team.msg.domain.student.presentation.data.request.CreateStudentActivityRequest
import team.msg.domain.student.repository.StudentActivityRepository
import team.msg.domain.student.repository.StudentRepository
import team.msg.domain.teacher.exception.TeacherNotFoundException
import team.msg.domain.teacher.repository.TeacherRepository
import java.util.*
@Service
class StudentActivityServiceImpl(
private val userUtil: UserUtil,
private val studentRepository: StudentRepository,
private val teacherRepository: TeacherRepository,
private val studentActivityRepository: StudentActivityRepository
) : StudentActivityService {
/**
* 학생 활동을 생성하는 비지니스 로직입니다
* @param CreateStudentActivityRequest
*/
@Transactional(rollbackFor = [Exception::class])
override fun createStudentActivity(request: CreateStudentActivityRequest) {
val user = userUtil.queryCurrentUser()
val student = studentRepository.findByUser(user)
?: throw StudentNotFoundException("학생을 찾을 수 없습니다. info : [ name = ${user.name} ]")
val teacher = teacherRepository.findByClub(student.club)
?: throw TeacherNotFoundException("취업 동아리 선생님을 찾을 수 없습니다.")
val studentActivity = StudentActivity(
id = UUID.randomUUID(),
title = request.title,
content = request.content,
credit = request.credit,
activityDate = request.activityDate,
student = student,
teacher = teacher,
approveStatus = ApproveStatus.PENDING
)
studentActivityRepository.save(studentActivity)
}
} | 7 | Kotlin | 0 | 10 | 37dca293fa5b84e5afcf768ce202263f08ab0d8e | 1,985 | Bitgouel-Server | MIT License |
app/src/main/java/com/car_inspection/ui/base/BaseDataActivity.kt | ProjectFreelancerMobile | 143,440,982 | false | {"Java": 685952, "Kotlin": 291627, "IDL": 11675} | package com.car_inspection.ui.base
import android.os.Bundle
import androidx.databinding.ViewDataBinding
import com.toan_itc.core.base.BaseViewModel
import com.toan_itc.core.base.CoreBaseDataActivity
/**
* Created by ToanDev on 28/2/18.
* Email:[email protected]
*/
abstract class BaseDataActivity<VM : BaseViewModel, DB : ViewDataBinding> : CoreBaseDataActivity<VM, DB>() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
}
| 1 | null | 1 | 1 | aa2d2a67a684ebbc021b42d27fa2ed7ac7dafd12 | 500 | Car_Inspection | MIT License |
administrator/src/main/java/com/kukus/administrator/delivery/tab/DeliveryList.kt | anas-abdrahman | 457,402,197 | false | {"Kotlin": 745237, "Java": 79801} | package com.kukus.administrator.delivery.tab
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.androidhuman.rxfirebase2.database.*
import com.cipolat.superstateview.SuperStateView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.kukus.administrator.R
import com.kukus.administrator.delivery.drag.OnCustomerListChangedListener
import com.kukus.administrator.delivery.drag.OnStartDragListener
import com.kukus.administrator.delivery.drag.ItemTouchHelperCallback
import com.kukus.library.Constant.Companion.EXTRA_STATUS
import com.kukus.library.Constant.Companion.STATUS
import com.kukus.library.Constant.Companion.TRIP
import com.kukus.library.FirebaseUtils.Companion.getDate
import com.kukus.library.FirebaseUtils.Companion.getShip
import com.kukus.library.FirebaseUtils.Companion.getUserId
import com.kukus.library.model.Ship
import org.jetbrains.anko.find
import java.lang.StringBuilder
import kotlin.collections.ArrayList
class DeliveryList : Fragment(), OnCustomerListChangedListener, OnStartDragListener {
var statusDelivery = TRIP.NEW
var date = getDate
var list = arrayListOf<Ship>()
lateinit var adapter: DeliveryAdapter
lateinit var mItemTouchHelper: ItemTouchHelper
lateinit var mSharedPreferences: SharedPreferences
lateinit var recyclerView: RecyclerView
lateinit var empty: SuperStateView
lateinit var txt_info: TextView
lateinit var progress: LinearLayout
var isOnline = false
companion object {
fun newInstance(status: TRIP): DeliveryList {
val bundle = Bundle()
val fragment = DeliveryList()
bundle.putSerializable(EXTRA_STATUS, status)
fragment.arguments = bundle
return fragment
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
statusDelivery = arguments?.get(EXTRA_STATUS) as TRIP
val view = inflater.inflate(R.layout.fragment_delivery, container, false)
recyclerView = view.find(R.id.recyclerView)
empty = view.find(R.id.empty)
txt_info = view.find(R.id.txt_info)
progress = view.find(R.id.progress)
mSharedPreferences = context!!.getSharedPreferences("$statusDelivery-preference-file", Context.MODE_PRIVATE)
setupRecyclerView()
setupAdapterList()
return view
}
@SuppressLint("CheckResult")
fun setupAdapterList(date: String = getDate) {
this.date = date
getShip(this.date).dataChanges().subscribe {
if (it.exists()) {
list.clear()
it.children.forEach { data ->
val ship = data.getValue(Ship::class.java)
if (ship != null) {
if (statusDelivery == TRIP.ACTIVE && ship.status == STATUS.PENDING && ship.deliveryId == "" && isOnline) {
list.add(ship)
} else if (statusDelivery == TRIP.UPCOMING && (ship.status == STATUS.PENDING || ship.status == STATUS.DISPATCHED) && ship.deliveryId == getUserId) {
list.add(ship)
} else if (statusDelivery == TRIP.PAST && ship.status == STATUS.COMPLETE && ship.deliveryId == getUserId) {
list.add(ship)
}
}
}
if (list.size > 0) {
list = getSampleData(list)
adapter.swapAdapter(list)
adapter.notifyDataSetChanged()
recyclerView.adapter = adapter
recyclerView.visibility = View.VISIBLE
empty.visibility = View.GONE
} else {
recyclerView.visibility = View.GONE
empty.visibility = View.VISIBLE
}
txt_info.text = StringBuilder("$date (" + list.size.toString() + ")")
} else {
txt_info.text = StringBuilder("$date (0)")
recyclerView.visibility = View.GONE
empty.visibility = View.VISIBLE
}
progress.visibility = View.GONE
}
}
override fun onNoteListChanged(ships: ArrayList<Ship>) {
val listOfSortedCustomerId = ArrayList<String>()
for (ship in ships) {
listOfSortedCustomerId.add(ship.id)
}
val gson = Gson()
val jsonListOfSortedCustomerIds = gson.toJson(listOfSortedCustomerId)
//save to SharedPreference
mSharedPreferences.edit().putString("$statusDelivery-list-$date", jsonListOfSortedCustomerIds).apply()
mSharedPreferences.edit().apply()
}
private fun getSampleData(list: ArrayList<Ship>): ArrayList<Ship> {
val customerList = list
val sortedCustomers = ArrayList<Ship>()
val jsonListOfSortedCustomerId = mSharedPreferences.getString("$statusDelivery-list-$date", "")
if (jsonListOfSortedCustomerId!!.isNotEmpty()) {
val gson = Gson()
val listOfSortedCustomersId = gson.fromJson<List<String>>(jsonListOfSortedCustomerId, object : TypeToken<List<String>>() {}.type)
if (listOfSortedCustomersId != null && listOfSortedCustomersId.isNotEmpty()) {
for (id in listOfSortedCustomersId) {
for (customer in customerList) {
if (customer.id == id) {
sortedCustomers.add(customer)
customerList.remove(customer)
break
}
}
}
}
if (customerList.size > 0) {
sortedCustomers.addAll(customerList)
}
return sortedCustomers
} else {
return customerList
}
}
private fun setupRecyclerView() {
val linearLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = linearLayoutManager
adapter = DeliveryAdapter(list, this, this)
mItemTouchHelper = ItemTouchHelper(ItemTouchHelperCallback(adapter))
mItemTouchHelper.attachToRecyclerView(recyclerView)
}
override fun onStartDrag(viewHolder: RecyclerView.ViewHolder?) {
mItemTouchHelper.startDrag(viewHolder)
}
}
| 0 | Kotlin | 0 | 0 | a5961fd9c4061246c94c603ea5027f82934b59e8 | 7,062 | food-order-and-delivery | MIT License |
app/src/main/java/com/research/researchbuddy/ui/activities/search/SearchViewModel.kt | data-programmer | 580,098,714 | false | null | package com.research.researchbuddy.ui.activities.search
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.research.researchbuddy.api.core.CoreRepository
import com.research.researchbuddy.api.springernature.SpringerNatureRepository
import com.research.researchbuddy.api.utilities.CoreResponseParser
import com.research.researchbuddy.api.utilities.SpringerNatureResponseParser
import com.research.researchbuddy.models.ApiResult
import com.research.researchbuddy.models.CoreResponse
import com.research.researchbuddy.models.Paper
import com.research.researchbuddy.models.SpringerNatureResponse
import kotlinx.coroutines.launch
import java.io.IOException
class SearchViewModel(
private val springerNatureRepository: SpringerNatureRepository,
private val coreRepository: CoreRepository
): ViewModel() {
var searchProvider = ""
var searchBy = ""
var searchText = ""
private val _researchSearchResult = MutableLiveData<List<Paper>>()
val researchSearchResult: LiveData<List<Paper>> = _researchSearchResult
fun fetchResearchSearchResult() {
viewModelScope.launch {
val result = when (searchProvider) {
"Springer Nature" -> { searchSpringerNature() }
"CORE" -> { searchCore() }
else -> { ApiResult.Error(IOException("Unknown data source")) }
}
if (result is ApiResult.Success) {
val data = result.data
val parsedResultList = when (searchProvider) {
"Springer Nature" -> { SpringerNatureResponseParser.parseResponseObject(data as SpringerNatureResponse) }
"CORE" -> { CoreResponseParser.parseResponseObject(data as CoreResponse) }
else -> { listOf() }
}
_researchSearchResult.postValue(parsedResultList)
} else {
_researchSearchResult.postValue(listOf())
}
}
}
private suspend fun searchSpringerNature(): ApiResult<SpringerNatureResponse> {
return springerNatureRepository.getResearchResult(buildSpringerNatureQuery())
}
private suspend fun searchCore(): ApiResult<CoreResponse> {
return coreRepository.getResearchResult(buildCoreQuery())
}
private fun buildSpringerNatureQuery(): String = "keyword:$searchText"
private fun buildCoreQuery(): String = "$searchText"
} | 0 | Kotlin | 0 | 0 | 7152791a87616178ad2fdf4abd9d99ec1f3a267a | 2,532 | research-buddy | MIT License |
kotlin-eclipse-core/src/org/jetbrains/kotlin/core/model/scriptTemplateProviderEP.kt | yugecin | 180,190,172 | true | {"Kotlin": 848423, "Java": 745576, "AspectJ": 15193} | package org.jetbrains.kotlin.core.model
import org.eclipse.core.resources.IFile
import org.eclipse.core.runtime.IProgressMonitor
import org.eclipse.core.runtime.SubMonitor
import org.jetbrains.kotlin.core.log.KotlinLogger
import org.jetbrains.kotlin.script.KotlinScriptDefinition
import org.jetbrains.kotlin.script.KotlinScriptDefinitionFromAnnotatedTemplate
import org.jetbrains.kotlin.script.ScriptTemplatesProvider
import org.jetbrains.kotlin.script.makeScriptDefsFromTemplatesProviders
import java.io.File
import java.net.URLClassLoader
const val SCRIPT_TEMPLATE_PROVIDER_EP_ID = "org.jetbrains.kotlin.core.scriptTemplateProvider"
const val SCRIPT_TEMPLATE_PROVIDER_EP_EX_ID = "org.jetbrains.kotlin.core.scriptTemplateProviderEx"
fun loadAndCreateDefinitionsByTemplateProviders(
eclipseFile: IFile,
monitor: IProgressMonitor
): Pair<List<KotlinScriptDefinition>, List<String>> {
val scriptTemplateProviders = loadExecutableEP<ScriptTemplatesProvider>(SCRIPT_TEMPLATE_PROVIDER_EP_ID).mapNotNull { it.createProvider() }
val definitionsFromProviders = makeScriptDefsFromTemplatesProviders(scriptTemplateProviders) { provider, e ->
KotlinLogger.logError(
"Extension (scriptTemplateProvider) with template ${provider.templateClassNames.joinToString()} " +
"could not be initialized", e)
}
val scriptTemplateProvidersEx = loadExecutableEP<ScriptTemplateProviderEx>(SCRIPT_TEMPLATE_PROVIDER_EP_EX_ID).mapNotNull { it.createProvider() }
val definitionsFromProvidersEx = makeScriptDefsFromEclipseTemplatesProviders(eclipseFile, scriptTemplateProvidersEx, monitor)
val onlyProvidersEx = definitionsFromProvidersEx.map { it.first }
val providersClasspath = definitionsFromProvidersEx.flatMap { it.second }
return Pair(definitionsFromProviders + onlyProvidersEx, providersClasspath)
}
interface ScriptTemplateProviderEx {
val templateClassName: String
fun isApplicable(file: IFile): Boolean = true
fun getTemplateClasspath(environment: Map<String, Any?>?, monitor: IProgressMonitor): Iterable<String>
fun getEnvironment(file: IFile): Map<String, Any?>?
}
fun makeScriptDefsFromEclipseTemplatesProviders(
eclipseFile: IFile,
providers: Iterable<ScriptTemplateProviderEx>,
monitor: IProgressMonitor
): List<Pair<KotlinScriptDefinition, Iterable<String>>> {
return providers
.filter { it.isApplicable(eclipseFile) }
.map { provider: ScriptTemplateProviderEx ->
try {
val subMonitor = SubMonitor.convert(monitor)
val templateClasspath = provider.getTemplateClasspath(provider.getEnvironment(eclipseFile), subMonitor)
if (subMonitor.isCanceled) return@map null
val loader = URLClassLoader(
templateClasspath.map { File(it).toURI().toURL() }.toTypedArray(),
ScriptTemplateProviderEx::class.java.classLoader
)
val cl = loader.loadClass(provider.templateClassName)
Pair(KotlinScriptDefinitionFromAnnotatedTemplate(cl.kotlin, null, null, provider.getEnvironment(eclipseFile)), templateClasspath)
} catch (ex: Exception) {
KotlinLogger.logError(
"Extension (EclipseScriptTemplateProvider) ${provider::class.java.name} with templates ${provider.templateClassName} " +
"could not be initialized", ex)
null
}
}
.filterNotNull()
} | 0 | Kotlin | 0 | 0 | 726d8be8a3c4dab9f6053b1257e3bfac9824cea3 | 3,716 | kotlin-eclipse | Apache License 2.0 |
androidloggeroutput/src/main/java/com/ultimatelogger/android/output/AndroidLog.kt | ArturBorowy | 202,520,475 | false | null | package com.ultimatelogger.android.output
import android.util.Log
import com.ultimatelogger.multiplatform.output.MultiPriorityLogger
internal class AndroidLog : MultiPriorityLogger {
override fun v(tag: String?, msg: String?, throwable: Throwable?) {
Log.v(tag, msg, throwable)
}
override fun d(tag: String?, msg: String?, throwable: Throwable?) {
Log.d(tag, msg, throwable)
}
override fun i(tag: String?, msg: String?, throwable: Throwable?) {
Log.i(tag, msg, throwable)
}
override fun w(tag: String?, msg: String?, throwable: Throwable?) {
Log.w(tag, msg, throwable)
}
override fun e(tag: String?, msg: String?, throwable: Throwable?) {
Log.e(tag, msg, throwable)
}
override fun wtf(tag: String?, msg: String?, throwable: Throwable?) {
Log.wtf(tag, msg, throwable)
}
override fun println(priority: Int, tag: String?, msg: String?) {
Log.println(priority, tag, msg)
}
} | 0 | Kotlin | 0 | 2 | 7349742f55a00058d627e121ec7c4ac53481a6d2 | 991 | ultimate-logger-android | MIT License |
app/src/main/java/com/globalfsm/features/viewAllOrder/interf/ColorListOnCLick.kt | DebashisINT | 614,841,798 | false | null | package com.globalfsm.features.viewAllOrder.interf
import com.globalfsm.app.domain.NewOrderGenderEntity
import com.globalfsm.features.viewAllOrder.model.ProductOrder
interface ColorListOnCLick {
fun colorListOnCLick(size_qty_list: ArrayList<ProductOrder>, adpPosition:Int)
} | 0 | Kotlin | 0 | 0 | f0435b0dd4b1ce20137b6a892ed58c2b7d7142f7 | 280 | GLOBAL | Apache License 2.0 |
app/src/main/java/com/example/graduation/presentation/ui/Relief/nature/MyData.kt | PanicLess-2023 | 628,118,517 | false | null | package com.example.graduation.presentation.ui.Relief.nature
data class MyData(val imageResource: Int, val text: String,val time:String)
| 0 | Kotlin | 0 | 0 | c6c8e69421f441e48b5869e98dea804ffe31183a | 138 | Panicless | MIT License |
src/main/kotlin/in/rcard/domain/JobDomain.kt | rcardin | 619,442,922 | false | null | package `in`.rcard.domain
val JOBS_DATABASE: Map<JobId, Job> = mapOf(
JobId(1) to Job(
JobId(1),
Company("Apple, Inc."),
Role("Software Engineer"),
Salary(70_000.00),
),
JobId(2) to Job(
JobId(2),
Company("Microsoft"),
Role("Software Engineer"),
Salary(80_000.00),
),
JobId(3) to Job(
JobId(3),
Company("Google"),
Role("Software Engineer"),
Salary(90_000.00),
),
)
class CurrencyConverter {
fun convertUsdToEur(amount: Double): Double = amount * 0.91
}
data class Job(val id: JobId, val company: Company, val role: Role, val salary: Salary)
@JvmInline
value class JobId(val value: Long)
@JvmInline
value class Company(val name: String)
@JvmInline
value class Role(val name: String)
@JvmInline
value class Salary(val value: Double) {
operator fun compareTo(other: Salary): Int = value.compareTo(other.value)
}
| 0 | Kotlin | 0 | 0 | a65f045dfe59c1332c7372a13bf0068864e6a857 | 944 | functional-error-handling-in-kotlin | MIT License |
app/src/main/java/io/horizontalsystems/bankwallet/modules/swap/coinselect/SelectSwapCoinViewHolder.kt | horizontalsystems | 142,825,178 | false | null | package io.horizontalsystems.bankwallet.modules.swap.coinselect
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import io.horizontalsystems.bankwallet.core.*
import io.horizontalsystems.bankwallet.databinding.ViewHolderSwapCoinSelectBinding
import io.horizontalsystems.bankwallet.modules.swap.SwapMainModule.CoinBalanceItem
class SelectSwapCoinViewHolder(
private val binding: ViewHolderSwapCoinSelectBinding,
val onClick: (item: CoinBalanceItem) -> Unit
) : RecyclerView.ViewHolder(binding.root) {
private var coinItem: CoinBalanceItem? = null
init {
binding.wrapper.setOnSingleClickListener {
coinItem?.let {
onClick(it)
}
}
}
fun bind(coinItem: CoinBalanceItem, showBottomBorder: Boolean) {
this.coinItem = coinItem
binding.bottomShade.isVisible = showBottomBorder
coinItem.apply {
binding.coinIcon.setRemoteImage(
platformCoin.coin.iconUrl,
platformCoin.coinType.iconPlaceholder
)
binding.coinTitle.text = platformCoin.name
binding.coinSubtitle.text = platformCoin.code
binding.coinBalance.text = balance?.let {
App.numberFormatter.formatCoin(it, platformCoin.code, 0, 8)
}
binding.fiatBalance.text = fiatBalanceValue?.let {
App.numberFormatter.formatFiat(
fiatBalanceValue.value,
fiatBalanceValue.currency.symbol,
0,
2
)
}
}
}
}
| 153 | Kotlin | 190 | 348 | fea4c5d96759a865408f92e661a13e10faa66226 | 1,652 | unstoppable-wallet-android | MIT License |
game/src/main/java/com/reco1l/rimu/ui/entity/hitobjects/HitCircle.kt | Reco1I | 730,791,679 | false | null | package com.reco1l.rimu.ui.entity.hitobjects
import com.reco1l.rimu.MainContext
import com.reco1l.rimu.management.skin.WorkingSkin
import com.reco1l.rimu.ui.entity.Sprite
import com.reco1l.rimu.ui.entity.TextureText
open class HitCircleEntity(ctx: MainContext) : HitObjectEntity(ctx)
{
val bodySprite = Sprite { rules.texture = "hitcircle" }
val overlaySprite = Sprite { rules.texture = "hitcircleoverlay" }
val numberSprite = TextureText {
rules.textureProvider = {
// Prepending the skin prefix for the font.
"${ctx.skins.current?.run { data.fonts.hitCirclePrefix } ?: "default"}-$it"
}
text = "1"
}
val approachCircleSprite = Sprite { rules.texture = "approachcircle" }
override fun onApplySkin(skin: WorkingSkin)
{
super.onApplySkin(skin)
// If true the number sprite will be placed as index 1 which is below the hit circle overlay otherwise 2 which
// is the last index.
val above = skin.data.general.hitCircleOverlayAboveNumber
numberSprite.zIndex = if (above) 1 else 2
overlaySprite.zIndex = if (above) 2 else 1
}
} | 0 | null | 1 | 3 | 611c6224060baeb242ecc2422449cdf1ba13b78a | 1,164 | rimu | Apache License 2.0 |
src/main/kotlin/org/jetbrains/research/testspark/tools/llm/generation/Patterns.kt | JetBrains-Research | 563,889,235 | false | {"Kotlin": 468262, "Java": 3848, "Shell": 132} | package org.jetbrains.research.testspark.tools.llm.generation
val importPattern = Regex(
pattern = "^import\\s+(static\\s)?((?:[a-zA-Z_]\\w*\\.)*[a-zA-Z_](?:\\w*\\.?)*)(?:\\.\\*)?;",
options = setOf(RegexOption.MULTILINE),
)
val packagePattern = Regex(
pattern = "^package\\s+((?:[a-zA-Z_]\\w*\\.)*[a-zA-Z_](?:\\w*\\.?)*)(?:\\.\\*)?;",
options = setOf(RegexOption.MULTILINE),
)
val runWithPattern = Regex(
pattern = "@RunWith\\([^)]*\\)",
options = setOf(RegexOption.MULTILINE),
)
| 15 | Kotlin | 3 | 9 | c728ca34820480025e1ea0f6ddd6847228b7f142 | 508 | TestSpark | MIT License |
composeApp/src/commonMain/kotlin/com/ethossoftworks/land/service/discovery/INSDService.kt | ethossoftworks | 662,813,245 | false | {"Kotlin": 209395, "Swift": 14097, "Shell": 703} | package com.ethossoftworks.land.service.discovery
import com.outsidesource.oskitkmp.outcome.Outcome
import kotlinx.coroutines.flow.Flow
interface INSDService {
suspend fun init()
suspend fun registerService(
type: String,
name: String,
port: Int,
properties: Map<String, Any> = emptyMap()
): Outcome<Unit, Any>
suspend fun unregisterService(type: String, name: String, port: Int): Outcome<Unit, Any>
suspend fun observeServiceTypes(): Flow<NSDServiceType>
suspend fun observeServices(type: String): Flow<NSDServiceEvent>
suspend fun getLocalIpAddress(): String?
}
sealed class NSDServiceEvent {
data class ServiceAdded(val service: NSDServicePartial) : NSDServiceEvent()
data class ServiceResolved(val service: NSDService) : NSDServiceEvent()
data class ServiceRemoved(val service: NSDServicePartial) : NSDServiceEvent()
data class Error(val error: NSDServiceError) : NSDServiceEvent()
}
enum class NSDServiceError {
Unknown,
NoPermission,
Cancelled,
}
data class NSDServiceType(
val type: String,
)
data class NSDService(
val type: String, // Fully qualified type i.e. "_hue._tcp.local."
val name: String,
val port: Int,
val iPv4Addresses: Set<String>,
val iPv6Addresses: Set<String>,
val props: Map<String, ByteArray>,
)
data class NSDServicePartial(
val type: String,
val name: String,
) | 0 | Kotlin | 0 | 0 | 4f80493cb1ddc91b21d077c562d34fe6dbae71db | 1,421 | LANd | MIT License |
app/src/main/java/com/yelinaung/luluaung/views/views/DetailView.kt | yemyatthu1990 | 91,767,251 | true | {"Java": 929950, "Kotlin": 49268, "HTML": 4048} | package com.yelinaung.luluaung.views.views
import com.yelinaung.luluaung.views.View
/**
* Created by user on 9/9/16.
*/
interface DetailView : View {
}
| 0 | Java | 0 | 0 | 334b884267bcca85f315c7ea3908c4b9c32dced8 | 164 | Lu-lu-aung | Do What The F*ck You Want To Public License |
eos-http-rpc/src/main/kotlin/com/memtrip/eos/http/rpc/model/block/response/Block.kt | memtrip | 149,500,589 | false | null | /**
* Copyright 2013-present memtrip LTD.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.memtrip.eos.http.rpc.model.block.response
import com.squareup.moshi.JsonClass
import java.util.Date
@JsonClass(generateAdapter = true)
data class Block(
val id: String,
val block_num: Int,
val confirmed: Int,
val ref_block_prefix: Long,
val previous: String,
val timestamp: String,
val transaction_mroot: String,
val action_mroot: String,
val block_mroot: String?,
val producer: String,
val schedule_version: Int,
val new_producers: Any?,
val producer_signature: String,
val regions: List<Region>?,
val transactions: List<TransactionInBlock>?
)
@JsonClass(generateAdapter = true)
data class TransactionInBlock(
val status: String,
val cpu_usage_us: Int,
val net_usage_words: Int,
val trx: Any?
)
class Trx(map: Map<String, Any?>) {
val id: String by map
val transaction: Map<String, Any> by map
}
class BlockTransaction(map: Map<String, Any?>) {
val expiration: Date by map
val ref_block_num: Int by map
val ref_block_prefix: Long by map
val max_net_usage_words: Long by map
val max_cpu_usage_ms: Long by map
val delay_sec: Long by map
val context_free_actions: List<Map<String, Any>> by map
val actions: List<Map<String, Any>> by map
}
class BlockTransactionAction(map: Map<String, Any?>) {
val account: String by map
val name: String by map
val data: Map<String, Any> by map
}
class TransferData(map: Map<String, Any?>) {
val from: String by map
val to: String by map
val quantity: String by map
val memo: String by map
} | 5 | null | 3 | 38 | 30006ce7047843ba3f2f8d43d657c7e7627a63ca | 2,190 | eos-jvm | Apache License 2.0 |
publication/publication-statistic/src/main/kotlin/com/lurking/cobra/blog/farm/api/reciever/PublicationLifecycleSchedulerConfiguration.kt | ekgreen | 432,851,339 | false | {"Kotlin": 185548} | package com.lurking.cobra.blog.farm.api.reciever
interface PublicationLifecycleSchedulerConfiguration {
fun getSchedulingDelay(): Long
} | 0 | Kotlin | 2 | 0 | 0f8e59450fb2da05aa38769cc38285af7754d09c | 142 | the-lurking-cobra-in-borsh-blog | Apache License 2.0 |
editor/src/main/kotlin/de/hanno/hpengine/graphics/editor/ImGuiEditor.kt | hannomalie | 330,376,962 | false | {"Kotlin": 977710, "GLSL": 659823, "JavaScript": 3160, "Shell": 137, "Batchfile": 65} | package de.hanno.hpengine.graphics.editor
import InternalTextureFormat.RGB8
import com.artemis.BaseEntitySystem
import com.artemis.BaseSystem
import com.artemis.ComponentManager
import com.artemis.World
import com.artemis.annotations.All
import com.artemis.utils.Bag
import de.hanno.hpengine.component.TransformComponent
import de.hanno.hpengine.config.Config
import de.hanno.hpengine.graphics.*
import de.hanno.hpengine.graphics.constants.Facing
import de.hanno.hpengine.graphics.constants.MinFilter
import de.hanno.hpengine.graphics.constants.RenderingMode
import de.hanno.hpengine.graphics.constants.TextureFilterConfig
import de.hanno.hpengine.graphics.editor.extension.EditorExtension
import de.hanno.hpengine.graphics.editor.panels.PanelLayout
import de.hanno.hpengine.graphics.editor.panels.leftPanel
import de.hanno.hpengine.graphics.editor.panels.rightPanel
import de.hanno.hpengine.graphics.editor.select.EntitySelection
import de.hanno.hpengine.graphics.editor.select.MeshSelection
import de.hanno.hpengine.graphics.editor.select.Selection
import de.hanno.hpengine.graphics.editor.select.SimpleEntitySelection
import de.hanno.hpengine.graphics.fps.FPSCounter
import de.hanno.hpengine.graphics.output.FinalOutput
import de.hanno.hpengine.graphics.output.FinalOutputImpl
import de.hanno.hpengine.graphics.profiling.GPUProfiler
import de.hanno.hpengine.graphics.rendertarget.*
import de.hanno.hpengine.graphics.shader.ProgramManager
import de.hanno.hpengine.graphics.state.PrimaryCameraStateHolder
import de.hanno.hpengine.graphics.state.RenderState
import de.hanno.hpengine.graphics.texture.TextureManagerBaseSystem
import de.hanno.hpengine.graphics.window.Window
import de.hanno.hpengine.model.BoundingVolumeComponent
import de.hanno.hpengine.model.ModelComponent
import de.hanno.hpengine.model.ModelSystem
import de.hanno.hpengine.scene.AddResourceContext
import de.hanno.hpengine.transform.AABB
import de.hanno.hpengine.transform.EntityMovementSystem
import imgui.ImGui
import imgui.flag.ImGuiConfigFlags
import imgui.flag.ImGuiDir
import imgui.flag.ImGuiStyleVar
import imgui.flag.ImGuiWindowFlags.*
import imgui.gl3.ImGuiImplGl3
import org.koin.core.annotation.Single
import org.lwjgl.glfw.GLFW
interface ImGuiEditorExtension {
fun render(imGuiEditor: ImGuiEditor)
}
enum class SelectionMode { Entity, Mesh; }
data class EditorConfig(var selectionMode: SelectionMode = SelectionMode.Entity)
@Single(binds = [BaseSystem::class, BaseEntitySystem::class, RenderSystem::class])
@All(EditorCameraInputComponent::class)
class ImGuiEditor(
private val graphicsApi: GraphicsApi,
internal val window: Window,
internal val textureManager: TextureManagerBaseSystem,
internal val config: Config,
internal val addResourceContext: AddResourceContext,
internal val fpsCounter: FPSCounter,
internal val editorExtensions: List<ImGuiEditorExtension>,
internal val entityClickListener: EntityClickListener,
internal val primaryCameraStateHolder: PrimaryCameraStateHolder,
internal val gpuProfiler: GPUProfiler,
internal val renderSystemsConfig: Lazy<RenderSystemsConfig>,
internal val renderManager: Lazy<RenderManager>,
internal val programManager: ProgramManager,
internal val input: EditorInput,
internal val primaryRendererSelection: PrimaryRendererSelection,
internal val outputSelection: OutputSelection,
internal val entityMovementSystem: EntityMovementSystem,
_editorExtensions: List<EditorExtension>,
) : BaseEntitySystem(), PrimaryRenderer {
override val renderPriority: Int get() = 100
private val glslVersion = "#version 450" // TODO: Derive from configured version, wikipedia OpenGl_Shading_Language
override val supportsSingleStep: Boolean get() = false
internal val extensions: List<EditorExtension> = _editorExtensions.distinct()
private var editorConfig = EditorConfig()
internal val layout = PanelLayout()
private val gizmoSystem = GizmoSystem(input)
val renderTarget = RenderTarget2D(
graphicsApi,
RenderTargetImpl(
graphicsApi,
OpenGLFrameBuffer(graphicsApi, null),
1920,
1080,
listOf(
ColorAttachmentDefinition("Color", RGB8, TextureFilterConfig(MinFilter.LINEAR))
).toTextures(graphicsApi, config.width, config.height),
"Final Editor Image",
)
)
override val finalOutput: FinalOutput = FinalOutputImpl(renderTarget.textures.first(), 0, this)
var selection: Selection? = null
set(value) {
field = if (field == value) null else value
}
lateinit var artemisWorld: World
init {
graphicsApi.onGpu {
ImGui.createContext()
ImGui.getIO().apply {
// addConfigFlags(ImGuiConfigFlags.ViewportsEnable)
addConfigFlags(ImGuiConfigFlags.DockingEnable)
}
}
}
private val imGuiImplGlfw = graphicsApi.onGpu {
ImGuiImplGlfwFrameBufferAware().apply {
init(window.handle, true)
}
}
private val imGuiImplGl3 = graphicsApi.onGpu {
ImGuiImplGl3().apply {
init(glslVersion)
}
}
override fun processSystem() {}
override fun render(renderState: RenderState) {
primaryRendererSelection.primaryRenderer.render(renderState)
layout.update(ImGui.getIO().displaySizeX, ImGui.getIO().displaySizeY)
entityClickListener.consumeClick { entityClicked -> handleClick(entityClicked) }
graphicsApi.polygonMode(Facing.FrontAndBack, RenderingMode.Fill)
outputSelection.draw()
renderTarget.use(true)
imGuiImplGlfw.newFrame(renderTarget.width, renderTarget.height)
try {
ImGui.newFrame()
background(layout.windowWidth, layout.windowHeight)
if (renderPanels) {
menu(layout.windowWidth, layout.windowHeight)
rightPanel(editorConfig, renderManager.value, extensions)
if (::artemisWorld.isInitialized) {
leftPanel(layout.leftPanelYOffset, layout.leftPanelWidth, layout.windowHeight)
}
midPanel(renderState)
bottomPanel()
}
renderEditorExtensions()
// ImGui.showDemoWindow(ImBoolean(true))
} catch (it: Exception) {
it.printStackTrace()
} finally {
try {
ImGui.render()
imGuiImplGl3.renderDrawData(ImGui.getDrawData())
if (ImGui.getIO().hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) {
val backupWindowHandle = GLFW.glfwGetCurrentContext()
ImGui.updatePlatformWindows()
ImGui.renderPlatformWindowsDefault()
GLFW.glfwMakeContextCurrent(backupWindowHandle)
}
} catch (it: Exception) {
it.printStackTrace()
}
}
}
private fun renderEditorExtensions() {
editorExtensions.forEach {
try {
it.render(this)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
private fun handleClick(entityClicked: EntityClicked) {
if (layout.contains(entityClicked)) {
val entityId = entityClicked.indices.entityId
val meshIndex = entityClicked.indices.meshIndex
val componentManager = artemisWorld.getSystem(ComponentManager::class.java)!!
val components = componentManager.getComponentsFor(entityId, Bag())
selection = when (editorConfig.selectionMode) {
SelectionMode.Mesh -> {
val modelComponent = components.filterIsInstance<ModelComponent>().first()
val model =
artemisWorld.getSystem(ModelSystem::class.java)!![modelComponent.modelComponentDescription]!!
MeshSelection(entityId, model.meshes[meshIndex], modelComponent, components)
}
else -> SimpleEntitySelection(entityId, components)
}
}
}
private fun bottomPanel() {
(selection as? EntitySelection)?.let {
ImGui.setNextWindowPos(layout.bottomPanelPositionX, layout.bottomPanelPositionY)
ImGui.setNextWindowSize(layout.bottomPanelWidth, layout.bottomPanelHeight)
ImGui.getStyle().windowMenuButtonPosition = ImGuiDir.None
ImGui.setNextWindowBgAlpha(1.0f)
de.hanno.hpengine.graphics.imgui.dsl.ImGui.run {
window(
"Bottom panel", NoCollapse or
NoResize or
NoTitleBar or
HorizontalScrollbar
) {
gizmoSystem.renderTransformationConfig()
}
}
}
}
private val renderPanels get() = !input.prioritizeGameInput
private fun background(screenWidth: Float, screenHeight: Float) {
val windowFlags =
NoBringToFrontOnFocus or // we just want to use this window as a host for the menubar and docking
NoNavFocus or // so turn off everything that would make it act like a window
// NoDocking or
NoTitleBar or
NoResize or
NoMove or
NoCollapse or
NoBackground
de.hanno.hpengine.graphics.imgui.dsl.ImGui.run {
ImGui.pushStyleVar(ImGuiStyleVar.WindowPadding, 0f, 0f)
window("Main", windowFlags) {
ImGui.popStyleVar()
ImGui.image(
outputSelection.textureOrNull ?: primaryRendererSelection.primaryRenderer.finalOutput.texture2D.id,
screenWidth,
screenHeight,
0f,
1f,
1f,
0f,
)
input.swallowInput = !ImGui.isItemHovered()
}
}
}
private fun ImGuiEditor.midPanel(renderState: RenderState) {
(selection as? EntitySelection)?.let { entitySelection ->
val entity = artemisWorld.getEntity(entitySelection.entity)
entity.getComponent(TransformComponent::class.java)
?.let { transformComponent ->
val camera = renderState[primaryCameraStateHolder.camera]
val entityMoved = gizmoSystem.showGizmo(
viewMatrixBuffer = camera.viewMatrixBuffer,
projectionMatrixBuffer = camera.projectionMatrixBuffer,
panelLayout = layout,
transform = transformComponent.transform,
entity.getComponent(BoundingVolumeComponent::class.java)?.boundingVolume ?: dummyAABB
)
if(entityMoved) {
entityMovementSystem.setEntityHasMovedInCycle(entitySelection.entity, -1)
}
}
}
}
}
private val dummyAABB = AABB()
private fun PanelLayout.contains(entityClicked: EntityClicked): Boolean {
return entityClicked.coordinates.x > leftPanelWidth &&
entityClicked.coordinates.x < (leftPanelWidth + midPanelWidth) &&
entityClicked.coordinates.y > 0 &&
windowHeight - entityClicked.coordinates.y < bottomPanelPositionY
}
| 0 | Kotlin | 0 | 0 | d0ecc78d2d90033758d480b2383d8d5c3d2febd3 | 11,630 | hpengine | MIT License |
app/src/main/kotlin/vitalii/pankiv/dev/android/basedata/storage/Memory.kt | pankivV | 679,640,982 | false | null | package vitalii.pankiv.dev.android.basedata.storage
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
abstract class HashMapMemory : MutableMap<String, Any?> by ConcurrentHashMap()
class SessionMemory @Inject constructor() : HashMapMemory()
class AppMemory @Inject constructor() : HashMapMemory() | 0 | Kotlin | 0 | 0 | 3dbb32a879647a315e461f4c34b618f5df670a07 | 323 | code-sample | Apache License 2.0 |
block/src/main/java/com/rarible/ethereum/block/domain.kt | rarible | 358,506,329 | false | null | package com.rarible.ethereum.block
import io.daonomic.rpc.domain.Bytes
data class BlockEvent<B : Block>(
val block: B,
val reverted: BlockInfo? = null
)
data class BlockInfo(
val hash: Bytes,
val number: Long
) | 0 | Kotlin | 5 | 6 | f71615888db1a092867baef0fbf95292e50a1672 | 229 | ethereum-core | MIT License |
app/src/main/java/com/teamnoyes/majorparksinseoul/network/ParkApiService.kt | kjh9589 | 373,385,554 | false | null | package com.teamnoyes.majorparksinseoul.network
import com.teamnoyes.majorparksinseoul.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ParkApiService {
private const val baseUrl = "http://openAPI.seoul.go.kr:8088/"
val retrofit: Service = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(buildOkHttpClient())
.build()
.create(Service::class.java)
private fun buildOkHttpClient(): OkHttpClient =
OkHttpClient.Builder()
.addInterceptor(
HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) {
HttpLoggingInterceptor.Level.BODY
}else {
HttpLoggingInterceptor.Level.NONE
}
}
).build()
} | 0 | Kotlin | 0 | 0 | 0c12c5b787730eb36263afcc3de0ab7163c8692a | 992 | Android-Major-Parks-In-Seoul | Apache License 2.0 |
conventions/src/main/kotlin/wing/Colors.kt | 5hmlA | 799,497,673 | false | {"Kotlin": 60903} | package wing//以下是20种常见的颜色以及它们的 ANSI 转义码:
//
//黑色(Black):[30m
//红色(Red):[31m
//绿色(Green):[32m
//黄色(Yellow):[33m
//蓝色(Blue):[34m
//洋红色(Magenta):[35m
//青色(Cyan):[36m
//白色(White):[37m
//亮黑色(Bright Black):[90m
//亮红色(Bright Red):[91m
//亮绿色(Bright Green):[92m
//亮黄色(Bright Yellow):[93m
//亮蓝色(Bright Blue):[94m
//亮洋红色(Bright Magenta):[95m
//亮青色(Bright Cyan):[96m
//亮白色(Bright White):[97m
//橙色(Orange):[38;5;208m
//粉红色(Pink):[38;5;206m
//棕色(Brown):[38;5;130m
//灰色(Gray):[38;5;240m
val String.red: String
get() = "\u001B[91m${this}\u001B[0m"
val String.lightRed: String
get() = "\u001B[31m${this}\u001B[0m"
val String.green: String
get() = "\u001B[92m${this}\u001B[0m"
val String.yellow: String
get() = "\u001B[93m${this}\u001B[0m"
val String.gray: String
get() = "\u001B[90m${this}\u001B[0m"
val String.blue: String
get() = "\u001B[94m${this}\u001B[0m"
val String.purple: String
get() = "\u001B[95m${this}\u001B[0m" | 0 | Kotlin | 0 | 0 | ba126e3d129b29db83fe5620470f8bb7c952759f | 936 | conventions | Apache License 2.0 |
src/main/kotlin/net/ree_jp/simplebuilder/event/EventListener.kt | Ree-jp-minecraft | 269,153,984 | false | {"Kotlin": 11808} | /*
* RRRRRR jjj
* RR RR eee eee pp pp
* RRRRRR ee e ee e _____ jjj ppp pp
* RR RR eeeee eeeee jjj pppppp
* RR RR eeeee eeeee jjj pp
* jjjj pp
*
* Copyright (c) 2020. Ree-jp. All Rights Reserved.
*/
package net.ree_jp.simplebuilder.event
import cn.nukkit.Player
import cn.nukkit.Server
import cn.nukkit.block.Block
import cn.nukkit.block.BlockAir
import cn.nukkit.event.EventHandler
import cn.nukkit.event.EventPriority
import cn.nukkit.event.Listener
import cn.nukkit.event.block.BlockPlaceEvent
import cn.nukkit.event.player.PlayerInteractEvent
import cn.nukkit.item.Item
import cn.nukkit.level.Position
import cn.nukkit.level.particle.DustParticle
import cn.nukkit.math.BlockFace
import cn.nukkit.math.BlockVector3
import cn.nukkit.scheduler.TaskHandler
import cn.nukkit.utils.BlockColor
import net.ree_jp.simplebuilder.SimpleBuilderPlugin
import net.ree_jp.simplebuilder.api.SimpleBuilderAPI
class EventListener : Listener {
private val cool = mutableMapOf<String, TaskHandler>()
@EventHandler(priority = EventPriority.MONITOR)
fun onPlace(ev: BlockPlaceEvent) {
val p = ev.player
val n = p.name
val item = ev.item
val bl = ev.block
if (ev.isCancelled || cool.contains(n)) return
val space = getBuildSpace(p, bl) ?: return
if (item.count <= space.size) return
val iterator = space.iterator()
var against: Block = ev.blockAgainst
val handler = Server.getInstance().scheduler.scheduleRepeatingTask(
SimpleBuilderPlugin.instance,
{
if (iterator.hasNext() && (against.id != Block.AIR)) {
val pos = iterator.next()
against = placeBlock(p, item, pos, against) ?: Block.get(Block.AIR)
} else {
cool[n]?.cancel()
cool.remove(n)
}
},
3
)
cool[n] = handler
}
@EventHandler
fun onTap(ev: PlayerInteractEvent) {
val p = ev.player
val bl = p.inventory.itemInHand.block
val view = ev.block.getSide(ev.face)
bl.setVec(view)
val space = getBuildSpace(p, bl) ?: return
for (pos in space) {
sendBlockParticle(p, pos, bl.color)
}
}
private fun getBuildSpace(p: Player, bl: Block): List<BlockVector3>? {
val api = SimpleBuilderAPI.getInstance()
val level = p.level
val pos = bl.asBlockVector3()
if (!p.hasPermission("simplebuilder.build") || (bl is BlockAir) || !api.isBuilder(p)) return null
val list = mutableListOf<BlockVector3>()
(1..100).forEach { index ->
val checkPos = nextPos(pos, index, p.direction)
val checkBl = level.getBlock(checkPos.asVector3())
if (!p.hasPermission("simplebuilder.build.$index")) return null
if (!isCanPlace(checkBl, bl)) {
if ((checkBl.fullId != bl.fullId) || list.isEmpty()) return null
return list
}
list.add(checkPos)
}
throw Exception("limit is 100")
}
private fun sendBlockParticle(p: Player, pos: BlockVector3, color: BlockColor) {
val vec = pos.asVector3()
(0..1).forEach { x ->
(0..1).forEach { y ->
(0..1).forEach { z ->
p.level.addParticle(DustParticle(vec.add(x.toDouble(), y.toDouble(), z.toDouble()), color), p)
}
}
}
}
private fun placeBlock(p: Player, item: Item, pos: BlockVector3, tapBl: Block): Block? {
if (!item.canBePlaced()) return null
val level = p.level
val bl = item.block
val beforeBl = level.getBlock(pos.asVector3())
bl.position(Position.fromObject(pos.asVector3(), level))
if (!isCanPlace(beforeBl, bl)) {
return null
}
val ev = BlockPlaceEvent(p, bl, beforeBl, tapBl, item)
Server.getInstance().pluginManager.callEvent(ev)
if (ev.isCancelled || !reduceHandItem(p)) return null
level.setBlock(bl, bl)
return bl
}
private fun nextPos(pos: BlockVector3, int: Int, face: BlockFace): BlockVector3 {
return when (face) {
BlockFace.NORTH -> pos.north(int)
BlockFace.SOUTH -> pos.south(int)
BlockFace.EAST -> pos.east(int)
BlockFace.WEST -> pos.west(int)
else -> throw Exception("direction bad value")
}
}
private fun isCanPlace(before: Block, after: Block): Boolean {
return before.canBeReplaced() || ((after.id == Item.SLAB) && (before.id == Item.SLAB))
}
private fun reduceHandItem(p: Player): Boolean {
val hand = p.inventory.itemInHand
if (hand.id == Item.AIR) return false
hand.setCount(hand.count - 1)
return p.inventory.setItemInHand(hand)
}
private fun Block.setVec(bl: Block) {
x = bl.x
y = bl.y
z = bl.z
}
}
| 0 | Kotlin | 0 | 0 | a7abeb819c4c2af1301fa845576124c61c78b67d | 5,150 | SimpleBuilder | MIT License |
src/com/hzh/kotlin/L04/ClassTest.kt | shihuihzh | 135,589,087 | false | {"Kotlin": 18476, "Java": 205} | package com.hzh.kotlin.L04
// data class
data class Persion(var name: String, var age: Int) {
val sex: String = "man"
operator fun component3(): String {
return this.sex;
}
}
// sealed class
sealed abstract class Shape { // just can inheritance in this file
abstract fun print()
}
class Rect : Shape() {
override fun print() {
println("Rect...")
}
}
class Trans : Shape() {
override fun print() {
println("Trans...")
}
}
fun printShape(shape: Shape) = when(shape) {
is Rect -> shape.print()
is Trans -> shape.print()
// no need else becase all subclass here
}
// nested class and inner class
class Outer {
class nested
inner class inner()
}
// enum
enum class Color(val c: Int) {
RED(0xff0000),
GREEN(0x00ff00),
BLUE(0x0000ff)
}
// just a object
object MyObject {
val value = 1;
}
fun main(args: Array<String>) {
// data class
val p = Persion("Zhanhao", 27)
p.age = p.age - 1
println(p) // auto toString
var p2 = p.copy(name = "Zhanhao2")
println(p2)
// Destructuring
val (name, age, sex) = p2
println("$name, $age, $sex")
println()
// sealed class
printShape(Rect())
println()
// inner and nested
Outer.nested() // not need outer to instance
Outer().inner() // need outer to Instance
Thread(object: Runnable { // use object to create a annoymous class
override fun run() {
println("run!!!")
}
}).start()
println()
// enmu
val c = Color.valueOf("RED")
println(c.c)
// object
println(MyObject.value) // is a object already
val innerObj = object {
val value = 100
}
println(innerObj.value)
println()
}
| 0 | Kotlin | 0 | 0 | e585386e6f7fd5f403d3b0eed6a311af37c76573 | 1,783 | Kotlin-learning | MIT License |
shared/compose/src/main/kotlin/team/applemango/runnerbe/shared/compose/component/ToggleTabBar.kt | ricky-buzzni | 485,390,072 | false | {"Kotlin": 615137} | /*
* RunnerBe © 2022 Team AppleMango. all rights reserved.
* RunnerBe license is under the MIT.
*
* [ToggleTopBar.kt] created by <NAME> on 22. 2. 23. 오후 10:33
*
* Please see: https://github.com/applemango-runnerbe/RunnerBe-Android/blob/main/LICENSE.
*/
package team.applemango.runnerbe.shared.compose.component
import androidx.annotation.Size
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import team.applemango.runnerbe.domain.runningitem.common.RunningItemType
import team.applemango.runnerbe.shared.compose.default.RunnerbeToggleTabBarDefaults
import team.applemango.runnerbe.shared.compose.extension.noRippleClickable
import team.applemango.runnerbe.shared.compose.theme.ColorAsset
import team.applemango.runnerbe.shared.compose.theme.Typography
import team.applemango.runnerbe.shared.compose.theme.animatedColorState
private const val DefaultToggleTopBarRadius = 34
private const val DefaultToggleTopBarHeight = 36
@Immutable
data class ToggleTopBarItem<T>(
val id: T,
val text: String,
)
@Immutable
data class ToggleTopBarColors(
val baseBackground: Color = ColorAsset.Primary,
val activateBackground: Color = ColorAsset.PrimaryDarker,
val inactivateBackground: Color = baseBackground,
val activateText: Color = Color.DarkGray,
val inactivateText: Color = Color.LightGray,
)
@Composable
fun <T> ToggleTabBar(
modifier: Modifier = Modifier,
colors: ToggleTopBarColors = ToggleTopBarColors(),
activateTextStyle: TextStyle = LocalTextStyle.current,
inactivateTextStyle: TextStyle = LocalTextStyle.current,
height: Dp = DefaultToggleTopBarHeight.dp,
radius: Dp = DefaultToggleTopBarRadius.dp,
@Size(min = 1) toggleTopBarItems: List<ToggleTopBarItem<T>>,
selectedItemState: T,
onTabClick: (itemId: T) -> Unit,
) {
require(toggleTopBarItems.isNotEmpty()) {
"topBarItems size must be not zero."
}
@Stable
@Composable
fun selectedTextStyle(itemId: T) = when (selectedItemState == itemId) {
true -> activateTextStyle
else -> inactivateTextStyle
}
Row(
modifier = modifier
.fillMaxWidth()
.height(height)
.clip(RoundedCornerShape(radius))
.background(color = colors.baseBackground),
verticalAlignment = Alignment.CenterVertically
) {
toggleTopBarItems.forEach { item ->
Box(
modifier = Modifier
.padding(2.dp)
.weight(1f)
.fillMaxSize()
.clip(RoundedCornerShape(radius))
.background(
color = animatedColorState(
target = item.id,
selectState = selectedItemState,
defaultColor = colors.inactivateBackground,
selectedColor = colors.activateBackground
)
)
.noRippleClickable {
onTabClick(item.id)
},
contentAlignment = Alignment.Center
) {
Text(
text = item.text,
style = selectedTextStyle(item.id).copy(
color = animatedColorState(
target = item.id,
selectState = selectedItemState,
defaultColor = colors.inactivateText,
selectedColor = colors.activateText
)
)
)
}
}
}
}
@Composable
fun RunningItemTypeToggleBar(
modifier: Modifier = Modifier,
selectedItemState: RunningItemType,
onTabClick: (type: RunningItemType) -> Unit,
) {
ToggleTabBar(
modifier = modifier,
colors = RunnerbeToggleTabBarDefaults.colors(),
activateTextStyle = Typography.Body14M,
inactivateTextStyle = Typography.Body14R,
toggleTopBarItems = RunnerbeToggleTabBarDefaults.items(),
selectedItemState = selectedItemState,
onTabClick = { runningItemType ->
onTabClick(runningItemType)
}
)
}
| 0 | null | 0 | 0 | f48fb298c07732a9c32afcff0bddb16f9fe2e37a | 5,067 | RunnerBe-Android | MIT License |
idea/testData/codeInsight/moveUpDown/classBodyDeclarations/function/functionAtBrace6.kt | develar | 4,304,550 | true | {"Java": 10888937, "Kotlin": 2416878, "JavaScript": 1540292, "CSS": 109687, "Shell": 15888, "Groovy": 2174} | // MOVE: up
fun foo() {
class B {
<caret>fun foo() {
}
}
} | 0 | Java | 1 | 1 | bf5b387580265cba01efc8fd30d1d0c0b41ac5a9 | 83 | kotlin | Apache License 2.0 |
src/main/kotlin/algorithmic_toolbox/week2/LeastCommonMultiple.kt | eniltonangelim | 369,331,780 | false | null | package algorithmic_toolbox.week2
import java.util.*
fun getGCD(a: Long, b: Long): Long {
if (b == 0L)
return a
return getGCD(b, a % b)
}
fun lcmFast(a: Long, b: Long): Long {
return a * b / getGCD(a, b)
}
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val a = scanner.nextLong()
val b = scanner.nextLong()
println(lcmFast(a, b))
} | 0 | Kotlin | 0 | 0 | 031bccb323339bec05e8973af7832edc99426bc1 | 395 | AlgorithmicToolbox | MIT License |
wearApp/src/main/java/dev/johnoreilly/starwars/wearApp/StarWarsApplication.kt | joreilly | 357,294,402 | false | null | package dev.johnoreilly.starwars.wearApp
import android.app.Application
import dev.johnoreilly.starwars.wearApp.di.appModule
import dev.johnoreilly.starwars.shared.di.initKoin
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.logger.Level
class StarWarsApplication : Application() {
override fun onCreate() {
super.onCreate()
initKoin {
// workaround for https://github.com/InsertKoinIO/koin/issues/1188
androidLogger(if (BuildConfig.DEBUG) Level.ERROR else Level.NONE)
androidContext(this@StarWarsApplication)
modules(appModule)
}
}
} | 11 | null | 17 | 209 | 90d7c73bbddd27899d52e301d4520011353054b4 | 685 | StarWars | Apache License 2.0 |
src/main/kotlin/nbt/editor/NbtFileEditorProvider.kt | minecraft-dev | 42,327,118 | false | null | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.editor
import com.demonwav.mcdev.nbt.NbtVirtualFile
import com.demonwav.mcdev.nbt.filetype.NbtFileType
import com.demonwav.mcdev.nbt.lang.NbttFile
import com.demonwav.mcdev.util.invokeAndWait
import com.demonwav.mcdev.util.invokeLater
import com.intellij.ide.actions.SaveAllAction
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionResult
import com.intellij.openapi.actionSystem.ex.AnActionListener
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.command.UndoConfirmationPolicy
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorPolicy
import com.intellij.openapi.fileEditor.FileEditorState
import com.intellij.openapi.fileEditor.FileEditorStateLevel
import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider
import com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorProvider
import com.intellij.openapi.fileEditor.impl.text.TextEditorState
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.util.IncorrectOperationException
import java.awt.BorderLayout
import java.beans.PropertyChangeListener
import javax.swing.JPanel
import org.jetbrains.concurrency.runAsync
class NbtFileEditorProvider : PsiAwareTextEditorProvider(), DumbAware {
override fun getEditorTypeId() = EDITOR_TYPE_ID
override fun accept(project: Project, file: VirtualFile) = file.fileType == NbtFileType
override fun getPolicy() = FileEditorPolicy.NONE
override fun createEditor(project: Project, file: VirtualFile): FileEditor {
val fileEditor = NbtFileEditor(file) { nbtFile ->
invokeAndWait {
super.createEditor(project, nbtFile)
}
}
runAsync {
val nbtFile = NbtVirtualFile(file, project)
if (NonProjectFileWritingAccessProvider.isWriteAccessAllowed(file, project)) {
NonProjectFileWritingAccessProvider.allowWriting(listOf(nbtFile))
}
fileEditor.ready(nbtFile, project)
}
return fileEditor
}
companion object {
private const val EDITOR_TYPE_ID = "nbt_editor"
}
}
private class NbtFileEditor(
private val file: VirtualFile,
private val editorProvider: (NbtVirtualFile) -> FileEditor
) : FileEditor {
private var editor: FileEditor? = null
private val component = JPanel(BorderLayout())
init {
val loading = JBLoadingPanel(null, this)
loading.setLoadingText("Parsing NBT file")
loading.startLoading()
component.add(loading, BorderLayout.CENTER)
}
fun ready(nbtFile: NbtVirtualFile, project: Project) {
if (project.isDisposed) {
return
}
component.removeAll()
val toolbar = NbtToolbar(nbtFile)
nbtFile.toolbar = toolbar
editor = invokeAndWait {
editorProvider(nbtFile)
}
editor?.let { editor ->
try {
Disposer.register(this, editor)
} catch (e: IncorrectOperationException) {
// The editor can be disposed really quickly when opening a large number of NBT files
// Since everything happens basically at the same time, calling Disposer.isDisposed right before
// returns false but #dispose throws this IOE...
Disposer.dispose(this)
return@let
}
invokeLater {
component.add(toolbar.panel, BorderLayout.NORTH)
component.add(editor.component, BorderLayout.CENTER)
}
}
// This can be null if the file is too big to be parsed as a psi file
val psiFile = runReadAction {
PsiManager.getInstance(project).findFile(nbtFile) as? NbttFile
} ?: return
WriteCommandAction.writeCommandAction(psiFile)
.shouldRecordActionForActiveDocument(false)
.withUndoConfirmationPolicy(UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION)
.run<Throwable> {
CodeStyleManager.getInstance(project).reformat(psiFile, true)
}
project.messageBus.connect(this).subscribe(
AnActionListener.TOPIC,
object : AnActionListener {
override fun afterActionPerformed(action: AnAction, event: AnActionEvent, result: AnActionResult) {
if (action !is SaveAllAction) {
return
}
val selectedEditor = FileEditorManager.getInstance(project).selectedEditor ?: return
if (selectedEditor !is NbtFileEditor || selectedEditor.editor != editor) {
return
}
nbtFile.writeFile(this)
}
}
)
}
override fun isModified() = editor.exec { isModified } ?: false
override fun addPropertyChangeListener(listener: PropertyChangeListener) {
editor.exec { addPropertyChangeListener(listener) }
}
override fun getName() = editor.exec { name } ?: ""
override fun setState(state: FileEditorState) {
editor.exec { setState(state) }
}
override fun getState(level: FileEditorStateLevel): FileEditorState = editor.exec { getState(level) }
?: TextEditorState()
override fun getFile(): VirtualFile = editor.exec { file } ?: file
override fun getComponent() = component
override fun getPreferredFocusedComponent() = editor.exec { preferredFocusedComponent }
override fun <T : Any?> getUserData(key: Key<T>) = editor.exec { getUserData(key) }
override fun selectNotify() {
editor.exec { selectNotify() }
}
override fun <T : Any?> putUserData(key: Key<T>, value: T?) {
editor.exec { putUserData(key, value) }
}
override fun getCurrentLocation() = editor.exec { currentLocation }
override fun deselectNotify() {
editor.exec { deselectNotify() }
}
override fun getBackgroundHighlighter() = editor.exec { backgroundHighlighter }
override fun isValid() = editor.exec { isValid } ?: true
override fun removePropertyChangeListener(listener: PropertyChangeListener) {
editor.exec { removePropertyChangeListener(listener) }
}
override fun dispose() {}
override fun getStructureViewBuilder() = editor.exec { structureViewBuilder }
override fun equals(other: Any?) = other is NbtFileEditor && other.component == this.component
override fun hashCode() = editor.hashCode()
override fun toString() = editor.toString()
private inline fun <T : Any?> FileEditor?.exec(action: FileEditor.() -> T): T? {
if (editor?.let { ed -> Disposer.isDisposed(ed) } == true) {
return null
}
return this?.action()
}
}
| 204 | null | 152 | 1,154 | 36cc3d47f7f39c847c0ebdcbf84980bc7262dab7 | 7,499 | MinecraftDev | MIT License |
src/main/kotlin/me/glaremasters/guilds/api/events/GuildKickEvent.kt | guilds-plugin | 93,349,217 | false | {"Java": 471828, "Kotlin": 391607} | /*
* MIT License
*
* Copyright (c) 2023 Glare
*
* 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 me.glaremasters.guilds.api.events
import me.glaremasters.guilds.api.events.base.GuildEvent
import me.glaremasters.guilds.guild.Guild
import org.bukkit.OfflinePlayer
import org.bukkit.entity.Player
/**
* Class representing an event that occurs when a player is kicked from a guild.
*
* @property player the player who performed the kick
* @property guild the guild the player was kicked from
* @property kicked the player who was kicked
* @property cause the reason for the player being kicked
*
* @constructor Creates a new [GuildKickEvent].
*/
class GuildKickEvent(player: Player, guild: Guild, val kicked: OfflinePlayer, val cause: Cause) : GuildEvent(player, guild) {
/**
* Enumeration class representing the possible reasons a player may be kicked from a guild.
*/
enum class Cause {
/** The player was kicked by another player. */
PLAYER_KICKED,
/** The player was kicked by an administrator. */
ADMIN_KICKED
}
}
| 62 | Java | 58 | 164 | 9e287d586aff41c488e380efc8ee92e10d46e490 | 2,120 | Guilds | MIT License |
MLKit-Sample/module-vision/src/main/java/com/huawei/mlkit/sample/activity/StartActivity.kt | FStranieri | 430,136,682 | true | {"Java": 1963963, "Kotlin": 480051, "GLSL": 1042, "Batchfile": 56} | /**
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.huawei.mlkit.sample.activity
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.*
import android.widget.AdapterView
import android.widget.GridView
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.huawei.agconnect.config.AGConnectServicesConfig
import com.huawei.hms.mlplugin.productvisionsearch.MLProductVisionSearchCapture
import com.huawei.hms.mlplugin.productvisionsearch.MLProductVisionSearchCaptureConfig
import com.huawei.hms.mlplugin.productvisionsearch.MLProductVisionSearchCaptureFactory
import com.huawei.hms.mlsdk.common.MLApplication
import com.huawei.hms.mlsdk.productvisionsearch.MLProductVisionSearch
import com.huawei.mlkit.sample.R
import com.huawei.mlkit.sample.activity.Imagesupersesolution.ImageSuperResolutionStartActivity
import com.huawei.mlkit.sample.activity.`object`.ObjectDetectionActivity
import com.huawei.mlkit.sample.activity.adapter.GridViewAdapter
import com.huawei.mlkit.sample.activity.documentskew.DocumentSkewStartActivity
import com.huawei.mlkit.sample.activity.entity.GridViewItem
import com.huawei.mlkit.sample.activity.fragment.ProductFragment
import com.huawei.mlkit.sample.activity.imageclassfication.ImageClassificationActivity
import com.huawei.mlkit.sample.activity.imageseg.ImageSegmentationActivity
import com.huawei.mlkit.sample.activity.scenedection.SceneStartActivity
import com.huawei.mlkit.sample.activity.table.TableRecognitionStartActivity
import com.huawei.mlkit.sample.util.Constant
import com.huawei.mlkit.sample.views.overlay.GraphicOverlay
import java.util.*
class StartActivity : BaseActivity(), ActivityCompat.OnRequestPermissionsResultCallback,
View.OnClickListener {
private lateinit var mGridView: GridView
private var mDataList: ArrayList<GridViewItem>? = null
private var graphicOverlay: GraphicOverlay? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStatusBarColor(this, R.color.logo_background)
this.setContentView(R.layout.activity_start)
findViewById<View>(R.id.setting_img).setOnClickListener(this)
graphicOverlay = findViewById(R.id.fireFaceOverlay)
initData()
mGridView = findViewById(R.id.gridview)
val mAdapter = GridViewAdapter(mDataList, applicationContext)
mGridView.adapter = mAdapter
initClickEvent()
// Set the ApiKey of the application for accessing cloud services.
setApiKey()
if (!allPermissionsGranted()) {
runtimePermissions
}
}
/**
* Read the ApiKey field in the sample-agconnect-services.json to obtain the API key of the application and set it.
* For details about how to apply for the sample-agconnect-services.json, see section https://developer.huawei.com/consumer/cn/doc/development/HMS-Guides/ml-add-agc.
*/
private fun setApiKey() {
val config = AGConnectServicesConfig.fromContext(application)
MLApplication.getInstance().apiKey = config.getString(API_KEY)
}
private fun initClickEvent() {
mGridView.onItemClickListener =
AdapterView.OnItemClickListener { parent, view, position, id ->
when (position) {
0 -> //Table Recognition
startActivity(
Intent(
this@StartActivity,
TableRecognitionStartActivity::class.java
)
)
1 -> // Image Segmentation
startActivity(
Intent(
this@StartActivity,
ImageSegmentationActivity::class.java
)
)
2 -> // Object detection and tracking
startActivity(
Intent(this@StartActivity, ObjectDetectionActivity::class.java)
)
3 -> // Image classification
startActivity(
Intent(
this@StartActivity,
ImageClassificationActivity::class.java
)
)
4 -> {
// Landmark recognition
val intent = Intent(this@StartActivity, RemoteDetectionActivity::class.java)
intent.putExtra(Constant.MODEL_TYPE, Constant.CLOUD_LANDMARK_DETECTION)
startActivity(intent)
}
5 -> {
// Image super resolution
val intentIsr = Intent(
this@StartActivity,
ImageSuperResolutionStartActivity::class.java
)
intentIsr.putExtra(
Constant.SUPER_RESOLUTION_TYPE,
Constant.TYPE_IMAGE_SUPER_RESOLUTION
)
startActivity(intentIsr)
}
6 -> {
// Text image super resolution
val intentTsr = Intent(
this@StartActivity,
ImageSuperResolutionStartActivity::class.java
)
intentTsr.putExtra(
Constant.SUPER_RESOLUTION_TYPE,
Constant.TYPE_TEXT_SUPER_RESOLUTION
)
startActivity(intentTsr)
}
7 -> //Scene
startActivity(Intent(this@StartActivity, SceneStartActivity::class.java))
8 -> {
// Product Visual Search
val config: MLProductVisionSearchCaptureConfig =
MLProductVisionSearchCaptureConfig.Factory()
.setLargestNumOfReturns(16)
.setProductFragment<MLProductVisionSearch>(ProductFragment())
.setRegion(MLProductVisionSearchCaptureConfig.REGION_DR_CHINA)
.create()
val capture: MLProductVisionSearchCapture =
MLProductVisionSearchCaptureFactory.getInstance().create(config)
capture.startCapture(this@StartActivity)
}
9 -> // Document Skew Corretion
startActivity(
Intent(
this@StartActivity,
DocumentSkewStartActivity::class.java
)
)
else -> {}
}
}
}
override fun onClick(view: View) {
if (view.id == R.id.setting_img) {
startActivity(Intent(this@StartActivity, SettingActivity::class.java))
}
}
private fun initData() {
mDataList = ArrayList()
var item: GridViewItem
for (i in ICONS.indices) {
item = GridViewItem(ICONS[i], TITLES[i])
mDataList!!.add(item)
}
}
private val requiredPermissions: Array<String?>
private get() = try {
val info = this.packageManager
.getPackageInfo(this.packageName, PackageManager.GET_PERMISSIONS)
val ps = info.requestedPermissions
if (ps != null && ps.size > 0) {
ps
} else {
arrayOfNulls(0)
}
} catch (e: RuntimeException) {
throw e
} catch (e: Exception) {
arrayOfNulls(0)
}
private fun allPermissionsGranted(): Boolean {
for (permission in requiredPermissions) {
if (!isPermissionGranted(this, permission)) {
return false
}
}
return true
}
private val runtimePermissions: Unit
private get() {
val allNeededPermissions: MutableList<String?> = ArrayList()
for (permission in requiredPermissions) {
if (!isPermissionGranted(this, permission)) {
allNeededPermissions.add(permission)
}
}
if (!allNeededPermissions.isEmpty()) {
ActivityCompat.requestPermissions(
this, allNeededPermissions.toTypedArray(), PERMISSION_REQUESTS
)
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode != PERMISSION_REQUESTS) {
return
}
var isNeedShowDiag = false
for (i in permissions.indices) {
if (permissions[i] == Manifest.permission.CAMERA && grantResults[i] != PackageManager.PERMISSION_GRANTED
|| permissions[i] == Manifest.permission.READ_EXTERNAL_STORAGE && grantResults[i] != PackageManager.PERMISSION_GRANTED
) {
// If the camera or storage permissions are not authorized, need to pop up an authorization prompt box.
isNeedShowDiag = true
}
}
if (isNeedShowDiag && !ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.CALL_PHONE
)
) {
val dialog = AlertDialog.Builder(this)
.setMessage(this.getString(R.string.camera_permission_rationale))
.setPositiveButton(this.getString(R.string.settings)) { dialog, which ->
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
// Open the corresponding setting interface according to the package name.
intent.data = Uri.parse("package:" + [email protected])
[email protected](intent, 200)
[email protected](intent)
}
.setNegativeButton(this.getString(R.string.cancel)) { dialog, which -> finish() }
.create()
dialog.show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 200) {
if (!allPermissionsGranted()) {
runtimePermissions
}
}
}
companion object {
private const val TAG = "StartActivity"
const val API_KEY = "client/api_key"
private const val PERMISSION_REQUESTS = 1
private val ICONS = intArrayOf(
R.drawable.icon_table,
R.drawable.icon_segmentation,
R.drawable.icon_object,
R.drawable.icon_classification,
R.drawable.icon_landmark,
R.drawable.icon_image_super_resolution,
R.drawable.icon_text_super_resolution,
R.drawable.icon_scene_detection,
R.drawable.icon_shopping,
R.drawable.icon_documentskew
)
private val TITLES = intArrayOf(
R.string.table,
R.string.image_segmentation,
R.string.object_detection,
R.string.image_classification,
R.string.landmark,
R.string.image_super_resolution_s,
R.string.text_super_resolution_s,
R.string.scene_detection,
R.string.photographed_shopping,
R.string.document_skew
)
private fun isPermissionGranted(context: Context, permission: String?): Boolean {
if (ContextCompat.checkSelfPermission(context, permission!!)
== PackageManager.PERMISSION_GRANTED
) {
Log.i(TAG, "Permission granted: $permission")
return true
}
Log.i(TAG, "Permission NOT granted: $permission")
return false
}
}
} | 1 | Java | 1 | 1 | c7cd308b6c25d3b981b4fc91436f32adb4c98649 | 13,443 | hms-ml-demo | Apache License 2.0 |
app/src/main/java/co/tami/basketball/team/data/PlayerAttributesData.kt | Hydratant | 747,542,242 | false | {"Kotlin": 39818} | package co.tami.basketball.team.data
data class PlayerAttributesData(
val outsideScoringData: OutsideScoringData,
val insideScoringData: InsideScoringData,
val athleticismData: AthleticismData,
val playMakingData: PlayMakingData,
val defendingData: DefendingData,
val reboundingData: ReboundingData
)
data class OutsideScoringData(
val closeShot: Int,
val midRangeShot: Int,
val threePointShot: Int,
val freeThrow: Int,
val shotIQ: Int,
val offensiveConsistency: Int
)
data class InsideScoringData(
val layup: Int,
val postHook: Int,
val postFad: Int,
val postControl: Int,
val drawFoul: Int,
val hands: Int
)
data class AthleticismData(
val speed: Int,
val acceleration: Int,
val strength: Int,
val stamina: Int,
val hustle: Int,
val overallDurability: Int
)
data class PlayMakingData(
val passAccuracy: Int,
val ballHandle: Int,
val speedWithBall: Int,
val passIQ: Int,
val passVision: Int
)
data class DefendingData(
val interiorDefense: Int,
val perimeterDefense: Int,
val steal: Int,
val block: Int,
val lateralQuickness: Int,
val helpDefenseIQ: Int,
val passPerception: Int,
val defensiveConsistency: Int
)
data class ReboundingData(
val offensiveRebound: Int,
val defensiveRebound: Int
) | 2 | Kotlin | 0 | 0 | d977ec05a5e351d0365ccb3cabb89cc35a8eeb8a | 1,357 | team | Apache License 2.0 |
app/src/main/java/com/example/airlines/presentation/passengers/list/PassengerListFragment.kt | gabrielmoreira-dev | 506,308,112 | false | null | package com.example.airlines.presentation.passengers.list
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.airlines.R
import com.example.airlines.databinding.FragmentPassengerListBinding
import com.example.airlines.presentation.common.BaseFragment
import com.example.airlines.presentation.common.State
import com.example.airlines.presentation.common.UIString
import com.example.airlines.presentation.passengers.list.adapters.PassengerAdapter
import com.example.airlines.presentation.passengers.list.models.PassengerPM
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class PassengerListFragment: BaseFragment<FragmentPassengerListBinding>(
FragmentPassengerListBinding::inflate
) {
private val viewModel by viewModels<PassengerListViewModel>()
private lateinit var passengerAdapter: PassengerAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
}
override fun onStart() {
super.onStart()
viewModel.state.observe(this) {
when (it) {
is State.Success -> {
handleSuccessState(it.model)
}
is State.Loading -> {
handleLoadingState()
}
is State.Error -> {
handleErrorState(it.message)
}
}
}
binding.errorView.setOnTryAgainListener {
viewModel.getPassengerList()
}
}
override fun onResume() {
super.onResume()
viewModel.getPassengerList()
}
private fun setupRecyclerView() {
passengerAdapter = PassengerAdapter()
binding.recyclerView.apply {
layoutManager = LinearLayoutManager(context)
adapter = passengerAdapter
}
}
private fun handleSuccessState(passengerList: List<PassengerPM>) {
passengerAdapter.setupItems(passengerList)
binding.apply {
loadingView.dismiss()
errorView.dismiss()
}
}
private fun handleLoadingState() {
binding.apply {
loadingView.show()
errorView.dismiss()
}
}
private fun handleErrorState(message: UIString) {
val description = context?.let {
message.asString(it)
} ?: getString(R.string.generic_error_message)
binding.apply {
errorView.setDescription(description)
errorView.show()
loadingView.dismiss()
}
}
} | 0 | Kotlin | 0 | 1 | 569e4669becae2676e38b3466b658fb50a6674e1 | 2,705 | airlines-android | MIT License |
linea/src/commonMain/kotlin/compose/icons/lineaicons/weather/WaxingCresent.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.lineaicons.weather
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
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 compose.icons.lineaicons.WeatherGroup
public val WeatherGroup.WaxingCresent: ImageVector
get() {
if (_waxingCresent != null) {
return _waxingCresent!!
}
_waxingCresent = Builder(name = "WaxingCresent", defaultWidth = 64.0.dp, defaultHeight =
64.0.dp, viewportWidth = 64.0f, viewportHeight = 64.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(32.0f, 32.0f)
moveToRelative(-31.0f, 0.0f)
arcToRelative(31.0f, 31.0f, 0.0f, true, true, 62.0f, 0.0f)
arcToRelative(31.0f, 31.0f, 0.0f, true, true, -62.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(23.0f, 2.0f)
curveToRelative(13.243f, 3.528f, 22.0f, 15.646f, 22.0f, 30.0f)
curveToRelative(0.0f, 14.355f, -8.756f, 26.473f, -22.0f, 30.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(30.0f, 59.0f)
lineTo(17.0f, 59.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(37.0f, 53.0f)
lineTo(9.0f, 53.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(42.0f, 47.0f)
lineTo(5.0f, 47.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(44.0f, 41.0f)
lineTo(2.0f, 41.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(45.0f, 35.0f)
lineTo(1.0f, 35.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(45.0f, 29.0f)
lineTo(1.0f, 29.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(44.0f, 23.0f)
lineTo(2.0f, 23.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(41.0f, 17.0f)
lineTo(5.0f, 17.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(37.0f, 11.0f)
lineTo(9.0f, 11.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(30.0f, 5.0f)
lineTo(17.0f, 5.0f)
}
}
.build()
return _waxingCresent!!
}
private var _waxingCresent: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 5,535 | compose-icons | MIT License |
app/src/main/java/ru/tinkoff/news/model/TinkoffApiResponse.kt | nikitosbobin | 185,379,960 | false | null | package ru.tinkoff.news.model
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class TinkoffApiResponse<T>(
@SerializedName("payload")
val payload: T
) : Serializable
| 0 | Kotlin | 0 | 0 | aff0d4858776d4363a44f5fbdc1fd1b51200cf52 | 211 | tinkoff-news | Apache License 2.0 |
components/src/commonMain/kotlin/me/lincolnstuart/funblocks/components/form/select/BasicSelect.kt | LincolnStuart | 645,064,211 | false | {"Kotlin": 451042} | package me.lincolnstuart.funblocks.essentials.form.select
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextOverflow
import compose.icons.TablerIcons
import compose.icons.tablericons.ChevronDown
import me.lincolnstuart.funblocks.essentials.core.helper.Counter
import me.lincolnstuart.funblocks.essentials.core.icon.Icon
import me.lincolnstuart.funblocks.essentials.core.icon.utils.IconOptions
import me.lincolnstuart.funblocks.essentials.core.icon.utils.IconSize
import me.lincolnstuart.funblocks.essentials.core.text.Text
import me.lincolnstuart.funblocks.essentials.core.text.utils.TextMode
import me.lincolnstuart.funblocks.essentials.core.text.utils.topic.TopicSize
import me.lincolnstuart.funblocks.essentials.form.select.utils.SelectOptions
import me.lincolnstuart.funblocks.essentials.form.utils.BasicInputSkeleton
import me.lincolnstuart.funblocks.foundation.ui.token.color.FunBlocksColors
import me.lincolnstuart.funblocks.foundation.ui.token.content.spacing.FunBlocksInset
import me.lincolnstuart.funblocks.foundation.ui.token.content.spacing.FunBlocksSpacing
/**
* Generic select responsible to draw an basic select component.
*
* @param options customized options.
* @param paddingValues it is recommended to use [FunBlocksSpacing] or [FunBlocksInset].
* @param onClick callback that executes when click is performed.
* @param contentOptions options that will be showed when the click is performed.
*/
@Composable
internal fun BasicSelect(
options: SelectOptions,
paddingValues: PaddingValues,
onClick: () -> Unit,
contentOptions: @Composable () -> Unit
) = with(options) {
BasicInputSkeleton(
content = {
Column {
SelectInput(
label = label,
value = selectedItem,
placeholder = placeholder,
expandOptionDescription = expandOptionDescription,
counter = counter
)
}
},
disabled = enabled.not() || readOnly,
error = error,
modifier = Modifier
.padding(paddingValues)
.clickable { onClick() }
)
contentOptions()
}
@Composable
private fun SelectInput(
label: String?,
value: String,
placeholder: String?,
expandOptionDescription: String?,
counter: Int?
) {
Row {
Column(modifier = Modifier.weight(1f)) {
label?.let {
Text(
text = label,
mode = TextMode.Topic(size = TopicSize.Small)
)
}
Box {
if (value.isEmpty()) {
Text(text = placeholder.orEmpty())
}
OneLineText(text = value)
}
}
if (counter != null && counter > 0) {
Counter(
formattedNumber = counter.toString(),
modifier = Modifier
.padding(horizontal = FunBlocksSpacing.xxxSmall)
.align(Alignment.CenterVertically),
backgroundColor = FunBlocksColors.Primary,
fontColor = FunBlocksColors.PrimaryContrast
)
}
SelectOption(
icon = TablerIcons.ChevronDown,
description = expandOptionDescription
)
}
}
@Composable
private fun RowScope.SelectOption(
icon: ImageVector,
description: String?
) {
Icon(
imageVector = icon,
options = IconOptions(
description = description,
size = IconSize.Tiny
),
modifier = Modifier
.align(Alignment.CenterVertically)
)
}
@Composable
private fun OneLineText(text: String) {
Text(
text = text,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
| 1 | Kotlin | 0 | 4 | 5a9d60f062132df12a6022530dfa10692fbf6c6d | 4,332 | fun-blocks | MIT License |
app/src/main/java/com/example/tmdbmovie/data/model/tvshows/TvShowDataDTO.kt | Mashnjogu | 662,502,908 | false | null | package com.example.tmdbmovie.data.model.tvshows
import com.google.gson.annotations.SerializedName
data class TvShowDataDTO(
@SerializedName("id")
val id: Int,
@SerializedName("name")
val name: String,
@SerializedName("overview")
val overview: String,
@SerializedName("original_language")
val original_language: String,
@SerializedName("poster_path")
val poster_path: String,
@SerializedName("first_air_date")
val first_air_date: String,
@SerializedName("genre_ids")
val genre_ids: List<Int>,
@SerializedName("vote_average")
val vote_average: Double,
@SerializedName("backdrop_path")
val backdrop_path: String,
)
| 0 | Kotlin | 0 | 0 | f47b9d550dfe453cb17c2c2c2d1f294c71565bc2 | 687 | TMDBMovie | Apache License 2.0 |
app/src/main/kotlin/io/github/xudaojie/gankioforkotlin/home/HomeFragment.kt | XuDaojie | 67,398,646 | false | null | package io.github.xudaojie.gankioforkotlin.home
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import io.github.xudaojie.gankioforkotlin.BaseFragment
import io.github.xudaojie.gankioforkotlin.R
import io.github.xudaojie.gankioforkotlin.adapter.HomeListAdapter
import io.github.xudaojie.gankioforkotlin.bean.GankData
import io.github.xudaojie.gankioforkotlin.data.Api
import io.github.xudaojie.gankioforkotlin.data.remote.GankIoService
import io.github.xudaojie.gankioforkotlin.widget.DividerItemDecoration
import kotlinx.android.synthetic.main.home_frag.view.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
/**
* Created by xdj on 16/9/6.
*/
class HomeFragment : BaseFragment() {
companion object {
fun newInstance(): HomeFragment {
return HomeFragment()
}
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
mRoot = inflater!!.inflate(R.layout.home_frag, container, false)
// 快速滑动时可能会出现item互相交错
// val adapter = SlideInBottomAnimationAdapter(ListAdapter(mActivity!!))
// val adapter = HomeListAdapter(mActivity!!)
val divider = DividerItemDecoration(mActivity, LinearLayoutManager.VERTICAL)
divider.divider = ContextCompat.getDrawable(mActivity, R.drawable.divider_8dp)
//
mRoot!!.recycler_view.layoutManager = LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false)
mRoot!!.recycler_view.addItemDecoration(divider)
// mRoot!!.recycler_view.adapter = adapter
mRoot!!.refresh_layout.setOnRefreshListener {
// val adapter = HomeListAdapter(mActivity!!, )
// mRoot!!.recycler_view.adapter = adapter
// mRoot!!.refresh_layout.isRefreshing = false
}
val service = Api.INSTANCE.net().create(GankIoService::class.java)
service.data("福利", 20, 1).enqueue(object : Callback<GankData> {
override fun onResponse(call: Call<GankData>?, response: Response<GankData>?) {
val adapter = HomeListAdapter(mActivity!!, response!!.body())
mRoot!!.recycler_view.adapter = adapter
}
override fun onFailure(call: Call<GankData>?, e: Throwable?) {
Toast.makeText(mActivity, e.toString(), Toast.LENGTH_SHORT).show()
}
})
return mRoot
}
}
| 0 | Kotlin | 0 | 3 | fb038fd088aadde8834d51c378d08a0fecd9e81b | 2,683 | GankIOForKotlin | Apache License 2.0 |
litho-core/src/main/java/com/facebook/litho/TextContent.kt | jillmnolan | 611,154,412 | false | {"Java Properties": 55, "Markdown": 81, "Shell": 17, "Batchfile": 12, "Java": 1715, "Kotlin": 777, "C": 2, "C++": 41, "CMake": 3, "Proguard": 10, "JavaScript": 7, "HTML": 1211, "CSS": 1, "INI": 1} | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho
import com.facebook.proguard.annotations.DoNotStrip
import kotlin.jvm.JvmField
/** A UI element that contains text. */
@DoNotStrip
interface TextContent {
/**
* @return the list of text items that are rendered by this UI element. The list returned should
* not be modified and may be unmodifiable.
*/
@get:DoNotStrip val textItems: List<CharSequence>
companion object {
/** An empty instance of [TextContent]. */
@JvmField
val EMPTY: TextContent =
object : TextContent {
override val textItems: List<CharSequence>
get() = emptyList()
}
}
}
| 1 | null | 1 | 1 | d50c9fb0b3b984c2570e5518d07dabdc1f270403 | 1,260 | litho | Apache License 2.0 |
app/src/main/java/com/perol/asdpl/pixivez/view/AutoTabLayoutMediator.kt | ultranity | 258,955,010 | false | null | package com.perol.asdpl.pixivez.ui
import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.android.material.tabs.TabLayoutMediator
import java.lang.ref.WeakReference
//Viewpager2 in ViewPager, ViewPager 会遍历所有子view判断是否canScroll, 必须重写以实现阻断 Viewpager2 nested scroll
//isUserInputEnabled可以禁止滑动但外层Viewpager仍会放弃阻断触摸
class NotCrossScrollableLinearLayoutManager(
context: Context,
private val mRecyclerView: RecyclerView,
private val mViewpager: ViewPager2,
) :
LinearLayoutManager(context, RecyclerView.HORIZONTAL, false) {
private fun getPageSize(): Int {
return if (orientation == ViewPager2.ORIENTATION_HORIZONTAL)
mRecyclerView.width - mRecyclerView.paddingLeft - mRecyclerView.paddingRight
else
mRecyclerView.height - mRecyclerView.paddingTop - mRecyclerView.paddingBottom
}
override fun calculateExtraLayoutSpace(
state: RecyclerView.State,
extraLayoutSpace: IntArray
) {
val pageLimit: Int = mViewpager.offscreenPageLimit
if (pageLimit == ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT) {
// Only do custom prefetching of offscreen pages if requested
super.calculateExtraLayoutSpace(state, extraLayoutSpace)
return
}
val offscreenSpace: Int = getPageSize() * pageLimit
extraLayoutSpace[0] = offscreenSpace
extraLayoutSpace[1] = offscreenSpace
}
override fun requestChildRectangleOnScreen(
parent: RecyclerView,
child: View, rect: Rect, immediate: Boolean,
focusedChildVisible: Boolean
): Boolean {
return false // users should use setCurrentItem instead
}
override fun canScrollHorizontally(): Boolean {
return false
}
}
/**
* A callback interface that must be implemented to set the text and styling of newly created
* tabs.
*/
interface TabSelectedStrategy {
fun invoke(tab: TabLayout.Tab)
}
//点击
class AutoTabLayoutMediator(
private val tabLayout: TabLayout,
private val viewPager: ViewPager2,
private val autoRefresh: Boolean = true,
private val smoothScroll: Boolean = false,
private val tabConfigurationStrategy: TabLayoutMediator.TabConfigurationStrategy
) {
var adapter: RecyclerView.Adapter<*>? = null
private var attached = false
private var onPageChangeCallback: TabLayoutOnPageChangeCallback? = null
private var onTabSelectedListener: OnTabSelectedListener? = null
private var pagerAdapterObserver: RecyclerView.AdapterDataObserver? = null
var onTabSelectedStrategy: TabSelectedStrategy? = null
var onTabUnSelectedStrategy: TabSelectedStrategy? = null
var onTabReSelectedStrategy: TabSelectedStrategy? = null
/**
* Link the TabLayout and the ViewPager2 together. Must be called after ViewPager2 has an adapter
* set. To be called on a new instance of TabLayoutMediator or if the ViewPager2's adapter
* changes.
*
* @throws IllegalStateException If the mediator is already attached, or the ViewPager2 has no
* adapter.
*/
fun attach(): AutoTabLayoutMediator {
check(!attached) { "TabLayoutMediator is already attached" }
adapter = viewPager.adapter
checkNotNull(adapter) { "TabLayoutMediator attached before ViewPager2 has an " + "adapter" }
attached = true
// Add our custom OnPageChangeCallback to the ViewPager
onPageChangeCallback = TabLayoutOnPageChangeCallback(tabLayout)
viewPager.registerOnPageChangeCallback(onPageChangeCallback!!)
// Now we'll add a tab selected listener to set ViewPager's current item
onTabSelectedListener = ViewPagerOnTabSelectedListener(
viewPager, smoothScroll
)
tabLayout.addOnTabSelectedListener(onTabSelectedListener)
// Now we'll populate ourselves from the pager adapter, adding an observer if
// autoRefresh is enabled
if (autoRefresh) {
// Register our observer on the new adapter
pagerAdapterObserver = PagerAdapterObserver()
adapter!!.registerAdapterDataObserver(pagerAdapterObserver!!)
}
populateTabsFromPagerAdapter()
// Now update the scroll position to match the ViewPager's current item
tabLayout.setScrollPosition(viewPager.currentItem, 0f, true)
return this
}
/**
* Unlink the TabLayout and the ViewPager. To be called on a stale TabLayoutMediator if a new one
* is instantiated, to prevent holding on to a view that should be garbage collected. Also to be
* called before [.attach] when a ViewPager2's adapter is changed.
*/
fun detach() {
if (autoRefresh && adapter != null) {
if (pagerAdapterObserver != null) {
adapter!!.unregisterAdapterDataObserver(pagerAdapterObserver!!)
}
pagerAdapterObserver = null
}
if (onTabSelectedListener != null) {
tabLayout.removeOnTabSelectedListener(onTabSelectedListener)
}
if (onPageChangeCallback != null) {
viewPager.unregisterOnPageChangeCallback(onPageChangeCallback!!)
}
onTabSelectedListener = null
onPageChangeCallback = null
adapter = null
attached = false
}
fun populateTabsFromPagerAdapter() {
tabLayout.removeAllTabs()
if (adapter != null) {
val adapterCount = adapter!!.itemCount
for (i in 0 until adapterCount) {
val tab = tabLayout.newTab()
tabConfigurationStrategy.onConfigureTab(tab, i)
tabLayout.addTab(tab, false)
}
// Make sure we reflect the currently set ViewPager item
if (adapterCount > 0) {
val lastItem = tabLayout.tabCount - 1
val currItem = viewPager.currentItem.coerceAtMost(lastItem)
if (currItem != tabLayout.selectedTabPosition) {
tabLayout.selectTab(tabLayout.getTabAt(currItem))
}
}
}
}
/**
* A [ViewPager2.OnPageChangeCallback] class which contains the necessary calls back to the
* provided [TabLayout] so that the tab position is kept in sync.
*
*
* This class stores the provided TabLayout weakly, meaning that you can use [ ][ViewPager2.registerOnPageChangeCallback] without removing the
* callback and not cause a leak.
*/
private class TabLayoutOnPageChangeCallback(tabLayout: TabLayout) :
OnPageChangeCallback() {
private val tabLayoutRef: WeakReference<TabLayout>
var previousScrollState = 0
private var scrollState = 0
init {
tabLayoutRef = WeakReference(tabLayout)
reset()
}
override fun onPageScrollStateChanged(state: Int) {
previousScrollState = scrollState
scrollState = state
}
override fun onPageScrolled(
position: Int, positionOffset: Float, positionOffsetPixels: Int
) {
val tabLayout = tabLayoutRef.get()
if (tabLayout != null) {
// Only update the text selection if we're not settling, or we are settling after
// being dragged
val updateText =
scrollState != ViewPager2.SCROLL_STATE_SETTLING || previousScrollState == ViewPager2.SCROLL_STATE_DRAGGING
// Update the indicator if we're not settling after being idle. This is caused
// from a setCurrentItem() call and will be handled by an animation from
// onPageSelected() instead.
val updateIndicator =
!(scrollState == ViewPager2.SCROLL_STATE_SETTLING && previousScrollState == ViewPager2.SCROLL_STATE_IDLE)
tabLayout.setScrollPosition(position, positionOffset, updateText, updateIndicator)
}
}
override fun onPageSelected(position: Int) {
val tabLayout = tabLayoutRef.get()
if (tabLayout != null && tabLayout.selectedTabPosition != position && position < tabLayout.tabCount) {
// Select the tab, only updating the indicator if we're not being dragged/settled
// (since onPageScrolled will handle that).
val updateIndicator =
(scrollState == ViewPager2.SCROLL_STATE_IDLE || (scrollState == ViewPager2.SCROLL_STATE_SETTLING && previousScrollState == ViewPager2.SCROLL_STATE_IDLE))
tabLayout.selectTab(tabLayout.getTabAt(position), updateIndicator)
}
}
fun reset() {
scrollState = ViewPager2.SCROLL_STATE_IDLE
previousScrollState = scrollState
}
}
/**
* A [TabLayout.OnTabSelectedListener] class which contains the necessary calls back to the
* provided [ViewPager2] so that the tab position is kept in sync.
*/
private inner class ViewPagerOnTabSelectedListener(
private val viewPager: ViewPager2, private val smoothScroll: Boolean
) : OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
if (viewPager.currentItem == tab.position){
return
}
if (onPageChangeCallback != null) {
if (onPageChangeCallback!!.previousScrollState == ViewPager2.SCROLL_STATE_DRAGGING) {
viewPager.setCurrentItem(tab.position, true)
} else {
viewPager.setCurrentItem(tab.position, smoothScroll)
}
}
onTabSelectedStrategy?.invoke(tab)
}
override fun onTabUnselected(tab: TabLayout.Tab) {
onTabUnSelectedStrategy?.invoke(tab)
// No-op
}
override fun onTabReselected(tab: TabLayout.Tab) {
// No-op
onTabReSelectedStrategy?.invoke(tab)
}
}
private inner class PagerAdapterObserver : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
populateTabsFromPagerAdapter()
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
populateTabsFromPagerAdapter()
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {
populateTabsFromPagerAdapter()
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
populateTabsFromPagerAdapter()
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
populateTabsFromPagerAdapter()
}
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
populateTabsFromPagerAdapter()
}
}
}
| 6 | null | 33 | 692 | d5caf81746e4f16a1af64d45490a358fd19aec1a | 11,250 | Pix-EzViewer | MIT License |
app/src/main/java/com/perol/asdpl/pixivez/view/AutoTabLayoutMediator.kt | ultranity | 258,955,010 | false | null | package com.perol.asdpl.pixivez.ui
import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.android.material.tabs.TabLayoutMediator
import java.lang.ref.WeakReference
//Viewpager2 in ViewPager, ViewPager 会遍历所有子view判断是否canScroll, 必须重写以实现阻断 Viewpager2 nested scroll
//isUserInputEnabled可以禁止滑动但外层Viewpager仍会放弃阻断触摸
class NotCrossScrollableLinearLayoutManager(
context: Context,
private val mRecyclerView: RecyclerView,
private val mViewpager: ViewPager2,
) :
LinearLayoutManager(context, RecyclerView.HORIZONTAL, false) {
private fun getPageSize(): Int {
return if (orientation == ViewPager2.ORIENTATION_HORIZONTAL)
mRecyclerView.width - mRecyclerView.paddingLeft - mRecyclerView.paddingRight
else
mRecyclerView.height - mRecyclerView.paddingTop - mRecyclerView.paddingBottom
}
override fun calculateExtraLayoutSpace(
state: RecyclerView.State,
extraLayoutSpace: IntArray
) {
val pageLimit: Int = mViewpager.offscreenPageLimit
if (pageLimit == ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT) {
// Only do custom prefetching of offscreen pages if requested
super.calculateExtraLayoutSpace(state, extraLayoutSpace)
return
}
val offscreenSpace: Int = getPageSize() * pageLimit
extraLayoutSpace[0] = offscreenSpace
extraLayoutSpace[1] = offscreenSpace
}
override fun requestChildRectangleOnScreen(
parent: RecyclerView,
child: View, rect: Rect, immediate: Boolean,
focusedChildVisible: Boolean
): Boolean {
return false // users should use setCurrentItem instead
}
override fun canScrollHorizontally(): Boolean {
return false
}
}
/**
* A callback interface that must be implemented to set the text and styling of newly created
* tabs.
*/
interface TabSelectedStrategy {
fun invoke(tab: TabLayout.Tab)
}
//点击
class AutoTabLayoutMediator(
private val tabLayout: TabLayout,
private val viewPager: ViewPager2,
private val autoRefresh: Boolean = true,
private val smoothScroll: Boolean = false,
private val tabConfigurationStrategy: TabLayoutMediator.TabConfigurationStrategy
) {
var adapter: RecyclerView.Adapter<*>? = null
private var attached = false
private var onPageChangeCallback: TabLayoutOnPageChangeCallback? = null
private var onTabSelectedListener: OnTabSelectedListener? = null
private var pagerAdapterObserver: RecyclerView.AdapterDataObserver? = null
var onTabSelectedStrategy: TabSelectedStrategy? = null
var onTabUnSelectedStrategy: TabSelectedStrategy? = null
var onTabReSelectedStrategy: TabSelectedStrategy? = null
/**
* Link the TabLayout and the ViewPager2 together. Must be called after ViewPager2 has an adapter
* set. To be called on a new instance of TabLayoutMediator or if the ViewPager2's adapter
* changes.
*
* @throws IllegalStateException If the mediator is already attached, or the ViewPager2 has no
* adapter.
*/
fun attach(): AutoTabLayoutMediator {
check(!attached) { "TabLayoutMediator is already attached" }
adapter = viewPager.adapter
checkNotNull(adapter) { "TabLayoutMediator attached before ViewPager2 has an " + "adapter" }
attached = true
// Add our custom OnPageChangeCallback to the ViewPager
onPageChangeCallback = TabLayoutOnPageChangeCallback(tabLayout)
viewPager.registerOnPageChangeCallback(onPageChangeCallback!!)
// Now we'll add a tab selected listener to set ViewPager's current item
onTabSelectedListener = ViewPagerOnTabSelectedListener(
viewPager, smoothScroll
)
tabLayout.addOnTabSelectedListener(onTabSelectedListener)
// Now we'll populate ourselves from the pager adapter, adding an observer if
// autoRefresh is enabled
if (autoRefresh) {
// Register our observer on the new adapter
pagerAdapterObserver = PagerAdapterObserver()
adapter!!.registerAdapterDataObserver(pagerAdapterObserver!!)
}
populateTabsFromPagerAdapter()
// Now update the scroll position to match the ViewPager's current item
tabLayout.setScrollPosition(viewPager.currentItem, 0f, true)
return this
}
/**
* Unlink the TabLayout and the ViewPager. To be called on a stale TabLayoutMediator if a new one
* is instantiated, to prevent holding on to a view that should be garbage collected. Also to be
* called before [.attach] when a ViewPager2's adapter is changed.
*/
fun detach() {
if (autoRefresh && adapter != null) {
if (pagerAdapterObserver != null) {
adapter!!.unregisterAdapterDataObserver(pagerAdapterObserver!!)
}
pagerAdapterObserver = null
}
if (onTabSelectedListener != null) {
tabLayout.removeOnTabSelectedListener(onTabSelectedListener)
}
if (onPageChangeCallback != null) {
viewPager.unregisterOnPageChangeCallback(onPageChangeCallback!!)
}
onTabSelectedListener = null
onPageChangeCallback = null
adapter = null
attached = false
}
fun populateTabsFromPagerAdapter() {
tabLayout.removeAllTabs()
if (adapter != null) {
val adapterCount = adapter!!.itemCount
for (i in 0 until adapterCount) {
val tab = tabLayout.newTab()
tabConfigurationStrategy.onConfigureTab(tab, i)
tabLayout.addTab(tab, false)
}
// Make sure we reflect the currently set ViewPager item
if (adapterCount > 0) {
val lastItem = tabLayout.tabCount - 1
val currItem = viewPager.currentItem.coerceAtMost(lastItem)
if (currItem != tabLayout.selectedTabPosition) {
tabLayout.selectTab(tabLayout.getTabAt(currItem))
}
}
}
}
/**
* A [ViewPager2.OnPageChangeCallback] class which contains the necessary calls back to the
* provided [TabLayout] so that the tab position is kept in sync.
*
*
* This class stores the provided TabLayout weakly, meaning that you can use [ ][ViewPager2.registerOnPageChangeCallback] without removing the
* callback and not cause a leak.
*/
private class TabLayoutOnPageChangeCallback(tabLayout: TabLayout) :
OnPageChangeCallback() {
private val tabLayoutRef: WeakReference<TabLayout>
var previousScrollState = 0
private var scrollState = 0
init {
tabLayoutRef = WeakReference(tabLayout)
reset()
}
override fun onPageScrollStateChanged(state: Int) {
previousScrollState = scrollState
scrollState = state
}
override fun onPageScrolled(
position: Int, positionOffset: Float, positionOffsetPixels: Int
) {
val tabLayout = tabLayoutRef.get()
if (tabLayout != null) {
// Only update the text selection if we're not settling, or we are settling after
// being dragged
val updateText =
scrollState != ViewPager2.SCROLL_STATE_SETTLING || previousScrollState == ViewPager2.SCROLL_STATE_DRAGGING
// Update the indicator if we're not settling after being idle. This is caused
// from a setCurrentItem() call and will be handled by an animation from
// onPageSelected() instead.
val updateIndicator =
!(scrollState == ViewPager2.SCROLL_STATE_SETTLING && previousScrollState == ViewPager2.SCROLL_STATE_IDLE)
tabLayout.setScrollPosition(position, positionOffset, updateText, updateIndicator)
}
}
override fun onPageSelected(position: Int) {
val tabLayout = tabLayoutRef.get()
if (tabLayout != null && tabLayout.selectedTabPosition != position && position < tabLayout.tabCount) {
// Select the tab, only updating the indicator if we're not being dragged/settled
// (since onPageScrolled will handle that).
val updateIndicator =
(scrollState == ViewPager2.SCROLL_STATE_IDLE || (scrollState == ViewPager2.SCROLL_STATE_SETTLING && previousScrollState == ViewPager2.SCROLL_STATE_IDLE))
tabLayout.selectTab(tabLayout.getTabAt(position), updateIndicator)
}
}
fun reset() {
scrollState = ViewPager2.SCROLL_STATE_IDLE
previousScrollState = scrollState
}
}
/**
* A [TabLayout.OnTabSelectedListener] class which contains the necessary calls back to the
* provided [ViewPager2] so that the tab position is kept in sync.
*/
private inner class ViewPagerOnTabSelectedListener(
private val viewPager: ViewPager2, private val smoothScroll: Boolean
) : OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
if (viewPager.currentItem == tab.position){
return
}
if (onPageChangeCallback != null) {
if (onPageChangeCallback!!.previousScrollState == ViewPager2.SCROLL_STATE_DRAGGING) {
viewPager.setCurrentItem(tab.position, true)
} else {
viewPager.setCurrentItem(tab.position, smoothScroll)
}
}
onTabSelectedStrategy?.invoke(tab)
}
override fun onTabUnselected(tab: TabLayout.Tab) {
onTabUnSelectedStrategy?.invoke(tab)
// No-op
}
override fun onTabReselected(tab: TabLayout.Tab) {
// No-op
onTabReSelectedStrategy?.invoke(tab)
}
}
private inner class PagerAdapterObserver : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
populateTabsFromPagerAdapter()
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
populateTabsFromPagerAdapter()
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {
populateTabsFromPagerAdapter()
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
populateTabsFromPagerAdapter()
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
populateTabsFromPagerAdapter()
}
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
populateTabsFromPagerAdapter()
}
}
}
| 6 | null | 33 | 692 | d5caf81746e4f16a1af64d45490a358fd19aec1a | 11,250 | Pix-EzViewer | MIT License |
wallet/src/main/kotlin/org/trustnote/superwallet/biz/msgs/FragmentMsgsContactsAdd.kt | ringringringring | 129,693,546 | false | null | package org.trustnote.wallet.biz.msgs
import android.view.View
import android.widget.Button
import org.trustnote.wallet.R
import org.trustnote.wallet.TApp
import org.trustnote.wallet.biz.wallet.WalletManager
import org.trustnote.wallet.uiframework.ActivityBase
import org.trustnote.wallet.util.AndroidUtils
import org.trustnote.wallet.util.SCAN_RESULT_TYPE
import org.trustnote.wallet.util.TTTUtils
import org.trustnote.wallet.widget.MyTextWatcher
import org.trustnote.wallet.widget.ScanLayout
class FragmentMsgsContactsAdd : FragmentMsgsBase() {
lateinit var scanLayout: ScanLayout
lateinit var btn: Button
lateinit var ownerActivity: ActivityBase
override fun getLayoutId(): Int {
return R.layout.f_msg_contacts_add
}
override fun initFragment(view: View) {
super.initFragment(view)
ownerActivity = activity as ActivityBase
scanLayout = mRootView.findViewById(R.id.contacts_add_scan_layoiut)
btn = mRootView.findViewById(R.id.contacts_add_btn)
setupScan(scanLayout.scanIcon) {
if (it.isNotEmpty() && it.startsWith("TTT:")) {
scanLayout.scanResult.setText(it.substring(4))
} else {
scanLayout.scanResult.setText(it)
}
updateUI()
}
scanLayout.scanTitle.setText(activity.getString(R.string.contacts_add_pair_code_label))
scanLayout.scanResult.setHint(activity.getString(R.string.message_contacts_add_hint))
val qrCode = AndroidUtils.getQrcodeFromBundle(arguments)
scanLayout.scanResult.setText(qrCode)
btn.setOnClickListener {
if (isQrCodeValid()) {
onBackPressed()
MessageModel.instance.addContacts("TTT:" + scanLayout.scanResult.text.toString()) {
chatWithFriend(it, ownerActivity)
}
} else {
val res = scanLayout.scanResult.text.toString()
if (res.isEmpty()) {
scanLayout.scanErr.visibility = View.INVISIBLE
} else {
scanLayout.scanErr.visibility = View.VISIBLE
scanLayout.scanErr.text = getErrInfo()
}
}
}
scanLayout.scanResult.addTextChangedListener(MyTextWatcher(this))
}
override fun updateUI() {
super.updateUI()
AndroidUtils.enableBtn(btn, scanLayout.scanResult.text.isNotEmpty())
scanLayout.scanErr.visibility = View.INVISIBLE
}
private fun isQrCodeValid(): Boolean {
val res = "TTT:" + scanLayout.scanResult.text.toString()
val matchRes = TTTUtils.parseQrCodeType(res) == SCAN_RESULT_TYPE.TTT_PAIRID
return if (matchRes) {
!res.contains(WalletManager.model.mProfile.pubKeyForPairId)
} else {
matchRes
}
}
private fun getErrInfo(): String {
val res = "TTT:" + scanLayout.scanResult.text.toString()
val matchRes = TTTUtils.parseQrCodeType(res) == SCAN_RESULT_TYPE.TTT_PAIRID
return if (matchRes) {
activity.getString(R.string.contacts_add_err_cannot_add_myself)
} else {
activity.getString(R.string.contacts_add_pairid_format_err)
}
}
}
| 1 | null | 5 | 6 | 7a1c95b60569600ff09b5d520a1c4694fc1a3707 | 3,298 | trustnote-wallet-android | MIT License |
android/store/src/main/java/com/smarttoni/store/StoreRequest.kt | karthikv8058 | 359,537,229 | false | null | package com.smarttoni.store
class StoreRequest {
internal var latestVersion: String? = null
internal var latestVersionCode: Int = 0
internal var url: String? = null
internal var releaseNotes: String? = null
}
| 1 | null | 1 | 1 | a2d21a019d8a67f0c3b52c102b6961e558219732 | 226 | kitchen-app | MIT License |
app/src/main/java/org/ranapat/webrtc/example/ui/util/ViewExtensions.kt | ranapat | 217,318,264 | false | {"Java": 146295, "Kotlin": 38914} | package org.ranapat.webrtc.example.ui.util
import android.content.Context.INPUT_METHOD_SERVICE
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
/**
* Performs the given action when enter key is pressed with id: [EditorInfo.IME_ACTION_DONE] on the edit text.
*/
fun EditText.onEditorActionDone(action: (TextView) -> Unit) {
this.setOnEditorActionListener { textView, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
action.invoke(textView)
return@setOnEditorActionListener true
}
return@setOnEditorActionListener false
}
}
inline fun View.watchLayoutOnce(crossinline body: (View) -> Unit) {
if (this.isLaidOut) {
body(this)
} else {
viewTreeObserver.addOnGlobalLayoutListener(
object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
body(this@watchLayoutOnce)
}
})
}
}
/**
* Performs the given action when the view tree is about to be drawn.
*/
inline fun View.doOnPreDraw(crossinline action: (view: View) -> Unit) {
val vto = viewTreeObserver
vto.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
action(this@doOnPreDraw)
when {
vto.isAlive -> vto.removeOnPreDrawListener(this)
else -> viewTreeObserver.removeOnPreDrawListener(this)
}
return true
}
})
}
/**
* Hides the soft keyboard
*/
fun View.hideSoftKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
inputMethodManager?.hideSoftInputFromWindow(this.windowToken, 0)
}
/**
* Shows the soft keyboard
*/
fun View.showSoftKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
fun ViewGroup.inflate(layoutRes: Int): View {
return LayoutInflater.from(context).inflate(layoutRes, this, false)
} | 1 | Java | 1 | 1 | 385fdfe7096ffca4f36c537455b5b608abfbedf0 | 2,448 | webrtc.client | The Unlicense |
certificatetransparency/src/test/kotlin/com/babylon/certificatetransparency/internal/utils/CertificateExtTest.kt | babylonhealth | 152,060,574 | false | null | /*
* Copyright 2019 Babylon Partners Limited
*
* 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.
*
* Code derived from https://github.com/google/certificate-transparency-java
*/
package com.babylon.certificatetransparency.internal.utils
import com.babylon.certificatetransparency.utils.TestData.PRE_CERT_SIGNING_CERT
import com.babylon.certificatetransparency.utils.TestData.ROOT_CA_CERT
import com.babylon.certificatetransparency.utils.TestData.TEST_CERT
import com.babylon.certificatetransparency.utils.TestData.TEST_PRE_CERT
import com.babylon.certificatetransparency.utils.TestData.loadCertificates
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/** Make sure the correct info about certificates is provided. */
class CertificateExtTest {
@Test
fun correctlyIdentifiesPreCertificateSigningCert() {
val preCertificateSigningCert = loadCertificates(PRE_CERT_SIGNING_CERT)[0]
val ordinaryCaCert = loadCertificates(ROOT_CA_CERT)[0]
assertTrue(preCertificateSigningCert.isPreCertificateSigningCert())
assertFalse(ordinaryCaCert.isPreCertificateSigningCert())
}
@Test
fun correctlyIdentifiesPreCertificates() {
val regularCert = loadCertificates(TEST_CERT)[0]
val preCertificate = loadCertificates(TEST_PRE_CERT)[0]
assertTrue(preCertificate.isPreCertificate())
assertFalse(regularCert.isPreCertificate())
}
}
| 1 | Kotlin | 24 | 197 | 15ea45c73631cf39c0bbf206b10641f0dbfef957 | 1,955 | certificate-transparency-android | Apache License 2.0 |
compiler/tests-common-new/tests/org/jetbrains/kotlin/test/services/configuration/WasmEnvironmentConfigurator.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.test.services.configuration
import org.jetbrains.kotlin.config.AnalysisFlag
import org.jetbrains.kotlin.config.AnalysisFlags.allowFullyQualifiedNameInKClass
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.js.config.JSConfigurationKeys
import org.jetbrains.kotlin.js.config.SourceMapSourceEmbedding
import org.jetbrains.kotlin.library.KotlinLibrary
import org.jetbrains.kotlin.serialization.js.ModuleKind
import org.jetbrains.kotlin.test.directives.JsEnvironmentConfigurationDirectives.INFER_MAIN_MODULE
import org.jetbrains.kotlin.test.directives.JsEnvironmentConfigurationDirectives.EXPECT_ACTUAL_LINKER
import org.jetbrains.kotlin.test.directives.JsEnvironmentConfigurationDirectives.PROPERTY_LAZY_INITIALIZATION
import org.jetbrains.kotlin.test.directives.JsEnvironmentConfigurationDirectives.SOURCE_MAP_EMBED_SOURCES
import org.jetbrains.kotlin.test.directives.WasmEnvironmentConfigurationDirectives
import org.jetbrains.kotlin.test.directives.model.DirectivesContainer
import org.jetbrains.kotlin.test.directives.model.RegisteredDirectives
import org.jetbrains.kotlin.test.frontend.classic.moduleDescriptorProvider
import org.jetbrains.kotlin.test.model.ArtifactKinds
import org.jetbrains.kotlin.test.model.DependencyKind
import org.jetbrains.kotlin.test.model.DependencyRelation
import org.jetbrains.kotlin.test.model.TestModule
import org.jetbrains.kotlin.test.services.*
import java.io.File
class WasmEnvironmentConfigurator(testServices: TestServices) : EnvironmentConfigurator(testServices) {
override val directiveContainers: List<DirectivesContainer>
get() = listOf(WasmEnvironmentConfigurationDirectives)
companion object {
private const val OUTPUT_KLIB_DIR_NAME = "outputKlibDir"
fun getRuntimePathsForModule(): List<String> {
return listOf(System.getProperty("kotlin.wasm.stdlib.path")!!, System.getProperty("kotlin.wasm.kotlin.test.path")!!)
}
fun getKlibDependencies(module: TestModule, testServices: TestServices, kind: DependencyRelation): List<File> {
val visited = mutableSetOf<TestModule>()
fun getRecursive(module: TestModule, relation: DependencyRelation) {
val dependencies = if (relation == DependencyRelation.FriendDependency) {
module.friendDependencies
} else {
module.regularDependencies
}
dependencies
.filter { it.kind != DependencyKind.Source }
.map { testServices.dependencyProvider.getTestModule(it.moduleName) }.forEach {
if (it !in visited) {
visited += it
getRecursive(it, relation)
}
}
}
getRecursive(module, kind)
return visited.map { testServices.dependencyProvider.getArtifact(it, ArtifactKinds.KLib).outputFile }
}
fun getDependencies(module: TestModule, testServices: TestServices, kind: DependencyRelation): List<ModuleDescriptor> {
return getKlibDependencies(module, testServices, kind)
.map { testServices.libraryProvider.getDescriptorByPath(it.absolutePath) }
}
fun getWasmKlibArtifactPath(testServices: TestServices, moduleName: String): String {
return getWasmKlibOutputDir(testServices).absolutePath + File.separator + JsEnvironmentConfigurator.getJsArtifactSimpleName(
testServices,
moduleName
)
}
fun getWasmKlibOutputDir(testServices: TestServices): File {
return testServices.temporaryDirectoryManager.getOrCreateTempDirectory(OUTPUT_KLIB_DIR_NAME)
}
fun getAllRecursiveDependenciesFor(module: TestModule, testServices: TestServices): Set<ModuleDescriptorImpl> {
val visited = mutableSetOf<ModuleDescriptorImpl>()
fun getRecursive(descriptor: ModuleDescriptor) {
descriptor.allDependencyModules.forEach {
if (it is ModuleDescriptorImpl && it !in visited) {
visited += it
getRecursive(it)
}
}
}
getRecursive(testServices.moduleDescriptorProvider.getModuleDescriptor(module))
return visited
}
fun getAllRecursiveLibrariesFor(module: TestModule, testServices: TestServices): Map<KotlinLibrary, ModuleDescriptorImpl> {
val dependencies = getAllRecursiveDependenciesFor(module, testServices)
return dependencies.associateBy { testServices.libraryProvider.getCompiledLibraryByDescriptor(it) }
}
fun getAllDependenciesMappingFor(module: TestModule, testServices: TestServices): Map<KotlinLibrary, List<KotlinLibrary>> {
val allRecursiveLibraries: Map<KotlinLibrary, ModuleDescriptor> =
getAllRecursiveLibrariesFor(module, testServices)
val m2l = allRecursiveLibraries.map { it.value to it.key }.toMap()
return allRecursiveLibraries.keys.associateWith { m ->
val descriptor = allRecursiveLibraries[m] ?: error("No descriptor found for library ${m.libraryName}")
descriptor.allDependencyModules.filter { it != descriptor }.map { m2l.getValue(it) }
}
}
fun getMainModule(testServices: TestServices): TestModule {
val modules = testServices.moduleStructure.modules
val inferMainModule = INFER_MAIN_MODULE in testServices.moduleStructure.allDirectives
return when {
inferMainModule -> modules.last()
else -> modules.singleOrNull { it.name == ModuleStructureExtractor.DEFAULT_MODULE_NAME } ?: modules.last()
}
}
fun isMainModule(module: TestModule, testServices: TestServices): Boolean {
return module == getMainModule(testServices)
}
}
override fun provideAdditionalAnalysisFlags(
directives: RegisteredDirectives,
languageVersion: LanguageVersion
): Map<AnalysisFlag<*>, Any?> {
return super.provideAdditionalAnalysisFlags(directives, languageVersion).toMutableMap().also {
it[allowFullyQualifiedNameInKClass] = false
}
}
override fun DirectiveToConfigurationKeyExtractor.provideConfigurationKeys() {
register(PROPERTY_LAZY_INITIALIZATION, JSConfigurationKeys.PROPERTY_LAZY_INITIALIZATION)
}
override fun configureCompilerConfiguration(configuration: CompilerConfiguration, module: TestModule) {
val registeredDirectives = module.directives
configuration.put(JSConfigurationKeys.MODULE_KIND, ModuleKind.ES)
configuration.put(CommonConfigurationKeys.MODULE_NAME, module.name)
configuration.put(JSConfigurationKeys.WASM_ENABLE_ASSERTS, true)
configuration.put(JSConfigurationKeys.WASM_ENABLE_ARRAY_RANGE_CHECKS, true)
val sourceDirs = module.files.map { it.originalFile.parent }.distinct()
configuration.put(JSConfigurationKeys.SOURCE_MAP_SOURCE_ROOTS, sourceDirs)
configuration.put(JSConfigurationKeys.SOURCE_MAP, true)
val sourceMapSourceEmbedding = registeredDirectives[SOURCE_MAP_EMBED_SOURCES].singleOrNull() ?: SourceMapSourceEmbedding.NEVER
configuration.put(JSConfigurationKeys.SOURCE_MAP_EMBED_SOURCES, sourceMapSourceEmbedding)
configuration.put(CommonConfigurationKeys.EXPECT_ACTUAL_LINKER, EXPECT_ACTUAL_LINKER in registeredDirectives)
}
} | 154 | null | 5566 | 45,025 | 8a69904d02dd3e40fae5f2a1be4093d44a227788 | 8,110 | kotlin | Apache License 2.0 |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/util/debug/TimeMeasurement.kt | corona-warn-app | 268,027,139 | false | null | package de.rki.coronawarnapp.util.debug
inline fun <T> measureTimeMillisWithResult(block: () -> T): Pair<T, Long> {
val start = System.currentTimeMillis()
val result = block()
return result to (System.currentTimeMillis() - start)
}
inline fun <T> measureTime(onMeasured: (Long) -> Unit, block: () -> T): T {
val start = System.currentTimeMillis()
try {
return block()
} finally {
val stop = System.currentTimeMillis()
onMeasured(stop - start)
}
}
| 6 | Kotlin | 514 | 2,495 | d3833a212bd4c84e38a1fad23b282836d70ab8d5 | 501 | cwa-app-android | Apache License 2.0 |
app/src/main/java/org/fossasia/openevent/general/speakers/ListSpeakerIdConverter.kt | fossasia | 34,847,604 | false | null | package org.fossasia.openevent.general.speakers
import androidx.room.TypeConverter
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
class ListSpeakerIdConverter {
@TypeConverter
fun fromListSpeakerId(speakerIdList: List<SpeakerId>): String {
return ObjectMapper().writeValueAsString(speakerIdList)
}
@TypeConverter
fun toListSpeakerId(speakerIdList: String): List<SpeakerId> {
return jacksonObjectMapper().readValue(speakerIdList, object : TypeReference<List<SpeakerId>>() {})
}
}
| 73 | null | 562 | 1,942 | e3214589f83c155e477f9e727370d7bbef8fd915 | 643 | open-event-attendee-android | Apache License 2.0 |
platform/statistics/src/com/intellij/internal/statistic/service/fus/collectors/UIEventLogger.kt | hieuprogrammer | 284,920,751 | false | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("UIEventLogger")
package com.intellij.internal.statistic.service.fus.collectors
import com.intellij.internal.statistic.eventLog.FeatureUsageData
/**
* @author yole
*/
enum class UIEventId {
NavBarShowPopup,
NavBarNavigate,
LookupShowElementActions,
LookupExecuteElementAction,
DaemonEditorPopupInvoked,
HectorPopupDisplayed,
ProgressPaused,
ProgressResumed,
BreadcrumbShowTooltip,
BreadcrumbNavigate,
DumbModeBalloonWasNotNeeded,
DumbModeBalloonRequested,
DumbModeBalloonShown,
DumbModeBalloonCancelled,
DumbModeBalloonProceededToActions,
IncrementalSearchActivated,
IncrementalSearchKeyTyped,
IncrementalSearchCancelled,
IncrementalSearchNextPrevItemSelected
}
fun logUIEvent(eventId: UIEventId) {
FUCounterUsageLogger.getInstance().logEvent("ui.event", eventId.name)
}
fun logUIEvent(eventId: UIEventId, data: FeatureUsageData) {
FUCounterUsageLogger.getInstance().logEvent("ui.event", eventId.name, data)
}
| 1 | null | 1 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 1,114 | intellij-community | Apache License 2.0 |
utilcode/src/main/java/com/blankj/utilcode/util/StartActivityResultExt.kt | cat-x | 121,213,241 | true | {"Gradle": 7, "Markdown": 7, "Java Properties": 3, "Shell": 1, "Text": 9, "Ignore List": 4, "Batchfile": 1, "YAML": 1, "Proguard": 3, "XML": 88, "Kotlin": 139, "Java": 15, "INI": 1} | package com.blankj.utilcode.util
import android.app.Activity
import android.app.Application
import android.app.Fragment
import android.content.Intent
import android.os.Bundle
/**
* Created by Cat-x on 2018/2/8.
* For QuickToolkit-master
*/
private class Result(val resultCode: Int, val data: Any?)
private var resultObjectData = HashMap<String, Result>()
/**
* Activity请求的key
*/
private const val RESULT_KEY_CLASS_CODE = "result_key_class_code"
/**
* 是否是Result扩展请求
*/
private const val RESULT_KEY_USE = "result_key_use"
fun Fragment.startActivityForObject(intent: Intent, requestCode: Int, callback: (requestCode: Int, resultCode: Int, data: Any?) -> Unit) {
activity?.startActivityForObject(intent, requestCode, callback)
}
fun Activity.startActivityForObject(intent: Intent, requestCode: Int, callback: (requestCode: Int, resultCode: Int, data: Any?) -> Unit) {
val requestKey = this.javaClass.canonicalName + "/" + requestCode
application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityPaused(activity: Activity?) {}
override fun onActivityResumed(activity: Activity?) {
if (this@startActivityForObject == activity/*activity != null && activity.javaClass == [email protected]*/) {//必须是同一个Activity,无需关心父类
val result = resultObjectData[requestKey]
callback(requestCode, result?.resultCode ?: Activity.RESULT_CANCELED, result?.data)
releaseData()//当如果有人忘记设置setResult(),会存在影响没有取消监听ActivityLifecycleCallbacks的影响
}
}
override fun onActivityStarted(activity: Activity?) {}
override fun onActivityDestroyed(activity: Activity?) {
/**
* 当activity销毁时,需要判断是不是进行设置setData数据的Activity,因为可能有人会进行反复对同一个Activity调用
*/
if (this@startActivityForObject == activity/*activity != null && activity.javaClass == [email protected]*/) {
val data = resultObjectData[requestKey]
if (data != null) {
releaseData()
}
}
}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {}
override fun onActivityStopped(activity: Activity?) {}
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {}
private fun releaseData() {
resultObjectData.remove(requestKey)
application.unregisterActivityLifecycleCallbacks(this)
}
})
intent.putExtra(RESULT_KEY_CLASS_CODE, requestKey)
intent.putExtra(RESULT_KEY_USE, true)
this.startActivity(intent)
}
fun Fragment.setObjectResult(resultCode: Int = Activity.RESULT_OK, needFinish: Boolean = false) {
activity?.setObjectResult(resultCode, null, needFinish)
}
fun Fragment.setObjectResult(resultCode: Int = Activity.RESULT_OK, data: Any?, needFinish: Boolean = false) {
activity?.setObjectResult(resultCode, data, needFinish)
}
fun Activity.setObjectResult(resultCode: Int = Activity.RESULT_OK, needFinish: Boolean = false) {
setObjectResult(resultCode, null, needFinish)
}
fun Activity.setObjectResult(resultCode: Int = Activity.RESULT_OK, data: Any?, needFinish: Boolean = false) {
try {
val intentPre = intent
if (intentPre != null) {
val isResultCall = intentPre.getBooleanExtra(RESULT_KEY_USE, false)
if (isResultCall) {
val requestKey = intentPre.getStringExtra(RESULT_KEY_CLASS_CODE)
resultObjectData[requestKey] = Result(resultCode, data)
} else {
throw RuntimeException("You must be call setObjectResult before calling setIntent")
}
} else {
throw RuntimeException("You must be call setObjectResult before calling setIntent")
}
} finally {
if (needFinish) {
finish()
}
}
}
| 0 | Kotlin | 0 | 0 | ba2d70d56ae44180933524aa3e2cfe96909e4876 | 3,990 | AndroidUtilCode-Kotlin | Apache License 2.0 |
zman-backend/src/main/kotlin/com/peterservice/zman/api/zookeeper/ZookeeperServiceManager.kt | peterservice-rnd | 84,971,970 | false | null | package com.peterservice.zman.api.zookeeper
import com.peterservice.zman.api.entities.ZServer
interface ZookeeperServiceManager {
fun getServiceFor(server: ZServer): ZookeeperService
fun invalidateCacheFor(server: ZServer)
}
| 4 | null | 5 | 19 | e06223480bffe1eea3e02b49e67d4c5bc686eddf | 237 | zman | Apache License 2.0 |
rewrite-java-tck/src/main/kotlin/org/openrewrite/java/format/WrappingAndBracesTest.kt | eugene-sadovsky | 578,187,930 | true | {"INI": 2, "Gradle Kotlin DSL": 20, "Shell": 6, "Markdown": 9, "Git Attributes": 1, "Batchfile": 2, "Text": 4, "Ignore List": 3, "Kotlin": 369, "Java": 1234, "YAML": 31, "JSON": 2, "ANTLR": 21, "EditorConfig": 13, "Groovy": 3, "XML": 1} | /*
* Copyright 2020 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.java.format
import org.junit.jupiter.api.Test
import org.openrewrite.Issue
import org.openrewrite.Tree
import org.openrewrite.java.Assertions.java
import org.openrewrite.java.JavaParser
import org.openrewrite.java.style.IntelliJ
import org.openrewrite.java.style.WrappingAndBracesStyle
import org.openrewrite.style.NamedStyles
import org.openrewrite.style.Style
import org.openrewrite.test.RecipeSpec
import org.openrewrite.test.RewriteTest
import org.openrewrite.test.RewriteTest.toRecipe
@Suppress("UnusedAssignment", "ClassInitializerMayBeStatic")
interface WrappingAndBracesTest : RewriteTest {
override fun defaults(spec: RecipeSpec) {
spec.recipe(toRecipe {WrappingAndBracesVisitor(WrappingAndBracesStyle(WrappingAndBracesStyle.IfStatement(false)))})
}
fun namedStyles(styles: Collection<Style>) : Iterable<NamedStyles> {
return listOf(NamedStyles(Tree.randomId(), "Test", "test", "test", emptySet(), styles))
}
@Suppress("StatementWithEmptyBody", "ConstantConditions")
@Issue("https://github.com/openrewrite/rewrite/issues/804")
@Test
fun conditionalsShouldStartOnNewLines() = rewriteRun(
{ spec -> spec.recipe(WrappingAndBraces().doNext(TabsAndIndents()))},
java("""
class Test {
void test() {
if (1 == 2) {
} if (1 == 3) {
}
}
}
""",
"""
class Test {
void test() {
if (1 == 2) {
}
if (1 == 3) {
}
}
}
"""
)
)
@Test
fun blockLevelStatements() = rewriteRun(
java("""
public class Test {
{ int n = 0;
n++;
}
}
""",
"""
public class Test {
{
int n = 0;
n++;
}
}
"""
)
)
@Test
fun blockEndOnOwnLine() = rewriteRun(
java("""
class Test {
int n = 0;}
""",
"""
class Test {
int n = 0;
}
"""
)
)
@Test
fun annotatedMethod() = rewriteRun(
java("""
public class Test {
@SuppressWarnings({"ALL"}) Object method() {
return new Object();
}
}
""",
"""
public class Test {
@SuppressWarnings({"ALL"})
Object method() {
return new Object();
}
}
"""
)
)
@Test
fun annotatedMethodWithModifier() = rewriteRun(
java("""
public class Test {
@SuppressWarnings({"ALL"}) public Object method() {
return new Object();
}
}
""",
"""
public class Test {
@SuppressWarnings({"ALL"})
public Object method() {
return new Object();
}
}
"""
)
)
@Test
fun annotatedMethodWithModifiers() = rewriteRun(
java("""
public class Test {
@SuppressWarnings({"ALL"}) public final Object method() {
return new Object();
}
}
""",
"""
public class Test {
@SuppressWarnings({"ALL"})
public final Object method() {
return new Object();
}
}
"""
)
)
@Test
fun annotatedMethodWithTypeParameter() = rewriteRun(
java("""
public class Test {
@SuppressWarnings({"ALL"}) <T> T method() {
return null;
}
}
""",
"""
public class Test {
@SuppressWarnings({"ALL"})
<T> T method() {
return null;
}
}
"""
)
)
@Test
fun multipleAnnotatedMethod() = rewriteRun(
java("""
public class Test {
@SuppressWarnings({"ALL"}) @Deprecated Object method() {
return new Object();
}
}
""",
"""
public class Test {
@SuppressWarnings({"ALL"})
@Deprecated
Object method() {
return new Object();
}
}
"""
)
)
@Test
fun annotatedConstructor() = rewriteRun(
java("""
public class Test {
@SuppressWarnings({"ALL"}) @Deprecated Test() {
}
}
""",
"""
public class Test {
@SuppressWarnings({"ALL"})
@Deprecated
Test() {
}
}
"""
)
)
@Test
fun annotatedClassDecl() = rewriteRun(
java("""
@SuppressWarnings({"ALL"}) class Test {
}
""",
"""
@SuppressWarnings({"ALL"})
class Test {
}
"""
)
)
@Test
fun annotatedClassDeclAlreadyCorrect() = rewriteRun(
java("""
@SuppressWarnings({"ALL"})
class Test {
}
"""
)
)
@Test
fun annotatedClassDeclWithModifiers() = rewriteRun(
java("""
@SuppressWarnings({"ALL"}) public class Test {
}
""",
"""
@SuppressWarnings({"ALL"})
public class Test {
}
"""
)
)
@Test
fun annotatedVariableDecl() = rewriteRun(
java("""
public class Test {
public void doSomething() {
@SuppressWarnings("ALL") int foo;
}
}
""",
"""
public class Test {
public void doSomething() {
@SuppressWarnings("ALL")
int foo;
}
}
"""
)
)
@Test
fun annotatedVariableAlreadyCorrect() = rewriteRun(
java("""
public class Test {
public void doSomething() {
@SuppressWarnings("ALL")
int foo;
}
}
"""
)
)
@Test
fun annotatedVariableDeclWithModifier() = rewriteRun(
java("""
public class Test {
@SuppressWarnings("ALL") private int foo;
}
""",
"""
public class Test {
@SuppressWarnings("ALL")
private int foo;
}
"""
)
)
@Test
fun annotatedVariableDeclInMethodDeclaration() = rewriteRun(
java("""
public class Test {
public void doSomething(@SuppressWarnings("ALL") int foo) {
}
}
"""
)
)
@Issue("https://github.com/openrewrite/rewrite/issues/375")
@Test
fun retainTrailingComments() = rewriteRun(
java("""
public class Test {
int m; /* comment */ int n;}
""",
"""
public class Test {
int m; /* comment */
int n;
}
"""
)
)
@Issue("https://github.com/openrewrite/rewrite/issues/2469")
@Test
fun elseOnNewLine() = rewriteRun(
{ spec ->
spec.parser(
JavaParser.fromJavaVersion().styles(
namedStyles(listOf(IntelliJ.spaces().run {
withBeforeKeywords(beforeKeywords.run {
withElseKeyword(true)
})
}))
)
).recipe(toRecipe {WrappingAndBracesVisitor(WrappingAndBracesStyle(WrappingAndBracesStyle.IfStatement(true)))}
.doNext(TabsAndIndents()))
},
java("""
public class Test {
void method(int arg0) {
if (arg0 == 0) {
System.out.println("if");
} else if (arg0 == 1) {
System.out.println("else if");
} else {
System.out.println("else");
}
}
}
""",
"""
public class Test {
void method(int arg0) {
if (arg0 == 0) {
System.out.println("if");
}
else if (arg0 == 1) {
System.out.println("else if");
}
else {
System.out.println("else");
}
}
}
"""
)
)
@Issue("https://github.com/openrewrite/rewrite/issues/2469")
@Test
fun elseNotOnNewLine() = rewriteRun(
{ spec ->
spec.parser(
JavaParser.fromJavaVersion().styles(
namedStyles(listOf(IntelliJ.spaces().run {
withBeforeKeywords(beforeKeywords.run {
withElseKeyword(true)
})
}))
)
).recipe(toRecipe {WrappingAndBracesVisitor(WrappingAndBracesStyle(WrappingAndBracesStyle.IfStatement(false)))}
.doNext(Spaces())
.doNext(TabsAndIndents()))
},
java("""
public class Test {
void method(int arg0) {
if (arg0 == 0) {
System.out.println("if");
}
else if (arg0 == 1) {
System.out.println("else if");
}
else {
System.out.println("else");
}
}
}
""",
"""
public class Test {
void method(int arg0) {
if (arg0 == 0) {
System.out.println("if");
} else if (arg0 == 1) {
System.out.println("else if");
} else {
System.out.println("else");
}
}
}
"""
)
)
}
| 0 | null | 0 | 0 | ff1173fd900e7b93dbb4dbec643b4c5adba5f268 | 11,590 | rewrite | Apache License 2.0 |
components/time-support/src/main/kotlin/org/cloudfoundry/credhub/util/InstantMillisecondsConverter.kt | cloudfoundry | 57,061,988 | false | null | package org.cloudfoundry.credhub.util
import java.time.Instant
import javax.persistence.AttributeConverter
class InstantMillisecondsConverter : AttributeConverter<Instant, Long> {
override fun convertToDatabaseColumn(attribute: Instant): Long? {
return attribute.toEpochMilli()
}
override fun convertToEntityAttribute(dbData: Long?): Instant {
return Instant.ofEpochMilli(dbData!!)
}
}
| 8 | null | 68 | 237 | 56a4b4209b9a324df6a8e49cd1b4f628d85fc21e | 422 | credhub | Apache License 2.0 |
app/src/main/java/com/goldze/mvvmhabit/aioui/scan/qrcode/QRCodeModel.kt | fengao1004 | 505,038,355 | false | {"Java Properties": 2, "Gradle": 6, "Shell": 1, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Text": 4, "Ignore List": 4, "Proguard": 3, "Java": 214, "XML": 141, "Kotlin": 158} | package com.goldze.mvvmhabit.aioui.scan.qrcode
import android.app.Application
import android.content.Intent
import android.graphics.Bitmap
import android.text.TextUtils
import com.goldze.mvvmhabit.R
import com.goldze.mvvmhabit.aioui.http.HttpRepository
import com.goldze.mvvmhabit.aioui.webview.WebViewFromUrlActivityA
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
import me.goldze.mvvmhabit.base.BaseViewModel
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
/**
* Created by Android Studio.
* User: fengao
* Date: 2022/6/19
* Time: 4:56 下午
*/
class QRCodeModel(application: Application) : BaseViewModel<HttpRepository>(application) {
var mobileUrl = ""
var deviceUrl = ""
var reportId = 0L
var start: BindingCommand<String> = BindingCommand(BindingAction {
var intent = Intent(activity, WebViewFromUrlActivityA::class.java)
intent.putExtra("title", "情绪分析")
intent.putExtra("url", deviceUrl)
intent.putExtra("id", reportId)
activity.startActivity(intent)
activity.finish()
})
var exit: BindingCommand<String> = BindingCommand(BindingAction {
(activity as QRCodeActivity).gotoScan()
})
// 使用 ZXing 生成二维码
fun getUrlQRCode(): Bitmap? {
if (TextUtils.isEmpty(mobileUrl)) {
return null
}
val bitMatrix = MultiFormatWriter().encode(mobileUrl, BarcodeFormat.QR_CODE, 512, 512)
val width = bitMatrix.width
val height = bitMatrix.height
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
for (x in 0 until width) {
for (y in 0 until height) {
val color: Int = if (bitMatrix[x, y])
activity.resources.getColor(R.color.black)
else
activity.resources.getColor(R.color.white)
bitmap.setPixel(x, y, color)
}
}
return bitmap
}
} | 1 | null | 1 | 1 | 1099bd7bfcf8a81d545567ae875b3528aa5fb1cd | 2,037 | AIO | Apache License 2.0 |
core/src/main/kotlin/com/krake/core/media/task/ProgressMediaInfoViewer.kt | LaserSrl | 165,023,586 | false | {"Gradle": 23, "Text": 3, "INI": 20, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "XML": 512, "JSON": 4, "Java": 163, "Kotlin": 393, "Proguard": 2, "Groovy": 2} | package com.krake.core.media.task
import android.graphics.Bitmap
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import androidx.annotation.DrawableRes
import com.krake.core.R
import com.krake.core.media.MediaLoadable
import com.krake.core.media.MediaType
import com.krake.core.media.UploadableMediaInfo
import java.lang.ref.WeakReference
/**
* [MediaInfoPreviewTask.Viewer] used for load a [Bitmap] into an [ImageView]
* and handle the visibility of a [ProgressBar] and a container [ViewGroup]
* if the bitmap passed is null then show a generic placeholder
*/
class ProgressMediaInfoViewer(imageView: ImageView,
progressBar: ProgressBar,
container: ViewGroup?) : MediaInfoPreviewTask.Viewer {
private val imageViewRef = WeakReference(imageView)
private var progressBarRef = WeakReference(progressBar)
private var containerRef: WeakReference<ViewGroup>? = container?.let { WeakReference(it) }
@MediaType
private var mediaType: Int = 0
override fun onInitLoad(mediaInfo: UploadableMediaInfo) {
mediaType = mediaInfo.type
containerRef?.get()?.visibility = View.GONE
progressBarRef.get()?.visibility = View.VISIBLE
}
override fun onLoadSuccess(bitmap: Bitmap) {
//if the thumbnail is null set the placeholder
imageViewRef.get()?.setImageBitmap(bitmap)
finishLoad()
}
override fun onLoadError() {
imageViewRef.get()?.let { imageView ->
//if the thumbnail is null set the placeholder
imageView.setImageResource(getPlaceholderResource(imageView, mediaType))
}
finishLoad()
}
private fun finishLoad() {
progressBarRef.get()?.visibility = View.GONE
containerRef?.get()?.visibility = View.VISIBLE
}
/**
* Ottiene il placeholder a partire dal tipo del media e dagli attributi custom dell'ImageView, se presenti
*
* @param imageView ImageView in cui verrà settato il placeholder (utilizzata solo per fare delle verifiche su [MediaLoadable]
* @param mediaType tipo del media
* @return risorsa del placeholder
*/
@DrawableRes
private fun getPlaceholderResource(imageView: ImageView, @MediaType mediaType: Int): Int {
return if (imageView is MediaLoadable && imageView.showPlaceholder()) {
when (mediaType) {
MediaType.IMAGE -> imageView.photoPlaceholder
MediaType.VIDEO -> imageView.videoPlaceholder
MediaType.AUDIO -> imageView.audioPlaceholder
else -> 0
}
} else {
when (mediaType) {
MediaType.IMAGE -> R.drawable.photo_placeholder
MediaType.VIDEO -> R.drawable.video_placeholder
MediaType.AUDIO -> R.drawable.audio_placeholder
else -> 0
}
}
}
} | 1 | null | 1 | 1 | 51b97524ff72273227d029faf06acbef0f2699f8 | 2,990 | KrakeAndroid | Apache License 2.0 |
app/src/main/java/crux/bphc/cms/glide/SvgModule.kt | crux-bphc | 76,649,862 | false | null | package crux.bphc.cms.glide
import android.content.Context
import android.graphics.drawable.PictureDrawable
import com.bumptech.glide.Glide
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule
import com.caverock.androidsvg.SVG
import java.io.InputStream
/**
* An Svg Module for Glide that uses AndroidSVG to parse SVG images.
*/
@GlideModule
class SvgModule : AppGlideModule() {
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
registry.register(SVG::class.java, PictureDrawable::class.java, SvgDrawableTranscoder())
.append(InputStream::class.java, SVG::class.java, SvgDecoder());
}
override fun isManifestParsingEnabled(): Boolean {
return false
}
}
| 30 | null | 40 | 27 | a2e229378afddb4771757263630e0869ecfd4067 | 824 | CMS-Android | MIT License |
riistaandroid/src/main/java/fi/riista/mobile/feature/groupHunting/harvests/EditGroupHarvestFragment.kt | suomenriistakeskus | 78,840,058 | false | null | package fi.riista.mobile.feature.groupHunting.harvests
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import fi.riista.common.domain.groupHunting.GroupHuntingHarvestOperationResponse
import fi.riista.common.domain.groupHunting.model.GroupHuntingHarvest
import fi.riista.common.domain.groupHunting.model.GroupHuntingHarvestId
import fi.riista.common.domain.groupHunting.model.GroupHuntingHarvestTarget
import fi.riista.common.domain.groupHunting.ui.groupHarvest.modify.EditGroupHarvestController
import fi.riista.mobile.R
import fi.riista.mobile.ui.AlertDialogFragment
import fi.riista.mobile.ui.DelegatingAlertDialogListener
import fi.riista.mobile.ui.AlertDialogId
import kotlinx.coroutines.*
/**
* A fragment for either approving a proposed [GroupHuntingHarvest] or
* editing an already accepted [GroupHuntingHarvest].
*/
class EditGroupHarvestFragment
: ModifyGroupHarvestFragment<EditGroupHarvestController, EditGroupHarvestFragment.Manager>()
{
interface Manager : BaseManager {
val editGroupHarvestController: EditGroupHarvestController
val groupHuntingHarvestTarget: GroupHuntingHarvestTarget
fun onSavingHarvest()
fun onHarvestSaveCompleted(success: Boolean, harvestId: GroupHuntingHarvestId?, createObservation: Boolean, indicatorsDismissed: () -> Unit = {})
}
enum class Mode {
APPROVE,
EDIT
}
private lateinit var dialogListener: AlertDialogFragment.Listener
private lateinit var mode: Mode
private var saveScope: CoroutineScope? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = super.onCreateView(inflater, container, savedInstanceState)
mode = getModeFromArgs(arguments)
setViewTitle(
when (mode) {
Mode.APPROVE -> R.string.group_hunting_approve_proposed_harvest
Mode.EDIT -> R.string.edit
}
)
saveButton.setText(
when (mode) {
Mode.APPROVE -> R.string.group_hunting_approve
Mode.EDIT -> R.string.save
}
)
dialogListener = DelegatingAlertDialogListener(requireActivity()).apply {
registerPositiveCallback(AlertDialogId.EDIT_GROUP_HARVEST_FRAGMENT_CREATE_OBSERVATION_QUESTION) { value ->
value?.toLong().let { harvestId ->
manager.onHarvestSaveCompleted(success = true, harvestId = harvestId, createObservation = false)
}
}
registerNegativeCallback(AlertDialogId.EDIT_GROUP_HARVEST_FRAGMENT_CREATE_OBSERVATION_QUESTION) { value ->
value?.toLong().let { harvestId ->
manager.onHarvestSaveCompleted(success = true, harvestId = harvestId, createObservation = true)
}
}
}
return view
}
override fun onPause() {
super.onPause()
saveScope?.cancel()
}
override fun onSaveButtonClicked() {
manager.onSavingHarvest()
val scope = MainScope()
scope.launch {
val result = when (mode) {
Mode.APPROVE -> controller.acceptHarvest()
Mode.EDIT -> controller.updateHarvest()
}
// allow cancellation to take effect i.e don't continue updating UI
// if saveScope has been cancelled
yield()
if (result is GroupHuntingHarvestOperationResponse.Success) {
if (!isResumed) {
return@launch
}
val shouldCreateObservation = (mode == Mode.APPROVE) && controller.shouldCreateObservation()
if (shouldCreateObservation) {
AlertDialogFragment.Builder(
requireContext(),
AlertDialogId.EDIT_GROUP_HARVEST_FRAGMENT_CREATE_OBSERVATION_QUESTION
)
.setMessage(R.string.group_hunting_create_observation_from_harvest)
.setPositiveButton(R.string.yes, result.harvest.id.toString())
.setNegativeButton(R.string.no, result.harvest.id.toString())
.build()
.show(requireActivity().supportFragmentManager)
} else {
manager.onHarvestSaveCompleted(success = true, harvestId = result.harvest.id, createObservation = false)
}
} else {
manager.onHarvestSaveCompleted(success = false, harvestId = null, createObservation = false) {
if (!isResumed) {
return@onHarvestSaveCompleted
}
AlertDialogFragment.Builder(
requireContext(),
AlertDialogId.EDIT_GROUP_HARVEST_FRAGMENT_HARVEST_SAVE_FAILED
)
.setMessage(R.string.group_hunting_harvest_save_failed_generic)
.setPositiveButton(R.string.ok)
.build()
.show(requireActivity().supportFragmentManager)
}
}
}
saveScope = scope
}
override fun getManagerFromContext(context: Context): Manager {
return context as Manager
}
override fun getControllerFromManager(): EditGroupHarvestController {
return manager.editGroupHarvestController
}
companion object {
private const val ARGS_MODE = "EGHF_args_mode"
fun create(mode: Mode): EditGroupHarvestFragment {
return EditGroupHarvestFragment().apply {
arguments = Bundle().apply {
putString(ARGS_MODE, mode.toString())
}
}
}
private fun getModeFromArgs(arguments: Bundle?): Mode {
return Mode.valueOf(requireNotNull(arguments?.getString(ARGS_MODE)))
}
}
}
| 0 | Kotlin | 0 | 3 | 23645d1abe61c68d649b6d0ca1d16556aa8ffa16 | 6,197 | oma-riista-android | MIT License |
app/src/main/java/com/nicopasso/kotlinplayground/DSLs/Models.kt | nicopasso | 118,920,023 | false | null | package com.nicopasso.kotlinplayground.DSLs
data class Handover(var id: Int? = null,
var items: MutableList<Item> = mutableListOf()) {
operator fun Item.unaryPlus(): Unit {
items.add(this)
}
}
data class Item(var id: Int? = null,
var name: String? = null)
/*
HANDOVER ITEMS w/o DSL
*/
val boringHandover = Handover(id = 1234, items = mutableListOf(
Item(id = 1234, name = "SHS 200W"),
Item(id = 45677, name = "Solar Radio"),
Item(id = 98766, name = "Light Bulb")
))
/*
HANDOVER ITEMS with DSL
*/
fun handoverItem(block: Item.() -> Unit) = Item().apply(block)
val handoverItem = handoverItem {
id = 12345
name = "SHS 200W"
}
/*
HANDOVER with DSL
*/
fun handover(block: Handover.() -> Unit) = Handover().apply(block)
val handover = handover {
id = 987654
val item1 = handoverItem {
id = 333444
name = "TV 14'"
}
val item2 = handoverItem {
id = 555566666
name = "Solar Radio"
}
val item3 = handoverItem {
id = 77788888
name = "Light Bulb"
}
items.add(item1)
items.add(item2)
items.add(item3)
}
/*
HANDOVER with DSL and Unary plus operator
*/
val fancierHandover = handover {
id = 789872392
+handoverItem { id = 333444; name = "TV 14'" }
+handoverItem { id = 555566666; name = "Solar Radio" }
+handoverItem { id = 77788888; name = "Light Bulb"}
}
| 0 | Kotlin | 0 | 0 | 6272d423ccc95c6eeae72f9a80b5f9919be39814 | 1,671 | KotlinPlayground | MIT License |
core/src/rustyengine/resources/ShaderLoader.kt | eyneill777 | 51,181,302 | false | null | package rustyengine.resources;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.assets.loaders.SynchronousAssetLoader;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.Array;
import com.esotericsoftware.minlog.Log;
class ShaderLoader(fileHandleResolver: FileHandleResolver) :
SynchronousAssetLoader<ShaderProgram, ShaderParameter>(fileHandleResolver) {
override fun load(assetManager: AssetManager, fileName: String, file: FileHandle, parameter: ShaderParameter?):
ShaderProgram {
val dir = file.parent()
val program = ShaderProgram(dir.child(file.name() + ".vert"), dir.child(file.name() + ".frag"))
if (!program.isCompiled) {
Log.error(program.log)
}
return program
}
override fun getDependencies(fileName: String, file: FileHandle, parameter: ShaderParameter?):
Array<AssetDescriptor<Any>> = Array()
}
| 1 | null | 1 | 1 | 1e22436d0860f9950d2f2e4fed984e9623b9b0db | 1,114 | SpacePirates | MIT License |
kotlin-common/src/main/java/com/zhouhaoo/common/extensions/ToastExt.kt | zhouhaoo | 110,637,983 | false | {"Kotlin": 138591, "Java": 1347} | /*
* Copyright (c) 2018 zhouhaoo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zhouhaoo.common.extensions
import android.content.Context
import android.support.annotation.StringRes
import android.widget.Toast
/**
* Created by zhou on 2018/3/30.
*/
inline fun Context.toast(text: CharSequence): Toast = Toast.makeText(this, text, Toast.LENGTH_SHORT).apply { show() }
inline fun Context.longToast(text: CharSequence): Toast = Toast.makeText(this, text, Toast.LENGTH_LONG).apply { show() }
inline fun Context.toast(@StringRes resId: Int): Toast = Toast.makeText(this, resId, Toast.LENGTH_SHORT).apply { show() }
inline fun Context.longToast(@StringRes resId: Int): Toast = Toast.makeText(this, resId, Toast.LENGTH_LONG).apply { show() } | 1 | Kotlin | 1 | 10 | 73c95dd5032c0d7b91a9bacd9db03cebf5afc118 | 1,277 | kotlin-common | Apache License 2.0 |
core/src/main/java/com/variant_gson/core/internal/JavaVersion.kt | ZuiRenA | 319,275,239 | false | null | package com.variant_gson.core.internal
import java.lang.NumberFormatException
/**
* Come from Gson
*
*
* Utility to check the major Java version of the current JVM.
*/
object JavaVersion {
val majorJavaVersion: Int get() {
val javaVersion = System.getProperty("java.version")
return getMajorJavaVersion(javaVersion)
}
@JvmStatic
fun isJava9OrLater() = majorJavaVersion >= 9
// Visible for testing only
private fun getMajorJavaVersion(javaVersion: String): Int {
var version = parseDotted(javaVersion)
if (version == -1) {
version = extractBeginningInt(javaVersion)
}
return if (version == -1) 6 else version
}
// Parses both legacy 1.8 style and newer 9.0.4 style
private fun parseDotted(javaVersion: String): Int = try {
val parts = javaVersion.split("[._]".toRegex())
val firstVer = parts[0].toInt()
if (firstVer == 1 && parts.size > 1) {
parts[1].toInt()
} else {
firstVer
}
} catch (e: NumberFormatException) {
-1
}
private fun extractBeginningInt(javaVersion: String): Int = try {
val num = StringBuilder()
for (c in javaVersion) {
if (Character.isDigit(c)) {
num.append(c)
} else {
break
}
}
num.toString().toInt()
} catch (e: NumberFormatException) {
-1
}
} | 1 | null | 1 | 1 | bcd39c393a85340e45e9a85c3911091153ccf737 | 1,482 | VariantGson | MIT License |
product-service/src/main/kotlin/br/com/maccommerce/productservice/domain/service/impl/CategoryServiceImpl.kt | wellingtoncosta | 251,454,379 | false | {"Text": 1, "Markdown": 4, "Batchfile": 3, "Shell": 3, "Maven POM": 1, "Dockerfile": 3, "Ignore List": 3, "INI": 10, "Java": 34, "SQL": 3, "Gradle Kotlin DSL": 4, "Kotlin": 77, "XML": 2} | package br.com.maccommerce.productservice.domain.service.impl
import br.com.maccommerce.productservice.domain.entity.Category
import br.com.maccommerce.productservice.domain.repository.CategoryRepository
import br.com.maccommerce.productservice.domain.service.CategoryService
class CategoryServiceImpl(
repository: CategoryRepository
) : CategoryService, CrudServiceImpl<Category>(repository)
| 0 | Kotlin | 0 | 1 | f25c2157e5ffe362e405a145e4889b4e9166897d | 399 | maccommerce | MIT License |
src/main/kotlin/org/taktik/couchdb/handlers/RFC1123DateTimeDeserializer.kt | icure | 512,831,778 | false | {"Kotlin": 215586, "JavaScript": 7399} | package org.taktik.couchdb.handlers
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
class RFC1123DateTimeDeserializer : JsonDeserializer<ZonedDateTime>() {
override fun deserialize(
p: JsonParser?,
ctxt: DeserializationContext?
): ZonedDateTime = ZonedDateTime.parse(p?.valueAsString, DateTimeFormatter.RFC_1123_DATE_TIME)
}
| 3 | Kotlin | 1 | 0 | 99d7e39b96277316f81c792e65dc86097895d6eb | 545 | krouch | Apache License 2.0 |
app/src/main/java/it/polito/timebanking/fragments/ShowProfileFragment.kt | tndevelop | 586,483,147 | false | null | package it.polito.timebanking.fragments
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.navigation.fragment.findNavController
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import it.polito.timebanking.R
import it.polito.timebanking.database.User
import it.polito.timebanking.viewmodels.UserViewModel
import org.json.JSONObject
import java.io.File
class ShowProfileFragment: Fragment(R.layout.fragment_show_profile) {
val userViewModel by activityViewModels<UserViewModel>()
lateinit var user: LiveData<User>
lateinit var nicknameTextView: TextView
lateinit var ratingTextView: TextView
lateinit var descriptionTextView: TextView
lateinit var emailTextView2: TextView
lateinit var fullnameTextView2: TextView
lateinit var locationTextView2: TextView
lateinit var timeCreditTextView: TextView
lateinit var profileImageView: ImageView
lateinit var loadingSpinner: ProgressBar
lateinit var ratingBar: RatingBar
lateinit var skillsGridView: GridView
lateinit var reviewsCardView: CardView
lateinit var skillsAdapter: ArrayAdapter<String>
lateinit var skillsArray: ArrayList<String>
lateinit var ppImage: String
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
init(view)
//Loading user's data from database
userViewModel.user.observe(viewLifecycleOwner) {
if (it == null) {
setNoUserDetails()
} else {
setUserDetails(it)
}
skillsAdapter = ArrayAdapter(requireContext(), R.layout.skill_item, R.id.textview, skillsArray)
skillsGridView.adapter = skillsAdapter
skillsGridView.emptyView = view.findViewById(R.id.emptyTextView)
skillsGridView.stopNestedScroll()
skillsGridView.layoutParams.height = (40 * ((skillsArray.size + 10) / 2) as Int)
}
}
private fun init(view: View) {
nicknameTextView = view.findViewById(R.id.nicknameTextView)
ratingTextView = view.findViewById(R.id.ratingTextView)
descriptionTextView = view.findViewById(R.id.descriptionTextView)
emailTextView2 = view.findViewById(R.id.emailTextView2)
fullnameTextView2 = view.findViewById(R.id.fullnameTextView2)
locationTextView2 = view.findViewById(R.id.locationTextView2)
ratingBar = view.findViewById(R.id.ratingBar)
skillsGridView = view.findViewById(R.id.skillsGridView)
profileImageView = view.findViewById(R.id.avatarImageView)
timeCreditTextView = view.findViewById(R.id.time_credit_value_text_view)
reviewsCardView = view.findViewById(R.id.reviewsCardView)
reviewsCardView.visibility = View.GONE
// Set up loading spinner
loadingSpinner = view.findViewById(R.id.loadingSpinner)
}
private fun setNoUserDetails() {
nicknameTextView.text = ""
ratingBar.rating = 0f
ratingTextView.text = "${ratingBar.rating} stars"
descriptionTextView.text = ""
emailTextView2.text = ""
fullnameTextView2.text = ""
locationTextView2.text = "Torino"
timeCreditTextView.text = "05:00"
skillsArray = arrayListOf(*"Crafting,Babysitting".split(",").toTypedArray())
ppImage = ""
profileImageView.setImageDrawable(resources.getDrawable(R.drawable.avatar))
loadingSpinner.visibility = View.GONE
}
private fun setUserDetails(it: User) {
nicknameTextView.text = it.nickname
ratingBar.rating = it.rating
ratingTextView.text = "${it.rating} stars"
descriptionTextView.text = it.description
emailTextView2.text = it.email
fullnameTextView2.text = it.fullName
locationTextView2.text = it.location
val creditHours = it.credit / 60
val creditMins = it.credit - creditHours*60
timeCreditTextView.text = String.format("%02d:%02d",creditHours, creditMins)
if(it.skillsArray.isNullOrEmpty())
skillsArray = arrayListOf()
else
skillsArray = arrayListOf(*it.skillsArray.split(",").toTypedArray())
ppImage = ""
if(!it.imagePath.isEmpty()) {
if(!it.imagePath.contains("profileImages"))
it.imagePath = "/profileImages/${it.imagePath.split("/").last()}"
ppImage = it.imagePath
getProfilePicFromFirebaseStorage(it.imagePath)
} else {
// Set default image
profileImageView.setImageDrawable(resources.getDrawable(R.drawable.avatar))
loadingSpinner.visibility = View.GONE
}
}
private fun getProfilePicFromFirebaseStorage(imagePath: String) {
val storage = FirebaseStorage.getInstance()
val gsReference = storage.getReferenceFromUrl("gs://labs-1b5fa.appspot.com/")
val imageRef : StorageReference = gsReference.child("/profileImages/${imagePath.split("/").last()}")
val ONE_MEGABYTE: Long = 1024 * 1024
imageRef.getBytes(ONE_MEGABYTE).addOnSuccessListener {
// // Update profile image view
profileImageView.setImageBitmap(BitmapFactory.decodeByteArray(it, 0, it.size))
loadingSpinner.visibility = View.GONE
}.addOnFailureListener {
// Handle any errors
loadingSpinner.visibility = View.GONE
Log.e("Firestore", "Error loading profile image: " + it.toString())
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_edit, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_item_edit -> {
editProfile()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun editProfile() {
findNavController().navigate(R.id.action_showFragment_to_editFragment)
}
} | 0 | Kotlin | 1 | 1 | edb734d5bf2aa391e7012d45447a8ba4bf5489e4 | 6,669 | Android-Timebanking | MIT License |
app/src/main/java/com/bike/race/utils/ViewUtils.kt | praslnx8 | 497,069,010 | false | null | package com.bike.race.utils
import androidx.appcompat.app.AppCompatDelegate
import com.bike.race.domain.preference.UserPreferenceManager
object ViewUtils {
fun setTheme(themeStyle: UserPreferenceManager.ThemeStyle) {
when (themeStyle) {
UserPreferenceManager.ThemeStyle.AUTO -> AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
)
UserPreferenceManager.ThemeStyle.LIGHT -> AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_NO
)
UserPreferenceManager.ThemeStyle.DARK -> AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES
)
}
}
} | 0 | Kotlin | 0 | 6 | c52bc1c958435212319e3d971fa20b5d0f5f53a6 | 745 | Topsed-Speedometer | Apache License 2.0 |
app/src/androidTest/java/org/fossasia/susi/ai/login/WelcomeActivityTest.kt | fossasia | 68,798,776 | false | null | package org.fossasia.susi.ai.login
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.isDisplayed
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.filters.MediumTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.util.Log
import android.view.WindowManager
import org.fossasia.susi.ai.R
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import timber.log.Timber
import java.io.IOException
/**
* Created by collinx on 22-10-2017.
*/
@RunWith(AndroidJUnit4::class)
@MediumTest
class WelcomeActivityTest {
@Rule
@JvmField
val mActivityRule = ActivityTestRule(WelcomeActivity::class.java)
@Before
@Throws(IOException::class, InterruptedException::class)
fun unlockScreen() {
Timber.d("running unlockScreen..")
val activity = mActivityRule.activity
val wakeUpDevice = Runnable {
activity.window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
activity.runOnUiThread(wakeUpDevice)
}
@Test
fun testUIViewsPresenceOnLoad() {
Timber.d("running testUIViewsPresenceOnLoad..")
// checks if viewpager is displayed or not
onView(withId(R.id.pager)).check(matches(isDisplayed()))
// checks if tab layout is shown or not
onView(withId(R.id.tabDots)).check(matches(isDisplayed()))
// checks if next button is present
onView(withId(R.id.btn_next)).check(matches(isDisplayed()))
// checks if skip button is present
onView(withId(R.id.btn_skip)).check(matches(isDisplayed()))
}
} | 81 | Kotlin | 1131 | 2,391 | a3409051185d4624e65f7df7847e2fca0910cebe | 1,981 | susi_android | Apache License 2.0 |
domain/src/main/kotlin/no/nav/su/se/bakover/domain/vilkår/bosituasjon/KunneIkkeLeggeTilBosituasjon.kt | navikt | 227,366,088 | false | null | package no.nav.su.se.bakover.domain.vilkår.bosituasjon
import no.nav.su.se.bakover.domain.behandling.Stønadsbehandling
import no.nav.su.se.bakover.domain.grunnlag.Konsistensproblem
import no.nav.su.se.bakover.domain.grunnlag.KunneIkkeLageGrunnlagsdata
import no.nav.su.se.bakover.domain.revurdering.Revurdering
import kotlin.reflect.KClass
sealed interface KunneIkkeLeggeTilBosituasjon {
data class Valideringsfeil(val feil: KunneIkkeLageGrunnlagsdata) : KunneIkkeLeggeTilBosituasjon
data class UgyldigTilstand(
val fra: KClass<out Stønadsbehandling>,
val til: KClass<out Stønadsbehandling>,
) : KunneIkkeLeggeTilBosituasjon
data class Konsistenssjekk(val feil: Konsistensproblem.Bosituasjon) : KunneIkkeLeggeTilBosituasjon
data class KunneIkkeOppdatereFormue(val feil: Revurdering.KunneIkkeLeggeTilFormue) : KunneIkkeLeggeTilBosituasjon
data object PerioderMangler : KunneIkkeLeggeTilBosituasjon
}
| 2 | Kotlin | 1 | 1 | fbeb1614c40e0f6fce631d4beb1ba25e2f78ddda | 942 | su-se-bakover | MIT License |
src/main/kotlin/com/github/dangerground/Day6.kt | dangerground | 226,153,955 | false | null | package com.github.dangerground
class Day6(directOrbits: MutableList<String>) {
private val orbits = HashMap<String, String>()
init {
directOrbits.forEach {
val objects = it.split(")")
orbits[objects[1]] = objects[0]
}
}
private fun countOrbit(obj: String?): Int {
if (obj == "COM" || obj == null) {
return 0
}
return countOrbit(orbits[obj]) + 1
}
fun countOrbits(): Int {
var total = 0
orbits.forEach { (key, value) ->
// println("$key -> $value")
total += countOrbit(key)
}
return total
}
private fun findWay(obj: String): ArrayList<String> {
val path = ArrayList<String>()
var current : String? = obj
do {
current = orbits[current]
if (current != null) {
path.add(current)
} else break
} while (current != "COM")
return path
}
fun countMinimalDistance(): Int {
val you = findWay("YOU").reversed()
val san = findWay("SAN").reversed()
for (i in 0..you.size) {
if (you[i] != san[i]) {
return you.size - i + san.size - i
}
}
return 0
}
} | 0 | Kotlin | 0 | 1 | 125d57d20f1fa26a0791ab196d2b94ba45480e41 | 1,300 | adventofcode | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.