path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/andrii_a/walleria/ui/common/components/SingleChoiceSelector.kt | andrew-andrushchenko | 525,795,850 | false | {"Kotlin": 656065} | package com.andrii_a.walleria.ui.common.components
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.remember
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.graphics.lerp
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlin.math.absoluteValue
private const val ANIMATION_DURATION_MILLIS = 500
@Stable
interface SingleChoiceSelectorState {
val selectedIndex: Float
val startCornerPercent: Int
val endCornerPercent: Int
val textColors: List<Color>
fun selectOption(scope: CoroutineScope, index: Int)
}
@Stable
class SingleChoiceSelectorStateImpl(
options: List<SingleChoiceSelectorItem>,
selectedOptionOrdinal: Int,
private val selectedColor: Color,
private val unselectedColor: Color,
) : SingleChoiceSelectorState {
override val selectedIndex: Float
get() = _selectedIndex.value
override val startCornerPercent: Int
get() = _startCornerPercent.value.toInt()
override val endCornerPercent: Int
get() = _endCornerPercent.value.toInt()
override val textColors: List<Color>
get() = _textColors.value
private var _selectedIndex = Animatable(selectedOptionOrdinal.toFloat())
private var _startCornerPercent = Animatable(
if (selectedOptionOrdinal == 0) {
50f
} else {
15f
}
)
private var _endCornerPercent = Animatable(
if (selectedOptionOrdinal == options.size - 1) {
50f
} else {
15f
}
)
private var _textColors: State<List<Color>> = derivedStateOf {
List(numOptions) { index ->
lerp(
start = unselectedColor,
stop = selectedColor,
fraction = 1f - (((selectedIndex - index.toFloat()).absoluteValue).coerceAtMost(1f))
)
}
}
private val numOptions = options.size
private val animationSpec = tween<Float>(
durationMillis = ANIMATION_DURATION_MILLIS,
easing = FastOutSlowInEasing,
)
override fun selectOption(scope: CoroutineScope, index: Int) {
scope.launch {
_selectedIndex.animateTo(
targetValue = index.toFloat(),
animationSpec = animationSpec,
)
}
scope.launch {
_startCornerPercent.animateTo(
targetValue = if (index == 0) 50f else 15f,
animationSpec = animationSpec,
)
}
scope.launch {
_endCornerPercent.animateTo(
targetValue = if (index == numOptions - 1) 50f else 15f,
animationSpec = animationSpec,
)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SingleChoiceSelectorStateImpl
if (selectedColor != other.selectedColor) return false
if (unselectedColor != other.unselectedColor) return false
if (_selectedIndex != other._selectedIndex) return false
if (_startCornerPercent != other._startCornerPercent) return false
if (_endCornerPercent != other._endCornerPercent) return false
if (numOptions != other.numOptions) return false
if (animationSpec != other.animationSpec) return false
return true
}
override fun hashCode(): Int {
var result = selectedColor.hashCode()
result = 31 * result + unselectedColor.hashCode()
result = 31 * result + _selectedIndex.hashCode()
result = 31 * result + _startCornerPercent.hashCode()
result = 31 * result + _endCornerPercent.hashCode()
result = 31 * result + numOptions
result = 31 * result + animationSpec.hashCode()
return result
}
}
@Composable
fun rememberSingleChoiceSelectorState(
options: List<SingleChoiceSelectorItem>,
selectedOptionOrdinal: Int,
selectedColor: Color,
unSelectedColor: Color,
) = remember {
SingleChoiceSelectorStateImpl(
options,
selectedOptionOrdinal,
selectedColor,
unSelectedColor,
)
}
enum class SelectorItemType {
IconAndText,
IconOnly,
TextOnly
}
data class SingleChoiceSelectorItem(
@StringRes val titleRes: Int = 0,
@DrawableRes val iconRes: Int = 0,
val type: SelectorItemType = SelectorItemType.TextOnly
)
private enum class SelectorOption {
Option,
Background
}
@Composable
fun SingleChoiceSelector(
options: List<SingleChoiceSelectorItem>,
selectedOptionOrdinal: Int,
onOptionSelect: (Int) -> Unit,
modifier: Modifier = Modifier,
selectedColor: Color = MaterialTheme.colorScheme.primaryContainer,
unselectedColor: Color = MaterialTheme.colorScheme.primary,
state: SingleChoiceSelectorState = rememberSingleChoiceSelectorState(
options = options,
selectedOptionOrdinal = selectedOptionOrdinal,
selectedColor = selectedColor,
unSelectedColor = unselectedColor,
),
) {
require(options.size >= 2) { "This composable requires at least 2 options" }
require(selectedOptionOrdinal < options.size) { "Invalid selected option [$selectedOptionOrdinal]" }
LaunchedEffect(key1 = options, key2 = selectedOptionOrdinal) {
state.selectOption(this, selectedOptionOrdinal)
}
Layout(
modifier = modifier
.clip(
shape = RoundedCornerShape(percent = 50)
)
.background(Color.Transparent),
content = {
val colors = state.textColors
options.forEachIndexed { index, option ->
Box(
modifier = Modifier
.layoutId(SelectorOption.Option)
.clickable { onOptionSelect(index) },
contentAlignment = Alignment.Center,
) {
when (option.type) {
SelectorItemType.IconAndText -> {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround
) {
Icon(
painter = painterResource(id = option.iconRes),
tint = colors[index],
contentDescription = null
)
Text(
text = stringResource(id = option.titleRes),
style = MaterialTheme.typography.bodyMedium,
color = colors[index],
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 4.dp),
)
}
}
SelectorItemType.IconOnly -> {
Icon(
painter = painterResource(id = option.iconRes),
tint = colors[index],
contentDescription = null
)
}
SelectorItemType.TextOnly -> {
Text(
text = stringResource(id = option.titleRes),
style = MaterialTheme.typography.bodyMedium,
color = colors[index],
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 4.dp),
)
}
}
}
}
Box(
modifier = Modifier
.layoutId(SelectorOption.Background)
.clip(
shape = RoundedCornerShape(
topStartPercent = state.startCornerPercent,
bottomStartPercent = state.startCornerPercent,
topEndPercent = state.endCornerPercent,
bottomEndPercent = state.endCornerPercent,
)
)
.background(MaterialTheme.colorScheme.primary),
)
}
) { measurables, constraints ->
val optionWidth = constraints.maxWidth / options.size
val optionConstraints = Constraints.fixed(
width = optionWidth,
height = constraints.maxHeight,
)
val optionPlaceables = measurables
.filter { measurable -> measurable.layoutId == SelectorOption.Option }
.map { measurable -> measurable.measure(optionConstraints) }
val backgroundPlaceable = measurables
.first { measurable -> measurable.layoutId == SelectorOption.Background }
.measure(optionConstraints)
layout(
width = constraints.maxWidth,
height = constraints.maxHeight,
) {
backgroundPlaceable.placeRelative(
x = (state.selectedIndex * optionWidth).toInt(),
y = 0,
)
optionPlaceables.forEachIndexed { index, placeable ->
placeable.placeRelative(
x = optionWidth * index,
y = 0,
)
}
}
}
}
| 0 | Kotlin | 2 | 3 | c25661c610d3197390ac86b7c63295a10095e622 | 11,080 | Walleria | MIT License |
app/src/main/java/eu/darken/androidkotlinstarter/main/ui/fragment/ExampleFragment.kt | sebnapi | 147,829,801 | true | {"Kotlin": 40605, "Java": 1015} | package eu.darken.androidkotlinstarter.main.ui.fragment
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v7.widget.Toolbar
import android.view.*
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import eu.darken.androidkotlinstarter.R
import eu.darken.androidkotlinstarter.common.Check
import eu.darken.androidkotlinstarter.common.smart.SmartFragment
import eu.darken.mvpbakery.base.MVPBakery
import eu.darken.mvpbakery.base.ViewModelRetainer
import eu.darken.mvpbakery.injection.InjectedPresenter
import eu.darken.mvpbakery.injection.PresenterInjectionCallback
import javax.inject.Inject
class ExampleFragment : SmartFragment(), ExampleFragmentPresenter.View {
@BindView(R.id.toolbar) lateinit var toolbar: Toolbar
@BindView(R.id.emoji_text) lateinit var emojiText: TextView
@Inject lateinit var presenter: ExampleFragmentPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val layout = inflater.inflate(R.layout.example_fragment, container, false)
addUnbinder(ButterKnife.bind(this, layout))
return layout
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
MVPBakery.builder<ExampleFragmentPresenter.View, ExampleFragmentPresenter>()
.presenterFactory(InjectedPresenter(this))
.presenterRetainer(ViewModelRetainer(this))
.addPresenterCallback(PresenterInjectionCallback(this))
.attach(this)
super.onActivityCreated(savedInstanceState)
toolbar.setTitle(R.string.app_name)
toolbar.subtitle = null
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_main, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_help -> {
Snackbar.make(Check.notNull(view), R.string.app_name, Snackbar.LENGTH_SHORT).show()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
@OnClick(R.id.fab)
fun onFabClicked(fab: View) {
presenter.onGetNewEmoji()
}
override fun showEmoji(emoji: String) {
emojiText.text = emoji
}
companion object {
fun newInstance(): Fragment {
return ExampleFragment()
}
}
}
| 0 | Kotlin | 0 | 0 | 5af9358d805fd0d0eb1cac84362b6c9ecf917a62 | 2,759 | android-kotlin-starter | Apache License 2.0 |
mobile_app1/module364/src/main/java/module364packageKt0/Foo1851.kt | uber-common | 294,831,672 | false | null | package module364packageKt0;
annotation class Foo1851Fancy
@Foo1851Fancy
class Foo1851 {
fun foo0(){
module364packageKt0.Foo1850().foo6()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
fun foo6(){
foo5()
}
} | 6 | null | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 331 | android-build-eval | Apache License 2.0 |
src/main/kotlin/tech/kzen/shell/proxy/ProxyApi.kt | alexoooo | 128,688,439 | false | {"Kotlin": 48283} | package tech.kzen.shell.proxy
//import org.springframework.context.annotation.Bean
//import org.springframework.context.annotation.Configuration
//import org.springframework.web.reactive.function.server.router
//
//
//@Configuration
//class ProxyApi(
// private val proxyHandler: ProxyHandler
//) {
// @Bean
// fun counterRouter() = router {
// GET("/shell/project", proxyHandler::list)
// GET("/shell/project/start", proxyHandler::start)
// GET("/shell/project/stop", proxyHandler::stop)
//
// GET("/**", proxyHandler::handle)
// PUT("/**", proxyHandler::handle)
// POST("/**", proxyHandler::handle)
// }
//} | 0 | Kotlin | 0 | 0 | 57467e2d3e0cdaad2c6e5d5414233fe31f309ffa | 668 | kzen-shell | MIT License |
videopicker/src/main/java/com/crazylegend/videopicker/contracts/MultiPickerContracts.kt | FunkyMuse | 262,344,948 | false | null | package com.crazylegend.videopicker.contracts
import com.crazylegend.core.contracts.BaseContractMultiPick
import com.crazylegend.videopicker.listeners.onVideosPicked
import com.crazylegend.videopicker.pickers.MultiVideoPicker
import com.crazylegend.videopicker.videos.VideosVM
/**
* Created by crazy on 5/8/20 to long live and prosper !
*/
internal interface MultiPickerContracts : BaseContractMultiPick {
val videosVM: VideosVM
var onVideosPicked: onVideosPicked?
val errorTag: String get() = MultiVideoPicker::javaClass.name
} | 0 | Kotlin | 2 | 9 | e9a3b041b0b5a7f87fbebe4cbcbd64de4873e25b | 545 | MediaPicker | Apache License 2.0 |
app/src/main/java/com/muratozturk/mova/common/interceptor/LanguageInterceptor.kt | muratozturk5 | 587,507,400 | false | null | package com.hoangtien2k3.themoviedb.common.interceptor
import com.hoangtien2k3.themoviedb.domain.source.DataSource
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.Response
class LanguageInterceptor(private val preferenceDataSource: DataSource.Preference) : Interceptor {
override fun intercept(chain: Chain): Response {
val request = chain.request()
val languageCode = preferenceDataSource.getCurrentLanguageCode()
val url =
request.url.newBuilder().addQueryParameter(LANGUAGE, languageCode).build()
val newRequest = request.newBuilder().url(url).build()
return chain.proceed(newRequest)
}
companion object {
private const val LANGUAGE = "language"
}
}
| 1 | null | 13 | 96 | 280ced4d70d4e2f9e7c4549b5c919cc7cd821146 | 760 | Mova | MIT License |
app/src/main/java/com/ch4019/multibox/ui/screen/colorswitching/ColorSwitchingPage.kt | CH4019 | 702,447,413 | false | {"Kotlin": 72506} | package com.ch4019.multibox.ui.screen.colorswitching
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun ColorSwitchingPage() {
Column (
modifier = Modifier
.fillMaxSize()
){
}
} | 0 | Kotlin | 0 | 0 | 6b2e48cdf2611bb4fa82c97a5789ce72ca1dade9 | 359 | MultiBox | MIT License |
common/src/main/java/com/github/fajaragungpramana/morent/common/app/AppActivity.kt | fajaragungpramana | 758,782,516 | false | {"Kotlin": 60435} | package com.github.fajaragungpramana.morent.common.app
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.github.fajaragungpramana.morent.common.contract.AppState
abstract class AppActivity<VB : ViewBinding> : AppCompatActivity() {
private lateinit var _viewBinding: VB
val viewBinding: VB
get() = _viewBinding
protected abstract fun onViewBinding(): VB
protected abstract fun onCreated(savedInstanceState: Bundle?)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!::_viewBinding.isInitialized)
_viewBinding = onViewBinding()
setContentView(viewBinding.root)
onCreated(savedInstanceState)
if (this is AppState) onStateObserver()
}
} | 0 | Kotlin | 0 | 1 | ef8254d6056233e1300bdd7be10cf4304fd8d377 | 843 | android.morent | Apache License 2.0 |
analytics/src/main/java/io/appmetrica/analytics/impl/utils/PublicLogConstructor.kt | appmetrica | 650,662,094 | false | {"Gradle Kotlin DSL": 30, "Java Properties": 18, "Markdown": 74, "Shell": 13, "TOML": 1, "Text": 68, "Ignore List": 3, "Batchfile": 1, "JSON": 23, "Kotlin": 973, "Java": 1483, "XML": 78, "Proguard": 44, "CMake": 10, "C++": 1238, "C": 145, "Python": 77, "GN": 46, "Checksums": 5, "Emacs Lisp": 2, "AppleScript": 1, "INI": 6, "Diff": 3, "Git Attributes": 4, "YAML": 7, "Objective-C++": 21, "Objective-C": 10, "OpenStep Property List": 8, "Unix Assembly": 7, "Assembly": 3, "CSS": 1, "Go": 1, "Starlark": 5, "HAProxy": 4, "Makefile": 2, "SCSS": 2, "HTML": 1, "AIDL": 2, "Protocol Buffer": 23} | package io.appmetrica.analytics.impl.utils
import android.text.TextUtils
import io.appmetrica.analytics.impl.CounterReport
import io.appmetrica.analytics.impl.EventsManager
import io.appmetrica.analytics.impl.protobuf.backend.EventProto
object PublicLogConstructor {
@JvmStatic
fun constructCounterReportLog(reportData: CounterReport, message: String): String? {
return if (EventsManager.isPublicForLogs(reportData.type)) {
buildString {
append(message)
append(": ")
append(reportData.name)
if (EventsManager.shouldLogValue(reportData.type) && !TextUtils.isEmpty(reportData.value)) {
append(" with value ")
append(reportData.value)
}
}
} else {
null
}
}
@JvmStatic
fun constructEventLog(event: EventProto.ReportMessage.Session.Event, message: String): String? {
return if (EventsManager.isSuitableForLogs(event)) {
"$message: ${getLogValue(event)}"
} else {
null
}
}
private fun getLogValue(event: EventProto.ReportMessage.Session.Event): String {
return if (event.type == EventProto.ReportMessage.Session.Event.EVENT_CRASH && TextUtils.isEmpty(event.name)) {
"Native crash of app"
} else if (event.type == EventProto.ReportMessage.Session.Event.EVENT_CLIENT) {
val logValue = java.lang.StringBuilder(event.name)
if (event.value != null) {
val value = String(event.value)
if (!TextUtils.isEmpty(value)) {
logValue.append(" with value ")
logValue.append(value)
}
}
logValue.toString()
} else {
event.name
}
}
}
| 0 | Java | 5 | 53 | 89961cf3ceb94c1807558349134a04b165278e01 | 1,867 | appmetrica-sdk-android | MIT License |
app/src/main/java/com/example/pizzaapp/ui/categories/BaseCategoryFragment.kt | Malekel3alamy | 871,968,916 | false | {"Kotlin": 30637} | package com.example.pizzaapp.ui.categories
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.example.pizzaapp.R
import com.example.pizzaapp.adapters.BaseCategoryAdapter
import com.example.pizzaapp.databinding.FragmentBaseCategoryBinding
import com.example.pizzaapp.model.products.Products
import com.example.pizzaapp.utils.Resources
import com.example.pizzaapp.viewmodel.ProductsViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
@AndroidEntryPoint
open class BaseCategoryFragment : Fragment(R.layout.fragment_base_category) {
private val productsViewModel by viewModels<ProductsViewModel>()
lateinit var binding: FragmentBaseCategoryBinding
lateinit var product :Products
val productAdapter = BaseCategoryAdapter()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentBaseCategoryBinding.bind(view)
setupRV()
// moving to product details fragment
productAdapter.onProductClick={
val bundle = Bundle().apply {
putInt("product_id",it.id)
}
findNavController().navigate(R.id.action_homeFragment2_to_productDetailsFragment,bundle)
}
// getting products from view model
lifecycleScope.launch {
productsViewModel.products.collectLatest {
when(it){
is Resources.Error -> {
hidePR()
Toast.makeText(requireContext()," Error",Toast.LENGTH_SHORT).show()
}
is Resources.Loading -> {
showPR()
Log.d("Loading","Loading State")
}
is Resources.Success -> {
productAdapter.differ.submitList(it.data)
hidePR()
}
is Resources.UnSpecified -> {
}
}
}
}
}
// setup recycler view
private fun setupRV(){
binding.productsRv.adapter = productAdapter
binding.productsRv.layoutManager = GridLayoutManager(requireContext(),2)
}
private fun hidePR(){
binding.baseCategoryFragmentPR.visibility = View.INVISIBLE
}
private fun showPR(){
binding.baseCategoryFragmentPR.visibility = View.VISIBLE
}
} | 0 | Kotlin | 0 | 0 | eb3e1091bbc68c8d505720afc2c26a20c3042d58 | 2,799 | PizzaApp | MIT License |
src/main/kotlin/com/autonomousapps/DependencyAnalysisExtension.kt | stephanenicolas | 229,741,812 | true | {"Kotlin": 116771, "Java": 71861} | @file:Suppress("UnstableApiUsage")
package com.autonomousapps
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.SetProperty
import org.gradle.kotlin.dsl.setProperty
private const val ANDROID_LIB_VARIANT_DEFAULT = "debug"
internal const val JAVA_LIB_SOURCE_SET_DEFAULT = "main"
open class DependencyAnalysisExtension(objects: ObjectFactory) {
internal val theVariants: SetProperty<String> = objects.setProperty()
private val fallbacks: SetProperty<String> = objects.setProperty()
init {
theVariants.convention(listOf(ANDROID_LIB_VARIANT_DEFAULT, JAVA_LIB_SOURCE_SET_DEFAULT))
fallbacks.set(listOf(ANDROID_LIB_VARIANT_DEFAULT, JAVA_LIB_SOURCE_SET_DEFAULT))
}
fun setVariants(vararg v: String) {
theVariants.set(v.toSet())
}
fun getFallbacks() = theVariants.get() + fallbacks.get()
}
| 0 | null | 0 | 0 | ca48137d55f2a24a3e381635ecccd0ad7d6ce310 | 865 | dependency-analysis-android-gradle-plugin | Apache License 2.0 |
woodstock/src/test/kotlin/com/talkdesk/woodstock/batch/sender/HttpLogSenderTest.kt | Talkdesk | 165,652,227 | false | null | package com.talkdesk.woodstock.batch.sender
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import com.talkdesk.woodstock.Logger
import com.talkdesk.woodstock.batch.Log
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
class HttpLogSenderTest : Spek({
describe("HTTP Log Sender") {
it("should send log to a remote server via HTTP") {
val server = MockWebServer()
server.start()
server.enqueue(MockResponse().setResponseCode(204))
val extraData = mapOf(
"appId" to "AppId",
"osVersion" to "24",
"deviceName" to "Samsung S9",
"sdkVersion" to "0.0.4",
"logVersion" to "0.0.1"
)
val jsonConverterMock = mock<LogJsonConverter>()
val logSender = HttpLogSender.Builder()
.setBaseUrl(server.url("/").toString())
.setExtraDataProvider(object : ExtraDataProvider {
override fun getExtraData(): Map<String, String> = extraData
})
.build()
whenever(jsonConverterMock.convertToJson(
"2018-04-19 17:48:42.088",
Logger.LogLevel.CUSTOMER,
"Log message.",
extraData
)).thenReturn("{}")
logSender.send(Log(
"1",
Logger.LogLevel.CUSTOMER,
"Log message.",
"2018-04-19 17:48:42.088")
)
server.shutdown()
}
}
})
| 0 | Kotlin | 0 | 6 | cb4f1ca1757142d6094b9bdf6379fd87eeaf8813 | 1,744 | woodstock | Apache License 2.0 |
kmp/features/guidance/src/commonMain/kotlin/com/egoriku/grodnoroads/guidance/screen/ui/mode/chooselocation/ChooseLocation.kt | BehindWheel | 485,026,420 | false | {"Kotlin": 1186756, "Ruby": 5708, "Swift": 1889, "Shell": 830} | package com.egoriku.grodnoroads.guidance.screen.ui.mode.chooselocation
import androidx.compose.foundation.layout.Arrangement
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.padding
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.dp
import com.egoriku.grodnoroads.foundation.core.alignment.OffsetAlignment
import com.egoriku.grodnoroads.foundation.icons.GrodnoRoads
import com.egoriku.grodnoroads.foundation.icons.outlined.Close
import com.egoriku.grodnoroads.foundation.icons.outlined.Ok
import com.egoriku.grodnoroads.foundation.preview.GrodnoRoadsM3ThemePreview
import com.egoriku.grodnoroads.foundation.preview.PreviewGrodnoRoads
import com.egoriku.grodnoroads.foundation.uikit.button.PrimaryCircleButton
import com.egoriku.grodnoroads.foundation.uikit.button.PrimaryInverseCircleButton
import com.egoriku.grodnoroads.foundation.uikit.button.common.Size.Large
import com.egoriku.grodnoroads.guidance.screen.ui.mode.chooselocation.component.PinMarker
@Composable
fun ChooseLocation(
isCameraMoving: Boolean,
isChooseInDriveMode: Boolean,
onCancel: () -> Unit,
modifier: Modifier = Modifier,
onLocationSelect: (Offset) -> Unit
) {
var markerOffset = remember { Offset.Zero }
val offsetAlignment = remember {
if (isChooseInDriveMode) {
OffsetAlignment(xOffset = 0.5f, yOffset = 0.7f)
} else {
OffsetAlignment(xOffset = 0.5f, yOffset = 0.5f)
}
}
Box(modifier = modifier.fillMaxSize()) {
PinMarker(
modifier = Modifier.align(offsetAlignment),
animate = isCameraMoving,
onGloballyPosition = {
markerOffset = it
}
)
Row(
modifier = Modifier
.fillMaxWidth()
.align(Alignment.BottomCenter)
.padding(bottom = 32.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(48.dp, Alignment.CenterHorizontally)
) {
PrimaryInverseCircleButton(size = Large, onClick = onCancel) {
Icon(
imageVector = GrodnoRoads.Outlined.Close,
contentDescription = null
)
}
PrimaryCircleButton(
size = Large,
onClick = {
if (!isCameraMoving) {
onLocationSelect(markerOffset)
}
}
) {
Icon(
imageVector = GrodnoRoads.Outlined.Ok,
contentDescription = null
)
}
}
}
}
@PreviewGrodnoRoads
@Composable
private fun ChooseLocationPreview() = GrodnoRoadsM3ThemePreview {
ChooseLocation(
isCameraMoving = false,
isChooseInDriveMode = true,
onCancel = {},
onLocationSelect = {}
)
}
| 19 | Kotlin | 1 | 18 | 07b1ec1f97c6f4a4948ba28b7cd0743f8efa850a | 3,337 | BehindWheelKMP | Apache License 2.0 |
app/src/main/java/com/mapbox/maps/testapp/examples/markersandcallouts/viewannotation/ViewAnnotationWithPointAnnotationActivity.kt | mapbox | 330,365,289 | false | null | package com.mapbox.maps.testapp.examples.markersandcallouts.viewannotation
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import com.mapbox.geojson.Point
import com.mapbox.maps.CameraOptions
import com.mapbox.maps.MapView
import com.mapbox.maps.Style
import com.mapbox.maps.ViewAnnotationAnchor
import com.mapbox.maps.extension.style.layers.properties.generated.IconAnchor
import com.mapbox.maps.plugin.annotation.Annotation
import com.mapbox.maps.plugin.annotation.AnnotationConfig
import com.mapbox.maps.plugin.annotation.annotations
import com.mapbox.maps.plugin.annotation.generated.*
import com.mapbox.maps.testapp.R
import com.mapbox.maps.testapp.databinding.ActivityViewAnnotationShowcaseBinding
import com.mapbox.maps.testapp.databinding.ItemCalloutViewBinding
import com.mapbox.maps.testapp.utils.BitmapUtils
import com.mapbox.maps.viewannotation.ViewAnnotationManager
import com.mapbox.maps.viewannotation.ViewAnnotationUpdateMode
import com.mapbox.maps.viewannotation.annotationAnchor
import com.mapbox.maps.viewannotation.geometry
import com.mapbox.maps.viewannotation.viewAnnotationOptions
/**
* Example how to add view annotation to the point annotation.
*/
class ViewAnnotationWithPointAnnotationActivity : AppCompatActivity() {
private lateinit var viewAnnotationManager: ViewAnnotationManager
private lateinit var pointAnnotationManager: PointAnnotationManager
private lateinit var pointAnnotation: PointAnnotation
private lateinit var viewAnnotation: View
private lateinit var binding: ActivityViewAnnotationShowcaseBinding
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityViewAnnotationShowcaseBinding.inflate(layoutInflater)
setContentView(binding.root)
val iconBitmap = BitmapUtils.bitmapFromDrawableRes(
this@ViewAnnotationWithPointAnnotationActivity,
R.drawable.ic_blue_marker
)!!
viewAnnotationManager = binding.mapView.viewAnnotationManager
resetCamera()
binding.mapView.mapboxMap.loadStyle(Style.STANDARD) {
prepareAnnotationMarker(binding.mapView, iconBitmap)
prepareViewAnnotation()
// show / hide view annotation based on a marker click
pointAnnotationManager.addClickListener { clickedAnnotation ->
if (pointAnnotation == clickedAnnotation) {
viewAnnotation.toggleViewVisibility()
}
true
}
// show / hide view annotation based on marker visibility
binding.fabStyleToggle.setOnClickListener {
if (pointAnnotation.iconImage == null) {
pointAnnotation.iconImageBitmap = iconBitmap
viewAnnotation.isVisible = true
} else {
pointAnnotation.iconImageBitmap = null
viewAnnotation.isVisible = false
}
pointAnnotationManager.update(pointAnnotation)
}
// reset annotations and camera position
binding.fabReframe.setOnClickListener {
resetCamera()
pointAnnotation.point = POINT
pointAnnotationManager.update(pointAnnotation)
syncAnnotationPosition()
}
// update view annotation geometry if dragging the marker
pointAnnotationManager.addDragListener(object : OnPointAnnotationDragListener {
override fun onAnnotationDragStarted(annotation: Annotation<*>) {
}
override fun onAnnotationDrag(annotation: Annotation<*>) {
if (annotation == pointAnnotation) {
syncAnnotationPosition()
}
}
override fun onAnnotationDragFinished(annotation: Annotation<*>) {
}
})
}
}
private fun resetCamera() {
binding.mapView.mapboxMap.setCamera(
CameraOptions.Builder()
.center(POINT)
.pitch(45.0)
.zoom(12.5)
.bearing(-17.6)
.build()
)
}
private fun syncAnnotationPosition() {
viewAnnotationManager.updateViewAnnotation(
viewAnnotation,
viewAnnotationOptions {
geometry(pointAnnotation.geometry)
}
)
ItemCalloutViewBinding.bind(viewAnnotation).apply {
textNativeView.text = "lat=%.2f\nlon=%.2f".format(
pointAnnotation.geometry.latitude(),
pointAnnotation.geometry.longitude()
)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_view_annotation, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_view_annotation_fixed_delay -> {
viewAnnotationManager.setViewAnnotationUpdateMode(ViewAnnotationUpdateMode.MAP_FIXED_DELAY)
true
}
R.id.action_view_annotation_map_synchronized -> {
viewAnnotationManager.setViewAnnotationUpdateMode(ViewAnnotationUpdateMode.MAP_SYNCHRONIZED)
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun View.toggleViewVisibility() {
visibility = if (visibility == View.VISIBLE) View.GONE else View.VISIBLE
}
@SuppressLint("SetTextI18n")
private fun prepareViewAnnotation() {
viewAnnotation = viewAnnotationManager.addViewAnnotation(
resId = R.layout.item_callout_view,
options = viewAnnotationOptions {
geometry(pointAnnotation.geometry)
annotationAnchor {
anchor(ViewAnnotationAnchor.BOTTOM)
offsetY((pointAnnotation.iconImageBitmap?.height!!.toDouble()))
}
}
)
ItemCalloutViewBinding.bind(viewAnnotation).apply {
textNativeView.text = "lat=%.2f\nlon=%.2f".format(POINT.latitude(), POINT.longitude())
closeNativeView.setOnClickListener {
viewAnnotationManager.removeViewAnnotation(viewAnnotation)
}
selectButton.setOnClickListener { b ->
val button = b as Button
val isSelected = button.text.toString().equals("SELECT", true)
val pxDelta = if (isSelected) SELECTED_ADD_COEF_PX else -SELECTED_ADD_COEF_PX
button.text = if (isSelected) "DESELECT" else "SELECT"
viewAnnotationManager.updateViewAnnotation(
viewAnnotation,
viewAnnotationOptions {
selected(isSelected)
}
)
(button.layoutParams as ViewGroup.MarginLayoutParams).apply {
bottomMargin += pxDelta
rightMargin += pxDelta
leftMargin += pxDelta
}
button.requestLayout()
}
}
}
private fun prepareAnnotationMarker(mapView: MapView, iconBitmap: Bitmap) {
val annotationPlugin = mapView.annotations
val pointAnnotationOptions: PointAnnotationOptions = PointAnnotationOptions()
.withPoint(POINT)
.withIconImage(iconBitmap)
.withIconAnchor(IconAnchor.BOTTOM)
.withDraggable(true)
pointAnnotationManager = annotationPlugin.createPointAnnotationManager(
AnnotationConfig(
layerId = LAYER_ID
)
)
pointAnnotation = pointAnnotationManager.create(pointAnnotationOptions)
}
private companion object {
const val SELECTED_ADD_COEF_PX = 25
val POINT: Point = Point.fromLngLat(0.381457, 6.687337)
val LAYER_ID = "layer-id"
}
} | 216 | null | 131 | 472 | 2700dcaf18e70d23a19fc35b479bff6a2d490475 | 7,432 | mapbox-maps-android | Apache License 2.0 |
compiler/testData/diagnostics/tests/cast/AsErasedWarning.fir.kt | android | 263,405,600 | false | null |
fun ff(a: Any) = a as MutableList<String>
| 0 | null | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 43 | kotlin | Apache License 2.0 |
app/src/main/java/com/gigigo/imagerecognition/MainActivity.kt | Gigigo-Android-Devs | 106,403,278 | false | {"Gradle": 10, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 1, "Java": 36, "XML": 34, "Kotlin": 13, "INI": 1, "C++": 81} | package com.gigigo.imagerecognition
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.startScannerButton
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
startScannerButton.setOnClickListener {
val intent = Intent(this, ScannerActivity::class.java)
startActivity(intent)
}
}
}
| 1 | null | 2 | 1 | 26cb51ad5171df36961a6c27bb5dab31a7d84891 | 539 | gigigo-imageRecognition-library-android | Apache License 2.0 |
anmitsu/src/main/java/net/kikuchy/anmitsu/internal/IntentLongArray.kt | kikuchy | 62,986,081 | false | null |
package net.kikuchy.anmitsu.internal
import android.content.Intent
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class IntentLongArray<T>(val getter: () -> Intent, val name: String? = null) : ReadWriteProperty<T, LongArray?> {
override fun getValue(thisRef: T, property: KProperty<*>): LongArray? {
return getter().getLongArrayExtra(name ?: property.name)
}
override fun setValue(thisRef: T, property: KProperty<*>, value: LongArray?) {
getter().putExtra(name ?: property.name, value)
}
}
| 1 | null | 1 | 1 | 783d210e59e283bde1940f8cf335c28e2c62a6a1 | 554 | anmitsu | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/IpAddress.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.IpAddress: ImageVector
get() {
if (_ipAddress != null) {
return _ipAddress!!
}
_ipAddress = Builder(name = "IpAddress", 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) {
moveToRelative(19.071f, 2.936f)
horizontalLineToRelative(0.0f)
curveTo(17.182f, 1.046f, 14.671f, 0.006f, 12.0f, 0.006f)
reflectiveCurveToRelative(-5.182f, 1.04f, -7.071f, 2.929f)
curveToRelative(-3.899f, 3.899f, -3.899f, 10.243f, 0.012f, 14.153f)
lineToRelative(7.06f, 6.905f)
lineToRelative(7.071f, -6.917f)
curveToRelative(3.899f, -3.899f, 3.899f, -10.243f, 0.0f, -14.142f)
close()
moveTo(16.962f, 14.945f)
lineToRelative(-4.962f, 4.853f)
lineToRelative(-4.95f, -4.841f)
curveToRelative(-2.729f, -2.729f, -2.729f, -7.17f, 0.0f, -9.899f)
curveToRelative(1.322f, -1.323f, 3.081f, -2.051f, 4.95f, -2.051f)
reflectiveCurveToRelative(3.628f, 0.728f, 4.95f, 2.05f)
curveToRelative(2.729f, 2.729f, 2.729f, 7.17f, 0.012f, 9.888f)
close()
moveTo(8.9f, 6.0f)
horizontalLineToRelative(1.6f)
verticalLineToRelative(8.0f)
horizontalLineToRelative(-1.6f)
lineTo(8.9f, 6.0f)
close()
moveTo(14.5f, 6.0f)
horizontalLineToRelative(-2.5f)
verticalLineToRelative(8.0f)
horizontalLineToRelative(1.6f)
verticalLineToRelative(-3.0f)
horizontalLineToRelative(0.9f)
curveToRelative(1.381f, 0.0f, 2.5f, -1.119f, 2.5f, -2.5f)
reflectiveCurveToRelative(-1.119f, -2.5f, -2.5f, -2.5f)
close()
moveTo(14.5f, 9.4f)
horizontalLineToRelative(-0.9f)
verticalLineToRelative(-1.801f)
horizontalLineToRelative(0.9f)
curveToRelative(0.497f, 0.0f, 0.9f, 0.403f, 0.9f, 0.9f)
reflectiveCurveToRelative(-0.403f, 0.9f, -0.9f, 0.9f)
close()
}
}
.build()
return _ipAddress!!
}
private var _ipAddress: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,233 | icons | MIT License |
kochange-core/src/commonMain/kotlin/dev/itbasis/kochange/core/currency/pair/currency-pairs-c.kt | itbasis | 430,295,476 | false | {"Kotlin": 50677} | @file:Suppress("ClassName", "unused")
package dev.itbasis.kochange.core.currency.pair
import dev.itbasis.kochange.core.currency.BTC
import dev.itbasis.kochange.core.currency.COMP
import dev.itbasis.kochange.core.currency.CNC
public object CNC_BTC : SealedCurrencyPair(base = CNC, counter = BTC)
public object COMP_BTC : SealedCurrencyPair(base = COMP, counter = BTC)
| 8 | Kotlin | 0 | 1 | 95b464deefbb1a947adb433563fc9ed25fd1cf31 | 371 | kochange | MIT License |
data/kotlin/data-uploader/src/main/kotlin/org/radarbase/iot/consumer/RestProxyDataConsumer.kt | RADAR-base | 194,692,100 | false | {"Kotlin": 101863, "Python": 51512, "Dockerfile": 3488, "Shell": 318} | package org.radarbase.iot.consumer
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.apache.avro.SchemaValidationException
import org.radarbase.data.RecordData
import org.radarbase.iot.config.Configuration.Companion.CONFIGURATION
import org.radarbase.iot.converter.avro.AvroConverter
import org.radarbase.iot.sender.KafkaAvroDataSender
import org.slf4j.LoggerFactory
import java.io.IOException
open class RestProxyDataConsumer : DataConsumer<AvroConverter<*, *>> {
private val kafkaDataSender: KafkaAvroDataSender
constructor(
uploadIntervalSeconds: Int,
maxCacheSize: Int,
kafkaDataSender: KafkaAvroDataSender
) : super(uploadIntervalSeconds, maxCacheSize) {
this.kafkaDataSender = kafkaDataSender
}
constructor(
uploadIntervalSeconds: Int,
maxCacheSize: Int
) : super(uploadIntervalSeconds, maxCacheSize) {
this.kafkaDataSender = KafkaAvroDataSender(
authorizer = null,
schemaUrl = CONFIGURATION.radarConfig.schemaRegistryUrl,
kafkaUrl = CONFIGURATION.radarConfig.kafkaUrl
)
}
override fun processData(messages: Map<AvroConverter<*, *>, List<String>>) {
for ((k, v) in messages) {
logger.debug("Converting and sending $v using $k")
try {
sendToRestProxy(k.convert(v))
} catch (exc: IOException) {
logger.warn(
"Messages for $k could not be sent. Adding to cache " +
"to be sent later...", exc
)
// TODO: Add to a persistent cache
GlobalScope.launch(exceptionHadler) {
messages.forEach { (t, u) ->
u.forEach { handleData(it, t) }
}
}
}
}
}
override fun close() {
processData(this.cache.toMap()).also { this.cache.stop() }
kafkaDataSender.close()
}
@Throws(IOException::class)
open fun <K, V> sendToRestProxy(records: RecordData<K, V>) {
try {
kafkaDataSender.sendAll(records)
} catch (exc: SchemaValidationException) {
logger.error(
"Messages for ${records.topic} could not be sent due to schema " +
"validation failure. Discarding these messages.", exc
)
}
logger.info("Successfully uploaded ${records.size()} records.")
}
companion object {
private val logger = LoggerFactory.getLogger(this::class.java)
private val exceptionHadler: CoroutineExceptionHandler = CoroutineExceptionHandler { _, e ->
logger.warn("Error while uploading records to Rest proxy", e)
}
}
}
| 16 | Kotlin | 2 | 7 | 1bcc0a310e4c2eee0fd7f32347bd7e9a5f183a0d | 2,858 | RADAR-IoT | Apache License 2.0 |
keyboard-compose/src/main/kotlin/ComposeKeyboardManager.kt | splendo | 191,371,940 | false | null | /*
Copyright 2022 Splendo Consulting B.V. The Netherlands
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.splendo.kaluga.keyboard.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.focus.FocusManager
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalWindowInfo
import com.splendo.kaluga.architecture.compose.lifecycle.ComposableLifecycleSubscribable
import com.splendo.kaluga.architecture.viewmodel.BaseLifecycleViewModel
import com.splendo.kaluga.keyboard.BaseKeyboardManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import java.util.WeakHashMap
/**
* A [BaseKeyboardManager] that takes a [ComposeFocusHandler]. Uses for managing the keyboard in Compose views.
* @param currentFocusManager The initial [FocusManager] to manage the focus.
* @param focusHandlerQueue a [MutableSharedFlow] used to manage the [FocusRequester] to focus on.
*/
class ComposeKeyboardManager(internal var currentFocusManager: FocusManager? = null, private val focusHandlerQueue: MutableSharedFlow<FocusRequester?>) :
BaseKeyboardManager<ComposeFocusHandler> {
/**
* A [BaseKeyboardManager.Builder] for creating a [ComposeKeyboardManager]
*/
class Builder :
BaseKeyboardManager.Builder<ComposeFocusHandler>,
ComposableLifecycleSubscribable {
private val builtManagers = WeakHashMap<Int, ComposeKeyboardManager>()
private val focusHandlerQueue = MutableStateFlow<FocusRequester?>(null)
override fun create(coroutineScope: CoroutineScope): BaseKeyboardManager<ComposeFocusHandler> = ComposeKeyboardManager(focusHandlerQueue = focusHandlerQueue).also {
builtManagers[it.hashCode()] = it
}
override val modifier: @Composable BaseLifecycleViewModel.(
@Composable BaseLifecycleViewModel.() -> Unit,
) -> Unit = { content ->
val windowInfo = LocalWindowInfo.current
val focusManager = LocalFocusManager.current
val currentFocus = focusHandlerQueue.collectAsState()
currentFocus.value?.let {
LaunchedEffect(windowInfo) {
snapshotFlow { windowInfo.isWindowFocused }.first { it }
it.requestFocus()
focusHandlerQueue.tryEmit(null)
}
}
builtManagers.values.forEach {
it.currentFocusManager = focusManager
}
content()
}
}
override fun show(focusHandler: ComposeFocusHandler) {
focusHandlerQueue.tryEmit(focusHandler.focusRequester)
}
override fun hide() {
currentFocusManager?.clearFocus()
}
}
| 87 | null | 7 | 315 | 4094d5625a4cacb851b313d4e96bce6faac1c81f | 3,552 | kaluga | Apache License 2.0 |
src/main/kotlin/no/nav/bidrag/transport/behandling/vedtak/request/OpprettStønadsendringGrunnlagRequestDto.kt | navikt | 607,658,805 | false | {"Kotlin": 143030} | package no.nav.bidrag.transport.behandling.vedtak.request
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.validation.constraints.Min
@Schema
data class OpprettStønadsendringGrunnlagRequestDto(
@Schema(description = "Stønadsendring-id")
@Min(0)
val stønadsendringId: Int,
@Schema(description = "grunnlag-id")
@Min(0)
val grunnlagId: Int,
)
| 0 | Kotlin | 0 | 0 | c1b40d212a72f233974da1e3c7932479c4151b0a | 384 | bidrag-transport | MIT License |
educational-core/src/com/jetbrains/edu/learning/checker/gradle/GradleTheoryTaskChecker.kt | vipyami | 148,315,801 | true | {"Java": 1011668, "Kotlin": 800975, "JavaScript": 451524, "CSS": 34668, "HTML": 10175, "Python": 4431} | package com.jetbrains.edu.learning.checker.gradle
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.edu.learning.checker.*
import com.jetbrains.edu.learning.courseFormat.CheckStatus
import com.jetbrains.edu.learning.courseFormat.tasks.TheoryTask
class GradleTheoryTaskChecker(
task: TheoryTask,
project: Project,
private val mainClassForFile: (Project, VirtualFile) -> String?
) : TheoryTaskChecker(task, project) {
override fun onTaskSolved(message: String) {
// do not show popup
}
override fun check(): CheckResult {
val result = runGradleRunTask(project, task, mainClassForFile)
val output = when (result) {
is Err -> return result.error
is Ok -> result.value
}
CheckUtils.showOutputToolWindow(project, output)
return CheckResult(CheckStatus.Solved, "")
}
}
| 0 | Java | 0 | 0 | b11da94620a30fea2a27fe9f289897d4e5906fa5 | 876 | educational-plugin | Apache License 2.0 |
idea/testData/refactoring/changeSignature/RemoveParameterBeforeLambdaAfter.kt | JakeWharton | 99,388,807 | false | null | fun foo(x: Int, cl: () -> Int): Int {
return x + cl()
}
fun bar() {
foo(1) {
3
}
}
| 284 | null | 5162 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 104 | kotlin | Apache License 2.0 |
src/Day05_part1.kt | lowielow | 578,058,273 | false | null | class Stack {
val input = readInput("Day05")
private val rawList = mutableListOf<MutableList<Char>>()
private val newList = mutableListOf<MutableList<Char>>()
fun addStack(str: String) {
var raw = ""
for (i in 1 until str.length step 4) {
raw += str[i].toString()
}
rawList.add(raw.toMutableList())
}
fun arrangeStack() {
for (j in 0 until rawList[0].size) {
var new = ""
for (i in 0 until rawList.size) {
if (rawList[i][j] == ' ') {
continue
} else {
new = rawList[i][j] + new
}
}
newList.add(new.toMutableList())
}
}
fun handleMove(regex: Regex, str: String) {
val match = regex.find(str)!!
val (a, b, c) = match.destructured
var i = 0
while (i != a.toInt()) {
newList[c.toInt() - 1].add(newList[b.toInt() - 1][newList[b.toInt() - 1].size - 1])
newList[b.toInt() - 1].removeAt(newList[b.toInt() - 1].size - 1)
i++
}
}
fun printTopStack(): String {
var str = ""
for (i in newList.indices) {
str += newList[i][newList[i].size - 1].toString()
}
return str
}
}
fun main() {
val stack = Stack()
val regexStack = Regex(".*[A-Z].*")
val regexMove = Regex("\\D*(\\d+)\\D*(\\d)\\D*(\\d)")
fun part1(input: List<String>): String {
for (i in input.indices) {
if (regexStack.matches(input[i])) {
stack.addStack(input[i])
} else if (input[i].isEmpty()) {
stack.arrangeStack()
} else if (regexMove.matches(input[i])) {
stack.handleMove(regexMove, input[i])
}
}
return stack.printTopStack()
}
part1(stack.input).println()
}
| 0 | Kotlin | 0 | 0 | acc270cd70a8b7f55dba07bf83d3a7e72256a63f | 1,926 | aoc2022 | Apache License 2.0 |
app/src/main/java/org/kl/smartword/view/adapter/CategoryAdapter.kt | klappdev | 226,633,534 | false | null | /*
* Licensed under the MIT License <http://opensource.org/licenses/MIT>.
* SPDX-License-Identifier: MIT
* Copyright (c) 2019 - 2021 https://github.com/klappdev
*
* 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 org.kl.smartword.view.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.kl.smartword.R
import org.kl.smartword.model.Lesson
import org.kl.smartword.view.holder.CategoryViewHolder
class CategoryAdapter(val listLessons: MutableList<Lesson>) : RecyclerView.Adapter<CategoryViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.category_item, parent, false)
return CategoryViewHolder(view)
}
override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
val lesson = listLessons[position]
holder.bind(lesson)
}
override fun getItemCount() = listLessons.size
}
| 0 | Kotlin | 0 | 0 | df17a7357f9d131d6cc71be4b0185213aefc403b | 2,151 | smartword | MIT License |
app/src/main/java/tk/zwander/fabricateoverlaysample/data/AvailableResourceItemData.kt | zacharee | 414,052,379 | false | {"Kotlin": 81007, "AIDL": 186} | package tk.zwander.fabricateoverlaysample.data
data class AvailableResourceItemData(
val name: String,
val resourceName: String,
val type: Int,
val values: Array<String>
) : Comparable<AvailableResourceItemData> {
override fun compareTo(other: AvailableResourceItemData): Int {
return name.compareTo(other.name)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AvailableResourceItemData
if (name != other.name) return false
if (type != other.type) return false
if (!values.contentEquals(other.values)) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + type
result = 31 * result + values.contentHashCode()
return result
}
} | 8 | Kotlin | 11 | 98 | 97cf0fd2ba7e42a95e0ba56590a25be9bb994dde | 910 | FabricateOverlay | MIT License |
app/src/main/java/com/example/weatherapp/view/MainActivity.kt | kamil-matula | 350,345,105 | false | null | package com.example.weatherapp.view
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.example.weatherapp.databinding.ActivityMainBinding
import com.example.weatherapp.viewmodel.WeatherVM
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var weatherVM: WeatherVM
override fun onCreate(savedInstanceState: Bundle?) {
// Binding with layout:
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Gathering data from Room:
weatherVM = ViewModelProvider(this).get(WeatherVM::class.java)
weatherVM.weatherInfo.observe(this, {
if (it != null && weatherVM.currentWeather.value == null)
weatherVM.setCurrentWeatherByRoomData(it)
})
weatherVM.hourForecast.observe(this, {
if (it != null && weatherVM.currentHourlyForecast.value == null)
weatherVM.setHourlyForecastByRoomData(it)
})
weatherVM.dayForecast.observe(this, {
if (it != null && weatherVM.currentDailyForecast.value == null)
weatherVM.setDailyForecastByRoomData(it)
})
}
}
| 0 | Kotlin | 0 | 0 | ac3c1dc63231e589d316357232df05cf4a265bb2 | 1,326 | WeatherApp | MIT License |
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/team/avatar/RefreshBackgroundAvatarRsp.kt | Anime-Game-Servers | 642,871,918 | false | {"Kotlin": 1651536} | package org.anime_game_servers.multi_proto.gi.data.team.avatar
import org.anime_game_servers.core.base.Version.GI_CB2
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.annotations.proto.CommandType.*
import org.anime_game_servers.core.base.annotations.proto.ProtoCommand
import org.anime_game_servers.multi_proto.gi.data.general.Retcode
@AddedIn(GI_CB2)
@ProtoCommand(RESPONSE)
internal interface RefreshBackgroundAvatarRsp {
var retcode: Retcode
var hpFullTimeMap: Map<Long, Int>
}
| 0 | Kotlin | 2 | 6 | 7639afe4f546aa5bbd9b4afc9c06c17f9547c588 | 543 | anime-game-multi-proto | MIT License |
video-sdk/src/test/java/com/kaleyra/video_sdk/ui/call/virtualbackground/VirtualBackgroundItemTest.kt | KaleyraVideo | 686,975,102 | false | {"Kotlin": 3104373, "Shell": 7470, "Python": 6756, "Java": 1213} | /*
* Copyright 2023 Kaleyra @ https://www.kaleyra.com
*
* 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.kaleyra.video_sdk.ui.call.virtualbackground
import androidx.activity.ComponentActivity
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithText
import com.kaleyra.video_sdk.R
import com.kaleyra.video_sdk.call.virtualbackground.model.VirtualBackgroundUi
import com.kaleyra.video_sdk.call.virtualbackground.view.VirtualBackgroundItem
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class VirtualBackgroundItemTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
private var background by mutableStateOf<VirtualBackgroundUi>(VirtualBackgroundUi.None)
@Before
fun setUp() {
composeTestRule.setContent {
VirtualBackgroundItem(background = background, selected = false)
}
}
@After
fun tearDown() {
background = VirtualBackgroundUi.None
}
@Test
fun noVirtualBackground_noVirtualBackgroundTextDisplayed() {
background = VirtualBackgroundUi.None
val none = composeTestRule.activity.getString(R.string.kaleyra_virtual_background_none)
composeTestRule.onNodeWithText(none).assertIsDisplayed()
}
@Test
fun blurVirtualBackground_blurVirtualBackgroundTextDisplayed() {
background = VirtualBackgroundUi.Blur("id")
val blur = composeTestRule.activity.getString(R.string.kaleyra_virtual_background_blur)
composeTestRule.onNodeWithText(blur).assertIsDisplayed()
}
@Test
fun imageVirtualBackground_imageVirtualBackgroundTextDisplayed() {
background = VirtualBackgroundUi.Image("id")
val image = composeTestRule.activity.getString(R.string.kaleyra_virtual_background_image)
composeTestRule.onNodeWithText(image).assertIsDisplayed()
}
} | 0 | Kotlin | 0 | 1 | bd76590cc18ca2b05c1978f37f43147cb71a6d4f | 2,759 | VideoAndroidSDK | Apache License 2.0 |
app/src/main/java/com/assentify/sdk/AssentifySdkCallback.kt | AssentifyLTD | 807,433,944 | false | {"Kotlin": 140371, "Java": 95067} | package com.assentify.sdk
import com.assentify.sdk.RemoteClient.Models.ConfigModel
import com.assentify.sdk.RemoteClient.Models.StepDefinitions
import com.assentify.sdk.RemoteClient.Models.TemplatesByCountry
interface AssentifySdkCallback {
fun onAssentifySdkInitError(message: String)
fun onAssentifySdkInitSuccess(configModel: ConfigModel)
}
| 0 | Kotlin | 0 | 0 | cc7479e30090dd7e65c0ebeca983b76784d7f160 | 356 | Assentify.SDK.Android | MIT License |
tegral-prismakt/tegral-prismakt-generator-tests/simple-sql/src/test/kotlin/guru/zoroark/tegral/prismakt/generator/tests/simple/SimpleUserTableTest.kt | utybo | 491,247,680 | false | {"Kotlin": 1066259, "Nix": 2449, "Shell": 8} | /*
* 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 guru.zoroark.tegral.prismakt.generator.tests.simple
import guru.zoroark.tegral.prismakt.generator.tests.prismaDbPush
import kotlinx.coroutines.runBlocking
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.deleteAll
import org.jetbrains.exposed.sql.insertAndGetId
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.junit.jupiter.api.BeforeEach
import prismakt.generated.SqlUserTable
import kotlin.test.Test
import kotlin.test.assertEquals
fun withDb(block: suspend Database.() -> Unit) {
val db = Database.connect("jdbc:sqlite:prisma/dev.db", "org.sqlite.JDBC")
runBlocking {
newSuspendedTransaction(db = db) {
SqlUserTable.deleteAll()
}
block(db)
}
}
class SimpleSqlUserTableTest {
@BeforeEach
fun resetDb() {
prismaDbPush(null)
}
@Test
fun `Simple database transaction with DSL API`() = withDb {
val id = newSuspendedTransaction(db = this) {
SqlUserTable.insertAndGetId {
it[email] = "<EMAIL>"
it[name] = "User"
}
}
val result = newSuspendedTransaction {
SqlUserTable.select(SqlUserTable.id eq id).single()
}
assertEquals("<EMAIL>", result[SqlUserTable.email])
assertEquals("User", result[SqlUserTable.name])
}
}
| 26 | Kotlin | 4 | 37 | fa4284047f2ce7ba9ee78e92d8c67954716e9dcc | 2,053 | Tegral | Apache License 2.0 |
src/main/kotlin/no/skatteetaten/aurora/boober/feature/JavaDeployFeature.kt | Skatteetaten | 84,482,382 | false | null | package no.skatteetaten.aurora.boober.feature
import io.fabric8.kubernetes.api.model.Container
import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec
import no.skatteetaten.aurora.boober.model.PortNumbers
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
@Service
class JavaDeployFeature(@Value("\${integrations.docker.registry}") val registry: String) :
AbstractDeployFeature(registry) {
override fun enable(platform: ApplicationPlatform) = platform == ApplicationPlatform.java
override fun createContainers(adc: AuroraDeploymentSpec): List<Container> {
return listOf(
createContainer(
adc, "${adc.name}-java",
mapOf(
"http" to PortNumbers.INTERNAL_HTTP_PORT,
"management" to PortNumbers.INTERNAL_ADMIN_PORT,
"jolokia" to PortNumbers.JOLOKIA_HTTP_PORT,
"extra" to PortNumbers.EXTRA_APPLICATION_PORT
)
)
)
}
}
| 2 | Kotlin | 5 | 18 | 5a9e91f6f52d959395af7314c2f592074010d635 | 1,060 | boober | Apache License 2.0 |
turbo/src/main/kotlin/dev/hotwire/turbo/util/TurboExtensions.kt | ujjwalagrawal17 | 342,825,014 | true | {"Kotlin": 197267, "JavaScript": 4569} | package dev.hotwire.turbo.util
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.content.Context
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import dev.hotwire.turbo.visit.TurboVisitAction
import dev.hotwire.turbo.visit.TurboVisitActionAdapter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import java.io.File
internal fun Context.runOnUiThread(func: () -> Unit) {
when (mainLooper.isCurrentThread) {
true -> func()
else -> Handler(mainLooper).post { func() }
}
}
internal fun Context.contentFromAsset(filePath: String): String {
return assets.open(filePath).use {
String(it.readBytes())
}
}
internal fun Context.coroutineScope(): CoroutineScope {
return (this as? AppCompatActivity)?.lifecycleScope ?: GlobalScope
}
internal fun String.extract(patternRegex: String): String? {
val regex = Regex(patternRegex, RegexOption.IGNORE_CASE)
return regex.find(this)?.groups?.get(1)?.value
}
internal fun File.deleteAllFilesInDirectory() {
if (!isDirectory) return
listFiles()?.forEach {
it.delete()
}
}
internal fun Any.toJson(): String {
return gson.toJson(this)
}
internal fun <T> String.toObject(typeToken: TypeToken<T>): T {
return gson.fromJson(this, typeToken.type)
}
internal fun Int.animateColorTo(toColor: Int, duration: Long = 150, onUpdate: (Int) -> Unit) {
ValueAnimator.ofObject(ArgbEvaluator(), this, toColor).apply {
this.duration = duration
this.addUpdateListener {
val color = it.animatedValue as Int?
color?.let { onUpdate(color) }
}
}.start()
}
private val gson: Gson = GsonBuilder()
.registerTypeAdapter(TurboVisitAction::class.java, TurboVisitActionAdapter())
.create()
| 0 | null | 0 | 1 | d771ace49960ca4ceefe0da2044285b4a285eba3 | 1,990 | turbo-android | MIT License |
weaver/sdks/corda/src/main/kotlin/org/hyperledger/cacti/weaver/sdk/corda/VerificationPolicyManager.kt | RafaelAPB | 241,220,244 | true | {"Markdown": 534, "YAML": 326, "JSON with Comments": 89, "JSON": 375, "JavaScript": 76, "Ignore List": 86, "CODEOWNERS": 2, "Text": 19, "Git Attributes": 1, "SVG": 13, "Gradle": 56, "Makefile": 40, "INI": 27, "Shell": 191, "Batchfile": 24, "XML": 14, "Kotlin": 695, "Dockerfile": 50, "Go": 130, "Go Checksums": 16, "Go Module": 16, "Gerber Image": 46, "TOML": 41, "Roff Manpage": 1, "Rust": 53, "Gradle Kotlin DSL": 2, "Java": 1, "ANTLR": 1, "Protocol Buffer": 47, "Dotenv": 6, "Smarty": 8, "JAR Manifest": 2, "EJS": 2, "CSS": 34, "OASv3-json": 32, "PlantUML": 25, "SQL": 7, "PLpgSQL": 1, "Maven POM": 1, "OASv3-yaml": 1, "Mustache": 7, "HTML": 15, "TypeScript": 1, "TSX": 58, "Python": 1, "reStructuredText": 5, "SCSS": 6, "Solidity": 1, "robots.txt": 1, "Gherkin": 4, "Logos": 2, "Public Key": 3} | /*
* Copyright IBM Corp. All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.cacti.weaver.sdk.corda;
import arrow.core.Either
import arrow.core.Left
import arrow.core.Right
import arrow.core.flatMap
import kotlinx.coroutines.runBlocking
import java.lang.Exception
import org.slf4j.LoggerFactory
import net.corda.core.messaging.startFlow
import net.corda.core.messaging.CordaRPCOps
import net.corda.core.contracts.UniqueIdentifier
import net.corda.core.identity.Party
import org.hyperledger.cacti.weaver.imodule.corda.states.VerificationPolicyState
import org.hyperledger.cacti.weaver.imodule.corda.states.Identifier
import org.hyperledger.cacti.weaver.imodule.corda.states.Policy
import org.hyperledger.cacti.weaver.imodule.corda.flows.*
import org.hyperledger.cacti.weaver.protos.common.verification_policy.VerificationPolicyOuterClass
class VerificationPolicyManager {
companion object {
private val logger = LoggerFactory.getLogger(VerificationPolicyManager::class.java)
/**
* Function to create an verification policy state in Vault
*/
@JvmStatic
@JvmOverloads fun createVerificationPolicyState(
proxy: CordaRPCOps,
verificationPolicyProto: VerificationPolicyOuterClass.VerificationPolicy,
sharedParties: List<Party> = listOf<Party>()
): Either<Error, String> {
val verificationPolicyState = protoToState(verificationPolicyProto)
logger.debug("Writing VerificationPolicyState: ${verificationPolicyState}")
return try {
runCatching {
proxy.startFlow(::CreateVerificationPolicyState, verificationPolicyState, sharedParties)
.returnValue.get()
}.fold({
it.flatMap {
Right(it.toString())
}
}, {
Left(Error("Error running CreateVerificationPolicy flow: ${it.message}"))
})
} catch (e: Exception) {
Left(Error("${e.message}"))
}
}
/**
* Function to update an verification policy state in Vault
*/
@JvmStatic
fun updateVerificationPolicyState(
proxy: CordaRPCOps,
verificationPolicyProto: VerificationPolicyOuterClass.VerificationPolicy
): Either<Error, String> {
val verificationPolicyState = protoToState(verificationPolicyProto)
logger.debug("Update VerificationPolicyState: ${verificationPolicyState}")
return try {
runCatching {
proxy.startFlow(::UpdateVerificationPolicyState, verificationPolicyState)
.returnValue.get()
}.fold({
it.flatMap {
Right(it.toString())
}
}, {
Left(Error("Error running UpdateVerificationPolicyState flow: ${it.message}"))
})
} catch (e: Exception) {
Left(Error("${e.message}"))
}
}
/**
* Function to delete an verification policy state from Vault
*/
@JvmStatic
fun deleteVerificationPolicyState(
proxy: CordaRPCOps,
securityDomain: String
): Either<Error, String> {
logger.debug("Deleting verification policy for securityDomain $securityDomain")
return try {
logger.debug("Deleting verification policy for securityDomain $securityDomain")
val result = runCatching {
proxy.startFlow(::DeleteVerificationPolicyState, securityDomain)
.returnValue.get().flatMap {
logger.debug("Verification Policy for securityDomain $securityDomain deleted\n")
Right(it.toString())
}
}.fold({ it }, { Left(Error(it.message)) })
result
} catch (e: Exception) {
Left(Error("Corda Network Error: ${e.message}"))
}
}
/**
* Function to get an verification policy state from Vault
*/
@JvmStatic
fun getVerificationPolicyState(
proxy: CordaRPCOps,
securityDomain: String
): Either<Error, VerificationPolicyOuterClass.VerificationPolicy> {
return try {
logger.debug("Getting verification policy for securityDomain $securityDomain")
val verificationPolicy = runCatching {
proxy.startFlow(::GetVerificationPolicyStateBySecurityDomain, securityDomain)
.returnValue.get().fold({
logger.error("Error getting verification policy from network: ${it.message}")
Left(Error("Corda Network Error: ${it.message}"))
}, {
logger.debug("Verification Policy for securityDomain $securityDomain: ${it.state.data} \n")
Right(stateToProto(it.state.data))
})
}.fold({ it }, {
Left(Error("Corda Network Error: ${it.message}"))
})
verificationPolicy
} catch (e: Exception) {
Left(Error("Error with network connection: ${e.message}"))
}
}
/**
* Function to get all verification policies from Vault
*/
@JvmStatic
fun getVerificationPolicies(
proxy: CordaRPCOps
): Either<Error, List<VerificationPolicyOuterClass.VerificationPolicy>> {
return try {
logger.debug("Getting all verification policies")
val verificationPolicies = proxy.startFlow(::GetVerificationPolicies)
.returnValue.get()
var verificationPolicyList: List<VerificationPolicyOuterClass.VerificationPolicy> = listOf()
for (vp in verificationPolicies) {
verificationPolicyList += stateToProto(vp.state.data)
}
logger.debug("Verification Policies: $verificationPolicyList\n")
Right(verificationPolicyList)
} catch (e: Exception) {
Left(Error("${e.message}"))
}
}
/**
* Function to convert proto VerificationPolicyOuterClass.VerificationPolicy
* to state VerificationPolicyState
*/
@JvmStatic
fun protoToState(
verificationPolicyProto: VerificationPolicyOuterClass.VerificationPolicy
): VerificationPolicyState {
var identifiers: List<Identifier> = listOf()
for (identifierProto in verificationPolicyProto.identifiersList) {
val identifier = Identifier(
pattern = identifierProto.pattern,
policy = Policy(identifierProto.policy.type, identifierProto.policy.criteriaList)
)
identifiers += identifier
}
return VerificationPolicyState(
securityDomain = verificationPolicyProto.securityDomain,
identifiers = identifiers
)
}
/**
* Function to convert state VerificationPolicyState to
* proto VerificationPolicyOuterClass.VerificationPolicy
*/
@JvmStatic
fun stateToProto(
verificationPolicyState: VerificationPolicyState
): VerificationPolicyOuterClass.VerificationPolicy {
var identifiersList: List<VerificationPolicyOuterClass.Identifier> = listOf()
for (identifier in verificationPolicyState.identifiers) {
val policyProto = VerificationPolicyOuterClass.Policy.newBuilder()
.setType(identifier.policy.type)
.addAllCriteria(identifier.policy.criteria)
val identifierProto = VerificationPolicyOuterClass.Identifier.newBuilder()
.setPattern(identifier.pattern)
.setPolicy(policyProto)
.build()
identifiersList += identifierProto
}
return VerificationPolicyOuterClass.VerificationPolicy.newBuilder()
.setSecurityDomain(verificationPolicyState.securityDomain)
.addAllIdentifiers(identifiersList)
.build()
}
}
}
| 50 | TypeScript | 45 | 6 | 4c94bf21ee570349995c61204fe60a2dc6a35766 | 8,802 | blockchain-integration-framework | Apache License 2.0 |
build/icons/compose/vitaminicons/line/Wallet.kt | Decathlon | 511,157,831 | false | {"Kotlin": 4443549, "HTML": 226066, "Swift": 163852, "TypeScript": 60822, "CSS": 53872, "JavaScript": 33193, "Handlebars": 771} | package com.decathlon.vitamin.compose.vitaminicons.line
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.decathlon.vitamin.compose.vitaminicons.LineGroup
public val LineGroup.Wallet: ImageVector
get() {
if (_wallet != null) {
return _wallet!!
}
_wallet = Builder(name = "Wallet", 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(18.0f, 7.0f)
horizontalLineTo(21.0f)
curveTo(21.2652f, 7.0f, 21.5196f, 7.1054f, 21.7071f, 7.2929f)
curveTo(21.8946f, 7.4804f, 22.0f, 7.7348f, 22.0f, 8.0f)
verticalLineTo(20.0f)
curveTo(22.0f, 20.2652f, 21.8946f, 20.5196f, 21.7071f, 20.7071f)
curveTo(21.5196f, 20.8946f, 21.2652f, 21.0f, 21.0f, 21.0f)
horizontalLineTo(3.0f)
curveTo(2.7348f, 21.0f, 2.4804f, 20.8946f, 2.2929f, 20.7071f)
curveTo(2.1054f, 20.5196f, 2.0f, 20.2652f, 2.0f, 20.0f)
verticalLineTo(4.0f)
curveTo(2.0f, 3.7348f, 2.1054f, 3.4804f, 2.2929f, 3.2929f)
curveTo(2.4804f, 3.1054f, 2.7348f, 3.0f, 3.0f, 3.0f)
horizontalLineTo(18.0f)
verticalLineTo(7.0f)
close()
moveTo(4.0f, 9.0f)
verticalLineTo(19.0f)
horizontalLineTo(20.0f)
verticalLineTo(9.0f)
horizontalLineTo(4.0f)
close()
moveTo(4.0f, 5.0f)
verticalLineTo(7.0f)
horizontalLineTo(16.0f)
verticalLineTo(5.0f)
horizontalLineTo(4.0f)
close()
moveTo(15.0f, 13.0f)
horizontalLineTo(18.0f)
verticalLineTo(15.0f)
horizontalLineTo(15.0f)
verticalLineTo(13.0f)
close()
}
}
.build()
return _wallet!!
}
private var _wallet: ImageVector? = null
| 1 | Kotlin | 5 | 33 | 852dcd924b82cac447918d2609615819d34caf82 | 2,762 | vitamin-design | Apache License 2.0 |
core-db/src/main/java/io/novafoundation/nova/core_db/dao/WalletConnectSessionsDao.kt | novasamatech | 415,834,480 | false | {"Kotlin": 11121812, "Rust": 25308, "Java": 17664, "JavaScript": 425} | package io.novafoundation.nova.core_db.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import io.novafoundation.nova.core_db.model.WalletConnectPairingLocal
import kotlinx.coroutines.flow.Flow
@Dao
interface WalletConnectSessionsDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertPairing(pairing: WalletConnectPairingLocal)
@Query("DELETE FROM wallet_connect_pairings WHERE pairingTopic = :pairingTopic")
suspend fun deletePairing(pairingTopic: String)
@Query("SELECT * FROM wallet_connect_pairings WHERE pairingTopic = :pairingTopic")
suspend fun getPairing(pairingTopic: String): WalletConnectPairingLocal?
@Query("SELECT * FROM wallet_connect_pairings WHERE pairingTopic = :pairingTopic")
fun pairingFlow(pairingTopic: String): Flow<WalletConnectPairingLocal?>
@Query("DELETE FROM wallet_connect_pairings WHERE pairingTopic NOT IN (:pairingTopics)")
suspend fun removeAllPairingsOtherThan(pairingTopics: List<String>)
@Query("SELECT * FROM wallet_connect_pairings")
fun allPairingsFlow(): Flow<List<WalletConnectPairingLocal>>
@Query("SELECT * FROM wallet_connect_pairings WHERE metaId = :metaId")
fun pairingsByMetaIdFlow(metaId: Long): Flow<List<WalletConnectPairingLocal>>
}
| 12 | Kotlin | 30 | 50 | 127f8739ca86dc74d006f018237daed0de5095a1 | 1,344 | nova-wallet-android | Apache License 2.0 |
tmp/arrays/youTrackTests/5719.kt | DaniilStepanov | 228,623,440 | false | {"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4} | // Original bug: KT-23675
class Environment(
val fieldAccessedInsideChild: Int,
val how: Environment.() -> Unit
)
fun main(args: Array<String>) {
Environment(
3,
{
class Child {
val a = fieldAccessedInsideChild
}
class Parent {
val children: List<Child> =
(0..4).map { Child() }
}
}
)
}
| 1 | null | 12 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 431 | bbfgradle | Apache License 2.0 |
.teamcity/src/main/kotlin/promotion/BasePublishGradleDistribution.kt | jjustinic | 95,342,455 | true | {"Groovy": 30120204, "Java": 28219555, "Kotlin": 4020929, "C++": 1781062, "CSS": 173378, "C": 123600, "JavaScript": 78583, "HTML": 59961, "XSLT": 42693, "Shell": 11851, "Scala": 10840, "Swift": 2040, "Objective-C": 652, "Objective-C++": 441, "GAP": 424, "Assembly": 277, "Gherkin": 191, "Python": 57, "Brainfuck": 54, "Ruby": 16} | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 promotion
import jetbrains.buildServer.configs.kotlin.v2019_2.RelativeId
import vcsroots.gradlePromotionMaster
abstract class BasePublishGradleDistribution(
// The branch to be promoted
val promotedBranch: String,
val triggerName: String,
val gitUserName: String = "bot-teamcity",
val gitUserEmail: String = "<EMAIL>",
val extraParameters: String = "",
vcsRootId: String = gradlePromotionMaster,
cleanCheckout: Boolean = true
) : BasePromotionBuildType(vcsRootId, cleanCheckout) {
init {
artifactRules = """
**/build/git-checkout/subprojects/base-services/build/generated-resources/build-receipt/org/gradle/build-receipt.properties
**/build/distributions/*.zip => promote-build-distributions
**/build/website-checkout/data/releases.xml
**/build/git-checkout/build/reports/integTest/** => distribution-tests
**/smoke-tests/build/reports/tests/** => post-smoke-tests
**/build/version-info.properties => version-info.properties
""".trimIndent()
dependencies {
snapshot(RelativeId("Check_Stage_${[email protected]}_Trigger")) {
synchronizeRevisions = false
}
}
}
}
| 0 | Groovy | 0 | 1 | da9db6394bb4f51c413b23c1380c51de755ade3c | 1,879 | gradle | Apache License 2.0 |
app/src/main/java/com/shahin/meistersearch/general/extensions/ViewHolderExtension.kt | shahin68 | 369,420,907 | false | null | package com.shahin.meistersearch.general.extensions
import android.graphics.drawable.Drawable
import android.view.View
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
/**
* ViewHolder extension to ease setting click listener on itemView
* @return [RecyclerView.ViewHolder]
*/
fun <T : RecyclerView.ViewHolder> T.onClick(event: (view: View, position: Int, type: Int) -> Unit): T {
itemView.setOnClickListener {
event.invoke(it, adapterPosition, itemViewType)
}
return this
}
/**
* ViewHolder extension to ease setting long click listener on itemView
* @return [RecyclerView.ViewHolder]
*/
fun <T : RecyclerView.ViewHolder> T.onLongClick(event: (view: View, position: Int, type: Int) -> Unit): T {
itemView.setOnClickListener {
event.invoke(it, adapterPosition, itemViewType)
}
return this
}
/**
* ViewHolder extension to ease getting color
* @return color associated with color resource id
*/
fun <T : RecyclerView.ViewHolder> T.getColor(@ColorRes colorRes: Int): Int {
return ContextCompat.getColor(itemView.context, colorRes)
}
/**
* ViewHolder extension to ease getting drawable
* @return drawable associated with drawable resource id
*/
fun <T : RecyclerView.ViewHolder> T.getDrawable(@DrawableRes drawableId: Int): Drawable? {
return ContextCompat.getDrawable(itemView.context, drawableId)
} | 0 | Kotlin | 0 | 0 | c04a20438794ed2feb4faf8b4bd38614a141c968 | 1,479 | meister-challenge | MIT License |
app/src/main/kotlin/com/github/premnirmal/ticker/news/QuoteDetailActivity.kt | saurabhnmahajan | 268,342,935 | true | {"Kotlin": 312120} | package com.github.premnirmal.ticker.news
import android.app.Activity
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory
import androidx.recyclerview.widget.LinearLayoutManager
import com.github.mikephil.charting.charts.LineChart
import com.github.premnirmal.ticker.CustomTabs
import com.github.premnirmal.ticker.analytics.ClickEvent
import com.github.premnirmal.ticker.analytics.GeneralEvent
import com.github.premnirmal.ticker.base.BaseGraphActivity
import com.github.premnirmal.ticker.components.InAppMessage
import com.github.premnirmal.ticker.components.Injector
import com.github.premnirmal.ticker.isNetworkOnline
import com.github.premnirmal.ticker.network.data.NewsArticle
import com.github.premnirmal.ticker.network.data.Quote
import com.github.premnirmal.ticker.portfolio.AddPositionActivity
import com.github.premnirmal.ticker.showDialog
import com.github.premnirmal.ticker.ui.SpacingDecoration
import com.github.premnirmal.ticker.widget.WidgetDataProvider
import com.github.premnirmal.tickerwidget.R
import com.github.premnirmal.tickerwidget.R.color
import com.github.premnirmal.tickerwidget.R.dimen
import kotlinx.android.synthetic.main.activity_quote_detail.average_price
import kotlinx.android.synthetic.main.activity_quote_detail.change
import kotlinx.android.synthetic.main.activity_quote_detail.day_change
import kotlinx.android.synthetic.main.activity_quote_detail.edit_positions
import kotlinx.android.synthetic.main.activity_quote_detail.equityValue
import kotlinx.android.synthetic.main.activity_quote_detail.exchange
import kotlinx.android.synthetic.main.activity_quote_detail.graphView
import kotlinx.android.synthetic.main.activity_quote_detail.graph_container
import kotlinx.android.synthetic.main.activity_quote_detail.lastTradePrice
import kotlinx.android.synthetic.main.activity_quote_detail.news_container
import kotlinx.android.synthetic.main.activity_quote_detail.numShares
import kotlinx.android.synthetic.main.activity_quote_detail.positions_container
import kotlinx.android.synthetic.main.activity_quote_detail.positions_header
import kotlinx.android.synthetic.main.activity_quote_detail.progress
import kotlinx.android.synthetic.main.activity_quote_detail.recycler_view
import kotlinx.android.synthetic.main.activity_quote_detail.tickerName
import kotlinx.android.synthetic.main.activity_quote_detail.toolbar
import kotlinx.android.synthetic.main.activity_quote_detail.total_gain_loss
import javax.inject.Inject
class QuoteDetailActivity : BaseGraphActivity(), NewsFeedAdapter.NewsClickListener {
companion object {
const val TICKER = "TICKER"
private const val REQ_EDIT_POSITIONS = 12345
private const val INDEX_PROGRESS = 0
private const val INDEX_ERROR = 1
private const val INDEX_EMPTY = 2
private const val INDEX_DATA = 3
}
override val simpleName: String = "NewsFeedActivity"
@Inject internal lateinit var widgetDataProvider: WidgetDataProvider
private lateinit var adapter: NewsFeedAdapter
private lateinit var ticker: String
private lateinit var quote: Quote
private lateinit var viewModel: QuoteDetailViewModel
override fun onCreate(savedInstanceState: Bundle?) {
Injector.appComponent.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quote_detail)
toolbar.setNavigationOnClickListener {
finish()
}
if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
graph_container.layoutParams.height = (resources.displayMetrics.widthPixels * 0.5625f).toInt()
graph_container.requestLayout()
}
adapter = NewsFeedAdapter(this)
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.addItemDecoration(
SpacingDecoration(resources.getDimensionPixelSize(dimen.list_spacing_double))
)
recycler_view.adapter = adapter
recycler_view.isNestedScrollingEnabled = false
setupGraphView()
ticker = checkNotNull(intent.getStringExtra(TICKER))
viewModel = ViewModelProvider(this, AndroidViewModelFactory.getInstance(application))
.get(QuoteDetailViewModel::class.java)
viewModel.quote.observe(this, Observer { result ->
if (result.wasSuccessful) {
quote = result.data
fetch()
setupUi()
} else {
InAppMessage.showMessage(this@QuoteDetailActivity, R.string.error_fetching_stock, error = true)
progress.visibility = View.GONE
graphView.setNoDataText(getString(R.string.error_fetching_stock))
news_container.displayedChild = INDEX_ERROR
}
})
viewModel.data.observe(this, Observer { data ->
dataPoints = data
loadGraph(ticker)
})
viewModel.dataFetchError.observe(this, Observer {
progress.visibility = View.GONE
graphView.setNoDataText(getString(R.string.graph_fetch_failed))
InAppMessage.showMessage(this@QuoteDetailActivity, R.string.graph_fetch_failed, error = true)
})
viewModel.newsData.observe(this, Observer { data ->
analytics.trackGeneralEvent(
GeneralEvent("FetchNews")
.addProperty("Instrument", ticker)
.addProperty("Success", "True")
)
setUpArticles(data)
})
viewModel.newsError.observe(this, Observer {
news_container.displayedChild = INDEX_ERROR
InAppMessage.showMessage(this@QuoteDetailActivity, R.string.news_fetch_failed, error = true)
analytics.trackGeneralEvent(
GeneralEvent("FetchNews")
.addProperty("Instrument", ticker)
.addProperty("Success", "False")
)
})
viewModel.fetchQuote(ticker)
}
private fun setupUi() {
toolbar.menu.clear()
toolbar.inflateMenu(R.menu.menu_news_feed)
val isInPortfolio = viewModel.isInPortfolio(ticker)
val addMenuItem = toolbar.menu.findItem(R.id.action_add)
val removeMenuItem = toolbar.menu.findItem(R.id.action_remove)
if (isInPortfolio) {
addMenuItem.isVisible = false
removeMenuItem.isVisible = true
} else {
removeMenuItem.isVisible = false
addMenuItem.isVisible = true
}
toolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.action_add -> {
if (widgetDataProvider.hasWidget()) {
val widgetIds = widgetDataProvider.getAppWidgetIds()
if (widgetIds.size > 1) {
val widgets =
widgetIds.map { widgetDataProvider.dataForWidgetId(it) }
.sortedBy { it.widgetName() }
val widgetNames = widgets.map { it.widgetName() }
.toTypedArray()
AlertDialog.Builder(this)
.setTitle(R.string.select_widget)
.setItems(widgetNames) { dialog, which ->
val id = widgets[which].widgetId
addTickerToWidget(ticker, id)
dialog.dismiss()
}
.create()
.show()
} else {
addTickerToWidget(ticker, widgetIds.first())
}
} else {
addTickerToWidget(ticker, WidgetDataProvider.INVALID_WIDGET_ID)
}
updatePositionsUi()
return@setOnMenuItemClickListener true
}
R.id.action_remove -> {
removeMenuItem.isVisible = false
addMenuItem.isVisible = true
viewModel.removeStock(ticker)
updatePositionsUi()
return@setOnMenuItemClickListener true
}
}
return@setOnMenuItemClickListener false
}
toolbar.title = ticker
tickerName.text = quote.name
lastTradePrice.text = quote.priceString()
val changeText = "${quote.changeStringWithSign()} ( ${quote.changePercentStringWithSign()})"
change.text = changeText
if (quote.change > 0 || quote.changeInPercent >= 0) {
change.setTextColor(resources.getColor(color.positive_green))
lastTradePrice.setTextColor(resources.getColor(color.positive_green))
} else {
change.setTextColor(resources.getColor(color.negative_red))
lastTradePrice.setTextColor(resources.getColor(color.negative_red))
}
exchange.text = quote.stockExchange
updatePositionsUi()
edit_positions.setOnClickListener {
analytics.trackClickEvent(
ClickEvent("EditPositionClick")
.addProperty("Instrument", ticker)
)
val intent = Intent(this, AddPositionActivity::class.java)
intent.putExtra(AddPositionActivity.TICKER, quote.symbol)
startActivityForResult(intent, REQ_EDIT_POSITIONS)
}
}
private fun fetchData() {
if (isNetworkOnline()) {
viewModel.fetchHistoricalDataShort(quote.symbol)
} else {
progress.visibility = View.GONE
graphView.setNoDataText(getString(R.string.no_network_message))
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQ_EDIT_POSITIONS) {
if (resultCode == Activity.RESULT_OK) {
quote = checkNotNull(data?.getParcelableExtra(AddPositionActivity.QUOTE))
}
}
super.onActivityResult(requestCode, resultCode, data)
}
private fun setUpArticles(articles: List<NewsArticle>) {
if (articles.isEmpty()) {
news_container.displayedChild = INDEX_EMPTY
} else {
adapter.setData(articles)
news_container.displayedChild = INDEX_DATA
}
}
override fun onResume() {
super.onResume()
if (this::quote.isInitialized) {
updatePositionsUi()
}
}
private fun updatePositionsUi() {
val isInPortfolio = viewModel.hasTicker(ticker)
if (isInPortfolio) {
positions_container.visibility = View.VISIBLE
positions_header.visibility = View.VISIBLE
numShares.text = quote.numSharesString()
equityValue.text = quote.holdingsString()
if (quote.hasPositions()) {
total_gain_loss.visibility = View.VISIBLE
total_gain_loss.setText("${quote.gainLossString()} (${quote.gainLossPercentString()})")
if (quote.gainLoss() >= 0) {
total_gain_loss.setTextColor(resources.getColor(color.positive_green))
} else {
total_gain_loss.setTextColor(resources.getColor(color.negative_red))
}
average_price.visibility = View.VISIBLE
average_price.setText(quote.averagePositionPrice())
day_change.visibility = View.VISIBLE
day_change.setText(quote.dayChangeString())
if (quote.change > 0 || quote.changeInPercent >= 0) {
day_change.setTextColor(resources.getColor(color.positive_green))
} else {
day_change.setTextColor(resources.getColor(color.negative_red))
}
} else {
total_gain_loss.visibility = View.GONE
day_change.visibility = View.GONE
average_price.visibility = View.GONE
}
} else {
positions_container.visibility = View.GONE
positions_header.visibility = View.GONE
}
}
private fun fetch() {
if (!isNetworkOnline()) {
InAppMessage.showMessage(this, R.string.no_network_message, error = true)
}
if (adapter.itemCount == 0) {
news_container.displayedChild = INDEX_PROGRESS
fetchNews()
}
if (dataPoints == null) {
fetchData()
} else {
loadGraph(ticker)
}
}
private fun fetchNews() {
if (isNetworkOnline()) {
viewModel.fetchNews(quote)
} else {
news_container.displayedChild = INDEX_ERROR
}
}
override fun onGraphDataAdded(graphView: LineChart) {
progress.visibility = View.GONE
analytics.trackGeneralEvent(GeneralEvent("GraphLoaded"))
}
override fun onNoGraphData(graphView: LineChart) {
progress.visibility = View.GONE
analytics.trackGeneralEvent(GeneralEvent("NoGraphData"))
}
/**
* Called via xml
*/
fun openGraph(v: View) {
analytics.trackClickEvent(
ClickEvent("GraphClick")
.addProperty("Instrument", ticker)
)
val intent = Intent(this, GraphActivity::class.java)
intent.putExtra(GraphActivity.TICKER, ticker)
startActivity(intent)
}
private fun addTickerToWidget(
ticker: String,
widgetId: Int
) {
val widgetData = widgetDataProvider.dataForWidgetId(widgetId)
if (!widgetData.hasTicker(ticker)) {
widgetData.addTicker(ticker)
widgetDataProvider.broadcastUpdateWidget(widgetId)
val addMenuItem = toolbar.menu.findItem(R.id.action_add)
val removeMenuItem = toolbar.menu.findItem(R.id.action_remove)
addMenuItem.isVisible = false
removeMenuItem.isVisible = true
InAppMessage.showMessage(this, getString(R.string.added_to_list, ticker))
} else {
showDialog(getString(R.string.already_in_portfolio, ticker))
}
}
// NewsFeedAdapter.NewsClickListener
override fun onClickNewsArticle(article: NewsArticle) {
CustomTabs.openTab(this, article.url)
}
} | 0 | null | 1 | 0 | 0e121f0039f1a57f9afe9e27cb2fbde9691f874a | 13,160 | StockTicker | MIT License |
multi-ansible-runner/src/test/kotlin/cz/dbydzovsky/multiAnsibleRunner/ansible/runner/SampleAnsiblePlaybookInvoke.kt | dbydzovsky | 134,363,298 | false | {"Kotlin": 34205, "Ruby": 3000} | package cz.dbydzovsky.multiAnsibleRunner.ansible.runner
import cz.dbydzovsky.multiAnsibleRunner.ansible.run.playbook.AnsiblePlaybookRunBuilder
import cz.dbydzovsky.multiAnsibleRunner.application.MultiAnsibleRunner
import cz.dbydzovsky.multiAnsibleRunner.clusterProvider.auth.UsernamePasswordAuthentication
import cz.dbydzovsky.multiAnsibleRunner.clusterProvider.impl.VagrantClusterProvider
import cz.dbydzovsky.multiAnsibleRunner.configuration.Configuration
import cz.dbydzovsky.multiAnsibleRunner.tool.asResource
import name.falgout.jeffrey.testing.junit.mockito.MockitoExtension
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import java.io.File
@ExtendWith(MockitoExtension::class)
internal class SampleAnsiblePlaybookInvoke {
val playbookName = "playbook-ping.yml"
val pingPlaybook = "playbook_ping/$playbookName".asResource(this)
@Test
fun `run ansible playbook`() {
val conf = Configuration()
val playbookBuilder = AnsiblePlaybookRunBuilder()
.withPlaybook(playbookName)
.withWorkingDir(File(pingPlaybook.path).parentFile)
val provider = VagrantClusterProvider()
provider.nodeNames = mutableListOf("Earth")
conf.setClusterProvider(provider)
conf.addAnsibleRun(playbookBuilder.build())
MultiAnsibleRunner().run(conf)
}
@Test
fun `status` () {
val provider = VagrantClusterProvider()
provider.nodeNames = mutableListOf("Earth")
provider.getStatus()
}
@Test
fun `suspend` () {
val conf = Configuration()
val playbookBuilder = AnsiblePlaybookRunBuilder()
.withPlaybook(playbookName)
.withWorkingDir(File(pingPlaybook.path).parentFile)
val provider = VagrantClusterProvider()
provider.nodeNames = mutableListOf("Earth")
conf.setClusterProvider(provider)
conf.addAnsibleRun(playbookBuilder.build())
MultiAnsibleRunner().run(conf)
provider.suspend(listOf("Earth"))
}
@Test
fun `run ansible playbook in vagrant virtuals`() {
val hosts = File.createTempFile("hosts", ".file")
val conf = Configuration()
val playbookBuilder = AnsiblePlaybookRunBuilder()
.withPlaybook(playbookName)
.withHosts("inventories/hosts.file")
.withWorkingDir(File(pingPlaybook.path).parentFile)
val ansibleRunner = AnsibleInDockerRunner()
.setPlaybookPath(File(pingPlaybook.path).parentFile.canonicalPath)
.addSharedFolder(hosts.canonicalPath, "/ansible/playbooks/inventories/hosts.file")
val provider = VagrantClusterProvider()
.addNodeName("Mercury")
conf.register { ansibleRun, info ->
hosts.appendText("[all]\n")
info?.forEach {
val authentication = it.authentication as UsernamePasswordAuthentication
hosts.appendText("${it.hostname}\tansible_host=${it.ip}\tansible_connection=ssh\tansible_user=${authentication.username}\tansible_password=${authentication.password}\n")
}
return@register ansibleRun
}
conf.setClusterProvider(provider)
conf.setAnsibleRunner(ansibleRunner)
conf.addAnsibleRun(playbookBuilder.build())
MultiAnsibleRunner().run(conf)
}
@Test
fun `asks for state of virtuals` () {
val provider = VagrantClusterProvider()
.addNodeName("Mercury")
provider.execute(listOf("status", "1a4844904551418b8b7406945d6ef869"))
}
@Test
fun `asks for state of virtuals - vagrant box list` () {
val provider = VagrantClusterProvider()
// .addNodeName("Mercury")
provider.execute(listOf("box", "list", "-i"))
}
@Test
fun `destroy with same parameters as creation`() {
val provider = VagrantClusterProvider()
provider.nodeNames.add("Earth")
provider.nodeNames.add("Mars")
provider.nodeNames.add("Venus")
provider.destroy()
}
}
| 0 | Kotlin | 0 | 0 | 896617ac52979d0622764a19dc6df605a2d6406a | 4,134 | qa-mutli-ansible-runner | MIT License |
app/src/main/java/com/example/noteapp/di/AppModule.kt | Wit0r | 621,182,013 | false | null | package com.example.noteapp.di
import android.content.Context
import androidx.room.Room
import com.example.noteapp.core.Constants.TABLE_NAME
import com.example.noteapp.data.dao.NoteDao
import com.example.noteapp.data.network.NoteDb
import com.example.noteapp.data.repository.NoteRepositoryImpl
import com.example.noteapp.domain.repository.NoteRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
class AppModule {
@Provides
fun provideNoteDb(
@ApplicationContext
context: Context
) = Room.databaseBuilder(context, NoteDb::class.java, TABLE_NAME).build()
@Provides
fun providesNoteDao(noteDb: NoteDb) = noteDb.noteDao
@Provides
fun provideNoteRepository(noteDao: NoteDao): NoteRepository = NoteRepositoryImpl(noteDao)
} | 0 | Kotlin | 0 | 0 | 392c854505309c39d3963e9fc0c7124874b78c16 | 950 | NoteApp-JetpackCompose | MIT License |
dependencies/infrastructure/src/main/java/com/foreveross/atwork/infrastructure/model/discussion/template/DiscussionDefinition.kt | AoEiuV020 | 421,650,297 | false | {"Java": 8618305, "Kotlin": 1733509, "JavaScript": 719597, "CSS": 277438, "HTML": 111559} | package com.foreveross.atwork.infrastructure.model.discussion.template
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
@Parcelize
class DiscussionDefinition(
@SerializedName("url")
var url: String? = null,
@SerializedName("params")
var params: List<HashMap<String, String>>? = null,
@SerializedName("app_id")
var appId: String? = null,
@SerializedName("domain_id")
var domainId: String? = null,
@SerializedName("entry_id")
var entryId: String? = null,
@SerializedName("org_code")
var orgCode: String? = null,
@SerializedName("org_name")
var orgName: String? = null,
@SerializedName("desc")
var desc: String? = null
) : Parcelable | 1 | null | 1 | 1 | 1c4ca5bdaea6d5230d851fb008cf2578a23b2ce5 | 839 | w6s_lite_android | MIT License |
app/src/main/java/com/yaky/betaseriefollowing/domain/request/RequestToBetaSerie.kt | galoat | 112,076,765 | false | {"Java": 26687, "Kotlin": 23872} | package com.yaky.betaseriefollowing.domain.request
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.yaky.betaseriefollowing.Exception.CredentialException
import com.yaky.betaseriefollowing.R
import com.yaky.betaseriefollowing.data.classes.Shows
import com.yaky.betaseriefollowing.data.classes.User
import com.yaky.betaseriefollowing.domain.Command
import com.yaky.betaseriefollowing.ui.App
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
import org.jetbrains.anko.warn
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit
//TODO use retrofit for multiple use ?
class RequestToBetaSerie : Command<Shows>, AnkoLogger {
private val client = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build()
companion object {
private val urlListSerie = App.instance.getString(R.string.betaSerieURL)
}
override fun postEpisodeSeen(token: String, episodeId: String):Boolean{
info{"post Episode seen "+episodeId}
val formBody = FormBody.Builder()
.add("id", episodeId)
.build()
var request = Request.Builder().post(formBody)
.addHeader("Authorization", token)
val result = sendRequest(request, App.instance.getString(R.string.betaSerieURLPostSeen))
if(result !=null) {
if(JSONObject(result).getJSONArray("errors").length() != 0){
return false
}
}
return true
}
override fun requestListSerie(token : String) : Shows{
//TODO parameter shouldn't be hard coded
info{"requestListSerie request"}
val request = Request.Builder()
.addHeader("Authorization", token)
.addHeader("Accept"," application/json")
val listShows: Shows? = Gson().fromJson(sendRequest(request, App.instance.getString(R.string.betaSerieURLEpisodeList)), Shows::class.java)
if(listShows == null){
warn("deserialization problem ")
throw JsonSyntaxException("Problem deserialize JSon from server")
}else {
return listShows
}
}
///TODO use Oauth2 and not HTTPS
override fun requestCredential(user: User): String {
info{"request credential user "+user.login +" login "+user.password}
val formBody = FormBody.Builder()
.add("login", user.login)
.add("password", <PASSWORD>)
.build()
val request = Request.Builder().post(formBody)
val credential =sendRequest(request, App.instance.getString(R.string.betaSerieURLHttpsLogin))
return credential ?: throw CredentialException("Can't identificate User")
}
private fun sendRequest(requestBuilder: okhttp3.Request.Builder, requestUrl: String): String?{
val request = requestBuilder.addHeader("X-BetaSeries-Key", App.instance.getString(R.string.betaKey) )
.url(urlListSerie + requestUrl)
.build()
val response = client.newCall(request).execute()
if (!response.isSuccessful) {
warn("problem connection server \n error :"+ response.body()?.string())
throw IOException("Unexpected code " + response)
}
info("response OK from server ")
return response.body()?.string()
}
} | 1 | null | 1 | 1 | 43c28307ab44a2a0a12a4b246224ba4b58ca73f1 | 3,598 | betaSerieFollowing | MIT License |
app/src/main/java/com/eliasball/debtmanager/ui/PersonDetailActivity.kt | blue1stone | 273,737,308 | false | null | package com.eliasball.debtmanager.ui
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.eliasball.debtmanager.R
import com.eliasball.debtmanager.data.db.entities.Debt
import com.eliasball.debtmanager.data.db.entities.PersonDetail
import com.eliasball.debtmanager.data.providers.CurrencyProvider
import com.eliasball.debtmanager.data.providers.ShareParser
import com.eliasball.debtmanager.data.repository.DebtRepository
import com.eliasball.debtmanager.databinding.ActivityPersonDetailBinding
import com.eliasball.debtmanager.internal.ScrollAware
import com.eliasball.debtmanager.internal.slideEnter
import com.eliasball.debtmanager.internal.slideExit
import com.eliasball.debtmanager.ui.adapters.DebtRecyclerAdapter
import com.eliasball.debtmanager.ui.fragments.CreateDebtFragment
import kotlinx.coroutines.*
import org.kodein.di.KodeinAware
import org.kodein.di.android.closestKodein
import org.kodein.di.generic.instance
class PersonDetailActivity : AppCompatActivity(), KodeinAware, ScrollAware {
// The injected variables
override val kodein by closestKodein()
private val debtRepository by instance<DebtRepository>()
private val currencyProvider by instance<CurrencyProvider>()
private val shareParser by instance<ShareParser>()
// The binding variables
private lateinit var binding: ActivityPersonDetailBinding
// Coroutine setup
private var job = Job()
private val coroutineScope = CoroutineScope(job + Dispatchers.Main)
// The data required for recycler and other views
private lateinit var debts: LiveData<List<Debt>>
private lateinit var personDetail: LiveData<PersonDetail>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Inflate the binding
binding = ActivityPersonDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
// setup the action bar
setSupportActionBar(binding.bar)
binding.bar.setNavigationOnClickListener {
onBackPressed()
}
// create the layout manager
binding.recycler.layoutManager = LinearLayoutManager(this)
// Create and attach the debt adapter
val adapter = DebtRecyclerAdapter(mutableListOf(), currencyProvider, true,
onSendClick = {
coroutineScope.launch {
// Get the text
val text = shareParser.getShareDebtString(
it,
debtRepository,
currencyProvider.getCurrencySymbol()
)
// Create the intent
val sendIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, text)
type = "text/plain"
}
val shareIntent = Intent.createChooser(sendIntent, getString(R.string.share_debt))
startActivity(shareIntent)
}
},
onTickClick = {
coroutineScope.launch {
withContext(Dispatchers.IO) {
debtRepository.deleteDebt(it)
}
}
},
onContainerClick = {
CreateDebtFragment.newInstance(it.date)
.show(supportFragmentManager, "dialog")
})
binding.recycler.adapter = adapter
// get and observe the data for the recycler
coroutineScope.launch {
withContext(Dispatchers.IO) {
debts = debtRepository.getDebtsByPerson(intent.getStringExtra(EXTRA_NAME)!!)
}
debts.observe(this@PersonDetailActivity, Observer {
if(it.isNotEmpty()){
binding.backdrop.backdrop.visibility = View.GONE
} else {
binding.backdrop.backdrop.visibility = View.VISIBLE
}
adapter.setData(it)
})
}
binding.personName.text = intent.getStringExtra(EXTRA_NAME)
// Get and observe the data for the views
coroutineScope.launch {
withContext(Dispatchers.IO) {
personDetail = debtRepository.getPersonDetails(intent.getStringExtra(EXTRA_NAME)!!)
}
personDetail.observe(this@PersonDetailActivity, Observer {
binding.totalText.text = if (it.moneyCount > 0) getString(
R.string.total_text,
it.total,
currencyProvider.getCurrencySymbol()
) else getString(R.string.total_empty_text)
binding.moneyCountText.text = getString(R.string.count_text, it.moneyCount)
binding.objectsCountText.text = getString(R.string.count_text, it.objectsCount)
})
}
// set the fab to create a new debt for this person
binding.fab.setOnClickListener {
CreateDebtFragment.newInstance(0L, person = intent.getStringExtra(EXTRA_NAME)!!)
.show(supportFragmentManager, "dialog")
}
// Implement share button
binding.sendAsText.setOnClickListener {
coroutineScope.launch {
// Get the text
val text = shareParser.getShareDebtsForPersonString(
intent.getStringExtra(EXTRA_NAME)!!,
debtRepository,
currencyProvider.getCurrencySymbol()
)
// Create the intent
val sendIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, text)
type = "text/plain"
}
val shareIntent = Intent.createChooser(sendIntent, getString(R.string.share_debt))
startActivity(shareIntent)
}
}
// make the toolbar appear and disappear on scroll
attachToScroll(binding.recycler, {
binding.toolbar.slideExit()
}, {
binding.toolbar.slideEnter()
})
}
override fun onBackPressed() {
super.onBackPressed()
// Animate the window
overridePendingTransition(R.anim.fade_in, R.anim.slide_out_right)
}
companion object {
// The extra for the person name
const val EXTRA_NAME = "EXTRA_NAME"
}
override fun onDestroy() {
super.onDestroy()
// Cancel all coroutines on the job
job.cancel()
}
}
| 0 | Kotlin | 1 | 1 | 6728222876f687ba188b0e30b93034be9f1f501b | 6,850 | debt_manager_android | MIT License |
multiplatform-settings/android/src/main/java/com/russhwolf/settings/PlatformSettings.kt | touchlab-lab | 144,027,035 | true | {"Kotlin": 42198, "Shell": 139} | /*
* Copyright 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.russhwolf.settings
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences
import android.preference.PreferenceManager
/**
* A collection of storage-backed key-value data
*
* This class allows storage of values with the [Int], [Long], [String], [Float], [Double], or [Boolean] types, using a
* [String] reference as a key. Values will be persisted across app launches.
*
* The specific persistence mechanism is defined using a platform-specific implementation, so certain behavior may vary
* across platforms. In general, updates will be reflected immediately in-memory, but will be persisted to disk
* asynchronously.
*
* Operator extensions are defined in order to simplify usage. In addition, property delegates are provided for cleaner
* syntax and better type-safety when interacting with values stored in a `Settings` instance.
*
* This class can be instantiated via a platform-specific constructor or via a [Factory].
*
* On the Android platform, this class can be created by passing a [SharedPreferences] instance which will be used as a
* delegate. Thus two `Settings` instances created using the same [delegate] will be backed by the same data.
*/
actual class PlatformSettings public constructor(private val delegate: SharedPreferences) : Settings {
/**
* A factory that can produce [Settings] instances.
*
* This class can only be instantiated via a platform-specific constructor. It's purpose is so that `Settings`
* objects can be created in common code, so that the only platform-specific behavior necessary in order to use
* multiple `Settings` objects is the one-time creation of a single `Factory`.
*
* On the Android platform, this class creates `Settings` objects backed by [SharedPreferences]. It can only be
* created by supplying a [Context] instance. The `Factory` will hold onto a reference to the
* [applicationContext][Context.getApplicationContext] property of the supplied `context` and will use that to
* create [SharedPreferences] objects.
*/
actual class Factory(context: Context) : Settings.Factory {
private val appContext = context.applicationContext
/**
* Creates a [Settings] object associated with the provided [name].
*
* Multiple `Settings` instances created with the same `name` parameter will be backed by the same persistent
* data, while distinct `name`s will use different data. If `name` is `null` then a platform-specific default
* will be used.
*
* On the Android platform, this is implemented by calling [Context.getSharedPreferences] and passing [name]. If
* `name` is `null` then [PreferenceManager.getDefaultSharedPreferences] will be used instead.
*/
actual override fun create(name: String?): Settings {
val delegate = if (name == null) {
PreferenceManager.getDefaultSharedPreferences(appContext)
} else {
appContext.getSharedPreferences(name, MODE_PRIVATE)
}
return PlatformSettings(delegate)
}
}
/**
* Clears all values stored in this [Settings] instance.
*/
actual override fun clear(): Unit = delegate.edit().clear().apply()
/**
* Removes the value stored at [key].
*/
actual override fun remove(key: String): Unit = delegate.edit().remove(key).apply()
/**
* Returns `true` if there is a value stored at [key], or `false` otherwise.
*/
actual override fun hasKey(key: String): Boolean = delegate.contains(key)
/**
* Stores the `Int` [value] at [key].
*/
actual override fun putInt(key: String, value: Int): Unit = delegate.edit().putInt(key, value).apply()
/**
* Returns the `Int` value stored at [key], or [defaultValue] if no value was stored. If a value of a different
* type was stored at `key`, the behavior is not defined.
*/
actual override fun getInt(key: String, defaultValue: Int): Int = delegate.getInt(key, defaultValue)
/**
* Stores the `Long` [value] at [key].
*/
actual override fun putLong(key: String, value: Long): Unit = delegate.edit().putLong(key, value).apply()
/**
* Returns the `Long` value stored at [key], or [defaultValue] if no value was stored. If a value of a different
* type was stored at `key`, the behavior is not defined.
*/
actual override fun getLong(key: String, defaultValue: Long): Long = delegate.getLong(key, defaultValue)
/**
* Stores the `String` [value] at [key].
*/
actual override fun putString(key: String, value: String): Unit = delegate.edit().putString(key, value).apply()
/**
* Returns the `String` value stored at [key], or [defaultValue] if no value was stored. If a value of a different
* type was stored at `key`, the behavior is not defined.
*/
actual override fun getString(key: String, defaultValue: String): String = delegate.getString(key, defaultValue)
/**
* Stores the `Float` [value] at [key].
*/
actual override fun putFloat(key: String, value: Float): Unit = delegate.edit().putFloat(key, value).apply()
/**
* Returns the `Float` value stored at [key], or [defaultValue] if no value was stored. If a value of a different
* type was stored at `key`, the behavior is not defined.
*/
actual override fun getFloat(key: String, defaultValue: Float): Float = delegate.getFloat(key, defaultValue)
/**
* Stores the `Double` [value] at [key].
*/
actual override fun putDouble(key: String, value: Double): Unit = delegate.edit().putLong(key, value.toRawBits()).apply()
/**
* Returns the `Double` value stored at [key], or [defaultValue] if no value was stored. If a value of a different
* type was stored at `key`, the behavior is not defined.
*/
actual override fun getDouble(key: String, defaultValue: Double): Double =
Double.fromBits(delegate.getLong(key, defaultValue.toRawBits()))
/**
* Stores the `Boolean` [value] at [key].
*/
actual override fun putBoolean(key: String, value: Boolean): Unit = delegate.edit().putBoolean(key, value).apply()
/**
* Returns the `Boolean` value stored at [key], or [defaultValue] if no value was stored. If a value of a different
* type was stored at `key`, the behavior is not defined.
*/
actual override fun getBoolean(key: String, defaultValue: Boolean): Boolean = delegate.getBoolean(key, defaultValue)
}
| 0 | Kotlin | 0 | 0 | 2f80ddc63c9bf124171d76d56e0f0dfabf1afec4 | 7,229 | multiplatform-settings | Apache License 2.0 |
src/test/kotlin/pluralize/PluralizeTest.kt | dchenk | 266,243,310 | false | null | package pluralize
import kotlin.test.Test
import kotlin.test.assertEquals
class PluralizeTest {
@Test
fun pluralizeWithoutSpecifiedPlural() {
assertEquals("friends", "friend".pluralize(0))
assertEquals("friend", "friend".pluralize(1))
assertEquals("friends", "friend".pluralize(2))
assertEquals("horses", "horse".pluralize(0))
assertEquals("horse", "horse".pluralize(1))
assertEquals("horses", "horse".pluralize(35))
}
@Test
fun pluralizeWithSpecifiedPlural() {
assertEquals("friends", "friend".pluralize(0, "friends"))
assertEquals("friend", "friend".pluralize(1, "friends"))
assertEquals("friends", "friend".pluralize(2, "friends"))
// Custom "plural" form.
assertEquals("xyz", "friend".pluralize(0, "xyz"))
assertEquals("friend", "friend".pluralize(1, "xyz"))
assertEquals("xyz", "friend".pluralize(2, "xyz"))
}
}
| 0 | Kotlin | 0 | 0 | b3a1e02c8eb1d49178377b23132b200f1cb11867 | 950 | kt-pluralize | MIT License |
azuredata/src/main/java/com/azure/data/service/DocumentClient.kt | CiskooCiskoo | 247,443,839 | true | {"Kotlin": 565872, "PowerShell": 29081, "Java": 28653, "HTML": 8933, "Batchfile": 816} | package com.azure.data.service
import com.azure.core.http.*
import com.azure.core.log.configureNetworkLogging
import com.azure.core.log.d
import com.azure.core.log.e
import com.azure.core.network.NetworkConnectivity
import com.azure.core.network.NetworkConnectivityManager
import com.azure.core.util.ContextProvider
import com.azure.core.util.DateUtil
import com.azure.core.util.urlEncode
import com.azure.data.constants.HttpHeaderValue
import com.azure.data.constants.MSHttpHeader
import com.azure.data.model.*
import com.azure.data.model.indexing.IndexingPolicy
import com.azure.data.model.partition.PartitionKeyRange
import com.azure.data.model.service.*
import com.azure.data.model.service.Response
import com.azure.data.util.*
import com.azure.data.util.json.ResourceListJsonDeserializer
import com.azure.data.util.json.gson
import getDefaultHeaders
import okhttp3.*
import java.io.IOException
import java.net.URL
import java.text.SimpleDateFormat
import java.util.*
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class DocumentClient private constructor() {
private var host: String? = null
private var permissionProvider: PermissionProvider? = null
private var resourceTokenProvider: ResourceTokenProvider? = null
private var isOffline = false
var connectivityManager: NetworkConnectivityManager? = null
set(value) {
if (isConfigured && value != null) {
value.registerListener(networkConnectivityChanged)
value.startListening()
}
}
//region Configuration
val configuredWithMasterKey: Boolean
get() = resourceTokenProvider != null
fun configure(accountName: String, masterKey: String, permissionMode: PermissionMode) {
resourceTokenProvider = ResourceTokenProvider(masterKey, permissionMode)
commonConfigure("$accountName.documents.azure.com")
}
fun configure(accountUrl: URL, masterKey: String, permissionMode: PermissionMode) {
resourceTokenProvider = ResourceTokenProvider(masterKey, permissionMode)
commonConfigure(accountUrl.host)
}
fun configure(accountUrl: HttpUrl, masterKey: String, permissionMode: PermissionMode) {
resourceTokenProvider = ResourceTokenProvider(masterKey, permissionMode)
commonConfigure(accountUrl.host)
}
fun configure(accountName: String, permissionProvider: PermissionProvider) {
this.permissionProvider = permissionProvider
commonConfigure("$accountName.documents.azure.com")
}
fun configure(accountUrl: URL, permissionProvider: PermissionProvider) {
this.permissionProvider = permissionProvider
commonConfigure(accountUrl.host)
}
fun configure(accountUrl: HttpUrl, permissionProvider: PermissionProvider) {
this.permissionProvider = permissionProvider
commonConfigure(accountUrl.host)
}
val isConfigured: Boolean
get() = !host.isNullOrEmpty() && (resourceTokenProvider != null || permissionProvider != null)
// base headers... grab these once and then re-serve
private val defaultHeaders: Headers by lazy {
ContextProvider.appContext.getDefaultHeaders()
}
private fun commonConfigure(host: String) {
if (host.isEmpty()) {
throw Exception("Host is invalid")
}
this.host = host
ResourceOracle.init(ContextProvider.appContext, host)
PermissionCache.init(host)
connectivityManager = NetworkConnectivity.manager
// create client and configure OkHttp logging if logLevel is low enough
val builder = OkHttpClient.Builder()
configureNetworkLogging(builder)
client = builder.build()
}
fun reset() {
host = null
permissionProvider = null
resourceTokenProvider = null
}
//endregion
//region Network Connectivity
private val networkConnectivityChanged: (Boolean) -> Unit = { isConnected ->
d { "Network Status Changed: ${if (isConnected) "Connected" else "Not Connected"}" }
this.isOffline = !isConnected
if (isConnected) {
ResourceWriteOperationQueue.shared.sync()
}
}
//endregion
//region Database
// create
fun createDatabase(databaseId: String, throughput: Int?, callback: (Response<Database>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Database())
return throughput?.let {
if (!it.isValidThroughput()) {
return callback(Response(DataError(DocumentClientError.InvalidThroughputError)))
}
requestDetails.offerThroughput = it
create(Database(databaseId), requestDetails, callback)
} ?: create(Database(databaseId), requestDetails, callback)
}
// list
fun getDatabases(maxPerPage: Int? = null, callback: (ListResponse<Database>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Database())
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// get
fun getDatabase(databaseId: String, callback: (Response<Database>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Database(databaseId))
return resource(requestDetails, callback)
}
// delete
fun deleteDatabase(databaseId: String, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Database(databaseId))
return delete(requestDetails, callback)
}
//endregion
//region Collections
// create
@Deprecated("Creating a collection without a partition key is deprecated and will be removed in a future version of AzureData", ReplaceWith("createCollection(collectionId: String, throughput: Int? = null, partitionKey: String, databaseId: String, callback: (Response<DocumentCollection>) -> Unit)"))
fun createCollection(collectionId: String, databaseId: String, callback: (Response<DocumentCollection>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Collection(databaseId))
return create(DocumentCollection(collectionId), requestDetails, callback)
}
// create
fun createCollection(collectionId: String, throughput: Int? = null, partitionKey: String, databaseId: String, indexingPolicy: IndexingPolicy? = null, callback: (Response<DocumentCollection>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Collection(databaseId))
return throughput?.let {
if (!it.isValidThroughput()) {
return callback(Response(DataError(DocumentClientError.InvalidThroughputError)))
}
requestDetails.offerThroughput = it
create(DocumentCollection(collectionId, partitionKey, indexingPolicy), requestDetails, callback)
}
?: create(DocumentCollection(collectionId, partitionKey, indexingPolicy), requestDetails, callback)
}
// list
fun getCollectionsIn(databaseId: String, maxPerPage: Int? = null, callback: (ListResponse<DocumentCollection>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Collection(databaseId))
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// get
fun getCollection(collectionId: String, databaseId: String, callback: (Response<DocumentCollection>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Collection(databaseId, collectionId))
return resource(requestDetails, callback)
}
// delete
fun deleteCollection(collectionId: String, databaseId: String, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Collection(databaseId, collectionId))
return delete(requestDetails, callback)
}
// replace
fun replaceCollection(collection: DocumentCollection, databaseId: String, indexingPolicy: IndexingPolicy, callback: (Response<DocumentCollection>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Collection(databaseId, collection.id))
collection.indexingPolicy = indexingPolicy
return replace(collection, requestDetails, callback)
}
// get partition key ranges
fun getCollectionPartitionKeyRanges(collectionId: String, databaseId: String, callback: (ListResponse<PartitionKeyRange>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.PkRanges(databaseId, collectionId))
return resources(requestDetails, callback)
}
//endregion
//region Documents
// create
fun <T : Document> createDocument(document: T, partitionKey: String? = null, preTrigger: String? = null, postTrigger: String? = null, collectionId: String, databaseId: String, callback: (Response<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Document(databaseId, collectionId), partitionKey)
requestDetails.preTriggers = preTrigger?.let { setOf(it) }
requestDetails.postTriggers = postTrigger?.let { setOf(it) }
return create(document, requestDetails, callback)
}
// create
fun <T : Document> createDocument(document: T, partitionKey: String? = null, preTrigger: String? = null, postTrigger: String? = null, collection: DocumentCollection, callback: (Response<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Document, collection), partitionKey)
requestDetails.preTriggers = preTrigger?.let { setOf(it) }
requestDetails.postTriggers = postTrigger?.let { setOf(it) }
return create(document, requestDetails, callback)
}
// createOrReplace
fun <T : Document> createOrUpdateDocument(document: T, partitionKey: String? = null, collectionId: String, databaseId: String, callback: (Response<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Document(databaseId, collectionId), partitionKey)
requestDetails.isUpsert = true
return create(document, requestDetails, callback)
}
// createOrReplace
fun <T : Document> createOrUpdateDocument(document: T, partitionKey: String? = null, collection: DocumentCollection, callback: (Response<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Document, collection), partitionKey)
requestDetails.isUpsert = true
return create(document, requestDetails, callback)
}
// list
fun <T : Document> getDocumentsAs(collectionId: String, databaseId: String, documentClass: Class<T>, maxPerPage: Int? = null, callback: (ListResponse<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Document(databaseId, collectionId))
requestDetails.maxPerPage = maxPerPage
requestDetails.resourceType = documentClass // send the specific doc type here
return resources(requestDetails, callback)
}
// list
fun <T : Document> getDocumentsAs(collection: DocumentCollection, documentClass: Class<T>, maxPerPage: Int? = null, callback: (ListResponse<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Document, collection))
requestDetails.maxPerPage = maxPerPage
requestDetails.resourceType = documentClass // send the specific doc type here
return resources(requestDetails, callback)
}
// get
fun <T : Document> getDocument(documentId: String, partitionKey: String?, collectionId: String, databaseId: String, documentClass: Class<T>, callback: (Response<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Document(databaseId, collectionId, documentId), partitionKey)
requestDetails.resourceType = documentClass // send the specific doc type here
return resource(requestDetails, callback)
}
// get
fun <T : Document> getDocument(documentId: String, partitionKey: String?, collection: DocumentCollection, documentClass: Class<T>, callback: (Response<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Document, collection, documentId), partitionKey)
requestDetails.resourceType = documentClass // send the specific doc type here
return resource(requestDetails, callback)
}
// delete
@Deprecated("Deleting a document without a partition key is deprecated and will be removed in a future version of AzureData", ReplaceWith("deleteDocument(documentId: String, partitionKey: String, collectionId: String, databaseId: String, callback: (DataResponse) -> Unit)"))
fun deleteDocument(documentId: String, collectionId: String, databaseId: String, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Document(databaseId, collectionId, documentId))
return delete(requestDetails, callback)
}
// delete
@Deprecated("Deleting a document without a partition key is deprecated and will be removed in a future version of AzureData", ReplaceWith("deleteDocument(documentId: String, partitionKey: String, collection: DocumentCollection, callback: (DataResponse) -> Unit)"))
fun deleteDocument(documentId: String, collection: DocumentCollection, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Document, collection, documentId))
return delete(requestDetails, callback)
}
// delete
fun <TDoc: Document> deleteDocument(document: TDoc, preTrigger: String? = null, postTrigger: String? = null, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails.fromResource(document)
requestDetails.setResourcePartitionKey(document)
requestDetails.preTriggers = preTrigger?.let { setOf(it) }
requestDetails.postTriggers = postTrigger?.let { setOf(it) }
return delete(requestDetails, callback)
}
// delete
fun deleteDocument(documentId: String, partitionKey: String, collectionId: String, databaseId: String, preTrigger: String? = null, postTrigger: String? = null, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Document(databaseId, collectionId, documentId), partitionKey)
requestDetails.preTriggers = preTrigger?.let { setOf(it) }
requestDetails.postTriggers = postTrigger?.let { setOf(it) }
return delete(requestDetails, callback)
}
// delete
fun deleteDocument(documentId: String, partitionKey: String, collection: DocumentCollection, preTrigger: String? = null, postTrigger: String? = null, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Document, collection, documentId), partitionKey)
requestDetails.preTriggers = preTrigger?.let { setOf(it) }
requestDetails.postTriggers = postTrigger?.let { setOf(it) }
return delete(requestDetails, callback)
}
// replace
fun <T : Document> replaceDocument(document: T, partitionKey: String? = null, collectionId: String, databaseId: String, preTrigger: String? = null, postTrigger: String? = null, callback: (Response<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Document(databaseId, collectionId, document.id), partitionKey)
requestDetails.preTriggers = preTrigger?.let { setOf(it) }
requestDetails.postTriggers = postTrigger?.let { setOf(it) }
return replace(document, requestDetails, callback)
}
// replace
fun <T : Document> replaceDocument(document: T, partitionKey: String? = null, collection: DocumentCollection, preTrigger: String? = null, postTrigger: String? = null, callback: (Response<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Document, collection, document.id), partitionKey)
requestDetails.preTriggers = preTrigger?.let { setOf(it) }
requestDetails.postTriggers = postTrigger?.let { setOf(it) }
return replace(document, requestDetails, callback)
}
// query
fun <T : Document> queryDocuments(collectionId: String, databaseId: String, query: Query, documentClass: Class<T>, maxPerPage: Int? = null, callback: (ListResponse<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Document(databaseId, collectionId))
requestDetails.maxPerPage = maxPerPage
requestDetails.resourceType = documentClass
return query(query, requestDetails, callback)
}
// query
fun <T : Document> queryDocuments(collectionId: String, partitionKey: String, databaseId: String, query: Query, documentClass: Class<T>, maxPerPage: Int? = null, callback: (ListResponse<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Document(databaseId, collectionId), partitionKey)
requestDetails.maxPerPage = maxPerPage
requestDetails.resourceType = documentClass
return query(query, requestDetails, callback)
}
// query
fun <T : Document> queryDocuments(collection: DocumentCollection, query: Query, documentClass: Class<T>, maxPerPage: Int? = null, callback: (ListResponse<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Document, collection))
requestDetails.maxPerPage = maxPerPage
requestDetails.resourceType = documentClass
return query(query, requestDetails, callback)
}
// query
fun <T : Document> queryDocuments(collection: DocumentCollection, partitionKey: String, query: Query, documentClass: Class<T>, maxPerPage: Int? = null, callback: (ListResponse<T>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Document, collection), partitionKey)
requestDetails.maxPerPage = maxPerPage
requestDetails.resourceType = documentClass
return query(query, requestDetails, callback)
}
// get/query a single doc
fun <T : Document> findDocument(documentId: String, collectionId: String, databaseId: String, documentClass: Class<T>, callback: (ListResponse<T>) -> Unit) {
// create query
val query = Query.select()
.from(collectionId)
.where(Resource.Companion.Keys.idKey, documentId)
val requestDetails = RequestDetails(ResourceLocation.Document(databaseId, collectionId))
requestDetails.maxPerPage = 1
requestDetails.resourceType = documentClass
return query(query, requestDetails, callback)
}
// get/query a single doc
fun <T : Document> findDocument(documentId: String, collection: DocumentCollection, documentClass: Class<T>, callback: (ListResponse<T>) -> Unit) {
// create query
val query = Query.select()
.from(collection.id)
.where(Resource.Companion.Keys.idKey, documentId)
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Document, collection))
requestDetails.maxPerPage = 1
requestDetails.resourceType = documentClass
return query(query, requestDetails, callback)
}
//endregion
//region Attachments
// create
fun createAttachment(attachmentId: String, contentType: String, mediaUrl: HttpUrl, documentId: String, collectionId: String, databaseId: String, partitionKey: String, callback: (Response<Attachment>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Attachment(databaseId, collectionId, documentId), partitionKey)
return create(Attachment(attachmentId, contentType, mediaUrl.toString()), requestDetails, callback)
}
// create
fun createAttachment(attachmentId: String, contentType: String, media: ByteArray, documentId: String, collectionId: String, databaseId: String, partitionKey: String, callback: (Response<Attachment>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Attachment(databaseId, collectionId, documentId), partitionKey)
requestDetails.contentType = contentType
requestDetails.slug = attachmentId
requestDetails.body = media
return createOrReplace(requestDetails, false, callback)
}
// create
fun createAttachment(attachmentId: String, contentType: String, mediaUrl: HttpUrl, document: Document, callback: (Response<Attachment>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Attachment, document))
requestDetails.setResourcePartitionKey(document)
return create(Attachment(attachmentId, contentType, mediaUrl.toString()), requestDetails, callback)
}
// create
fun createAttachment(attachmentId: String, contentType: String, media: ByteArray, document: Document, callback: (Response<Attachment>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Attachment, document))
requestDetails.setResourcePartitionKey(document)
requestDetails.contentType = contentType
requestDetails.slug = attachmentId
requestDetails.body = media
return createOrReplace(requestDetails, false, callback)
}
// list
fun getAttachments(documentId: String, collectionId: String, databaseId: String, partitionKey: String, maxPerPage: Int? = null, callback: (ListResponse<Attachment>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Attachment(databaseId, collectionId, documentId), partitionKey)
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// list
fun getAttachments(document: Document, maxPerPage: Int? = null, callback: (ListResponse<Attachment>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Attachment, document))
requestDetails.setResourcePartitionKey(document)
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// delete
fun deleteAttachment(attachmentId: String, documentId: String, collectionId: String, databaseId: String, partitionKey: String, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Attachment(databaseId, collectionId, documentId, attachmentId), partitionKey)
return delete(requestDetails, callback)
}
// delete
fun deleteAttachment(attachmentId: String, document: Document, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Attachment, document, attachmentId))
requestDetails.setResourcePartitionKey(document)
return delete(requestDetails, callback)
}
// replace
fun replaceAttachment(attachmentId: String, contentType: String, mediaUrl: HttpUrl, documentId: String, collectionId: String, databaseId: String, partitionKey: String, callback: (Response<Attachment>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Attachment(databaseId, collectionId, documentId, attachmentId), partitionKey)
return replace(Attachment(attachmentId, contentType, mediaUrl.toString()), requestDetails, callback)
}
// replace
fun replaceAttachment(attachmentId: String, contentType: String, mediaUrl: HttpUrl, document: Document, callback: (Response<Attachment>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Attachment, document, attachmentId))
requestDetails.setResourcePartitionKey(document)
return replace(Attachment(attachmentId, contentType, mediaUrl.toString()), requestDetails, callback)
}
// replace
fun replaceAttachmentMedia(attachmentId: String, contentType: String, media: ByteArray, documentId: String, collectionId: String, databaseId: String, partitionKey: String, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Attachment(databaseId, collectionId, documentId, attachmentId), partitionKey)
resource<Attachment>(requestDetails) { response ->
if (response.isSuccessful) {
response.resource?.let {
replaceAttachmentMedia(it, partitionKey, contentType, media, callback)
}
?: callback(Response(DataError(DocumentClientError.UnknownError), response = response.response))
} else {
callback(Response(response.error!!))
}
}
}
// replace
fun replaceAttachmentMedia(attachment: Attachment, contentType: String, media: ByteArray, document: Document, callback: (DataResponse) -> Unit) {
val partitionKey = PartitionKeyPropertyCache.getPartitionKeyValues(document)
replaceAttachmentMedia(attachment, partitionKey.first(), contentType, media, callback)
}
// replace
fun replaceAttachmentMedia(attachment: Attachment, partitionKey: String, contentType: String, media: ByteArray, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.MediaLink(attachment.mediaLink!!, attachment.resourceId!!), partitionKey)
requestDetails.method = HttpMethod.Put
requestDetails.acceptEncoding = HttpMediaType.Any.value
requestDetails.contentType = contentType
requestDetails.slug = attachment.id
requestDetails.body = media
try {
createRequest(requestDetails) { request ->
sendRequest(request, requestDetails, callback)
}
} catch (ex: Exception) {
e(ex)
callback(Response(DataError(ex)))
}
}
// replace
fun replaceAttachmentMedia(attachmentId: String, contentType: String, media: ByteArray, document: Document, callback: (Response<Attachment>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Attachment, document, attachmentId))
requestDetails.setResourcePartitionKey(document)
requestDetails.contentType = contentType
requestDetails.slug = attachmentId
requestDetails.body = media
return createOrReplace(requestDetails, true, callback)
}
fun getAttachmentMedia(attachmentId: String, document: Document, callback: (Response<ByteArray>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Attachment, document, attachmentId))
requestDetails.setResourcePartitionKey(document)
resource<Attachment>(requestDetails) { response ->
if (response.isSuccessful) {
response.resource?.let {
getAttachmentMedia(it, document, callback)
}
?: callback(Response(DataError(DocumentClientError.UnknownError), response = response.response))
} else {
callback(Response(response.error!!))
}
}
}
fun getAttachmentMedia(attachment: Attachment, document: Document, callback: (Response<ByteArray>) -> Unit) {
val mediaLink = attachment.mediaLink
val requestDetails = RequestDetails(ResourceLocation.MediaLink(mediaLink!!, attachment.resourceId!!))
requestDetails.setResourcePartitionKey(document)
requestDetails.acceptEncoding = HttpMediaType.Any.value
requestDetails.cacheControl = HttpHeaderValue.noCache
return getMedia(requestDetails, callback)
}
//endregion
//region Stored Procedures
// create
fun createStoredProcedure(storedProcedureId: String, procedure: String, collectionId: String, databaseId: String, callback: (Response<StoredProcedure>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.StoredProcedure(databaseId, collectionId))
return create(StoredProcedure(storedProcedureId, procedure), requestDetails, callback)
}
// create
fun createStoredProcedure(storedProcedureId: String, procedure: String, collection: DocumentCollection, callback: (Response<StoredProcedure>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.StoredProcedure, collection))
return create(StoredProcedure(storedProcedureId, procedure), requestDetails, callback)
}
// list
fun getStoredProcedures(collectionId: String, databaseId: String, maxPerPage: Int? = null, callback: (ListResponse<StoredProcedure>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.StoredProcedure(databaseId, collectionId))
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// list
fun getStoredProcedures(collection: DocumentCollection, maxPerPage: Int? = null, callback: (ListResponse<StoredProcedure>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.StoredProcedure, collection))
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// delete
fun deleteStoredProcedure(storedProcedureId: String, collectionId: String, databaseId: String, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.StoredProcedure(databaseId, collectionId, storedProcedureId))
return delete(requestDetails, callback)
}
// delete
fun deleteStoredProcedure(storedProcedureId: String, collection: DocumentCollection, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.StoredProcedure, collection, storedProcedureId))
return delete(requestDetails, callback)
}
// replace
fun replaceStoredProcedure(storedProcedureId: String, procedure: String, collectionId: String, databaseId: String, callback: (Response<StoredProcedure>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.StoredProcedure(databaseId, collectionId, storedProcedureId))
return replace(StoredProcedure(storedProcedureId, procedure), requestDetails, callback)
}
// replace
fun replaceStoredProcedure(storedProcedureId: String, procedure: String, collection: DocumentCollection, callback: (Response<StoredProcedure>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.StoredProcedure, collection, storedProcedureId))
return replace(StoredProcedure(storedProcedureId, procedure), requestDetails, callback)
}
// execute
fun executeStoredProcedure(storedProcedureId: String, parameters: List<String>?, partitionKey: String? = null, collectionId: String, databaseId: String, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.StoredProcedure(databaseId, collectionId, storedProcedureId), partitionKey)
return execute(requestDetails, parameters, callback)
}
// execute
fun executeStoredProcedure(storedProcedureId: String, parameters: List<String>?, partitionKey: String? = null, collection: DocumentCollection, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.StoredProcedure, collection, storedProcedureId), partitionKey)
return execute(requestDetails, parameters, callback)
}
//endregion
//region User Defined Functions
// create
fun createUserDefinedFunction(userDefinedFunctionId: String, functionBody: String, collectionId: String, databaseId: String, callback: (Response<UserDefinedFunction>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Udf(databaseId, collectionId))
return create(UserDefinedFunction(userDefinedFunctionId, functionBody), requestDetails, callback)
}
// create
fun createUserDefinedFunction(userDefinedFunctionId: String, functionBody: String, collection: DocumentCollection, callback: (Response<UserDefinedFunction>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Udf, collection))
return create(UserDefinedFunction(userDefinedFunctionId, functionBody), requestDetails, callback)
}
// list
fun getUserDefinedFunctions(collectionId: String, databaseId: String, maxPerPage: Int? = null, callback: (ListResponse<UserDefinedFunction>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Udf(databaseId, collectionId))
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// list
fun getUserDefinedFunctions(collection: DocumentCollection, maxPerPage: Int? = null, callback: (ListResponse<UserDefinedFunction>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Udf, collection))
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// delete
fun deleteUserDefinedFunction(userDefinedFunctionId: String, collectionId: String, databaseId: String, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Udf(databaseId, collectionId, userDefinedFunctionId))
return delete(requestDetails, callback)
}
// delete
fun deleteUserDefinedFunction(userDefinedFunctionId: String, collection: DocumentCollection, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Udf, collection, userDefinedFunctionId))
return delete(requestDetails, callback)
}
// replace
fun replaceUserDefinedFunction(userDefinedFunctionId: String, function: String, collectionId: String, databaseId: String, callback: (Response<UserDefinedFunction>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Udf(databaseId, collectionId, userDefinedFunctionId))
return replace(UserDefinedFunction(userDefinedFunctionId, function), requestDetails, callback)
}
// replace
fun replaceUserDefinedFunction(userDefinedFunctionId: String, function: String, collection: DocumentCollection, callback: (Response<UserDefinedFunction>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Udf, collection, userDefinedFunctionId))
return replace(UserDefinedFunction(userDefinedFunctionId, function), requestDetails, callback)
}
//endregion
//region Triggers
// create
fun createTrigger(triggerId: String, operation: Trigger.Operation, triggerType: Trigger.Type, triggerBody: String, collectionId: String, databaseId: String, callback: (Response<Trigger>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Trigger(databaseId, collectionId))
return create(Trigger(triggerId, triggerBody, operation, triggerType), requestDetails, callback)
}
// create
fun createTrigger(triggerId: String, operation: Trigger.Operation, triggerType: Trigger.Type, triggerBody: String, collection: DocumentCollection, callback: (Response<Trigger>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Trigger, collection))
return create(Trigger(triggerId, triggerBody, operation, triggerType), requestDetails, callback)
}
// list
fun getTriggers(collectionId: String, databaseId: String, maxPerPage: Int? = null, callback: (ListResponse<Trigger>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Trigger(databaseId, collectionId))
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// list
fun getTriggers(collection: DocumentCollection, maxPerPage: Int? = null, callback: (ListResponse<Trigger>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Trigger, collection))
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// delete
fun deleteTrigger(triggerId: String, collectionId: String, databaseId: String, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Trigger(databaseId, collectionId, triggerId))
return delete(requestDetails, callback)
}
// delete
fun deleteTrigger(triggerId: String, collection: DocumentCollection, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Trigger, collection, triggerId))
return delete(requestDetails, callback)
}
// replace
fun replaceTrigger(triggerId: String, operation: Trigger.Operation, triggerType: Trigger.Type, triggerBody: String, collectionId: String, databaseId: String, callback: (Response<Trigger>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Trigger(databaseId, collectionId, triggerId))
return replace(Trigger(triggerId, triggerBody, operation, triggerType), requestDetails, callback)
}
// replace
fun replaceTrigger(triggerId: String, operation: Trigger.Operation, triggerType: Trigger.Type, triggerBody: String, collection: DocumentCollection, callback: (Response<Trigger>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Trigger, collection, triggerId))
return replace(Trigger(triggerId, triggerBody, operation, triggerType), requestDetails, callback)
}
//endregion
//region Users
// create
fun createUser(userId: String, databaseId: String, callback: (Response<User>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.User(databaseId))
return create(User(userId), requestDetails, callback)
}
// list
fun getUsers(databaseId: String, maxPerPage: Int? = null, callback: (ListResponse<User>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.User(databaseId))
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// get
fun getUser(userId: String, databaseId: String, callback: (Response<User>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.User(databaseId, userId))
return resource(requestDetails, callback)
}
// delete
fun deleteUser(userId: String, databaseId: String, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.User(databaseId, userId))
return delete(requestDetails, callback)
}
// replace
fun replaceUser(userId: String, newUserId: String, databaseId: String, callback: (Response<User>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.User(databaseId, userId))
return replace(User(newUserId), requestDetails, callback)
}
//endregion
//region Permissions
// create
fun createPermission(permissionId: String, permissionMode: PermissionMode, resource: Resource, userId: String, databaseId: String, callback: (Response<Permission>) -> Unit) {
val permission = Permission(permissionId, permissionMode, resource.selfLink!!)
val requestDetails = RequestDetails(ResourceLocation.Permission(databaseId, userId))
return create(permission, requestDetails, callback)
}
// create
fun createPermission(permissionId: String, permissionMode: PermissionMode, resource: Resource, user: User, callback: (Response<Permission>) -> Unit) {
val permission = Permission(permissionId, permissionMode, resource.selfLink!!)
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Permission, user))
return create(permission, requestDetails, callback)
}
// list
fun getPermissions(userId: String, databaseId: String, maxPerPage: Int? = null, callback: (ListResponse<Permission>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Permission(databaseId, userId))
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// list
fun getPermissions(user: User, maxPerPage: Int? = null, callback: (ListResponse<Permission>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Permission, user))
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// get
fun getPermission(permissionId: String, userId: String, databaseId: String, callback: (Response<Permission>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Permission(databaseId, userId, permissionId))
return resource(requestDetails, callback)
}
// get
fun getPermission(permissionId: String, user: User, callback: (Response<Permission>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Permission, user, permissionId))
return resource(requestDetails, callback)
}
// delete
fun deletePermission(permissionId: String, userId: String, databaseId: String, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Permission(databaseId, userId, permissionId))
return delete(requestDetails, callback)
}
// delete
fun deletePermission(permissionId: String, user: User, callback: (DataResponse) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Permission, user, permissionId))
return delete(requestDetails, callback)
}
// replace
fun replacePermission(permissionId: String, permissionMode: PermissionMode, resourceSelfLink: String, userId: String, databaseId: String, callback: (Response<Permission>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Permission(databaseId, userId, permissionId))
return replace(Permission(permissionId, permissionMode, resourceSelfLink), requestDetails, callback)
}
// replace
fun replacePermission(permissionId: String, permissionMode: PermissionMode, resourceSelfLink: String, user: User, callback: (Response<Permission>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Child(ResourceType.Permission, user, permissionId))
return replace(Permission(permissionId, permissionMode, resourceSelfLink), requestDetails, callback)
}
//endregion
//region Offers
// list
fun getOffers(maxPerPage: Int? = null, callback: (ListResponse<Offer>) -> Unit) {
val requestDetails = RequestDetails(ResourceLocation.Offer())
requestDetails.maxPerPage = maxPerPage
return resources(requestDetails, callback)
}
// get
fun getOffer(offerId: String, callback: (Response<Offer>) -> Unit): Any {
return resource(RequestDetails(ResourceLocation.Offer(offerId)), callback)
}
//endregion
//region Resource operations
// create
private fun <T : Resource> create(resource: T, requestDetails: RequestDetails, callback: (Response<T>) -> Unit) {
if (!resource.hasValidId()) {
return callback(Response(DataError(DocumentClientError.InvalidId)))
}
createOrReplace(resource, requestDetails, false, callback)
}
// list
private fun <T : Resource> resources(requestDetails: RequestDetails, callback: (ListResponse<T>) -> Unit) {
requestDetails.method = HttpMethod.Get
createRequest(requestDetails) { request ->
sendResourceListRequest<T>(
request,
requestDetails,
callback = { response ->
processResourceListResponse(
requestDetails,
response,
callback
)
}
)
}
}
// get
private fun <T : Resource> resource(requestDetails: RequestDetails, callback: (Response<T>) -> Unit) {
requestDetails.method = HttpMethod.Get
createRequest(requestDetails) { request ->
sendResourceRequest<T>(
request,
requestDetails,
callback = { response ->
processResourceGetResponse(
requestDetails,
response,
callback
)
}
)
}
}
// refresh
fun <T : Resource> refresh(resource: T, partitionKey: String? = null, callback: (Response<T>) -> Unit) {
return try {
val requestDetails = RequestDetails.fromResource(resource, partitionKey)
requestDetails.method = HttpMethod.Get
// if we have an eTag, we'll set & send the IfNoneMatch header
requestDetails.ifNoneMatchETag = resource.etag
createRequest(requestDetails) { request ->
//send the request!
sendResourceRequest(request, requestDetails, resource, callback)
}
} catch (ex: Exception) {
e(ex)
callback(Response(DataError(ex)))
}
}
// delete
private fun delete(requestDetails: RequestDetails, callback: (DataResponse) -> Unit) {
requestDetails.method = HttpMethod.Delete
createRequest(requestDetails) { request ->
sendRequest(
request,
requestDetails,
callback = { response: DataResponse ->
processDeleteResponse(
requestDetails,
response,
callback
)
}
)
}
}
fun <TResource : Resource> delete(resource: TResource, partitionKey: String? = null, callback: (DataResponse) -> Unit) {
return try {
val requestDetails = RequestDetails.fromResource(resource, partitionKey)
delete(requestDetails, callback)
} catch (ex: Exception) {
e(ex)
callback(Response(DataError(ex)))
}
}
// replace
private fun <T : Resource> replace(resource: T, requestDetails: RequestDetails, callback: (Response<T>) -> Unit) {
if (!resource.hasValidId()) {
return callback(Response(DataError(DocumentClientError.InvalidId)))
}
createOrReplace(resource, requestDetails, true, callback)
}
// create or replace
internal fun <T : Resource> createOrReplace(body: T, requestDetails: RequestDetails, replacing: Boolean = false, callback: (Response<T>) -> Unit) {
try {
requestDetails.method = if (replacing) HttpMethod.Put else HttpMethod.Post
//serialize the resource
requestDetails.body = gson.toJson(body).toByteArray()
requestDetails.resourceType = body::class.java
//look for partition key property(ies) to send for this resource type
requestDetails.setResourcePartitionKey(body)
createRequest(requestDetails) { request ->
sendResourceRequest(
request,
requestDetails,
callback = { response: Response<T> ->
processCreateOrReplaceResponse(
body,
requestDetails,
replacing,
response,
callback
)
}
)
}
} catch (ex: Exception) {
e(ex)
callback(Response(DataError(ex)))
}
}
// create or replace
private fun <T : Resource> createOrReplace(requestDetails: RequestDetails, replacing: Boolean = false, callback: (Response<T>) -> Unit) {
try {
requestDetails.method = if (replacing) HttpMethod.Put else HttpMethod.Post
createRequest(requestDetails) { request ->
sendResourceRequest(request, requestDetails, callback)
}
} catch (ex: Exception) {
e(ex)
callback(Response(DataError(ex)))
}
}
// query
private fun <T : Resource> query(query: Query, requestDetails: RequestDetails, callback: (ListResponse<T>) -> Unit) {
try {
requestDetails.isQuery = true
requestDetails.method = HttpMethod.Post
requestDetails.body = gson.toJson(query.dictionary).toByteArray()
createRequest(requestDetails) { request ->
sendResourceListRequest<T>(request, requestDetails) { response ->
processQueryResponse(query, requestDetails, response) { processedResponse ->
if (processedResponse.isSuccessful) { // success case
callback(processedResponse)
} else if (processedResponse.isErrored && processedResponse.error!!.isInvalidCrossPartitionQueryError()) {
// if we've tried to query cross partition but have a TOP or ORDER BY, we'll get a specific error we can work around by using partition key range Ids
// reference: https://stackoverflow.com/questions/50240232/cosmos-db-rest-api-order-by-with-partitioning
// we will grab the partition key ranges for the collection we're querying
val dbId = requestDetails.resourceLocation.ancestorIds().getValue(ResourceType.Database)
val collId = requestDetails.resourceLocation.ancestorIds().getValue(ResourceType.Collection)
getCollectionPartitionKeyRanges(collId, dbId) { pkRanges ->
// THEN, we can retry our request after setting the range Id header
requestDetails.partitionKeyRange = pkRanges.resource
createRequest(requestDetails) { retryRequest ->
sendResourceListRequest<T>(retryRequest, requestDetails) { retryResponse ->
processQueryResponse(query, requestDetails, retryResponse) {
// DO NOT try to inline this into the method call above. Bad. Things. Happen.
callback(it)
}
}
}
}
}
}
}
}
} catch (ex: Exception) {
e(ex)
callback(ListResponse(DataError(ex)))
}
}
// next
internal fun <T : Resource> next(response : ListResponse<T>, callback: (ListResponse<T>) -> Unit) {
try {
val request = response.request
?: return callback(ListResponse(DataError(DocumentClientError.NextCalledTooEarlyError)))
val continuation = response.metadata.continuation
?: return callback(ListResponse(DataError(DocumentClientError.NoMoreResultsError)))
val resourceLocation = response.resourceLocation
?: return callback(ListResponse(DataError(DocumentClientError.NextCalledTooEarlyError)))
val resourceType = response.resourceType
?: return callback(ListResponse(DataError(DocumentClientError.NextCalledTooEarlyError)))
val requestDetails = RequestDetails(resourceLocation)
requestDetails.resourceType = resourceType
val newRequest = request.newBuilder()
.header(MSHttpHeader.MSContinuation.value, continuation)
.build()
client.newCall(newRequest)
.enqueue(object : Callback {
// only transport errors handled here
override fun onFailure(call: Call, e: IOException) {
isOffline = true
// todo: callback with cached data instead of the callback with the error below
callback(ListResponse(DataError(e)))
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: okhttp3.Response) =
callback(processListResponse(request, response, requestDetails))
})
} catch (ex: Exception) {
e(ex)
callback(ListResponse(DataError(ex)))
}
}
// execute
private fun <T> execute(requestDetails: RequestDetails, body: T? = null, callback: (DataResponse) -> Unit) {
try {
requestDetails.method = HttpMethod.Post
requestDetails.body = body?.let { gson.toJson(body).toByteArray() } ?: gson.toJson(arrayOf<String>()).toByteArray()
createRequest(requestDetails) { request ->
sendRequest(request, requestDetails, callback)
}
} catch (ex: Exception) {
e(ex)
callback(Response(DataError(ex)))
}
}
// get media bytes
private fun getMedia(requestDetails: RequestDetails, callback: (Response<ByteArray>) -> Unit) {
requestDetails.method = HttpMethod.Get
createRequest(requestDetails) { request ->
sendByteRequest(request, callback)
}
}
//endregion
//region Network plumbing
private val dateFormatter : SimpleDateFormat by lazy {
DateUtil.getDateFromatter(DateUtil.Format.Rfc1123Format)
}
private inline fun getTokenForResource(requestDetails: RequestDetails, crossinline callback: (Response<ResourceToken>) -> Unit) {
if (!isConfigured) {
return callback(Response(DataError(DocumentClientError.ConfigureError)))
}
if (requestDetails.resourceLocation.id?.isValidIdForResource() == false) {
return callback(Response(DataError(DocumentClientError.InvalidId)))
}
if (resourceTokenProvider != null) {
resourceTokenProvider!!.getToken(requestDetails.resourceLocation, requestDetails.method)?.let {
return callback(Response(it))
}
} else {
if (!requestDetails.resourceLocation.supportsPermissionToken) {
return callback(Response(DataError(DocumentClientError.PermissionError)))
}
return permissionProvider?.getPermission(requestDetails.resourceLocation, if (requestDetails.method.isWrite()) PermissionMode.All else PermissionMode.Read) {
if (it.isSuccessful) {
val dateString = String.format("%s %s", dateFormatter.format(Date()), "GMT")
it.resource?.token?.let { token ->
callback(Response(ResourceToken(token.urlEncode(), dateString)))
} ?: callback(Response(DataError(DocumentClientError.PermissionError)))
} else {
callback(Response(it.error!!))
}
} ?: callback(Response(DataError(DocumentClientError.UnknownError)))
}
return callback(Response(DataError(DocumentClientError.UnknownError)))
}
private inline fun createRequest(requestDetails: RequestDetails, crossinline callback: (Request) -> Unit) {
getTokenForResource(requestDetails) {
when {
it.isSuccessful -> it.resource?.let { token ->
val url = HttpUrl.Builder()
.scheme(HttpScheme.Https.toString())
.host(this.host!!)
.addPathSegment(requestDetails.resourceLocation.path())
.build()
val headersBuilder = Headers.Builder()
// add base headers
headersBuilder.addAll(defaultHeaders)
// set the api version
headersBuilder.add(MSHttpHeader.MSVersion.value, HttpHeaderValue.apiVersion)
// and the token data
headersBuilder.add(MSHttpHeader.MSDate.value, token.date)
headersBuilder.add(HttpHeader.Authorization.value, token.token)
// fill in all extra headers defined by the request details
requestDetails.fillHeaders(headersBuilder)
callback(requestDetails.buildRequest(url, headersBuilder))
} ?: throw DocumentClientError.UnknownError
it.isErrored -> throw it.error!!
else -> throw DocumentClientError.UnknownError
}
}
}
private inline fun <T : Resource> sendResourceRequest(request: Request, requestDetails: RequestDetails, crossinline callback: (Response<T>) -> Unit)
= sendResourceRequest(request, requestDetails, null, callback)
private inline fun <T : Resource> sendResourceRequest(request: Request, requestDetails: RequestDetails, resource: T?, crossinline callback: (Response<T>) -> Unit) {
try {
client.newCall(request)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e(e)
isOffline = true
callback(Response(DataError(DocumentClientError.InternetConnectivityError), request))
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: okhttp3.Response) =
callback(processResponse(request, response, requestDetails, resource))
})
} catch (ex: Exception) {
e(ex)
callback(Response(DataError(ex), request))
}
}
private inline fun sendRequest(request: Request, requestDetails: RequestDetails, crossinline callback: (DataResponse) -> Unit) {
try {
client.newCall(request)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e(e)
isOffline = true
callback(Response(DataError(DocumentClientError.InternetConnectivityError), request))
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: okhttp3.Response) =
callback(processDataResponse(request, requestDetails.resourceLocation, response))
})
} catch (ex: Exception) {
e(ex)
callback(Response(DataError(ex), request))
}
}
private inline fun sendByteRequest(request: Request, crossinline callback: (Response<ByteArray>) -> Unit) {
try {
client.newCall(request)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e(e)
isOffline = true
callback(Response(DataError(DocumentClientError.InternetConnectivityError), request))
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: okhttp3.Response) =
callback(processByteResponse(request, response))
})
} catch (ex: Exception) {
e(ex)
callback(Response(DataError(ex), request))
}
}
private inline fun <T : Resource> sendResourceListRequest(request: Request, requestDetails: RequestDetails, crossinline callback: (ListResponse<T>) -> Unit) {
try {
client.newCall(request)
.enqueue(object : Callback {
// only transport errors handled here
override fun onFailure(call: Call, e: IOException) {
e(e)
isOffline = true
callback(ListResponse(DataError(DocumentClientError.InternetConnectivityError), request))
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: okhttp3.Response) =
callback(processListResponse(request, response, requestDetails))
})
} catch (ex: Exception) {
e(ex)
callback(ListResponse(DataError(ex), request))
}
}
private fun <T : Resource> processResponse(request: Request, response: okhttp3.Response, requestDetails: RequestDetails, resource: T?): Response<T> {
try {
val body = response.body
?: return Response(DataError("Empty response body received"))
val json = body.string()
val code = response.code
//check http return code/success
when {
// HttpStatusCode.Created: // cache locally
// HttpStatusCode.NoContent: // DELETEing a resource remotely should delete the cached version (if the delete was successful indicated by a response status code of 204 No Content); also a PUT can/will return this status
// HttpStatusCode.Unauthorized:
// HttpStatusCode.Forbidden: // reauth
// HttpStatusCode.Conflict: // conflict callback
// HttpStatusCode.NotFound: // (indicating the resource has been deleted/no longer exists in the remote database), confirm that resource does not exist locally, and if it does, delete it
// HttpStatusCode.PreconditionFailure: // The operation specified an eTag that is different from the version available at the server, that is, an optimistic concurrency error. Retry the request after reading the latest version of the resource and updating the eTag on the request.
response.isSuccessful -> {
val type = requestDetails.resourceType ?: resource?.javaClass ?: requestDetails.resourceLocation.resourceType.type
val returnedResource = gson.fromJson<T>(json, type)
?: return Response(json.toError())
setResourceMetadata(response, returnedResource, requestDetails.resourceLocation.resourceType)
return Response(request, response, json, Result(returnedResource))
}
code == HttpStatusCode.NotModified.code -> {
resource?.let {
setResourceMetadata(response, it, requestDetails.resourceLocation.resourceType)
}
//return the original resource
return Response(request, response, json, Result(resource))
}
else -> return Response(json.toError(), request, response, json)
}
} catch (e: Exception) {
return Response(DataError(e), request, response)
}
}
private fun <T : Resource> processListResponse(request: Request, response: okhttp3.Response, requestDetails: RequestDetails): ListResponse<T> {
return try {
val body = response.body
?: return ListResponse(DataError("Empty response body received"), request, response)
val json = body.string()
if (response.isSuccessful) {
val type = requestDetails.resourceType ?: requestDetails.resourceLocation.resourceType.type
val resourceList = ResourceListJsonDeserializer<T>().deserialize(json, type)
setResourceMetadata(response, resourceList, requestDetails.resourceLocation.resourceType)
ResourceCache.shared.cache(resourceList)
ListResponse(request, response, json, Result(resourceList), requestDetails.resourceLocation, type)
} else {
ListResponse(json.toError(), request, response, json)
}
} catch (e: Exception) {
ListResponse(DataError(e), request, response)
}
}
private fun <T : Resource> processCreateOrReplaceResponse(resource: T, requestDetails: RequestDetails, replace: Boolean, response: Response<T>, callback: (Response<T>) -> Unit) {
when {
response.isSuccessful -> {
callback(response)
when (replace) {
true -> response.resource?.let { ResourceCache.shared.replace(it) }
false -> response.resource?.let { ResourceCache.shared.cache(it) }
}
}
response.isErrored -> {
if (response.error!!.isConnectivityError()) {
ResourceWriteOperationQueue.shared.addCreateOrReplace(resource, requestDetails, replace, callback)
return
}
callback(response)
}
else -> {
callback(response)
}
}
}
private fun <T : Resource> processResourceGetResponse(requestDetails: RequestDetails, response: Response<T>, callback: (Response<T>) -> Unit) {
when {
response.isSuccessful -> {
callback(response)
response.resource?.let { ResourceCache.shared.cache(it) }
}
response.isErrored -> {
if (response.error!!.isConnectivityError()) {
cachedResource(requestDetails, response, callback)
return
}
if (response.is404()) {
ResourceCache.shared.remove(requestDetails.resourceLocation)
}
callback(response)
}
else -> { callback(response) }
}
}
private fun <T : Resource> processResourceListResponse(requestDetails: RequestDetails, response: ListResponse<T>, callback: (ListResponse<T>) -> Unit) {
when {
response.isSuccessful -> {
callback(response)
response.resource?.let { ResourceCache.shared.cache(it) }
}
response.isErrored -> {
if (response.error!!.isConnectivityError()) {
cachedResources(requestDetails, response, callback)
return
}
callback(response)
}
else -> { callback(response) }
}
}
private fun <T : Resource> processQueryResponse(query: Query, requestDetails: RequestDetails, response: ListResponse<T>, callback: (ListResponse<T>) -> Unit) {
when {
response.isSuccessful -> {
callback(response)
response.resource?.let { ResourceCache.shared.cache(it, query, requestDetails.resourceLocation.link()) }
}
response.isErrored -> {
if (response.error!!.isConnectivityError()) {
cachedResources(query, requestDetails, response, callback)
return
}
callback(response)
}
else -> { callback(response) }
}
}
private fun processDeleteResponse(requestDetails: RequestDetails, response: DataResponse, callback: (DataResponse) -> Unit) {
when {
response.isSuccessful -> {
callback(response)
ResourceCache.shared.remove(requestDetails.resourceLocation)
}
response.isErrored -> {
if (response.error!!.isConnectivityError()) {
ResourceWriteOperationQueue.shared.addDelete(requestDetails, callback)
return
}
callback(response)
}
}
}
private fun processDataResponse(request: Request, resourceLocation: ResourceLocation, response: okhttp3.Response): DataResponse {
try {
val body = response.body
?: return Response(DataError("Empty response body received"), request, response)
val responseBodyString = body.string()
//check http return code
return if (response.isSuccessful) {
if (request.method == HttpMethod.Delete.toString()) {
ResourceCache.shared.remove(resourceLocation)
}
DataResponse(request, response, responseBodyString, Result(responseBodyString))
} else {
Response(responseBodyString.toError(), request, response, responseBodyString)
}
} catch (e: Exception) {
return Response(DataError(e), request, response)
}
}
private fun processByteResponse(request: Request, response: okhttp3.Response): Response<ByteArray> {
try {
val body = response.body
?: return Response(DataError("Empty response body received"), request, response)
//check http return code
return if (response.isSuccessful) {
Response(request, response, "{}", Result(body.bytes()))
} else {
val responseBodyString = body.string()
Response(responseBodyString.toError(), request, response, responseBodyString)
}
} catch (e: Exception) {
return Response(DataError(e), request, response)
}
}
private fun setResourceMetadata(response: okhttp3.Response, resource: ResourceBase, resourceType: ResourceType) {
//grab & store alt Link and persist alt link <-> self link mapping
val altContentPath = response.header(MSHttpHeader.MSAltContentPath.value, null)
resource.setAltContentLink(resourceType.path, altContentPath)
ResourceOracle.shared.storeLinks(resource)
}
//endregion
//region Cache Responses
private fun <T : Resource> cachedResource(requestDetails: RequestDetails, response: Response<T>? = null, callback: (Response<T>) -> Unit) {
val type = requestDetails.resourceType ?: requestDetails.resourceLocation.resourceType.type
return ResourceCache.shared.getResourceAt<T>(requestDetails.resourceLocation, type)?.let { resource ->
callback(Response(response?.request, response?.response, response?.jsonData, Result(resource), requestDetails.resourceLocation, response?.resourceType, true))
} ?: callback(Response(DataError(DocumentClientError.NotFound)))
}
private fun <T : Resource> cachedResources(requestDetails: RequestDetails, response: ListResponse<T>? = null, callback: (ListResponse<T>) -> Unit) {
val type = requestDetails.resourceType ?: requestDetails.resourceLocation.resourceType.type
return ResourceCache.shared.getResourcesAt<T>(requestDetails.resourceLocation, type)?.let { resources ->
callback(ListResponse(response?.request, response?.response, response?.jsonData, Result(resources), requestDetails.resourceLocation, response?.resourceType, true))
} ?: callback(ListResponse(DataError(DocumentClientError.ServiceUnavailableError)))
}
private fun <T : Resource> cachedResources(query: Query, requestDetails: RequestDetails, response: ListResponse<T>? = null, callback: (ListResponse<T>) -> Unit) {
val type = requestDetails.resourceType ?: requestDetails.resourceLocation.resourceType.type
return ResourceCache.shared.getResourcesForQuery<T>(query, type)?.let { resources ->
callback(ListResponse(response?.request, response?.response, response?.jsonData, Result(resources), requestDetails.resourceLocation, response?.resourceType, true))
} ?: callback(ListResponse(DataError(DocumentClientError.ServiceUnavailableError)))
}
//endregion
companion object {
val shared = DocumentClient()
lateinit var client: OkHttpClient
}
} | 0 | null | 0 | 0 | 6477f880d0a7b55c0f2fda320febe307199e1ca3 | 72,756 | azure-sdk-for-android | MIT License |
src/main/kotlin/com/vepanimas/intellij/prisma/ide/structureview/PrismaStructureViewElement.kt | vepanimas | 527,378,342 | false | {"Kotlin": 303241, "HTML": 7321, "Lex": 2375, "JavaScript": 1076} | package com.vepanimas.intellij.prisma.ide.structureview
import com.intellij.ide.projectView.PresentationData
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.util.treeView.smartTree.SortableTreeElement
import com.intellij.ide.util.treeView.smartTree.TreeElement
import com.intellij.navigation.ItemPresentation
import com.intellij.psi.NavigatablePsiElement
import com.vepanimas.intellij.prisma.lang.psi.PrismaDeclaration
import com.vepanimas.intellij.prisma.lang.psi.PrismaFile
class PrismaStructureViewElement(val element: NavigatablePsiElement) : StructureViewTreeElement, SortableTreeElement {
override fun getPresentation(): ItemPresentation = element.presentation ?: PresentationData()
override fun navigate(requestFocus: Boolean) = element.navigate(requestFocus)
override fun canNavigate(): Boolean = element.canNavigate()
override fun canNavigateToSource(): Boolean = element.canNavigateToSource()
override fun getValue(): Any = element
override fun getAlphaSortKey(): String = element.name.orEmpty()
override fun getChildren(): Array<TreeElement> {
return when (element) {
is PrismaFile -> element.declarations.map { PrismaStructureViewElement(it) }.toTypedArray()
is PrismaDeclaration -> element.getMembers().map { PrismaStructureViewElement(it) }.toTypedArray()
else -> emptyArray()
}
}
} | 0 | Kotlin | 0 | 0 | f98b18d5f9f451d70994ebe672ab9a584f184b73 | 1,427 | intellij-prisma | Apache License 2.0 |
app/src/main/java/com/android/sensyneapplication/domain/search/RegexProcessor.kt | mobileappconsultant | 310,363,474 | false | null | package com.android.sensyneapplication.domain.search
interface RegexProcessor {
/**
* This method is the basis of any regex validation
* It takes a string that represents a generic search that has been fully typed in
* or in being typed in. The processor runs a validation process and
* returns a list of database tables that are being queried
*
*
*/
fun process(searchEntry: String): List<String>
}
| 0 | Kotlin | 0 | 1 | 7071b065bbc66dd47b55fa42ef1f75636425df7a | 444 | SensedyneTestProject | MIT License |
feature_playerfullscreen/src/main/java/com/allsoftdroid/audiobook/feature/feature_playerfullscreen/presentation/MainPlayerViewModel.kt | pravinyo | 209,936,085 | false | null | package com.allsoftdroid.audiobook.feature.feature_playerfullscreen.presentation
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.allsoftdroid.audiobook.feature.feature_playerfullscreen.data.PlayerControlState
import com.allsoftdroid.audiobook.feature.feature_playerfullscreen.data.PlayingTrackDetails
import com.allsoftdroid.audiobook.feature.feature_playerfullscreen.di.FeatureMainPlayerModule.SUPER_VISOR_JOB
import com.allsoftdroid.audiobook.feature.feature_playerfullscreen.di.FeatureMainPlayerModule.VIEW_MODEL_SCOPE
import com.allsoftdroid.audiobook.feature.feature_playerfullscreen.domain.usecase.GetPlayingTrackProgressUsecase
import com.allsoftdroid.audiobook.feature.feature_playerfullscreen.domain.usecase.GetTrackRemainingTimeUsecase
import com.allsoftdroid.common.base.extension.Event
import com.allsoftdroid.common.base.extension.PlayingState
import com.allsoftdroid.common.base.store.audioPlayer.*
import com.allsoftdroid.common.base.store.userAction.OpenMiniPlayerUI
import com.allsoftdroid.common.base.store.userAction.UserActionEventStore
import com.allsoftdroid.common.base.usecase.BaseUseCase
import com.allsoftdroid.common.base.usecase.UseCaseHandler
import kotlinx.coroutines.CompletableJob
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.koin.core.KoinComponent
import org.koin.core.inject
import org.koin.core.qualifier.named
import timber.log.Timber
class MainPlayerViewModel(
private val playerEventStore : AudioPlayerEventStore,
private val userActionEventStore: UserActionEventStore,
private val useCaseHandler : UseCaseHandler,
private val trackProgressUsecase: GetPlayingTrackProgressUsecase,
private val remainingTimeUsecase: GetTrackRemainingTimeUsecase) : ViewModel(), KoinComponent {
/**
* cancelling this job cancels all the job started by this viewmodel
*/
private val viewModelJob: CompletableJob by inject(named(name = SUPER_VISOR_JOB))
/**
* main scope for all coroutine launched by viewmodel
*/
private val viewModelScope : CoroutineScope by inject(named(name = VIEW_MODEL_SCOPE))
private var _playerControlState = MutableLiveData<Event<PlayerControlState>>()
val previousControlState : LiveData<Event<PlayerControlState>> = _playerControlState
private var _shouldItPlay:Boolean = false
var shouldItPlay = MutableLiveData<Boolean>()
private var _playingTrackDetails = MutableLiveData<PlayingTrackDetails>()
val playingTrackDetails : LiveData<PlayingTrackDetails> = _playingTrackDetails
private var currentPlayingIndex = 0
private var isBookFinished:Boolean = false
val trackProgress:LiveData<Int>
get() = trackProgressUsecase.trackProgress
val trackRemainingTime:LiveData<String>
get() = remainingTimeUsecase.trackRemainingTime
private var _isPlayerBusy : Boolean = false
fun playPrevious(){
_playerControlState.value = Event(PlayerControlState(playPrevious = true))
Timber.d("Sending new Previous event")
playerEventStore.publish(
Event(
Previous(
PlayingState(
playingItemIndex = currentPlayingIndex - 1,
action_need = true
)
)
)
)
}
fun goBackward(){
Timber.d("Sending new Rewind event")
playerEventStore.publish(Event(Rewind))
}
fun goForward(){
Timber.d("Sending new Forward event")
playerEventStore.publish(Event(Forward))
}
fun playNext(){
_playerControlState.value = Event(PlayerControlState(playNext = true))
Timber.d("Sending new next event")
playerEventStore.publish(
Event(
Next(
PlayingState(
playingItemIndex = currentPlayingIndex + 1,
action_need = true
)
)
)
)
}
fun playPause(){
setShouldPlay(!_shouldItPlay)
_playerControlState.value = Event(PlayerControlState(shouldItPlay = _shouldItPlay))
shouldPlayEvent()
}
fun bookFinished(isFinished: Boolean = true){
isBookFinished = isFinished
}
fun setBookDetails(bookId:String, bookName:String, trackName:String, currentPlayingTrack: Int, totalChapter:Int,isPlaying:Boolean){
_playingTrackDetails.value = PlayingTrackDetails(
bookIdentifier = bookId,
bookTitle = bookName,
trackName = trackName,
chapterIndex = currentPlayingTrack,
totalChapter = totalChapter,
isPlaying = isPlaying
)
currentPlayingIndex = currentPlayingTrack
viewModelScope.launch {
initTrackProgress()
initTrackRemainingTimeStatus()
}
}
fun updateTrackDetails(chapterIndex:Int,chapterTitle:String){
_playingTrackDetails.value?.let {
setBookDetails(it.bookIdentifier,it.bookTitle,chapterTitle,chapterIndex,it.totalChapter,it.isPlaying)
}
}
private fun setShouldPlay(play:Boolean){
_shouldItPlay = play
shouldItPlay.value = _shouldItPlay
}
private fun shouldPlayEvent(){
Timber.d("should play event is $_shouldItPlay")
if(_shouldItPlay){
Timber.d("Sending new play event")
playerEventStore.publish(
Event(
Play(
PlayingState(
playingItemIndex = currentPlayingIndex,
action_need = true
)
)
)
)
}else{
Timber.d("Sending new pause event")
playerEventStore.publish(
Event(
Pause(
PlayingState(
playingItemIndex = currentPlayingIndex,
action_need = true
)
)
)
)
}
}
fun showMiniPlayerIfPlaying(){
if (!isBookFinished){
Timber.d("Book is not finished: Sending open mini player")
userActionEventStore.publish(Event(OpenMiniPlayerUI(this::class.java.simpleName)))
}else{
Timber.d("Book is finished: No action required")
}
}
private suspend fun initTrackProgress() {
useCaseHandler.execute(trackProgressUsecase,GetPlayingTrackProgressUsecase.RequestValues(),
object : BaseUseCase.UseCaseCallback<GetPlayingTrackProgressUsecase.ResponseValues>{
override suspend fun onSuccess(response: GetPlayingTrackProgressUsecase.ResponseValues) {
Timber.d("Track Progress initialization completed")
}
override suspend fun onError(t: Throwable) {
Timber.d("Track Progress init error: ${t.message}")
}
})
}
private suspend fun initTrackRemainingTimeStatus() {
useCaseHandler.execute(remainingTimeUsecase,GetTrackRemainingTimeUsecase.RequestValues(),
object : BaseUseCase.UseCaseCallback<GetTrackRemainingTimeUsecase.ResponseValues>{
override suspend fun onSuccess(response: GetTrackRemainingTimeUsecase.ResponseValues) {
Timber.d("Track remaining time initialization completed")
}
override suspend fun onError(t: Throwable) {
Timber.d("Track remaining time init error: ${t.message}")
}
})
}
fun resumeProgressTracking(){
trackProgressUsecase.start()
remainingTimeUsecase.start()
}
fun stopProgressTracking(){
trackProgressUsecase.cancel()
remainingTimeUsecase.cancel()
}
fun setPlayerBusy(status:Boolean){
_isPlayerBusy = status
}
fun isPlayerBusy() = _isPlayerBusy
override fun onCleared() {
super.onCleared()
stopProgressTracking()
viewModelJob.cancel()
}
} | 3 | Kotlin | 4 | 12 | 8358f69c0cf8dbde18904b0c3a304ec89b518c9b | 8,251 | AudioBook | MIT License |
server/src/main/kotlin/com/studystream/app/data/database/extensions/enums/EnumTable.kt | ImpossibleAccuracy | 834,219,225 | false | {"Kotlin": 89003, "Dockerfile": 618} | package com.studystream.data.database.extensions.enums
import org.jetbrains.exposed.dao.id.IntIdTable
import org.jetbrains.exposed.sql.Column
import kotlin.reflect.KClass
abstract class EnumTable<T : Enum<T>>(
tableName: String,
columnName: String = "title",
columnLength: Int = 255,
enum: KClass<T>,
) : IntIdTable(tableName) {
val title: Column<T> = enumerationByName(columnName, columnLength, enum)
} | 0 | Kotlin | 0 | 0 | 9f3afd2307a90836d2628752f3be5e6438a675e8 | 425 | study-stream | The Unlicense |
feature-progress/src/main/java/com/dragote/feature/progress/region/domain/scenario/GetRegionProgressScenario.kt | Dragote | 718,160,762 | false | {"Kotlin": 147679} | package com.dragote.feature.progress.region.domain.scenario
import com.dragote.shared.country.domain.entity.Region
import com.dragote.shared.country.domain.usecase.GetCountriesUseCase
import com.dragote.shared.stats.domain.usecase.GetCountryStatsUseCase
import javax.inject.Inject
class GetRegionProgressScenario @Inject constructor(
private val getCountriesUseCase: GetCountriesUseCase,
private val getCountryStatsUseCase: GetCountryStatsUseCase,
) {
suspend operator fun invoke(region: Region): Float {
val countryList = getCountriesUseCase(region)
if (countryList.isEmpty()) throw Exception("Country list can't be empty")
val stats = countryList.sumOf { countryInfo ->
getCountryStatsUseCase(countryInfo.id).progress.toDouble()
} / countryList.size
return stats.toFloat()
}
} | 0 | Kotlin | 0 | 2 | 59d44860a9a74bd8824e6e617f834102a3a1f7b1 | 852 | Flapp | MIT License |
domain/src/main/kotlin/de/kramhal/server/service/DomainEntityController.kt | gaerfield | 273,227,978 | false | null | package de.kramhal.server.service
import de.kramhal.server.domain.DomainEntity
import de.kramhal.server.domain.DomainEntityId
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.web.bind.annotation.*
interface DomainEntityRepository : JpaRepository<DomainEntity, DomainEntityId>
@RestController
@RequestMapping("/domain-entity")
class DomainEntityController(
val repo: DomainEntityRepository
) {
@GetMapping
fun get() : List<DomainEntity> = repo.findAll()
data class CreateDomainEntity(val description: String)
@PostMapping
fun create(@RequestBody create: CreateDomainEntity) : DomainEntity
= repo.save(DomainEntity(create.description))
} | 0 | Kotlin | 0 | 0 | df211001444990e32af77299d66eacaab08cec90 | 715 | hibernate-ij-bug-reproduction | MIT License |
skrapers/src/main/kotlin/ru/sokomishalov/skraper/provider/pikabu/PikabuSkraper.kt | edwinRNDR | 262,866,888 | true | {"Kotlin": 201997, "Shell": 41, "Batchfile": 33} | /**
* Copyright (c) 2019-present Mikhael Sokolov
*
* 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 ru.sokomishalov.skraper.provider.pikabu
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import ru.sokomishalov.skraper.Skraper
import ru.sokomishalov.skraper.SkraperClient
import ru.sokomishalov.skraper.client.jdk.DefaultBlockingSkraperClient
import ru.sokomishalov.skraper.fetchDocument
import ru.sokomishalov.skraper.internal.jsoup.*
import ru.sokomishalov.skraper.internal.number.div
import ru.sokomishalov.skraper.model.*
import java.nio.charset.Charset
import java.time.Duration
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import kotlin.text.Charsets.UTF_8
class PikabuSkraper(
override val client: SkraperClient = DefaultBlockingSkraperClient,
override val baseUrl: URLString = "https://pikabu.ru"
) : Skraper {
override suspend fun getPosts(path: String, limit: Int): List<Post> {
val page = getPage(path = path)
val stories = page
?.getElementsByTag("article")
?.take(limit)
.orEmpty()
return stories.map {
val storyBlocks = it.getElementsByClass("story-block")
val title = it.extractPostTitle()
val text = storyBlocks.parseText()
val caption = when {
text.isBlank() -> title
else -> "${title}\n\n${text}"
}
Post(
id = it.extractPostId(),
text = String(caption.toByteArray(UTF_8)),
publishedAt = it.extractPostPublishDate(),
rating = it.extractPostRating(),
commentsCount = it.extractPostCommentsCount(),
media = storyBlocks.extractPostMediaItems()
)
}
}
override suspend fun getPageInfo(path: String): PageInfo? {
val page = getPage(path = path)
val isCommunity = path.contains("community")
return when {
isCommunity -> PageInfo(
nick = page.extractCommunityNick(),
name = page.extractCommunityName(),
postsCount = page.extractCommunityPostsCount(),
followersCount = page.extractCommunityFollowersCount(),
avatarsMap = singleImageMap(url = page.extractCommunityAvatar()),
coversMap = singleImageMap(url = page.extractPageCover())
)
else -> PageInfo(
nick = page.extractUserNick(),
name = page.extractUserNick(),
postsCount = page.extractUserPostsCount(),
followersCount = page.extractUserFollowersCount(),
avatarsMap = singleImageMap(url = page.extractUserAvatar()),
coversMap = singleImageMap(url = page.extractPageCover())
)
}
}
private suspend fun getPage(path: String): Document? {
return client.fetchDocument(
url = baseUrl.buildFullURL(path = path),
charset = Charset.forName("windows-1251")
)
}
private fun Element.extractPostId(): String {
return getFirstElementByClass("story__title-link")
?.attr("href")
?.substringAfter("${baseUrl}/story/")
.orEmpty()
}
private fun Element.extractPostTitle(): String {
return getFirstElementByClass("story__title-link")
?.wholeText()
.orEmpty()
}
private fun Element.extractPostPublishDate(): Long? {
return getFirstElementByTag("time")
?.attr("datetime")
?.run { ZonedDateTime.parse(this, DATE_FORMATTER).toEpochSecond() }
}
private fun Element.extractPostRating(): Int? {
return getFirstElementByClass("story__rating-count")
?.wholeText()
?.toIntOrNull()
}
private fun Element.extractPostCommentsCount(): Int? {
return getFirstElementByClass("story__comments-link-count")
?.wholeText()
?.toIntOrNull()
}
private fun Elements.extractPostMediaItems(): List<Media> {
return mapNotNull { b ->
when {
"story-block_type_image" in b.classNames() -> {
Image(
url = b
.getFirstElementByTag("img")
?.getFirstAttr("data-src", "src")
.orEmpty(),
aspectRatio = b
.getFirstElementByTag("rect")
?.run {
attr("width")?.toDoubleOrNull() / attr("height")?.toDoubleOrNull()
}
)
}
"story-block_type_video" in b.classNames() -> b
.getFirstElementByAttributeValueContaining("data-type", "video")
?.run {
Video(
url = attr("data-source").orEmpty(),
aspectRatio = attr("data-ratio")?.toDoubleOrNull(),
duration = attr("data-duration")?.toLongOrNull()?.let { Duration.ofSeconds(it) }
)
}
else -> null
}
}
}
private fun Document?.extractUserAvatar(): String? {
return this
?.getFirstElementByClass("main")
?.getFirstElementByClass("avatar")
?.getFirstElementByTag("img")
?.attr("data-src")
}
private fun Document?.extractCommunityAvatar(): String? {
return this
?.getFirstElementByClass("community-avatar")
?.getFirstElementByTag("img")
?.attr("data-src")
}
private fun Document?.extractUserNick(): String? {
return this
?.getFirstElementByClass("profile__nick")
?.getFirstElementByTag("span")
?.wholeText()
}
private fun Document?.extractCommunityNick(): String? {
return this
?.getFirstElementByClass("community-header__controls")
?.getFirstElementByTag("span")
?.attr("data-link-name")
}
private fun Document?.extractCommunityName(): String {
return this
?.getFirstElementByClass("community-header__title")
?.wholeText()
.orEmpty()
}
private fun Document?.extractCommunityPostsCount(): Int? {
return this
?.getFirstElementByAttributeValue("data-role", "stories_cnt")
?.attr("data-value")
?.toIntOrNull()
}
private fun Document?.extractCommunityFollowersCount(): Int? {
return this
?.getFirstElementByAttributeValue("data-role", "subs_cnt")
?.attr("data-value")
?.toIntOrNull()
}
private fun Document?.extractUserFollowersCount(): Int? {
return this
?.getElementsByClass("profile__digital")
?.getOrNull(1)
?.attr("aria-label")
?.trim()
?.toIntOrNull()
}
private fun Document?.extractUserPostsCount(): Int? {
return this
?.getElementsByClass("profile__digital")
?.getOrNull(3)
?.getFirstElementByTag("b")
?.wholeText()
?.trim()
?.toIntOrNull()
}
private fun Document?.extractPageCover(): String? {
return this
?.getFirstElementByClass("background__placeholder")
?.getBackgroundImageStyle()
}
private fun Elements.parseText(): String {
return filter { b -> "story-block_type_text" in b.classNames() }
.joinToString("\n") { b -> b.wholeText() }
}
companion object {
private val DATE_FORMATTER = DateTimeFormatter.ISO_DATE_TIME
}
} | 0 | Kotlin | 0 | 0 | d65c41d559552796497bdeb2007b472dc9c58220 | 8,836 | skraper | Apache License 2.0 |
chat/chat_domain/src/main/java/com/beomsu317/chat_domain/di/ChatDomainModule.kt | beomsu317 | 485,776,806 | false | null | package com.beomsu317.chat_domain.di
import com.beomsu317.chat_domain.repository.ChatRepository
import com.beomsu317.chat_domain.use_case.*
import com.beomsu317.core.domain.repository.CoreRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object ChatDomainModule {
@Provides
@Singleton
fun provideChatUseCases(chatRepository: ChatRepository, coreRepository: CoreRepository): ChatUseCases {
return ChatUseCases(
createRoomUseCase = CreateRoomUseCase(chatRepository),
getLastMessagesFlowUseCase = GetLastMessagesFlowUseCase(chatRepository),
getMessagesFlowUseCase = GetMessagesFlowUseCase(chatRepository),
getFriendUseCase = GetFriendUseCase(chatRepository),
sendMessageUseCase = SendMessageUseCase(chatRepository),
readAllMessagesUseCase = ReadAllMessagesUseCase(chatRepository),
getRecentMessagesUseCase = GetRecentMessagesUseCase(chatRepository, coreRepository = coreRepository),
leaveRoomUseCase = LeaveRoomUseCase(chatRepository),
connectToServerUseCase = ConnectToServerUseCase(chatRepository, coreRepository),
removeMessagesUseCase = RemoveMessagesUseCase(chatRepository)
)
}
} | 0 | Kotlin | 0 | 0 | 4ff38347196aaebb75d2729d62289bc717f14370 | 1,397 | private-chat-app | Apache License 2.0 |
android/src/main/kotlin/com/transcoder/lat_hdr_transcoder_v2/lat_hdr_transcoder_v2/TranscoderErrorType.kt | thangpn0207 | 748,556,813 | false | {"Kotlin": 9883, "Swift": 9155, "Dart": 5154, "Ruby": 2289, "Objective-C": 38} | package com.transcoder.lat_hdr_transcoder_v2.lat_hdr_transcoder_v2
import androidx.annotation.NonNull
import io.flutter.plugin.common.MethodChannel
enum class TranscoderErrorType (private val rawValue: Int) {
InvalidArgs(0),
NotSupportVersion(1),
ExistsOutputFile(2),
FailedTranscode(3);
private val code: String
get() = "$rawValue"
private fun message(extra: String?): String {
return when (this) {
InvalidArgs -> "argument are not valid"
NotSupportVersion -> "os version is not supported: $extra"
ExistsOutputFile -> "output file exists: $extra"
FailedTranscode -> "failed transcode error: $extra"
}
}
fun occurs(@NonNull result: MethodChannel.Result, extra: String? = null) {
result.error(code, message(extra), null)
}
} | 0 | Kotlin | 0 | 0 | 83d183f06757864abf69b5e7fc927ad3eb7b8f90 | 843 | lat_hdr_transcoder_v2 | MIT License |
rest-contract/src/main/kotlin/dev/hypest/pis/orders/FinalizeOrderRequest.kt | PIS22Z | 557,250,063 | false | {"Kotlin": 118874, "Groovy": 79090, "Dockerfile": 145} | package dev.hypest.pis.orders
import java.util.UUID
data class FinalizeOrderRequest(
val userId: UUID,
val deliveryDetails: DeliveryDetails
) {
data class DeliveryDetails(
val address: String
)
}
| 0 | Kotlin | 0 | 0 | a5eab87108f49a6355362682b94b7c49d5dd421b | 222 | backend | MIT License |
app/src/main/java/com/dheerajk1994/app/MainActivity.kt | Dheerajk1994 | 366,529,195 | false | null | package com.dheerajk1994.app
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.dheerajk1994.pine.Pine
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Pine.setLogLevel(Pine.LogLevel.INFO)
Pine.i("hello")
Pine.w("test warning")
Pine.d("test debug")
Pine.v("test verbose")
Pine.e("test error")
btn_test_button.setOnClickListener {
Pine.logStep("pressed ", btn_test_button)
}
testFunction()
}
private fun testFunction() {
Pine.d("test")
}
} | 0 | Kotlin | 0 | 0 | c719d3e7647c2ac133382d4b01338e1550a02c3b | 777 | Pine | Apache License 2.0 |
generator/src/test/kotlin/at/yawk/javabrowser/generator/MavenTest.kt | yawkat | 135,326,421 | false | {"Git Config": 1, "Python": 1, "Maven POM": 4, "Text": 1, "Ignore List": 1, "Markdown": 1, "YAML": 2, "Kotlin": 172, "Java": 3, "PLpgSQL": 1, "FreeMarker": 13, "Fluent": 3, "CSS": 7, "JavaScript": 3, "robots.txt": 1, "SVG": 2, "XML": 1, "SQL": 2} | package at.yawk.javabrowser.generator
import org.testng.Assert
import org.testng.annotations.Test
/**
* @author yawkat
*/
class MavenTest {
@Test
fun deps() {
val dependencies = MavenDependencyResolver().getMavenDependencies("com.google.guava", "guava", "25.1-jre")
Assert.assertTrue(
dependencies.map { it.coordinate.toCanonicalForm() }
.any { it.matches("com.google.errorprone:.*".toRegex()) }
)
}
@Test
fun `central location`() {
MavenDependencyResolver().getMavenDependencies("org.jdbi", "jdbi3-testing", "3.8.2")
}
} | 17 | Kotlin | 3 | 35 | b9233824bf594bacffaee2efbf12ab9ea941763e | 622 | java-browser | Apache License 2.0 |
common/src/commonMain/kotlin/com/darkrockstudios/apps/hammer/common/components/encyclopedia/ViewEntry.kt | Wavesonics | 499,367,913 | false | null | package com.darkrockstudios.apps.hammer.common.components.encyclopedia
import com.arkivanov.decompose.value.Value
import com.darkrockstudios.apps.hammer.common.data.MenuItemDescriptor
import com.darkrockstudios.apps.hammer.common.data.encyclopediarepository.EntryResult
import com.darkrockstudios.apps.hammer.common.data.encyclopediarepository.entry.EntryContent
import com.darkrockstudios.apps.hammer.common.data.encyclopediarepository.entry.EntryDef
interface ViewEntry {
val state: Value<State>
data class State(
val entryDef: EntryDef,
val entryImagePath: String? = null,
val content: EntryContent? = null,
val showAddImageDialog: Boolean = false,
val showDeleteImageDialog: Boolean = false,
val showDeleteEntryDialog: Boolean = false,
val editText: Boolean = false,
val editName: Boolean = false,
val confirmClose: Boolean = false,
val menuItems: Set<MenuItemDescriptor> = emptySet(),
)
fun getImagePath(entryDef: EntryDef): String?
suspend fun loadEntryContent(entryDef: EntryDef): EntryContent
suspend fun deleteEntry(entryDef: EntryDef): Boolean
suspend fun updateEntry(name: String, text: String, tags: List<String>): EntryResult
suspend fun removeEntryImage(): Boolean
suspend fun setImage(path: String)
fun showDeleteEntryDialog()
fun closeDeleteEntryDialog()
fun showDeleteImageDialog()
fun closeDeleteImageDialog()
fun showAddImageDialog()
fun closeAddImageDialog()
fun startNameEdit()
fun startTextEdit()
fun finishNameEdit()
fun finishTextEdit()
fun confirmClose()
fun dismissConfirmClose()
} | 7 | null | 6 | 42 | cfd42f869c895ee116129691afd05b656e09cc9b | 1,555 | hammer-editor | MIT License |
okio-testing-support/src/nonWasmMain/kotlin/okio/TestingNonWasm.kt | square | 17,812,502 | false | {"Kotlin": 1559919, "Java": 43685, "Shell": 1180} | /*
* Copyright (C) 2023 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import okio.fakefilesystem.FakeFileSystem
actual typealias Clock = kotlinx.datetime.Clock
actual typealias Instant = kotlinx.datetime.Instant
actual fun fromEpochSeconds(
epochSeconds: Long,
) = Instant.fromEpochSeconds(epochSeconds)
actual fun fromEpochMilliseconds(
epochMilliseconds: Long,
) = Instant.fromEpochMilliseconds(epochMilliseconds)
actual val FileSystem.isFakeFileSystem: Boolean
get() = this is FakeFileSystem
actual val FileSystem.allowSymlinks: Boolean
get() = (this as? FakeFileSystem)?.allowSymlinks == true
actual val FileSystem.allowReadsWhileWriting: Boolean
get() = (this as? FakeFileSystem)?.allowReadsWhileWriting == true
actual var FileSystem.workingDirectory: Path
get() {
return when (this) {
is FakeFileSystem -> workingDirectory
is ForwardingFileSystem -> delegate.workingDirectory
else -> error("cannot get working directory: $this")
}
}
set(value) {
when (this) {
is FakeFileSystem -> workingDirectory = value
is ForwardingFileSystem -> delegate.workingDirectory = value
else -> error("cannot set working directory: $this")
}
}
| 89 | Kotlin | 1178 | 8,795 | 0f6c9cf31101483e6ee9602e80a10f7697c8f75a | 1,753 | okio | Apache License 2.0 |
kover-gradle-plugin/src/main/kotlin/kotlinx/kover/gradle/aggregation/settings/tasks/KoverHtmlReportTask.kt | Kotlin | 394,574,917 | false | {"Kotlin": 680192, "Java": 23398} | /*
* Copyright 2017-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.kover.gradle.aggregation.settings.tasks
import kotlinx.kover.features.jvm.ClassFilters
import kotlinx.kover.features.jvm.KoverLegacyFeatures
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.*
import java.io.File
import java.net.URI
@CacheableTask
internal abstract class KoverHtmlReportTask : AbstractKoverTask() {
@get:OutputDirectory
abstract val htmlDir: DirectoryProperty
@get:Input
abstract val title: Property<String>
@get:Input
@get:Optional
abstract val charset: Property<String>
private val projectPath = project.path
@TaskAction
fun generate() {
KoverLegacyFeatures.generateHtmlReport(
htmlDir.asFile.get(),
charset.orNull,
reports,
outputs,
sources,
title.get(),
ClassFilters(includedClasses.get(), excludedClasses.get(), emptySet(), emptySet(), emptySet(), emptySet())
)
}
fun printPath() {
val clickablePath = URI(
"file",
"",
File(htmlDir.get().asFile.canonicalPath, "index.html").toURI().path,
null,
null,
).toASCIIString()
logger.lifecycle("Kover: HTML report for '$projectPath' $clickablePath")
}
} | 63 | Kotlin | 51 | 1,322 | 9d72c749701f1f661cf48672ae84bdabfd80a874 | 1,450 | kotlinx-kover | Apache License 2.0 |
app/src/main/java/com/aksh/counter/settings/Settings.kt | akshdeep-singh | 403,694,230 | false | {"Kotlin": 20749} | package com.aksh.counter.settings
import android.content.Context
class Settings(context: Context) {
private val prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE)
private fun getBoolean(key: String, default: Boolean) = prefs.getBoolean(key, default)
private fun setBoolean(key: String, value: Boolean) = prefs.edit().putBoolean(key, value).apply()
private fun getInt(key: String, default: Int) = prefs.getInt(key, default)
private fun setInt(key: String, value: Int) = prefs.edit().putInt(key, value).apply()
class CounterAction {
companion object {
const val INCREMENT = 1
const val DECREMENT = 2
const val RESET = 3
}
}
class CounterAnimation {
companion object {
const val OFF = 1
const val FADE = 2
const val SLIDE = 3
}
}
class CounterTextSize {
companion object {
const val SMALL = 24
const val MEDIUM = 32
const val LARGE = 40
}
}
companion object {
private const val KEY_ENABLED_COUNTER_ANIMATION = "keca"
private const val KEY_ENABLED_COUNTER_ALWAYS_ON = "kecao"
private const val KEY_ENABLED_COUNTER_CYCLE = "kecc"
private const val KEY_ENABLED_COUNTER_CYCLE_VIBRATE = "keccv"
private const val KEY_ENABLED_BUTTON_1 = "keb1"
private const val KEY_ENABLED_BUTTON_2 = "keb2"
private const val KEY_ENABLED_BUTTON_3 = "keb3"
private const val KEY_COUNTER_ANIMATION = "kca"
private const val KEY_COUNTER_CYCLE_LENGTH = "kccl"
private const val KEY_COUNTER_TEXT_SIZE = "kcts"
private const val KEY_BUTTON_1_ACTION = "kb1a"
private const val KEY_BUTTON_2_ACTION = "kb2a"
private const val KEY_BUTTON_3_ACTION = "kb3a"
}
var isCounterAnimationEnabled
get() = getBoolean(KEY_ENABLED_COUNTER_ANIMATION, true)
set(value) = setBoolean(KEY_ENABLED_COUNTER_ANIMATION, value)
var isCounterAlwaysOnEnabled
get() = getBoolean(KEY_ENABLED_COUNTER_ALWAYS_ON, false)
set(value) = setBoolean(KEY_ENABLED_COUNTER_ALWAYS_ON, value)
var isCounterCycleEnabled
get() = getBoolean(KEY_ENABLED_COUNTER_CYCLE, false)
set(value) = setBoolean(KEY_ENABLED_COUNTER_CYCLE, value)
var isCounterCycleVibrateEnabled
get() = getBoolean(KEY_ENABLED_COUNTER_CYCLE_VIBRATE, true)
set(value) = setBoolean(KEY_ENABLED_COUNTER_CYCLE_VIBRATE, value)
var isButton1Enabled
get() = getBoolean(KEY_ENABLED_BUTTON_1, true)
set(value) = setBoolean(KEY_ENABLED_BUTTON_1, value)
var isButton2Enabled
get() = getBoolean(KEY_ENABLED_BUTTON_2, false)
set(value) = setBoolean(KEY_ENABLED_BUTTON_2, value)
var isButton3Enabled
get() = getBoolean(KEY_ENABLED_BUTTON_3, false)
set(value) = setBoolean(KEY_ENABLED_BUTTON_3, value)
var counterAnimation
get() = getInt(KEY_COUNTER_ANIMATION, CounterAnimation.OFF)
set(value) = setInt(KEY_COUNTER_ANIMATION, value)
var counterCycleLength
get() = getInt(KEY_COUNTER_CYCLE_LENGTH, 10)
set(value) = setInt(KEY_COUNTER_CYCLE_LENGTH, value)
var counterTextSize
get() = getInt(KEY_COUNTER_TEXT_SIZE, CounterTextSize.MEDIUM)
set(value) = setInt(KEY_COUNTER_TEXT_SIZE, value)
var button1Action
get() = getInt(KEY_BUTTON_1_ACTION, CounterAction.INCREMENT)
set(value) = setInt(KEY_BUTTON_1_ACTION, value)
var button2Action
get() = getInt(KEY_BUTTON_2_ACTION, CounterAction.DECREMENT)
set(value) = setInt(KEY_BUTTON_2_ACTION, value)
var button3Action
get() = getInt(KEY_BUTTON_3_ACTION, CounterAction.RESET)
set(value) = setInt(KEY_BUTTON_3_ACTION, value)
} | 0 | Kotlin | 0 | 0 | ec9a1d7ef9cb3b78ce7258fe3ff6e1850113344c | 3,859 | counter_wear_os | MIT License |
komapper-dialect-postgresql-r2dbc/src/main/kotlin/org/komapper/dialect/postgresql/r2dbc/PostgreSqlR2dbcPointType.kt | komapper | 349,909,214 | false | {"Kotlin": 2652019, "Java": 57131} | package org.komapper.dialect.postgresql.r2dbc
import io.r2dbc.postgresql.codec.Point
import io.r2dbc.spi.Row
import org.komapper.r2dbc.AbstractR2dbcDataType
object PostgreSqlR2dbcPointType : AbstractR2dbcDataType<Point>(Point::class) {
override val name: String = "point"
override fun getValue(row: Row, index: Int): Point? {
return row.get(index, Point::class.java)
}
override fun getValue(row: Row, columnLabel: String): Point? {
return row.get(columnLabel, Point::class.java)
}
}
| 10 | Kotlin | 13 | 282 | 66dad22411fe5aebb51b7227a8eb9247a88891cf | 523 | komapper | Apache License 2.0 |
examples/wa-articles/src/main/java/com/anymore/wanandroid/articles/entry/ArticleTag.kt | anymao | 234,439,982 | false | null | package com.anymore.wanandroid.articles.entry
import java.io.Serializable
/**
* 文章tag
*/
data class ArticleTag(
val name: String,
val url: String
) : Serializable | 0 | Kotlin | 0 | 5 | f0c89b016e16303840e61c60337c39e82bf8c872 | 174 | Andkit | MIT License |
idea/testData/joinLines/removeBraces/IfWithElse.kt | JakeWharton | 99,388,807 | false | null | fun foo() {
<caret>if (a) {
bar1()
} else {
bar2()
}
}
| 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 83 | kotlin | Apache License 2.0 |
wework/src/main/java/com/wework/xposed/wework/util/ServiceUtil.kt | gtsigner | 162,666,532 | false | {"Kotlin": 121770, "Java": 8812} | package com.wework.xposed.wework.util
import com.wework.xposed.wework.WkGlobal
import com.wework.xposed.wework.WkObject
import de.robv.android.xposed.XposedHelpers
object ServiceUtil {
/**
* 获取会话引擎
* @return Conver
*/
public fun getConversationEngineInstance(): Any {
val conversationEngine = XposedHelpers.findClass(WkObject.ConversationEngine.C.ConversationEngine, WkGlobal.workLoader)
val instance = XposedHelpers.callStaticMethod(conversationEngine, WkObject.ConversationEngine.M.GetInstance)
return instance as Any
}
/**
* 获取会话服务
*/
public fun getConversationServiceInstance(): Any {
//通过引擎去拿service
val conversationEngine = WkObject.getClass(WkObject.ConversationEngine.C.ConversationEngine)
val service = XposedHelpers.callStaticMethod(conversationEngine, WkObject.ConversationEngine.M.GetConversationService)
return service as Any
}
/**
* 部门服务
*/
public fun getDepartmentService(): Any {
val conversationEngine = XposedHelpers.findClass(WkObject.ConversationEngine.C.ConversationEngine, WkGlobal.workLoader)
val service = XposedHelpers.callStaticMethod(conversationEngine, WkObject.ConversationEngine.M.GetDepartmentService)
return service as Any
}
} | 2 | Kotlin | 47 | 65 | d9aee1fe3c07443a18eb2fbbf47668effca17269 | 1,314 | wework-hook-example | MIT License |
orchestrate/src/commonMain/kotlin/com/jeantuffier/statemachine/orchestrate/SideEffect.kt | jeantuffier | 448,109,955 | false | null | package com.jeantuffier.statemachine.orchestrate
interface SideEffect {
val id: Long
}
| 0 | Kotlin | 0 | 2 | 031b240f4bbe3bb41d2b539005e7326c69f673ea | 92 | statemachine | MIT License |
src/main/kotlin/com/notnite/scraft/Scraft.kt | NotNite | 665,349,097 | false | null | package com.notnite.scraft
import com.notnite.scraft.commands.APIKeyCommand
import com.notnite.scraft.commands.ClaimUserCommand
import com.notnite.scraft.commands.DropUserCommand
import com.notnite.scraft.commands.ListUsersCommand
import com.notnite.scraft.database.ScraftDatabase
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback
import net.minecraft.network.ClientConnection
import net.minecraft.server.command.CommandManager
import org.slf4j.LoggerFactory
object Scraft : ModInitializer {
val logger = LoggerFactory.getLogger("scraft")
private val connections = mutableMapOf<ClientConnection, ScraftState>()
override fun onInitialize() {
ScraftDatabase.init()
CommandRegistrationCallback.EVENT.register { dispatcher, registry, env ->
if (!env.dedicated) return@register
val branch = CommandManager.literal("scraft")
ClaimUserCommand.register(branch)
DropUserCommand.register(branch)
APIKeyCommand.register(branch)
ListUsersCommand.register(branch)
dispatcher.register(branch)
}
}
fun getConnectionState(connection: ClientConnection): ScraftState = connections.getOrPut(connection) { ScraftState() }
fun removeConnectionState(connection: ClientConnection) = connections.remove(connection)
}
| 0 | Kotlin | 0 | 2 | cf9da5759db676b3578b1383e46f54a713876fb5 | 1,392 | scraft | MIT License |
StudyPlanet/src/main/java/com/qwict/studyplanetandroid/StudyPlanetApplication.kt | Qwict | 698,396,315 | false | {"Kotlin": 199488} | package com.qwict.studyplanetandroid
import android.app.Application
import android.content.Context
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.qwict.studyplanetandroid.common.AuthenticationSingleton
import com.qwict.studyplanetandroid.presentation.StudyPlanetNavigation
import com.qwict.studyplanetandroid.presentation.StudyPlanetScreens
import com.qwict.studyplanetandroid.presentation.components.nav.AppBar
import com.qwict.studyplanetandroid.presentation.components.nav.NavBar
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
/**
* The [Application] class for the StudyPlanet application.
*
* The [StudyPlanetApplication] class initializes the application and sets up the application context.
*/
@HiltAndroidApp
class StudyPlanetApplication : Application() {
private lateinit var appScope: CoroutineScope
/**
* Called when the application is starting. Initializes the [CoroutineScope] and sets the application context.
*/
override fun onCreate() {
super.onCreate()
appScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
appContext = applicationContext
}
/**
* The [Companion] object holds properties and functions that are shared across all instances of [StudyPlanetApplication].
*/
companion object {
// Might not be useful, because context is available everywhere... (looked cool tho)
lateinit var appContext: Context
}
}
/**
* The main [Composable] function for the StudyPlanet application.
*
* @param navController The [NavHostController] used for navigation within the application.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StudyPlanetApp(
navController: NavHostController = rememberNavController(),
) {
// Retrieve the current back stack entry
val backStackEntry by navController.currentBackStackEntryAsState()
// Determine the current screen based on the back stack entry
val currentScreen = StudyPlanetScreens.valueOf(
backStackEntry?.destination?.route ?: StudyPlanetScreens.MainScreen.name,
)
// Compose UI structure using Scaffold
Scaffold(
topBar = {
// Display the app bar with relevant actions
AppBar(
currentScreen = currentScreen,
canNavigateBack = navController.previousBackStackEntry != null,
navigateUp = { navController.navigateUp() },
)
},
// Display the bottom navigation bar if the user is authenticated
bottomBar = { if (AuthenticationSingleton.isUserAuthenticated) { NavBar(currentScreen, navController) } },
) { innerPadding ->
Box(modifier = Modifier.padding(innerPadding)) {
StudyPlanetNavigation(navController = navController)
}
}
}
| 0 | Kotlin | 0 | 0 | 9cb5ba383a6e1b30e261cd379739583cc3219c8a | 3,348 | StudyPlanetAndroid | MIT License |
src/commonMain/kotlin/baaahs/gl/shader/DistortionShader.kt | lucgirardin | 290,413,324 | true | {"Kotlin": 1134726, "C++": 479123, "JavaScript": 365308, "GLSL": 120375, "C": 100546, "CMake": 25514, "HTML": 10796, "CSS": 10322, "Shell": 663} | package baaahs.gl.shader
import baaahs.gl.glsl.GlslCode
import baaahs.gl.glsl.GlslType
import baaahs.gl.glsl.LinkException
import baaahs.gl.patch.ContentType
import baaahs.plugin.Plugins
import baaahs.show.Shader
import baaahs.show.ShaderOutPortRef
import baaahs.show.ShaderType
class DistortionShader(shader: Shader, glslCode: GlslCode, plugins: Plugins) : OpenShader.Base(shader, glslCode, plugins) {
companion object {
val proFormaInputPorts = listOf(
InputPort("gl_FragCoord", GlslType.Vec2, "U/V Coordinatess", ContentType.UvCoordinateStream)
)
val wellKnownInputPorts = listOf(
InputPort("gl_FragCoord", GlslType.Vec4, "Coordinates", ContentType.UvCoordinateStream),
InputPort("intensity", GlslType.Float, "Intensity", ContentType.Float), // TODO: ContentType.ZeroToOne
InputPort("time", GlslType.Float, "Time", ContentType.Time),
InputPort("startTime", GlslType.Float, "Activated Time", ContentType.Time),
InputPort("endTime", GlslType.Float, "Deactivated Time", ContentType.Time)
// varying vec2 surfacePosition; TODO
).associateBy { it.id }
val outputPort: OutputPort =
OutputPort(GlslType.Vec2, ShaderOutPortRef.ReturnValue, "U/V Coordinate", ContentType.UvCoordinateStream)
}
override val shaderType: ShaderType
get() = ShaderType.Distortion
override val entryPointName: String get() = "mainDistortion"
override val proFormaInputPorts
get() = DistortionShader.proFormaInputPorts
override val wellKnownInputPorts
get() = DistortionShader.wellKnownInputPorts
override val outputPort: OutputPort
get() = DistortionShader.outputPort
override fun invocationGlsl(
namespace: GlslCode.Namespace,
resultVar: String,
portMap: Map<String, String>
): String {
val inVar = portMap["gl_FragCoord"] ?: throw LinkException("No input for shader \"$title\"")
return resultVar + " = " + namespace.qualify(entryPoint.name) + "($inVar.xy)"
}
} | 0 | null | 0 | 0 | 80865b7141d4ab8fcaafcc1c58402afb02561ecc | 2,101 | sparklemotion | MIT License |
src/app/src/main/java/com/gabrielbmoro/crazymath/domain/usecase/SignUpUseCase.kt | gabrielbmoro | 574,750,061 | false | null | package com.gabrielbmoro.crazymath.domain.usecase
import com.gabrielbmoro.crazymath.repository.CrazyMathRepository
open class SignUpUseCase(private val repository: CrazyMathRepository) {
suspend fun execute(email: String): String? {
return repository.signUp(email)
}
} | 0 | Kotlin | 0 | 0 | e747b05712ab481b33ce65487cd5674a8d1b7b8a | 287 | CrazyMath-Android | MIT License |
menu/src/jvmMain/kotlin/Utils.kt | composablehorizons | 792,741,661 | false | null | @file:JvmName("CommonUtilsKt")
package com.composables.core
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.input.key.Key
import java.awt.KeyEventDispatcher
import java.awt.KeyboardFocusManager
import java.awt.event.KeyEvent
@Composable
internal actual fun KeyDownHandler(onEvent: (KeyDownEvent) -> Boolean) {
DisposableEffect(Unit) {
val dispatcher = KeyEventDispatcher { keyEvent ->
if (keyEvent.id == KeyEvent.KEY_PRESSED) {
val keyDownEvent = KeyDownEvent(Key(keyEvent.keyCode))
onEvent(keyDownEvent)
} else {
false
}
}
val keyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager()
keyboardFocusManager.addKeyEventDispatcher(dispatcher)
onDispose {
keyboardFocusManager.removeKeyEventDispatcher(dispatcher)
}
}
}
| 5 | null | 11 | 94 | 1c6bcc8d71a4ef71813175713ac39f0509ea6b0a | 962 | compose-menu | MIT License |
analysis/analysis-api/testData/components/referenceShortener/shortenRange/nestedClasses/nestedClassFromSupertypes3_java.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // FILE: main.kt
package test
import dependency.JavaBaseClass
class Foo : JavaBaseClass() {
<expr>val prop: JavaBaseClass.Nested = JavaBaseClass.Nested()</expr>
}
// FILE: dependency/JavaBaseClass.java
package dependency;
public class JavaBaseClass {
public static class Nested {}
} | 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 294 | kotlin | Apache License 2.0 |
css-gg/src/commonMain/kotlin/compose/icons/cssggicons/ArrowLongDownL.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.cssggicons
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 compose.icons.CssGgIcons
public val CssGgIcons.ArrowLongDownL: ImageVector
get() {
if (_arrowLongDownL != null) {
return _arrowLongDownL!!
}
_arrowLongDownL = Builder(name = "ArrowLongDownL", 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(8.998f, 0.972f)
verticalLineTo(2.972f)
horizontalLineTo(11.998f)
lineTo(10.998f, 2.973f)
lineTo(11.012f, 19.213f)
lineTo(9.168f, 17.379f)
lineTo(7.757f, 18.797f)
lineTo(12.012f, 23.028f)
lineTo(16.243f, 18.773f)
lineTo(14.825f, 17.363f)
lineTo(13.012f, 19.186f)
lineTo(12.998f, 2.972f)
horizontalLineTo(14.998f)
verticalLineTo(0.972f)
horizontalLineTo(8.998f)
close()
}
}
.build()
return _arrowLongDownL!!
}
private var _arrowLongDownL: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 1,866 | compose-icons | MIT License |
diskordin-base/src/main/kotlin/org/tesserakt/diskordin/impl/core/entity/object/PermissionOverwrite.kt | ITesserakt | 218,969,129 | false | null | package org.tesserakt.diskordin.impl.core.entity.`object`
import arrow.core.Either
import org.tesserakt.diskordin.core.data.Permission
import org.tesserakt.diskordin.core.data.json.response.OverwriteResponse
import org.tesserakt.diskordin.core.entity.`object`.IPermissionOverwrite
import org.tesserakt.diskordin.core.entity.`object`.MemberId
import org.tesserakt.diskordin.core.entity.`object`.RoleId
import org.tesserakt.diskordin.impl.util.typeclass.integral
import org.tesserakt.diskordin.util.enums.ValuedEnum
import org.tesserakt.diskordin.util.enums.and
import org.tesserakt.diskordin.util.enums.not
internal class PermissionOverwrite(raw: OverwriteResponse) : IPermissionOverwrite {
override val type: IPermissionOverwrite.Type =
IPermissionOverwrite.Type.values().find { it.ordinal == raw.type.toIntOrNull() } ?: when (raw.type) {
"role" -> IPermissionOverwrite.Type.Role
"member" -> IPermissionOverwrite.Type.Member
else -> error("Unknown type of permission override: ${raw.type}")
}
override val targetId: Either<RoleId, MemberId> = Either.conditionally(type == IPermissionOverwrite.Type.Role,
{ raw.id },
{ raw.id })
override val allowed = ValuedEnum<Permission, Long>(raw.allow, Long.integral())
override val denied = ValuedEnum<Permission, Long>(raw.deny, Long.integral())
override fun computeCode(): Long = (allowed and !denied).code
override fun toString(): String {
return "PermissionOverwrite(type=$type, targetId=$targetId, allowed=$allowed, denied=$denied)"
}
} | 1 | Kotlin | 1 | 12 | e93964fcb5ecb0e1d03dd0fc7d3dd2637a0e08ae | 1,591 | diskordin | Apache License 2.0 |
src/main/kotlin/me/giacomozama/adventofcode2023/days/Day.kt | giacomozama | 725,810,476 | false | {"Kotlin": 12023} | package me.giacomozama.adventofcode2023.days
import java.io.File
abstract class Day {
abstract fun parseInput(inputFile: File)
abstract fun solveFirstPuzzle(): Any
abstract fun solveSecondPuzzle(): Any
} | 0 | Kotlin | 0 | 0 | a86e9757288c63778e1f8f1f3fa5a2cfdaa6dcdd | 220 | aoc2023 | MIT License |
app/src/main/java/com/vladislaviliev/newair/fragments/home/HomeFragment.kt | vladislav-iliev | 606,184,408 | false | null | package com.vladislaviliev.newair.fragments.home
import android.location.Location
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.NavHostFragment
import androidx.preference.PreferenceManager
import com.google.android.gms.maps.model.LatLng
import com.vladislaviliev.newair.R
import com.vladislaviliev.newair.Vm
import com.vladislaviliev.newair.data.Sensor
import com.vladislaviliev.newair.data.UserLocation
class HomeFragment : Fragment() {
internal val vm: Vm by activityViewModels()
private lateinit var carousel: HomeCarousel
private lateinit var backgroundView: View
private lateinit var pollutionView: TextView
private lateinit var healthView: TextView
private lateinit var temperatureView: TextView
private lateinit var humidityView: TextView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
inflater.inflate(R.layout.fragment_home, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
carousel = HomeCarousel(this)
backgroundView = view.findViewById(R.id.container)
healthView = view.findViewById(R.id.healthMessage)
pollutionView = view.findViewById(R.id.pollutionText)
temperatureView = view.findViewById(R.id.temperatureText)
humidityView = view.findViewById(R.id.humidityText)
view.findViewById<View>(R.id.addButton).setOnClickListener {
NavHostFragment.findNavController(this).navigate(HomeFragmentDirections.actionNavigationHomeToNavigationMap(false))
}
view.findViewById<View>(R.id.settingsButton).setOnClickListener {
NavHostFragment.findNavController(this).navigate(HomeFragmentDirections.actionNavigationHomeToNavigationSettings())
}
view.findViewById<View>(R.id.refreshButton).setOnClickListener { vm.downloadData() }
vm.liveSensors.observe(viewLifecycleOwner) { updateScreen() }
}
internal fun updateScreen() {
val loc: UserLocation? = if (carousel.position == 0) null else vm.userLocations[carousel.position - 1]
val pollution = if (loc == null) getAverage(Sensor.SensorType.PM10) else closestSensor(loc, Sensor.SensorType.PM10).measure
val temp = if (loc == null) getAverage(Sensor.SensorType.TEMP) else closestSensor(loc, Sensor.SensorType.TEMP).measure
val humid = if (loc == null) getAverage(Sensor.SensorType.HUMID) else closestSensor(loc, Sensor.SensorType.HUMID).measure
carousel.checkArrowsVisibility(carousel.position)
pollutionView.text = pollution.toString()
temperatureView.text = temp.toString()
humidityView.text = humid.toString()
healthView.text = resources.getStringArray(R.array.health_messages)[getThresholdIndex(pollution)]
backgroundView.setBackgroundColor(getColor(pollution))
}
private fun getAverage(type: Sensor.SensorType): Double {
val sensors = vm.liveSensors.value!!
return (sensors.filter { it.type == type }.sumOf { it.measure } / sensors.size).toInt().toDouble()
}
private fun closestSensor(userLoc: UserLocation, type: Sensor.SensorType): Sensor {
val latLng = userLoc.latLng
return vm.liveSensors.value!!
.filter { it.type == type }
.minWith { a, b -> (distanceBetween(latLng, a.latLng) - distanceBetween(latLng, b.latLng)).toInt() }
}
private fun distanceBetween(a: LatLng, b: LatLng) =
Location("a").apply { latitude = a.latitude; longitude = a.longitude }
.distanceTo(Location("b").apply { latitude = b.latitude; longitude = b.longitude })
private fun getThresholdIndex(pollution: Double): Int {
val thresholds = resources.getIntArray(R.array.color_dividers_int)
var idx = thresholds.indexOfFirst { pollution <= it }
if (idx < 0) idx = thresholds.lastIndex
return idx
}
@ColorInt
private fun getColor(pollution: Double): Int {
val colorBlind =
PreferenceManager.getDefaultSharedPreferences(requireContext()).getBoolean(getString(R.string.color_blind_switch_key), false)
val colors = resources.getIntArray(if (colorBlind) R.array.colors_colorblind else R.array.colors)
return colors[getThresholdIndex(pollution)]
}
} | 0 | Kotlin | 0 | 0 | e90902f5f4cbca65d4f59c6c10de65bf61e9b4a8 | 4,631 | NewAir | MIT License |
src/main/kotlin/com/github/quanticheart/intellijplugincleantree/actions/test/CreateTest6FileAction.kt | quanticheart | 519,671,971 | false | null | package com.github.quanticheart.intellijplugincleantree.actions.test
import com.github.quanticheart.intellijplugincleantree.dialog.SampleDialog2Wrapper
import com.github.quanticheart.intellijplugincleantree.dialog.SampleDialogWrapper
import com.intellij.ide.actions.CreateFileFromTemplateAction.createFileFromTemplate
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.PsiManager
import com.intellij.ui.CheckBoxList
import com.intellij.ui.components.JBScrollPane
import net.miginfocom.swing.MigLayout
import org.jetbrains.kotlin.idea.KotlinLanguage
import java.awt.Dimension
import java.awt.Font
import javax.swing.BorderFactory
import javax.swing.JPanel
import javax.swing.border.Border
import javax.swing.border.CompoundBorder
import javax.swing.border.TitledBorder
class CreateTest6FileAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val d = SampleDialog2Wrapper()
d.showAndGet()
}
} | 0 | Kotlin | 0 | 0 | b01f10f49c010e6dc1ba6260c10cdef8e45df8d6 | 1,353 | intellij-plugin-cleantree | Apache License 2.0 |
src/test/kotlin/cn/edu/gxust/jiweihuang/kotlin/unit/MicroGramTest.kt | jwhgxust | 179,000,909 | false | null | package cn.edu.gxust.jiweihuang.kotlin.unit
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
internal class MicroGramTest{
@Test
fun getName() {
assertEquals("MicroGram", MicroGram.name)
assertEquals(MicroGram.javaClass.simpleName, MicroGram.name)
}
@Test
fun getSymbol() {
assertEquals("μg", MicroGram.symbol)
}
@Test
fun testToString() {
println("MicroGram:$MicroGram")
}
@Test
fun testInheritance() {
println("MicroGram:" + MicroGram::class.objectInstance)
println("MicroGram:" + MicroGram.javaClass.superclass)
println("MicroGram:" + MicroGram.javaClass.superclass.superclass)
println("MicroGram:" + MicroGram.javaClass.superclass.superclass.superclass)
println("MicroGram:" + MicroGram.javaClass.superclass.superclass.superclass.superclass)
}
} | 0 | Kotlin | 0 | 0 | ce3efec8030f167647cab6f579f8acf47652ad34 | 901 | bave-sizes | Apache License 2.0 |
samples/dungeon/app/src/main/java/com/squareup/sample/dungeon/DungeonActivity.kt | square | 268,864,554 | false | null | package com.squareup.sample.dungeon
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.squareup.workflow1.ui.WorkflowLayout
import com.squareup.workflow1.ui.WorkflowUiExperimentalApi
class DungeonActivity : AppCompatActivity() {
@OptIn(WorkflowUiExperimentalApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Ignore config changes for now.
val component = Component(this)
val model: TimeMachineModel by viewModels { component.timeMachineModelFactory }
setContentView(
WorkflowLayout(this).apply { start(model.renderings, component.viewRegistry) }
)
}
}
| 129 | Kotlin | 82 | 694 | 15bbeea7d83d309c3d5fe25b14e6c802179c66d1 | 715 | workflow-kotlin | Apache License 2.0 |
bidon/src/main/java/org/bidon/sdk/stats/StatisticsCollector.kt | bidon-io | 654,165,570 | false | {"Kotlin": 992814, "Java": 2186} | package org.bidon.sdk.stats
import org.bidon.sdk.adapter.DemandAd
import org.bidon.sdk.adapter.DemandId
import org.bidon.sdk.ads.Ad
import org.bidon.sdk.auction.models.BannerRequest
import org.bidon.sdk.auction.models.LineItem
import org.bidon.sdk.stats.models.BidStat
import org.bidon.sdk.stats.models.BidType
import org.bidon.sdk.stats.models.RoundStatus
/**
* Created by Bidon Team on 06/02/2023.
*/
interface StatisticsCollector {
val demandAd: DemandAd
val demandId: DemandId
val bidType: BidType
val auctionId: String
val roundId: String
val roundIndex: Int
fun getAd(demandAdObject: Any): Ad?
fun sendShowImpression()
fun sendClickImpression()
fun sendRewardImpression()
fun sendLoss(winnerDemandId: String, winnerEcpm: Double)
fun sendWin()
fun markFillStarted(lineItem: LineItem?, pricefloor: Double?)
fun markFillFinished(roundStatus: RoundStatus, ecpm: Double?)
fun markWin()
fun markLoss()
fun markBelowPricefloor()
fun setStatisticAdType(adType: AdType)
fun addAuctionConfigurationId(auctionConfigurationId: Int, auctionConfigurationUid: String)
fun addExternalWinNotificationsEnabled(enabled: Boolean)
fun addDemandId(demandId: DemandId)
fun addRoundInfo(
auctionId: String,
roundId: String,
roundIndex: Int,
demandAd: DemandAd,
bidType: BidType
)
fun getStats(): BidStat
sealed interface AdType {
object Rewarded : AdType
object Interstitial : AdType
data class Banner(val format: BannerRequest.StatFormat) : AdType
}
}
| 0 | Kotlin | 0 | 0 | 440f8824115bd71f949ce6aac075d830af89eca3 | 1,613 | bidon_sdk_android | Apache License 2.0 |
src/main/kotlin/r2dbcfun/dbio/vertx/VertxConnection.kt | dkindler | 351,886,663 | false | null | package r2dbcfun.dbio.vertx
import io.vertx.reactivex.sqlclient.SqlConnection
import kotlinx.coroutines.rx2.await
import r2dbcfun.dbio.DBConnection
import r2dbcfun.dbio.DBTransaction
import r2dbcfun.dbio.Statement
class VertxConnection(private val client: SqlConnection) : DBConnection {
override fun createStatement(sql: String): Statement {
return VertxStatement(client.preparedQuery(sql))
}
override fun createInsertStatement(sql: String): Statement {
return createStatement("$sql returning id")
}
override suspend fun beginTransaction(): DBTransaction {
return VertxTransaction(client.rxBegin().await())
}
override suspend fun close() {
client.rxClose().await()
}
override suspend fun execute(sql: String) {
client.query(sql).rxExecute().await()
}
}
| 0 | null | 0 | 0 | e35b459f245806125ea5820fbb31ced6e183e209 | 842 | r2dbcfun | MIT License |
Common/src/main/java/ram/talia/hexal/common/casting/Patterns.kt | Talia-12 | 519,549,575 | false | null | @file:Suppress("unused")
package ram.talia.hexal.common.casting
import at.petrak.hexcasting.api.PatternRegistry
import at.petrak.hexcasting.api.spell.Action
import at.petrak.hexcasting.api.spell.iota.DoubleIota
import at.petrak.hexcasting.api.spell.iota.PatternIota
import at.petrak.hexcasting.api.spell.iota.Vec3Iota
import at.petrak.hexcasting.api.spell.math.HexDir
import at.petrak.hexcasting.api.spell.math.HexPattern
import at.petrak.hexcasting.common.casting.operators.selectors.*
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.phys.Vec3
import ram.talia.hexal.api.HexalAPI.modLoc
import ram.talia.hexal.api.plus
import ram.talia.hexal.api.spell.casting.triggers.WispTriggerTypes
import ram.talia.hexal.common.casting.actions.*
import ram.talia.hexal.common.casting.actions.everbook.*
import ram.talia.hexal.common.casting.actions.spells.*
import ram.talia.hexal.common.casting.actions.spells.gates.*
import ram.talia.hexal.common.casting.actions.spells.great.*
import ram.talia.hexal.common.casting.actions.spells.motes.*
import ram.talia.hexal.common.casting.actions.spells.link.*
import ram.talia.hexal.common.casting.actions.spells.wisp.*
import ram.talia.hexal.common.entities.BaseWisp
object Patterns {
@JvmField
var PATTERNS: MutableList<Triple<HexPattern, ResourceLocation, Action>> = ArrayList()
@JvmField
var PER_WORLD_PATTERNS: MutableList<Triple<HexPattern, ResourceLocation, Action>> = ArrayList()
@JvmField
val SPECIAL_HANDLERS: MutableList<Pair<ResourceLocation, PatternRegistry.SpecialHandler>> = ArrayList()
@JvmStatic
fun registerPatterns() {
try {
for ((pattern, location, action) in PATTERNS)
PatternRegistry.mapPattern(pattern, location, action)
for ((pattern, location, action) in PER_WORLD_PATTERNS)
PatternRegistry.mapPattern(pattern, location, action, true)
for ((location, handler) in SPECIAL_HANDLERS)
PatternRegistry.addSpecialHandler(location, handler)
} catch (e: PatternRegistry.RegisterPatternException) {
e.printStackTrace()
}
}
// ============================ Type Comparison ===================================
@JvmField
val TYPE_BLOCK_ITEM = make(HexPattern.fromAngles("qaqqaea", HexDir.EAST), modLoc("type/block_item"), OpTypeBlockItem)
@JvmField
val TYPE_ENTITY = make(HexPattern.fromAngles("qawde", HexDir.SOUTH_WEST), modLoc("type/entity"), OpTypeEntity)
@JvmField
val TYPE_IOTA = make(HexPattern.fromAngles("awd", HexDir.SOUTH_WEST), modLoc("type/iota"), OpTypeIota)
@JvmField
val TYPE_ITEM_HELD = make(HexPattern.fromAngles("edeedqd", HexDir.SOUTH_WEST), modLoc("type/item_held"), OpTypeItemHeld)
@JvmField
val GET_ENTITY_TYPE = make(HexPattern.fromAngles("dadqqqqqdad", HexDir.NORTH_EAST), modLoc("get_entity/type"), OpGetEntityAtDyn)
@JvmField
val ZONE_ENTITY_TYPE = make(HexPattern.fromAngles("waweeeeewaw", HexDir.SOUTH_EAST), modLoc("zone_entity/type"), OpGetEntitiesByDyn(false))
@JvmField
val ZONE_ENTITY_NOT_TYPE = make(HexPattern.fromAngles("wdwqqqqqwdw", HexDir.NORTH_EAST), modLoc("zone_entity/not_type"), OpGetEntitiesByDyn(true))
// ========================== Misc Info Gathering =================================
@JvmField
val CURRENT_TICK = make(HexPattern.fromAngles("ddwaa", HexDir.NORTH_WEST), modLoc("current_tick"), OpCurrentTick)
@JvmField
val REMAINING_EVALS = make(HexPattern.fromAngles("qqaed", HexDir.SOUTH_EAST), modLoc("remaining_evals"), OpRemainingEvals)
@JvmField
val BREATH = make(HexPattern.fromAngles("aqawdwaqawd", HexDir.NORTH_WEST), modLoc("breath"), OpGetBreath)
@JvmField
val HEALTH = make(HexPattern.fromAngles("aqwawqa", HexDir.NORTH_WEST), modLoc("health"), OpGetHealth)
@JvmField
val ARMOUR = make(HexPattern.fromAngles("wqqqqw", HexDir.NORTH_WEST), modLoc("armour"), OpGetArmour)
@JvmField
val TOUGHNESS = make(HexPattern.fromAngles("aeqqqqea", HexDir.EAST), modLoc("toughness"), OpGetToughness)
@JvmField
val LIGHT_LEVEL = make(HexPattern.fromAngles("qedqde", HexDir.NORTH_EAST), modLoc("light_level"), OpGetLightLevel)
// =============================== Misc Maths =====================================
@JvmField
val FACTORIAL = make(HexPattern.fromAngles("wawdedwaw", HexDir.SOUTH_EAST), modLoc("factorial"), OpFactorial)
@JvmField
val RUNNING_SUM = make(HexPattern.fromAngles("aea", HexDir.WEST), modLoc("running/sum"), OpRunningOp ({ if (it is Vec3Iota) Vec3Iota(Vec3.ZERO) else DoubleIota(0.0) })
{ running, iota ->
when (running) {
is DoubleIota -> DoubleIota(running.double + ((iota as? DoubleIota)?.double ?: throw OpRunningOp.InvalidIotaException("list.double")))
is Vec3Iota -> Vec3Iota(running.vec3 + ((iota as? Vec3Iota)?.vec3 ?: throw OpRunningOp.InvalidIotaException("list.vec")))
else -> throw OpRunningOp.InvalidIotaException("list.doublevec")
}
})
@JvmField
val RUNNING_MUL = make(HexPattern.fromAngles("qaawaaq", HexDir.NORTH_EAST), modLoc("running/mul"), OpRunningOp ({ DoubleIota(1.0) })
{ running, iota ->
if (running !is DoubleIota)
throw OpRunningOp.InvalidIotaException("list.double")
DoubleIota(running.double * ((iota as? DoubleIota)?.double ?: throw OpRunningOp.InvalidIotaException("list.double")))
})
// ================================ Everbook ======================================
@JvmField
val EVERBOOK_READ = make(HexPattern.fromAngles("eweeewedqdeddw", HexDir.NORTH_EAST), modLoc("everbook/read"), OpEverbookRead)
@JvmField
val EVERBOOK_WRITE = make(HexPattern.fromAngles("qwqqqwqaeaqaaw", HexDir.SOUTH_EAST), modLoc("everbook/write"), OpEverbookWrite)
@JvmField
val EVERBOOK_DELETE = make(HexPattern.fromAngles("qwqqqwqaww", HexDir.SOUTH_EAST), modLoc("everbook/delete"), OpEverbookDelete)
@JvmField
val EVERBOOK_TOGGLE_MACRO = make(HexPattern.fromAngles("eweeewedww", HexDir.SOUTH_WEST), modLoc("everbook/toggle_macro"), OpToggleMacro)
// ============================== Misc Spells =====================================
@JvmField
val SMELT = make(HexPattern.fromAngles("wqqqwqqadad", HexDir.EAST), modLoc("smelt"), OpSmelt)
@JvmField
val FREEZE = make(HexPattern.fromAngles("weeeweedada", HexDir.WEST), modLoc("freeze"), OpFreeze)
@JvmField
val FALLING_BLOCK = make(HexPattern.fromAngles("wqwawqwqwqwqwqw", HexDir.EAST), modLoc("falling_block"), OpFallingBlock)
@JvmField
val PLACE_TYPE = make(HexPattern.fromAngles("eeeeedeeeee", HexDir.WEST), modLoc("place_type"), OpPlaceType)
@JvmField
val PARTICLES = make(HexPattern.fromAngles("eqqqqa", HexDir.NORTH_EAST), modLoc("particles"), OpParticles)
// =============================== Wisp Stuff =====================================
@JvmField
val WISP_SUMMON_PROJECTILE = make(HexPattern.fromAngles("aqaeqeeeee", HexDir.NORTH_WEST), modLoc("wisp/summon/projectile"), OpSummonWisp(false))
@JvmField
val WISP_SUMMON_TICKING = make(HexPattern.fromAngles("aqaweewaqawee", HexDir.NORTH_WEST), modLoc("wisp/summon/ticking"), OpSummonWisp(true))
@JvmField
val WISP_SELF = make(HexPattern.fromAngles("dedwqqwdedwqqaw", HexDir.NORTH_EAST), modLoc("wisp/self"), OpWispSelf)
@JvmField
val WISP_MEDIA = make(HexPattern.fromAngles("aqaweewaqaweedw", HexDir.NORTH_WEST), modLoc("wisp/media"), OpWispMedia)
@JvmField
val WISP_HEX = make(HexPattern.fromAngles("aweewaqaweewaawww", HexDir.SOUTH_EAST), modLoc("wisp/hex"), OpWispHex)
@JvmField
val WISP_OWNER = make(HexPattern.fromAngles("dwqqwdedwqqwddwww", HexDir.SOUTH_WEST), modLoc("wisp/owner"), OpWispOwner)
// Set and Get Move Target WEST awqwawqaw
@JvmField
val WISP_MOVE_TARGET_SET = make(HexPattern.fromAngles("awqwawqaw", HexDir.WEST), modLoc("wisp/move/target/set"), OpMoveTargetSet)
@JvmField
val WISP_MOVE_TARGET_GET = make(HexPattern.fromAngles("ewdwewdew", HexDir.EAST), modLoc("wisp/move/target/get"), OpMoveTargetGet)
@JvmField
val WISP_MOVE_SPEED_SET = make(HexPattern.fromAngles("aeawqqqae", HexDir.WEST), modLoc("wisp/move/speed/set"), OpMoveSpeedSet)
@JvmField
val WISP_MOVE_SPEED_GET = make(HexPattern.fromAngles("eeewdqdee", HexDir.EAST), modLoc("wisp/move/speed/get"), OpMoveSpeedGet)
// Entity purification and Zone distillations
@JvmField
val GET_ENTITY_WISP = make(HexPattern.fromAngles("qqwdedwqqdaqaaww", HexDir.SOUTH_EAST),
modLoc("get_entity/wisp"),
OpGetEntityAt{ entity -> entity is BaseWisp })
@JvmField
val ZONE_ENTITY_WISP = make(HexPattern.fromAngles("qqwdedwqqwdeddww", HexDir.SOUTH_EAST),
modLoc("zone_entity/wisp"),
OpGetEntitiesBy({ entity -> entity is BaseWisp }, false))
@JvmField
val ZONE_ENTITY_NOT_WISP = make(HexPattern.fromAngles("eewaqaweewaqaaww", HexDir.NORTH_EAST),
modLoc("zone_entity/not_wisp"),
OpGetEntitiesBy({ entity -> entity is BaseWisp }, true))
// Triggers
@JvmField
val WISP_TRIGGER_TICK = make(HexPattern.fromAngles("aqawded", HexDir.NORTH_WEST),
modLoc("wisp/trigger/tick"),
OpWispSetTrigger(WispTriggerTypes.TICK_TRIGGER_TYPE))
@JvmField
val WISP_TRIGGER_COMM = make(HexPattern.fromAngles("aqqqqqwdeddw", HexDir.EAST),
modLoc("wisp/trigger/comm"),
OpWispSetTrigger(WispTriggerTypes.COMM_TRIGGER_TYPE))
@JvmField
val WISP_TRIGGER_MOVE = make(HexPattern.fromAngles("eqwawqwaqww", HexDir.EAST),
modLoc("wisp/trigger/move"),
OpWispSetTrigger(WispTriggerTypes.MOVE_TRIGGER_TYPE))
val WISP_SEON_GET = make(HexPattern.fromAngles("daqweewqaeaqweewqaqwwww", HexDir.EAST),
modLoc("wisp/seon/get"),
OpSeonWispGet)
// =============================== Link Stuff =====================================
@JvmField
val LINK = make(HexPattern.fromAngles("eaqaaeqqqqqaweaqaaw", HexDir.EAST), modLoc("link"), OpLink)
@JvmField
val LINK_OTHERS = make(HexPattern.fromAngles("eqqqqqawqeeeeedww", HexDir.EAST), modLoc("link/others"), OpLinkOthers)
@JvmField
val UNLINK = make(HexPattern.fromAngles("qdeddqeeeeedwqdeddw", HexDir.WEST), modLoc("link/unlink"), OpUnlink)
@JvmField
val UNLINK_OTHERS = make(HexPattern.fromAngles("qeeeeedweqqqqqaww", HexDir.WEST), modLoc("link/unlink/others"), OpUnlinkOthers)
@JvmField
val LINK_GET = make(HexPattern.fromAngles("eqqqqqaww", HexDir.EAST), modLoc("link/get"), OpGetLinked)
@JvmField
val LINK_GET_INDEX = make(HexPattern.fromAngles("aeqqqqqawwd", HexDir.SOUTH_WEST), modLoc("link/get_index"), OpGetLinkedIndex)
@JvmField
val LINK_NUM = make(HexPattern.fromAngles("qeeeeedww", HexDir.WEST), modLoc("link/num"), OpNumLinked)
@JvmField
val LINK_COMM_SEND = make(HexPattern.fromAngles("qqqqqwdeddw", HexDir.NORTH_WEST), modLoc("link/comm/send"), OpSendIota)
@JvmField
val LINK_COMM_READ = make(HexPattern.fromAngles("weeeeew", HexDir.NORTH_EAST), modLoc("link/comm/read"), OpReadReceivedIota)
@JvmField
val LINK_COMM_NUM = make(HexPattern.fromAngles("aweeeeewaa", HexDir.SOUTH_EAST), modLoc("link/comm/num"), OpNumReceivedIota)
@JvmField
val LINK_COMM_CLEAR = make(HexPattern.fromAngles("aweeeeewa", HexDir.SOUTH_EAST), modLoc("link/comm/clear"), OpClearReceivedIotas)
@JvmField
val LINK_COMM_OPEN_TRANSMIT = make(HexPattern.fromAngles("qwdedwq", HexDir.WEST), modLoc("link/comm/open_transmit"), OpOpenTransmit)
@JvmField
val LINK_COMM_CLOSE_TRANSMIT = make(HexPattern.fromAngles("ewaqawe", HexDir.EAST), modLoc("link/comm/close_transmit"), OpCloseTransmit)
// =============================== Gate Stuff =====================================
@JvmField
val GATE_MARK = make(HexPattern.fromAngles("qaqeede", HexDir.WEST), modLoc("gate/mark"), OpMarkGate)
@JvmField
val GATE_UNMARK = make(HexPattern.fromAngles("edeqqaq", HexDir.EAST), modLoc("gate/unmark"), OpUnmarkGate)
@JvmField
val GATE_MARK_GET = make(HexPattern.fromAngles("edwwdeeede", HexDir.EAST), modLoc("gate/mark/get"), OpGetMarkedGate)
@JvmField
val GATE_MARK_NUM_GET = make(HexPattern.fromAngles("qawwaqqqaq", HexDir.WEST), modLoc("gate/mark/num/get"), OpGetNumMarkedGate)
@JvmField
val GATE_CLOSE = make(HexPattern.fromAngles("qqqwwqqqwqqawdedw", HexDir.WEST), modLoc("gate/close"), OpCloseGate)
// =============================== Gate Stuff =====================================
@JvmField
val BIND_STORAGE = make(HexPattern.fromAngles("qaqwqaqwqaq", HexDir.NORTH_WEST), modLoc("mote/storage/bind"), OpBindStorage(false))
@JvmField
val BIND_STORAGE_TEMP = make(HexPattern.fromAngles("edewedewede", HexDir.NORTH_EAST), modLoc("mote/storage/bind/temp"), OpBindStorage(true))
@JvmField
val MOTE_CONTAINED_TYPE_GET = make(HexPattern.fromAngles("dwqqqqqwddww", HexDir.NORTH_EAST), modLoc("mote/contained_type/get"), OpGetContainedItemTypes)
@JvmField
val MOTE_CONTAINED_GET = make(HexPattern.fromAngles("aweeeeewaaww", HexDir.SOUTH_EAST), modLoc("mote/contained/get"), OpGetContainedMotes)
@JvmField
val MOTE_STORAGE_REMAINING_CAPACITY_GET = make(HexPattern.fromAngles("awedqdewa", HexDir.SOUTH_EAST), modLoc("mote/storage/remaining_capacity/get"), OpGetStorageRemainingCapacity)
@JvmField
val MOTE_STORAGE_CONTAINS = make(HexPattern.fromAngles("dwqaeaqwd", HexDir.NORTH_EAST), modLoc("mote/storage/contains"), OpStorageContains)
@JvmField
val MOTE_MAKE = make(HexPattern.fromAngles("eaqa", HexDir.WEST), modLoc("mote/make"), OpMakeItem)
@JvmField
val MOTE_RETURN = make(HexPattern.fromAngles("qded", HexDir.EAST), modLoc("mote/return"), OpReturnMote)
@JvmField
val MOTE_COUNT_GET = make(HexPattern.fromAngles("qqqqwqqqqqaa", HexDir.NORTH_WEST), modLoc("mote/count/get"), OpGetCountMote)
@JvmField
val MOTE_COMBINE = make(HexPattern.fromAngles("aqaeqded", HexDir.NORTH_WEST), modLoc("mote/combine"), OpCombineMotes)
@JvmField
val MOTE_COMBINABLE = make(HexPattern.fromAngles("dedqeaqa", HexDir.SOUTH_WEST), modLoc("mote/combinable"), OpMotesCombinable)
@JvmField
val MOTE_SPLIT = make(HexPattern.fromAngles("eaqaaw", HexDir.EAST), modLoc("mote/split"), OpSplitMote)
@JvmField
val MOTE_STORAGE_GET = make(HexPattern.fromAngles("qqqqqaw", HexDir.SOUTH_WEST), modLoc("mote/storage/get"), OpGetMoteStorage)
@JvmField
val MOTE_STORAGE_SET = make(HexPattern.fromAngles("eeeeedw", HexDir.SOUTH_EAST), modLoc("mote/storage/set"), OpSetMoteStorage)
@JvmField
val MOTE_CRAFT = make(HexPattern.fromAngles("wwawdedwawdewwdwaqawdwwedwawdedwaww", HexDir.SOUTH_EAST), modLoc("mote/craft"), OpCraftMote)
@JvmField
val MOTE_VILLAGER_LEVEL_GET = make(HexPattern.fromAngles("qqwdedwqqaww", HexDir.NORTH_WEST), modLoc("mote/villager/level/get"), OpGetVillagerLevel)
@JvmField
val MOTE_TRADE_GET = make(HexPattern.fromAngles("awdedwaawwqded", HexDir.SOUTH_EAST), modLoc("mote/trade/get"), OpGetItemTrades)
@JvmField
val MOTE_TRADE = make(HexPattern.fromAngles("awdedwaeqded", HexDir.NORTH_WEST), modLoc("mote/trade"), OpTradeMote)
@JvmField
val MOTE_USE_ON = make(HexPattern.fromAngles("qqqwqqqqaa", HexDir.EAST), modLoc("mote/use_on"), OpUseMoteOn)
// ============================== Great Stuff =====================================
@JvmField
val CONSUME_WISP = make(HexPattern.fromAngles("wawqwawwwewwwewwwawqwawwwewwwewdeaweewaqaweewaawwww", HexDir.NORTH_WEST),
modLoc("wisp/consume"),
OpConsumeWisp,
true)
@JvmField
val WISP_SEON_SET = make(HexPattern.fromAngles("aqweewqaeaqweewqaqwww", HexDir.SOUTH_WEST),
modLoc("wisp/seon/set"),
OpSeonWispSet,
true)
@JvmField
val TICK = make(HexPattern.fromAngles("wwwdwdwwwawqqeqwqqwqeqwqq", HexDir.SOUTH_EAST), modLoc("tick"), OpTick, true)
@JvmField
val GATE_MAKE = make(HexPattern.fromAngles("qwqwqwqwqwqqeaeaeaeaeae", HexDir.WEST), modLoc("gate/make"), OpMakeGate, true)
// ================================ Special Handlers =======================================
// @JvmField
// val EXAMPLE_HANDLER = make(modLoc("example_handler")) {pat ->
// return@make Action.makeConstantOp(StringIota("example! $pat"))
// }
fun make (pattern: HexPattern, location: ResourceLocation, operator: Action, isPerWorld: Boolean = false): PatternIota {
val triple = Triple(pattern, location, operator)
if (isPerWorld)
PER_WORLD_PATTERNS.add(triple)
else
PATTERNS.add(triple)
return PatternIota(pattern)
}
fun make (location: ResourceLocation, specialHandler: PatternRegistry.SpecialHandler): Pair<ResourceLocation, PatternRegistry.SpecialHandler> {
val pair = location to specialHandler
SPECIAL_HANDLERS.add(pair)
return pair
}
} | 20 | Kotlin | 9 | 11 | de4ca64b9415363eb0144f1a8a9ed6cecde7721d | 16,379 | Hexal | MIT License |
Common/src/main/java/ram/talia/hexal/common/casting/Patterns.kt | Talia-12 | 519,549,575 | false | null | @file:Suppress("unused")
package ram.talia.hexal.common.casting
import at.petrak.hexcasting.api.PatternRegistry
import at.petrak.hexcasting.api.spell.Action
import at.petrak.hexcasting.api.spell.iota.DoubleIota
import at.petrak.hexcasting.api.spell.iota.PatternIota
import at.petrak.hexcasting.api.spell.iota.Vec3Iota
import at.petrak.hexcasting.api.spell.math.HexDir
import at.petrak.hexcasting.api.spell.math.HexPattern
import at.petrak.hexcasting.common.casting.operators.selectors.*
import net.minecraft.resources.ResourceLocation
import net.minecraft.world.phys.Vec3
import ram.talia.hexal.api.HexalAPI.modLoc
import ram.talia.hexal.api.plus
import ram.talia.hexal.api.spell.casting.triggers.WispTriggerTypes
import ram.talia.hexal.common.casting.actions.*
import ram.talia.hexal.common.casting.actions.everbook.*
import ram.talia.hexal.common.casting.actions.spells.*
import ram.talia.hexal.common.casting.actions.spells.gates.*
import ram.talia.hexal.common.casting.actions.spells.great.*
import ram.talia.hexal.common.casting.actions.spells.motes.*
import ram.talia.hexal.common.casting.actions.spells.link.*
import ram.talia.hexal.common.casting.actions.spells.wisp.*
import ram.talia.hexal.common.entities.BaseWisp
object Patterns {
@JvmField
var PATTERNS: MutableList<Triple<HexPattern, ResourceLocation, Action>> = ArrayList()
@JvmField
var PER_WORLD_PATTERNS: MutableList<Triple<HexPattern, ResourceLocation, Action>> = ArrayList()
@JvmField
val SPECIAL_HANDLERS: MutableList<Pair<ResourceLocation, PatternRegistry.SpecialHandler>> = ArrayList()
@JvmStatic
fun registerPatterns() {
try {
for ((pattern, location, action) in PATTERNS)
PatternRegistry.mapPattern(pattern, location, action)
for ((pattern, location, action) in PER_WORLD_PATTERNS)
PatternRegistry.mapPattern(pattern, location, action, true)
for ((location, handler) in SPECIAL_HANDLERS)
PatternRegistry.addSpecialHandler(location, handler)
} catch (e: PatternRegistry.RegisterPatternException) {
e.printStackTrace()
}
}
// ============================ Type Comparison ===================================
@JvmField
val TYPE_BLOCK_ITEM = make(HexPattern.fromAngles("qaqqaea", HexDir.EAST), modLoc("type/block_item"), OpTypeBlockItem)
@JvmField
val TYPE_ENTITY = make(HexPattern.fromAngles("qawde", HexDir.SOUTH_WEST), modLoc("type/entity"), OpTypeEntity)
@JvmField
val TYPE_IOTA = make(HexPattern.fromAngles("awd", HexDir.SOUTH_WEST), modLoc("type/iota"), OpTypeIota)
@JvmField
val TYPE_ITEM_HELD = make(HexPattern.fromAngles("edeedqd", HexDir.SOUTH_WEST), modLoc("type/item_held"), OpTypeItemHeld)
@JvmField
val GET_ENTITY_TYPE = make(HexPattern.fromAngles("dadqqqqqdad", HexDir.NORTH_EAST), modLoc("get_entity/type"), OpGetEntityAtDyn)
@JvmField
val ZONE_ENTITY_TYPE = make(HexPattern.fromAngles("waweeeeewaw", HexDir.SOUTH_EAST), modLoc("zone_entity/type"), OpGetEntitiesByDyn(false))
@JvmField
val ZONE_ENTITY_NOT_TYPE = make(HexPattern.fromAngles("wdwqqqqqwdw", HexDir.NORTH_EAST), modLoc("zone_entity/not_type"), OpGetEntitiesByDyn(true))
// ========================== Misc Info Gathering =================================
@JvmField
val CURRENT_TICK = make(HexPattern.fromAngles("ddwaa", HexDir.NORTH_WEST), modLoc("current_tick"), OpCurrentTick)
@JvmField
val REMAINING_EVALS = make(HexPattern.fromAngles("qqaed", HexDir.SOUTH_EAST), modLoc("remaining_evals"), OpRemainingEvals)
@JvmField
val BREATH = make(HexPattern.fromAngles("aqawdwaqawd", HexDir.NORTH_WEST), modLoc("breath"), OpGetBreath)
@JvmField
val HEALTH = make(HexPattern.fromAngles("aqwawqa", HexDir.NORTH_WEST), modLoc("health"), OpGetHealth)
@JvmField
val ARMOUR = make(HexPattern.fromAngles("wqqqqw", HexDir.NORTH_WEST), modLoc("armour"), OpGetArmour)
@JvmField
val TOUGHNESS = make(HexPattern.fromAngles("aeqqqqea", HexDir.EAST), modLoc("toughness"), OpGetToughness)
@JvmField
val LIGHT_LEVEL = make(HexPattern.fromAngles("qedqde", HexDir.NORTH_EAST), modLoc("light_level"), OpGetLightLevel)
// =============================== Misc Maths =====================================
@JvmField
val FACTORIAL = make(HexPattern.fromAngles("wawdedwaw", HexDir.SOUTH_EAST), modLoc("factorial"), OpFactorial)
@JvmField
val RUNNING_SUM = make(HexPattern.fromAngles("aea", HexDir.WEST), modLoc("running/sum"), OpRunningOp ({ if (it is Vec3Iota) Vec3Iota(Vec3.ZERO) else DoubleIota(0.0) })
{ running, iota ->
when (running) {
is DoubleIota -> DoubleIota(running.double + ((iota as? DoubleIota)?.double ?: throw OpRunningOp.InvalidIotaException("list.double")))
is Vec3Iota -> Vec3Iota(running.vec3 + ((iota as? Vec3Iota)?.vec3 ?: throw OpRunningOp.InvalidIotaException("list.vec")))
else -> throw OpRunningOp.InvalidIotaException("list.doublevec")
}
})
@JvmField
val RUNNING_MUL = make(HexPattern.fromAngles("qaawaaq", HexDir.NORTH_EAST), modLoc("running/mul"), OpRunningOp ({ DoubleIota(1.0) })
{ running, iota ->
if (running !is DoubleIota)
throw OpRunningOp.InvalidIotaException("list.double")
DoubleIota(running.double * ((iota as? DoubleIota)?.double ?: throw OpRunningOp.InvalidIotaException("list.double")))
})
// ================================ Everbook ======================================
@JvmField
val EVERBOOK_READ = make(HexPattern.fromAngles("eweeewedqdeddw", HexDir.NORTH_EAST), modLoc("everbook/read"), OpEverbookRead)
@JvmField
val EVERBOOK_WRITE = make(HexPattern.fromAngles("qwqqqwqaeaqaaw", HexDir.SOUTH_EAST), modLoc("everbook/write"), OpEverbookWrite)
@JvmField
val EVERBOOK_DELETE = make(HexPattern.fromAngles("qwqqqwqaww", HexDir.SOUTH_EAST), modLoc("everbook/delete"), OpEverbookDelete)
@JvmField
val EVERBOOK_TOGGLE_MACRO = make(HexPattern.fromAngles("eweeewedww", HexDir.SOUTH_WEST), modLoc("everbook/toggle_macro"), OpToggleMacro)
// ============================== Misc Spells =====================================
@JvmField
val SMELT = make(HexPattern.fromAngles("wqqqwqqadad", HexDir.EAST), modLoc("smelt"), OpSmelt)
@JvmField
val FREEZE = make(HexPattern.fromAngles("weeeweedada", HexDir.WEST), modLoc("freeze"), OpFreeze)
@JvmField
val FALLING_BLOCK = make(HexPattern.fromAngles("wqwawqwqwqwqwqw", HexDir.EAST), modLoc("falling_block"), OpFallingBlock)
@JvmField
val PLACE_TYPE = make(HexPattern.fromAngles("eeeeedeeeee", HexDir.WEST), modLoc("place_type"), OpPlaceType)
@JvmField
val PARTICLES = make(HexPattern.fromAngles("eqqqqa", HexDir.NORTH_EAST), modLoc("particles"), OpParticles)
// =============================== Wisp Stuff =====================================
@JvmField
val WISP_SUMMON_PROJECTILE = make(HexPattern.fromAngles("aqaeqeeeee", HexDir.NORTH_WEST), modLoc("wisp/summon/projectile"), OpSummonWisp(false))
@JvmField
val WISP_SUMMON_TICKING = make(HexPattern.fromAngles("aqaweewaqawee", HexDir.NORTH_WEST), modLoc("wisp/summon/ticking"), OpSummonWisp(true))
@JvmField
val WISP_SELF = make(HexPattern.fromAngles("dedwqqwdedwqqaw", HexDir.NORTH_EAST), modLoc("wisp/self"), OpWispSelf)
@JvmField
val WISP_MEDIA = make(HexPattern.fromAngles("aqaweewaqaweedw", HexDir.NORTH_WEST), modLoc("wisp/media"), OpWispMedia)
@JvmField
val WISP_HEX = make(HexPattern.fromAngles("aweewaqaweewaawww", HexDir.SOUTH_EAST), modLoc("wisp/hex"), OpWispHex)
@JvmField
val WISP_OWNER = make(HexPattern.fromAngles("dwqqwdedwqqwddwww", HexDir.SOUTH_WEST), modLoc("wisp/owner"), OpWispOwner)
// Set and Get Move Target WEST awqwawqaw
@JvmField
val WISP_MOVE_TARGET_SET = make(HexPattern.fromAngles("awqwawqaw", HexDir.WEST), modLoc("wisp/move/target/set"), OpMoveTargetSet)
@JvmField
val WISP_MOVE_TARGET_GET = make(HexPattern.fromAngles("ewdwewdew", HexDir.EAST), modLoc("wisp/move/target/get"), OpMoveTargetGet)
@JvmField
val WISP_MOVE_SPEED_SET = make(HexPattern.fromAngles("aeawqqqae", HexDir.WEST), modLoc("wisp/move/speed/set"), OpMoveSpeedSet)
@JvmField
val WISP_MOVE_SPEED_GET = make(HexPattern.fromAngles("eeewdqdee", HexDir.EAST), modLoc("wisp/move/speed/get"), OpMoveSpeedGet)
// Entity purification and Zone distillations
@JvmField
val GET_ENTITY_WISP = make(HexPattern.fromAngles("qqwdedwqqdaqaaww", HexDir.SOUTH_EAST),
modLoc("get_entity/wisp"),
OpGetEntityAt{ entity -> entity is BaseWisp })
@JvmField
val ZONE_ENTITY_WISP = make(HexPattern.fromAngles("qqwdedwqqwdeddww", HexDir.SOUTH_EAST),
modLoc("zone_entity/wisp"),
OpGetEntitiesBy({ entity -> entity is BaseWisp }, false))
@JvmField
val ZONE_ENTITY_NOT_WISP = make(HexPattern.fromAngles("eewaqaweewaqaaww", HexDir.NORTH_EAST),
modLoc("zone_entity/not_wisp"),
OpGetEntitiesBy({ entity -> entity is BaseWisp }, true))
// Triggers
@JvmField
val WISP_TRIGGER_TICK = make(HexPattern.fromAngles("aqawded", HexDir.NORTH_WEST),
modLoc("wisp/trigger/tick"),
OpWispSetTrigger(WispTriggerTypes.TICK_TRIGGER_TYPE))
@JvmField
val WISP_TRIGGER_COMM = make(HexPattern.fromAngles("aqqqqqwdeddw", HexDir.EAST),
modLoc("wisp/trigger/comm"),
OpWispSetTrigger(WispTriggerTypes.COMM_TRIGGER_TYPE))
@JvmField
val WISP_TRIGGER_MOVE = make(HexPattern.fromAngles("eqwawqwaqww", HexDir.EAST),
modLoc("wisp/trigger/move"),
OpWispSetTrigger(WispTriggerTypes.MOVE_TRIGGER_TYPE))
val WISP_SEON_GET = make(HexPattern.fromAngles("daqweewqaeaqweewqaqwwww", HexDir.EAST),
modLoc("wisp/seon/get"),
OpSeonWispGet)
// =============================== Link Stuff =====================================
@JvmField
val LINK = make(HexPattern.fromAngles("eaqaaeqqqqqaweaqaaw", HexDir.EAST), modLoc("link"), OpLink)
@JvmField
val LINK_OTHERS = make(HexPattern.fromAngles("eqqqqqawqeeeeedww", HexDir.EAST), modLoc("link/others"), OpLinkOthers)
@JvmField
val UNLINK = make(HexPattern.fromAngles("qdeddqeeeeedwqdeddw", HexDir.WEST), modLoc("link/unlink"), OpUnlink)
@JvmField
val UNLINK_OTHERS = make(HexPattern.fromAngles("qeeeeedweqqqqqaww", HexDir.WEST), modLoc("link/unlink/others"), OpUnlinkOthers)
@JvmField
val LINK_GET = make(HexPattern.fromAngles("eqqqqqaww", HexDir.EAST), modLoc("link/get"), OpGetLinked)
@JvmField
val LINK_GET_INDEX = make(HexPattern.fromAngles("aeqqqqqawwd", HexDir.SOUTH_WEST), modLoc("link/get_index"), OpGetLinkedIndex)
@JvmField
val LINK_NUM = make(HexPattern.fromAngles("qeeeeedww", HexDir.WEST), modLoc("link/num"), OpNumLinked)
@JvmField
val LINK_COMM_SEND = make(HexPattern.fromAngles("qqqqqwdeddw", HexDir.NORTH_WEST), modLoc("link/comm/send"), OpSendIota)
@JvmField
val LINK_COMM_READ = make(HexPattern.fromAngles("weeeeew", HexDir.NORTH_EAST), modLoc("link/comm/read"), OpReadReceivedIota)
@JvmField
val LINK_COMM_NUM = make(HexPattern.fromAngles("aweeeeewaa", HexDir.SOUTH_EAST), modLoc("link/comm/num"), OpNumReceivedIota)
@JvmField
val LINK_COMM_CLEAR = make(HexPattern.fromAngles("aweeeeewa", HexDir.SOUTH_EAST), modLoc("link/comm/clear"), OpClearReceivedIotas)
@JvmField
val LINK_COMM_OPEN_TRANSMIT = make(HexPattern.fromAngles("qwdedwq", HexDir.WEST), modLoc("link/comm/open_transmit"), OpOpenTransmit)
@JvmField
val LINK_COMM_CLOSE_TRANSMIT = make(HexPattern.fromAngles("ewaqawe", HexDir.EAST), modLoc("link/comm/close_transmit"), OpCloseTransmit)
// =============================== Gate Stuff =====================================
@JvmField
val GATE_MARK = make(HexPattern.fromAngles("qaqeede", HexDir.WEST), modLoc("gate/mark"), OpMarkGate)
@JvmField
val GATE_UNMARK = make(HexPattern.fromAngles("edeqqaq", HexDir.EAST), modLoc("gate/unmark"), OpUnmarkGate)
@JvmField
val GATE_MARK_GET = make(HexPattern.fromAngles("edwwdeeede", HexDir.EAST), modLoc("gate/mark/get"), OpGetMarkedGate)
@JvmField
val GATE_MARK_NUM_GET = make(HexPattern.fromAngles("qawwaqqqaq", HexDir.WEST), modLoc("gate/mark/num/get"), OpGetNumMarkedGate)
@JvmField
val GATE_CLOSE = make(HexPattern.fromAngles("qqqwwqqqwqqawdedw", HexDir.WEST), modLoc("gate/close"), OpCloseGate)
// =============================== Gate Stuff =====================================
@JvmField
val BIND_STORAGE = make(HexPattern.fromAngles("qaqwqaqwqaq", HexDir.NORTH_WEST), modLoc("mote/storage/bind"), OpBindStorage(false))
@JvmField
val BIND_STORAGE_TEMP = make(HexPattern.fromAngles("edewedewede", HexDir.NORTH_EAST), modLoc("mote/storage/bind/temp"), OpBindStorage(true))
@JvmField
val MOTE_CONTAINED_TYPE_GET = make(HexPattern.fromAngles("dwqqqqqwddww", HexDir.NORTH_EAST), modLoc("mote/contained_type/get"), OpGetContainedItemTypes)
@JvmField
val MOTE_CONTAINED_GET = make(HexPattern.fromAngles("aweeeeewaaww", HexDir.SOUTH_EAST), modLoc("mote/contained/get"), OpGetContainedMotes)
@JvmField
val MOTE_STORAGE_REMAINING_CAPACITY_GET = make(HexPattern.fromAngles("awedqdewa", HexDir.SOUTH_EAST), modLoc("mote/storage/remaining_capacity/get"), OpGetStorageRemainingCapacity)
@JvmField
val MOTE_STORAGE_CONTAINS = make(HexPattern.fromAngles("dwqaeaqwd", HexDir.NORTH_EAST), modLoc("mote/storage/contains"), OpStorageContains)
@JvmField
val MOTE_MAKE = make(HexPattern.fromAngles("eaqa", HexDir.WEST), modLoc("mote/make"), OpMakeItem)
@JvmField
val MOTE_RETURN = make(HexPattern.fromAngles("qded", HexDir.EAST), modLoc("mote/return"), OpReturnMote)
@JvmField
val MOTE_COUNT_GET = make(HexPattern.fromAngles("qqqqwqqqqqaa", HexDir.NORTH_WEST), modLoc("mote/count/get"), OpGetCountMote)
@JvmField
val MOTE_COMBINE = make(HexPattern.fromAngles("aqaeqded", HexDir.NORTH_WEST), modLoc("mote/combine"), OpCombineMotes)
@JvmField
val MOTE_COMBINABLE = make(HexPattern.fromAngles("dedqeaqa", HexDir.SOUTH_WEST), modLoc("mote/combinable"), OpMotesCombinable)
@JvmField
val MOTE_SPLIT = make(HexPattern.fromAngles("eaqaaw", HexDir.EAST), modLoc("mote/split"), OpSplitMote)
@JvmField
val MOTE_STORAGE_GET = make(HexPattern.fromAngles("qqqqqaw", HexDir.SOUTH_WEST), modLoc("mote/storage/get"), OpGetMoteStorage)
@JvmField
val MOTE_STORAGE_SET = make(HexPattern.fromAngles("eeeeedw", HexDir.SOUTH_EAST), modLoc("mote/storage/set"), OpSetMoteStorage)
@JvmField
val MOTE_CRAFT = make(HexPattern.fromAngles("wwawdedwawdewwdwaqawdwwedwawdedwaww", HexDir.SOUTH_EAST), modLoc("mote/craft"), OpCraftMote)
@JvmField
val MOTE_VILLAGER_LEVEL_GET = make(HexPattern.fromAngles("qqwdedwqqaww", HexDir.NORTH_WEST), modLoc("mote/villager/level/get"), OpGetVillagerLevel)
@JvmField
val MOTE_TRADE_GET = make(HexPattern.fromAngles("awdedwaawwqded", HexDir.SOUTH_EAST), modLoc("mote/trade/get"), OpGetItemTrades)
@JvmField
val MOTE_TRADE = make(HexPattern.fromAngles("awdedwaeqded", HexDir.NORTH_WEST), modLoc("mote/trade"), OpTradeMote)
@JvmField
val MOTE_USE_ON = make(HexPattern.fromAngles("qqqwqqqqaa", HexDir.EAST), modLoc("mote/use_on"), OpUseMoteOn)
// ============================== Great Stuff =====================================
@JvmField
val CONSUME_WISP = make(HexPattern.fromAngles("wawqwawwwewwwewwwawqwawwwewwwewdeaweewaqaweewaawwww", HexDir.NORTH_WEST),
modLoc("wisp/consume"),
OpConsumeWisp,
true)
@JvmField
val WISP_SEON_SET = make(HexPattern.fromAngles("aqweewqaeaqweewqaqwww", HexDir.SOUTH_WEST),
modLoc("wisp/seon/set"),
OpSeonWispSet,
true)
@JvmField
val TICK = make(HexPattern.fromAngles("wwwdwdwwwawqqeqwqqwqeqwqq", HexDir.SOUTH_EAST), modLoc("tick"), OpTick, true)
@JvmField
val GATE_MAKE = make(HexPattern.fromAngles("qwqwqwqwqwqqeaeaeaeaeae", HexDir.WEST), modLoc("gate/make"), OpMakeGate, true)
// ================================ Special Handlers =======================================
// @JvmField
// val EXAMPLE_HANDLER = make(modLoc("example_handler")) {pat ->
// return@make Action.makeConstantOp(StringIota("example! $pat"))
// }
fun make (pattern: HexPattern, location: ResourceLocation, operator: Action, isPerWorld: Boolean = false): PatternIota {
val triple = Triple(pattern, location, operator)
if (isPerWorld)
PER_WORLD_PATTERNS.add(triple)
else
PATTERNS.add(triple)
return PatternIota(pattern)
}
fun make (location: ResourceLocation, specialHandler: PatternRegistry.SpecialHandler): Pair<ResourceLocation, PatternRegistry.SpecialHandler> {
val pair = location to specialHandler
SPECIAL_HANDLERS.add(pair)
return pair
}
} | 20 | Kotlin | 9 | 11 | de4ca64b9415363eb0144f1a8a9ed6cecde7721d | 16,379 | Hexal | MIT License |
app/src/main/java/com/eneskayiklik/wallup/feature_home/domain/repository/HomeRepository.kt | Enes-Kayiklik | 448,236,227 | false | {"Kotlin": 135987} | package com.eneskayiklik.wallup.feature_home.domain.repository
import com.eneskayiklik.wallup.feature_home.data.dto.UnsplashPhotoDto
import com.eneskayiklik.wallup.feature_home.domain.model.Category
import com.eneskayiklik.wallup.feature_home.domain.model.ColorItem
import com.eneskayiklik.wallup.utils.network.Resource
interface HomeRepository {
suspend fun getColorList(): List<ColorItem>
suspend fun getCategoryList(): List<Category>
suspend fun getRandomPhotos(): Resource<List<UnsplashPhotoDto>>
} | 0 | Kotlin | 3 | 38 | 03a9d3f07b7f788f6c36a059fe882eae78065937 | 519 | Wall-Up | Apache License 2.0 |
library/src/main/java/renetik/android/event/registration/CSHasRegistrations.kt | renetik | 506,084,889 | false | null | package renetik.android.event.registration
//TODO: Does CSHasRegistrations always extend HasDestruct ?
interface CSHasRegistrations {
companion object
val registrations: CSRegistrations
} | 0 | Kotlin | 0 | 2 | a980d7656afc6634e5c0ffceeece661511b75241 | 198 | renetik-android-event | MIT License |
app/src/main/java/com/qs/tv/tvplayer/utils/FileUtils.kt | suresh000 | 665,561,729 | false | null | package com.qs.tv.tvplayer.utils
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Environment
import android.text.TextUtils
import android.widget.Toast
import androidx.core.content.FileProvider
import com.qs.sharedcode.utils.AppUtils
import java.io.File
import java.io.IOException
import java.util.Locale
class FileUtils private constructor() {
init {
throw IllegalStateException(javaClass.name)
}
// Checks if external storage is available for read and write
companion object {
const val FILE_PROVIDER = "com.qs.tv.tvplayer.fileprovider"
private val extensions = arrayOf(
"avi", "3gp", "mp4", "mp3", "jpeg", "jpg",
"gif", "png",
"pdf", "docx", "doc", "xls", "xlsx", "csv", "ppt", "pptx",
"txt", "zip", "rar"
)
@JvmStatic
@Throws(ActivityNotFoundException::class, IOException::class)
fun openFile(activity: Activity, url: File) {
// Create URI
//Uri uri = Uri.fromFile(url);
//TODO you want to use this method then create file provider in androidmanifest.xml with fileprovider name
val uri = FileProvider.getUriForFile(activity, FILE_PROVIDER, url)
val urlString = url.toString().lowercase(Locale.getDefault())
val intent = Intent(Intent.ACTION_VIEW)
val resInfoList = activity.packageManager.queryIntentActivities(
intent,
PackageManager.MATCH_DEFAULT_ONLY
)
for (resolveInfo in resInfoList) {
val packageName = resolveInfo.activityInfo.packageName
activity.grantUriPermission(
packageName,
uri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
)
}
if (urlString.lowercase(Locale.getDefault()).lowercase(Locale.getDefault())
.contains(".doc")
|| urlString.lowercase(Locale.getDefault()).contains(".docx")
) {
// Word document
intent.setDataAndType(uri, "application/msword")
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
} else if (urlString.lowercase(Locale.getDefault()).contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf")
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
} else if (urlString.lowercase(Locale.getDefault()).contains(".ppt")
|| urlString.lowercase(Locale.getDefault()).contains(".pptx")
) {
// Powerpoint file
intent.setDataAndType(uri, "application/vnd.ms-powerpoint")
} else if (urlString.lowercase(Locale.getDefault()).contains(".xls")
|| urlString.lowercase(Locale.getDefault()).contains(".xlsx")
) {
// Excel file
intent.setDataAndType(uri, "application/vnd.ms-excel")
} else if (urlString.lowercase(Locale.getDefault()).contains(".zip")
|| urlString.lowercase(Locale.getDefault()).contains(".rar")
) {
// ZIP file
intent.setDataAndType(uri, "application/trap")
} else if (urlString.lowercase(Locale.getDefault()).contains(".rtf")) {
// RTF file
intent.setDataAndType(uri, "application/rtf")
} else if (urlString.lowercase(Locale.getDefault()).contains(".wav")
|| urlString.lowercase(Locale.getDefault()).contains(".mp3")
) {
// WAV/MP3 audio file
intent.setDataAndType(uri, "audio/*")
} else if (urlString.lowercase(Locale.getDefault()).contains(".gif")) {
// GIF file
intent.setDataAndType(uri, "image/gif")
} else if (urlString.lowercase(Locale.getDefault()).contains(".jpg")
|| urlString.lowercase(Locale.getDefault()).contains(".jpeg")
|| urlString.lowercase(Locale.getDefault()).contains(".png")
) {
// JPG file
intent.setDataAndType(uri, "image/jpeg")
} else if (urlString.lowercase(Locale.getDefault()).contains(".txt")) {
// Text file
intent.setDataAndType(uri, "text/plain")
} else if (urlString.lowercase(Locale.getDefault()).contains(".3gp")
|| urlString.lowercase(Locale.getDefault()).contains(".mpg")
|| urlString.lowercase(Locale.getDefault()).contains(".mpeg")
|| urlString.lowercase(Locale.getDefault()).contains(".mpe")
|| urlString.lowercase(Locale.getDefault()).contains(".mp4")
|| urlString.lowercase(Locale.getDefault()).contains(".avi")
) {
// Video files
intent.setDataAndType(uri, "video/*")
} else {
intent.setDataAndType(uri, "*/*")
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
activity.startActivity(intent)
} catch (e: ActivityNotFoundException) {
activity.runOnUiThread {
AppUtils.showToast(
activity,
"Something Wrong. Viewer not found", Toast.LENGTH_LONG
)
}
}
}
@JvmStatic
fun getAppCacheDir(context: Context): String {
val dir = File(
context.cacheDir.toString()
+ File.separator
+ "tvPlayer"
+ File.separator
)
if (!dir.exists()) {
dir.mkdirs()
}
return dir.path + File.separator
}
@JvmStatic
fun getAppPath(context: Context): String {
val dir = File(
context.getExternalFilesDir(null).toString()
+ File.separator
+ "tvPlayer"
+ File.separator
)
if (!dir.exists()) {
dir.mkdirs()
}
return dir.path + File.separator
}
@JvmStatic
fun getImagePath(context: Context): String {
val dir = File(
context.getExternalFilesDir(null).toString()
+ File.separator
+ "tvPlayer"
+ File.separator
+ "Image"
+ File.separator
)
if (!dir.exists()) {
dir.mkdirs()
}
return dir.path + File.separator
}
@JvmStatic
fun getImageExternalStorageDirectory(context: Context): String {
val root = Environment.getExternalStorageDirectory()
if (!isExternalStorageRemovable(root)) {
val dir = File(
root.absolutePath
+ File.separator
+ "tvPlayer"
+ File.separator
+ "Image"
+ File.separator
)
if (!dir.exists()) {
dir.mkdirs()
}
return dir.path + File.separator
} else {
return getImagePath(context)
}
}
@JvmStatic
fun getVideoPath(context: Context): String {
val dir = File(
context.getExternalFilesDir(null).toString()
+ File.separator
+ "tvPlayer"
+ File.separator
+ "Video"
+ File.separator
)
if (!dir.exists()) {
dir.mkdirs()
}
return dir.path + File.separator
}
@JvmStatic
fun getVideoExternalStorageDirectory(context: Context): String {
val root = Environment.getExternalStorageDirectory()
if (!isExternalStorageRemovable(root)) {
val dir = File(
root.absolutePath
+ File.separator
+ "tvPlayer"
+ File.separator
+ "Video"
+ File.separator
)
if (!dir.exists()) {
dir.mkdirs()
}
return dir.path + File.separator
} else {
return getVideoPath(context)
}
}
@JvmStatic
fun isExit(imagePath: String?): Boolean {
return if (!TextUtils.isEmpty(imagePath)) {
val uri = Uri.parse(imagePath)
val file = File(uri.path.toString())
file.exists()
} else {
false
}
}
@JvmStatic
fun isExternalStorageRemovable(file: File) : Boolean {
return Environment.isExternalStorageRemovable(file)
}
@JvmStatic
val isExternalStorageWritable: Boolean
get() {
val state = Environment.getExternalStorageState()
return Environment.MEDIA_MOUNTED == state
}
@JvmStatic
fun isValidExtension(ext: String): Boolean {
return mutableListOf(*extensions).contains(ext)
}
@JvmStatic
fun getExtension(path: String): String {
return if (path.contains(".")) path.substring(path.lastIndexOf(".") + 1)
.lowercase(Locale.getDefault()) else ""
}
@JvmStatic
fun deleteFile(file: File?): Boolean {
return if (file != null && file.exists()) {
file.delete()
} else false
}
}
} | 0 | Kotlin | 0 | 0 | 246e40e96ebe2648f243f1b105787a456f8529f5 | 10,417 | tvPlayer | Apache License 2.0 |
server/src/main/java/roomScanner/CarController.kt | olonho | 60,483,862 | false | null | package roomScanner
import CodedInputStream
import RouteMetricRequest
import SonarRequest
import SonarResponse
import net.car.client.Client
import objects.CarReal
class CarController(var car: CarReal) {
enum class Direction(val id: Int) {
FORWARD(0),
BACKWARD(1),
LEFT(2),
RIGHT(3);
}
//todo use x,y,angle from car object. x,y in sm, angle in degrees
var position = Pair(0.0, 0.0)
private set
private var angle = 0.0
private val CHARGE_CORRECTION = 0.97
private val MAX_ANGLE = 360.0
private val SCAN_STEP = 5.0
private val MIN_ROTATION = 10
private val MAX_VALID_DISTANCE = 100.0
fun moveTo(to: Pair<Double, Double>, distance: Double) {
val driveAngle = (Math.toDegrees(Math.atan2(to.second, to.first)) + MAX_ANGLE) % MAX_ANGLE
rotateOn(driveAngle)
drive(Direction.FORWARD, distance.toInt())
position = Pair(position.first + distance * Math.cos(Math.toRadians(driveAngle)),
position.second + distance * Math.sin(Math.toRadians(driveAngle)))
}
fun rotateOn(target: Double) {
val rotateAngle = angleDistance(angle, target)
val direction = if (rotateAngle > 0) Direction.LEFT else Direction.RIGHT
drive(direction, Math.abs(rotateAngle.toInt()))
angle = target
}
fun rotateLeftWithCorrection(angle: Double) {
val horizon = horizon()
val before = scan(horizon)
drive(Direction.LEFT, angle.toInt())
var after = scan(horizon)
val distance = fun(first: Double, second: Double): Double = Math.max(when {
first == second -> 0.0
first == -1.0 -> second
second == -1.0 -> first
else -> Math.max(Math.abs(first - second).toDouble(), 100.0)
}, MAX_VALID_DISTANCE)
var realAngle = (maxSuffix(before, after, distance) + 1) * SCAN_STEP
while (realAngle != angle) {
val direction = if (realAngle > angle) Direction.RIGHT else Direction.LEFT
drive(direction, Math.min(MIN_ROTATION, Math.abs(realAngle - angle).toInt()))
after = scan(horizon)
realAngle = maxSuffix(before, after, distance) * SCAN_STEP
}
this.angle = realAngle
}
fun scan(angles: IntArray): List<Double> {
val request = SonarRequest.BuilderSonarRequest(angles, IntArray(angles.size, { 1 }), 1, SonarRequest.Smoothing.NONE).build()
val data = serialize(request.getSizeNoTag(), { request.writeTo(it) })
val response = car.carConnection.sendRequest(Client.Request.SONAR, data).get().responseBodyAsBytes
val result = SonarResponse.BuilderSonarResponse(IntArray(0)).parseFrom(CodedInputStream(response)).build().distances.map { it.toDouble() }
return result
}
fun convertToPoint(angle: Double, distance: Double): Pair<Double, Double> {
if (distance <= 0) {
return Pair(0.0, 0.0)
}
val realAngle = Math.toRadians(angle + this.angle)
return Pair(Math.cos(realAngle) * distance + position.first, Math.sin(realAngle) * distance + position.second)
}
fun drive(direction: Direction, distance: Int) {
val request = RouteMetricRequest.BuilderRouteMetricRequest(intArrayOf((distance * CHARGE_CORRECTION).toInt()), intArrayOf(direction.id)).build()
val data = serialize(request.getSizeNoTag(), { i -> request.writeTo(i) })
car.carConnection.sendRequest(Client.Request.ROUTE_METRIC, data).get()
}
}
| 0 | C | 1 | 10 | 321925af6cd64339a12a1658c3412a5461a32563 | 3,542 | carkot | MIT License |
automation/code-generator/src/main/kotlin/io/github/typesafegithub/workflows/codegenerator/model/ActionBindingRequest.kt | typesafegithub | 439,670,569 | false | {"Kotlin": 1903542} | package io.github.typesafegithub.workflows.codegenerator.model
import io.github.typesafegithub.workflows.actionbindinggenerator.domain.ActionCoords
data class ActionBindingRequest(
val actionCoords: ActionCoords,
)
| 31 | Kotlin | 24 | 498 | eafac8ece82c076293bd2e6db47b1911e108b501 | 221 | github-workflows-kt | Apache License 2.0 |
feature-viewhighlights/src/main/java/com/sriniketh/feature_viewhighlights/HighlightViewHolder.kt | sriniketh | 508,750,949 | false | null | package com.sriniketh.feature_viewhighlights
import androidx.recyclerview.widget.RecyclerView
import com.squareup.phrase.Phrase
import com.sriniketh.feature_viewhighlights.databinding.HighlightItemCardBinding
class HighlightViewHolder(
private val binding: HighlightItemCardBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(uiState: HighlightUIState) {
val context = binding.root.context
binding.highlightText.text = uiState.text
binding.highlightSubtext.text = Phrase.from(context.getString(R.string.saved_on_template)).put("datetime", uiState.savedOn).format()
}
}
| 0 | Kotlin | 0 | 1 | 8f52412858acba12446ea2c1d7e0c8402f5f0ee1 | 617 | prose | Apache License 2.0 |
app/src/main/java/utn/frba/mobile/konzern/expenses/adapter/ExpensesAdapter.kt | UTN-FRBA-Mobile | 261,071,131 | false | null | package utn.frba.mobile.konzern.expenses.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.expenses_item.view.*
import utn.frba.mobile.konzern.R
import utn.frba.mobile.konzern.contact.model.Contact
import utn.frba.mobile.konzern.expenses.model.Expenses
import utn.frba.mobile.konzern.expenses.ui.ExpensesFragment.ExpensesFragmentView
class ExpensesAdapter(private var expensesList: List<Expenses>,
private val expensesView: ExpensesFragmentView?,
private val expensesPdfAdapter: ExpensesPdfAdapter?,
private val consortium: Contact,
private val context: Context?
) : RecyclerView.Adapter<ExpensesAdapter.ExpensesItem>(), Filterable {
private var expensesFullList = mutableListOf<Expenses>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExpensesItem {
val view = LayoutInflater
.from(parent.context)
.inflate(R.layout.expenses_item, parent, false)
if(expensesFullList.isEmpty())
expensesFullList.addAll(0, expensesList)
return ExpensesItem(view)
}
override fun getItemCount(): Int = expensesList.size
override fun onBindViewHolder(expense: ExpensesItem, position: Int) {
expense.run {
month.text = expensesList[position].monthLabel
year.text = expensesList[position].year
amount.text = expensesList[position].amount
expirationDate.text = expensesList[position].expirationDate
downloadButton.setOnClickListener {
val path = expensesPdfAdapter?.createPDFFile (expensesList[position], consortium, context); expensesView?.downloadPDFSuccess(path.toString())
}
}
}
class ExpensesItem(view: View) : RecyclerView.ViewHolder(view) {
var month = view.vExpensesItemMonthValue
var year = view.vExpensesItemYearValue
var amount = view.vExpensesItemAmountValue
var expirationDate = view.vExpensesItemExpirationDateValue
var downloadButton = view.vExpensesItemDownloadButton
}
override fun getFilter(): Filter {
return expensesFilter
}
private val expensesFilter: Filter = object : Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults {
var expensesFilteredList = mutableListOf<Expenses>()
var filterResults = FilterResults()
if (constraint == null || constraint.isEmpty()) {
expensesFilteredList.addAll(0, expensesFullList)
} else {
var filterPattern = constraint.toString().toUpperCase().trim()
for ( i : Expenses in expensesFullList) {
if (i.monthLabel.toUpperCase().trim().contains(filterPattern)) {
expensesFilteredList.add(i)
}
}
}
filterResults.values = expensesFilteredList
return filterResults
}
override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
expensesList = results?.values as List<Expenses>
notifyDataSetChanged()
}
}
} | 0 | Kotlin | 0 | 0 | d8b1261be749d03a5ef8b0866054206e6f76e00f | 3,482 | Konzern | MIT License |
server/src/test/kotlin/com/derekleerock/todolistapi/todolist/LocalToDoListRepoTest.kt | derekleerock | 156,353,094 | false | null | package com.derekleerock.todolistapi.todolist
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Before
import org.junit.Test
class LocalToDoListRepoTest {
lateinit var localToDoListRepo: LocalToDoListRepo
@Before
fun setUp() {
localToDoListRepo = LocalToDoListRepo()
}
@Test
fun getAll_returnsEmptyList_whenNoItems() {
val toDos = localToDoListRepo.getAll()
assertThat(toDos.size, `is`(equalTo(0)))
}
@Test
fun create_returnsCreatedItem() {
val toDoItem = localToDoListRepo.create(
NewToDo("Buy groceries")
)
val expectedToDoItem = ToDoItem(1, "Buy groceries", false)
assertThat(toDoItem, `is`(equalTo(expectedToDoItem)))
}
@Test
fun getAll_returnsItem_whenCreatingSingleItem() {
localToDoListRepo.create(
NewToDo("Buy groceries")
)
val toDos = localToDoListRepo.getAll()
assertThat(toDos.size, `is`(equalTo(1)))
assertThat(toDos.first(), `is`(equalTo(ToDoItem(1, "Buy groceries", false))))
}
@Test
fun create_incrementsIdAutomatically_whenCreatingNewToDoItems() {
localToDoListRepo.create(NewToDo("First ToDo"))
localToDoListRepo.create(NewToDo("Second ToDo"))
val lastToDo = localToDoListRepo.getAll().last()
assertThat(lastToDo.id, `is`(equalTo(2L)))
}
}
| 3 | Swift | 1 | 12 | 30f30571e2da5c733c276fddf6db4397c32b4a5d | 1,488 | ToDoList | MIT License |
app/src/main/java/com/example/animeapp/domain/module/AnimeEntity.kt | emrekizil | 578,072,214 | false | {"Kotlin": 66198} | package com.example.animeapp.domain.module
data class AnimeEntity (
val id:String,
val name:String,
val imageUrl:String,
val description:String,
val popularityRank:String
) | 0 | Kotlin | 0 | 4 | 8f15b49b95a598d8c9aadfaf08870cd5a4c3f77e | 193 | AnimeApp | Apache License 2.0 |
app/src/main/kotlin/cz/covid19cz/erouska/ui/exposure/ExposuresVM.kt | vandac | 297,722,215 | true | {"Kotlin": 246509, "Java": 1863, "Shell": 384} | package cz.covid19cz.erouska.ui.exposure
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import arch.viewmodel.BaseArchViewModel
import cz.covid19cz.erouska.exposurenotifications.ExposureNotificationsRepository
import cz.covid19cz.erouska.ext.daysSinceEpochToDateString
import cz.covid19cz.erouska.ui.exposure.event.ExposuresCommandEvent
import cz.covid19cz.erouska.utils.L
import kotlinx.coroutines.launch
class ExposuresVM @ViewModelInject constructor(private val exposureNotificationsRepo: ExposureNotificationsRepository) :
BaseArchViewModel() {
val lastExposureDate = MutableLiveData<String>()
fun checkExposures(demo: Boolean) {
// TODO Check if there were any exposures in last 14 days
// If yes -> Show RECENT_EXPOSURE
// If not and there are some exposures in the past -> Show NO_RECENT_EXPOSURES
// If there are NO exposures in the DB -> Show NO_EXPOSURES
if (!demo) {
viewModelScope.launch {
kotlin.runCatching {
exposureNotificationsRepo.getLastRiskyExposure()
}.onSuccess {
publish(
ExposuresCommandEvent(
if (it != null) {
lastExposureDate.value =
it.daysSinceEpoch.daysSinceEpochToDateString()
ExposuresCommandEvent.Command.RECENT_EXPOSURE
} else {
ExposuresCommandEvent.Command.NO_RECENT_EXPOSURES
}
)
)
}.onFailure {
L.e(it)
}
}
} else {
lastExposureDate.value =
((System.currentTimeMillis() / 1000 / 60 / 60 / 24) - 3).toInt()
.daysSinceEpochToDateString()
publish(
ExposuresCommandEvent(ExposuresCommandEvent.Command.RECENT_EXPOSURE)
)
}
}
fun debugRecentExp() {
publish(ExposuresCommandEvent(ExposuresCommandEvent.Command.RECENT_EXPOSURE))
}
fun debugExp() {
publish(ExposuresCommandEvent(ExposuresCommandEvent.Command.NO_RECENT_EXPOSURES))
}
} | 0 | null | 0 | 0 | 76c0d1348ca939ec0503ea3e09967741f86df2aa | 2,378 | erouska-android | MIT License |
export/kotlin/MobileOrders/app/src/main/java/com/glowbom/mobileorders/model/ItemDatabase.kt | glowbom | 258,701,167 | false | {"Dart": 78503, "Kotlin": 49836, "Swift": 17474, "HTML": 8909, "JavaScript": 3152, "Ruby": 1354, "Objective-C": 38} | /*
* Created on 4/28/20 3:12 AM
*
* Copyright 2020 Glowbom, Inc.
*/
package com.glowbom.mobileorders.model
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = arrayOf(Item::class), version = 2)
abstract class ItemDatabase: RoomDatabase() {
abstract fun itemDao(): ItemDao
companion object {
@Volatile private var instance: ItemDatabase? = null
private val LOCK = Any()
operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
instance ?: buildDatabase(context).also {
instance = it
}
}
private fun buildDatabase(context: Context) = Room.databaseBuilder(
context.applicationContext,
ItemDatabase::class.java,
"itemdatabase"
).build()
}
}
@Database(entities = arrayOf(Item::class), version = 2)
abstract class CheckoutDatabase: RoomDatabase() {
abstract fun itemDao(): ItemDao
companion object {
@Volatile private var instance: ItemDatabase? = null
private val LOCK = Any()
operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
instance ?: buildDatabase(context).also {
instance = it
}
}
private fun buildDatabase(context: Context) = Room.databaseBuilder(
context.applicationContext,
ItemDatabase::class.java,
"checkoutdatabase"
).build()
}
} | 0 | Dart | 11 | 43 | ea255fd4402907aab4b1d4f35d74d3ee39eb30b1 | 1,551 | mobile-orders | MIT License |
src/main/kotlin/me/itdog/hko_bot/api/model/Wfntsac.kt | tingtingths | 419,632,365 | false | null | package me.itdog.hko_bot.api.model
import javax.annotation.Generated
@Generated("jsonschema2pojo")
class Wfntsac : WarningBase()
| 0 | Kotlin | 0 | 0 | ae469003043f3a8d7fbcd184dd8e286cfabe18ca | 131 | hko_bot | MIT License |
src/all/animeworldindia/src/eu/kanade/tachiyomi/animeextension/all/animeworldindia/AnimeWorldIndia.kt | tonmoyislam250 | 672,950,261 | false | null | package eu.kanade.tachiyomi.animeextension.all.animeworldindia
import android.app.Application
import android.content.SharedPreferences
import androidx.preference.ListPreference
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.animesource.online.ParsedAnimeHttpSource
import eu.kanade.tachiyomi.lib.streamsbextractor.StreamSBExtractor
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.util.asJsoup
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
import java.lang.Exception
open class AnimeWorldIndia(
final override val lang: String,
private val language: String,
) : ConfigurableAnimeSource, ParsedAnimeHttpSource() {
override val name = "AnimeWorld India"
override val baseUrl = "https://anime-world.in"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
private val json: Json by injectLazy()
private val preferences: SharedPreferences by lazy {
Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000)
}
// =============================== Search ===============================
override fun searchAnimeNextPageSelector(): String = "ul.page-numbers li:has(span[aria-current=\"page\"]) + li"
override fun searchAnimeSelector(): String = "div.col-span-1"
override fun searchAnimeFromElement(element: Element): SAnime {
val anime = SAnime.create()
anime.setUrlWithoutDomain(element.selectFirst("a")!!.attr("href"))
var thumbnail = element.selectFirst("img")!!.attr("src")
if (!thumbnail.contains("https")) {
thumbnail = "$baseUrl/$thumbnail"
}
anime.thumbnail_url = thumbnail
anime.title = element.select("div.font-medium.line-clamp-2.mb-3").text()
return anime
}
override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList): Request {
val searchParams = AnimeWorldIndiaFilters().getSearchParams(filters)
return GET("$baseUrl/advanced-search/page/$page/?s_keyword=$query&s_lang=$lang$searchParams")
}
override fun getFilterList() = AnimeWorldIndiaFilters().filters
// ============================== Popular ===============================
override fun popularAnimeNextPageSelector(): String = searchAnimeNextPageSelector()
override fun popularAnimeSelector(): String = searchAnimeSelector()
override fun popularAnimeFromElement(element: Element): SAnime = searchAnimeFromElement(element)
override fun popularAnimeRequest(page: Int): Request = GET("$baseUrl/advanced-search/page/$page/?s_keyword=&s_type=all&s_status=all&s_lang=$lang&s_sub_type=all&s_year=all&s_orderby=viewed&s_genre=")
// =============================== Latest ===============================
override fun latestUpdatesNextPageSelector(): String = searchAnimeNextPageSelector()
override fun latestUpdatesSelector(): String = searchAnimeSelector()
override fun latestUpdatesFromElement(element: Element): SAnime = searchAnimeFromElement(element)
override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/advanced-search/page/$page/?s_keyword=&s_type=all&s_status=all&s_lang=$lang&s_sub_type=all&s_year=all&s_orderby=update&s_genre=")
// =========================== Anime Details ============================
override fun animeDetailsParse(document: Document): SAnime {
val anime = SAnime.create().apply {
genre = document.select("span.leading-6 a[class~=border-opacity-30]").joinToString(", ") { it.text() }
description = document.select("span.block.w-full.max-h-24.overflow-scroll.my-3.overflow-x-hidden.text-xs.text-gray-200").text()
author = document.select("span.leading-6 a[href*=\"producer\"]:first-child").text()
artist = document.select("span.leading-6 a[href*=\"studio\"]:first-child").text()
status = parseStatus(document)
}
return anime
}
private val selector = "ul li:has(div.w-1.h-1.bg-gray-500.rounded-full) + li"
private fun parseStatus(document: Document): Int {
return when (document.select("$selector a:not(:contains(Ep))").text()) {
"Movie" -> SAnime.COMPLETED
else -> {
val episodeString = document.select("$selector a:not(:contains(TV))").text().drop(3).split("/")
if (episodeString[0].trim().compareTo(episodeString[1].trim()) == 0) {
SAnime.COMPLETED
} else SAnime.ONGOING
}
}
}
// ============================== Episodes ==============================
override fun episodeListSelector() = throw Exception("not used")
override fun episodeFromElement(element: Element): SEpisode = throw Exception("not used")
override fun episodeListParse(response: Response): List<SEpisode> {
val document = response.asJsoup()
val episodeList = mutableListOf<SEpisode>()
val seasonsJson = json.decodeFromString<JsonArray>(
document.html()
.substringAfter("var season_list = ")
.substringBefore("var season_label =")
.trim().dropLast(1),
)
var seasonNumber = 1
var episodeNumber = 1f
val isAnimeCompleted = parseStatus(document) == SAnime.COMPLETED
seasonsJson.forEach { season ->
val seasonName = if (seasonsJson.size == 1) "" else "Season $seasonNumber"
val episodesJson = season.jsonObject["episodes"]!!.jsonObject[language]?.jsonArray?.reversed() ?: return@forEach
episodesJson.forEach {
val episodeTitle = it.jsonObject["metadata"]!!
.jsonObject["title"]!!
.toString()
.drop(1).dropLast(1)
val epNum = it.jsonObject["metadata"]!!
.jsonObject["number"]!!
.toString().drop(1)
.dropLast(1).toInt()
val episodeName = if (isAnimeCompleted && seasonsJson.size == 1 && episodesJson.size == 1) {
"Movie"
} else if (episodeTitle.isNotEmpty()) {
"$seasonName Ep $epNum - $episodeTitle"
} else {
"$seasonName - Episode $epNum"
}
val episode = SEpisode.create().apply {
name = episodeName
episode_number = episodeNumber
setUrlWithoutDomain(url = "$baseUrl/wp-json/kiranime/v1/episode?id=${it.jsonObject["id"]}")
date_upload = it.jsonObject["metadata"]
?.jsonObject?.get("released")?.toString()
?.drop(1)?.dropLast(1)
?.toLong()?.times(1000) ?: 0L
}
episodeNumber += 1
episodeList.add(episode)
}
seasonNumber += 1
}
return episodeList.reversed()
}
// ============================ Video Links =============================
override fun videoFromElement(element: Element): Video = throw Exception("not used")
override fun videoUrlParse(document: Document) = throw Exception("not used")
override fun videoListSelector() = throw Exception("not used")
override fun videoListParse(response: Response): List<Video> {
val document = response.asJsoup()
val videoList = mutableListOf<Video>()
val playersIndex = document.html().lastIndexOf("players")
val documentTrimmed = document.html().substring(playersIndex)
.substringAfter("players\":")
.substringBefore(",\"noplayer\":")
.trim()
val playerJson = json.decodeFromString<JsonArray>(documentTrimmed)
val filterStreams = playerJson.filter {
it.jsonObject["type"].toString()
.drop(1).dropLast(1)
.compareTo("stream") == 0
}
val filterLanguages = filterStreams.filter {
it.jsonObject["language"].toString()
.drop(1).dropLast(1)
.compareTo(language) == 0
}
// Abyss - Server does not work
val abyssStreams = filterLanguages.filter {
it.jsonObject["server"].toString()
.drop(1).dropLast(1)
.compareTo("Abyss") == 0
}
// MyStream
filterLanguages.filter {
it.jsonObject["server"].toString()
.drop(1).dropLast(1)
.compareTo("Mystream") == 0
}.forEach {
val url = it.jsonObject["url"].toString().drop(1).dropLast(1)
val videos = MyStreamExtractor().videosFromUrl(url, headers)
videoList.addAll(videos)
}
// StreamSB
filterLanguages.filter {
it.jsonObject["server"].toString()
.drop(1).dropLast(1)
.compareTo("Streamsb") == 0
}.forEach {
val url = "https://cloudemb.com/e/${it.jsonObject["url"].toString()
.drop(1).dropLast(1)
.substringAfter("id=")}.html"
val videos = StreamSBExtractor(client).videosFromUrl(url, headers)
videoList.addAll(videos)
}
return videoList
}
override fun List<Video>.sort(): List<Video> {
val quality = preferences.getString("preferred_quality", "1080")!!
val server = preferences.getString("preferred_server", "MyStream")!!
return sortedWith(
compareBy(
{ it.quality.lowercase().contains(quality.lowercase()) },
{ it.quality.lowercase().contains(server.lowercase()) },
),
).reversed()
}
// ============================ Preferences =============================
override fun setupPreferenceScreen(screen: PreferenceScreen) {
ListPreference(screen.context).apply {
key = "preferred_quality"
title = "Preferred quality"
entries = arrayOf("1080p", "720p", "480p", "360p", "240p")
entryValues = arrayOf("1080", "720", "480", "360", "240")
setDefaultValue("1080")
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
ListPreference(screen.context).apply {
key = "preferred_server"
title = "Preferred server"
entries = arrayOf("MyStream", "StreamSB")
entryValues = arrayOf("MyStream", "StreamSB")
setDefaultValue("MyStream")
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
}
}
| 0 | Kotlin | 0 | 0 | 346a01160edf993fbaa857b84152ec4ec259d4ba | 11,906 | aniyomi-extensions | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.