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/org/dclm/live/ui/experience/prayer/PrayerFragment.kt | Ochornma | 275,347,425 | false | null | package org.dclm.live.ui.experience.prayer
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import kotlinx.android.synthetic.main.prayer_fragment.*
import kotlinx.android.synthetic.main.testimony_fragment.*
import kotlinx.android.synthetic.main.testimony_fragment.email
import kotlinx.android.synthetic.main.testimony_fragment.name
import kotlinx.android.synthetic.main.testimony_fragment.subject
import kotlinx.android.synthetic.main.testimony_fragment.submit_testimony
import kotlinx.android.synthetic.main.testimony_fragment.your_testimony
import org.dclm.live.R
import org.dclm.live.ui.util.PrayerSubmitted
class PrayerFragment : Fragment(), PrayerSubmitted {
companion object {
fun newInstance() = PrayerFragment()
}
private lateinit var viewModel: PrayerViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.prayer_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val factory = context?.let { PrayerFactory(this, it) }
viewModel = factory?.let { ViewModelProvider(this, it).get(PrayerViewModel::class.java) }!!
submit_testimony.setOnClickListener {
viewModel.postPrayer(name.text.toString(), email.text.toString(), subject.text.toString(), your_testimony.text.toString())
name.setText("")
email.setText("")
subject.setText("")
your_testimony.setText("")
}
}
override fun submitted() {
Toast.makeText(context, activity?.resources?.getString(R.string.prayer_submit), Toast.LENGTH_LONG).show()
}
override fun errorInSubmit() {
Toast.makeText(context, activity?.resources?.getString(R.string.error), Toast.LENGTH_LONG).show()
}
} | 0 | Kotlin | 1 | 1 | 2715e65c7c96587f0365c870b5fa6c8120d00f82 | 2,105 | DCLM-Project | MIT License |
app/src/main/java/com/naeem/merasangeet/adapter/PlaylistViewAdapter.kt | naeem-manyar | 640,937,185 | false | null | package com.naeem.merasangeet.adapter
import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.naeem.merasangeet.R
import com.naeem.merasangeet.activity.PlaylistDetails
import com.naeem.merasangeet.databinding.PlaylistViewBinding
import com.naeem.merasangeet.fragment.PlaylistsFragment
class PlaylistViewAdapter (private val context: Context, private var playlistList:ArrayList<Playlist>): RecyclerView.Adapter<PlaylistViewAdapter.PlaylistViewHolder>() {
inner class PlaylistViewHolder(binding: PlaylistViewBinding): RecyclerView.ViewHolder(binding.root){
val image = binding.imgPlaylist
val name = binding.tvPlaylistName
val root = binding.root
val delete = binding.btnPlaylistDelete
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaylistViewHolder {
return PlaylistViewHolder(
PlaylistViewBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun getItemCount(): Int {
return playlistList.size
}
override fun onBindViewHolder(holder: PlaylistViewHolder, position: Int) {
holder.name.text = playlistList[position].name
holder.name.isSelected = true
holder.delete.setOnClickListener {
val builder = MaterialAlertDialogBuilder(context)
builder.setTitle(playlistList[position].name)
.setMessage("Do you want to delete playlist?")
.setPositiveButton("Yes") { dialog: DialogInterface, i: Int ->
PlaylistsFragment.musicPlaylist.ref.removeAt(position)
refreshPlaylist()
dialog.dismiss()
}
.setNegativeButton("No") { dialog: DialogInterface, i: Int -> dialog.dismiss() }
val customDialog = builder.create()
customDialog.show()
}
holder.root.setOnClickListener {
val intent = Intent(context, PlaylistDetails::class.java)
intent.putExtra("index",position)
ContextCompat.startActivity(context,intent,null)
}
if (PlaylistsFragment.musicPlaylist.ref[position].playlist.size > 0)
{
Glide.with(context)
.load(PlaylistsFragment.musicPlaylist.ref[position].playlist[0].artUri)
.apply(RequestOptions().placeholder(R.drawable.splash_screen).centerCrop())
.into(holder.image)
}
}
@SuppressLint("NotifyDataSetChanged")
fun refreshPlaylist(){
playlistList = ArrayList()
playlistList.addAll(PlaylistsFragment.musicPlaylist.ref)
notifyDataSetChanged()
}
} | 0 | Kotlin | 0 | 0 | 93783989442e76348b862e8e704bdc4e95bf9698 | 3,125 | Mera-Sangeet | MIT License |
kotlin-springwebmvc/src/test/kotlin/com/gyejoon/springwebmvc/blog/HttpApiTests.kt | Gyejoon | 141,891,522 | false | null | package blog
import com.nhaarman.mockito_kotlin.whenever
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.Mockito.any
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
@ExtendWith(SpringExtension::class)
@WebMvcTest
class HttpApiTests(@Autowired val mockMvc: MockMvc) {
@MockBean
private lateinit var userRepository: UserRepository
@MockBean
private lateinit var articleRepository: ArticleRepository
@MockBean
private lateinit var markdownConverter: MarkdownConverter
@Test
fun `List articles`() {
val juergen = User("springjuergen", "Juergen", "Hoeller")
val spring5Article = Article("Spring Framework 5.0 goes GA", "Dear Spring community ...", "Lorem ipsum", juergen, 1)
val spring43Article = Article("Spring Framework 4.3 goes GA", "Dear Spring community ...", "Lorem ipsum", juergen, 2)
whenever(articleRepository.findAllByOrderByAddedAtDesc()).thenReturn(listOf(spring5Article, spring43Article))
whenever(markdownConverter(any())).thenAnswer { it.arguments[0] }
mockMvc.perform(get("/api/article/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk)
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("\$.[0].author.login").value(juergen.login))
.andExpect(jsonPath("\$.[0].id").value(spring5Article.id!!))
.andExpect(jsonPath("\$.[1].author.login").value(juergen.login))
.andExpect(jsonPath("\$.[1].id").value(spring43Article.id!!))
}
@Test
fun `List users`() {
val juergen = User("springjuergen", "Juergen", "Hoeller")
val smaldini = User("smaldini", "Stéphane", "Maldini")
whenever(userRepository.findAll()).thenReturn(listOf(juergen, smaldini))
mockMvc.perform(get("/api/user/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk)
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("\$.[0].login").value(juergen.login))
.andExpect(jsonPath("\$.[1].login").value(smaldini.login))
}
} | 0 | Kotlin | 0 | 2 | 2118ea4ccfb857434cc5b22009e58a6126d2c6d9 | 2,855 | kotlin-examples | MIT License |
src/main/kotlin/no/nav/personbruker/minesaker/api/domain/Datotype.kt | navikt | 331,032,645 | false | null | package no.nav.personbruker.minesaker.api.domain
enum class Datotype {
OPPRETTET,
REGISTRERT,
EKSPEDERT,
AV_RETUR,
DOKUMENT,
JOURNALFORT,
SENDT_PRINT,
UKJENT
}
| 1 | Kotlin | 1 | 0 | 9483405e40b286e7b537a699ca3cf4eaca40ed0e | 193 | mine-saker-api | MIT License |
app/src/main/java/es/voghdev/playbattlegrounds/features/season/usecase/SetCurrentSeason.kt | voghDev | 125,352,944 | false | null | /*
* Copyright (C) 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 es.voghdev.playbattlegrounds.features.season.usecase
import es.voghdev.playbattlegrounds.features.season.Season
interface SetCurrentSeason {
fun setCurrentSeason(season: Season)
} | 5 | Kotlin | 2 | 10 | 860788cebfa6d0563e8c4de9611c0daeca492a1b | 784 | PlayBattlegrounds | Apache License 2.0 |
projectgraphmetrics/src/test/kotlin/io/github/cdsap/projectgraphmetrics/parser/GraphIndicatorsParserTest.kt | cdsap | 725,238,050 | false | {"Kotlin": 11798} | package io.github.cdsap.projectgraphmetrics.parser
import io.github.cdsap.projectgraphmetrics.ProjectGraphMetrics
import io.github.cdsap.projectgraphmetrics.parser.GraphParser
import org.junit.Assert.*
import org.junit.Test
import java.io.File
class GraphIndicatorsParserTest {
@Test
fun testModulesAreParsedCorrectly() {
val file = File(this::class.java.classLoader!!.getResource("graph.dot")?.path)
val graph = ProjectGraphMetrics(file)
val graphIndicatorsParser = graph.getMetrics()
assertTrue(graphIndicatorsParser.containsKey(":layer_1:module_1_54"))
assertTrue(graphIndicatorsParser.containsKey(":layer_2:module_2_85"))
assertTrue(graphIndicatorsParser.containsKey(":layer_3:module_3_102"))
assertTrue(graphIndicatorsParser.containsKey(":layer_4:module_4_115"))
assertTrue(graphIndicatorsParser.containsKey(":layer_5:module_5_121"))
}
@Test
fun testMetricsByModuleAreParsedCorrectly() {
val file = File(this::class.java.classLoader!!.getResource("graph.dot")?.path)
val graph = ProjectGraphMetrics(file)
val graphIndicatorsParser = graph.getMetrics()
assertEquals(1, graphIndicatorsParser[":layer_1:module_1_54"]?.height)
assertEquals(4, graphIndicatorsParser[":layer_1:module_1_54"]?.outdegree)
assertEquals(10, graphIndicatorsParser[":layer_1:module_1_54"]?.indegree)
assertEquals(14.44, graphIndicatorsParser[":layer_1:module_1_54"]?.betweennessCentrality)
}
}
| 0 | Kotlin | 0 | 5 | b54094c23d3a53bc0208f405a1705f7cc812f735 | 1,518 | ProjectGraphMetrics | MIT License |
features/feature-settings/src/main/kotlin/com/maximillianleonov/musicmax/feature/settings/SettingsScreen.kt | MaximillianLeonov | 559,137,206 | false | null | /*
* Copyright 2022 Maximillian Leonov
*
* 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.maximillianleonov.musicmax.feature.settings
import android.net.Uri
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import com.maximillianleonov.musicmax.core.designsystem.icon.MusicmaxIcons
import com.maximillianleonov.musicmax.core.designsystem.theme.spacing
import com.maximillianleonov.musicmax.feature.settings.component.Group
import com.maximillianleonov.musicmax.feature.settings.component.InfoText
import com.maximillianleonov.musicmax.feature.settings.component.UrlText
@Composable
internal fun SettingsRoute(
modifier: Modifier = Modifier,
viewModel: SettingsViewModel = hiltViewModel()
) {
SettingsScreen(
repoUrl = viewModel.repoUrl,
privacyPolicyUrl = viewModel.privacyPolicyUrl,
version = viewModel.version,
modifier = modifier
)
}
@Composable
fun SettingsScreen(
repoUrl: Uri,
privacyPolicyUrl: Uri,
version: String,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.smallMedium)
) {
Group(titleResource = R.string.about) {
UrlText(
icon = MusicmaxIcons.GitHub,
textResource = R.string.source_code_github,
url = repoUrl
)
UrlText(
icon = MusicmaxIcons.Security,
textResource = R.string.privacy_policy,
url = privacyPolicyUrl
)
InfoText(
icon = MusicmaxIcons.Info,
textResource = R.string.version,
info = version
)
}
}
}
| 5 | Kotlin | 4 | 61 | 29dd1c65e202aae78d6565c6490e3019d921fb23 | 2,655 | Musicmax | Apache License 2.0 |
platform/statistics/uploader/src/com/intellij/internal/statistic/eventLog/LogEvents.kt | hieuprogrammer | 284,920,751 | false | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.eventLog
import com.intellij.internal.statistic.eventLog.StatisticsEventEscaper.escapeFieldName
import java.util.*
fun newLogEvent(session: String,
build: String,
bucket: String,
time: Long,
groupId: String,
groupVersion: String,
recorderVersion: String,
event: LogEventAction): LogEvent {
return LogEvent(session, build, bucket, time, groupId, groupVersion, recorderVersion, event)
}
fun newLogEvent(session: String,
build: String,
bucket: String,
time: Long,
groupId: String,
groupVersion: String,
recorderVersion: String,
eventId: String,
isState: Boolean = false): LogEvent {
val event = LogEventAction(StatisticsEventEscaper.escapeEventIdOrFieldValue(eventId), isState, 1)
return LogEvent(session, build, bucket, time, groupId, groupVersion, recorderVersion, event)
}
open class LogEvent(session: String,
build: String,
bucket: String,
eventTime: Long,
groupId: String,
groupVersion: String,
recorderVersion: String,
eventAction: LogEventAction) {
val recorderVersion: String = StatisticsEventEscaper.escape(recorderVersion)
val session: String = StatisticsEventEscaper.escape(session)
val build: String = StatisticsEventEscaper.escape(build)
val bucket: String = StatisticsEventEscaper.escape(bucket)
val time: Long = eventTime
val group: LogEventGroup = LogEventGroup(StatisticsEventEscaper.escape(groupId), StatisticsEventEscaper.escape(groupVersion))
val event: LogEventAction = eventAction
fun shouldMerge(next: LogEvent): Boolean {
if (session != next.session) return false
if (bucket != next.bucket) return false
if (build != next.build) return false
if (recorderVersion != next.recorderVersion) return false
if (group.id != next.group.id) return false
if (group.version != next.group.version) return false
if (!event.shouldMerge(next.event)) return false
return true
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEvent
if (session != other.session) return false
if (bucket != other.bucket) return false
if (build != other.build) return false
if (time != other.time) return false
if (group != other.group) return false
if (recorderVersion != other.recorderVersion) return false
if (event != other.event) return false
return true
}
override fun hashCode(): Int {
var result = session.hashCode()
result = 31 * result + bucket.hashCode()
result = 31 * result + build.hashCode()
result = 31 * result + time.hashCode()
result = 31 * result + group.hashCode()
result = 31 * result + recorderVersion.hashCode()
result = 31 * result + event.hashCode()
return result
}
}
class LogEventGroup(val id: String, val version: String) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventGroup
if (id != other.id) return false
if (version != other.version) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + version.hashCode()
return result
}
}
class LogEventAction(val id: String, var state: Boolean = false, var count: Int = 1) {
var data: MutableMap<String, Any> = Collections.emptyMap()
fun increment() {
count++
}
fun isEventGroup(): Boolean {
return count > 1
}
fun shouldMerge(next: LogEventAction): Boolean {
if (state || next.state) return false
if (id != next.id) return false
if (data != next.data) return false
return true
}
fun addData(key: String, value: Any) {
if (data.isEmpty()) {
data = HashMap()
}
data[escapeFieldName(key)] = escapeValue(value)
}
private fun escapeValue(value: Any): Any {
return when (value) {
is String -> StatisticsEventEscaper.escapeEventIdOrFieldValue(value)
is List<*> -> value.map { if (it != null) escapeValue(it) else it }
is Map<*, *> -> {
value.entries.associate { (entryKey, entryValue) ->
val newKey = if (entryKey is String) escapeFieldName(entryKey) else entryKey
val newValue = if (entryValue != null) escapeValue(entryValue) else entryValue
newKey to newValue
}
}
else -> value
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventAction
if (id != other.id) return false
if (count != other.count) return false
if (data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + count
result = 31 * result + data.hashCode()
return result
}
}
| 1 | null | 1 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 5,362 | intellij-community | Apache License 2.0 |
ospf-kotlin-core/src/main/fuookami/ospf/kotlin/core/frontend/expression/symbol/linear_function/SatisfiedAmountInequality.kt | fuookami | 359,831,793 | false | {"Kotlin": 2440181, "Python": 6629} | package fuookami.ospf.kotlin.core.frontend.expression.symbol.linear_function
import org.apache.logging.log4j.kotlin.*
import fuookami.ospf.kotlin.utils.math.*
import fuookami.ospf.kotlin.utils.functional.*
import fuookami.ospf.kotlin.utils.multi_array.*
import fuookami.ospf.kotlin.core.frontend.variable.*
import fuookami.ospf.kotlin.core.frontend.expression.monomial.*
import fuookami.ospf.kotlin.core.frontend.expression.polynomial.*
import fuookami.ospf.kotlin.core.frontend.expression.symbol.*
import fuookami.ospf.kotlin.core.frontend.inequality.*
import fuookami.ospf.kotlin.core.frontend.model.mechanism.*
sealed class AbstractSatisfiedAmountInequalityFunction(
inequalities: List<LinearInequality>,
private val constraint: Boolean = false,
override var name: String,
override var displayName: String? = null
) : LinearFunctionSymbol {
private val logger = logger()
open val amount: ValueRange<UInt64>? = null
protected val inequalities by lazy {
inequalities.map { it.normalize() }
}
private val u: BinVariable1 by lazy {
BinVariable1("${name}_u", Shape1(inequalities.size))
}
private val y: BinVar by lazy {
BinVar("${name}_y")
}
private val polyY: AbstractLinearPolynomial<*> by lazy {
if (amount != null) {
if (!constraint) {
val polyY = LinearPolynomial(y)
polyY.range.set(possibleRange)
polyY
} else {
LinearPolynomial(1)
}
} else {
val polyY = sum(u)
polyY.range.set(possibleRange)
polyY
}
}
override val discrete = true
override val range get() = polyY.range
override val lowerBound get() = polyY.lowerBound
override val upperBound get() = polyY.upperBound
override val category: Category = Linear
override val dependencies: Set<Symbol>
get() {
val dependencies = HashSet<Symbol>()
for (inequality in inequalities) {
dependencies.addAll(inequality.lhs.dependencies)
dependencies.addAll(inequality.rhs.dependencies)
}
return dependencies
}
override val cells get() = polyY.cells
override val cached get() = polyY.cached
private val possibleRange: ValueRange<Flt64>
get() {
// todo: impl by Inequality.judge()
return if (amount != null) {
ValueRange(Flt64.zero, Flt64.one)
} else {
ValueRange(Flt64.zero, Flt64(inequalities.size))
}
}
override fun flush(force: Boolean) {
for (inequality in inequalities) {
inequality.flush(force)
}
polyY.flush(force)
polyY.range.set(possibleRange)
}
override suspend fun prepare(tokenTable: AbstractTokenTable) {
for (inequality in inequalities) {
inequality.lhs.cells
inequality.rhs.cells
}
if (tokenTable.cachedSolution && tokenTable.cached(this) == false) {
val count = inequalities.count { (it.isTrue(tokenTable) ?: return) }
val yValue = if (amount != null) {
if (!constraint) {
val bin = amount!!.contains(UInt64(count))
val yValue = if (bin) {
Flt64.one
} else {
Flt64.zero
}
logger.trace { "Setting SatisfiedAmountInequalityFunction ${name}.y to $bin" }
tokenTable.find(y)?.let { token ->
token._result = yValue
}
yValue
} else {
Flt64.one
}
} else {
Flt64(count)
}
when (tokenTable) {
is TokenTable -> {
tokenTable.cachedSymbolValue[this to null] = yValue
}
is MutableTokenTable -> {
tokenTable.cachedSymbolValue[this to null] = yValue
}
}
}
}
override fun register(tokenTable: MutableTokenTable): Try {
when (val result = tokenTable.add(u)) {
is Ok -> {}
is Failed -> {
return Failed(result.error)
}
}
if (amount != null && !constraint) {
when (val result = tokenTable.add(y)) {
is Ok -> {}
is Failed -> {
return Failed(result.error)
}
}
}
return ok
}
override fun register(model: AbstractLinearMechanismModel): Try {
for ((i, inequality) in inequalities.withIndex()) {
when (val result = inequality.register(name, u[i], model)) {
is Ok -> {}
is Failed -> {
return Failed(result.error)
}
}
}
if (amount != null) {
if (!constraint) {
when (val result = model.addConstraint(
sum(u) geq amount!!.lowerBound.toFlt64() - UInt64(inequalities.size) * (Flt64.one - y),
"${name}_lb"
)) {
is Ok -> {}
is Failed -> {
return Failed(result.error)
}
}
when (val result = model.addConstraint(
sum(u) leq amount!!.upperBound.toFlt64() + UInt64(inequalities.size) * (Flt64.one - y),
"${name}_ub"
)) {
is Ok -> {}
is Failed -> {
return Failed(result.error)
}
}
} else {
when (val result = model.addConstraint(
sum(u) geq amount!!.lowerBound.toFlt64(),
"${name}_lb"
)) {
is Ok -> {}
is Failed -> {
return Failed(result.error)
}
}
when (val result = model.addConstraint(
sum(u) leq amount!!.upperBound.toFlt64(),
"${name}_ub"
)) {
is Ok -> {}
is Failed -> {
return Failed(result.error)
}
}
}
}
return ok
}
override fun toString(): String {
return displayName ?: name
}
override fun toRawString(unfold: Boolean): String {
return if (amount != null) {
"satisfied_amount_${amount}(${inequalities.joinToString(", ") { it.toRawString(unfold) }})"
} else {
"satisfied_amount(${inequalities.joinToString(", ") { it.toRawString(unfold) }})"
}
}
override fun value(tokenList: AbstractTokenList, zeroIfNone: Boolean): Flt64? {
var counter = UInt64.zero
for (inequality in inequalities) {
if (inequality.isTrue(tokenList, zeroIfNone) ?: return null) {
counter += UInt64.one
}
}
return if (amount != null) {
if (amount!!.contains(counter)) {
Flt64.one
} else {
Flt64.zero
}
} else {
counter.toFlt64()
}
}
override fun value(results: List<Flt64>, tokenList: AbstractTokenList, zeroIfNone: Boolean): Flt64? {
var counter = UInt64.zero
for (inequality in inequalities) {
if (inequality.isTrue(results, tokenList, zeroIfNone) ?: return null) {
counter += UInt64.one
}
}
return if (amount != null) {
if (amount!!.contains(counter)) {
Flt64.one
} else {
Flt64.zero
}
} else {
counter.toFlt64()
}
}
override fun calculateValue(tokenTable: AbstractTokenTable, zeroIfNone: Boolean): Flt64? {
var counter = UInt64.zero
for (inequality in inequalities) {
if (inequality.isTrue(tokenTable, zeroIfNone) ?: return null) {
counter += UInt64.one
}
}
return if (amount != null) {
if (amount!!.contains(counter)) {
Flt64.one
} else {
Flt64.zero
}
} else {
counter.toFlt64()
}
}
override fun calculateValue(results: List<Flt64>, tokenTable: AbstractTokenTable, zeroIfNone: Boolean): Flt64? {
var counter = UInt64.zero
for (inequality in inequalities) {
if (inequality.isTrue(results, tokenTable, zeroIfNone) ?: return null) {
counter += UInt64.one
}
}
return if (amount != null) {
if (amount!!.contains(counter)) {
Flt64.one
} else {
Flt64.zero
}
} else {
counter.toFlt64()
}
}
}
// todo: optimize
open class AnyFunction(
inequalities: List<LinearInequality>,
name: String,
displayName: String? = null
) : AbstractSatisfiedAmountInequalityFunction(inequalities, name = name, displayName = displayName),
LinearLogicFunctionSymbol {
override val amount: ValueRange<UInt64> = ValueRange(UInt64.one, UInt64(inequalities.size))
override fun toRawString(unfold: Boolean): String {
return "any(${inequalities.joinToString(", ") { it.toRawString(unfold) }})"
}
}
class InListFunction(
val x: AbstractLinearPolynomial<*>,
val list: List<AbstractLinearPolynomial<*>>,
name: String,
displayName: String? = null
) : AnyFunction(list.map { x eq it }, name, displayName)
class NotAllFunction(
inequalities: List<LinearInequality>,
name: String,
displayName: String? = null
) : AbstractSatisfiedAmountInequalityFunction(inequalities, name = name, displayName = displayName),
LinearLogicFunctionSymbol {
override val amount: ValueRange<UInt64> = ValueRange(UInt64.one, UInt64(inequalities.size - 1))
override fun toRawString(unfold: Boolean): String {
return "for_all(${inequalities.joinToString(", ") { it.toRawString(unfold) }})"
}
}
// todo: optimize
class AllFunction(
inequalities: List<LinearInequality>,
name: String,
displayName: String? = null
) : AbstractSatisfiedAmountInequalityFunction(inequalities, name = name, displayName = displayName),
LinearLogicFunctionSymbol {
override val amount: ValueRange<UInt64> = ValueRange(UInt64(inequalities.size), UInt64(inequalities.size))
override fun toRawString(unfold: Boolean): String {
return "for_all(${inequalities.joinToString(", ") { it.toRawString(unfold) }})"
}
}
class SatisfiedAmountInequalityFunction(
inequalities: List<LinearInequality>,
name: String,
displayName: String? = null
) : AbstractSatisfiedAmountInequalityFunction(inequalities, name = name, displayName = displayName)
class AtLeastInequalityFunction(
inequalities: List<LinearInequality>,
constraint: Boolean = true,
amount: UInt64,
name: String,
displayName: String? = null
) : AbstractSatisfiedAmountInequalityFunction(inequalities, constraint, name, displayName), LinearLogicFunctionSymbol {
init {
assert(amount != UInt64.zero)
assert(UInt64(inequalities.size) geq amount)
}
override val amount: ValueRange<UInt64> = ValueRange(amount, UInt64(inequalities.size))
override fun toRawString(unfold: Boolean): String {
return "at_least_${amount}(${inequalities.joinToString(", ") { it.toRawString(unfold) }})"
}
}
class NumerableFunction(
inequalities: List<LinearInequality>,
override val amount: ValueRange<UInt64>,
constraint: Boolean = true,
name: String,
displayName: String? = null
) : AbstractSatisfiedAmountInequalityFunction(inequalities, constraint, name, displayName), LinearLogicFunctionSymbol {
override fun toRawString(unfold: Boolean): String {
return "numerable_${amount}(${inequalities.joinToString(", ") { it.toRawString(unfold) }})"
}
}
| 0 | Kotlin | 0 | 4 | b34cda509b31884e6a15d77f00a6134d001868de | 12,372 | ospf-kotlin | Apache License 2.0 |
app/src/main/java/com/example/android/marsphotos/network/MarsApiService.kt | kbhh | 511,225,618 | false | {"Kotlin": 9860} | package com.example.android.marsphotos
import com.example.android.marsphotos.network.MarsPhoto
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
private val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
private val BASE_URL = "https://android-kotlin-fun-mars-server.appspot.com"
private val retrofit =
Retrofit.Builder().addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build();
interface MarsApiService {
@GET("photos")
suspend fun getPhotos() : List<MarsPhoto>
}
object MarsApi {
val retrofitService : MarsApiService by lazy {
retrofit.create(MarsApiService::class.java)
}
}
| 0 | Kotlin | 0 | 0 | 0f6437aa87e61bcdf8ebd806b71a3bc75e0a98e6 | 820 | MarsPhotos | Apache License 2.0 |
app/src/main/java/com/lighttigerxiv/simple/mp/compose/backend/realm/collections/Album.kt | jpbandroid | 733,977,750 | false | {"Kotlin": 458602} | package com.jpb.music.compose.backend.realm.collections
import io.realm.kotlin.types.RealmObject
import io.realm.kotlin.types.annotations.PrimaryKey
class Album: RealmObject {
@PrimaryKey var id: Long = 0L
var artistId: Long = 0L
var name: String = ""
} | 0 | Kotlin | 0 | 0 | e53569c3ebe0cba05a70519805ffb6c97137fe1e | 267 | jpbMusic-Compose | MIT License |
src/main/kotlin/org/misarch/shipment/persistence/repository/ShipmentMethodRepository.kt | MiSArch | 761,247,429 | false | {"Kotlin": 103125, "Shell": 748, "Dockerfile": 219} | package org.misarch.shipment.persistence.repository
import com.infobip.spring.data.r2dbc.QuerydslR2dbcRepository
import org.misarch.shipment.persistence.model.ShipmentMethodEntity
import org.springframework.stereotype.Repository
import java.util.*
/**
* Repository for [ShipmentMethodEntity]s
*/
@Repository
interface ShipmentMethodRepository : QuerydslR2dbcRepository<ShipmentMethodEntity, UUID> | 0 | Kotlin | 0 | 0 | 634bf9623e868f1822a6b8e79bf3372993c654b7 | 400 | shipment | MIT License |
shared/core/src/main/java/com/sadri/core/domain/executor/DispatcherProviderImpl.kt | sepehrsadri | 577,511,564 | false | {"Kotlin": 57847} | package com.sadri.core.domain.executor
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
class DispatcherProviderImpl : DispatcherProvider {
override val ui: CoroutineDispatcher
get() = Dispatchers.Main
override val io: CoroutineDispatcher
get() = Dispatchers.IO
override val default: CoroutineDispatcher
get() = Dispatchers.Default
} | 0 | Kotlin | 0 | 0 | 2ee26111d7ff892d2f1d23c182894245cb7e8258 | 388 | KittenAppComposeUI | Apache License 2.0 |
mobile/src/main/java/com/github/ssa/plugin/NoPlugin.kt | FakeTrader | 76,080,289 | true | {"Kotlin": 603376, "C": 39979, "Makefile": 16869, "C++": 5312, "Batchfile": 3611, "Shell": 3486, "Python": 3428, "Java": 2916, "HTML": 2874, "Perl": 280, "Dockerfile": 212} | package com.github.ssa.plugin
import com.github.ssa.App.Companion.app
object NoPlugin : Plugin() {
override val id: String get() = ""
override val label: CharSequence get() = app.getText(com.github.ssa.R.string.plugin_disabled)
}
| 0 | Kotlin | 0 | 0 | 3559e6b101546750e18d1e79beb5e4933b7cd3d7 | 240 | shadowsocks-android | ISC License |
app/src/main/java/openfoodfacts/github/scrachx/openfood/models/Nutriment.kt | openfoodfacts | 35,174,991 | false | null | package openfoodfacts.rackluxury.scrachx.openfood.models
import openfoodfacts.rackluxury.scrachx.openfood.R
import openfoodfacts.rackluxury.scrachx.openfood.models.Nutriment.*
enum class Nutriment(val key: String) {
ENERGY_KCAL("energy-kcal"),
ENERGY_KJ("energy-kj"),
ENERGY_FROM_FAT("energy-from-fat"),
FAT("fat"),
SATURATED_FAT("saturated-fat"),
BUTYRIC_ACID("butyric-acid"),
CAPROIC_ACID("caproic-acid"),
CAPRYLIC_ACID("caprylic-acid"),
CAPRIC_ACID("capric-acid"),
LAURIC_ACID("lauric-acid"),
MYRISTIC_ACID("myristic-acid"),
PALMITIC_ACID("palmitic-acid"),
STEARIC_ACID("stearic-acid"),
ARACHIDIC_ACID("arachidic-acid"),
BEHENIC_ACID("behenic-acid"),
LIGNOCERIC_ACID("lignoceric-acid"),
CEROTIC_ACID("cerotic-acid"),
MONTANIC_ACID("montanic-acid"),
MELISSIC_ACID("melissic-acid"),
MONOUNSATURATED_FAT("monounsaturated-fat"),
POLYUNSATURATED_FAT("polyunsaturated-fat"),
OMEGA_3_FAT("omega-3-fat"),
ALPHA_LINOLENIC_ACID("alpha-linolenic-acid"),
EICOSAPENTAENOIC_ACID("eicosapentaenoic-acid"),
DOCOSAHEXAENOIC_ACID("docosahexaenoic-acid"),
OMEGA_6_FAT("omega-6-fat"),
LINOLEIC_ACID("linoleic-acid"),
ARACHIDONIC_ACID("arachidonic-acid"),
GAMMA_LINOLENIC_ACID("gamma-linolenic-acid"),
DIHOMO_GAMMA_LINOLENIC_ACID("dihomo-gamma-linolenic-acid"),
OMEGA_9_FAT("omega-9-fat"),
OLEIC_ACID("oleic-acid"),
ELAIDIC_ACID("elaidic-acid"),
GONDOIC_ACID("gondoic-acid"),
MEAD_ACID("mead-acid"),
ERUCIC_ACID("erucic-acid"),
NERVONIC_ACID("nervonic-acid"),
TRANS_FAT("trans-fat"),
CHOLESTEROL("cholesterol"),
CARBOHYDRATES("carbohydrates"),
SUGARS("sugars"),
SUCROSE("sucrose"),
GLUCOSE("glucose"),
FRUCTOSE("fructose"),
LACTOSE("lactose"),
MALTOSE("maltose"),
MALTODEXTRINS("maltodextrins"),
STARCH("starch"),
POLYOLS("polyols"),
FIBER("fiber"),
PROTEINS("proteins"),
CASEIN("casein"),
SERUM_PROTEINS("serum-proteins"),
NUCLEOTIDES("nucleotides"),
SALT("salt"),
SODIUM("sodium"),
ALCOHOL("alcohol"),
VITAMIN_A("vitamin-a"),
BETA_CAROTENE("beta-carotene"),
VITAMIN_D("vitamin-d"),
VITAMIN_E("vitamin-e"),
VITAMIN_K("vitamin-k"),
VITAMIN_C("vitamin-c"),
VITAMIN_B1("vitamin-b1"),
VITAMIN_B2("vitamin-b2"),
VITAMIN_PP("vitamin-pp"),
VITAMIN_B6("vitamin-b6"),
VITAMIN_B9("vitamin-b9"),
WATER_HARDNESS("water-hardness"),
GLYCEMIC_INDEX("glycemic-index"),
NUTRITION_SCORE_UK("nutrition-score-uk"),
NUTRITION_SCORE_FR("nutrition-score-fr"),
CARBON_FOOTPRINT("carbon-footprint"),
CHLOROPHYL("chlorophyl"),
COCOA("cocoa"),
COLLAGEN_MEAT_PROTEIN_RATIO("collagen-meat-protein-ratio"),
FRUITS_VEGETABLES_NUTS("fruits-vegetables-nuts"),
PH("ph"),
TAURINE("taurine"),
CAFFEINE("caffeine"),
IODINE("iodine"),
MOLYBDENUM("molybdenum"),
CHROMIUM("chromium"),
SELENIUM("selenium"),
FLUORIDE("fluoride"),
MANGANESE("manganese"),
COPPER("copper"),
ZINC("zinc"),
VITAMIN_B12("vitamin-b12"),
BIOTIN("biotin"),
PANTOTHENIC_ACID("pantothenic-acid"),
SILICA("silica"),
BICARBONATE("bicarbonate"),
POTASSIUM("potassium"),
CHLORIDE("chloride"),
CALCIUM("calcium"),
PHOSPHORUS("phosphorus"),
IRON("iron"),
MAGNESIUM("magnesium");
companion object {
fun findbyKey(key: String) = values().find { it.key == key }
fun requireByKey(key: String) = findbyKey(key) ?: throw IllegalArgumentException("Cannot find nutriment with key '$key'")
}
}
val MINERALS_MAP = mapOf(
SILICA to R.string.silica,
BICARBONATE to R.string.bicarbonate,
POTASSIUM to R.string.potassium,
CHLORIDE to R.string.chloride,
CALCIUM to R.string.calcium,
CALCIUM to R.string.calcium,
PHOSPHORUS to R.string.phosphorus,
IRON to R.string.iron,
MAGNESIUM to R.string.magnesium,
ZINC to R.string.zinc,
COPPER to R.string.copper,
MANGANESE to R.string.manganese,
FLUORIDE to R.string.fluoride,
SELENIUM to R.string.selenium,
CHROMIUM to R.string.chromium,
MOLYBDENUM to R.string.molybdenum,
IODINE to R.string.iodine,
CAFFEINE to R.string.caffeine,
TAURINE to R.string.taurine,
PH to R.string.ph,
FRUITS_VEGETABLES_NUTS to R.string.fruits_vegetables_nuts,
COLLAGEN_MEAT_PROTEIN_RATIO to R.string.collagen_meat_protein_ratio,
COCOA to R.string.cocoa,
CHLOROPHYL to R.string.chlorophyl
)
val FAT_MAP = mapOf(
SATURATED_FAT to R.string.nutrition_satured_fat,
MONOUNSATURATED_FAT to R.string.nutrition_monounsaturatedFat,
POLYUNSATURATED_FAT to R.string.nutrition_polyunsaturatedFat,
OMEGA_3_FAT to R.string.nutrition_omega3,
OMEGA_6_FAT to R.string.nutrition_omega6,
OMEGA_9_FAT to R.string.nutrition_omega9,
TRANS_FAT to R.string.nutrition_trans_fat,
CHOLESTEROL to R.string.nutrition_cholesterol
)
val CARBO_MAP = mapOf(
SUGARS to R.string.nutrition_sugars,
SUCROSE to R.string.nutrition_sucrose,
GLUCOSE to R.string.nutrition_glucose,
FRUCTOSE to R.string.nutrition_fructose,
LACTOSE to R.string.nutrition_lactose,
MALTOSE to R.string.nutrition_maltose,
MALTODEXTRINS to R.string.nutrition_maltodextrins
)
val PROT_MAP = mapOf(
CASEIN to R.string.nutrition_casein,
SERUM_PROTEINS to R.string.nutrition_serum_proteins,
NUCLEOTIDES to R.string.nutrition_nucleotides
)
val VITAMINS_MAP = mapOf(
VITAMIN_A to R.string.vitamin_a,
BETA_CAROTENE to R.string.vitamin_a,
VITAMIN_D to R.string.vitamin_d,
VITAMIN_E to R.string.vitamin_e,
VITAMIN_K to R.string.vitamin_k,
VITAMIN_C to R.string.vitamin_c,
VITAMIN_B1 to R.string.vitamin_b1,
VITAMIN_B2 to R.string.vitamin_b2,
VITAMIN_PP to R.string.vitamin_pp,
VITAMIN_B6 to R.string.vitamin_b6,
VITAMIN_B9 to R.string.vitamin_b9,
VITAMIN_B12 to R.string.vitamin_b12,
BIOTIN to R.string.biotin,
PANTOTHENIC_ACID to R.string.pantothenic_acid
) | 390 | null | 447 | 772 | 836bab540ec9e2792b692a3b25ff61e444fae045 | 6,051 | openfoodfacts-androidapp | Apache License 2.0 |
libraries/navigation/src/nonAndroidMain/kotlin/com/hoc081098/compose_multiplatform_kmpviewmodel_sample/navigation/internal/StoreViewModel.kt | hoc081098 | 675,918,221 | false | null | /**
* Copied from [com.freeletics.khonshu.navigation.compose.internal.StoreViewModel.kt](https://github.com/freeletics/khonshu/blob/de0e8f812d89303ac347119d5c448bc40224d4f2/navigation-experimental/src/main/kotlin/com/freeletics/khonshu/navigation/compose/internal/StoreViewModel.kt).
*/
package com.hoc081098.compose_multiplatform_kmpviewmodel_sample.navigation.internal
import com.hoc081098.kmp.viewmodel.SavedStateHandle
import com.hoc081098.kmp.viewmodel.ViewModel
@InternalNavigationApi
internal class StoreViewModel(
internal val globalSavedStateHandle: SavedStateHandle,
) : ViewModel() {
init {
println("🔥 StoreViewModel init")
}
private val stores = mutableMapOf<StackEntry.Id, NavigationExecutorStore>()
private val savedStateHandles = mutableMapOf<StackEntry.Id, SavedStateHandle>()
fun provideStore(id: StackEntry.Id): NavigationExecutor.Store {
return stores.getOrPut(id) { NavigationExecutorStore() }
}
fun provideSavedStateHandle(id: StackEntry.Id): SavedStateHandle {
return savedStateHandles.getOrPut(id) { SavedStateHandle() }
}
fun removeEntry(id: StackEntry.Id) {
val store = stores.remove(id)
store?.close()
savedStateHandles.remove(id)
globalSavedStateHandle.remove<Any>(id.value)
}
public override fun onCleared() {
for (store in stores.values) {
store.close()
}
stores.clear()
for (key in savedStateHandles.keys) {
globalSavedStateHandle.remove<Any>(key.value)
}
savedStateHandles.clear()
}
}
| 12 | null | 4 | 8 | 539c189185a5c77646e020928ec3a23334722317 | 1,518 | Compose-Multiplatform-KmpViewModel-Unsplash-Sample | Apache License 2.0 |
src/main/kotlin/algorithms/sorting/QuickSort.kt | ibado | 484,821,732 | false | null | package algorithms.sorting
class QuickSort : Sort {
override fun <T : Comparable<T>> invoke(target: List<T>): List<T> {
if (target.isEmpty()) return emptyList()
val pivot = target.last()
val left = mutableListOf<T>()
val right = mutableListOf<T>()
for (i in 0 until target.size - 1) {
val current = target[i]
if (current > pivot) {
right.add(current)
} else {
left.add(current)
}
}
return invoke(left) + pivot + invoke(right)
}
} | 0 | Kotlin | 0 | 0 | ede1947912874b408697c91acd2df9b932b41ab5 | 578 | Computer-science-fundamentals | MIT License |
src/main/kotlin/com/arkivanov/composnake/DefaultGame.kt | arkivanov | 355,491,169 | false | null | package com.arkivanov.composnake
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
class DefaultGame : Game {
private val _board: MutableState<Board>
private val randomPointGenerator: RandomPointGenerator
init {
val width = 16
val height = 16
val cy = height / 2
val snake =
setOf(
Point(x = 0, y = cy),
Point(x = 1, y = cy),
Point(x = 2, y = cy),
Point(x = 3, y = cy),
Point(x = 4, y = cy)
)
val grid =
List(height) { y ->
List(width) { x ->
Point(x = x, y = y)
}
}
randomPointGenerator = RandomPointGenerator()
grid.forEach { row ->
row.forEach(randomPointGenerator::free)
}
snake.forEach(randomPointGenerator::occupy)
_board =
mutableStateOf(
Board(
snake = Snake(points = snake, head = snake.last()),
grid = grid,
cells = grid.flatten().toSet(),
direction = Direction.RIGHT,
food = randomPointGenerator.generate()
)
)
}
override val board: State<Board> = _board
override fun step() {
update {
val newSnake = snake?.step(direction = direction, food = food, cells = cells)
snake?.points?.forEach(randomPointGenerator::free)
newSnake?.points?.forEach(randomPointGenerator::occupy)
copy(
snake = newSnake,
food = when {
newSnake == null -> null
newSnake.head == food -> randomPointGenerator.generate()
else -> food
}
)
}
}
// TODO: Consider persistent collections
private fun Snake.step(direction: Direction, food: Point?, cells: Set<Point>): Snake? {
val newPoints = LinkedHashSet<Point>(points)
val newHead = points.last().step(direction)
if ((newHead in newPoints) || (newHead !in cells)) {
return null
}
newPoints += newHead
if (newHead != food) {
newPoints -= points.first()
}
return copy(points = newPoints, head = newHead)
}
private fun Point.step(direction: Direction): Point =
when (direction) {
Direction.LEFT -> copy(x = x - 1)
Direction.UP -> copy(y = y - 1)
Direction.RIGHT -> copy(x = x + 1)
Direction.DOWN -> copy(y = y + 1)
}
override fun setDirection(direction: Direction) {
update {
copy(
direction = if (direction != this.direction.invert()) direction else this.direction
)
}
}
private inline fun update(func: Board.() -> Board) {
_board.value = _board.value.func()
}
}
| 1 | null | 1 | 66 | 6bc96a46d577e4d95d09d6f33730e4ff0afbdc1e | 3,079 | CompoSnake | MIT License |
src/main/kotlin/domain/model/Config.kt | omuomugin | 264,404,491 | false | null | package domain.model
data class Config(
val labels: List<Label>
)
| 0 | Kotlin | 0 | 0 | e39ab93c5de45e849750b3b70db728b9bff67025 | 71 | labelit | MIT License |
app/src/test/java/com/arjanvlek/oxygenupdater/models/SystemVersionPropertiesTest.kt | iGotYourBackMr | 254,597,651 | true | {"Kotlin": 640563, "Java": 101703} | package com.arjanvlek.oxygenupdater.models
import com.arjanvlek.oxygenupdater.OxygenUpdater
import com.arjanvlek.oxygenupdater.utils.Utils.checkDeviceOsSpec
import java.lang.reflect.InvocationTargetException
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
abstract class SystemVersionPropertiesTest {
private val systemVersionProperties = SystemVersionProperties(null, null, null, null, null, false)
/**
* Test if a device is supported in the app
*
* @param propertiesInDir Directory name of properties files
* @param propertiesOfVersion OS version of build.prop file or 'getprop' command output file
* @param expectedDeviceDisplayName23x Display name as shown in app 2.3.2 and newer.
* @param expectedDeviceDisplayName12x Display name as shown in app between 1.2.0 and 2.3.1.
* @param expectedDeviceDisplayName11x Display name as shown in app between 1.1.x and older.
* @param expectedOxygenOs Expected OxygenOS version. Is the same as propertiesOfVersion on newer devices (and op1) or like expectedOxygenOSOta in other cases.
* @param expectedOxygenOsOta Expected OxygenOS OTA version (as sent to the server to query for updates).
* @param expectedAbPartitionLayout Expected value for if the device has an A/B partition layout (true) or classic partition layout (false)
*
* @return Whether or not the device is marked as supported in the app.
*/
fun isSupportedDevice(
propertiesInDir: String,
propertiesOfVersion: String,
expectedDeviceDisplayName23x: String?,
expectedDeviceDisplayName12x: String?,
expectedDeviceDisplayName11x: String?,
expectedOxygenOs: String?,
expectedOxygenOsOta: String?,
expectedAbPartitionLayout: Boolean
): Boolean {
val testDataSet = readBuildPropFile(propertiesInDir, propertiesOfVersion)
val testDataType = testDataSet.first
val properties = testDataSet.second
val deviceDisplayName23x = readProperty(DEVICE_NAME_LOOKUP_KEY, properties, testDataType)
val deviceDisplayName12x = readProperty("ro.display.series", properties, testDataType)
val deviceDisplayName11x = readProperty("ro.build.product", properties, testDataType)
val oxygenOSDisplayVersion = readProperty(OS_VERSION_NUMBER_LOOKUP_KEY, properties, testDataType)
val oxygenOSOtaVersion = readProperty(OS_OTA_VERSION_NUMBER_LOOKUP_KEY, properties, testDataType)
val buildFingerPrint = readProperty(BUILD_FINGERPRINT_LOOKUP_KEY, properties, testDataType)
val abPartitionLayout = java.lang.Boolean.parseBoolean(readProperty(AB_PARTITION_LAYOUT_LOOKUP_KEY, properties, testDataType))
assertEquals(expectedDeviceDisplayName23x, deviceDisplayName23x)
assertEquals(expectedDeviceDisplayName12x, deviceDisplayName12x)
assertEquals(expectedDeviceDisplayName11x, deviceDisplayName11x)
assertEquals(expectedOxygenOs, oxygenOSDisplayVersion)
assertEquals(expectedOxygenOsOta, oxygenOSOtaVersion)
assertTrue(buildFingerPrint.contains(SUPPORTED_BUILD_FINGERPRINT_KEYS))
assertEquals(expectedAbPartitionLayout, abPartitionLayout)
val deviceOsSpec = checkDeviceOsSpec(allOnePlusDevicesApp232AndNewer)
assertSame(deviceOsSpec, DeviceOsSpec.SUPPORTED_OXYGEN_OS)
return true
}
fun getSupportedDevice(propertiesInDir: String, propertiesOfVersion: String): Device {
val testDataSet = readBuildPropFile(propertiesInDir, propertiesOfVersion)
val testDataType = testDataSet.first
val properties = testDataSet.second
val deviceDisplayName23x = readProperty(DEVICE_NAME_LOOKUP_KEY, properties, testDataType)
return allOnePlusDevicesApp232AndNewer
.find { it.productNames.contains(deviceDisplayName23x) }
?: throw IllegalArgumentException("Unsupported device")
}
private fun readBuildPropFile(
deviceName: String,
oxygenOsVersion: String
): Pair<TestDataType, String> {
// Read the build.prop file from the test resources folder.
var testDataType = TestDataType.BUILD_PROP_FILE
var propertiesStream = javaClass.getResourceAsStream("/build-props/$deviceName/$oxygenOsVersion.prop")
if (propertiesStream == null) {
propertiesStream = javaClass.getResourceAsStream("/build-props/$deviceName/$oxygenOsVersion.getprop")
testDataType = TestDataType.GETPROP_COMMAND_OUTPUT
}
assertNotNull(propertiesStream, "Test data file build-props/$deviceName/$oxygenOsVersion.(get)prop does not exist!")
// Convert input stream to String using Scanner method.
val scanner = Scanner(propertiesStream).useDelimiter("\\A")
return Pair(testDataType, if (scanner.hasNext()) scanner.next() else "")
}
private fun readProperty(key: String, testData: String, testDataType: TestDataType): String {
@Suppress("REDUNDANT_ELSE_IN_WHEN")
return when (testDataType) {
TestDataType.BUILD_PROP_FILE -> getBuildPropItem(key, testData)
TestDataType.GETPROP_COMMAND_OUTPUT -> getItemFromGetPropCommandOutput(key, testData)
else -> throw IllegalStateException("Unknown test data type $testDataType")
}
}
// This version is a bit different than on a real device. Since we parse build.prop file directly,
// the output is "key=value" in contrast to getprop output of format "[key]:[value]".
// So we need to split the result on the "=" sign in this helper method to get the same result as on a real device.
private fun getBuildPropItem(key: String, propertyFileContents: String): String {
var result = OxygenUpdater.NO_OXYGEN_OS
try {
val readBuildPropItem = SystemVersionProperties::class.java.getDeclaredMethod("readBuildPropItem", String::class.java, String::class.java, String::class.java)
readBuildPropItem.isAccessible = true
val rawResult = readBuildPropItem.invoke(systemVersionProperties, key, propertyFileContents, null) as String
if (rawResult != OxygenUpdater.NO_OXYGEN_OS) {
val keyValue = rawResult.split("=")
if (keyValue.size > 1) {
result = keyValue[1]
}
}
} catch (e: NoSuchMethodException) {
throw RuntimeException(e)
} catch (e: IllegalAccessException) {
throw RuntimeException(e)
} catch (e: InvocationTargetException) {
throw RuntimeException(e)
}
return result
}
// This version is the same as what happens on the real device: Parse the output from 'getprop' command to a property item.
private fun getItemFromGetPropCommandOutput(key: String, getPropCommandOutput: String): String {
return try {
val readBuildPropItem = SystemVersionProperties::class.java.getDeclaredMethod("readBuildPropItem", String::class.java, String::class.java, String::class.java)
readBuildPropItem.isAccessible = true
readBuildPropItem.invoke(systemVersionProperties, key, getPropCommandOutput, null) as String
} catch (e: NoSuchMethodException) {
throw RuntimeException(e)
} catch (e: IllegalAccessException) {
throw RuntimeException(e)
} catch (e: InvocationTargetException) {
throw RuntimeException(e)
}
}
// do *not* add new devices here, it is pointless to support app versions from 2016-2017 on them \\
private val allOnePlusDevicesApp11AndOlder = listOf(
Device(5, "OnePlus One", "OnePlus"),
Device(1, "OnePlus 2", "OnePlus2"),
Device(3, "OnePlus X", "OnePlus"),
Device(2, "OnePlus 3", "OnePlus3"),
Device(6, "OnePlus 3T", "OnePlus3"),
Device(7, "OnePlus 5", "OnePlus5"),
Device(8, "OnePlus 5T", "OnePlus5T"),
Device(9, "OnePlus 6", "OnePlus6"),
Device(10, "OnePlus 6T (Global)", "OnePlus6T")
)
// do *not* add new devices here, it is pointless to support app versions from 2016-2017 on them \\
private val allOnePlusDevicesApp12Until231 = listOf(
Device(5, "OnePlus One", "OnePlus"),
Device(1, "OnePlus 2", "OnePlus2"),
Device(3, "OnePlus X", "OnePlus"),
Device(2, "OnePlus 3", "OnePlus3"),
Device(6, "OnePlus 3T", "OnePlus3"),
Device(7, "OnePlus 5", "OnePlus5"),
Device(8, "OnePlus 5T", "OnePlus5T"),
Device(9, "OnePlus 6", "OnePlus6"),
Device(10, "OnePlus 6T (Global)", "OnePlus6T")
)
private val allOnePlusDevicesApp232AndNewer = listOf(
Device(5, "OnePlus One", "OnePlus, One"),
Device(1, "OnePlus 2", "OnePlus2"),
Device(3, "OnePlus X", "OnePlus X"),
Device(2, "OnePlus 3", "OnePlus 3"),
Device(6, "OnePlus 3T", "OnePlus 3T"),
Device(7, "OnePlus 5", "OnePlus 5"),
Device(8, "OnePlus 5T", "OnePlus 5T"),
Device(9, "OnePlus 6", "OnePlus 6"),
Device(10, "OnePlus 6T (Global)", "OnePlus 6T"),
Device(11, "OnePlus 7", "OnePlus7"),
Device(11, "OnePlus 7 Pro (EU)", "OnePlus7Pro_EEA"),
Device(12, "OnePlus 7 Pro", "OnePlus7Pro"),
Device(13, "OnePlus 7 Pro 5G (EU)", "OnePlus7ProNR_EEA"),
Device(11, "OnePlus 7T (EU)", "OnePlus7T_EEA"),
Device(12, "OnePlus 7T", "OnePlus7T"),
Device(13, "OnePlus 7T (India)", "OnePlus7T_IN"),
Device(11, "OnePlus 7T Pro (EU)", "OnePlus7TPro_EEA"),
Device(12, "OnePlus 7T Pro", "OnePlus7TPro"),
Device(13, "OnePlus 7T Pro (India)", "OnePlus7TPro_IN")
)
private enum class TestDataType {
BUILD_PROP_FILE,
GETPROP_COMMAND_OUTPUT
}
private class Pair<F, S>(val first: F, val second: S)
companion object {
private const val OS_OTA_VERSION_NUMBER_LOOKUP_KEY = "ro.build.version.ota"
private const val OS_VERSION_NUMBER_LOOKUP_KEY = "ro.rom.version, ro.oxygen.version, ro.build.ota.versionname"
private const val SUPPORTED_BUILD_FINGERPRINT_KEYS = "release-keys"
private const val BUILD_FINGERPRINT_LOOKUP_KEY = "ro.build.oemfingerprint, ro.build.fingerprint"
private const val DEVICE_NAME_LOOKUP_KEY = "ro.display.series, ro.build.product"
private const val AB_PARTITION_LAYOUT_LOOKUP_KEY = "ro.build.ab_update"
}
}
| 0 | null | 0 | 0 | 884766371e62969831f2933ba790bbec4c2c1613 | 10,593 | oxygen-updater | MIT License |
app/src/main/java/com/febers/uestc_bbs/module/message/view/MessageFragment.kt | Febers | 135,606,653 | false | null | package com.febers.uestc_bbs.module.message.view
import android.os.Bundle
import androidx.annotation.UiThread
import androidx.recyclerview.widget.LinearLayoutManager
import com.febers.uestc_bbs.MyApp
import com.febers.uestc_bbs.R
import com.febers.uestc_bbs.base.*
import com.febers.uestc_bbs.entity.*
import com.febers.uestc_bbs.module.message.contract.MessageContract
import com.febers.uestc_bbs.module.message.presenter.MsgPresenterImpl
import com.febers.uestc_bbs.module.context.ClickContext
import com.febers.uestc_bbs.module.context.ClickContext.clickToPostDetail
import com.febers.uestc_bbs.module.context.ClickContext.clickToUserDetail
import com.febers.uestc_bbs.module.context.ClickContext.clickToPrivateMsg
import com.febers.uestc_bbs.view.adapter.*
import com.febers.uestc_bbs.utils.finishFail
import com.febers.uestc_bbs.utils.finishSuccess
import com.febers.uestc_bbs.utils.initAttrAndBehavior
import com.othershe.baseadapter.ViewHolder
import kotlinx.android.synthetic.main.fragment_sub_message.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
/**
* 消息列表的Fragment,分为四种类型
* 依次为帖子回复、私信、At和系统消息
*/
class MessageFragment : BaseFragment(), MessageContract.View {
private val replyList: MutableList<MsgReplyBean.ListBean> = ArrayList()
private val privateList: MutableList<MsgPrivateBean.BodyBean.ListBean> = ArrayList()
private val atList: MutableList<MsgAtBean.ListBean> = ArrayList()
private val systemList: MutableList<MsgSystemBean.BodyBean.DataBean> = ArrayList()
private lateinit var messagePresenter: MessageContract.Presenter
private lateinit var msgAdapter: MsgBaseAdapter
private var page = 1
private var loadFinish = false
override fun registerEventBus(): Boolean = true
override fun setView(): Int = R.layout.fragment_sub_message
/**
* 根据mMsgType,确定当前视图应该展示哪一种消息
*/
override fun initView() {
messagePresenter = MsgPresenterImpl(this)
when(mMsgType) {
MSG_TYPE_REPLY -> msgAdapter = MsgReplyAdapter(context!!, replyList, false).apply {
recyclerview_sub_message.adapter = this
setOnItemClickListener { viewHolder, listBean, i ->
clickToPostDetail(context, listBean.topic_id) }
setOnItemChildClickListener(R.id.image_view_msg_reply_author_avatar) {
p0: ViewHolder?, p1: MsgReplyBean.ListBean?, p2: Int ->
clickToUserDetail(context, p1?.user_id)}
setOnItemChildClickListener(R.id.image_view_msg_post_reply) {
viewHolder, listBean, i ->
ClickContext.clickToPostReply(context = activity,
toUserId = listBean.user_id,
toUserName = listBean.reply_nick_name,
postId = listBean.topic_id,
replyId = listBean.reply_remind_id,
isQuota = true,
replySimpleDescription = listBean.reply_content.toString())
}
setEmptyView(getEmptyViewForRecyclerView(recyclerview_sub_message))
}
MSG_TYPE_PRIVATE -> msgAdapter = MsgPrivateAdapter(context!!, privateList, false).apply {
recyclerview_sub_message.adapter = this
setOnItemClickListener { viewHolder, listBean, i ->
clickToPrivateMsg(context, listBean.toUserId, listBean.toUserName)
listBean.isNew = 0
this.notifyDataSetChanged()}
setOnItemChildClickListener(R.id.image_view_msg_private_author_avatar) {
viewHolder, listBean, i -> clickToUserDetail(activity, listBean.toUserId)
}
setEmptyView(getEmptyViewForRecyclerView(recyclerview_sub_message))
}
MSG_TYPE_AT -> msgAdapter = MsgAtAdapter(context!!, atList, false).apply {
recyclerview_sub_message.adapter = this
setOnItemClickListener { viewHolder, listBean, i ->
clickToPostDetail(context, listBean.topic_id, "", MyApp.user().name)}
setOnItemChildClickListener(R.id.image_view_msg_at_author_avatar) {
viewHolder, listBean, i -> clickToUserDetail(activity, listBean.user_id)
}
setEmptyView(getEmptyViewForRecyclerView(recyclerview_sub_message))
}
MSG_TYPE_SYSTEM -> msgAdapter = MsgSystemAdapter(context!!, systemList, false).apply {
recyclerview_sub_message.adapter = this
setEmptyView(getEmptyViewForRecyclerView(recyclerview_sub_message))
}
}
recyclerview_sub_message.apply {
layoutManager = LinearLayoutManager(context)
}
refresh_layout_sub_message.apply {
initAttrAndBehavior(true)
setOnRefreshListener {
page = 1
getMsg(page)
}
setOnLoadMoreListener {
getMsg(++page)
}
}
}
override fun onLazyInitView(savedInstanceState: Bundle?) {
super.onLazyInitView(savedInstanceState)
refresh_layout_sub_message.autoRefresh()
}
private fun getMsg(page: Int) {
messagePresenter.msgRequest(type = mMsgType?: MSG_TYPE_PRIVATE, page = page)
}
@UiThread
override fun <M : MsgBaseBean> showMessage(event: BaseEvent<M>) {
loadFinish = true
refresh_layout_sub_message?.finishSuccess()
val msgBean = event.data
when(mMsgType) {
MSG_TYPE_REPLY -> {
msgBean as MsgReplyBean
EventBus.getDefault().post(MsgFeedbackEvent(BaseCode.SUCCESS, MSG_TYPE_REPLY)) //隐藏通知
if (page == 1) {
(msgAdapter as MsgReplyAdapter).setNewData(msgBean.list)
return
}
(msgAdapter as MsgReplyAdapter).setLoadMoreData(msgBean.list)
}
MSG_TYPE_PRIVATE -> {
msgBean as MsgPrivateBean
if (page == 1) {
(msgAdapter as MsgPrivateAdapter).setNewData(msgBean.body?.list)
return
}
(msgAdapter as MsgPrivateAdapter).setLoadMoreData(msgBean.body?.list)
}
MSG_TYPE_AT -> {
msgBean as MsgAtBean
EventBus.getDefault().post(MsgFeedbackEvent(BaseCode.SUCCESS, MSG_TYPE_AT))
if (page == 1) {
(msgAdapter as MsgAtAdapter).setNewData(msgBean.list)
return
}
(msgAdapter as MsgAtAdapter).setLoadMoreData(msgBean.list)
}
MSG_TYPE_SYSTEM -> {
msgBean as MsgSystemBean
EventBus.getDefault().post(MsgFeedbackEvent(BaseCode.SUCCESS, MSG_TYPE_SYSTEM))
if (page == 1) {
(msgAdapter as MsgSystemAdapter).setNewData(msgBean.body?.data)
return
}
(msgAdapter as MsgSystemAdapter).setLoadMoreData(msgBean.body?.data)
}
}
if (event.code == BaseCode.SUCCESS_END) {
refresh_layout_sub_message?.finishLoadMoreWithNoMoreData()
}
}
override fun showError(msg: String) {
showHint(msg)
refresh_layout_sub_message?.finishFail()
}
override fun onSupportVisible() {
super.onSupportVisible()
if (mMsgType != MSG_TYPE_PRIVATE) {
// log("visible and type is $mMsgType")
EventBus.getDefault().post(MsgFeedbackEvent(BaseCode.SUCCESS, mMsgType!!))
}
}
/**
* 接收BottomNavigation的二次点击事件
* 当当前页面正在显示的时候,刷新
*/
@Subscribe(threadMode = ThreadMode.MAIN)
fun onTabReselected(event: TabReselectedEvent) {
if (isSupportVisible && loadFinish && event.position == 2) {
scroll_view_sub_message?.scrollTo(0, 0)
refresh_layout_sub_message?.autoRefresh()
}
}
/**
* 当后台Service接收到新消息时,此方法会接受到相应的消息
* 如果正在显示,则刷新界面
*/
@Subscribe(threadMode = ThreadMode.MAIN)
fun onReceiveNewMsg(event: MsgEvent) {
if (userVisibleHint && event.type == mMsgType) {
refresh_layout_sub_message?.autoRefresh()
}
}
companion object {
@JvmStatic
fun newInstance(type: String) =
MessageFragment().apply {
arguments = Bundle().apply {
putString(MSG_TYPE, type)
}
}
}
} | 1 | Kotlin | 11 | 41 | b9da253984e2febc235121ac6745bfbc215a7609 | 8,746 | UESTC_BBS | Apache License 2.0 |
projects/workforce-allocations-to-delius/src/dev/kotlin/uk/gov/justice/digital/hmpps/data/generator/ManagerGenerator.kt | ministryofjustice | 500,855,647 | false | null | package uk.gov.justice.digital.hmpps.data.generator
import uk.gov.justice.digital.hmpps.datetime.EuropeLondon
import uk.gov.justice.digital.hmpps.integrations.delius.allocations.entity.ManagerBaseEntity
import uk.gov.justice.digital.hmpps.integrations.delius.provider.Provider
import uk.gov.justice.digital.hmpps.integrations.delius.provider.Staff
import uk.gov.justice.digital.hmpps.integrations.delius.provider.Team
import java.time.ZonedDateTime
interface ManagerGenerator {
companion object {
val START_DATE_TIME: ZonedDateTime =
ZonedDateTime.of(2022, 7, 1, 10, 30, 0, 0, EuropeLondon)
}
fun ManagerBaseEntity.build(
provider: Provider = ProviderGenerator.DEFAULT,
team: Team = TeamGenerator.DEFAULT,
staff: Staff = StaffGenerator.DEFAULT,
dateTime: ZonedDateTime = START_DATE_TIME,
createdDateTime: ZonedDateTime = ZonedDateTime.now(),
lastModifiedDateTime: ZonedDateTime = ZonedDateTime.now(),
createdUserId: Long = UserGenerator.AUDIT_USER.id,
lastModifiedUserId: Long = UserGenerator.AUDIT_USER.id,
version: Long = 0
) = apply {
this.provider = provider
this.team = team
this.staff = staff
trustProviderTeam = team
staffEmployee = staff
startDate = dateTime
this.createdDateTime = createdDateTime
this.lastModifiedDateTime = lastModifiedDateTime
this.createdUserId = createdUserId
this.lastModifiedUserId = lastModifiedUserId
this.version = version
}
}
| 5 | Kotlin | 0 | 2 | f7042c113b7cfd4d439c6c77231a1a28f93e9485 | 1,565 | hmpps-probation-integration-services | MIT License |
autofill/autofill-impl/src/main/java/com/duckduckgo/autofill/impl/email/incontext/prompt/EmailProtectionInContextSignUpPromptFragment.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} |
package com.duckduckgo.autofill.impl.email.incontext.prompt
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.setFragmentResult
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import com.duckduckgo.anvil.annotations.InjectWith
import com.duckduckgo.app.statistics.pixels.Pixel
import com.duckduckgo.autofill.api.EmailProtectionInContextSignUpDialog
import com.duckduckgo.autofill.impl.R
import com.duckduckgo.autofill.impl.databinding.DialogEmailProtectionInContextSignUpBinding
import com.duckduckgo.autofill.impl.email.incontext.prompt.EmailProtectionInContextSignUpPromptViewModel.Command.FinishWithResult
import com.duckduckgo.autofill.impl.pixel.AutofillPixelNames
import com.duckduckgo.common.utils.FragmentViewModelFactory
import com.duckduckgo.di.scopes.FragmentScope
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import dagger.android.support.AndroidSupportInjection
import javax.inject.Inject
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import timber.log.Timber
@InjectWith(FragmentScope::class)
class EmailProtectionInContextSignUpPromptFragment : BottomSheetDialogFragment(), EmailProtectionInContextSignUpDialog {
override fun getTheme(): Int = R.style.AutofillBottomSheetDialogTheme
@Inject
lateinit var pixel: Pixel
@Inject
lateinit var viewModelFactory: FragmentViewModelFactory
private val viewModel by lazy {
ViewModelProvider(this, viewModelFactory)[EmailProtectionInContextSignUpPromptViewModel::class.java]
}
override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
// If being created after a configuration change, dismiss the dialog as the WebView will be re-created too
dismiss()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
pixel.fire(AutofillPixelNames.EMAIL_PROTECTION_IN_CONTEXT_PROMPT_DISPLAYED)
val binding = DialogEmailProtectionInContextSignUpBinding.inflate(inflater, container, false)
configureViews(binding)
observeViewModel()
return binding.root
}
private fun observeViewModel() {
viewModel.commands.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED).onEach {
when (it) {
is FinishWithResult -> returnResult(it.result)
}
}.launchIn(lifecycleScope)
}
private fun configureViews(binding: DialogEmailProtectionInContextSignUpBinding) {
(dialog as BottomSheetDialog).behavior.state = BottomSheetBehavior.STATE_EXPANDED
configureDialogButtons(binding)
}
private fun configureDialogButtons(binding: DialogEmailProtectionInContextSignUpBinding) {
context?.let {
binding.protectMyEmailButton.setOnClickListener {
viewModel.onProtectEmailButtonPressed()
}
binding.closeButton.setOnClickListener {
viewModel.onCloseButtonPressed()
}
binding.doNotShowAgainButton.setOnClickListener {
viewModel.onDoNotShowAgainButtonPressed()
}
}
}
private fun returnResult(resultType: EmailProtectionInContextSignUpDialog.EmailProtectionInContextSignUpResult) {
Timber.v("User action: %s", resultType::class.java.simpleName)
val result = Bundle().also {
it.putParcelable(EmailProtectionInContextSignUpDialog.KEY_RESULT, resultType)
}
parentFragment?.setFragmentResult(EmailProtectionInContextSignUpDialog.resultKey(getTabId()), result)
dismiss()
}
override fun onCancel(dialog: DialogInterface) {
pixel.fire(AutofillPixelNames.EMAIL_PROTECTION_IN_CONTEXT_PROMPT_DISMISSED)
returnResult(EmailProtectionInContextSignUpDialog.EmailProtectionInContextSignUpResult.Cancel)
}
private fun getTabId() = arguments?.getString(KEY_TAB_ID)!!
companion object {
fun instance(
tabId: String,
): EmailProtectionInContextSignUpPromptFragment {
val fragment = EmailProtectionInContextSignUpPromptFragment()
fragment.arguments = Bundle().also {
it.putString(KEY_TAB_ID, tabId)
}
return fragment
}
private const val KEY_TAB_ID = "tabId"
}
}
| 0 | Kotlin | 0 | 0 | b89591136b60933d6a03fac43a38ee183116b7f8 | 5,005 | DuckDuckGo | Apache License 2.0 |
idea/testData/run/ClassesAndObjects/module/src/test.kt | JakeWharton | 99,388,807 | false | null | package q
import kotlin.platform.platformStatic
// RUN: q.Foo
object Foo {
// RUN: q.Foo
platformStatic fun main(s: Array<String>) {
println("Foo")
}
// RUN: q.Foo.InnerFoo
class InnerFoo {
companion object {
// RUN: q.Foo.InnerFoo
platformStatic fun main(s: Array<String>) {
println("InnerFoo")
}
}
}
// RUN: q.Foo
class InnerFoo2 {
// RUN: q.Foo
platformStatic fun main(s: Array<String>) {
println("InnerFoo")
}
}
}
// RUN: q.TestKt
object Foo2 {
// RUN: q.TestKt
fun main(s: Array<String>) {
println("Foo2")
}
}
// RUN: q.Bar
class Bar {
companion object {
// RUN: q.Bar
platformStatic fun main(s: Array<String>) {
println("Bar")
}
}
}
// RUN: q.TestKt
class Bar2 {
companion object {
// RUN: q.TestKt
fun main(s: Array<String>) {
println("Bar2")
}
}
}
// RUN: q.TestKt
class Baz {
// RUN: q.TestKt
platformStatic fun main(s: Array<String>) {
println("Baz")
}
}
// RUN: q.TestKt
class Baz2 {
// RUN: q.TestKt
fun main(s: Array<String>) {
println("Baz2")
}
}
// RUN: q.TestKt
fun main(s: Array<String>) {
println("Top-level")
} | 284 | null | 5162 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,339 | kotlin | Apache License 2.0 |
koncat-compile-contract/src/main/kotlin/me/xx2bab/koncat/contract/KoncatArgumentsContract.kt | 2BAB | 433,810,120 | false | {"Kotlin": 83292, "Shell": 128} | package me.xx2bab.koncat.contract
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import java.io.File
@Serializable
data class KoncatArgumentsContract(
val projectName: String,
val koncatVersion: String,
val gradlePlugins: List<String>,
val declaredAsMainProject: Boolean,
val generateAggregationClass: Boolean,
val generateExtensionClass: Boolean,
val targetAnnotations: List<String>,
val targetClassTypes: List<String>,
val targetPropertyTypes: List<String>
)
fun KoncatArgumentsContract.encodeKoncatArguments(): String = Json.encodeToString(this)
fun decodeKoncatArguments(targetDirectory: File, variantName: String = ""): KoncatArgumentsContract {
val fileName = if (variantName.isBlank()) {
KONCAT_ARGUMENT_TARGET_FILE_BASE
} else {
KONCAT_ARGUMENT_TARGET_FILE_VARIANT_AWARE.format(variantName)
}
val jsonFile = File(targetDirectory, fileName)
return Json.decodeFromStream(jsonFile.inputStream())
} | 3 | Kotlin | 3 | 57 | 04e6400fe06fb8d099ed31c8f3ed246f8c805ac6 | 1,107 | Koncat | Apache License 2.0 |
src/main/kotlin/com/github/breninsul/webfluxlogging/client/WebClientLoggingAutoConfig.kt | BreninSul | 631,416,800 | false | {"Kotlin": 50389} | /*
* MIT License
*
* Copyright (c) 2023 BreninSul
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.github.breninsul.webfluxlogging.client
import com.github.breninsul.webfluxlogging.CommonLoggingUtils
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.AutoConfigureOrder
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.Ordered
import org.springframework.web.reactive.function.client.WebClient
@Configuration
@ConditionalOnClass(WebClient::class)
@ConditionalOnProperty(
prefix = "webflux.logging.webclient",
name = ["disabled"],
matchIfMissing = true,
havingValue = "false"
)
@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE)
@EnableConfigurationProperties(WebClientLoggingProperties::class)
class WebClientLoggingAutoConfig {
@Bean
@ConditionalOnMissingBean(CommonLoggingUtils::class)
fun getCommonLoggingUtils(
): CommonLoggingUtils {
return CommonLoggingUtils()
}
@Bean
@ConditionalOnMissingBean(WebClientLoggingUtils::class)
fun getWebClientLoggingUtils(
props: WebClientLoggingProperties,
commonLoggingUtils: CommonLoggingUtils
): WebClientLoggingUtils {
val logger=java.util.logging.Logger.getLogger(props.loggerClass)
return WebClientLoggingUtils(props.maxBodySize, logger,props.getLoggingLevelAsJavaLevel(), props.logTime, props.logHeaders, props.logBody, commonLoggingUtils)
}
@Bean
@ConditionalOnMissingBean(WebClientLoggingExchangeFilterFunction::class)
fun getWebClientLoggingExchangeFilterFunction(
loggingUtils: WebClientLoggingUtils
): WebClientLoggingExchangeFilterFunction {
return WebClientLoggingExchangeFilterFunction(loggingUtils)
}
@Bean
@ConditionalOnMissingBean(WebClient::class)
fun getWebClientLogging(
filter: WebClientLoggingExchangeFilterFunction
): WebClient {
return WebClient
.builder()
.filter(filter)
.build()
}
} | 0 | Kotlin | 0 | 0 | 6c89ff1e860f010291df35b2d29780a26ff4a179 | 3,597 | webflux-request-logging | MIT License |
src/main/kotlin/no/nav/helse/inntektsmeldingsvarsel/varsling/VarslingMapper.kt | navikt | 255,909,562 | false | null | package no.nav.helse.inntektsmeldingsvarsel.varsling
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import no.nav.helse.inntektsmeldingsvarsel.domene.varsling.Varsling
import no.nav.helse.inntektsmeldingsvarsel.domene.varsling.repository.VarslingDbEntity
class VarslingMapper(private val mapper: ObjectMapper) {
fun mapDto(varsling: Varsling): VarslingDbEntity {
return VarslingDbEntity(
uuid = varsling.uuid,
data = mapper.writeValueAsString(varsling.liste),
sent = varsling.varslingSendt,
opprettet = varsling.opprettet,
virksomhetsNr = varsling.virksomhetsNr,
read = varsling.varslingLest
)
}
fun mapDomain(dbEntity: VarslingDbEntity): Varsling {
return Varsling(
virksomhetsNr = dbEntity.virksomhetsNr,
uuid = dbEntity.uuid,
opprettet = dbEntity.opprettet,
varslingSendt = dbEntity.sent,
varslingLest = dbEntity.read,
liste = mapper.readValue(dbEntity.data)
)
}
}
| 6 | Kotlin | 0 | 0 | a519ca65a4c93e277d5c6395e4e38b33678eb99a | 1,121 | im-varsel | MIT License |
app/src/main/java/com/oreo/status/hub/ui/whatsapp/WhatsappPagerAdapter.kt | africantechdotworld | 842,383,119 | false | {"Kotlin": 22124} | package com.oreo.status.hub.ui.whabus
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.oreo.status.hub.fragments.whabus.WhabusStatusFragment
import com.oreo.status.hub.fragments.whabus.WhabusVideoFragment
import com.oreo.status.hub.fragments.whabus.WhabusPhotoFragment
class WhabusPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {
override fun getItemCount(): Int {
return 3 // Number of fragments
}
override fun createFragment(position: Int): Fragment {
// Return the fragment instance based on position
return when (position) {
0 -> WhabusStatusFragment()
1 -> WhabusVideoFragment()
2 -> WhabusPhotoFragment()
else -> throw IllegalArgumentException("Invalid position: $position")
}
}
}
| 0 | Kotlin | 0 | 0 | 61994e1c419fd663f90822d95388a8851b04e55a | 932 | status-hub | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/hover/stax/hover/BountyContract.kt | UseHover | 286,494,631 | false | {"Kotlin": 1033610, "Java": 88968, "Shell": 274, "Ruby": 235} | /*
* Copyright 2023 Stax
*
* 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.hover.stax.hover
import android.content.Context
import android.content.Intent
import androidx.activity.result.contract.ActivityResultContract
import com.hover.sdk.actions.HoverAction
import com.hover.sdk.api.HoverParameters
import com.hover.stax.notifications.PushNotificationTopicsInterface
import timber.log.Timber
class BountyContract :
ActivityResultContract<HoverAction, Intent?>(),
PushNotificationTopicsInterface {
override fun createIntent(context: Context, a: HoverAction): Intent {
updatePushNotifGroupStatus(context, a)
return HoverParameters.Builder(context).request(a.public_id).setEnvironment(HoverParameters.MANUAL_ENV).buildIntent()
}
override fun parseResult(resultCode: Int, intent: Intent?): Intent? {
// We don't care about the resultCode - bounties are currently always cancelled because they rely on the timer running out to end.
if (intent == null || intent.extras == null || intent.extras!!.getString("uuid") == null) {
Timber.e("Bounty result got null transaction data")
}
return intent
}
private fun updatePushNotifGroupStatus(c: Context, a: HoverAction) {
joinAllBountiesGroup(c)
joinBountyCountryGroup(a.country_alpha2, c)
}
} | 106 | Kotlin | 72 | 79 | 5b735dc215b63533420fe899c579a42a44f598ea | 1,868 | Stax | Apache License 2.0 |
src/main/kotlin/pm/n2/hajlib/event/EventHandler.kt | n2pm | 657,755,321 | false | {"Kotlin": 12266, "Java": 4332} | package pm.n2.hajlib.event
/**
* Marks a function as an event handler.
* The function must have a single parameter of the event type.
*/
@Target(AnnotationTarget.FUNCTION)
annotation class EventHandler
| 0 | Kotlin | 0 | 0 | 449af9b78d74ec5a8c1b9af935441f1e8d04b382 | 206 | hajlib | MIT License |
app/src/main/kotlin/com/w10group/hertzdictionary/app/core/view/CurveView.kt | qiaoyuang | 119,500,508 | false | null | package com.w10group.hertzdictionary.app.core.view
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat
import com.w10group.hertzdictionary.app.R
import com.w10group.hertzdictionary.core.fmtDateNormal
import com.w10group.hertzdictionary.core.fmtMonthDay
import org.jetbrains.anko.dip
import org.jetbrains.anko.sp
import java.text.NumberFormat
import kotlin.math.abs
/**
* 查询频数曲线自定义 View
* @author Qiao
*/
class CurveView : View {
constructor(context: Context) : super(context)
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)
constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr)
/**
* 颜色
*/
private val darkBlue = ContextCompat.getColor(context, R.color.pool_curve_blue_dark)
private val lightBlue = ContextCompat.getColor(context, R.color.pool_curve_blue_light)
private val windowBackground = ContextCompat.getColor(context, R.color.pool_curve_window_background)
private val white = Color.WHITE
/**
* dp 以及 sp 值
*/
private val dp1 = 1.dp
private val dp2 = 2.dp
private val dp4 = 4.dp
private val dp6 = 6.dp
private val dp12 = 12.dp
private val dp16 = 16.dp
private val dp24 = 24.dp
private val dp28 = 28.dp
private val dp32 = 32.dp
private val dp48 = 48.dp
private val dp96 = 96.dp
private val sp10 = 10.sp
private val sp12 = 12.sp
/**
* 画笔
*/
// 文字画笔
private val mTextPaint = Paint().apply {
isAntiAlias = true
color = ContextCompat.getColor(context, R.color.text_disable_color)
textSize = sp10
}
// 虚线画笔
private val mDashLinePaint = Paint().apply {
isAntiAlias = true
color = ContextCompat.getColor(context, R.color.list_divider_color)
pathEffect = DashPathEffect(floatArrayOf(dp6, dp4), 0f)
strokeWidth = dp1
}
// 浅蓝色图形画笔
private val mGraphicsPaint = Paint().apply {
isAntiAlias = true
color = lightBlue
pathEffect = CornerPathEffect(dp4)
}
// 深蓝色曲线画笔
private val mCurvePaint = Paint().apply {
isAntiAlias = true
color = darkBlue
style = Paint.Style.STROKE
pathEffect = CornerPathEffect(dp4)
strokeWidth = dp2
}
// 查询频数单位画笔
private val mUnitPaint = Paint().apply {
isAntiAlias = true
textSize = sp10
}
// 点击处竖线画笔
private val mVerticalLinePaint = Paint().apply {
isAntiAlias = true
color = darkBlue
strokeWidth = dp1
}
// 触摸点画笔
private val mTouchPaint = Paint().apply {
isAntiAlias = true
textSize = sp12
}
/**
* 路径
*/
// 浅蓝色图形路径
private val mGraphicsPath = Path()
// 深蓝色曲线路径
private val mCurvePath = Path()
private var isPathEmpty = false
set(value) {
field = value
if (value) {
mGraphicsPath.reset()
mCurvePath.reset()
}
}
/**
* 一些参数
*/
// 图标的时间(X 轴参数)
private val time = ArrayList<Long>()
// 图表的查询频数值(Y 轴参数)
private val value = ArrayList<Int>()
// 触摸点的横纵坐标
private var touchX = 0f
private var touchY = 0f
private val mFormat = NumberFormat.getInstance().apply {
maximumFractionDigits = 1
}
private val mDefaultUnit = context.getString(R.string.default_unit)
// 真实宽度
private var realWidth = 0f
// 设置数据
fun setData(xList: List<Long>, yList: List<Int>) {
time.clear()
time.addAll(xList)
value.clear()
value.addAll(yList)
require(time.size == value.size) { "xList and yList must be equal in size." }
require(time.size >= 2) { "The size of xList and yList must be greater than 1." }
touchX = 0f
touchY = 0f
isPathEmpty = true
invalidate()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
realWidth = width - dp4 * 1.5f
}
override fun onDraw(canvas: Canvas) = canvas whenTimeAndValueNotEmpty {
drawXText()
drawYText()
drawUnit()
drawDottedLine()
drawCurve()
drawWindow()
}
private inline infix fun Canvas.whenTimeAndValueNotEmpty(block: Canvas.() -> Unit) {
if (time.isNotEmpty() && value.isNotEmpty())
block()
}
// 第一步:绘制 X 轴坐标参数(时间)
private fun Canvas.drawXText() {
val time1 = time.first().fmtMonthDay()
val time4 = time.last().fmtMonthDay()
val position = time.size / 3
val time2 = time[position].fmtMonthDay()
val time3 = time[position shl 1].fmtMonthDay()
val y = (height * 9 / 10).toFloat()
val fWidth = realWidth
val x1 = fWidth / 10
val x2 = x1 * 4 - dp16
val x3 = x1 * 7 - dp24
val x4 = fWidth - dp32
infix fun String.drawTextX(x: Float) = drawText(this, x, y, mTextPaint)
time1 drawTextX x1
time2 drawTextX x2
time3 drawTextX x3
time4 drawTextX x4
}
// 第二步:绘制 Y 轴坐标参数(查询频数)
private fun Canvas.drawYText() {
val maxValue = value.maxOrNull()!!
val value1 = "0"
val (value2, value3, value4) = if (maxValue == 0)
Triple("1", "2", "3")
else Triple(mFormat.format(maxValue.toFloat() / 3),
mFormat.format(maxValue.toFloat() / 3 * 2),
"$maxValue")
val x = 0f
val y1 = (height / 5).toFloat()
val y2 = y1 * 2
val y3 = y1 * 3
val y4 = y1 * 4
infix fun String.drawTextY(y: Float) = drawText(this, x, y, mTextPaint)
value4 drawTextY y1
value3 drawTextY y2
value2 drawTextY y3
value1 drawTextY y4
}
// 第三步:绘制右上角查询频数单位
private fun Canvas.drawUnit() {
val x = width.toFloat() - dp32
val y = dp24
mUnitPaint.color = darkBlue
drawText(mDefaultUnit, x, y, mUnitPaint)
mUnitPaint.color = lightBlue
drawRoundRect(x - dp4, y - dp12, x + dp28, y + dp4, 10f, 10f, mUnitPaint)
}
// 第四步:绘制横向虚线
private fun Canvas.drawDottedLine() {
val stopX = realWidth
val startX = realWidth / 10
fun drawLine(y: Float) = drawLine(startX, y, stopX, y, mDashLinePaint)
val y1 = (height / 5).toFloat()
val y2 = y1 * 2
val y3 = y1 * 3
val y4 = y1 * 4
drawLine(y1)
drawLine(y2)
drawLine(y3)
drawLine(y4)
}
// 第五步:绘制查询频数曲线以及下方浅蓝色区域
private fun Canvas.drawCurve() {
if (!isPathEmpty) {
if (value.any { it != 0 })
drawPath(mGraphicsPath, mGraphicsPaint)
drawPath(mCurvePath, mCurvePaint)
return
}
val width = realWidth
val x0 = width / 10
val y0 = (height / 5 * 4).toFloat()
if (value.all { it == 0 }) {
mCurvePath.moveTo(x0, y0)
mCurvePath.lineTo(width, y0)
drawPath(mCurvePath, mCurvePaint)
return
}
mGraphicsPath.moveTo(x0, y0)
val (x1, y1) = valueToCoordinate(0)
mGraphicsPath.lineTo(x1, y1)
mCurvePath.moveTo(x1, y1)
for (index in 1 until value.size) {
val (x, y) = valueToCoordinate(index)
mGraphicsPath.lineTo(x, y)
mCurvePath.lineTo(x, y)
}
mGraphicsPath.lineTo(width, y0)
mGraphicsPath.close()
drawPath(mGraphicsPath, mGraphicsPaint)
drawPath(mCurvePath, mCurvePaint)
}
// 第六步:绘制触摸点以及弹窗
private fun Canvas.drawWindow() = if (touchX > 0 && touchY > 0) {
// 获取与触摸点最近的有值的点在 time 和 value 中的 index
val index = getTimeTemp()
if (index >= 0) {
// 获取要绘制竖线的 x 与 y 坐标
val (x, y) = valueToCoordinate(index)
val radius = dp4
val startY = height / 5 - radius
val endY = height.toFloat() / 5 * 4
// 绘制弹窗
val touchDiaPowerText = context.getString(R.string.curve_view_count, "${value[index]}$mDefaultUnit")
val touchTimeText = time[index].fmtDateNormal()
val windowWidth = dp96
val offset = dp16
val windowHeight = dp48
val binaryOffset = offset / 2
val windowX = if (x < realWidth / 2) x + binaryOffset else x - windowWidth - offset
val windowY = if (y < height shr 1) y + binaryOffset else y - windowHeight - offset
// 绘制竖线
drawLine(x, startY, x, endY, mVerticalLinePaint)
// 绘制白边蓝心圆
mTouchPaint.color = white
drawCircle(x, y, radius * 1.5f, mTouchPaint)
mTouchPaint.color = darkBlue
drawCircle(x, y, radius, mTouchPaint)
// 绘制深色背景
mTouchPaint.color = windowBackground
drawRoundRect(windowX, windowY, windowX + windowWidth, windowY + windowHeight, dp4, dp4, mTouchPaint)
// 绘制时间文字
mTouchPaint.color = white
val drawX = windowX + offset / 2
val drawY = windowY + offset
drawText(touchTimeText, drawX, drawY, mTouchPaint)
// 绘制查询频数值文字
drawText(touchDiaPowerText, drawX, drawY + windowHeight / 2, mTouchPaint)
} else Unit
} else Unit
// 给出 index,返回该 index 对应数据在图表中的坐标
private fun valueToCoordinate(index: Int): FloatArray {
// 计算时间
val diff = time[index] - time.first()
val maxDiff = time.last() - time.first()
val diffScale = diff.toFloat() / maxDiff.toFloat()
val offset = realWidth / 10
val maxWidth = offset * 9
val x = diffScale * maxWidth + offset
// 计算查询频数
val max = value.maxOrNull()!!.toFloat()
val baseHeight = height.toFloat() / 5
val y = if (max == 0f) baseHeight * 4 else (max - value[index]) / max * (baseHeight * 3) + baseHeight
return floatArrayOf(x, y)
}
// 给定横坐标 X,计算出对应的时间与值的 index
private fun getTimeTemp(): Int {
// 获取 realTime 的过程本质上就是 valueToCoordinate 函数计算 x 过程的逆运算
val offset = realWidth / 10
val maxWidth = offset * 9
val diffScale = (touchX - offset) / maxWidth
val maxDiff = time.last() - time.first()
val diff = diffScale * maxDiff
// 得到触摸点对应的大概的时间戳值
val touchTime = diff + time.first()
// 获得 time 中与 touchTime 差值的绝对值最小的值
val realTime = time.minByOrNull { abs(it - touchTime) }
return if (realTime != null) time.indexOf(realTime) else -1
}
private inline val Int.dp
get() = dip(this).toFloat()
private inline val Int.sp
get() = sp(this).toFloat()
@Suppress("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
touchX = event.x
touchY = event.y
isPathEmpty = false
invalidate()
return true
}
} | 0 | Kotlin | 2 | 10 | 3d52dafa3d3cf89f483d50f4721c3f42a0bb5536 | 11,216 | HertzDictionary | Apache License 2.0 |
src/main/kotlin/edu/rit/gis/sunspec/models/model_12.kt | wz2b | 303,254,575 | true | {"Kotlin": 556515} | /*
* Model 12 - model_12
*/
package edu.rit.gis.sunspec.models
import edu.rit.gis.sunspec.annotations.*
import edu.rit.gis.sunspec.parser.SunSpecByteBuffer
import edu.rit.gis.sunspec.parser.SunSpecModelBase
data class Model_12 (
@SunSpecPoint(id="ID", label="Model ID", offset=0, registers=1, description="Model identifier")
var ID : UShort,
@SunSpecPoint(id="L", label="Model Length", offset=1, registers=1, description="Model length")
var L : UShort,
@SunSpecPoint(id="Nam", label="Name", offset=2, registers=4, description="Interface name")
var Nam : String,
@SunSpecPoint(id="CfgSt", label="Config Status", offset=6, registers=1, description="Enumerated value. Configuration status")
var CfgSt : UShort,
@SunSpecPoint(id="ChgSt", label="Change Status", offset=7, registers=1, description="Bitmask value. A configuration change is pending")
var ChgSt : UShort,
@SunSpecPoint(id="Cap", label="Config Capability", offset=8, registers=1, description="Bitmask value. Identify capable sources of configuration")
var Cap : UShort,
@SunSpecPoint(id="Cfg", label="IPv4 Config", offset=9, registers=1, description="Enumerated value. Configuration method used.")
var Cfg : UShort,
@SunSpecPoint(id="Ctl", label="Control", offset=10, registers=1, description="Configure use of services")
var Ctl : UShort,
@SunSpecPoint(id="Addr", label="IP", offset=11, registers=8, description="IPv4 numeric address as a dotted string xxx.xxx.xxx.xxx")
var Addr : String,
@SunSpecPoint(id="Msk", label="Netmask", offset=19, registers=8, description="IPv4 numeric netmask as a dotted string xxx.xxx.xxx.xxx")
var Msk : String,
@SunSpecPoint(id="Gw", label="Gateway", offset=27, registers=8, description="IPv4 numeric gateway address as a dotted string xxx.xxx.xxx.xxx")
var Gw : String,
@SunSpecPoint(id="DNS1", label="DNS1", offset=35, registers=8, description="IPv4 numeric DNS address as a dotted string xxx.xxx.xxx.xxx")
var DNS1 : String,
@SunSpecPoint(id="DNS2", label="DNS2", offset=43, registers=8, description="IPv4 numeric DNS address as a dotted string xxx.xxx.xxx.xxx")
var DNS2 : String,
@SunSpecPoint(id="NTP1", label="NTP1", offset=51, registers=12, description="IPv4 numeric NTP address as a dotted string xxx.xxx.xxx.xxx")
var NTP1 : String,
@SunSpecPoint(id="NTP2", label="NTP2", offset=63, registers=12, description="IPv4 numeric NTP address as a dotted string xxx.xxx.xxx.xxx")
var NTP2 : String,
@SunSpecPoint(id="DomNam", label="Domain", offset=75, registers=12, description="Domain name (24 chars max)")
var DomNam : String,
@SunSpecPoint(id="HostNam", label="Host Name", offset=87, registers=12, description="Host name (24 chars max)")
var HostNam : String,
@SunSpecPoint(id="Pad", label="Pad", offset=99, registers=1, description="Pad")
var Pad : Any
) : SunSpecModelBase {
companion object {
fun parse(bytes: ByteArray) : Model_12 {
SunSpecByteBuffer(bytes).apply {
return Model_12(
ID = getUInt16(),
L = getUInt16(),
Nam = { val size=4; getString(size) }(),
CfgSt = getUInt16(),
ChgSt = getUInt16(),
Cap = getUInt16(),
Cfg = getUInt16(),
Ctl = getUInt16(),
Addr = { val size=8; getString(size) }(),
Msk = { val size=8; getString(size) }(),
Gw = { val size=8; getString(size) }(),
DNS1 = { val size=8; getString(size) }(),
DNS2 = { val size=8; getString(size) }(),
NTP1 = { val size=12; getString(size) }(),
NTP2 = { val size=12; getString(size) }(),
DomNam = { val size=12; getString(size) }(),
HostNam = { val size=12; getString(size) }(),
Pad = getUInt16(),
)
}
}
}
}
| 0 | Kotlin | 0 | 0 | bfdbbff1764a7900eaf6427132c4e04bd2cb4f64 | 4,011 | sunspec-models-kotlin | Apache License 2.0 |
app/src/main/kotlin/com/aboust/develop_guide/widget/recyclerview/DividerAlignChildViewItemDecoration.kt | cyzaoj | 233,992,143 | false | null | package com.aboust.develop_guide.widget.recyclerview
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.View
import androidx.annotation.IntDef
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
/**
*
*
* onDraw:在item绘制之前时被调用,将指定的内容绘制到item view内容之下;
* onDrawOver:在item被绘制之后调用,将指定的内容绘制到item view内容之上
* getItemOffsets:在每次测量item尺寸时被调用,将decoration的尺寸计算到item的尺寸中
*/
class DividerAlignChildViewItemDecoration(@field:Orientation var orientation: Int) : RecyclerView.ItemDecoration() {
@IntDef(HORIZONTAL, VERTICAL)
@Retention(AnnotationRetention.SOURCE)
private annotation class Orientation
private var divider: Drawable? = null
set(value) {
requireNotNull(value) { "Drawable cannot be null." }
field = value
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDrawOver(c, parent, state)
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDraw(c, parent, state)
if (null == parent.layoutManager || divider == null) return
when (orientation) {
HORIZONTAL -> {
}
VERTICAL -> {
}
}
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
}
companion object {
const val HORIZONTAL = LinearLayoutManager.HORIZONTAL
const val VERTICAL = LinearLayoutManager.VERTICAL
}
} | 0 | Kotlin | 0 | 0 | 93f09425f686d1ea1476202ec00bedeeef5a1e40 | 1,743 | Android_Develop_Guide | MIT License |
src/test/kotlin/org/rust/lang/core/mir/MirBuildTest.kt | intellij-rust | 42,619,487 | false | {"Gradle Kotlin DSL": 2, "Java Properties": 5, "Markdown": 11, "TOML": 19, "Shell": 2, "Text": 124, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "XML": 140, "Kotlin": 2284, "INI": 3, "ANTLR": 1, "Rust": 362, "YAML": 131, "RenderScript": 1, "JSON": 6, "HTML": 198, "SVG": 136, "JFlex": 1, "Java": 1, "Python": 37} | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.mir
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.UsefulTestCase
import junit.framework.TestCase
import org.intellij.lang.annotations.Language
import org.junit.Test
import org.rust.ProjectDescriptor
import org.rust.RsTestBase
import org.rust.WithStdlibRustProjectDescriptor
import org.rust.lang.core.mir.schemas.*
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.RsFunction
import org.rust.stdext.singleOrFilter
import org.rust.stdext.toPath
import kotlin.io.path.absolutePathString
import kotlin.io.path.div
/**
* This mir representations are generated by rustc
* using `rustc -Z dump-mir=main src/main.rs`.
* There is a problem that you cannot disable all
* the optimizations (SimplifyCFG e.g.), so I am
* using slightly modified compiler
*/
@ProjectDescriptor(WithStdlibRustProjectDescriptor::class)
class MirBuildTest : RsTestBase() {
fun `test const pos constant`() = doTest()
fun `test static zero constant`() = doTest()
fun `test static mut neg constant`() = doTest()
fun `test const double neg constant`() = doTest()
fun `test static mut many parenthesis constant`() = doTest()
fun `test static mut many parenthesis and two neg constant`() = doTest()
fun `test static mut many parenthesis and many neg constant`() = doTest()
fun `test const way too many parenthesis and way too many neg constants`() = doTest()
fun `test const plus`() = doTest()
fun `test const minus`() = doTest()
fun `test const mul`() = doTest()
fun `test const shl`() = doTest()
fun `test const shr`() = doTest()
fun `test const div`() = doTest()
fun `test const rem`() = doTest()
fun `test const bitand`() = doTest()
fun `test const bitxor`() = doTest()
fun `test const bitor`() = doTest()
fun `test const complicated arith expr`() = doTest()
fun `test const lt`() = doTest()
fun `test const lteq`() = doTest()
fun `test const gt`() = doTest()
fun `test const gteq`() = doTest()
fun `test const eq`() = doTest()
fun `test const noteq`() = doTest()
fun `test const with block`() = doTest()
fun `test const with block with complicated arith expr`() = doTest()
fun `test const with block and simple if`() = doTest()
fun `test const boolean and`() = doTest()
fun `test const boolean or`() = doTest()
fun `test const boolean long logical`() = doTest()
fun `test unit type`() = doTest()
fun `test tuple fields simple`() = doTest()
fun `test tuple fields nested`() = doTest()
fun `test tuple fields temporary value`() = doTest()
fun `test three element tuple with tuples`() = doTest()
fun `test struct named fields simple`() = doTest()
fun `test struct named fields complex`() = doTest()
fun `test struct literal simple`() = doTest()
fun `test struct literal different fields order`() = doTest()
fun `test struct literal field shorthand`() = doTest()
fun `test struct literal nested 1`() = doTest()
fun `test struct literal nested 2`() = doTest()
fun `test enum variant literal simple`() = doTest()
fun `test enum variant literal complex`() = doTest()
fun `test tuple struct literals`() = doTest()
fun `test loop break`() = doTest()
fun `test block with let`() = doTest()
fun `test block with 3 lets`() = doTest()
fun `test if with else`() = doTest()
fun `test if without else`() = doTest()
fun `test if without else used as expr`() = doTest()
fun `test if let`() = doTest()
fun `test let mut and assign`() = doTest()
fun `test let mut and add assign`() = doTest()
fun `test let mut and add assign other variable`() = doTest()
fun `test let mut and multiple add assign`() = doTest()
fun `test immutable move`() = doTest()
fun `test mutable move`() = doTest()
fun `test immutable borrow`() = doTest()
fun `test empty function`() = doTest()
fun `test empty function with return ty`() = doTest()
fun `test mutable borrow`() = doTest()
fun `test empty let`() = doTest()
fun `test array`() = doTest()
fun `test repeat`() = doTest()
fun `test non-const zero repeat`() = doTest()
fun `test zero repeat`() = doTest()
fun `test expr stmt`() = doTest()
// TODO more terminator comments
fun `test function call without arguments`() = doTest()
fun `test function call with 1 copy argument`() = doTest()
fun `test function call with 2 copy arguments`() = doTest()
fun `test function call with 2 move arguments`() = doTest()
fun `test function call with return value`() = doTest()
fun `test nested function call`() = doTest()
fun `test associated function call without arguments`() = doTest()
fun `test method call with self receiver`() = doTest()
// TODO fix wrong order of drops
fun `test method call with ref self receiver`() = doTest()
fun `test deref`() = doTest()
fun `test deref and borrow`() = doTest()
@Test(expected = Throwable::class) // TODO support overloaded deref
fun `test overloaded deref`() = doTest()
fun `test index`() = doTest()
fun `test constant index`() = doTest()
fun `test function in impl`() = doTest()
fun `test while`() = expect<Throwable> { doTest() }
fun `test while count`() = expect<Throwable> { doTest() }
fun `test while let`() = expect<Throwable> { doTest() }
fun `test fun with args`() = doTest()
fun `test match pat binding 1`() = doTest()
fun `test match pat binding 2`() = doTest()
fun `test match single enum variant`() = doTest()
fun `test match enum variant without fields`() = doTest()
fun `test match enum variant with fields`() = doTest()
fun `test match enum variant fields pat rest`() = doTest()
fun `test match enum variant nested`() = doTest()
fun `test match pat wild`() = doTest()
fun `test match pat ident enum variant`() = doTest()
fun `test match pat tuple`() = doTest()
fun `test match pat struct for struct simple`() = doTest()
fun `test match pat struct for enum simple`() = doTest()
fun `test match pat struct complex`() = doTest()
fun `test match pat ref`() = doTest()
fun `test match pat ref mutable`() = doTest()
fun `test immutable self argument`() = doTest()
fun `test mutable self argument`() = doTest()
fun `test immutable ref self argument`() = doTest()
fun `test mutable ref self argument`() = doTest()
fun `test explicit self argument`() = doTest()
fun `test mut borrow adjustment`() = doTest()
fun `test range`() = doTest()
// TODO: more terminator comments
// TODO: `RangeInclusive::<i32>::new` instead of `new`
fun `test range inclusive`() = doTest()
fun `test cast i32 to i64`() = doTest()
fun `test path expr named const`() = doTest()
private fun doTest(fileName: String = "main.rs") {
val name = getTestName(true)
val codeFile = TEST_DATA_PATH / BASE_PATH / "$name.$RS_EXTENSION"
val mirFile = TEST_DATA_PATH / BASE_PATH / "$name.$MIR_EXTENSION"
doTest(
FileUtil.loadFile(codeFile.toFile()).trim(),
mirFile.absolutePathString(),
fileName,
)
}
private fun doTest(
@Language("Rust") code: String,
expectedFilePath: String,
fileName: String = "main.rs",
) {
InlineFile(code, fileName)
val builtMir = MirBuilder.build(myFixture.file as RsFile)
.singleOrFilter { it.sourceElement.let { fn -> fn is RsFunction && fn.name == "main" } }
.single()
val builtMirStr = MirPrettyPrinter(mir = builtMir).print()
UsefulTestCase.assertSameLinesWithFile(expectedFilePath, builtMirStr)
}
@Suppress("unused")
private fun test(
@Language("Rust") code: String,
mir: String,
fileName: String = "main.rs"
) {
InlineFile(code, fileName)
val builtMir = MirBuilder.build(myFixture.file as RsFile).single()
val buildMirStr = MirPrettyPrinter(mir = builtMir).print()
TestCase.assertEquals(mir, buildMirStr)
}
companion object {
private const val RS_EXTENSION = "rs"
private const val MIR_EXTENSION = "mir"
private val TEST_DATA_PATH = "src/test/resources".toPath()
private val BASE_PATH = "org/rust/lang/core/mir/fixtures".toPath()
}
}
| 1,841 | Kotlin | 380 | 4,528 | c6657c02bb62075bf7b7ceb84d000f93dda34dc1 | 8,501 | intellij-rust | MIT License |
code/Samples/app/src/main/java/com/ky/demo/util/AndroidUtils.kt | androidKy | 146,855,123 | false | null | package com.ky.demo.util
import android.util.Log
import java.io.BufferedReader
import java.io.InputStreamReader
/**
* description:
* author:kyXiao
* date:2019/5/27
*/
class AndroidUtils {
companion object {
private val TAG by lazy { AndroidUtils::class.java.simpleName }
fun getRunningProcess() {
val process = Runtime.getRuntime().exec("/system/bin/ps")
val bufferReader = BufferedReader(InputStreamReader(process.inputStream))
val sb = StringBuffer()
while (bufferReader.readLine() != null) {
sb.append(bufferReader.readLine() + "\n")
}
Log.i(TAG, "reader: $sb")
}
}
} | 0 | Kotlin | 0 | 0 | 44e060c1380a8c071939cb136facb744d7268adb | 700 | android-study-note | Apache License 2.0 |
src/test/java/com/vladsch/md/nav/editor/util/HtmlCompatibilityTest.kt | vsch | 32,095,357 | false | {"Kotlin": 2420465, "Java": 2294749, "HTML": 131988, "JavaScript": 68307, "CSS": 64158, "Python": 486} | /*
* Copyright (c) 2015-2019 Vladimir Schneider <[email protected]>
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.vladsch.md.nav.editor.util
import com.vladsch.md.nav.editor.jbcef.JBCefHtmlPanelProvider
import com.vladsch.md.nav.editor.resources.GitHubCollapseInCommentScriptProvider
import com.vladsch.md.nav.editor.resources.GitHubCollapseMarkdownScriptProvider
import com.vladsch.md.nav.editor.resources.HljsScriptProvider
import com.vladsch.md.nav.editor.resources.PrismScriptProvider
import org.junit.Assert.assertEquals
import org.junit.Test
import kotlin.test.assertTrue
class HtmlCompatibilityTest {
private val panel = "com.vladsch.md.nav.html.test.panel.provider"
private val resource = "com.vladsch.md.nav.html.test.css.provider"
val available = HtmlCompatibility(panel, 3f, 1f, 0f, arrayOf(), arrayOf())
@Test
fun test_Basic_Same() {
assertEquals("Same level or any failed", true, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 3f, 1f, 0f, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 3f, 1f, null, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 3f, null, 0f, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, null, 1f, 0f, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 3f, null, 0f, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, null, null, null, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, available.isForRequired(HtmlCompatibility(resource, 3f, 1f, 0f, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, available.isForRequired(HtmlCompatibility(resource, 3f, 1f, null, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, available.isForRequired(HtmlCompatibility(resource, 3f, null, 0f, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, available.isForRequired(HtmlCompatibility(resource, null, 1f, 0f, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, available.isForRequired(HtmlCompatibility(resource, 3f, null, 0f, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, available.isForRequired(HtmlCompatibility(resource, null, null, null, arrayOf(), arrayOf())))
assertEquals("Same level or any failed", true, HtmlCompatibility(resource, 3f, 1f, 0f, arrayOf(), arrayOf()).isForAvailable(available))
assertEquals("Same level or any failed", true, HtmlCompatibility(resource, 3f, 1f, null, arrayOf(), arrayOf()).isForAvailable(available))
assertEquals("Same level or any failed", true, HtmlCompatibility(resource, 3f, null, 0f, arrayOf(), arrayOf()).isForAvailable(available))
assertEquals("Same level or any failed", true, HtmlCompatibility(resource, null, 1f, 0f, arrayOf(), arrayOf()).isForAvailable(available))
assertEquals("Same level or any failed", true, HtmlCompatibility(resource, 3f, null, 0f, arrayOf(), arrayOf()).isForAvailable(available))
assertEquals("Same level or any failed", true, HtmlCompatibility(resource, null, null, null, arrayOf(), arrayOf()).isForAvailable(available))
}
@Test
fun test_Basic_NotCompatible() {
assertEquals("Not Compatible failed", false, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 3f, 3f, 0f, arrayOf(), arrayOf())))
assertEquals("Not Compatible failed", false, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 3f, 1f, 0.1f, arrayOf(), arrayOf())))
assertEquals("Not Compatible failed", false, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 3.1f, 1f, 0f, arrayOf(), arrayOf())))
assertEquals("Not Compatible failed", false, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 3.1f, null, null, arrayOf(), arrayOf())))
assertEquals("Not Compatible failed", false, available.isForRequired(HtmlCompatibility(resource, 3f, 3f, 0f, arrayOf(), arrayOf())))
assertEquals("Not Compatible failed", false, available.isForRequired(HtmlCompatibility(resource, 3f, 1f, 0.1f, arrayOf(), arrayOf())))
assertEquals("Not Compatible failed", false, available.isForRequired(HtmlCompatibility(resource, 3.1f, 1f, 0f, arrayOf(), arrayOf())))
assertEquals("Not Compatible failed", false, available.isForRequired(HtmlCompatibility(resource, 3.1f, null, null, arrayOf(), arrayOf())))
assertEquals("Not Compatible failed", false, HtmlCompatibility(resource, 3f, 3f, 0f, arrayOf(), arrayOf()).isForAvailable(available))
assertEquals("Not Compatible failed", false, HtmlCompatibility(resource, 3f, 1f, 0.1f, arrayOf(), arrayOf()).isForAvailable(available))
assertEquals("Not Compatible failed", false, HtmlCompatibility(resource, 3.1f, 1f, 0f, arrayOf(), arrayOf()).isForAvailable(available))
assertEquals("Not Compatible failed", false, HtmlCompatibility(resource, 3.1f, null, null, arrayOf(), arrayOf()).isForAvailable(available))
}
@Test
fun test_Basic_Compatible() {
assertEquals("Compatible failed", true, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 3f, 0.9f, 0f, arrayOf(), arrayOf())))
assertEquals("Compatible failed", true, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 3f, 1f, 0f, arrayOf(), arrayOf())))
assertEquals("Compatible failed", true, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 2.9f, 1f, 0f, arrayOf(), arrayOf())))
assertEquals("Compatible failed", true, HtmlCompatibility.isCompatibleWith(available, HtmlCompatibility(resource, 3f, 1f, null, arrayOf(), arrayOf())))
assertEquals("Compatible failed", true, available.isForRequired(HtmlCompatibility(resource, 3f, 0.9f, 0f, arrayOf(), arrayOf())))
assertEquals("Compatible failed", true, available.isForRequired(HtmlCompatibility(resource, 3f, 1f, 0f, arrayOf(), arrayOf())))
assertEquals("Compatible failed", true, available.isForRequired(HtmlCompatibility(resource, 2.9f, 1f, 0f, arrayOf(), arrayOf())))
assertEquals("Compatible failed", true, available.isForRequired(HtmlCompatibility(resource, 3f, 1f, null, arrayOf(), arrayOf())))
assertEquals("Compatible failed", true, HtmlCompatibility(resource, 3f, 0.9f, 0f, arrayOf(), arrayOf()).isForAvailable(available))
assertEquals("Compatible failed", true, HtmlCompatibility(resource, 3f, 1f, 0f, arrayOf(), arrayOf()).isForAvailable(available))
assertEquals("Compatible failed", true, HtmlCompatibility(resource, 2.9f, 1f, 0f, arrayOf(), arrayOf()).isForAvailable(available))
assertEquals("Compatible failed", true, HtmlCompatibility(resource, 3f, 1f, null, arrayOf(), arrayOf()).isForAvailable(available))
}
@Test
fun test_JavaFxJbCef_Compatible() {
val panel = JBCefHtmlPanelProvider.COMPATIBILITY
assertTrue(GitHubCollapseMarkdownScriptProvider.COMPATIBILITY.isForAvailable(panel))
assertTrue(GitHubCollapseInCommentScriptProvider.COMPATIBILITY.isForAvailable(panel))
assertTrue(HljsScriptProvider.COMPATIBILITY.isForAvailable(panel))
assertTrue(PrismScriptProvider.COMPATIBILITY.isForAvailable(panel))
}
}
| 134 | Kotlin | 131 | 809 | ec413c0e1b784ff7309ef073ddb4907d04345073 | 8,547 | idea-multimarkdown | Apache License 2.0 |
test-suite-kotlin-ksp/src/test/kotlin/io/micronaut/docs/aop/around/NotNullInterceptor.kt | micronaut-projects | 124,230,204 | false | null | /*
* Copyright 2017-2020 original 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 io.micronaut.docs.aop.around
// tag::imports[]
import io.micronaut.aop.MethodInterceptor
import io.micronaut.aop.MethodInvocationContext
import io.micronaut.core.type.MutableArgumentValue
import javax.inject.Singleton
import java.util.Objects
import java.util.Optional
// end::imports[]
// tag::interceptor[]
@Singleton
class NotNullInterceptor : MethodInterceptor<Any, Any> { // <1>
override fun intercept(context: MethodInvocationContext<Any, Any>): Any {
val nullParam = context.parameters
.entries
.stream()
.filter { entry ->
val argumentValue = entry.value
Objects.isNull(argumentValue.value)
}
.findFirst() // <2>
return if (nullParam.isPresent) {
throw IllegalArgumentException("Null parameter [" + nullParam.get().key + "] not allowed") // <3>
} else {
context.proceed() // <4>
}
}
}
// end::interceptor[]
| 753 | null | 1061 | 6,059 | c9144646b31b23bd3c4150dec8ddd519947e55cf | 1,613 | micronaut-core | Apache License 2.0 |
lib/src/main/java/me/jessyan/retrofiturlmanager/parser/SuperUrlParser.kt | genaku | 284,626,937 | true | {"Kotlin": 55405, "Java": 16706} | /*
* Copyright 2018 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.jessyan.retrofiturlmanager.parser
import me.jessyan.retrofiturlmanager.RetrofitUrlManager
import me.jessyan.retrofiturlmanager.cache.Cache
import me.jessyan.retrofiturlmanager.cache.LruCache
import okhttp3.HttpUrl
import java.util.*
/**
* ================================================
* 超级解析器
* 超级模式属于高级模式的加强版, 优先级高于高级模式, 在高级模式中, 需要传入一个 BaseUrl (您传入 Retrofit 的 BaseUrl) 作为被替换的基准
* 如这个传入的 BaseUrl 为 "https://www.github.com/wiki/part" (PathSize = 2), 那框架会将所有需要被替换的 Url 中的 域名 以及 域名 后面的前两个 pathSegments
* 使用您传入 [RetrofitUrlManager.putDomain] 方法的 Url 替换掉
* 但如果突然有一小部分的 Url 只想将 "https://www.github.com/wiki" (PathSize = 1) 替换掉, 后面的 pathSegment '/part' 想被保留下来
* 这时项目中就出现了多个 PathSize 不同的需要被替换的 BaseUrl
*
*
* 使用高级模式实现这种需求略显麻烦, 所以我创建了超级模式, 让每一个 Url 都可以随意指定不同的 BaseUrl (PathSize 自己定) 作为被替换的基准
* 使 RetrofitUrlManager 可以从容应对各种复杂的需求
*
*
* 超级模式也需要手动开启, 但与高级模式不同的是, 开启超级模式并不需要调用 API, 只需要在 Url 中加入 [RetrofitUrlManager.IDENTIFICATION_PATH_SIZE] + PathSize
*
*
* 替换规则如下:
* 1.
* 旧 URL 地址为 https://www.github.com/wiki/part#baseurl_path_size=1, #baseurl_path_size=1 表示其中 BaseUrl 为 https://www.github.com/wiki
* 您调用 [RetrofitUrlManager.putDomain]方法传入的 URL 地址是 https://www.google.com/api
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/part
*
*
* 2.
* 旧 URL 地址为 https://www.github.com/wiki/part#baseurl_path_size=1, #baseurl_path_size=1 表示其中 BaseUrl 为 https://www.github.com/wiki
* 您调用 [RetrofitUrlManager.putDomain]方法传入的 URL 地址是 https://www.google.com
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/part
*
*
* 3.
* 旧 URL 地址为 https://www.github.com/wiki/part#baseurl_path_size=0, #baseurl_path_size=0 表示其中 BaseUrl 为 https://www.github.com
* 您调用 [RetrofitUrlManager.putDomain]方法传入的 URL 地址是 https://www.google.com/api
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/wiki/part
*
*
* 4.
* 旧 URL 地址为 https://www.github.com/wiki/part/issues/1#baseurl_path_size=3, #baseurl_path_size=3 表示其中 BaseUrl 为 https://www.github.com/wiki/part/issues
* 您调用 [RetrofitUrlManager.putDomain]方法传入的 URL 地址是 https://www.google.com/api
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/1
*
* @see UrlParser
* Created by JessYan on 2018/6/21 16:41
* [Contact me](mailto:<EMAIL>)
* [Follow me](https://github.com/JessYanCoding)
* ================================================
*/
class SuperUrlParser : UrlParser {
private var mCache: Cache<String, String?> = LruCache(100)
override fun parseUrl(domainUrl: HttpUrl, url: HttpUrl): HttpUrl {
val builder = url.newBuilder()
val pathSize = resolvePathSize(url, builder)
val key = getKey(domainUrl, url, pathSize)
val cashedUrl = mCache[key]
if (cashedUrl.isNullOrBlank()) {
for (i in 0 until url.pathSize) {
//当删除了上一个 index, PathSegment 的 item 会自动前进一位, 所以 remove(0) 就好
builder.removePathSegment(0)
}
val newPathSegments: MutableList<String> = ArrayList()
newPathSegments.addAll(domainUrl.encodedPathSegments)
if (url.pathSize > pathSize) {
val encodedPathSegments = url.encodedPathSegments
for (i in pathSize until encodedPathSegments.size) {
newPathSegments.add(encodedPathSegments[i])
}
} else require(url.pathSize >= pathSize) {
String.format(
"Your final path is %s, the pathSize = %d, but the #baseurl_path_size = %d, #baseurl_path_size must be less than or equal to pathSize of the final path",
url.scheme + "://" + url.host + url.encodedPath, url.pathSize, pathSize)
}
for (PathSegment in newPathSegments) {
builder.addEncodedPathSegment(PathSegment)
}
} else {
builder.encodedPath(cashedUrl)
}
val httpUrl = builder
.scheme(domainUrl.scheme)
.host(domainUrl.host)
.port(domainUrl.port)
.build()
if (mCache[key].isNullOrBlank()) {
mCache.put(key, httpUrl.encodedPath)
}
return httpUrl
}
private fun getKey(domainUrl: HttpUrl, url: HttpUrl, pathSize: Int): String =
domainUrl.encodedPath + url.encodedPath + pathSize
private fun resolvePathSize(httpUrl: HttpUrl, builder: HttpUrl.Builder): Int {
val fragment = httpUrl.fragment ?: ""
var pathSize = 0
val newFragment = StringBuffer()
if (fragment.indexOf("#") == -1) {
val split = fragment.split("=".toRegex()).toTypedArray()
if (split.size > 1) {
pathSize = split[1].toInt()
}
} else {
if (fragment.indexOf(RetrofitUrlManager.IDENTIFICATION_PATH_SIZE) == -1) {
val index = fragment.indexOf("#")
newFragment.append(fragment.substring(index + 1, fragment.length))
val split = fragment.substring(0, index).split("=".toRegex()).toTypedArray()
if (split.size > 1) {
pathSize = split[1].toInt()
}
} else {
val split = fragment.split(RetrofitUrlManager.IDENTIFICATION_PATH_SIZE.toRegex()).toTypedArray()
newFragment.append(split[0])
if (split.size > 1) {
val index = split[1].indexOf("#")
if (index != -1) {
newFragment.append(split[1].substring(index, split[1].length))
val substring = split[1].substring(0, index)
if (!substring.isBlank()) {
pathSize = substring.toInt()
}
} else {
pathSize = split[1].toInt()
}
}
}
}
if (newFragment.toString().isBlank()) {
builder.fragment(null)
} else {
builder.fragment(newFragment.toString())
}
return pathSize
}
} | 0 | Kotlin | 0 | 0 | f9a4fb5b752bc68cfc956a359e227963f6fb7bed | 6,647 | RetrofitUrlManager | Apache License 2.0 |
pico-automator/src/main/java/com/github/aivanovski/picoautomator/domain/steps/AssertVisible.kt | aivanovski | 691,067,002 | false | {"Kotlin": 96751} | package com.github.aivanovski.picoautomator.domain.steps
import com.github.aivanovski.picoautomator.data.adb.AdbExecutor
import com.github.aivanovski.picoautomator.data.adb.command.GetUiTreeCommand
import com.github.aivanovski.picoautomator.domain.entity.Either
import com.github.aivanovski.picoautomator.domain.entity.ElementReference
import com.github.aivanovski.picoautomator.extensions.findNode
import com.github.aivanovski.picoautomator.extensions.matches
import com.github.aivanovski.picoautomator.extensions.toReadableFormat
internal class AssertVisible(
private val parentElement: ElementReference?,
private val elements: List<ElementReference>
) : ExecutableFlowStep<Unit>, FlakyFlowStep {
override fun describe(): String {
return when {
parentElement != null -> {
String.format(
"Assert is visible: inside [%s] -> %s",
parentElement.toReadableFormat(),
elements.toReadableFormat()
)
}
else -> "Assert is visible: ${elements.toReadableFormat()}"
}
}
override fun execute(adbExecutor: AdbExecutor): Either<Exception, Unit> {
val getUiTreeResult = adbExecutor.execute(GetUiTreeCommand())
if (getUiTreeResult.isLeft()) {
return getUiTreeResult.mapToLeft()
}
val rootNote = getUiTreeResult.unwrap()
val nodeToLookup = if (parentElement == null) {
rootNote
} else {
val parentNode = rootNote.findNode { node -> node.matches(parentElement) }
?: return Either.Left(Exception("Unable to find parent element: $parentElement"))
parentNode
}
for (element in elements) {
val node = nodeToLookup.findNode { node -> node.matches(element) }
if (node == null) {
return Either.Left(Exception("Unable to find element: $element"))
}
}
return Either.Right(Unit)
}
} | 1 | Kotlin | 0 | 0 | 75b47d8207239b5d6d30fee09949a999c5901655 | 2,028 | pico-automator | Apache License 2.0 |
src/main/kotlin/io/runescript/plugin/lang/psi/refs/RsDynamicExpressionReference.kt | waleedyaseen | 642,509,853 | false | {"Kotlin": 348987, "Java": 258240, "Lex": 11777, "HTML": 1047} | package io.runescript.plugin.lang.psi.refs
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StubIndex
import io.runescript.plugin.lang.psi.RsDynamicExpression
import io.runescript.plugin.lang.psi.RsScript
import io.runescript.plugin.lang.psi.scope.RsLocalVariableResolver
import io.runescript.plugin.lang.psi.scope.RsResolveMode
import io.runescript.plugin.lang.psi.scope.RsScopesUtil
import io.runescript.plugin.lang.psi.type.RsPrimitiveType
import io.runescript.plugin.lang.psi.type.RsType
import io.runescript.plugin.lang.psi.type.type
import io.runescript.plugin.lang.stubs.index.RsCommandScriptIndex
import io.runescript.plugin.symbollang.psi.index.RsSymbolIndex
class RsDynamicExpressionReference(element: RsDynamicExpression) : PsiPolyVariantReferenceBase<RsDynamicExpression>(element, element.nameLiteral.textRangeInParent) {
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
return resolveElement(element, element.type)
}
override fun getVariants(): Array<out LookupElement> = LookupElement.EMPTY_ARRAY
override fun handleElementRename(newElementName: String): PsiElement {
return element.setName(newElementName)
}
companion object {
fun resolveElement(element: RsDynamicExpression, type: RsType): Array<ResolveResult> {
val elementName = element.nameLiteral.text
// Try to resolve the element as a local array reference.
val localArrayResolver = RsLocalVariableResolver(elementName, RsResolveMode.Arrays)
RsScopesUtil.walkUpScopes(localArrayResolver, ResolveState.initial(), element)
val localArray = localArrayResolver.declaration
if (localArray != null) {
return arrayOf(PsiElementResolveResult(localArray))
}
// Try to resolve the element as a config reference.
val project = element.project
if (type is RsPrimitiveType) {
val resolvedConfig = RsSymbolIndex.lookup(project, type, elementName)
if (resolvedConfig != null) {
return arrayOf(PsiElementResolveResult(resolvedConfig))
}
}
// Try to resolve the element as a command reference.
val searchScope = GlobalSearchScope.allScope(project)
return StubIndex.getElements(RsCommandScriptIndex.KEY, elementName, project, searchScope, RsScript::class.java)
.map { PsiElementResolveResult(it) }
.toTypedArray()
}
}
} | 7 | Kotlin | 1 | 0 | 95deed024eaaed860e616b8ee46a30664c9a0793 | 2,669 | intellij-runescript | MIT License |
actions/src/git/git_status_opt_t.kt | hubvd | 388,790,188 | false | {"Kotlin": 250616, "Python": 22012, "Shell": 7638, "JavaScript": 922} | @file:Suppress("ClassName", "ktlint:standard:filename")
package com.github.hubvd.odootools.actions.git
enum class git_status_opt_t(val value: Int) {
GIT_STATUS_OPT_INCLUDE_UNTRACKED(1 shl 0),
GIT_STATUS_OPT_INCLUDE_IGNORED(1 shl 1),
GIT_STATUS_OPT_INCLUDE_UNMODIFIED(1 shl 2),
GIT_STATUS_OPT_EXCLUDE_SUBMODULES(1 shl 3),
GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS(1 shl 4),
GIT_STATUS_OPT_DISABLE_PATHSPEC_MATCH(1 shl 5),
GIT_STATUS_OPT_RECURSE_IGNORED_DIRS(1 shl 6),
GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX(1 shl 7),
GIT_STATUS_OPT_RENAMES_INDEX_TO_WORKDIR(1 shl 8),
GIT_STATUS_OPT_SORT_CASE_SENSITIVELY(1 shl 9),
GIT_STATUS_OPT_SORT_CASE_INSENSITIVELY(1 shl 10),
GIT_STATUS_OPT_RENAMES_FROM_REWRITES(1 shl 11),
GIT_STATUS_OPT_NO_REFRESH(1 shl 12),
GIT_STATUS_OPT_UPDATE_INDEX(1 shl 13),
GIT_STATUS_OPT_INCLUDE_UNREADABLE(1 shl 14),
GIT_STATUS_OPT_INCLUDE_UNREADABLE_AS_UNTRACKED(1 shl 15),
}
| 0 | Kotlin | 5 | 5 | d2d925c3b45161754c5dcafaaae2ba287ba4d86a | 952 | odoo-tools | MIT License |
src/main/kotlin/dev/bitflow/kfox/context/ButtonContext.kt | WinteryFox | 475,625,210 | false | {"Kotlin": 74517} | package dev.bitflow.kfox.context
import dev.bitflow.kfox.KFox
import dev.bitflow.kfox.data.ComponentRegistry
import dev.kord.core.Kord
import dev.kord.core.behavior.interaction.response.EphemeralMessageInteractionResponseBehavior
import dev.kord.core.behavior.interaction.response.PublicMessageInteractionResponseBehavior
import dev.kord.core.event.interaction.ButtonInteractionCreateEvent
open class ButtonContext<T>(
kord: Kord,
kfox: KFox<T, *>,
translationModule: String,
@Suppress("unused")
event: ButtonInteractionCreateEvent,
source: T,
registry: ComponentRegistry
) : ComponentContext<T>(kord, kfox, translationModule, event, source, null, registry)
class PublicButtonContext<T>(
kord: Kord,
kfox: KFox<T, *>,
translationModule: String,
@Suppress("unused")
override val response: PublicMessageInteractionResponseBehavior,
event: ButtonInteractionCreateEvent,
source: T,
registry: ComponentRegistry
) : ButtonContext<T>(kord, kfox, translationModule, event, source, registry)
class EphemeralButtonContext<T>(
kord: Kord,
kfox: KFox<T, *>,
translationModule: String,
@Suppress("unused")
override val response: EphemeralMessageInteractionResponseBehavior,
event: ButtonInteractionCreateEvent,
source: T,
registry: ComponentRegistry
) : ButtonContext<T>(kord, kfox, translationModule, event, source, registry)
| 0 | Kotlin | 0 | 4 | b6fc0b280468f52f9126bb015430cea3bfbffcc2 | 1,410 | KFox | Apache License 2.0 |
app/src/main/java/com/vobbla16/mesh/domain/repository/MeshRepository.kt | x3lfyn | 654,997,267 | false | null | package com.vobbla16.mesh.domain.repository
import com.vobbla16.mesh.common.structures.OrLoading
import com.vobbla16.mesh.common.structures.Resource
import com.vobbla16.mesh.domain.model.acadYears.AcademicYearItemModel
import com.vobbla16.mesh.domain.model.classmates.ClassmateModel
import com.vobbla16.mesh.domain.model.homework.HomeworkItemsForDateModel
import com.vobbla16.mesh.domain.model.lessonInfo.LessonInfoModel
import com.vobbla16.mesh.domain.model.marks.MarksSubjectModel
import com.vobbla16.mesh.domain.model.profile.ProfileModel
import com.vobbla16.mesh.domain.model.ratingClass.anon.PersonRatingModel
import com.vobbla16.mesh.domain.model.schedule.LessonType
import com.vobbla16.mesh.domain.model.schedule.ScheduleModel
import kotlinx.coroutines.flow.Flow
import kotlinx.datetime.LocalDate
import java.util.*
interface MeshRepository {
suspend fun getProfile(): Flow<OrLoading<Resource<ProfileModel>>>
suspend fun getSchedule(
studentId: Long,
date: LocalDate
): Flow<OrLoading<Resource<ScheduleModel>>>
suspend fun getAcademicYears(): Flow<OrLoading<Resource<List<AcademicYearItemModel>>>>
suspend fun getMarksReport(
studentId: Long,
academicYear: AcademicYearItemModel
): Flow<OrLoading<Resource<List<MarksSubjectModel>>>>
suspend fun getHomework(
studentId: Long,
week: LocalDate
): Flow<OrLoading<Resource<List<HomeworkItemsForDateModel>>>>
suspend fun getLessonInfo(
studentId: Long,
lessonId: Long,
educationType: LessonType
): Flow<OrLoading<Resource<LessonInfoModel>>>
suspend fun getClassmates(
classUnitId: Long
): Flow<OrLoading<Resource<List<ClassmateModel>>>>
suspend fun getRatingClass(
personId: UUID,
date: LocalDate
): Flow<OrLoading<Resource<List<PersonRatingModel>>>>
} | 5 | null | 1 | 6 | f4e73600627cd792569ffbf64e335ec8b9edec08 | 1,864 | libremesh | MIT License |
app/src/main/java/com/puutaro/commandclick/proccess/edit/edit_text_support_view/lib/DragSortListViewProducer.kt | puutaro | 596,852,758 | false | null | package com.puutaro.commandclick.proccess.edit.edit_text_support_view.lib
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Canvas
import android.view.Gravity
import android.widget.Button
import android.widget.LinearLayout
import android.widget.Toast
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.puutaro.commandclick.R
import com.puutaro.commandclick.common.variable.edit.EditParameters
import com.puutaro.commandclick.component.adapter.DragSortRecyclerAdapter
import com.puutaro.commandclick.fragment.EditFragment
import com.puutaro.commandclick.fragment_lib.edit_fragment.variable.EditTextSupportViewId
import com.puutaro.commandclick.proccess.edit.lib.ButtonSetter
import com.puutaro.commandclick.util.FileSystems
import com.puutaro.commandclick.util.ReadText
import java.io.File
object DragSortListViewProducer {
private val dataset: MutableList<String> = mutableListOf()
private var alertDialog: AlertDialog? = null
private val dragSortButtonLabel = "DST"
fun make(
editFragment: EditFragment,
editParameters: EditParameters,
currentComponentIndex: Int,
weight: Float,
): Button {
val currentFragment = editParameters.currentFragment
val context = editParameters.context
val currentId = editParameters.currentId
val linearParamsForDragSortListView = LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.MATCH_PARENT,
)
linearParamsForDragSortListView.weight = weight
val curSetValMap = editParameters.setVariableMap
val elsbMap = ListContentsSelectSpinnerViewProducer.getElsbMap(
editParameters,
currentComponentIndex
)
val listContentsFilePath = ListContentsSelectSpinnerViewProducer.getListPath(
elsbMap,
)
val fileObj = File(listContentsFilePath)
val parentDir = fileObj.parent ?: String()
val listFileName = fileObj.name
FileSystems.createDirs(parentDir)
val dragSortListViewButtonView = Button(context)
dragSortListViewButtonView.layoutParams = linearParamsForDragSortListView
dragSortListViewButtonView.id = currentId + EditTextSupportViewId.EDITABLE_GRID.id
dragSortListViewButtonView.tag = "gridEdit${currentId + EditTextSupportViewId.EDITABLE_GRID.id}"
dragSortListViewButtonView.text = dragSortButtonLabel
ButtonSetter.set(
context,
dragSortListViewButtonView
)
dragSortListViewButtonView.setOnClickListener {
buttonView ->
val buttonContext = buttonView.context
val dragSortList = ReadText(
parentDir,
listFileName
).textToList().filter {
it.trim().isNotEmpty()
}
val dragSortListView = createListView(
buttonContext,
dragSortList
)
alertDialog = AlertDialog.Builder(
buttonContext
)
.setTitle("Sort by drag, or remove by swipe")
.setView(dragSortListView)
.setPositiveButton("OK", DialogInterface.OnClickListener {
dialog, which ->
FileSystems.writeFile(
parentDir,
listFileName,
dataset.joinToString("\n")
)
})
.setNegativeButton("NO", null)
.show()
alertDialog?.getButton(DialogInterface.BUTTON_POSITIVE)?.setTextColor(
context?.getColor(android.R.color.black) as Int
)
alertDialog?.getButton(DialogInterface.BUTTON_NEGATIVE)?.setTextColor(
context?.getColor(android.R.color.black) as Int
)
alertDialog?.window?.setGravity(Gravity.BOTTOM)
alertDialog?.setOnCancelListener(object : DialogInterface.OnCancelListener {
override fun onCancel(dialog: DialogInterface?) {
alertDialog?.dismiss()
}
})
}
return dragSortListViewButtonView
}
private fun createListView(
context: Context,
dragSortList: List<String>,
): RecyclerView {
val recyclerView = RecyclerView(context)
recyclerView.setHasFixedSize(true)
val layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(context)
recyclerView.layoutManager = layoutManager
dataset.clear()
dataset.addAll(dragSortList.toMutableList())
val dragSortRecyclerAdapter = DragSortRecyclerAdapter(
dataset
)
// dragSortRecyclerAdapter.itemClickListener = object : DragSortRecyclerAdapter.OnItemClickListener{
// override fun onItemClick(holder: DragSortRecyclerAdapter.ViewHolder) {
// alertDialog?.dismiss()
// val _mesg = holder.textView.text
// val _position = dataset.indexOf(_mesg)
// Toast.makeText(
// context,
// "LongClick Pos=${_position} Mesg=\"${_mesg}\"",
// Toast.LENGTH_LONG
// ).show()
// }
// }
recyclerView.adapter = dragSortRecyclerAdapter
val itemDecoration: ItemDecoration =
DividerItemDecoration(
context,
DividerItemDecoration.VERTICAL
)
recyclerView.addItemDecoration(itemDecoration)
setItemTouchHelper(
context,
recyclerView,
dragSortRecyclerAdapter,
)
return recyclerView
}
private fun setItemTouchHelper(
context: Context,
recyclerView: RecyclerView,
dragSortRecyclerAdapter: DragSortRecyclerAdapter,
){
var moveTimes = 0
var fromPos = 0
var toPos = 0
var insertItem = String()
val mIth = ItemTouchHelper(
object : ItemTouchHelper.SimpleCallback(
ItemTouchHelper.UP or ItemTouchHelper.DOWN,
ItemTouchHelper.LEFT
) {
override fun onChildDraw(
c: Canvas,
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean
) {
when (isCurrentlyActive) {
true -> viewHolder.itemView.setBackgroundColor(
context.getColor(R.color.gray_out)
)
else -> {
activeStateFinishedHandler(
context,
viewHolder
)
}
}
super.onChildDraw(
c,
recyclerView,
viewHolder,
dX,
dY,
actionState,
isCurrentlyActive
)
}
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
if(
moveTimes == 0
) {
fromPos = viewHolder.bindingAdapterPosition
insertItem = dataset[fromPos]
}
toPos = target.bindingAdapterPosition
moveTimes++
return true // true if moved, false otherwise
}
override fun onSwiped(
viewHolder: RecyclerView.ViewHolder,
direction: Int
) {
if(
direction != ItemTouchHelper.LEFT
) return
val position = viewHolder.absoluteAdapterPosition
dataset.removeAt(position)
dragSortRecyclerAdapter.notifyDataSetChanged()
}
private fun activeStateFinishedHandler(
context: Context,
viewHolder: RecyclerView.ViewHolder,
){
viewHolder.itemView.setBackgroundColor(
context.getColor(R.color.white)
)
if(moveTimes > 0){
dataset.removeAt(fromPos)
dataset.add(toPos, insertItem)
}
moveTimes = 0
dragSortRecyclerAdapter.notifyDataSetChanged()
}
})
mIth.attachToRecyclerView(recyclerView)
}
} | 2 | Kotlin | 1 | 36 | b2e17401ae2d7d81b4aaf6b80c204b8bdb0e80c1 | 9,403 | CommandClick | MIT License |
modules/views-coroutines-material/src/androidMain/kotlin/splitties/views/coroutines/material/FloatingActionButton.kt | LouisCAD | 65,558,914 | false | null | /*
* Copyright 2019 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.views.coroutines.material
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
/**
* Enables this [FloatingActionButton], shows it, waits for the user to click it, and finally
* disables it and hides it. This function is cancellable.
*
* Uses the [FloatingActionButton.show] and [FloatingActionButton.hide] functions which animate
* the FAB when changing its visibility.
*
* If [disableAfterClick] is set to `false`, the enabled state of this [FloatingActionButton] will
* be left unchanged.
*/
suspend fun FloatingActionButton.showAndAwaitOneClickThenHide(
disableAfterClick: Boolean = true
) = try {
if (disableAfterClick) isEnabled = true
show()
suspendCancellableCoroutine<Unit> { continuation ->
setOnClickListener {
setOnClickListener(null)
continuation.resume(Unit)
}
}
} finally {
setOnClickListener(null)
if (disableAfterClick) isEnabled = false
hide()
}
| 53 | null | 160 | 2,476 | 1ed56ba2779f31dbf909509c955fce7b9768e208 | 1,172 | Splitties | Apache License 2.0 |
uicomponent-compose/main/src/test/java/ExampleUnitTest.kt | DroidKaigi | 283,062,475 | false | null | import org.junit.Assert
import org.junit.Test
class ExampleUnitTest {
/**
* For fixing build error
* * What went wrong:
* Execution failed for task ':uicomponent-compose:main:transformDebugUnitTestClassesWithAsm'.
* > java.nio.file.NoSuchFileException:
/home/runner/work/conference-app-2021/conference-app-2021/uicomponent-compose/main/build/tmp/kotlin-classes/debugUnitTest
*/
@Test
fun addition_isCorrect() {
Assert.assertEquals(4, (2 + 2).toLong())
}
}
| 45 | Kotlin | 189 | 633 | 3fb47a7b7b245e5a7c7c66d6c18cb7d2a7b295f2 | 511 | conference-app-2021 | Apache License 2.0 |
common/common_base/src/main/java/com/cl/common_base/bean/RichTextData.kt | alizhijun | 528,318,389 | false | null | package com.cl.common_base.bean
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.cl.common_base.BaseBean
import com.google.gson.annotations.SerializedName
data class RichTextData(
val flushingWeigh: String? = null, // 冲刷期重量
val name: String? = null, // 文档名称
val txtId: String? = null, // 文本ID
val testType: String? = null, // 文本ID
val bar: String? = null, // 文本标题
val page: MutableList<Page>? = null,
val topPage: MutableList<TopPage>? = null,
) : BaseBean() {
data class Page(
val id: String? = null,
val type: String? = null,
val value: Value? = null,
var videoTag: Boolean = false,
var videoPosition: Long? = null,
) : BaseBean(), MultiItemEntity {
override val itemType: Int
get() = when (type) {
"Bar" -> KEY_TYPE_BAR
"title" -> KEY_TYPE_TITLE
"txt" -> KEY_TYPE_TXT
"picture" -> KEY_TYPE_PICTURE
"url" -> KEY_TYPE_URL
"video" -> KEY_TYPE_VIDEO
"pageDown" -> KEY_TYPE_PAGE_DOWN
"pageClose" -> KEY_TYPE_PAGE_CLOSE
"customerService" -> KEY_TYPE_CUSTOMER_SERVICE
"imageTextJump" -> KEY_TYPE_IMAGE_TEXT_JUMP
"Discord" -> KEY_TYPE_DISCORD
"finishTask" -> KEY_TYPE_FINISH_TASK
"flushingWeigh" -> KEY_TYPE_FLUSHING_WEIGH
"dryingWeigh" -> KEY_TYPE_DRYING_WEIGH
"buttonJump" -> KEY_TYPE_BUTTON_JUMP
"option" -> KEY_TYPE_CHECK_BOX
else -> KEY_TYPE_BAR
}
}
data class TopPage(
val id: String? = null,
val type: String? = null,
val value: Value? = null,
)
data class Value(
val height: String? = null, // 高度
val taskCategory: String? = null, // 任务种类
val taskId: String? = null, // 任务ID
val taskType: String? = null, // 任务类型
val title: String? = null, // 标题
val top: String? = null, // 是否悬浮
val txt: String? = null, // 文本
val txtId: String? = null, // 文本ID
val url: String? = null, // URL
val width: String? = null, // 宽度
val icon: String? = null, // 按钮图标
val autoplay: Boolean? = null, // 自动播放
var isCheck: Boolean? = false, // 是否选中
@SerializedName("colour")
var color: String? = null, // 字体颜色
var size: String? = null, // 字体大小
@SerializedName("textAlign")
var left: String? = null, // 左边距
var bold: Boolean? = false, // 字体是否加粗
var bolds: MutableList<String>? = null,
) : BaseBean()
companion object {
// 这是Activity页面的标题
const val KEY_TYPE_BAR = 1
// 这是内容的标题
const val KEY_TYPE_TITLE = 2
// 这是内容文本
const val KEY_TYPE_TXT = 3
// 图片
const val KEY_TYPE_PICTURE = 4
// 设置视频的url类型、以文本的形式展示
const val KEY_TYPE_URL = 5
// 这是视频展示类型、以视频样式展示
const val KEY_TYPE_VIDEO = 6
// 跳下页
const val KEY_TYPE_PAGE_DOWN = 7
// 关闭本页
const val KEY_TYPE_PAGE_CLOSE = 8
// 客服类型
const val KEY_TYPE_CUSTOMER_SERVICE = 9
// 图文跳转
const val KEY_TYPE_IMAGE_TEXT_JUMP = 10
// Discord 类型
const val KEY_TYPE_DISCORD = 11
// 任务完成
const val KEY_TYPE_FINISH_TASK = 12
// 清洗期
const val KEY_TYPE_FLUSHING_WEIGH = 13
// 干燥器重量
const val KEY_TYPE_DRYING_WEIGH = 14
// 跳转到webView
const val KEY_TYPE_BUTTON_JUMP = 15
// 设置checkbox勾选项类型
const val KEY_TYPE_CHECK_BOX = 16
// 设置文本类型
const val KEY_TYPE_PAGE_TXT = 17
// 自己创建的类型
// 与商民的无关
const val KEY_BAR = "Bar"
}
} | 0 | Kotlin | 0 | 0 | e2de221f77fc9e2e0237570252aa4985b002d91d | 3,848 | abby | Apache License 2.0 |
app/src/main/java/io/github/gusandrianos/foxforreddit/data/models/ChildrenItem.kt | idalez | 288,726,149 | false | {"Java": 261363, "Kotlin": 161585} | package io.github.gusandrianos.foxforreddit.data.models
import com.google.gson.annotations.SerializedName
class ChildrenItem(val loadMoreChild: String) {
@SerializedName("data")
val data: CommentData? = null
@SerializedName("kind")
val kind: String? = null
} | 1 | null | 1 | 1 | a35f0675f322d366a6270dbc4e2d5ccda6580fe9 | 277 | fox-for-reddit | MIT License |
src/main/kotlin/no/nav/meldeplikt/meldekortservice/service/SoapService.kt | navikt | 207,759,254 | false | null | package no.nav.meldeplikt.meldekortservice.service
import no.aetat.arena.mk_meldekort_kontrollert.MeldekortKontrollertType
import no.nav.meldeplikt.meldekortservice.model.WeblogicPing
import no.nav.meldeplikt.meldekortservice.model.meldekortdetaljer.Meldekortdetaljer
interface SoapService {
fun kontrollerMeldekort(meldekortdetaljer: Meldekortdetaljer): MeldekortKontrollertType
fun pingWeblogic(): WeblogicPing
} | 0 | Kotlin | 1 | 0 | 982e896d5b98ff1cf0abf8fcc58b2a7f7bde8e87 | 424 | meldekortservice | MIT License |
app/src/main/java/com/cyl/musiclake/ui/music/playqueue/PlayQueueAdapter.kt | caiyonglong | 55,852,788 | false | null | package com.cyl.musiclake.ui.music.playqueue
import androidx.core.content.ContextCompat
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.BaseItemDraggableAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.cyl.musiclake.R
import com.cyl.musiclake.api.music.MusicApi
import com.cyl.musiclake.common.Constants
import com.cyl.musiclake.bean.Music
import com.cyl.musiclake.player.PlayManager
import com.cyl.musiclake.ui.theme.ThemeStore
import com.cyl.musiclake.utils.ConvertUtils
import com.cyl.musiclake.utils.CoverLoader
import com.cyl.musiclake.utils.ToastUtils
import org.jetbrains.anko.dip
/**
* Created by D22434 on 2017/9/26.ß
*/
class PlayQueueAdapter(musicList: List<Music>) : BaseItemDraggableAdapter<Music, BaseViewHolder>(R.layout.item_play_queue, musicList) {
override fun convert(holder: BaseViewHolder, item: Music) {
CoverLoader.loadImageView(mContext, item.coverUri, holder.getView(R.id.iv_cover))
holder.setText(R.id.tv_title, ConvertUtils.getTitle(item.title))
//音质图标显示
val quality = when {
item.sq -> mContext.resources.getDrawable(R.drawable.sq_icon, null)
item.hq -> mContext.resources.getDrawable(R.drawable.hq_icon, null)
else -> null
}
quality?.let {
quality.setBounds(0, 0, quality.minimumWidth + mContext.dip(2), quality.minimumHeight)
holder.getView<TextView>(R.id.tv_artist).setCompoundDrawables(quality, null, null, null)
}
//设置歌手专辑名
holder.setText(R.id.tv_artist, ConvertUtils.getArtistAndAlbum(item.artist, item.album))
//设置播放状态
if (PlayManager.getPlayingId() == item.mid) {
holder.getView<View>(R.id.v_playing).visibility = View.VISIBLE
holder.setTextColor(R.id.tv_title, ContextCompat.getColor(mContext, R.color.app_green))
holder.setTextColor(R.id.tv_artist, ContextCompat.getColor(mContext, R.color.app_green))
} else {
if (ThemeStore.THEME_MODE == ThemeStore.DAY) {
holder.setTextColor(R.id.tv_title, ContextCompat.getColor(mContext, R.color.black))
} else {
holder.setTextColor(R.id.tv_title, ContextCompat.getColor(mContext, R.color.white))
}
holder.getView<View>(R.id.v_playing).visibility = View.GONE
holder.setTextColor(R.id.tv_artist, ContextCompat.getColor(mContext, R.color.grey))
}
holder.addOnClickListener(R.id.iv_more)
if (item.isCp) {
holder.setTextColor(R.id.tv_title, ContextCompat.getColor(mContext, R.color.grey))
holder.setTextColor(R.id.tv_artist, ContextCompat.getColor(mContext, R.color.grey))
}
if (item.type == Constants.LOCAL) {
holder.getView<View>(R.id.iv_resource).visibility = View.GONE
} else {
holder.getView<View>(R.id.iv_resource).visibility = View.VISIBLE
when {
item.type == Constants.BAIDU -> {
holder.setImageResource(R.id.iv_resource, R.drawable.baidu)
}
item.type == Constants.NETEASE -> {
holder.setImageResource(R.id.iv_resource, R.drawable.netease)
}
item.type == Constants.QQ -> {
holder.setImageResource(R.id.iv_resource, R.drawable.qq)
}
item.type == Constants.XIAMI -> {
holder.setImageResource(R.id.iv_resource, R.drawable.xiami)
}
}
}
if (item.coverUri != null) {
CoverLoader.loadImageView(mContext, item.coverUri, holder.getView(R.id.iv_cover))
}
if (item.coverUri.isNullOrEmpty()) {
//加载歌曲专辑图
item.title?.let {
MusicApi.getMusicAlbumPic(item.title.toString(), success = {
item.coverUri = it
CoverLoader.loadImageView(mContext, it, holder.getView(R.id.iv_cover))
})
}
}
if (item.isCp) {
holder.itemView.setOnClickListener {
ToastUtils.show("Songs cannot be played")
}
}
holder.addOnClickListener(R.id.iv_more)
holder.addOnClickListener(R.id.iv_love)
}
}
| 8 | null | 455 | 2,316 | c7824199699c218b192d66036aa56fafa3164cfb | 4,361 | MusicLake | Apache License 2.0 |
compiler/psi/src/org/jetbrains/kotlin/psi/KtClass.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.psi
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.stubs.KotlinClassStub
import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes
open class KtClass : KtClassOrObject {
constructor(node: ASTNode) : super(node)
constructor(stub: KotlinClassStub) : super(stub, KtStubElementTypes.CLASS)
override fun <R, D> accept(visitor: KtVisitor<R, D>, data: D): R {
return visitor.visitClass(this, data)
}
private val _stub: KotlinClassStub?
get() = stub as? KotlinClassStub
fun getProperties(): List<KtProperty> = body?.properties.orEmpty()
fun isInterface(): Boolean =
_stub?.isInterface() ?: (findChildByType<PsiElement>(KtTokens.INTERFACE_KEYWORD) != null)
fun isEnum(): Boolean = hasModifier(KtTokens.ENUM_KEYWORD)
fun isData(): Boolean = hasModifier(KtTokens.DATA_KEYWORD)
fun isSealed(): Boolean = hasModifier(KtTokens.SEALED_KEYWORD)
fun isInner(): Boolean = hasModifier(KtTokens.INNER_KEYWORD)
fun isInline(): Boolean = hasModifier(KtTokens.INLINE_KEYWORD)
override fun getCompanionObjects(): List<KtObjectDeclaration> = body?.allCompanionObjects.orEmpty()
fun getClassOrInterfaceKeyword(): PsiElement? = findChildByType(TokenSet.create(KtTokens.CLASS_KEYWORD, KtTokens.INTERFACE_KEYWORD))
fun getClassKeyword(): PsiElement? = findChildByType(KtTokens.CLASS_KEYWORD)
fun getFunKeyword(): PsiElement? = modifierList?.getModifier(KtTokens.FUN_KEYWORD)
}
fun KtClass.createPrimaryConstructorIfAbsent(): KtPrimaryConstructor {
val constructor = primaryConstructor
if (constructor != null) return constructor
var anchor: PsiElement? = typeParameterList
if (anchor == null) anchor = nameIdentifier
if (anchor == null) anchor = lastChild
return addAfter(KtPsiFactory(project).createPrimaryConstructor(), anchor) as KtPrimaryConstructor
}
fun KtClass.createPrimaryConstructorParameterListIfAbsent(): KtParameterList {
val constructor = createPrimaryConstructorIfAbsent()
val parameterList = constructor.valueParameterList
if (parameterList != null) return parameterList
return constructor.add(KtPsiFactory(project).createParameterList("()")) as KtParameterList
} | 184 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 2,572 | kotlin | Apache License 2.0 |
goofy/oneko/src/main/kotlin/com/deflatedpickle/rawky/goofy/oneko/ONekoPlugin.kt | DeflatedPickle | 197,672,095 | false | {"Kotlin": 641980, "Python": 2204} | @file:Suppress("SpellCheckingInspection")
package com.deflatedpickle.rawky.goofy.oneko
import com.deflatedpickle.haruhi.api.constants.MenuCategory
import com.deflatedpickle.haruhi.api.plugin.Plugin
import com.deflatedpickle.haruhi.api.plugin.PluginType
import com.deflatedpickle.haruhi.event.EventProgramFinishSetup
import com.deflatedpickle.haruhi.util.ConfigUtil
import com.deflatedpickle.haruhi.util.RegistryUtil
import com.deflatedpickle.marvin.functions.extensions.get
import com.deflatedpickle.rawky.launcher.gui.Window
import com.deflatedpickle.undulation.functions.extensions.add
import oneko.Neko
import java.awt.MenuItem
import javax.swing.JMenu
import javax.swing.JMenuItem
@Plugin(
value = "oneko",
author = "DeflatedPickle",
version = "1.0.0",
description = """
<br>
Spawn cats that chase your mouse
""",
type = PluginType.OTHER,
settings = ONekoSettings::class,
)
object ONekoPlugin {
init {
EventProgramFinishSetup.addListener {
ConfigUtil.getSettings<ONekoSettings>("deflatedpickle@oneko#*")?.let { settings ->
RegistryUtil.get(MenuCategory.MENU.name)?.apply {
(get(MenuCategory.TOOLS.name) as JMenu).apply {
(menuComponents.filterIsInstance<JMenu>().firstOrNull { it.text == "Goofy" } ?: JMenu("Goofy").also { add(it) }).apply {
add("Neko") {
Neko(Window, settings.pack.name.lowercase(), true)
}
}
}
}
}
}
}
} | 7 | Kotlin | 6 | 27 | 81dafc9065f76fad8ffe0c10ad6cc9ed26c7965f | 1,629 | Rawky | MIT License |
app/src/main/java/com/example/myapplication/ui/Ai.kt | DeegayuA | 755,910,174 | false | {"Kotlin": 22632} | package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.myapplication.ui.MainScreen
import com.google.ai.client.generativeai.GenerativeModel
import com.example.myapplication.ui.theme.MyApplicationTheme
class SecondActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val detectedText = intent.getStringExtra("detectedTextKey") ?: "No text detected"
setContent {
MyApplicationTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val generativeModel = GenerativeModel(
modelName = "gemini-pro",
apiKey = BuildConfig.apiKey
)
val viewModel = AnswerViewModel(generativeModel)
AnswerRoute(detectedText, viewModel)
}
}
}
}
}
@Composable
internal fun AnswerRoute(
initialText: String, // Add initialText parameter
answerViewModel: AnswerViewModel = viewModel()
) {
val answerUiState by answerViewModel.uiState.collectAsState()
AnswerScreen(initialText, answerUiState, onAnswerClicked = { inputText ->
answerViewModel.summarize(inputText)
})
}
@Composable
fun AnswerScreen(
initialText: String,
uiState: AnswerUiState = AnswerUiState.Initial,
onAnswerClicked: (String) -> Unit = {}
) {
var prompt by remember { mutableStateOf(initialText) } // Initialize prompt with initialText
Column(
modifier = Modifier
.padding(all = 8.dp)
.verticalScroll(rememberScrollState())
) {
Row {
TextField(
value = prompt,
label = { Text(stringResource(R.string.summarize_label)) },
placeholder = { Text(stringResource(R.string.summarize_hint)) },
onValueChange = { prompt = it },
modifier = Modifier
.weight(8f)
)
TextButton(
onClick = {
if (prompt.isNotBlank()) {
onAnswerClicked(prompt)
}
},
modifier = Modifier
.weight(2f)
.padding(all = 4.dp)
.align(Alignment.CenterVertically)
) {
Text(stringResource(R.string.action_go))
}
}
when (uiState) {
AnswerUiState.Initial -> {
// Nothing is shown
}
AnswerUiState.Loading -> {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.padding(all = 8.dp)
.align(Alignment.CenterHorizontally)
) {
CircularProgressIndicator()
}
}
is AnswerUiState.Success -> {
Row(modifier = Modifier.padding(all = 8.dp)) {
Icon(
Icons.Outlined.Person,
contentDescription = "Person Icon"
)
Text(
text = uiState.outputText,
modifier = Modifier.padding(horizontal = 8.dp)
)
}
}
is AnswerUiState.Error -> {
Text(
text = uiState.errorMessage,
color = Color.Red,
modifier = Modifier.padding(all = 8.dp)
)
}
}
}
}
@Preview(showSystemUi = true)
@Composable
fun AnswerScreenPreview() {
AnswerScreen(
initialText = "Sample text", // Provide a sample initialText for preview
onAnswerClicked = {}
)
}
| 0 | Kotlin | 0 | 0 | cdcfc49002ed3c6af9dc93dffd8c4a2f9c4fdeb1 | 5,409 | SnapLearn | MIT License |
app/src/main/java/com/example/myapplication/ui/Ai.kt | DeegayuA | 755,910,174 | false | {"Kotlin": 22632} | package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.myapplication.ui.MainScreen
import com.google.ai.client.generativeai.GenerativeModel
import com.example.myapplication.ui.theme.MyApplicationTheme
class SecondActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val detectedText = intent.getStringExtra("detectedTextKey") ?: "No text detected"
setContent {
MyApplicationTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val generativeModel = GenerativeModel(
modelName = "gemini-pro",
apiKey = BuildConfig.apiKey
)
val viewModel = AnswerViewModel(generativeModel)
AnswerRoute(detectedText, viewModel)
}
}
}
}
}
@Composable
internal fun AnswerRoute(
initialText: String, // Add initialText parameter
answerViewModel: AnswerViewModel = viewModel()
) {
val answerUiState by answerViewModel.uiState.collectAsState()
AnswerScreen(initialText, answerUiState, onAnswerClicked = { inputText ->
answerViewModel.summarize(inputText)
})
}
@Composable
fun AnswerScreen(
initialText: String,
uiState: AnswerUiState = AnswerUiState.Initial,
onAnswerClicked: (String) -> Unit = {}
) {
var prompt by remember { mutableStateOf(initialText) } // Initialize prompt with initialText
Column(
modifier = Modifier
.padding(all = 8.dp)
.verticalScroll(rememberScrollState())
) {
Row {
TextField(
value = prompt,
label = { Text(stringResource(R.string.summarize_label)) },
placeholder = { Text(stringResource(R.string.summarize_hint)) },
onValueChange = { prompt = it },
modifier = Modifier
.weight(8f)
)
TextButton(
onClick = {
if (prompt.isNotBlank()) {
onAnswerClicked(prompt)
}
},
modifier = Modifier
.weight(2f)
.padding(all = 4.dp)
.align(Alignment.CenterVertically)
) {
Text(stringResource(R.string.action_go))
}
}
when (uiState) {
AnswerUiState.Initial -> {
// Nothing is shown
}
AnswerUiState.Loading -> {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.padding(all = 8.dp)
.align(Alignment.CenterHorizontally)
) {
CircularProgressIndicator()
}
}
is AnswerUiState.Success -> {
Row(modifier = Modifier.padding(all = 8.dp)) {
Icon(
Icons.Outlined.Person,
contentDescription = "Person Icon"
)
Text(
text = uiState.outputText,
modifier = Modifier.padding(horizontal = 8.dp)
)
}
}
is AnswerUiState.Error -> {
Text(
text = uiState.errorMessage,
color = Color.Red,
modifier = Modifier.padding(all = 8.dp)
)
}
}
}
}
@Preview(showSystemUi = true)
@Composable
fun AnswerScreenPreview() {
AnswerScreen(
initialText = "Sample text", // Provide a sample initialText for preview
onAnswerClicked = {}
)
}
| 0 | Kotlin | 0 | 0 | cdcfc49002ed3c6af9dc93dffd8c4a2f9c4fdeb1 | 5,409 | SnapLearn | MIT License |
nlp/model/storage-mongo/src/main/kotlin/NlpApplicationConfigurationMongoDAO.kt | theopenconversationkit | 84,538,053 | false | {"Kotlin": 6173880, "TypeScript": 1286450, "HTML": 532576, "Python": 376720, "SCSS": 79512, "CSS": 66318, "Shell": 12085, "JavaScript": 1849} | /*
* Copyright (C) 2017 VSCT
*
* 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 ai.tock.nlp.model.service.storage.mongo
import ai.tock.nlp.core.NlpEngineType
import ai.tock.nlp.core.configuration.NlpApplicationConfiguration
import ai.tock.nlp.model.service.storage.NlpApplicationConfigurationDAO
import ai.tock.nlp.model.service.storage.mongo.MongoModelConfiguration.database
import ai.tock.nlp.model.service.storage.mongo.NlpApplicationConfigurationCol_.Companion.ApplicationName
import ai.tock.nlp.model.service.storage.mongo.NlpApplicationConfigurationCol_.Companion.Date
import ai.tock.nlp.model.service.storage.mongo.NlpApplicationConfigurationCol_.Companion.EngineType
import org.litote.kmongo.Data
import org.litote.jackson.data.JacksonData
import org.litote.kmongo.descending
import org.litote.kmongo.descendingSort
import org.litote.kmongo.ensureIndex
import org.litote.kmongo.eq
import org.litote.kmongo.find
import org.litote.kmongo.getCollection
import org.litote.kmongo.lt
import java.time.Instant
import java.time.Instant.now
/**
*
*/
internal object NlpApplicationConfigurationMongoDAO : NlpApplicationConfigurationDAO {
@JacksonData(internal = true)
@Data(internal = true)
data class NlpApplicationConfigurationCol(
val applicationName: String,
val engineType: NlpEngineType,
val configuration: NlpApplicationConfiguration,
val date: Instant = now()
)
private val col = database.getCollection<NlpApplicationConfigurationCol>("nlp_application_configuration")
.apply {
ensureIndex(descending(ApplicationName, EngineType, Date))
}
override fun saveNewConfiguration(
applicationName: String,
engineType: NlpEngineType,
configuration: NlpApplicationConfiguration
) {
col.insertOne(NlpApplicationConfigurationCol(applicationName, engineType, configuration))
}
override fun loadLastConfiguration(
applicationName: String,
engineType: NlpEngineType,
updated: Instant
): NlpApplicationConfiguration? {
return col
.find(ApplicationName eq applicationName, EngineType eq engineType, Date lt updated)
.descendingSort(Date)
.limit(1)
.firstOrNull()
?.configuration
}
} | 163 | Kotlin | 127 | 475 | 890f69960997ae9146747d082d808d92ee407fcb | 2,827 | tock | Apache License 2.0 |
composeApp/src/commonMain/kotlin/com/rwmobi/kunigami/ui/destinations/usage/components/TariffProjectionTilesAdaptive.kt | ryanw-mobile | 794,752,204 | false | {"Kotlin": 1436400, "Ruby": 2466, "Swift": 693} | /*
* Copyright (c) 2024. RW MobiMedia UK Limited
*
* Contributions made by other developers remain the property of their respective authors but are licensed
* to RW MobiMedia UK Limited and others under the same licence terms as the main project, as outlined in
* the LICENSE file.
*
* RW MobiMedia UK Limited reserves the exclusive right to distribute this application on app stores.
* Reuse of this source code, with or without modifications, requires proper attribution to
* RW MobiMedia UK Limited. Commercial distribution of this code or its derivatives without prior written
* permission from RW MobiMedia UK Limited is prohibited.
*
* Please refer to the LICENSE file for the full terms and conditions.
*/
package com.rwmobi.kunigami.ui.destinations.usage.components
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.rwmobi.kunigami.domain.model.product.Tariff
import com.rwmobi.kunigami.ui.components.CommonPreviewSetup
import com.rwmobi.kunigami.ui.components.TariffSummaryTile
import com.rwmobi.kunigami.ui.composehelper.getScreenSizeInfo
import com.rwmobi.kunigami.ui.model.consumption.Insights
import com.rwmobi.kunigami.ui.previewsampledata.InsightsSamples
import com.rwmobi.kunigami.ui.previewsampledata.TariffSamples
import com.rwmobi.kunigami.ui.theme.getDimension
@Composable
internal fun TariffProjectionTilesAdaptive(
modifier: Modifier = Modifier,
tariff: Tariff?,
insights: Insights?,
layoutType: WindowWidthSizeClass = WindowWidthSizeClass.Compact,
) {
when (layoutType) {
WindowWidthSizeClass.Compact,
WindowWidthSizeClass.Medium,
-> {
TariffProjectionsTileFLinear(
modifier = modifier,
tariff = tariff,
insights = insights,
)
}
else -> {
TariffProjectionsTileFlowRow(
modifier = modifier,
tariff = tariff,
insights = insights,
)
}
}
}
@Composable
private fun TariffProjectionsTileFLinear(
modifier: Modifier = Modifier,
tariff: Tariff?,
insights: Insights?,
) {
val dimension = getScreenSizeInfo().getDimension()
Column(
modifier = modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(dimension.grid_1),
) {
val fullWidthModifier = Modifier
.fillMaxWidth()
.height(dimension.widgetHeight)
tariff?.let {
TariffSummaryTile(
modifier = fullWidthModifier,
tariff = it,
)
}
insights?.let { insights ->
InsightsTile(
modifier = fullWidthModifier,
insights = insights,
)
Row(
horizontalArrangement = Arrangement.spacedBy(dimension.grid_1),
) {
val halfWidthModifier = Modifier
.weight(1f)
.height(dimension.widgetHeight)
if (insights.consumptionTimeSpan > 1) {
ConsumptionTile(
modifier = halfWidthModifier,
insights = insights,
)
DailyAverageTile(
modifier = halfWidthModifier,
insights = insights,
)
} else {
ConsumptionTile(
modifier = halfWidthModifier,
insights = insights,
)
ProjectedConsumptionTile(
modifier = halfWidthModifier,
insights = insights,
)
}
}
if (insights.consumptionTimeSpan > 1) {
ProjectedConsumptionTile(
modifier = fullWidthModifier,
insights = insights,
)
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun TariffProjectionsTileFlowRow(
modifier: Modifier = Modifier,
tariff: Tariff?,
insights: Insights?,
) {
val dimension = getScreenSizeInfo().getDimension()
val halfWidthModifier = Modifier
.width(dimension.widgetWidthHalf)
.height(dimension.widgetHeight)
.padding(horizontal = dimension.grid_0_5)
val fullWidthModifier = Modifier
.width(dimension.widgetWidthFull)
.height(dimension.widgetHeight)
.padding(horizontal = dimension.grid_0_5)
FlowRow(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalArrangement = Arrangement.spacedBy(dimension.grid_1),
) {
tariff?.let {
TariffSummaryTile(
modifier = fullWidthModifier,
tariff = it,
)
}
insights?.let { insights ->
InsightsTile(
modifier = fullWidthModifier,
insights = insights,
)
ConsumptionTile(
modifier = halfWidthModifier,
insights = insights,
)
if (insights.consumptionTimeSpan > 1) {
DailyAverageTile(
modifier = halfWidthModifier,
insights = insights,
)
}
ProjectedConsumptionTile(
modifier = halfWidthModifier,
insights = insights,
)
}
}
}
@Preview
@Composable
private fun Preview() {
CommonPreviewSetup {
TariffProjectionTilesAdaptive(
modifier = Modifier.padding(all = 16.dp),
tariff = TariffSamples.agileFlex221125,
insights = InsightsSamples.trueCost,
layoutType = WindowWidthSizeClass.Expanded,
)
TariffProjectionTilesAdaptive(
modifier = Modifier.padding(all = 16.dp),
tariff = TariffSamples.agileFlex221125,
insights = InsightsSamples.trueCost,
layoutType = WindowWidthSizeClass.Compact,
)
}
}
| 19 | Kotlin | 10 | 145 | 67e4ea568fbae25b0ee59982bd97dcbe9c52a2a8 | 6,917 | OctoMeter | Creative Commons Attribution 4.0 International |
http/src/test/kotlin/io/wavebeans/http/AudioServiceSpec.kt | WaveBeans | 174,378,458 | false | {"Kotlin": 1263856, "Shell": 6924, "Dockerfile": 408} | package io.wavebeans.http
import assertk.Assert
import assertk.all
import assertk.assertThat
import assertk.assertions.*
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import io.wavebeans.lib.*
import io.wavebeans.lib.io.WavHeader
import io.wavebeans.lib.io.input
import io.wavebeans.lib.stream.map
import io.wavebeans.lib.stream.trim
import io.wavebeans.lib.stream.window.window
import io.wavebeans.lib.table.TableRegistry
import io.wavebeans.lib.table.TimeseriesTableDriver
import org.spekframework.spek2.Spek
import org.spekframework.spek2.lifecycle.CachingMode.*
import org.spekframework.spek2.style.specification.describe
import java.io.InputStream
private val sampleRate = 44100.0f
object AudioServiceSpec : Spek({
describe("Streaming WAV") {
describe("Sample table") {
val tableRegistry by memoized(TEST) { mock<TableRegistry>() }
val tableDriver by memoized(TEST) {
val driver = mock<TimeseriesTableDriver<Sample>>()
whenever(driver.tableType).thenReturn(Sample::class)
whenever(driver.sampleRate).thenReturn(sampleRate)
driver
}
val service by memoized(TEST) {
whenever(tableRegistry.exists(eq("table"))).thenReturn(true)
whenever(tableRegistry.byName<Sample>("table")).thenReturn(tableDriver)
AudioService(tableRegistry)
}
it("should start streaming 8 bit wav file") {
whenever(tableDriver.stream(any())).thenReturn(input8Bit())
assert8BitWavOutput<Sample>(service)
}
it("should start streaming 16 bit wav file") {
whenever(tableDriver.stream(any())).thenReturn(input16Bit())
assert16BitWavOutput<Sample>(service)
}
it("should start streaming 24 bit wav file") {
whenever(tableDriver.stream(any())).thenReturn(input24Bit())
assert24BitWavOutput<Sample>(service)
}
it("should start streaming 32 bit wav file") {
whenever(tableDriver.stream(any())).thenReturn(input32Bit())
assert32BitWavOutput<Sample>(service)
}
it("should start stream limited table") {
whenever(tableDriver.stream(any())).thenReturn(input8Bit().trim(1000))
assert8BitLimitedWavOutput<Sample>(service, 1000)
}
}
describe("SampleVector table") {
val tableRegistry by memoized(TEST) { mock<TableRegistry>() }
val tableDriver by memoized(TEST) {
val driver = mock<TimeseriesTableDriver<SampleVector>>()
whenever(driver.tableType).thenReturn(SampleVector::class)
whenever(driver.sampleRate).thenReturn(sampleRate)
driver
}
val service by memoized(TEST) {
whenever(tableRegistry.exists(eq("table"))).thenReturn(true)
whenever(tableRegistry.byName<SampleVector>("table")).thenReturn(tableDriver)
AudioService(tableRegistry)
}
it("should start streaming 8 bit wav file") {
whenever(tableDriver.stream(any())).thenReturn(input8Bit().window(16).map { sampleVectorOf(it) })
assert8BitWavOutput<SampleVector>(service)
}
it("should start streaming 16 bit wav file") {
whenever(tableDriver.stream(any())).thenReturn(input16Bit().window(16).map { sampleVectorOf(it) })
assert16BitWavOutput<SampleVector>(service)
}
it("should start streaming 24 bit wav file") {
whenever(tableDriver.stream(any())).thenReturn(input24Bit().window(16).map { sampleVectorOf(it) })
assert24BitWavOutput<SampleVector>(service)
}
it("should start streaming 32 bit wav file") {
whenever(tableDriver.stream(any())).thenReturn(input32Bit().window(16).map { sampleVectorOf(it) })
assert32BitWavOutput<SampleVector>(service)
}
it("should start stream limited table") {
whenever(tableDriver.stream(any())).thenReturn(input8Bit().trim(1000).window(16).map { sampleVectorOf(it) })
assert8BitLimitedWavOutput<Sample>(service, 1000)
}
}
}
})
private fun input32Bit() = input { (i, _) -> sampleOf((i and 0xFFFFFFFF).toInt()) }
private fun input24Bit() = input { (i, _) -> sampleOf((i and 0xFFFFFF).toInt(), as24bit = true) }
private fun input16Bit() = input { (i, _) -> sampleOf((i and 0xFFFF).toShort()) }
private fun input8Bit() = input { (i, _) -> sampleOf((i and 0xFF).toByte()) }
private fun <T : Any> assert8BitWavOutput(service: AudioService) {
assertThat(service.stream<T>(AudioStreamOutputFormat.WAV, "table", BitDepth.BIT_8, null, 0.s)).all {
take(44).all {
isNotEmpty() // header is there
range(0, 4).isEqualTo("RIFF".toByteArray())
}
take(256).prop("unsignedByte[]") { it.map(Byte::asUnsignedByte).toTypedArray() }
.isEqualTo(Array(256) { it and 0xFF })
take(256).prop("unsignedByte[]") { it.map(Byte::asUnsignedByte).toTypedArray() }
.isEqualTo(Array(256) { it and 0xFF })
take(256).prop("unsignedByte[]") { it.map(Byte::asUnsignedByte).toTypedArray() }
.isEqualTo(Array(256) { it and 0xFF })
}
}
private fun <T : Any> assert24BitWavOutput(service: AudioService) {
assertThat(service.stream<T>(AudioStreamOutputFormat.WAV, "table", BitDepth.BIT_24, null, 0.s)).all {
take(44).all {
isNotEmpty() // header is there
range(0, 4).isEqualTo("RIFF".toByteArray())
}
take(768).isEqualTo(ByteArray(768) { if (it % 3 == 0) (it / 3 and 0xFF).toByte() else if (it % 3 == 1) 0x00 else 0x00 })
take(768).isEqualTo(ByteArray(768) { if (it % 3 == 0) (it / 3 and 0xFF).toByte() else if (it % 3 == 1) 0x01 else 0x00 })
take(768).isEqualTo(ByteArray(768) { if (it % 3 == 0) (it / 3 and 0xFF).toByte() else if (it % 3 == 1) 0x02 else 0x00 })
}
}
private fun <T : Any> assert32BitWavOutput(service: AudioService) {
assertThat(service.stream<T>(AudioStreamOutputFormat.WAV, "table", BitDepth.BIT_32, null, 0.s)).all {
take(44).all {
isNotEmpty() // header is there
range(0, 4).isEqualTo("RIFF".toByteArray())
}
take(1024).isEqualTo(ByteArray(1024) { if (it % 4 == 0) (it / 4 and 0xFF).toByte() else if (it % 4 == 1) 0x00 else 0x00 })
take(1024).isEqualTo(ByteArray(1024) { if (it % 4 == 0) (it / 4 and 0xFF).toByte() else if (it % 4 == 1) 0x01 else 0x00 })
take(1024).isEqualTo(ByteArray(1024) { if (it % 4 == 0) (it / 4 and 0xFF).toByte() else if (it % 4 == 1) 0x02 else 0x00 })
}
}
private fun <T : Any> assert8BitLimitedWavOutput(service: AudioService, expectedLengthMs: Long) {
assertThat(service.stream<T>(AudioStreamOutputFormat.WAV, "table", BitDepth.BIT_8, null, 0.s)).all {
val dataSize = (BitDepth.BIT_8.bytesPerSample * sampleRate / 1000.0 * expectedLengthMs).toInt()
take(44).all {
isNotEmpty() // header is there
// size in wav header remains unlimited
isEqualTo(WavHeader(BitDepth.BIT_8, sampleRate, 1, Int.MAX_VALUE).header())
}
// though the data is all there
take(dataSize).prop("unsignedByte[]") { it.map(Byte::asUnsignedByte).toTypedArray() }
.isEqualTo(Array(dataSize) { it and 0xFF })
// and no more left
tryTake(128).prop("count") { it.first }.isEqualTo(-1)
}
}
private fun <T : Any> assert16BitWavOutput(service: AudioService) {
assertThat(service.stream<T>(AudioStreamOutputFormat.WAV, "table", BitDepth.BIT_16, null, 0.s)).all {
take(44).all {
isNotEmpty() // header is there
range(0, 4).isEqualTo("RIFF".toByteArray())
}
take(512).isEqualTo(ByteArray(512) { if (it % 2 == 0) (it / 2 and 0xFF).toByte() else 0x00 })
take(512).isEqualTo(ByteArray(512) { if (it % 2 == 0) (it / 2 and 0xFF).toByte() else 0x01 })
take(512).isEqualTo(ByteArray(512) { if (it % 2 == 0) (it / 2 and 0xFF).toByte() else 0x02 })
}
}
private fun Assert<InputStream>.take(count: Int): Assert<ByteArray> = this.prop("take($count)") { it.take(count) }
private fun Assert<InputStream>.tryTake(count: Int): Assert<Pair<Int, ByteArray>> = this.prop("tryTake($count)") { it.tryTake(count) }
private fun Assert<ByteArray>.range(start: Int, end: Int): Assert<ByteArray> = this.prop("range[$start:$end]") { it.copyOfRange(start, end) }
private fun InputStream.take(count: Int): ByteArray {
val (read, ba) = this.tryTake(count)
if (read < count) throw IllegalStateException("Expected to read $count bytes but read $read")
return ba
}
private fun InputStream.tryTake(count: Int): Pair<Int, ByteArray> {
val ba = ByteArray(count)
val read = this.read(ba)
return Pair(read, ba)
}
| 26 | Kotlin | 0 | 21 | 2a0eb6b481f0f848a7e66f7cb4c395ddb47952d1 | 9,239 | wavebeans | Apache License 2.0 |
Firebase_android/app/src/main/java/allanksr/com/firebase/cloudFirestore/FireStoreView.kt | Allanksr | 312,747,617 | false | null | package allanksr.com.firebase.cloudFirestore
interface FireStoreView {
fun waitResult()
fun setError(error: String)
fun getData()
} | 0 | Kotlin | 0 | 0 | 69c12649a2531c3fa728cbbbe2a8cacb1fea9756 | 144 | FirebaseApi | MIT License |
owl2java/src/main/kotlin/io/clouditor/graph/SemanticNodeGenerator.kt | clouditor | 383,231,250 | false | null | package io.clouditor.graph
import kotlin.Throws
import kotlin.jvm.JvmStatic
import org.jboss.forge.roaster.model.source.JavaClassSource
import org.apache.commons.lang3.StringUtils
import org.semanticweb.owlapi.model.OWLOntologyCreationException
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.util.Arrays
import java.util.Locale
import java.util.stream.Collectors
object SemanticNodeGenerator {
@Throws(OWLOntologyCreationException::class)
@JvmStatic
fun main(args: Array<String>) {
// TODO During development, the following parameters are default values
var outputBaseGo = "output/go/"
var packageNameGo = "voc"
var outputBaseJava = "../cloudpg/generated/main/java/io/clouditor/graph/"
var packageNameJava = "io.clouditor.graph"
// IMPORTANT: Only OWL/XML and RDF/XML are supported
var owlInputPath = "resources/urn_webprotege_ontology_e4316a28-d966-4499-bd93-6be721055117.owx"
if (args.size == 0) {
print(
"""
Please use the following parameters:
1st parameter: Ontology Input File (Only OWL/XML and RDF/XML are supported)2st parameter: Java package name
3nd parameter: Output path for generated Java files (optional, but the order must be respected)
4th parameter: Go package name
5th parameter: Output path for generated Go Files (optional, but the order must be respected)
""".trimIndent()
)
}
if (args.size == 5) {
owlInputPath = args[0]
packageNameJava = args[1]
outputBaseJava = checkPath(args[2])
packageNameGo = args[3]
outputBaseGo = checkPath(args[4])
} else if (args.size == 4) {
owlInputPath = args[0]
packageNameJava = args[1]
outputBaseJava = checkPath(args[2])
packageNameGo = args[3]
} else if (args.size == 3) {
owlInputPath = args[0]
packageNameJava = args[1]
outputBaseJava = checkPath(args[2])
} else if (args.size == 2) {
owlInputPath = args[0]
packageNameJava = args[1]
} else if (args.size == 1) {
owlInputPath = args[0]
}
val owl3 = OWLCloudOntology(owlInputPath)
// Create java class sources
val jcs = owl3.getJavaClassSources(packageNameJava)
writeClassesToFolder(jcs, outputBaseJava)
// Create Go sources
val ontologyDescription = owl3.getGoStructs(packageNameGo)
writeGoStringsToFolder(ontologyDescription, outputBaseGo, owl3)
}
private fun checkPath(outputBase: String): String {
var tmpOutputBase = outputBase
return if (tmpOutputBase[tmpOutputBase.length - 1] != '/') "/".let { tmpOutputBase += it; tmpOutputBase } else tmpOutputBase
}
// Create Go source code
private fun createGoSourceCodeString(goSource: GoStruct, owl3: OWLCloudOntology): String {
var goSourceCode = ""
// Add copyright
goSourceCode += """// Copyright 2021 Fraunhofer AISEC
//
// 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.
//
// ${"$"}$\ ${"$"}$\ ${"$"}$\ ${"$"}$\
// ${"$"}$ | ${"$"}$ |\__| ${"$"}$ |
// ${"$"}${"$"}${"$"}${"$"}${"$"}${"$"}$\ ${"$"}$ | ${"$"}${"$"}${"$"}${"$"}${"$"}$\ ${"$"}$\ ${"$"}$\ ${"$"}${"$"}${"$"}${"$"}${"$"}${"$"}$ |${"$"}$\ ${"$"}${"$"}${"$"}${"$"}${"$"}$\ ${"$"}${"$"}${"$"}${"$"}${"$"}$\ ${"$"}${"$"}${"$"}${"$"}${"$"}$\
// ${"$"}$ _____|${"$"}$ |${"$"}$ __${"$"}$\ ${"$"}$ | ${"$"}$ |${"$"}$ __${"$"}$ |${"$"}$ |\_${"$"}$ _| ${"$"}$ __${"$"}$\ ${"$"}$ __${"$"}$\
// ${"$"}$ / ${"$"}$ |${"$"}$ / ${"$"}$ |${"$"}$ | ${"$"}$ |${"$"}$ / ${"$"}$ |${"$"}$ | ${"$"}$ | ${"$"}$ / ${"$"}$ |${"$"}$ | \__|
// ${"$"}$ | ${"$"}$ |${"$"}$ | ${"$"}$ |${"$"}$ | ${"$"}$ |${"$"}$ | ${"$"}$ |${"$"}$ | ${"$"}$ |${"$"}$\ ${"$"}$ | ${"$"}$ |${"$"}$ |
// \${"$"}${"$"}${"$"}${"$"}${"$"}$\ ${"$"}$ |\${"$"}${"$"}${"$"}${"$"}$ |\${"$"}${"$"}${"$"}${"$"}$ |\${"$"}${"$"}${"$"}${"$"}${"$"}$ |${"$"}$ | \${"$"}${"$"}$ |\${"$"}${"$"}${"$"}${"$"}$ |${"$"}$ |
// \_______|\__| \______/ \______/ \_______|\__| \____/ \______/ \__|
//
// This file is part of Clouditor Community Edition.
"""
// Add package name
goSourceCode += """
package ${goSource.packageName}
""".trimIndent()
// Add imports
for (elem in goSource.dataProperties){
if (getGoType(elem.propertyType.toString()) == "time.Duration") {
goSourceCode += "import \"time\"\n\n"
break
}
}
// Add struct
goSourceCode += """type ${goSource.name} struct {
"""
// Check if parentClass exists
val parentClassName = getParentClassName(goSource.parentClass)
if (parentClassName != "") goSourceCode += "\t*" + getParentClassName(goSource.parentClass)
// Add object properties
goSourceCode += getObjectPropertiesForGoSource(goSource.objectProperties)
// Add data properties
goSourceCode += getDataPropertiesForGoSource(goSource.dataProperties)
goSourceCode += "\n}\n\n"
// Create method for interface
if (owl3.interfaceList.contains(goSource.parentClass)) {
goSourceCode += getInterfaceMethod(goSource)
}
// TODO: Do we need that anymore?
// Create new function
//goSourceCode += getNewFunctionForObjectProperties(goSource);
return goSourceCode
}
private fun getInterfaceMethod(gs: GoStruct): String {
var receiverType = gs.name
var receiverChar = receiverType.first().lowercaseChar()
var interfaceMethodName = gs.parentClass
var interfaceMethodReturnType = gs.parentClass
return "func ($receiverChar $receiverType) Get$interfaceMethodName() *$interfaceMethodReturnType{ \n\treturn $receiverChar.$interfaceMethodReturnType\n}"
}
// TODO: Do we need that anymore?
// private fun getNewFunctionForObjectProperties(gs: GoStruct): String {
// var newFunctionString = ""
// newFunctionString += "func New" + gs.name + "("
// for (property in gs.dataProperties) {
// property.propertyType?.let {
// newFunctionString += property.propertyName + " " + getGoType(it) + ", "
// }
// }
//
// // Delete last `,` if exists and close )
// if (newFunctionString[newFunctionString.length - 2] == ',') {
// newFunctionString = newFunctionString.substring(0, newFunctionString.length - 2) + ") "
// } else {
// newFunctionString += ") "
// }
// newFunctionString += """
// *${gs.name}{
//
// """.trimIndent()
// newFunctionString += """ return &${gs.name}{
//"""
// for (property in gs.objectProperties) {
// newFunctionString += """ ${StringUtils.capitalize(property.propertyName)}: TODO get propertyName stuff,
//"""
// }
// for (property in gs.dataProperties) {
// newFunctionString += """ ${StringUtils.capitalize(property.propertyName)}: ${
// StringUtils.uncapitalize(
// property.propertyName
// )
// },
//"""
// }
// newFunctionString += "\t}\n}"
// return newFunctionString
// }
// Change property type to GO type
private fun getGoType(type: String): String {
var goType = ""
goType = when (type) {
"String" -> "string"
"float" -> "float32"
"boolean" -> "bool"
"java.time.Duration" -> "time.Duration"
"java.util.Map<String, String>" -> "map[string]string"
"java.util.ArrayList<Short>" -> "[]int16"
"java.util.ArrayList<String>" -> "[]string"
"Short" -> "int16"
"de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration" -> // TODO What do we need here?
"string"
"de.fraunhofer.aisec.cpg.graph.statements.expressions.Expression" -> // TODO What do we need here?
"string"
"de.fraunhofer.aisec.cpg.graph.Node" -> "string"
"de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression" -> "string"
"java.util.List<de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration>" -> "[]string"
"java.util.List<de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression>" -> "[]string"
else -> type
}
return goType
}
private fun getParentClassName(parentClass: String): String {
if (parentClass == "") return ""
val parentClassSplit = parentClass.split("\\.").toTypedArray()
return parentClassSplit[parentClassSplit.size - 1]
}
private fun getObjectPropertiesForGoSource(properties: List<Properties>): String {
var propertiesStringSource = ""
for (property in properties) {
propertiesStringSource += if (!property.isRootClassNameResource && !property.isInterface) {
"""
${StringUtils.capitalize(property.propertyName)} *""" + StringUtils.capitalize(
property.propertyType
) + " `json:\"" + property.propertyName + "\"`"
} else if (!property.isRootClassNameResource && property.isInterface) {
"""
${StringUtils.capitalize(property.propertyName)} """ + StringUtils.capitalize(
property.propertyType
) + " `json:\"" + property.propertyName + "\"`"
} else {
// TODO is ResourceID always a slice?
"""
${StringUtils.capitalize(property.propertyName)} []ResourceID `json:"${property.propertyName}"`"""
}
}
return propertiesStringSource
}
private fun getDataPropertiesForGoSource(properties: List<Properties>): String {
var propertiesStringSource = ""
for (property in properties) {
property.propertyType?.let {
propertiesStringSource += """
${StringUtils.capitalize(property.propertyName)} ${getGoType(it)} `json:"${property.propertyName}"`"""
}
}
return propertiesStringSource
}
// Write Go source code to filesystem
private fun writeGoStringsToFolder(goSources: List<GoStruct>, outputBase: String, owl3: OWLCloudOntology) {
var filepath: String
for (goSource in goSources) {
filepath = getGoFilepath(goSource.name, outputBase)
val f = File(filepath)
val directory = f.parentFile
if (!directory.exists()) {
if (!directory.mkdirs()) {
println("Could not create base directory for file $outputBase")
}
}
try {
val fileWriter = FileWriter(f)
fileWriter.write(createGoSourceCodeString(goSource, owl3))
fileWriter.close()
println("File written to: $filepath")
} catch (e: IOException) {
e.printStackTrace()
}
}
}
private fun getGoFilepath(name: String, outputBase: String): String {
val filepath: String
var filenameList: List<String?>? =
Arrays.stream(name.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])".toRegex()).toTypedArray())
.map { obj: String -> obj.lowercase(Locale.getDefault()) }
.collect(Collectors.toList())
val filename: String = java.lang.String.join("_", filenameList)
// Create filepath
filepath = "$outputBase$filename.go"
return filepath
}
// Write java class files to filesystem
private fun writeClassesToFolder(jcs: List<JavaClassSource>, outputBase: String) {
var filename: String
for (jcsElem in jcs) {
filename = outputBase + jcsElem.name + ".java"
// write to file
val f = File(filename)
val directory = f.parentFile
if (!directory.exists()) {
if (!directory.mkdirs()) {
println("Could not create base directory for file $outputBase")
}
}
try {
val fileWriter = FileWriter(f)
fileWriter.write(jcsElem.toString())
fileWriter.close()
println("File written to: $filename")
} catch (e: IOException) {
e.printStackTrace()
}
}
}
} | 9 | Kotlin | 1 | 8 | 1677a4114b11871f2e7c6791e6f46be5a538d4e9 | 13,338 | cloud-property-graph | Apache License 2.0 |
app/composeApp/src/iosMain/kotlin/main.kt | alexaragao | 809,759,421 | false | {"Kotlin": 126157, "Dockerfile": 709, "Swift": 522} | import androidx.compose.ui.window.ComposeUIViewController
import com.xboxgamecollection.app.App
import platform.UIKit.UIViewController
fun MainViewController(): UIViewController = ComposeUIViewController { App() }
| 0 | Kotlin | 0 | 1 | 25cdf1704a2f5a9a587dce225cb612df731c38e7 | 215 | xbox-game-collection-app | MIT License |
src/main/kotlin/pubg/radar/ui/GLMap.kt | whitewingz2017 | 129,306,460 | false | null | @file:Suppress("NAME_SHADOWING")
package pubg.radar.ui
//import pubg.radar.deserializer.channel.ActorChannel.Companion.actorHasWeapons
//import pubg.radar.deserializer.channel.ActorChannel.Companion.weapons
import com.badlogic.gdx.ApplicationListener
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input.Buttons.LEFT
import com.badlogic.gdx.Input.Buttons.MIDDLE
import com.badlogic.gdx.Input.Buttons.RIGHT
import com.badlogic.gdx.Input.Keys.*
import com.badlogic.gdx.InputAdapter
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Color.*
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.GlyphLayout
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.DEFAULT_CHARS
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType.*
import com.badlogic.gdx.math.Matrix4
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import pubg.radar.ForceRestart
import com.badlogic.gdx.math.Vector3
import org.apache.commons.math3.ml.neuralnet.Network
import pubg.radar.*
import pubg.radar.deserializer.channel.ActorChannel.Companion.actorHasWeapons
import pubg.radar.deserializer.channel.ActorChannel.Companion.actors
import pubg.radar.deserializer.channel.ActorChannel.Companion.airDropLocation
import pubg.radar.deserializer.channel.ActorChannel.Companion.airDropItems
import pubg.radar.deserializer.channel.ActorChannel.Companion.corpseLocation
import pubg.radar.deserializer.channel.ActorChannel.Companion.droppedItemCompToItem
import pubg.radar.deserializer.channel.ActorChannel.Companion.droppedItemLocation
import pubg.radar.deserializer.channel.ActorChannel.Companion.droppedItemToItem
import pubg.radar.deserializer.channel.ActorChannel.Companion.visualActors
import pubg.radar.deserializer.channel.ActorChannel.Companion.weapons
import pubg.radar.deserializer.channel.ActorChannel.Companion.itemBag
import pubg.radar.struct.Actor
import pubg.radar.struct.Archetype
import pubg.radar.struct.Archetype.*
import pubg.radar.struct.NetworkGUID
import pubg.radar.struct.cmd.*
import pubg.radar.struct.cmd.ActorCMD.actorDowned
import pubg.radar.struct.cmd.ActorCMD.actorBeingRevived
import pubg.radar.struct.cmd.ActorCMD.actorHealth
import pubg.radar.struct.cmd.ActorCMD.actorWithPlayerState
import pubg.radar.struct.cmd.ActorCMD.playerStateToActor
import pubg.radar.struct.cmd.GameStateCMD.ElapsedWarningDuration
import pubg.radar.struct.cmd.GameStateCMD.NumAlivePlayers
import pubg.radar.struct.cmd.GameStateCMD.NumAliveTeams
import pubg.radar.struct.cmd.GameStateCMD.NumAliveTeams
import pubg.radar.struct.cmd.GameStateCMD.PoisonGasWarningPosition
import pubg.radar.struct.cmd.GameStateCMD.PoisonGasWarningRadius
import pubg.radar.struct.cmd.GameStateCMD.RedZonePosition
import pubg.radar.struct.cmd.GameStateCMD.RedZoneRadius
import pubg.radar.struct.cmd.GameStateCMD.SafetyZonePosition
import pubg.radar.struct.cmd.GameStateCMD.SafetyZoneRadius
import pubg.radar.struct.cmd.GameStateCMD.TotalWarningDuration
import pubg.radar.struct.cmd.GameStateCMD.isTeamMatch
import pubg.radar.struct.cmd.selfHeight
import pubg.radar.struct.cmd.PlayerStateCMD.attacks
import pubg.radar.struct.cmd.PlayerStateCMD.playerNames
import pubg.radar.struct.cmd.PlayerStateCMD.playerNumKills
import pubg.radar.struct.cmd.PlayerStateCMD.selfID
import pubg.radar.struct.cmd.PlayerStateCMD.selfStateID
import pubg.radar.struct.cmd.PlayerStateCMD.teamNumbers
import pubg.radar.util.tuple5
import wumo.pubg.struct.cmd.TeamCMD.team
import java.security.Key
import java.text.DecimalFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.pow
typealias renderInfo = tuple5<Actor, Float, Float, Float, Float>
//fun Float.d(n: Int) = String.format("%.${n}f", this)
class GLMap : InputAdapter(), ApplicationListener, GameListener {
companion object {
operator fun Vector3.component1(): Float = x
operator fun Vector3.component2(): Float = y
operator fun Vector3.component3(): Float = z
operator fun Vector2.component1(): Float = x
operator fun Vector2.component2(): Float = y
val spawnErangel = Vector2(795548.3f, 17385.875f)
val spawnDesert = Vector2(78282f, 731746f)
}
init {
register(this)
}
var firstAttach = true
override fun onGameStart() {
selfCoords.setZero()
selfAttachTo = null
firstAttach = true
/*
preSelfCoords.set(if (isErangel) GLMap.spawnErangel else GLMap.spawnDesert)
selfCoords.set(preSelfCoords)
preDirection.setZero()
*/
}
override fun onGameOver() {
camera.zoom = 2 / 4f
aimStartTime.clear()
attackLineStartTime.clear()
pinLocation.setZero()
}
fun show() {
val config = Lwjgl3ApplicationConfiguration()
config.setTitle("RageRadar 1.5")
config.useOpenGL3(false, 2, 1)
config.setWindowedMode(1200, 800)
config.setResizable(true)
config.setBackBufferConfig(4, 4, 4, 4, 16, 4, 8)
Lwjgl3Application(this, config)
}
private var playersize = 5f
private var self2Coords = Vector2(0f, 0f)
private lateinit var spriteBatch: SpriteBatch
private lateinit var shapeRenderer: ShapeRenderer
var allPlayers : ArrayList<renderInfo>? = null
private lateinit var mapErangelTiles: MutableMap<String, MutableMap<String, MutableMap<String, Texture>>>
private lateinit var mapMiramarTiles: MutableMap<String, MutableMap<String, MutableMap<String, Texture>>>
private lateinit var mapTiles: MutableMap<String, MutableMap<String, MutableMap<String, Texture>>>
private lateinit var iconImages: Icons
private lateinit var corpseboximage: Texture
private lateinit var airdropimage: Texture
private lateinit var largeFont: BitmapFont
private lateinit var littleFont: BitmapFont
private lateinit var itemNameFont: BitmapFont
private lateinit var nameFont: BitmapFont
private lateinit var nameFontRed: BitmapFont
private lateinit var nameFontGreen: BitmapFont
private lateinit var nameFontOrange: BitmapFont
private lateinit var itemFont: BitmapFont
private lateinit var fontCamera: OrthographicCamera
private lateinit var itemCamera: OrthographicCamera
private lateinit var camera: OrthographicCamera
lateinit var mapCamera : OrthographicCamera
private lateinit var alarmSound: Sound
private lateinit var hubpanel: Texture
private lateinit var hubpanelblank: Texture
private lateinit var vehicle: Texture
private lateinit var plane: Texture
private lateinit var boat: Texture
private lateinit var bike: Texture
private lateinit var bike3x: Texture
private lateinit var buggy: Texture
private lateinit var van: Texture
private lateinit var pickup: Texture
private lateinit var vehicle_b: Texture
private lateinit var jetski_b: Texture
private lateinit var boat_b: Texture
private lateinit var bike_b: Texture
private lateinit var bike3x_b: Texture
private lateinit var buggy_b: Texture
private lateinit var van_b: Texture
private lateinit var pickup_b: Texture
private lateinit var arrow: Texture
private lateinit var arrowsight: Texture
private lateinit var jetski: Texture
private lateinit var player: Texture
private lateinit var teamplayer: Texture
private lateinit var teamplayersight: Texture
private lateinit var playersight: Texture
private lateinit var parachute: Texture
private lateinit var parachute_team: Texture
private lateinit var parachute_self: Texture
private lateinit var grenade: Texture
private lateinit var hubFont: BitmapFont
private lateinit var hubFontSmall: BitmapFont
private lateinit var hubFont1: BitmapFont
private lateinit var hubFontShadow: BitmapFont
private lateinit var espFont: BitmapFont
private lateinit var espFontShadow: BitmapFont
private lateinit var compaseFont: BitmapFont
private lateinit var compaseFontShadow: BitmapFont
private lateinit var littleFontShadow: BitmapFont
val clipBound = Rectangle()
val healthBarWidth = 15000f
val healthBarHeight = 2000f
val gridWidth = 813000f
val runSpeed = 6.3 * 100//6.3m/s
val unit = gridWidth / 8
val unit2 = unit / 10
val visionRadius = mapWidth / 10
val attackLineDuration = 1000
val pinRadius = 4000f
private val tileZooms = listOf("256", "512", "1024", "2048", "4096", "8192")
private val tileRowCounts = listOf(1, 2, 4, 8, 16, 32)
private val tileSizes = listOf(819200f, 409600f, 204800f, 102400f, 51200f, 25600f)
private val layout = GlyphLayout()
private var windowWidth = initialWindowWidth
private var windowHeight = initialWindowWidth
private val aimStartTime = HashMap<NetworkGUID, Long>()
private val attackLineStartTime = LinkedList<Triple<NetworkGUID, NetworkGUID, Long>>()
private val pinLocation = Vector2()
private var filterWeapon = 1
private var filterAttach = 1
private var filterLvl2 = 1
private var filterScope = 1
private var filterHeals = 1
private var filterAmmo = 1
private var filterThrow = 1
private var filterLevel3 = -1
private var laptopToggle = -1
private var filterNames = -1
private var filterUseless = 1
private var toggleView = 1
private var toggleAirDropLines = 1
private var neverShow = arrayListOf("")
private var allItems = arrayListOf("")
private var scopesToFilter = arrayListOf("")
private var weaponsToFilter = arrayListOf("")
private var attachToFilter = arrayListOf("")
private var level2Filter = arrayListOf("")
private var specialItems = arrayListOf("")
private var healsToFilter = arrayListOf("")
private var ammoToFilter = arrayListOf("")
private var lvl3Filter = arrayListOf("")
private var dragging = false
private var prevScreenX = -1f
private var prevScreenY = -1f
private var screenOffsetX = 0f
private var screenOffsetY = 0f
private var toggleVehicles = -1
private var drawGrid = 1
private var showZ = 1
private var toggleVNames = 1
private fun windowToMap(x: Float, y: Float) =
Vector2(selfCoords.x + (x - windowWidth / 2.0f) * camera.zoom * windowToMapUnit + screenOffsetX,
selfCoords.y + (y - windowHeight / 2.0f) * camera.zoom * windowToMapUnit + screenOffsetY)
private fun mapToWindow(x: Float, y: Float) =
Vector2((x - selfCoords.x - screenOffsetX) / (camera.zoom * windowToMapUnit) + windowWidth / 2.0f,
(y - selfCoords.y - screenOffsetY) / (camera.zoom * windowToMapUnit) + windowHeight / 2.0f)
fun Vector2.mapToWindow() = mapToWindow(x, y)
fun Vector2.windowToMap() = windowToMap(x, y)
override fun scrolled(amount: Int): Boolean {
if (camera.zoom > 0.035f && camera.zoom < 1.09f) {
camera.zoom *= 1.05f.pow(amount)
} else {
if (camera.zoom < 0.035f) {
camera.zoom = 0.041f
println("Max Zoom")
}
if (camera.zoom > 1.09f) {
camera.zoom = 1.089f
println("Min Zoom")
}
}
return true
}
override fun touchDown(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
when (button) {
RIGHT -> {
pinLocation.set(pinLocation.set(screenX.toFloat(), screenY.toFloat()).windowToMap())
camera.update()
println(pinLocation)
return true
}
LEFT -> {
dragging = true
prevScreenX = screenX.toFloat()
prevScreenY = screenY.toFloat()
return true
}
MIDDLE -> {
screenOffsetX = 0f
screenOffsetY = 0f
}
}
return false
}
override fun keyDown(keycode: Int): Boolean {
if (laptopToggle != -1) { // Laptop Mode ON
when (keycode) {
V -> filterUseless = filterUseless * -1 //Filter Trash ON / OFF
F -> filterLevel3 = filterLevel3 * -1 //Filter Level 3 Itesm ON / OFF
A -> filterWeapon = filterWeapon * -1 // Filter Weapons ON / OFF
Z -> filterAttach = filterAttach * -1 // Filter Attachments ON / OFF
D -> filterLvl2 = filterLvl2 * -1 //Filter Equipment ON / OFF
S -> filterScope = filterScope * -1 // Filter Scopes ON / OFF
C -> filterHeals = filterHeals * -1 // Filte Heals ON / OFF
X -> filterAmmo = filterAmmo * -1 // Filter AMMO ON / OFF
Q -> camera.zoom = 1 / 6f //Zoom to SA View
W -> camera.zoom = 1 / 12f //Zoom to FAR loot view
E -> camera.zoom = 1 / 32f //Zoom to CLOSE loot view
ENTER -> { // Center on Player
screenOffsetX = 0f
screenOffsetY = 0f
}
// Zoom In/Out || Overrides Max/Min Zoom
LEFT_BRACKET -> camera.zoom = camera.zoom + 0.00525f //Zoom OUT
RIGHT_BRACKET -> camera.zoom = camera.zoom - 0.00525f //Zoom IN
// Toggle Transparent Player Icons
F1 -> laptopToggle = laptopToggle * -1 //Toggle Laptop-Keys Mode
NUM_4 -> showZ = showZ * -1 // Show if items are above/below/equal with player.
NUM_7 -> toggleVehicles = toggleVehicles * -1 //Toggle Vehicles (DEFAULT ON)
NUM_6 -> toggleVNames = toggleVNames * -1 //Toggle Vehicle Names (Default OFF)
NUM_8 -> filterNames = filterNames * -1 //Show Player Names (Default ON)
NUM_5 -> drawGrid = drawGrid * -1 //Show Grid (Default ON)
NUM_9 -> toggleAirDropLines = toggleAirDropLines * -1 //Show Lines to Airdrops
NUM_0 -> toggleView = toggleView * -1 //Show View Lines (Default ON)
}
} else { // Laptop Mode OFF
when (keycode) {
// Icon Filters
PERIOD -> filterUseless = filterUseless * -1 //Filter Trash ON / OFF
NUMPAD_0 -> filterLevel3 = filterLevel3 * -1 //Filter Level 3 Items ON / OFF
NUMPAD_4 -> filterWeapon = filterWeapon * -1 //Filter Weapons ON / OFF
NUMPAD_1 -> filterAttach = filterAttach * -1 //Filter Attachments ON / OFF
NUMPAD_6 -> filterLvl2 = filterLvl2 * -1 //Filter Equip ON / OFF
NUMPAD_5 -> filterScope = filterScope * -1 //Filter Scopes ON / OFF
NUMPAD_3 -> filterHeals = filterHeals * -1 //Filter Heals ON / OFF
NUMPAD_2 -> filterAmmo = filterAmmo * -1 //Turn AMMO Filter ON/OFF
NUMPAD_7 -> camera.zoom = 1 / 6f //Zoom to SA view
NUMPAD_8 -> camera.zoom = 1 / 12f //Zoom to FAR loot view
NUMPAD_9 -> camera.zoom = 1 / 32f //Zoom to Close loot view
ENTER -> { //Center on Player
screenOffsetX = 0f
screenOffsetY = 0f
}
// Functions
F1 -> laptopToggle = laptopToggle * -1 //Switch to Laptop Keys
F4 -> showZ = showZ * -1 // Show if items are above/below/equal with player.
F7 -> toggleVehicles = toggleVehicles * -1 //Show Vehicles (Default ON)
F6 -> toggleVNames = toggleVNames * -1 //Show Vehicle Names (Default OFF)
F8 -> filterNames = filterNames * -1 //Show Names (Default ON)
F5 -> drawGrid = drawGrid * -1 //Toggle Grid (Default ON)
F9 -> toggleAirDropLines = toggleAirDropLines * -1 //Show Lines to Airdrops
F11 -> toggleView = toggleView * -1 //Toggle View Lines (Default ON)
// F12 -> ForceRestart() //NOT YET IMPLEMENTED
// Zoom In/Out || Overrides Max/Min Zoom
MINUS -> camera.zoom = camera.zoom + 0.00525f //Zoom OUT
PLUS -> camera.zoom = camera.zoom - 0.00525f //Zoom IN
}
}
return false
}
override fun touchDragged(screenX: Int, screenY: Int, pointer: Int): Boolean {
if (!dragging) return false
with(camera) {
screenOffsetX += (prevScreenX - screenX.toFloat()) * camera.zoom * 500
screenOffsetY += (prevScreenY - screenY.toFloat()) * camera.zoom * 500
prevScreenX = screenX.toFloat()
prevScreenY = screenY.toFloat()
}
return true
}
override fun touchUp(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
if (button == LEFT) {
dragging = false
return true
}
return false
}
override fun create() {
spriteBatch = SpriteBatch()
shapeRenderer = ShapeRenderer()
Gdx.input.inputProcessor = this
camera = OrthographicCamera(windowWidth, windowHeight)
with(camera) {
setToOrtho(true, windowWidth * windowToMapUnit, windowHeight * windowToMapUnit)
zoom = 1 / 4f
update()
position.set(mapWidth / 2, mapWidth / 2, 0f)
update()
}
itemCamera = OrthographicCamera(initialWindowWidth, initialWindowWidth)
fontCamera = OrthographicCamera(initialWindowWidth, initialWindowWidth)
alarmSound = Gdx.audio.newSound(Gdx.files.internal("sounds/Alarm.wav"))
hubpanel = Texture(Gdx.files.internal("images/hub_panel.png"))
hubpanelblank = Texture(Gdx.files.internal("images/hub_panel_blank_long.png"))
corpseboximage = Texture(Gdx.files.internal("icons/box.png"))
airdropimage = Texture(Gdx.files.internal("icons/airdrop.png"))
vehicle = Texture(Gdx.files.internal("images/vehicle.png"))
arrow = Texture(Gdx.files.internal("images/arrow.png"))
plane = Texture(Gdx.files.internal("images/plane.png"))
player = Texture(Gdx.files.internal("images/player.png"))
teamplayer = Texture(Gdx.files.internal("images/team.png"))
playersight = Texture(Gdx.files.internal("images/green_view_line.png"))
teamplayersight = Texture(Gdx.files.internal("images/teamsight.png"))
arrowsight = Texture(Gdx.files.internal("images/red_view_line.png"))
parachute = Texture(Gdx.files.internal("images/parachute.png"))
parachute_team = Texture(Gdx.files.internal("images/parachuteteam.png"))
parachute_self = Texture(Gdx.files.internal("images/parachuteplayer.png"))
boat = Texture(Gdx.files.internal("images/boat.png"))
bike = Texture(Gdx.files.internal("images/bike.png"))
jetski = Texture(Gdx.files.internal("images/jetski.png"))
bike3x = Texture(Gdx.files.internal("images/bike3x.png"))
pickup = Texture(Gdx.files.internal("images/pickup.png"))
van = Texture(Gdx.files.internal("images/van.png"))
buggy = Texture(Gdx.files.internal("images/buggy.png"))
boat_b = Texture(Gdx.files.internal("images/boat_b.png"))
vehicle_b = Texture(Gdx.files.internal("images/vehicle_b.png"))
bike_b = Texture(Gdx.files.internal("images/bike_b.png"))
jetski_b = Texture(Gdx.files.internal("images/jetski_b.png"))
bike3x_b = Texture(Gdx.files.internal("images/bike3x_b.png"))
pickup_b = Texture(Gdx.files.internal("images/pickup_b.png"))
van_b = Texture(Gdx.files.internal("images/van_b.png"))
buggy_b = Texture(Gdx.files.internal("images/buggy_b.png"))
grenade = Texture(Gdx.files.internal("images/grenade.png"))
iconImages = Icons(Texture(Gdx.files.internal("images/item-sprites.png")), 64)
mapErangelTiles = mutableMapOf()
mapMiramarTiles = mutableMapOf()
var cur = 0
tileZooms.forEach {
mapErangelTiles[it] = mutableMapOf()
mapMiramarTiles[it] = mutableMapOf()
for (i in 1..tileRowCounts[cur]) {
val y = if (i < 10) "0$i" else "$i"
mapErangelTiles[it]?.set(y, mutableMapOf())
mapMiramarTiles[it]?.set(y, mutableMapOf())
for (j in 1..tileRowCounts[cur]) {
val x = if (j < 10) "0$j" else "$j"
mapErangelTiles[it]!![y]?.set(x, Texture(Gdx.files.internal("tiles/Erangel/$it/${it}_${y}_$x.png")))
mapMiramarTiles[it]!![y]?.set(x, Texture(Gdx.files.internal("tiles/Miramar/$it/${it}_${y}_$x.png")))
}
}
cur++
}
mapTiles = mapErangelTiles
val generatorHub = FreeTypeFontGenerator(Gdx.files.internal("font/AGENCYFB.TTF"))
val paramHub = FreeTypeFontParameter()
val hubhub = FreeTypeFontParameter()
hubhub.characters = DEFAULT_CHARS
hubhub.size = 24
hubhub.color = WHITE
hubFont1 = generatorHub.generateFont(hubhub)
paramHub.characters = DEFAULT_CHARS
paramHub.size = 30
paramHub.color = WHITE
hubFont = generatorHub.generateFont(paramHub)
paramHub.color = Color(1f, 1f, 1f, 0.4f)
hubFontShadow = generatorHub.generateFont(paramHub)
paramHub.size = 16
paramHub.color = WHITE
espFont = generatorHub.generateFont(paramHub)
paramHub.color = Color(1f, 1f, 1f, 0.2f)
espFontShadow = generatorHub.generateFont(paramHub)
paramHub.borderColor = Color.BLACK;
paramHub.borderWidth = 3f;
paramHub.characters = DEFAULT_CHARS
paramHub.size = 12
paramHub.color = WHITE
hubFontSmall = generatorHub.generateFont(paramHub)
val generatorNumber = FreeTypeFontGenerator(Gdx.files.internal("font/NUMBER.TTF"))
val paramNumber = FreeTypeFontParameter()
paramNumber.characters = DEFAULT_CHARS
paramNumber.size = 24
paramNumber.color = WHITE
largeFont = generatorNumber.generateFont(paramNumber)
val generator = FreeTypeFontGenerator(Gdx.files.internal("font/GOTHICB.TTF"))
val param = FreeTypeFontParameter()
param.characters = DEFAULT_CHARS
param.size = 38
param.color = WHITE
largeFont = generator.generateFont(param)
param.size = 15
param.color = WHITE
littleFont = generator.generateFont(param)
param.borderColor = Color.BLACK;
param.borderWidth = 1.5f;
param.color = WHITE
param.size = 20
itemNameFont = generator.generateFont(param)
param.borderColor = Color.BLACK;
param.borderWidth = 1f;
param.color = WHITE
param.size = 10
nameFont = generator.generateFont(param)
param.color = RED
param.size = 10
nameFontRed = generator.generateFont(param)
val healthColor = Color(0f, 0.392f, 0f, 1f)
param.color = healthColor
param.size = 10
nameFontGreen = generator.generateFont(param)
param.color = ORANGE
param.size = 10
nameFontOrange = generator.generateFont(param)
param.color = WHITE
param.size = 6
itemFont = generator.generateFont(param)
val compaseColor = Color(0f, 0.95f, 1f, 1f) //Turquoise1
param.color = compaseColor
param.size = 10
compaseFont = generator.generateFont(param)
param.size = 20
param.color = Color(0f, 0f, 0f, 0.5f)
compaseFontShadow = generator.generateFont(param)
param.characters = DEFAULT_CHARS
param.size = 20
param.color = WHITE
littleFont = generator.generateFont(param)
param.color = Color(0f, 0f, 0f, 0.5f)
littleFontShadow = generator.generateFont(param)
generatorHub.dispose()
generatorNumber.dispose()
generator.dispose()
}
override fun render() {
Gdx.gl.glClearColor(0.417f, 0.417f, 0.417f, 0f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
if (gameStarted)
mapTiles = if (isErangel) mapErangelTiles else mapMiramarTiles
else return
val currentTime = System.currentTimeMillis()
// CharMovComp
selfAttachTo?.apply {
if (Type == Plane || Type == Parachute) {
firstAttach = false
selfCoords.set(location.x, location.y, location.z)
selfHeight = location.z
selfDirection = rotation.y
} else {
firstAttach = false
selfCoords.set(location.x, location.y, location.z)
selfHeight = location.z
selfDirection = rotation.y
}
}
val (selfX, selfY, selfZ) = selfCoords
self2Coords = Vector2(selfX, selfY)
//move camera
camera.position.set(selfX + screenOffsetX, selfY + screenOffsetY, 0f)
camera.update()
val cameraTileScale = Math.max(windowWidth, windowHeight) / camera.zoom
val useScale: Int
useScale = when {
cameraTileScale > 8192 -> 5
cameraTileScale > 4096 -> 4
cameraTileScale > 2048 -> 3
cameraTileScale > 1024 -> 2
cameraTileScale > 512 -> 1
cameraTileScale > 256 -> 0
else -> 0
}
val (tlX, tlY) = Vector2(0f, 0f).windowToMap()
val (brX, brY) = Vector2(windowWidth, windowHeight).windowToMap()
val tileZoom = tileZooms[useScale]
val tileRowCount = tileRowCounts[useScale]
val tileSize = tileSizes[useScale]
val xMin = (tlX.toInt() / tileSize.toInt()).coerceIn(1, tileRowCount)
val xMax = ((brX.toInt() + tileSize.toInt()) / tileSize.toInt()).coerceIn(1, tileRowCount)
val yMin = (tlY.toInt() / tileSize.toInt()).coerceIn(1, tileRowCount)
val yMax = ((brY.toInt() + tileSize.toInt()) / tileSize.toInt()).coerceIn(1, tileRowCount)
paint(camera.combined) {
for (i in yMin..yMax) {
val y = if (i < 10) "0$i" else "$i"
for (j in xMin..xMax) {
val x = if (j < 10) "0$j" else "$j"
val tileStartX = (j - 1) * tileSize
val tileStartY = (i - 1) * tileSize
draw(mapTiles[tileZoom]!![y]!![x], tileStartX, tileStartY, tileSize, tileSize,
0, 0, 256, 256,
false, true)
}
}
}
shapeRenderer.projectionMatrix = camera.combined
Gdx.gl.glEnable(GL20.GL_BLEND)
drawCircles()
val typeLocation = EnumMap<Archetype, MutableList<renderInfo>>(Archetype::class.java)
for ((_, actor) in visualActors) {
typeLocation.compute(actor.Type) { _, v ->
val list = v ?: ArrayList()
val (centerX, centerY) = actor.location
val direction = actor.rotation.y
allPlayers?.add(tuple5(actor, centerX, centerY, actor.location.z, direction))
list.add(tuple5(actor, centerX, centerY, actor.location.z, direction))
list
}
}
//val playerStateGUID = actorWithPlayerState[selfID] ?: return
//val numKills = playerNumKills[playerStateGUID] ?: 0
//val zero = numKills.toString()
paint(fontCamera.combined) {
// NUMBER PANEL
val numText = "$NumAlivePlayers"
layout.setText(hubFont, numText)
spriteBatch.draw(hubpanel, windowWidth - 130f, windowHeight - 60f)
hubFontShadow.draw(spriteBatch, "ALIVE", windowWidth - 85f, windowHeight - 29f)
hubFont.draw(spriteBatch, "$NumAlivePlayers", windowWidth - 110f - layout.width / 2, windowHeight - 29f)
val teamText = "${GameStateCMD.NumAliveTeams}"
if (teamText != numText && teamText > "0") {
layout.setText(hubFont, teamText)
spriteBatch.draw(hubpanel, windowWidth - 260f, windowHeight - 60f)
hubFontShadow.draw(spriteBatch, "TEAM", windowWidth - 215f, windowHeight - 29f)
hubFont.draw(spriteBatch, "${GameStateCMD.NumAliveTeams}", windowWidth - 240f - layout.width / 2, windowHeight - 29f)
}
// ITEM ESP FILTER PANEL
spriteBatch.draw(hubpanelblank, 30f, windowHeight - 60f)
// This is what you were trying to do
if (filterWeapon != 1)
espFont.draw(spriteBatch, "WEAPON", 40f, windowHeight - 25f)
else
espFontShadow.draw(spriteBatch, "WEAPON", 40f, windowHeight - 25f)
if (filterAttach != 1)
espFont.draw(spriteBatch, "ATTACH", 40f, windowHeight - 42f)
else
espFontShadow.draw(spriteBatch, "ATTACH", 40f, windowHeight - 42f)
if (filterScope != 1)
espFont.draw(spriteBatch, "SCOPE", 100f, windowHeight - 25f)
else
espFontShadow.draw(spriteBatch, "SCOPE", 100f, windowHeight - 25f)
if (filterAmmo != 1)
espFont.draw(spriteBatch, "AMMO", 100f, windowHeight - 42f)
else
espFontShadow.draw(spriteBatch, "AMMO", 100f, windowHeight - 42f)
if (filterLvl2 != 1)
espFont.draw(spriteBatch, "EQUIP", 150f, windowHeight - 25f)
else
espFontShadow.draw(spriteBatch, "EQUIP", 150f, windowHeight - 25f)
if (filterHeals != 1)
espFont.draw(spriteBatch, "HEALS", 150f, windowHeight - 42f)
else
espFontShadow.draw(spriteBatch, "HEALS", 150f, windowHeight - 42f)
if (filterLevel3 != 1)
espFont.draw(spriteBatch, "LEVEL3", 200f, windowHeight - 25f)
else
espFontShadow.draw(spriteBatch, "LEVEL3", 200f, windowHeight - 25f)
if (filterUseless != 1)
espFont.draw(spriteBatch, "TRASH", 200f, windowHeight - 42f)
else
espFontShadow.draw(spriteBatch, "TRASH", 200f, windowHeight - 42f)
if (laptopToggle == 1) {
espFont.draw(spriteBatch, "[F1] Laptop Mode ON", 270f, windowHeight - 25f)
} else {
espFont.draw(spriteBatch, "[F1] Laptop Mode OFF", 270f, windowHeight - 25f)
}
val pinDistance = (pinLocation.cpy().sub(selfX, selfY).len() / 100).toInt()
val (x, y) = pinLocation.mapToWindow()
safeZoneHint()
drawPlayerNames(typeLocation[Player], selfX, selfY)
littleFont.draw(spriteBatch, "$pinDistance", x, windowHeight - y)
}
// This makes the array empty if the filter is off for performance with an inverted function since arrays are expensive
scopesToFilter = if (filterScope != 1) {
arrayListOf("")
} else {
arrayListOf("DotSight", "Aimpoint", "Holosight")
}
neverShow = if (filterUseless != 1) {
arrayListOf("")
} else {
arrayListOf("Armor1", "Bag1", "Helmet1", "U.Ext", "AR.Ext", "S.Ext", "U.ExtQ", "Choke", "FH", "U.Supp", "UMP", "Vector", "UZI", "Pan", "Bandage", "9mm", "45mm", "FlashBang", "SmokeBomb", "Molotov", "SawnOff","Crowbar","Sickle","Machete","Pan","Crossbow","R45", "R1895","P92","P1911","P18C")
}
attachToFilter = if (filterAttach != 1) {
arrayListOf("")
} else {
arrayListOf("AR.Stock", "S.Loops", "CheekPad", "A.Grip", "V.Grip", "AR.ExtQ", "S.ExtQ", "AR.Comp", "AR.Supp", "S.Supp", "S.Comp")
}
weaponsToFilter = if (filterWeapon != 1) {
arrayListOf("")
} else {
arrayListOf("M16A4", "SCAR-L", "AK47", "SKS", "Mini14", "DP28")
}
healsToFilter = if (filterHeals != 1) {
arrayListOf("")
} else {
arrayListOf("FirstAid", "MedKit", "Drink", "Pain", "Syringe")
}
ammoToFilter = if (filterAmmo != 1) {
arrayListOf("")
} else {
arrayListOf("556mm", "762mm", "300mm")
}
lvl3Filter = if (filterLevel3 != 1) {
arrayListOf("")
} else {
arrayListOf("Helmet3", "Armor3", "Bag3", "CQBSS", "ACOG", "HK416", "Kar98k")
}
level2Filter = if (filterLvl2 != 1) {
arrayListOf("")
} else {
arrayListOf("Bag2", "Armor2", "Helmet2", "Grenade")
}
specialItems = arrayListOf("AWM", "M24", "M249", "Mk14", "Groza", "G1B", "AUG", "Helmet3", "Armor3", "Bag3", "Syringe", "MedKit", "AR.Supp", "S.Supp", "CQBSS", "ACOG", "GhillieBrown", "GhillieGreen")
val iconScale = 1f / camera.zoom
paint(itemCamera.combined) {
droppedItemLocation.values
.forEach {
val (x, y, z) = it._1
val items = it._2
val (sx, sy) = Vector2(x, y).mapToWindow()
val syFix = windowHeight - sy
items.forEach {
if ((items !in neverShow && items !in weaponsToFilter && items !in scopesToFilter && items !in attachToFilter && items !in level2Filter
&& items !in ammoToFilter && items !in healsToFilter && items !in lvl3Filter)
&& iconScale > 11 && sx > 0 && sx < windowWidth && syFix > 0 && syFix < windowHeight) {
iconImages.setIcon(items)
draw(iconImages.icon,
sx - 10, syFix - 10,
30f, 30f)
if (showZ == 1) {
if (z > (selfCoords.z + 200)) {
itemNameFont.draw(spriteBatch, "^", sx-5,windowHeight - sy+5)
} else if (z < (selfCoords.z - 100)) {
itemNameFont.draw(spriteBatch, "v", sx-5 ,windowHeight - sy+5)
} else {
itemNameFont.draw(spriteBatch, "o", sx-5,windowHeight - sy+5)
}
}
}
}
}
//Draw Corpse Icon
corpseLocation.values.forEach {
val (x, y) = it
val (sx, sy) = Vector2(x + 16, y - 16).mapToWindow()
val syFix = windowHeight - sy
val iconScale = 2f / camera.zoom
spriteBatch.draw(corpseboximage, sx - iconScale / 2, syFix + iconScale / 2, iconScale, -iconScale,
0, 0, 64, 64,
false, true)
}
//Draw Airdrop Icon
airDropLocation.keys.forEach {
val grid = airDropLocation[it] ?: return@forEach
val items = itemBag[it]
val (x, y) = grid
val (sx, sy) = Vector2(x, y).mapToWindow()
val syFix = windowHeight - sy
val iconScale = if (camera.zoom < 1 / 14f) {
2f / camera.zoom
} else {
2f / (1 / 15f)
}
spriteBatch.draw(airdropimage, sx - iconScale / 2, syFix + iconScale / 2, iconScale, -iconScale,
0, 0, 64, 64,
false, true)
if(items?.size != 0) {
val fontText = "ITEMS: ${items?.size}"
var wep_xoff = getPositionOffset(nameFont,fontText)
nameFontGreen.draw(spriteBatch,
"${fontText}", sx - wep_xoff.toFloat() - 5, windowHeight - sy +20)
} else {
val fontText = "EMPTY"
var wep_xoff = getPositionOffset(nameFont,fontText)
nameFontRed.draw(spriteBatch,
"${fontText}", sx - wep_xoff.toFloat() - 5, windowHeight - sy +20)
}
val loot = airDropItems[it]
loot?.forEachIndexed { i, item ->
val offset = (i+1) * 13
val item = item
nameFont.draw(spriteBatch, "| $item",
sx +15, windowHeight - sy + 45 - offset)
}
}
//OLD
//drawMyself(tuple4(null, selfX, selfY, selfDir.angle()))
drawPawns(typeLocation)
drawMyself(tuple5(null, selfX, selfY, selfHeight, selfDirection))
}
val zoom = camera.zoom
Gdx.gl.glEnable(GL20.GL_BLEND)
draw(Filled) {
color = redZoneColor
circle(RedZonePosition, RedZoneRadius, 500)
color = visionColor
circle(selfX, selfY, visionRadius, 500)
color = pinColor
circle(pinLocation, pinRadius * zoom, 10)
drawPlayersH(typeLocation[Player])
}
drawGrid()
drawAirdropDir()
drawAttackLine(currentTime)
//OLD
//preSelfCoords.set(selfX,selfY)
//preDirection = selfDir
Gdx.gl.glDisable(GL20.GL_BLEND)
}
private fun ShapeRenderer.drawPlayersH(players: MutableList<renderInfo>?)
{
players?.forEach {
drawAllPlayerHealth(Color(0x32cd32ff) , it)
}
}
private fun drawMyself(actorInfo: renderInfo) {
val (_, x, y, z, dir) = actorInfo
val (sx, sy) = Vector2(x, y).mapToWindow()
var parents = actors[selfID]?.attachParent
if (parents == null) {
if (toggleView != -1) {
spriteBatch.draw(
playersight,
sx + 1, windowHeight - sy - 2,
2.toFloat() / 2,
2.toFloat() / 2,
12.toFloat(), 2.toFloat(),
20f, 10f,
dir * -1, 0, 0, 800, 64, true, false)
}
spriteBatch.draw(
player,
sx, windowHeight - sy - 2, 4.toFloat() / 2,
4.toFloat() / 2, 4.toFloat(), 4.toFloat(), 6f, 5f,
dir * -1, 0, 0, 64, 64, true, false)
}
}
private fun drawAttackLine(currentTime: Long) {
while (attacks.isNotEmpty()) {
val (A, B) = attacks.poll()
attackLineStartTime.add(Triple(A, B, currentTime))
}
if (attackLineStartTime.isEmpty()) return
draw(Line) {
val iter = attackLineStartTime.iterator()
while (iter.hasNext()) {
val (A, B, st) = iter.next()
if (A == selfStateID || B == selfStateID) {
if (A != B) {
val otherGUID = playerStateToActor[if (A == selfStateID) B else A]
if (otherGUID == null) {
iter.remove()
continue
}
val other = actors[otherGUID]
if (other == null || currentTime - st > attackLineDuration) {
iter.remove()
continue
}
color = attackLineColor
val (xA, yA, zA) = other.location
val (xB, yB, zB) = selfCoords
line(xA, yA, xB, yB)
}
} else {
val actorAID = playerStateToActor[A]
val actorBID = playerStateToActor[B]
if (actorAID == null || actorBID == null) {
iter.remove()
continue
}
val actorA = actors[actorAID]
val actorB = actors[actorBID]
if (actorA == null || actorB == null || currentTime - st > attackLineDuration) {
iter.remove()
continue
}
color = attackLineColor
val (xA, yA, zA) = actorA.location
val (xB, yB, zB) = actorB.location
line(xA, yA, xB, yB)
}
}
}
}
private fun drawCircles() {
Gdx.gl.glLineWidth(2f)
draw(Line) {
//vision circle
color = safeZoneColor
circle(PoisonGasWarningPosition, PoisonGasWarningRadius, 100)
color = BLUE
circle(SafetyZonePosition, SafetyZoneRadius, 100)
if (PoisonGasWarningPosition.len() > 0) {
color = safeDirectionColor
line(self2Coords, PoisonGasWarningPosition)
}
}
Gdx.gl.glLineWidth(1f)
}
private fun drawAirdropDir() {
Gdx.gl.glLineWidth(1f)
if (toggleAirDropLines == 1) {
draw(Line) {
airDropLocation.keys.forEach {
val grid = airDropLocation[it] ?: return@forEach
val items = itemBag[it]
val (x, y,z) = grid
val airdropcoords = (Vector2(x, y))
color = YELLOW
if(items?.size != 0) {
line(self2Coords, airdropcoords)
}
}
Gdx.gl.glDisable(GL20.GL_BLEND)
}
}
}
private fun drawGrid() {
if (drawGrid != 1) {
draw(Filled) {
color = BLACK
//thin grid
for (i in 0..7)
for (j in 0..9) {
rectLine(0f, i * unit + j * unit2, gridWidth, i * unit + j * unit2, 100f)
rectLine(i * unit + j * unit2, 0f, i * unit + j * unit2, gridWidth, 100f)
}
color = BLACK
//thick grid
for (i in 0..7) {
rectLine(0f, i * unit, gridWidth, i * unit, 250f)
rectLine(i * unit, 0f, i * unit, gridWidth, 250f)
}
}
}
}
private fun drawPawns(typeLocation: EnumMap<Archetype, MutableList<renderInfo>>) {
val iconScale = 3f / camera.zoom
for ((type, actorInfos) in typeLocation) {
when (type) {
TwoSeatBoat -> actorInfos?.forEach {
if (toggleVehicles != 1) {
val (actor, x, y, z, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
if (toggleVNames != 1) compaseFont.draw(spriteBatch, "JSKI", sx + 15, windowHeight - sy - 2)
val v_x = actor!!.velocity.x
val v_y = actor.velocity.y
var iconSize = iconScale/2
when {
playersize*4 > iconScale/2 -> iconSize = (playersize*4).toFloat()
else -> iconSize = (iconScale/2).toFloat()
}
if (actor.attachChildren.isNotEmpty() || v_x * v_x + v_y * v_y > 100) { //occupied
val numPlayers = actor.attachChildren?.size
spriteBatch.draw(
jetski,
sx + 2, windowHeight - sy - 2, 2.toFloat() / 2,
2.toFloat() / 2, 2.toFloat(), 2.toFloat(), iconSize, iconSize,
dir * -1, 0, 0, 128, 128, true, false)
if(numPlayers > 0) nameFontRed.draw(spriteBatch, "$numPlayers", sx + 20, windowHeight - sy + 20)
} else {
spriteBatch.draw(
jetski_b,
sx + 2, windowHeight - sy - 2, 2.toFloat() / 2,
2.toFloat() / 2, 2.toFloat(), 2.toFloat(), iconScale / 2, iconScale / 2,
dir * -1, 0, 0, 128, 128, true, false
)
}
}
}
SixSeatBoat -> actorInfos?.forEach {
if (toggleVehicles != 1) {
val (actor, x, y, z, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
if (toggleVNames != 1) compaseFont.draw(spriteBatch, "BOAT", sx + 15, windowHeight - sy - 2)
val v_x = actor!!.velocity.x
val v_y = actor.velocity.y
var iconSize = iconScale/2
when {
playersize*4 > iconScale/2 -> iconSize = (playersize*4).toFloat()
else -> iconSize = (iconScale/2).toFloat()
}
if (actor.attachChildren.isNotEmpty() || v_x * v_x + v_y * v_y > 80) { //occupied
val numPlayers = actor.attachChildren?.size
spriteBatch.draw(
boat,
sx + 2, windowHeight - sy - 2, 2.toFloat() / 2,
2.toFloat() / 2, 2.toFloat(), 2.toFloat(), iconSize, iconSize,
dir * -1, 0, 0, 128, 128, true, false
)
if(numPlayers > 0) nameFontRed.draw(spriteBatch, "$numPlayers", sx + 20, windowHeight - sy + 20)
} else {
spriteBatch.draw(
boat_b,
sx + 2, windowHeight - sy - 2, 2.toFloat() / 2,
2.toFloat() / 2, 2.toFloat(), 2.toFloat(), iconScale, iconScale,
dir * -1, 0, 0, 128, 128, true, false
)
}
}
}
TwoSeatBike -> actorInfos?.forEach {
if (toggleVehicles != 1) {
val (actor, x, y, z, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
if (toggleVNames != 1) compaseFont.draw(spriteBatch, "BIKE", sx + 15, windowHeight - sy - 2)
val v_x = actor!!.velocity.x
val v_y = actor.velocity.y
var iconSize = iconScale/2
when {
playersize*4 > iconScale/2 -> iconSize = (playersize*4).toFloat()
else -> iconSize = (iconScale/2).toFloat()
}
if (actor.attachChildren.isNotEmpty() || v_x * v_x + v_y * v_y > 80) {
val numPlayers = actor.attachChildren?.size
spriteBatch.draw(
bike,
sx + 2, windowHeight - sy - 2, 2.toFloat() / 2,
2.toFloat() / 2, 2.toFloat(), 2.toFloat(), iconSize, iconSize,
dir * -1, 0, 0, 128, 128, true, false
)
if(numPlayers > 0) nameFontRed.draw(spriteBatch, "$numPlayers", sx + 20, windowHeight - sy + 20)
} else {
spriteBatch.draw(
bike_b,
sx + 2, windowHeight - sy - 2, 2.toFloat() / 2,
2.toFloat() / 2, 2.toFloat(), 2.toFloat(), iconScale / 3, iconScale / 3,
dir * -1, 0, 0, 128, 128, true, false
)
}
}
}
TwoSeatCar -> actorInfos?.forEach {
if (toggleVehicles != 1) {
val (actor, x, y, z, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
if (toggleVNames != 1) compaseFont.draw(spriteBatch, "BUGGY", sx + 15, windowHeight - sy - 2)
val v_x = actor!!.velocity.x
val v_y = actor.velocity.y
var iconSize = iconScale/2
when {
playersize*4 > iconScale/2 -> iconSize = (playersize*4).toFloat()
else -> iconSize = (iconScale/2).toFloat()
}
if (actor.attachChildren.isNotEmpty() || v_x * v_x + v_y * v_y > 80) {
val numPlayers = actor.attachChildren?.size
spriteBatch.draw(
buggy,
sx + 2, windowHeight - sy - 2,
2.toFloat() / 2, 2.toFloat() / 2,
2.toFloat(), 2.toFloat(),
iconSize, iconSize,
dir * -1, 0, 0, 128, 128, false, false
)
if(numPlayers > 0) nameFontRed.draw(spriteBatch, "$numPlayers", sx + 20, windowHeight - sy + 20)
} else {
spriteBatch.draw(
buggy_b,
sx + 2, windowHeight - sy - 2,
2.toFloat() / 2, 2.toFloat() / 2,
2.toFloat(), 2.toFloat(),
iconScale / 2, iconScale / 2,
dir * -1, 0, 0, 128, 128, false, false
)
}
}
}
ThreeSeatCar -> actorInfos?.forEach {
if (toggleVehicles != 1) {
val (actor, x, y, z, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
if (toggleVNames != 1) compaseFont.draw(spriteBatch, "BIKE", sx + 15, windowHeight - sy - 2)
val v_x = actor!!.velocity.x
val v_y = actor.velocity.y
var iconSize = iconScale/2
when {
playersize*4 > iconScale/2 -> iconSize = (playersize*4).toFloat()
else -> iconSize = (iconScale/2).toFloat()
}
if (actor.attachChildren.isNotEmpty() || v_x * v_x + v_y * v_y > 80) {
val numPlayers = actor.attachChildren?.size
spriteBatch.draw(
bike3x,
sx + 2, windowHeight - sy - 2, 2.toFloat() / 2, 2.toFloat() / 2,
2.toFloat(), 2.toFloat(), iconSize, iconSize,
dir * -1, 0, 0, 128, 128, true, false
)
if(numPlayers > 0) nameFontRed.draw(spriteBatch, "$numPlayers", sx + 20, windowHeight - sy + 20)
} else {
spriteBatch.draw(
bike3x_b,
sx + 2, windowHeight - sy - 2, 2.toFloat() / 2, 2.toFloat() / 2,
2.toFloat(), 2.toFloat(), iconScale / 2, iconScale / 2,
dir * -1, 0, 0, 128, 128, true, false
)
}
}
}
FourSeatDU -> actorInfos?.forEach {
if (toggleVehicles != 1) {
val (actor, x, y, z, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
if (toggleVNames != 1) compaseFont.draw(spriteBatch, "CAR", sx + 15, windowHeight - sy - 2)
val v_x = actor!!.velocity.x
val v_y = actor.velocity.y
var iconSize = iconScale/2
when {
playersize*4 > iconScale/2 -> iconSize = (playersize*4).toFloat()
else -> iconSize = (iconScale/2).toFloat()
}
if (actor.attachChildren.isNotEmpty() || v_x * v_x + v_y * v_y > 80) {
val numPlayers = actor.attachChildren?.size
spriteBatch.draw(
vehicle,
sx + 2, windowHeight - sy - 2,
2.toFloat() / 2, 2.toFloat() / 2,
2.toFloat(), 2.toFloat(),
iconSize, iconSize,
dir * -1, 0, 0, 128, 128, false, false
)
if(numPlayers > 0) nameFontRed.draw(spriteBatch, "$numPlayers", sx + 20, windowHeight - sy + 20)
} else {
spriteBatch.draw(
vehicle_b,
sx + 2, windowHeight - sy - 2,
2.toFloat() / 2, 2.toFloat() / 2,
2.toFloat(), 2.toFloat(),
iconScale / 2, iconScale / 2,
dir * -1, 0, 0, 128, 128, false, false
)
}
}
}
FourSeatP -> actorInfos?.forEach {
if (toggleVehicles != 1) {
val (actor, x, y, z, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
if (toggleVNames != 1) compaseFont.draw(spriteBatch, "PICKUP", sx + 15, windowHeight - sy - 2)
val v_x = actor!!.velocity.x
val v_y = actor.velocity.y
var iconSize = iconScale/2
when {
playersize*4 > iconScale/2 -> iconSize = (playersize*4).toFloat()
else -> iconSize = (iconScale/2).toFloat()
}
if (actor.attachChildren.isNotEmpty() || v_x * v_x + v_y * v_y > 80) {
val numPlayers = actor.attachChildren?.size
spriteBatch.draw(
pickup,
sx + 2, windowHeight - sy - 2,
2.toFloat() / 2, 2.toFloat() / 2,
2.toFloat(), 2.toFloat(),
iconSize, iconSize,
dir * -1, 0, 0, 128, 128, true, false
)
if(numPlayers > 0) nameFontRed.draw(spriteBatch, "$numPlayers", sx + 20, windowHeight - sy + 20)
} else {
spriteBatch.draw(
pickup_b,
sx + 2, windowHeight - sy - 2,
2.toFloat() / 2, 2.toFloat() / 2,
2.toFloat(), 2.toFloat(),
iconScale / 2, iconScale / 2,
dir * -1, 0, 0, 128, 128, true, false
)
}
}
}
SixSeatCar -> actorInfos?.forEach {
if (toggleVehicles != 1) {
val (actor, x, y, z, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
if (toggleVNames != 1) compaseFont.draw(spriteBatch, "VAN", sx + 15, windowHeight - sy - 2)
val v_x = actor!!.velocity.x
val v_y = actor.velocity.y
var iconSize = iconScale/2
when {
playersize*4 > iconScale/2 -> iconSize = (playersize*4).toFloat()
else -> iconSize = (iconScale/2).toFloat()
}
if (actor.attachChildren.isNotEmpty() || v_x * v_x + v_y * v_y > 80) {
val numPlayers = actor.attachChildren?.size
spriteBatch.draw(
van,
sx + 2, windowHeight - sy - 2,
2.toFloat() / 2, 2.toFloat() / 2,
2.toFloat(), 2.toFloat(),
iconSize, iconSize,
dir * -1, 0, 0, 128, 128, true, false
)
if(numPlayers > 0) nameFontRed.draw(spriteBatch, "$numPlayers", sx + 20, windowHeight - sy + 20)
} else {
spriteBatch.draw(
van_b,
sx + 2, windowHeight - sy - 2,
2.toFloat() / 2, 2.toFloat() / 2,
2.toFloat(), 2.toFloat(),
iconScale / 2, iconScale / 2,
dir * -1, 0, 0, 128, 128, true, false
)
}
}
}
Player -> actorInfos?.forEach {
for ((_, _) in typeLocation) {
val (actor, x, y, z, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
if (isTeammate(actor)) {
if (toggleView != -1) {
spriteBatch.draw(
teamplayersight,
sx + 1, windowHeight - sy - 2,
2.toFloat() / 2,
2.toFloat() / 2,
12.toFloat(), 2.toFloat(),
20f, 8f,
dir * -1, 0, 0, 800, 64, true, false)
}
spriteBatch.draw(
teamplayer,
sx, windowHeight - sy - 2, 4.toFloat() / 2,
4.toFloat() / 2, 4.toFloat(), 4.toFloat(), 6f, 5f,
dir * -1, 0, 0, 64, 64, true, false)
} else {
if (toggleView != -1) {
spriteBatch.draw(
arrowsight,
sx + 1, windowHeight - sy - 2,
2.toFloat() / 2,
2.toFloat() / 2,
12.toFloat(), 2.toFloat(),
10f, 8f,
dir * -1, 0, 0, 800, 64, true, false)
}
spriteBatch.draw(
arrow,
sx, windowHeight - sy - 2, 4.toFloat() / 2,
4.toFloat() / 2, 4.toFloat(), 4.toFloat(), 6f, 5f,
dir * -1, 0, 0, 64, 64, true, false)
}
}
}
Parachute -> actorInfos?.forEach {
for ((_, _) in typeLocation) {
val (actor, x, y, z, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
val children = actor!!.attachChildren
if (children.isNotEmpty() && (actorWithPlayerState[ArrayList(children.keys)[0]]) != null) {
val list = ArrayList(children.keys)
val playerStateGUID = actorWithPlayerState[list[0]] ?: continue
val name = playerNames[playerStateGUID]
var myPlayerStateGUID = actorWithPlayerState[selfID]
var myName = playerNames[myPlayerStateGUID]
if (name == myName) {
spriteBatch.draw(
parachute_self,
sx - 2, windowHeight - sy - 2, 4.toFloat() / 2,
4.toFloat() / 2, 4.toFloat(), 4.toFloat(), 2 * playersize, 2 * playersize,
dir * -1, 0, 0, 128, 128, true, false)
} else if (name in team) {
spriteBatch.draw(
parachute_team,
sx - 2, windowHeight - sy - 2, 4.toFloat() / 2,
4.toFloat() / 2, 4.toFloat(), 4.toFloat(), 2 * playersize, 2 * playersize,
dir * -1, 0, 0, 128, 128, true, false)
if (filterNames != 1) {
nameFont.draw(spriteBatch, "$name", sx + 10, windowHeight - sy + 10)
}
} else {
spriteBatch.draw(
parachute,
sx - 2, windowHeight - sy - 2, 4.toFloat() / 2,
4.toFloat() / 2, 4.toFloat(), 4.toFloat(), 2 * playersize, 2 * playersize,
dir * -1, 0, 0, 128, 128, true, false)
}
} else {
spriteBatch.draw(
parachute,
sx - 2, windowHeight - sy - 2, 4.toFloat() / 2,
4.toFloat() / 2, 4.toFloat(), 4.toFloat(), 2 * playersize, 2 * playersize,
dir * -1, 0, 0, 128, 128, true, false)
}
}
}
Plane -> actorInfos?.forEach {
for ((_, _) in typeLocation) {
val (_, x, y, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
spriteBatch.draw(
plane,
sx - 3, windowHeight - sy - 3, 4.toFloat() / 2,
4.toFloat() / 2, 4.toFloat(), 4.toFloat(), 300f, 15f,
dir * -1, 0, 0, 1829, 64, true, false)
}
}
Grenade -> actorInfos?.forEach {
val (_, x, y, dir) = it
val (sx, sy) = Vector2(x, y).mapToWindow()
spriteBatch.draw(
grenade,
sx + 2, windowHeight - sy - 2, 4.toFloat() / 2,
4.toFloat() / 2, 4.toFloat(), 4.toFloat(), playersize, playersize,
dir * -1, 0, 0, 16, 16, true, false)
}
else -> {
//nothing
}
}
}
}
fun drawPlayerNames(players: MutableList<renderInfo>?, selfX: Float, selfY: Float) {
players?.forEach {
val (actor, x, y, z, _) = it
actor!!
val dir = Vector2(x - selfX, y - selfY)
val distance = (dir.len() / 100).toInt()
val angle = ((dir.angle() + 90) % 360).toInt()
val (sx, sy) = mapToWindow(x, y)
val playerStateGUID = actorWithPlayerState[actor.netGUID] ?: return@forEach
val name = playerNames[playerStateGUID] ?: return@forEach
// val teamNumber = teamNumbers[playerStateGUID] ?: 0
val numKills = playerNumKills[playerStateGUID] ?: 0
val health = actorHealth[actor.netGUID] ?: 100f
val equippedWeapons = actorHasWeapons[actor.netGUID]
val df = DecimalFormat("###.#")
val deltaHeight = (if (z > selfHeight) "+" else "-") + df.format((z - selfHeight) / 100f)
var weapon: MutableList<String> = mutableListOf<String>()
val offsetDist = 3
if (equippedWeapons != null) {
for (w in equippedWeapons) {
val a = weapons[w] ?: continue
val result = a.archetype.pathName.split("_")
weapon.add("${result[2].substring(4)}")
}
}
if (filterNames != 1) {
//First Let's Draw DISTANCE
val fontText = "${distance}m | $angle°|${deltaHeight}m\n"
var wep_xoff = getPositionOffset(nameFont,fontText)
nameFont.draw(spriteBatch,
"$fontText", sx - wep_xoff.toFloat(), windowHeight - sy +30)
//Name
val fontText1 = "${name}"
var name_xoff = getPositionOffset(nameFont,fontText1)
nameFont.draw(spriteBatch,
"$fontText1", sx - name_xoff.toFloat(), windowHeight - sy +20)
//HEALTH / STATUS
when {
actorDowned[actor.netGUID] == true -> {
val fontText = "[DOWNED]"
val health_xoff = getPositionOffset(nameFontRed,fontText)
//var health_xoff = ("[DOWNED]".length) * offsetDist
nameFontRed.draw(spriteBatch, fontText, sx - health_xoff.toFloat(), windowHeight - sy + -10)
}
actorBeingRevived[actor.netGUID] == true -> {
val fontText = "[REVIVE]"
val health_xoff = getPositionOffset(nameFontRed,fontText)
//var health_xoff = ("[DOWNED]".length) * offsetDist
nameFontRed.draw(spriteBatch, fontText, sx - health_xoff.toFloat(), windowHeight - sy + -10)
}
/*
(health > 75) -> {
val fontText = "[${df.format(health)}]"
val health_xoff = getPositionOffset(nameFontGreen,fontText)
//var health_xoff = ("[DOWNED]".length) * offsetDist
nameFontGreen.draw(spriteBatch, fontText, sx - health_xoff.toFloat(), windowHeight - sy -10)
}
(health > 15) -> {
val fontText = "[${df.format(health)}]"
val health_xoff = getPositionOffset(nameFontOrange,fontText)
//var health_xoff = ("[DOWNED]".length) * offsetDist
nameFontOrange.draw(spriteBatch, fontText, sx - health_xoff.toFloat(), windowHeight - sy -10)
}*/
else -> {
/*
val fontText = "[${df.format(health)}]"
val health_xoff = getPositionOffset(nameFontRed,fontText)
//var health_xoff = ("[DOWNED]".length) * offsetDist
nameFontRed.draw(spriteBatch, fontText, sx - health_xoff.toFloat(), windowHeight - sy -10)
*/
}
}
// WEAPONS
weapon.forEachIndexed { index, element ->
when(element){
"AWM" ->{
val dist = (index + 2) * 12
val fontText = "${element}"
var wep_xoff = getPositionOffset(nameFont,fontText)
nameFontRed.draw(spriteBatch,
"${element}", sx - wep_xoff.toFloat(), windowHeight - sy - dist)
}
"M24" ->{
val dist = (index + 2) * 12
val fontText = "${element}"
var wep_xoff = getPositionOffset(nameFont,fontText)
nameFontRed.draw(spriteBatch,
"${element}", sx - wep_xoff.toFloat(), windowHeight - sy - dist)
}
"Mk14" ->{
val dist = (index + 2) * 12
val fontText = "${element}"
var wep_xoff = getPositionOffset(nameFont,fontText)
nameFontRed.draw(spriteBatch,
"${element}", sx - wep_xoff.toFloat(), windowHeight - sy - dist)
}
"M249" ->{
val dist = (index + 2) * 12
val fontText = "${element}"
var wep_xoff = getPositionOffset(nameFont,fontText)
nameFontRed.draw(spriteBatch,
"${element}", sx - wep_xoff.toFloat(), windowHeight - sy - dist)
}
"Kar98k" ->{
val dist = (index + 2) * 12
val fontText = "${element}"
var wep_xoff = getPositionOffset(nameFont,fontText)
nameFontOrange.draw(spriteBatch,
"${element}", sx - wep_xoff.toFloat(), windowHeight - sy - dist)
}
"SKS" ->{
val dist = (index + 2) * 12
val fontText = "${element}"
var wep_xoff = getPositionOffset(nameFont,fontText)
nameFontOrange.draw(spriteBatch,
"${element}", sx - wep_xoff.toFloat(), windowHeight - sy - dist)
}
else ->{
val dist = (index + 2) * 12
val fontText = "${element}"
var wep_xoff = getPositionOffset(nameFont,fontText)
nameFont.draw(spriteBatch,
"${element}", sx - wep_xoff.toFloat(), windowHeight - sy - dist)
}
}
}
}
}
}
fun ShapeRenderer.drawAllPlayerHealth(pColor : Color? , actorInfo : renderInfo)
{
val (actor , x , y , dir) = actorInfo
val health = actorHealth[actor?.netGUID] ?: 100f
val width = (camera.zoom * 50) * 600
val height = (camera.zoom * 50) * 100
val he = y + (camera.zoom * 50) * 250
val healthWidth = (health / 100.0 * width).toFloat()
if(filterNames != 1) {
color = Color(0f, 0f, 0f, 0.5f)
rectLine((x - width / 2), he, (x - width / 2) + width, he, height)
color = when
{
health > 80f -> Color(0f, 1f, 0f, 0.5f)
health > 33f -> Color(1f, 0.647f, 0f, 0.5f)
else -> Color(1f, 0f, 0f, 0.5f)
}
rectLine(x - width / 2, he, x - width / 2 + healthWidth, he, height)
}
}
private fun getPositionOffset(bitmapFont: BitmapFont, value: String): Float {
val glyphLayout = GlyphLayout()
glyphLayout.setText(bitmapFont, value)
return glyphLayout.width / 2
}
private var lastPlayTime = System.currentTimeMillis()
private fun safeZoneHint() {
if (PoisonGasWarningPosition.len() > 0) {
val dir = PoisonGasWarningPosition.cpy().sub(self2Coords)
val road = dir.len() - PoisonGasWarningRadius
if (road > 0) {
val runningTime = (road / runSpeed).toInt()
val (x, y) = dir.nor().scl(road).add(self2Coords).mapToWindow()
littleFont.draw(spriteBatch, "$runningTime", x, windowHeight - y)
val remainingTime = (TotalWarningDuration - ElapsedWarningDuration).toInt()
if (remainingTime == 60 && runningTime > remainingTime) {
val currentTime = System.currentTimeMillis()
if (currentTime - lastPlayTime > 10000) {
lastPlayTime = currentTime
//alarmSound.play()
}
}
}
}
}
private inline fun draw(type: ShapeType, draw: ShapeRenderer.() -> Unit) {
shapeRenderer.apply {
begin(type)
draw()
end()
}
}
private inline fun paint(matrix: Matrix4, paint: SpriteBatch.() -> Unit) {
spriteBatch.apply {
projectionMatrix = matrix
begin()
paint()
end()
}
}
private fun ShapeRenderer.circle(loc: Vector2, radius: Float, segments: Int) {
circle(loc.x, loc.y, radius, segments)
}
private fun isTeammate(actor: Actor?): Boolean {
if (actor != null) {
val playerStateGUID = actorWithPlayerState[actor.netGUID]
if (playerStateGUID != null) {
val name = playerNames[playerStateGUID] ?: return false
if (name in team)
return true
}
}
return false
}
override fun resize(width: Int, height: Int) {
windowWidth = width.toFloat()
windowHeight = height.toFloat()
camera.setToOrtho(true, windowWidth * windowToMapUnit, windowHeight * windowToMapUnit)
itemCamera.setToOrtho(false, windowWidth, windowHeight)
fontCamera.setToOrtho(false, windowWidth, windowHeight)
}
override fun pause() {
}
override fun resume() {
}
override fun dispose() {
deregister(this)
alarmSound.dispose()
nameFont.dispose()
largeFont.dispose()
littleFont.dispose()
corpseboximage.dispose()
airdropimage.dispose()
vehicle.dispose()
iconImages.iconSheet.dispose()
compaseFont.dispose()
compaseFontShadow.dispose()
var cur = 0
tileZooms.forEach {
for (i in 1..tileRowCounts[cur]) {
val y = if (i < 10) "0$i" else "$i"
for (j in 1..tileRowCounts[cur]) {
val x = if (j < 10) "0$j" else "$j"
mapErangelTiles[it]!![y]!![x]!!.dispose()
mapMiramarTiles[it]!![y]!![x]!!.dispose()
mapTiles[it]!![y]!![x]!!.dispose()
}
}
cur++
}
spriteBatch.dispose()
shapeRenderer.dispose()
}
}
| 2 | null | 3 | 7 | 0810899b85ac5bea69cb558c24c8241d5cc29ff3 | 76,557 | Gdar | The Unlicense |
wear/src/main/kotlin/com/weartools/weekdayutccomp/presentation/ui/Components.kt | amoledwatchfaces | 571,962,206 | false | null | package com.weartools.weekdayutccomp.presentation
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.wear.compose.foundation.lazy.itemsIndexed
import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.ChipDefaults
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.ListHeader
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.ToggleChip
import androidx.wear.compose.material.ToggleChipDefaults
import androidx.wear.compose.material.dialog.Alert
import androidx.wear.compose.material.dialog.Dialog
import com.google.android.horologist.annotations.ExperimentalHorologistApi
import com.weartools.weekdayutccomp.R
import com.weartools.weekdayutccomp.presentation.rotary.rotaryWithScroll
import com.weartools.weekdayutccomp.theme.wearColorPalette
import kotlinx.coroutines.launch
@Composable
fun DialogChip(
text: String,
title: String,
onClick: (() -> Unit)? = null,
icon: @Composable (BoxScope.() -> Unit)?
) {
Chip(
modifier = Modifier
.fillMaxWidth(),
onClick = {
onClick?.invoke()
},
icon = icon,
colors = ChipDefaults.gradientBackgroundChipColors(
startBackgroundColor = Color(0xff2c2c2d),
endBackgroundColor = Color(0xff2c2c2d)
),
label = {
Text(
text = text,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
secondaryLabel = {
Text(text = title, color = Color.LightGray)
},
)
}
@OptIn(ExperimentalHorologistApi::class)
@Composable
fun ListItemsWidget(
focusRequester: FocusRequester,
titles: String,
items: List<String>,
preValue: String,
callback: (Int) -> Unit
) {
val state = remember { mutableStateOf(true) }
var position by remember {
mutableIntStateOf(0)
}
val listState = rememberScalingLazyListState(initialCenterItemIndex = 0)
val coroutineScope = rememberCoroutineScope()
LaunchedEffect(Unit) {focusRequester.requestFocus()}
Dialog(
showDialog = state.value,
scrollState = listState,
onDismissRequest = { callback.invoke(-1) }
)
{
LocalView.current.viewTreeObserver.addOnWindowFocusChangeListener {
if (it) {
focusRequester.requestFocus()
}
}
Alert(
modifier = Modifier
.rotaryWithScroll(
scrollableState = listState,
focusRequester = focusRequester
),
backgroundColor = Color.Black,
scrollState = listState,
title = { PreferenceCategory(title = titles) },
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.Top),
contentPadding = PaddingValues(
start = 10.dp,
end = 10.dp,
top = 24.dp,
bottom = 52.dp
),
content = {
itemsIndexed(items) { index, i ->
ToggleChip(
modifier = Modifier
.fillMaxWidth(),
checked = preValue == items[index],
colors = ToggleChipDefaults.toggleChipColors(
checkedEndBackgroundColor = wearColorPalette.primaryVariant,
checkedToggleControlColor = Color(0xFFffd215)
),
toggleControl = {
Icon(
imageVector = ToggleChipDefaults.radioIcon(preValue == items[index]),
contentDescription = stringResource(id = R.string.compose_toggle)
)
},
onCheckedChange = {
state.value = false
callback(index)
},
label = { Text(i) },
)
}
}
)
}
position= items.indexOf(preValue)
if (position != 0)
LaunchedEffect(position) {
coroutineScope.launch {
listState.scrollToItem(index = position,120)
}
}
}
@Composable
fun ToggleChip(
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
label: String,
secondaryLabelOn: String,
secondaryLabelOff: String,
icon: @Composable (BoxScope.() -> Unit)?
) {
ToggleChip(
modifier = Modifier
.fillMaxWidth(),
checked = checked,
colors = ToggleChipDefaults.toggleChipColors(
checkedEndBackgroundColor = wearColorPalette.primaryVariant,
checkedToggleControlColor = Color(0xFFffd215),
),
appIcon = icon,
onCheckedChange = { enabled ->
onCheckedChange(enabled)
},
label = { Text(label) },
secondaryLabel = {
if (checked) {
Text(text = secondaryLabelOn, color = Color.LightGray)
} else Text(text = secondaryLabelOff, color = Color.LightGray)
},
toggleControl = {
Icon(
imageVector = ToggleChipDefaults.switchIcon(checked),
contentDescription = stringResource(id = R.string.compose_toggle)
)
}
)
}
@Composable
fun Header() {
ListHeader { Text(
textAlign = TextAlign.Center,
color = MaterialTheme.colors.primary,
text = stringResource(id = R.string.settings),
style = MaterialTheme.typography.title3
)}
}
@Composable
fun PreferenceCategory(
modifier: Modifier = Modifier,
title: String
) {
Text(
textAlign = TextAlign.Center,
text = title,
modifier = modifier.padding(
start = 16.dp,
top = 14.dp,
end = 16.dp,
bottom = 4.dp
),
color = wearColorPalette.secondary,
style = MaterialTheme.typography.caption2
)
}
@Composable
fun SectionText(modifier: Modifier = Modifier, text: String) {
Text(
modifier = modifier,
textAlign = TextAlign.Center,
color = MaterialTheme.colors.onSecondary,
text = text,
style = MaterialTheme.typography.caption3
)
}
| 3 | null | 8 | 68 | f495275c519bf275b9eca72d6e0d958b4af2e64d | 7,783 | Complications-Suite-Wear-OS | Apache License 2.0 |
app/src/main/java/org/sesac/management/view/MainActivity.kt | SeSAC-3th | 703,429,812 | false | {"Kotlin": 178829} | package org.sesac.management.view
import android.graphics.Rect
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.fragment.app.Fragment
import org.sesac.management.R
import org.sesac.management.databinding.ActivityMainBinding
import org.sesac.management.util.common.ARTIST
import org.sesac.management.util.common.ApplicationClass
import org.sesac.management.util.common.CUURRENTFRAGMENTTAG
import org.sesac.management.util.common.EVENT
import org.sesac.management.util.common.HOME
import org.sesac.management.util.common.RATE
import org.sesac.management.view.artist.ArtistFragment
import org.sesac.management.view.artist.ArtistViewModel
import org.sesac.management.view.event.EventFragment
import org.sesac.management.view.event.EventViewModel
import org.sesac.management.view.home.HomeFragment
import org.sesac.management.view.notice.NoticeViewModel
import org.sesac.management.view.rate.RateFragment
/**
* Main activity
*
* @constructor Create empty Main activity
* @author 진혁
*/
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
// 모든 fragment에서 공유할 viewmodel을 하나씩 만든다.
val artistViewModel: ArtistViewModel by viewModels() {
ArtistViewModel.ArtistViewModelFactory(ApplicationClass.getApplicationContext().artistRepository)
}
// Notice 와 관련하여 모든 Fragment에서 공유 할 하나의 ViewModel을 Actitivty에 정의
val noticeViewModel : NoticeViewModel by viewModels() {
NoticeViewModel.NoticeViewModelFactory(ApplicationClass.getApplicationContext().noticeRepository)
}
val eventViewModel : EventViewModel by viewModels() {
EventViewModel.EventViewModelFactory(ApplicationClass.getApplicationContext().eventRepository)
}
private lateinit var currentFragmentTag: String // 현재 보고 있는 fragment의 tag
// 화면을 회전했을 때 지금까지 보고 있던 fragment의 tag로 해당 fragment를 찾아서 보여준다.
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
currentFragmentTag = savedInstanceState.getString(CUURRENTFRAGMENTTAG)
.toString() // 화면을 회전하기 전의 currentFragment를 불러옴
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
installSplashScreen()
binding = ActivityMainBinding.inflate(layoutInflater).also {
setContentView(it.root)
}
artistViewModel.getAllArtist()
noticeViewModel.getHomeNotice()
eventViewModel.getSearch()
if (savedInstanceState == null) { // 화면을 회전했을 경우 savedInstatnceState가 null이 아니다. 즉 내부 코드는 한번만 실행된다.
supportFragmentManager
.beginTransaction()
.add(binding.secondFramelayout.id, HomeFragment(), HOME)
.commitAllowingStateLoss()
currentFragmentTag = HOME // 현재 보고 있는 fragmet의 Tag
}
clickBottomNavigationView()
}
// 화면을 회전해도 새로운 fragment를 생산하지 않고 현재 보고 있는 fragment를 불러오기 위해 tag를 저장한다.
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(CUURRENTFRAGMENTTAG, currentFragmentTag)
}
/**
* Click bottom navigation view, 하단 바 버튼 클릭 이벤트 메서드
*
* 하단 바를 클릭하면, 해당 fragment의 tag로 FragmentManager의 stack을 확인해본다.
*
* 있으면 그 fragment를 show, 없으면 그 fragment를 add, 현재 보고 있는 화면은 hide
* @author 진혁
*/
private fun clickBottomNavigationView() {
binding.secondBottomNavigationView.setOnItemSelectedListener {
when (it.itemId) {
R.id.homeFragment -> { // 첫 번째 fragment
changeFragment(HOME, HomeFragment())
}
R.id.artistFragment -> { // 두 번째 fragment
changeFragment(ARTIST, ArtistFragment())
}
R.id.eventFragment -> { // 세 번째 fragment
changeFragment(EVENT, EventFragment())
}
R.id.rateFragment -> { // 세 번째 fragment
changeFragment(RATE, RateFragment())
}
}
true
}
}
/**
* Change fragment, fragment 전환 메서드
*
* FragmentManager에 bottomNavigationView를 통해 fragment를 전환할 때 해당 fragment와 tag를 저장하고,
*
* 다시 그 fragment로 전환할 때 새롭게 replace하는 것이 아니라 FragmentManager에 해당 fragment의 tag가 저장되어 있는지 확인하고, 있으면 그것을 show 해준다.
*
* @param tag : 전환할 fragment의 tag
* @param fragment : 전환할 fragment
* @author 진혁
*/
private fun changeFragment(tag: String, fragment: Fragment) {
// supportFragmentManager에 "first"라는 Tag로 저장된 fragment 있는지 확인
if (supportFragmentManager.findFragmentByTag(tag) == null) { // Tag가 없을 때 -> 없을 리가 없다.
supportFragmentManager
.beginTransaction()
.hide(supportFragmentManager.findFragmentByTag(currentFragmentTag)!!)
.add(binding.secondFramelayout.id, fragment, tag)
.commitAllowingStateLoss()
} else { // Tag가 있을 때
// 먼저 currentFragmentTag에 저장된 '이전 fragment Tag'를 활용해 이전 fragment를 hide 시킨다.
// supportFragmentManager에 저장된 "first"라는 Tag를 show 시킨다.
supportFragmentManager
.beginTransaction()
.hide(supportFragmentManager.findFragmentByTag(currentFragmentTag)!!)
.show(supportFragmentManager.findFragmentByTag(tag)!!)
.commitAllowingStateLoss()
}
// currentFragmentTag에 '현재 fragment Tag' "first"를 저장한다.
currentFragmentTag = tag
}
/**
* 키보드 위 빈 공간을 터치하면 키보드가 사라지도록 한다
* @author 우빈
*/
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
val focusView: View? = currentFocus
if (focusView != null) {
val rect = Rect()
focusView.getGlobalVisibleRect(rect)
val x = ev.x.toInt()
val y = ev.y.toInt()
if (!rect.contains(x, y)) {
val imm: InputMethodManager =
getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(focusView.windowToken, 0)
focusView.clearFocus()
}
}
return super.dispatchTouchEvent(ev)
}
} | 4 | Kotlin | 4 | 0 | eed031a47183b52c48a333187264a1e42f8879f1 | 6,545 | SeSalChai | MIT License |
playground/src/main/java/androidx/essentials/playground/location/LocationServiceImpl.kt | kunal26das | 282,238,393 | false | null | package androidx.essentials.playground.location
import android.location.Location
import com.google.android.gms.location.FusedLocationProviderClient
import javax.inject.Inject
class LocationServiceImpl @Inject constructor(
private val fusedLocationProviderClient: FusedLocationProviderClient
) : LocationService {
suspend fun getLastLocation(): Location? {
return getLastLocation(fusedLocationProviderClient)
}
} | 5 | Kotlin | 0 | 3 | 4968a43c341f728c905d3db7a124fd8b6e05041a | 435 | androidx-essentials | Apache License 2.0 |
src/main/kotlin/dev/capybaralabs/shipa/discord/interaction/model/ApplicationCommandType.kt | CapybaraLabs | 519,179,073 | false | {"Kotlin": 191942} | package dev.capybaralabs.shipa.discord.interaction.model
import com.fasterxml.jackson.annotation.JsonValue
/**
* [Discord Application Command Type](https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-types)
*/
enum class ApplicationCommandType(@JsonValue val value: Int) {
CHAT_INPUT(1),
USER(2),
MESSAGE(3),
}
| 0 | Kotlin | 0 | 1 | a8ad61315f5fb3bcbd1d85fbc0485b75ad22b5dc | 383 | shipa | MIT License |
plugins/server/io.ktor/pebble/2.3/install.kt | ktorio | 729,497,149 | false | {"Kotlin": 161300, "HTML": 329, "FreeMarker": 139} | import io.ktor.server.application.*
import io.ktor.server.pebble.*
import io.ktor.server.response.*
import io.pebbletemplates.pebble.loader.ClasspathLoader
public fun Application.configureTemplating() {
install(Pebble) {
loader(ClasspathLoader().apply {
prefix = "templates"
})
}
}
| 6 | Kotlin | 14 | 53 | fdbb3e01b1ab6c99ed8b6b7ff8940534515b7fe6 | 319 | ktor-plugin-registry | Apache License 2.0 |
app/src/main/java/uk/nhs/nhsx/covid19/android/app/battery/BatteryOptimizationRequired.kt | nhsx-mirror | 289,296,773 | true | {"Kotlin": 2761696, "Shell": 1098, "Ruby": 847, "Batchfile": 197} | package uk.nhs.nhsx.covid19.android.app.battery
import com.jeroenmols.featureflag.framework.FeatureFlag
import com.jeroenmols.featureflag.framework.RuntimeBehavior
import javax.inject.Inject
class BatteryOptimizationRequired @Inject constructor(
private val batteryOptimizationChecker: BatteryOptimizationChecker,
private val batteryOptimizationAcknowledgementProvider: BatteryOptimizationAcknowledgementProvider
) {
operator fun invoke() =
!batteryOptimizationChecker.isIgnoringBatteryOptimizations() &&
batteryOptimizationAcknowledgementProvider.value == null &&
RuntimeBehavior.isFeatureEnabled(FeatureFlag.BATTERY_OPTIMIZATION)
}
| 0 | Kotlin | 0 | 0 | 296c9decde1b5ed904b760ff77b05afc51f24281 | 681 | covid-19-app-android-ag-public | MIT License |
shared/src/commonMain/kotlin/me/saket/press/shared/sync/SyncCoordinator.kt | jeremiahespinosa | 292,441,707 | true | {"Kotlin": 439091, "Swift": 38925, "Java": 27798, "Ruby": 5879} | package me.saket.press.shared.sync
import com.badoo.reaktive.completable.Completable
import com.badoo.reaktive.completable.completableFromFunction
import com.badoo.reaktive.completable.doOnBeforeError
import com.badoo.reaktive.completable.onErrorComplete
import com.badoo.reaktive.completable.subscribe
import com.badoo.reaktive.observable.flatMapCompletable
import com.badoo.reaktive.observable.switchMap
import com.badoo.reaktive.subject.publish.PublishSubject
import com.soywiz.klock.seconds
import me.saket.press.shared.rx.Schedulers
import me.saket.press.shared.rx.observableInterval
/**
* Syncs can be triggered from multiple places at different times. This class
* coordinates between them and maintains a timer for syncing periodically.
*/
class SyncCoordinator(
private val syncer: Syncer,
private val schedulers: Schedulers
) {
private val triggers = PublishSubject<Unit>()
fun start() {
triggers.switchMap { observableInterval(0, 30.seconds, schedulers.computation) }
.flatMapCompletable { syncWithResult() }
.subscribe()
}
fun trigger() {
triggers.onNext(Unit)
}
internal fun syncWithResult(): Completable {
return completableFromFunction { syncer.sync() }
.doOnBeforeError { println(it.message) }
.onErrorComplete()
}
}
| 0 | null | 0 | 0 | 1de96c1b3e969ab462b9d5c3b6611d68d8024fda | 1,303 | press | Apache License 2.0 |
buildSrc/src/main/java/dependencies/Versions.kt | rintio | 418,429,604 | true | {"Java Properties": 2, "Shell": 3, "INI": 17, "Markdown": 16, "Batchfile": 1, "Java": 932, "Kotlin": 242, "HTML": 1, "JavaScript": 1, "Proguard": 2, "Gradle Kotlin DSL": 1} | package dependencies
object Versions {
const val android_compile_sdk = 30
const val android_min_sdk = 21
const val android_target_sdk = 29
const val androidx_fragment = "1.3.6"
const val okhttp3 = "4.9.1"
const val dagger = "2.38.1"
const val kotlin = "1.5.21"
const val mockito = "3.11.1" // the newest version is buggy https://github.com/mockito/mockito/issues/2370
}
| 0 | null | 0 | 0 | e84d3350e4939a2ce2678c44395c15af19ead1f8 | 404 | collect | Apache License 2.0 |
src/main/kotlin/no/nav/familie/baks/mottak/integrasjoner/BarnetrygdOppgaveMapper.kt | navikt | 221,166,975 | false | {"Kotlin": 543188, "Java": 28936, "Dockerfile": 165} | package no.nav.familie.baks.mottak.integrasjoner
import no.nav.familie.baks.mottak.søknad.barnetrygd.domene.SøknadRepository
import no.nav.familie.baks.mottak.søknad.barnetrygd.domene.harEøsSteg
import no.nav.familie.kontrakter.felles.Behandlingstema
import no.nav.familie.kontrakter.felles.Tema
import no.nav.familie.kontrakter.felles.oppgave.Behandlingstype
import org.springframework.stereotype.Service
@Service
class BarnetrygdOppgaveMapper(
hentEnhetClient: HentEnhetClient,
arbeidsfordelingClient: ArbeidsfordelingClient,
pdlClient: PdlClient,
val søknadRepository: SøknadRepository,
) : AbstractOppgaveMapper(hentEnhetClient, pdlClient, arbeidsfordelingClient) {
override val tema: Tema = Tema.BAR
// Behandlingstema og behandlingstype settes basert på regelsettet som er dokumentert nederst her: https://confluence.adeo.no/display/TFA/Mottak+av+dokumenter
override fun hentBehandlingstema(journalpost: Journalpost): Behandlingstema? =
when {
journalpost.erBarnetrygdSøknad() && journalpost.erDigitalKanal() ->
if (utledBehandlingUnderkategoriFraSøknad(journalpost) == BehandlingUnderkategori.UTVIDET) {
Behandlingstema.UtvidetBarnetrygd
} else {
Behandlingstema.OrdinærBarnetrygd
}
erDnummerPåJournalpost(journalpost) -> Behandlingstema.BarnetrygdEØS
hoveddokumentErÅrligDifferanseutbetalingAvBarnetrygd(journalpost) -> null
else -> Behandlingstema.OrdinærBarnetrygd
}
override fun hentBehandlingstemaVerdi(journalpost: Journalpost) = hentBehandlingstema(journalpost)?.value
override fun hentBehandlingstype(journalpost: Journalpost): Behandlingstype? =
when {
journalpost.erBarnetrygdSøknad() && journalpost.erDigitalKanal() ->
if (utledBehandlingKategoriFraSøknad(journalpost) == BehandlingKategori.EØS) {
Behandlingstype.EØS
} else {
Behandlingstype.NASJONAL
}
hoveddokumentErÅrligDifferanseutbetalingAvBarnetrygd(journalpost) -> Behandlingstype.Utland
else -> null
}
override fun hentBehandlingstypeVerdi(journalpost: Journalpost): String? = hentBehandlingstype(journalpost)?.value
fun utledBehandlingKategoriFraSøknad(journalpost: Journalpost): BehandlingKategori {
check(journalpost.erBarnetrygdSøknad()) { "Journalpost m/ id ${journalpost.journalpostId} er ikke en barnetrygd søknad" }
val søknad = søknadRepository.getByJournalpostId(journalpost.journalpostId)
return when {
søknad.harEøsSteg() -> BehandlingKategori.EØS
else -> BehandlingKategori.NASJONAL
}
}
fun utledBehandlingUnderkategoriFraSøknad(journalpost: Journalpost) =
when {
journalpost.erBarnetrygdUtvidetSøknad() -> BehandlingUnderkategori.UTVIDET
else -> BehandlingUnderkategori.ORDINÆR
}
private fun hoveddokumentErÅrligDifferanseutbetalingAvBarnetrygd(journalpost: Journalpost) =
// Brevkode "NAV 33-00.15" representerer dokumentet "Norsk sokkel - Årlig differanseutbetaling av barnetrygd"
journalpost.dokumenter!!.firstOrNull { it.brevkode != null }?.brevkode == "NAV 33-00.15"
}
| 4 | Kotlin | 0 | 1 | b53a012a103086d2c292a04cc5b378039f71bfa1 | 3,336 | familie-baks-mottak | MIT License |
plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/common/InlineStylesExtension.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.extensions.common
import com.intellij.openapi.project.Project
import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension
import org.intellij.plugins.markdown.settings.MarkdownSettings
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel
import org.intellij.plugins.markdown.ui.preview.ResourceProvider
internal class InlineStylesExtension(private val project: Project?) : MarkdownBrowserPreviewExtension, ResourceProvider {
override val priority: MarkdownBrowserPreviewExtension.Priority
get() = MarkdownBrowserPreviewExtension.Priority.AFTER_ALL
override val styles: List<String> = listOf("inlineStyles/inline.css")
override val resourceProvider: ResourceProvider = this
override fun canProvide(resourceName: String): Boolean = resourceName in styles
override fun loadResource(resourceName: String): ResourceProvider.Resource {
val settings = project?.let(MarkdownSettings::getInstance)
val text = settings?.customStylesheetText.takeIf { settings?.useCustomStylesheetText == true }
return when (text) {
null -> ResourceProvider.Resource(emptyStylesheet)
else -> ResourceProvider.Resource(text.toByteArray())
}
}
override fun dispose() = Unit
class Provider: MarkdownBrowserPreviewExtension.Provider {
override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension? {
return InlineStylesExtension(panel.project)
}
}
companion object {
private val emptyStylesheet = "".toByteArray()
}
}
| 191 | null | 4372 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 1,712 | intellij-community | Apache License 2.0 |
uiuser/src/main/java/it/codingjam/github/ui/user/UserViewState.kt | fabioCollini | 94,247,429 | false | null | package it.codingjam.github.ui.user
import it.codingjam.github.core.UserDetail
import it.codingjam.github.vo.Lce
typealias UserViewState = Lce<UserDetail> | 2 | Kotlin | 36 | 274 | 5248bae79f8faaba81ec2ef87bec1a402d475763 | 156 | ArchitectureComponentsDemo | Apache License 2.0 |
src/main/kotlin/dev/arbjerg/lavalink/libraries/discord4j/D4JVoiceUpdateHandler.kt | lavalink-devs | 642,292,256 | false | null | @file:JvmName("D4JVoiceHandler")
package dev.arbjerg.lavalink.libraries.discord4j
import dev.arbjerg.lavalink.client.LavalinkClient
import dev.arbjerg.lavalink.client.LinkState
import dev.arbjerg.lavalink.client.loadbalancing.VoiceRegion
import dev.arbjerg.lavalink.protocol.v4.VoiceState
import discord4j.core.GatewayDiscordClient
import discord4j.core.event.domain.VoiceServerUpdateEvent
import discord4j.core.event.domain.VoiceStateUpdateEvent
import reactor.core.Disposable
import reactor.core.Disposables
import reactor.core.publisher.Mono
import kotlin.jvm.optionals.getOrNull
/**
* Install the Lavalink voice handler to this client.
*
* Java users use:
* ```java
* D4JVoiceHandler.install(gatewayClient, lavalink);
* ```
*/
@JvmName("install")
fun GatewayDiscordClient.installVoiceHandler(lavalink: LavalinkClient): Disposable.Composite {
val voiceStateUpdate = on(VoiceStateUpdateEvent::class.java) { event ->
val update = event.current
if (update.userId != update.client.selfId) return@on Mono.empty()
val channel = update.channelId.getOrNull()
val link = lavalink.getLinkIfCached(update.guildId.asLong()) ?: return@on Mono.empty()
val player = link.node.playerCache[update.guildId.asLong()] ?: return@on Mono.empty()
val playerState = player.state
if (channel == null && playerState.connected) {
link.state = LinkState.DISCONNECTED
link.destroy()
} else {
link.state = LinkState.CONNECTED
Mono.empty()
}
}.subscribe()
val voiceServerUpdate = on(VoiceServerUpdateEvent::class.java) { update ->
val state = VoiceState(
update.token,
update.endpoint!!,
getGatewayClient(update.shardInfo.index).get().sessionId
)
val region = VoiceRegion.fromEndpoint(update.endpoint!!)
val link = lavalink.getOrCreateLink(update.guildId.asLong(), region)
link.onVoiceServerUpdate(state)
Mono.empty<Unit>()
}.subscribe()
return Disposables.composite(voiceStateUpdate, voiceServerUpdate)
}
| 3 | null | 5 | 9 | c6d430fefbab72a456a38afa5640f82c9ec32324 | 2,117 | lavalink-client | MIT License |
.teamcity/Buildship/Project.kt | eclipse | 32,398,083 | false | null | package Buildship
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.Project
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.gradle
import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.*
val individualBuildsForPhase1 = listOf(
IndividualScenarioBuildType(ScenarioType.SANITY_CHECK, OS.LINUX, EclipseVersion.ECLIPSE4_13, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8) // TODO use latest Eclipse version for sanity check coverage
)
val individualBuildsForPhase2 = listOf(
IndividualScenarioBuildType(ScenarioType.BASIC_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_8, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.BASIC_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_20, eclipseRuntimeJdk = Jdk.OPEN_JDK_11),
IndividualScenarioBuildType(ScenarioType.BASIC_COVERAGE, OS.WINDOWS, EclipseVersion.ECLIPSE4_8, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.BASIC_COVERAGE, OS.WINDOWS, EclipseVersion.ECLIPSE4_23, eclipseRuntimeJdk = Jdk.OPEN_JDK_11)
)
val individualBuildsForPhase3 = listOf(
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_8, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_9, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_10, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_11, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_12, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_13, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_14, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_15, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_16, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_17, eclipseRuntimeJdk = Jdk.OPEN_JDK_11),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_18, eclipseRuntimeJdk = Jdk.OPEN_JDK_11),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_19, eclipseRuntimeJdk = Jdk.OPEN_JDK_11),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_20, eclipseRuntimeJdk = Jdk.OPEN_JDK_11),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_21, eclipseRuntimeJdk = Jdk.OPEN_JDK_11),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_22, eclipseRuntimeJdk = Jdk.OPEN_JDK_11),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_23, eclipseRuntimeJdk = Jdk.OPEN_JDK_11),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_24, eclipseRuntimeJdk = Jdk.OPEN_JDK_11),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_25, eclipseRuntimeJdk = Jdk.OPEN_JDK_17),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_26, eclipseRuntimeJdk = Jdk.OPEN_JDK_17),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.LINUX, EclipseVersion.ECLIPSE4_27, eclipseRuntimeJdk = Jdk.OPEN_JDK_17),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.WINDOWS, EclipseVersion.ECLIPSE4_8, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
IndividualScenarioBuildType(ScenarioType.FULL_COVERAGE, OS.WINDOWS, EclipseVersion.ECLIPSE4_23, eclipseRuntimeJdk = Jdk.OPEN_JDK_11)
)
val individualBuildsForPhase4 = listOf(
IndividualScenarioBuildType(ScenarioType.CROSS_VERSION, OS.LINUX, EclipseVersion.ECLIPSE4_8, eclipseRuntimeJdk = Jdk.ORACLE_JDK_8),
// TODO Eclipse 4.8 can only run on Java 8 and below without further configuration https://wiki.eclipse.org/Configure_Eclipse_for_Java_9
//IndividualScenarioBuildType(ScenarioType.CROSS_VERSION, OS.LINUX, EclipseVersion.ECLIPSE4_8, eclipseRuntimeJdk = Jdk.ORACLE_JDK_9),
//IndividualScenarioBuildType(ScenarioType.CROSS_VERSION, OS.LINUX, EclipseVersion.ECLIPSE4_8, eclipseRuntimeJdk = Jdk.OPEN_JDK_10),
IndividualScenarioBuildType(ScenarioType.CROSS_VERSION, OS.LINUX, EclipseVersion.ECLIPSE4_23, eclipseRuntimeJdk = Jdk.OPEN_JDK_11),
IndividualScenarioBuildType(ScenarioType.CROSS_VERSION, OS.LINUX, EclipseVersion.ECLIPSE4_23, eclipseRuntimeJdk = Jdk.OPEN_JDK_12),
IndividualScenarioBuildType(ScenarioType.CROSS_VERSION, OS.LINUX, EclipseVersion.ECLIPSE4_23, eclipseRuntimeJdk = Jdk.OPEN_JDK_13),
IndividualScenarioBuildType(ScenarioType.CROSS_VERSION, OS.LINUX, EclipseVersion.ECLIPSE4_23, eclipseRuntimeJdk = Jdk.OPEN_JDK_14),
IndividualScenarioBuildType(ScenarioType.CROSS_VERSION, OS.LINUX, EclipseVersion.ECLIPSE4_23, eclipseRuntimeJdk = Jdk.OPEN_JDK_15),
IndividualScenarioBuildType(ScenarioType.CROSS_VERSION, OS.LINUX, EclipseVersion.ECLIPSE4_23, eclipseRuntimeJdk = Jdk.OPEN_JDK_16),
IndividualScenarioBuildType(ScenarioType.CROSS_VERSION, OS.LINUX, EclipseVersion.ECLIPSE4_23, eclipseRuntimeJdk = Jdk.OPEN_JDK_17),
// TODO JDK 18 is only supported in Eclipse 4.24
//IndividualScenarioBuildType(ScenarioType.CROSS_VERSION, OS.LINUX, EclipseVersion.ECLIPSE4_23, eclipseRuntimeJdk = Jdk.OPEN_JDK_18)
)
val tb1_1 = CheckpointBuildType("Sanity Check (Phase 1/1)", individualBuildsForPhase1, null)
val tb1_2 = CheckpointBuildType("Basic Test Coverage (Phase 1/2)", individualBuildsForPhase1, null)
val tb2_2 = CheckpointBuildType("Basic Test Coverage (Phase 2/2)", individualBuildsForPhase2, tb1_2)
val tb3_1 = CheckpointBuildType("Full Test Coverage (Phase 1/3)", individualBuildsForPhase1, null, Trigger.GIT)
val tb3_2 = CheckpointBuildType("Full Test Coverage (Phase 2/3)", individualBuildsForPhase2, tb3_1)
val tb3_3 = CheckpointBuildType("Full Test Coverage (Phase 3/3)", individualBuildsForPhase3, tb3_2)
val tb4_1 = CheckpointBuildType("Cross-Version Test Coverage (Phase 1/4)", individualBuildsForPhase1, null, Trigger.DAILY)
val tb4_2 = CheckpointBuildType("Cross-Version Test Coverage (Phase 2/4)", individualBuildsForPhase2, tb4_1)
val tb4_3 = CheckpointBuildType("Cross-Version Test Coverage (Phase 3/4)", individualBuildsForPhase3, tb4_2)
val tb4_4 = CheckpointBuildType("Cross-Version Test Coverage (Phase 4/4)", individualBuildsForPhase4, tb4_3)
val unsafeSnapshotPromotion = PromotionBuildType("snapshot (from sanity check)","snapshot", tb1_1)
val snapshotPromotion = PromotionBuildType("snapshot", "snapshot", tb4_4, Trigger.DAILY_MASTER)
val milestonePromotion = PromotionBuildType("milestone","milestone", tb4_4)
val releasePromotion = PromotionBuildType("release","release", tb4_4)
val individualSnapshotPromotions = EclipseVersion.values().map { SinglePromotionBuildType("Snapshot Eclipse ${it.codeName}", "snapshot", it, tb1_1) } // TODO should depend on tb4_4
val individualReleasePromotions = EclipseVersion.values().map { SinglePromotionBuildType("Release Eclipse ${it.codeName}", "release", it, tb1_1) } // TODO should depend on tb4_4
class IndividualScenarioBuildType(type: ScenarioType, os: OS, eclipseVersion: EclipseVersion, eclipseRuntimeJdk: Jdk) : BuildType({
createId("Individual", "${type.name.toLowerCase()}_Test_Coverage_${os.name.toLowerCase()}_Eclipse${eclipseVersion.versionNumber}_OnJava${eclipseRuntimeJdk.majorVersion}")
addCredentialsLeakFailureCondition()
artifactRules = """
org.eclipse.buildship.site/build/repository/** => .teamcity/update-site
org.eclipse.buildship.core.test/build/eclipseTest/workspace/.metadata/.log => .teamcity/test/org.eclipse.buildship.core.test
org.eclipse.buildship.ui.test/build/eclipseTest/workspace/.metadata/.log => .teamcity/test/org.eclipse.buildship.ui.test
""".trimIndent()
params {
param("eclipse.release.type", "snapshot")
param("build.invoker", "ci")
param("eclipse.version", eclipseVersion.updateSiteVersion)
param("eclipse.test.java.version", eclipseRuntimeJdk.majorVersion)
param("env.JAVA_HOME", Jdk.OPEN_JDK_11.getJavaHomePath(os))
param("gradle.tasks", type.gradleTasks)
param("repository.mirrors", allMirrors())
param("env.GRADLE_ENTERPRISE_ACCESS_KEY", "%ge.gradle.org.access.key%")
}
triggers {
retryBuild {
delaySeconds = 0
attempts = 2
}
}
steps {
gradle {
name = "RUNNER_21"
id = "RUNNER_21"
tasks = "%gradle.tasks%"
buildFile = ""
gradleParams = "-Prepository.mirrors=\"%repository.mirrors%\" -Peclipse.version=%eclipse.version% -Pbuild.invoker=%build.invoker% -Prelease.type=%eclipse.release.type% -Peclipse.test.java.version=%eclipse.test.java.version% --info --stacktrace -Declipse.p2.mirror=false -Dscan \"-Dgradle.cache.remote.url=%gradle.cache.remote.url%\" \"-Dgradle.cache.remote.username=%gradle.cache.remote.username%\" \"-Dgradle.cache.remote.password=%gradle.cache.remote.password%\" ${Jdk.javaInstallationPathsProperty(os)}"
jvmArgs = "-XX:MaxPermSize=256m"
param("org.jfrog.artifactory.selectedDeployableServer.defaultModuleVersionConfiguration", "GLOBAL")
jdkHome
}
}
vcs {
root(GitHubVcsRoot)
checkoutMode = CheckoutMode.ON_AGENT
}
cleanup {
all(days = 5)
history(days = 5)
artifacts(days = 5)
preventDependencyCleanup = false
}
requirements {
contains("teamcity.agent.jvm.os.name", os.name.toLowerCase().capitalize())
doesNotMatch("teamcity.agent.name", "ec2-.*")
}
})
class PromotionBuildType(promotionName: String, typeName: String, dependency: BuildType, trigger: Trigger = Trigger.NONE) : BuildType({
createId("Promotion", promotionName.capitalize())
artifactRules = "org.eclipse.buildship.site/build/repository/** => .teamcity/update-site"
trigger.applyOn(this)
addCredentialsLeakFailureCondition()
params {
when(typeName) {
"milestone" -> text("Confirm", "NO", label = "Do you want to proceed with the milestone?", description = "Confirm to publish a new milestone.", display = ParameterDisplay.PROMPT,regex = "YES", validationMessage = "Confirm by writing YES in order to proceed.")
"release" -> password("<PASSWORD>", "", label = "GitHub token", description = "Please specify your GitHub auth token to proceed with the release", display = ParameterDisplay.PROMPT)
}
param("eclipse.release.type", typeName)
param("build.invoker", "ci")
param("env.JAVA_HOME", Jdk.OPEN_JDK_11.getJavaHomePath(OS.LINUX))
param("repository.mirrors", allMirrors())
param("env.GRADLE_ENTERPRISE_ACCESS_KEY", "%ge.gradle.org.access.key%")
}
// The artifact upload requires uses ssh which requires manual confirmation. to work around that, we use the same
// machine for the upload.
// TODO We should separate the update site generation and the artifact upload into two separate steps.
requirements {
contains("teamcity.agent.jvm.os.name", "Linux")
contains("teamcity.agent.name", "dev")
}
vcs {
root(GitHubVcsRoot)
checkoutMode = CheckoutMode.ON_AGENT
cleanCheckout = true
showDependenciesChanges = true
}
failureConditions {
errorMessage = true
}
dependencies {
snapshot(dependency, DefaultFailureCondition)
}
steps {
for (eclipseVersion in EclipseVersion.values().reversed()) {
gradle {
name = "Build and upload update site for Eclipse ${eclipseVersion.codeName} (${eclipseVersion.versionNumber})"
tasks = "clean build uploadUpdateSite"
buildFile = ""
gradleParams = "-Prepository.mirrors=\"%repository.mirrors%\" --exclude-task eclipseTest -Peclipse.version=${eclipseVersion.updateSiteVersion} -Pbuild.invoker=%build.invoker% -Prelease.type=%eclipse.release.type% -PECLIPSE_ORG_FTP_HOST=projects-storage.eclipse.org -PECLIPSE_ORG_FTP_USER=%eclipse.downloadServer.username% -PECLIPSE_ORG_FTP_PASSWORD=%eclipse.downloadServer.password% -PECLIPSE_ORG_FTP_UPDATE_SITES_PATH=downloads/buildship/updates -PECLIPSE_ORG_TEMP_PATH=tmp -PECLIPSE_ORG_MIRROR_PATH=/buildship/updates --stacktrace -Declipse.p2.mirror=false \"-Dgradle.cache.remote.url=%gradle.cache.remote.url%\" \"-Dgradle.cache.remote.username=%gradle.cache.remote.username%\" \"-Dgradle.cache.remote.password=%gradle.cache.remote.password%\" ${Jdk.javaInstallationPathsProperty(OS.LINUX)}"
param("org.jfrog.artifactory.selectedDeployableServer.defaultModuleVersionConfiguration", "GLOBAL")
}
}
if (typeName == "release") {
gradle {
name = "Tag revision and increment version number"
tasks = "tag incrementVersion"
buildFile = ""
gradleParams = "-Prepository.mirrors=\"%repository.mirrors%\" --exclude-task eclipseTest -Peclipse.version=45 -Pbuild.invoker=%build.invoker% -Prelease.type=%eclipse.release.type% -PECLIPSE_ORG_FTP_HOST=projects-storage.eclipse.org -PECLIPSE_ORG_FTP_USER=%eclipse.downloadServer.username% -PECLIPSE_ORG_FTP_PASSWORD=%eclipse.downloadServer.password% -PECLIPSE_ORG_FTP_UPDATE_SITES_PATH=downloads/buildship/updates -PECLIPSE_ORG_TEMP_PATH=tmp -PECLIPSE_ORG_MIRROR_PATH=/buildship/updates -PgithubAccessKey=%github.token% --stacktrace \"-Dgradle.cache.remote.url=%gradle.cache.remote.url%\" \"-Dgradle.cache.remote.username=%gradle.cache.remote.username%\" \"-Dgradle.cache.remote.password=%gradle.cache.remote.password%\" ${Jdk.javaInstallationPathsProperty(OS.LINUX)}"
}
}
}
})
class SinglePromotionBuildType(promotionName: String, typeName: String, eclipseVersion: EclipseVersion, dependency: BuildType, trigger: Trigger = Trigger.NONE) : BuildType({
createId("Promotion", promotionName.capitalize())
artifactRules = "org.eclipse.buildship.site/build/repository/** => .teamcity/update-site"
trigger.applyOn(this)
addCredentialsLeakFailureCondition()
params {
when(typeName) {
"milestone" -> text("Confirm", "NO", label = "Do you want to proceed with the milestone?", description = "Confirm to publish a new milestone.", display = ParameterDisplay.PROMPT,regex = "YES", validationMessage = "Confirm by writing YES in order to proceed.")
"release" -> password("github.token", "", label = "GitHub token", description = "Please specify your GitHub auth token to proceed with the release", display = ParameterDisplay.PROMPT)
}
param("eclipse.release.type", typeName)
param("build.invoker", "ci")
param("env.JAVA_HOME", Jdk.OPEN_JDK_11.getJavaHomePath(OS.LINUX))
param("repository.mirrors", allMirrors())
param("env.GRADLE_ENTERPRISE_ACCESS_KEY", "%ge.gradle.org.access.key%")
}
// The artifact upload requires uses ssh which requires manual confirmation. to work around that, we use the same
// machine for the upload.
// TODO We should separate the update site generation and the artifact upload into two separate steps.
requirements {
contains("teamcity.agent.jvm.os.name", "Linux")
contains("teamcity.agent.name", "dev")
}
vcs {
root(GitHubVcsRoot)
checkoutMode = CheckoutMode.ON_AGENT
cleanCheckout = true
showDependenciesChanges = true
}
failureConditions {
errorMessage = true
}
dependencies {
snapshot(dependency, DefaultFailureCondition)
}
steps {
gradle {
name = "Build and upload update site for Eclipse ${eclipseVersion.codeName} (${eclipseVersion.versionNumber})"
tasks = "clean build uploadUpdateSite"
buildFile = ""
gradleParams = "-Prepository.mirrors=\"%repository.mirrors%\" --exclude-task eclipseTest -Peclipse.version=${eclipseVersion.updateSiteVersion} -Pbuild.invoker=%build.invoker% -Prelease.type=%eclipse.release.type% -PECLIPSE_ORG_FTP_HOST=projects-storage.eclipse.org -PECLIPSE_ORG_FTP_USER=%eclipse.downloadServer.username% -PECLIPSE_ORG_FTP_PASSWORD=%eclipse.downloadServer.password% -PECLIPSE_ORG_FTP_UPDATE_SITES_PATH=downloads/buildship/updates -PECLIPSE_ORG_TEMP_PATH=tmp -PECLIPSE_ORG_MIRROR_PATH=/buildship/updates --stacktrace -Declipse.p2.mirror=false \"-Dgradle.cache.remote.url=%gradle.cache.remote.url%\" \"-Dgradle.cache.remote.username=%gradle.cache.remote.username%\" \"-Dgradle.cache.remote.password=%gradle.cache.remote.password%\" ${Jdk.javaInstallationPathsProperty(OS.LINUX)}"
param("org.jfrog.artifactory.selectedDeployableServer.defaultModuleVersionConfiguration", "GLOBAL")
}
if (typeName == "release" && eclipseVersion.isLatest) {
gradle {
name = "Tag revision and increment version number"
tasks = "tag incrementVersion"
buildFile = ""
gradleParams = "-Prepository.mirrors=\"%repository.mirrors%\" --exclude-task eclipseTest -Peclipse.version=45 -Pbuild.invoker=%build.invoker% -Prelease.type=%eclipse.release.type% -PECLIPSE_ORG_FTP_HOST=projects-storage.eclipse.org -PECLIPSE_ORG_FTP_USER=%eclipse.downloadServer.username% -PECLIPSE_ORG_FTP_PASSWORD=%eclipse.downloadServer.password% -PECLIPSE_ORG_FTP_UPDATE_SITES_PATH=downloads/buildship/updates -PECLIPSE_ORG_TEMP_PATH=tmp -PECLIPSE_ORG_MIRROR_PATH=/buildship/updates -PgithubAccessKey=%github.token% --stacktrace \"-Dgradle.cache.remote.url=%gradle.cache.remote.url%\" \"-Dgradle.cache.remote.username=%gradle.cache.remote.username%\" \"-Dgradle.cache.remote.password=%<PASSWORD>%\" ${Jdk.javaInstallationPathsProperty(OS.LINUX)}"
}
}
}
})
class CheckpointBuildType(triggerName: String, scenarios: List<IndividualScenarioBuildType>, previousCheckpoint: CheckpointBuildType?, trigger: Trigger = Trigger.NONE) : BuildType({
createId("Checkpoint", triggerName)
trigger.applyOn(this)
vcs {
root(GitHubVcsRoot)
checkoutMode = CheckoutMode.ON_AGENT
cleanCheckout = true
showDependenciesChanges = true
}
if (previousCheckpoint != null) {
triggers {
finishBuildTrigger {
buildType = previousCheckpoint.id!!.value
successfulOnly = true
branchFilter = "+:*"
}
}
dependencies {
snapshot(previousCheckpoint, FailWhenDependenciesFail)
}
}
dependencies {
scenarios.forEach {
snapshot(it, DefaultFailureCondition)
}
}
})
object Project : Project({
description = "Eclipse plugins for Gradle http://eclipse.org/buildship"
vcsRoot(GitHubVcsRoot)
subprojectsWithOrder(listOf(IndividualBuilds, Checkpoints, Promotions))
params {
param("env.JAVA_TOOL_OPTIONS", "-Dfile.encoding=UTF8")
password("<PASSWORD>", "credentialsJSON:<PASSWORD>", label = "Password", display = ParameterDisplay.HIDDEN)
password("eclipse.downloadServer.username", "credentialsJSON:<PASSWORD>", label = "Username", display = ParameterDisplay.HIDDEN)
// Do not allow UI changes in the TeamCity configuration
param("teamcity.ui.settings.readOnly", "true")
param("env.GRADLE_ENTERPRISE_ACCESS_KEY", "%ge.gradle.org.access.key%")
}
cleanup {
all(days = 5)
history(days = 5)
artifacts(days = 5)
preventDependencyCleanup = false
}
})
object IndividualBuilds : Project({
createId("Individual Coverage Scenarios")
buildTypesWithOrder(individualBuildsForPhase1 + individualBuildsForPhase2 + individualBuildsForPhase3 + individualBuildsForPhase4)
})
object Checkpoints : Project({
createId("Checkpoints")
buildTypesWithOrder(listOf(
tb1_1,
tb1_2, tb2_2,
tb3_1, tb3_2, tb3_3,
tb4_1, tb4_2, tb4_3, tb4_4))
})
object Promotions : Project({
createId("Promotions")
buildTypesWithOrder(listOf(unsafeSnapshotPromotion, snapshotPromotion, milestonePromotion, releasePromotion) + individualSnapshotPromotions + individualReleasePromotions)
})
fun allMirrors() = EclipseVersion.values()
.map { "https://download.eclipse.org/releases/${it.codeName.toLowerCase()}->https://repo.grdev.net/artifactory/eclipse-ide/releases/${it.codeName.toLowerCase()}" }
.joinToString(",") +
",https://download.eclipse.org/tools/orbit/downloads/drops/R20210602031627/repository->https://repo.grdev.net/artifactory/eclipse-orbit" +
",https://download.eclipse.org/technology/swtbot/releases/2.2.1->https://repo.grdev.net/artifactory/eclipse-swtbot"
| 294 | null | 175 | 511 | 942a601b12e2da706ad3bbcbf3950cc29b5c86ab | 21,379 | buildship | Naumen Public License |
platform/lang-impl/src/com/intellij/codeInsight/actions/ReaderModeListener.kt | code-general | 400,360,974 | false | null | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.actions
import com.intellij.application.options.colors.ReaderModeStatsCollector
import com.intellij.codeInsight.actions.ReaderModeSettings.Companion.applyReaderMode
import com.intellij.codeInsight.actions.ReaderModeSettingsListener.Companion.applyToAllEditors
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions
import com.intellij.openapi.editor.colors.impl.FontPreferencesImpl
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.options.ex.Settings
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.ui.HyperlinkLabel
import com.intellij.util.messages.Topic
import com.intellij.util.ui.UIUtil
import java.beans.PropertyChangeListener
import java.util.*
import javax.swing.event.HyperlinkListener
interface ReaderModeListener : EventListener {
fun modeChanged(project: Project)
}
class ReaderModeSettingsListener : ReaderModeListener {
companion object {
@Topic.ProjectLevel
@JvmStatic
val TOPIC = Topic(ReaderModeListener::class.java, Topic.BroadcastDirection.NONE)
fun applyToAllEditors(project: Project) {
FileEditorManager.getInstance(project).allEditors.forEach {
if (it !is TextEditor) return
applyReaderMode(project, it.editor, it.file, fileIsOpenAlready = true)
}
EditorFactory.getInstance().allEditors.forEach {
if (it !is EditorImpl) return
applyReaderMode(project, it, FileDocumentManager.getInstance().getFile(it.document),
fileIsOpenAlready = true)
}
}
fun createReaderModeComment() = HyperlinkLabel().apply {
setTextWithHyperlink(IdeBundle.message("checkbox.also.in.reader.mode"))
font = UIUtil.getFont(UIUtil.FontSize.SMALL, font)
foreground = UIUtil.getLabelFontColor(UIUtil.FontColor.BRIGHTER)
addHyperlinkListener(HyperlinkListener {
DataManager.getInstance().dataContextFromFocusAsync.onSuccess { context ->
context?.let { dataContext ->
Settings.KEY.getData(dataContext)?.let { settings ->
settings.select(settings.find("editor.reader.mode"))
ReaderModeStatsCollector.logSeeAlsoNavigation()
}
}
}
})
}
}
override fun modeChanged(project: Project) = applyToAllEditors(project)
}
internal class ReaderModeEditorSettingsListener : StartupActivity, DumbAware {
override fun runActivity(project: Project) {
val propertyChangeListener = PropertyChangeListener { event ->
when (event.propertyName) {
EditorSettingsExternalizable.PROP_DOC_COMMENT_RENDERING -> {
ReaderModeSettings.instance(project).showRenderedDocs = EditorSettingsExternalizable.getInstance().isDocCommentRenderingEnabled
applyToAllEditors(project)
}
}
}
EditorSettingsExternalizable.getInstance().addPropertyChangeListener(propertyChangeListener, project)
val fontPreferences = AppEditorFontOptions.getInstance().fontPreferences as FontPreferencesImpl
fontPreferences.changeListener = Runnable {
fontPreferences.changeListener
ReaderModeSettings.instance(project).showLigatures = fontPreferences.useLigatures()
applyToAllEditors(project)
}
Disposer.register(project) { fontPreferences.changeListener = null }
}
} | 1 | null | 1 | 1 | a00c61d009b376bdf62a2859dd757c0766894a28 | 3,958 | intellij-community | Apache License 2.0 |
Lesson1/01-Hello-World.kt | PhoenixNest | 477,221,062 | false | {"Kotlin": 43932, "Java": 236} | package Lesson1
// in kotlin, all the function default type is public
public fun main() {
println("Hello World")
test()
}
private fun test() {
println("This is a private function")
} | 0 | Kotlin | 0 | 0 | f5e5f226de5578dfedd754bf19cb3e686afba5b1 | 197 | Hello-Kotlin | MIT License |
screens/page/src/main/java/com/app/mviarch/screens/page/PageScreen.kt | MichailSamoylov | 594,727,251 | false | null | package com.app.mviarch.screens.page
import com.app.mviarch.screens.page.ui.PageFragment
import com.github.terrakok.cicerone.androidx.FragmentScreen
fun getPageScreen(nameOfPokemon: String) = FragmentScreen { PageFragment.newInstance(nameOfPokemon) } | 0 | Kotlin | 0 | 0 | e951a8d4f1b8c3de38be951d5aa734d52a21c1f6 | 252 | MVI-Arch | Apache License 2.0 |
apollo/src/commonMain/kotlin/org/hyperledger/identus/apollo/base64/Base64.kt | hyperledger | 535,641,324 | false | null | package io.iohk.atala.prism.apollo.base64
import kotlin.math.min
/**
* Base64 implementation
*/
internal final object Base64 {
/**
* Encode ByteArray to Base64 String
*/
fun encodeToString(input: ByteArray, encoding: Encoding = Encoding.Standard): String {
if (input.contentEquals("".encodeToByteArray())) {
return ""
}
return when (encoding) {
Encoding.Standard -> getEncoder().withoutPadding().encodeToString(input)
Encoding.StandardPad -> getEncoder().encodeToString(input)
Encoding.UrlSafe -> getUrlEncoder().withoutPadding().encodeToString(input)
Encoding.UrlSafePad -> getUrlEncoder().encodeToString(input)
}
}
/**
* Encode ByteArray to Base64 ByteArray
*/
fun encode(input: ByteArray, encoding: Encoding = Encoding.Standard): ByteArray {
if (input.contentEquals("".encodeToByteArray())) {
return input
}
return when (encoding) {
Encoding.Standard -> getEncoder().withoutPadding().encode(input)
Encoding.StandardPad -> getEncoder().encode(input)
Encoding.UrlSafe -> getUrlEncoder().withoutPadding().encode(input)
Encoding.UrlSafePad -> getUrlEncoder().encode(input)
}
}
/**
* Decode string to Base64
*/
fun decode(input: String, encoding: Encoding = Encoding.Standard): ByteArray {
return when (encoding) {
Encoding.Standard, Encoding.StandardPad -> getDecoder().decode(input)
Encoding.UrlSafe, Encoding.UrlSafePad -> getUrlDecoder().decode(input)
}
}
private fun getEncoder(): Encoder {
return Encoder.RFC4648
}
private fun getDecoder(): Decoder {
return Decoder.RFC4648
}
private fun getUrlEncoder(): Encoder {
return Encoder.RFC4648_URLSAFE
}
private fun getUrlDecoder(): Decoder {
return Decoder.RFC4648_URLSAFE
}
/**
* This class implements a decoder for decoding byte data using the
* Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
*
*
* The Base64 padding character `'='` is accepted and
* interpreted as the end of the encoded byte data, but is not
* required. So if the final unit of the encoded byte data only has
* two or three Base64 characters (without the corresponding padding
* character(s) padded), they are decoded as if followed by padding
* character(s). If there is a padding character present in the
* final unit, the correct number of padding character(s) must be
* present, otherwise `IllegalArgumentException` (
* `IOException` when reading from a Base64 stream) is thrown
* during decoding.
*
*
* Instances of [Decoder] class are safe for use by
* multiple concurrent threads.
*
*
* Unless otherwise noted, passing a `null` argument to
* a method of this class will cause a
* [NullPointerException][NullPointerException] to
* be thrown.
*
* @see Encoder
*
* @since 1.8
*/
private class Decoder private constructor(private val isURL: Boolean, private val isMIME: Boolean) {
/**
* Decodes all bytes from the input byte array using the [Base64]
* encoding scheme, writing the results into a newly-allocated output
* byte array. The returned byte array is of the length of the resulting
* bytes.
*
* @param src
* the byte array to decode
*
* @return A newly-allocated byte array containing the decoded bytes.
*
* @throws IllegalArgumentException
* if `src` is not in valid Base64 scheme
*/
fun decode(src: ByteArray): ByteArray {
val dst = ByteArray(outLength(src, 0, src.size))
val ret = decode0(src, 0, src.size, dst)
if (ret != dst.size) {
dst.copyInto(ByteArray(ret))
// dst = java.util.Arrays.copyOf(dst, ret)
}
return dst
}
/**
* Decodes a Base64 encoded String into a newly-allocated byte array
* using the [Base64] encoding scheme.
*
*
* An invocation of this method has exactly the same effect as invoking
* `decode(src.getBytes(StandardCharsets.ISO_8859_1))`
*
* @param src
* the string to decode
*
* @return A newly-allocated byte array containing the decoded bytes.
*
* @throws IllegalArgumentException
* if `src` is not in valid Base64 scheme
*/
fun decode(src: String): ByteArray {
return decode(src.encodeToByteArray())
// return decode(src.toByteArray(java.nio.charset.StandardCharsets.ISO_8859_1))
}
/**
* Decodes all bytes from the input byte array using the [Base64]
* encoding scheme, writing the results into the given output byte array,
* starting at offset 0.
*
*
* It is the responsibility of the invoker of this method to make
* sure the output byte array `dst` has enough space for decoding
* all bytes from the input byte array. No bytes will be be written to
* the output byte array if the output byte array is not big enough.
*
*
* If the input byte array is not in valid Base64 encoding scheme
* then some bytes may have been written to the output byte array before
* [IllegalArgumentException] is thrown.
*
* @param src
* the byte array to decode
* @param dst
* the output byte array
*
* @return The number of bytes written to the output byte array
*
* @throws IllegalArgumentException
* if `src` is not in valid Base64 scheme, or `dst`
* does not have enough space for decoding all input bytes.
*/
@Throws(IllegalArgumentException::class)
fun decode(src: ByteArray, dst: ByteArray): Int {
val len = outLength(src, 0, src.size)
if (dst.size < len) {
throw IllegalArgumentException("Output byte array is too small for decoding all input bytes")
}
return decode0(src, 0, src.size, dst)
}
@Suppress("NAME_SHADOWING")
@Throws(IllegalArgumentException::class)
private fun outLength(src: ByteArray, sp: Int, sl: Int): Int {
var sp = sp
val base64 = if (isURL) {
fromBase64URL
} else {
fromBase64
}
var paddings = 0
var len = sl - sp
if (len == 0) {
return 0
}
if (len < 2) {
if (isMIME && base64[0] == -1) {
return 0
}
throw IllegalArgumentException("Input byte[] should at least have 2 bytes for base64 bytes")
}
if (isMIME) {
// scan all bytes to fill out all non-alphabet. a performance
// trade-off of pre-scan or Arrays.copyOf
var n = 0
while (sp < sl) {
var b = src[sp++].toInt() and 0xff
if (b == '='.code) {
len -= sl - sp + 1
break
}
if (base64[b].also { b = it } == -1) {
n++
}
}
len -= n
} else {
if (src[sl - 1] == '='.code.toByte()) {
paddings++
if (src[sl - 2] == '='.code.toByte()) {
paddings++
}
}
}
if (paddings == 0 && len and 0x3 != 0) paddings = 4 - (len and 0x3)
return 3 * ((len + 3) / 4) - paddings
}
@Suppress("NAME_SHADOWING")
@Throws(IllegalArgumentException::class)
private fun decode0(src: ByteArray, sp: Int, sl: Int, dst: ByteArray): Int {
var sp = sp
val base64 = if (isURL) fromBase64URL else fromBase64
var dp = 0
var bits = 0
var shiftto = 18 // pos of first byte of 4-byte atom
while (sp < sl) {
var b = src[sp++].toInt() and 0xff
if (base64[b].also { b = it } < 0) {
if (b == -2) { // padding byte '='
// = shiftto==18 unnecessary padding
// x= shiftto==12 a dangling single x
// x to be handled together with non-padding case
// xx= shiftto==6&&sp==sl missing last =
// xx=y shiftto==6 last is not =
if (shiftto == 6 && (sp == sl || src[sp++] != '='.code.toByte()) ||
shiftto == 18
) {
throw IllegalArgumentException("Input byte array has wrong 4-byte ending unit")
}
break
}
if (isMIME) { // skip if for rfc2045
continue
} else {
throw IllegalArgumentException("Illegal base64 character ${src[sp - 1].toInt().toString(16)}")
}
}
bits = bits or (b shl shiftto)
shiftto -= 6
if (shiftto < 0) {
dst[dp++] = (bits shr 16).toByte()
dst[dp++] = (bits shr 8).toByte()
dst[dp++] = bits.toByte()
shiftto = 18
bits = 0
}
}
// reached end of byte array or hit padding '=' characters.
when (shiftto) {
6 -> {
dst[dp++] = (bits shr 16).toByte()
}
0 -> {
dst[dp++] = (bits shr 16).toByte()
dst[dp++] = (bits shr 8).toByte()
}
12 -> {
// dangling single "x", incorrectly encoded.
throw IllegalArgumentException("Last unit does not have enough valid bits")
}
}
// anything left is invalid, if is not MIME.
// if MIME, ignore all non-base64 character
while (sp < sl) {
if (isMIME && base64[src[sp++].toInt()] < 0) {
continue
}
throw IllegalArgumentException("Input byte array has incorrect ending byte at $sp")
}
return dp
}
companion object {
/**
* Lookup table for decoding unicode characters drawn from the
* "Base64 Alphabet" (as specified in Table 1 of RFC 2045) into
* their 6-bit positive integer equivalents. Characters that
* are not in the Base64 alphabet but fall within the bounds of
* the array are encoded to -1.
*
*/
private val fromBase64 = IntArray(256)
init {
fromBase64.fill(-1)
// java.util.Arrays.fill(fromBase64, -1)
for (i in Encoder.toBase64.indices) fromBase64[Encoder.toBase64.get(i).code] =
i
fromBase64['='.code] = -2
}
/**
* Lookup table for decoding "URL and Filename safe Base64 Alphabet"
* as specified in Table2 of the RFC 4648.
*/
private val fromBase64URL = IntArray(256)
init {
fromBase64URL.fill(-1)
// java.util.Arrays.fill(fromBase64URL, -1)
for (i in Encoder.toBase64URL.indices) fromBase64URL[Encoder.toBase64URL[i].code] = i
fromBase64URL['='.code] = -2
}
val RFC4648 = Decoder(false, false)
val RFC4648_URLSAFE = Decoder(true, false)
val RFC2045 = Decoder(false, true)
}
}
/**
* This class implements an encoder for encoding byte data using
* the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
*
*
* Instances of [Encoder] class are safe for use by
* multiple concurrent threads.
*
*
* Unless otherwise noted, passing a `null` argument to
* a method of this class will cause a
* [NullPointerException][java.lang.NullPointerException] to
* be thrown.
*
* @see Decoder
*
* @since 1.8
*/
private class Encoder private constructor(
private val isURL: Boolean,
private val newline: ByteArray?,
private val linemax: Int,
private val doPadding: Boolean
) {
private fun outLength(srclen: Int): Int {
var len = if (doPadding) {
4 * ((srclen + 2) / 3)
} else {
val n = srclen % 3
4 * (srclen / 3) + if (n == 0) 0 else n + 1
}
if (linemax > 0) { // line separators
len += (len - 1) / linemax * newline!!.size
}
return len
}
/**
* Encodes all bytes from the specified byte array into a newly-allocated
* byte array using the [Base64] encoding scheme. The returned byte
* array is of the length of the resulting bytes.
*
* @param src
* the byte array to encode
* @return A newly-allocated byte array containing the resulting
* encoded bytes.
*/
fun encode(src: ByteArray): ByteArray {
val len = outLength(src.size) // dst array size
val dst = ByteArray(len)
val ret = encode0(src, 0, src.size, dst)
return if (ret != dst.size) {
dst.copyInto(ByteArray(ret))
// java.util.Arrays.copyOf(dst, ret)
} else {
dst
}
}
/**
* Encodes all bytes from the specified byte array using the
* [Base64] encoding scheme, writing the resulting bytes to the
* given output byte array, starting at offset 0.
*
*
* It is the responsibility of the invoker of this method to make
* sure the output byte array `dst` has enough space for encoding
* all bytes from the input byte array. No bytes will be written to the
* output byte array if the output byte array is not big enough.
*
* @param src
* the byte array to encode
* @param dst
* the output byte array
* @return The number of bytes written to the output byte array
*
* @throws IllegalArgumentException if `dst` does not have enough
* space for encoding all input bytes.
*/
@Throws(IllegalArgumentException::class)
fun encode(src: ByteArray, dst: ByteArray): Int {
val len = outLength(src.size) // dst array size
if (dst.size < len) {
throw IllegalArgumentException("Output byte array is too small for encoding all input bytes")
}
return encode0(src, 0, src.size, dst)
}
/**
* Encodes the specified byte array into a String using the [Base64]
* encoding scheme.
*
*
* This method first encodes all input bytes into a base64 encoded
* byte array and then constructs a new String by using the encoded byte
* array and the [ ISO-8859-1][java.nio.charset.StandardCharsets.ISO_8859_1] charset.
*
*
* In other words, an invocation of this method has exactly the same
* effect as invoking
* `new String(encode(src), StandardCharsets.ISO_8859_1)`.
*
* @param src
* the byte array to encode
* @return A String containing the resulting Base64 encoded characters
*/
fun encodeToString(src: ByteArray): String {
val encoded: ByteArray = encode(src)
return encoded.decodeToString()
// return String(encoded, 0, 0, encoded.size)
}
/**
* Returns an encoder instance that encodes equivalently to this one,
* but without adding any padding character at the end of the encoded
* byte data.
*
*
* The encoding scheme of this encoder instance is unaffected by
* this invocation. The returned encoder instance should be used for
* non-padding encoding operation.
*
* @return an equivalent encoder that encodes without adding any
* padding character at the end
*/
fun withoutPadding(): Encoder {
return if (!doPadding) this else Encoder(isURL, newline, linemax, false)
}
@Suppress("UNUSED_CHANGED_VALUE")
private fun encode0(src: ByteArray, off: Int, end: Int, dst: ByteArray): Int {
val base64 = if (isURL) toBase64URL else toBase64
var sp = off
var slen = (end - off) / 3 * 3
val sl = off + slen
if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3
var dp = 0
while (sp < sl) {
val sl0: Int = min(sp + slen, sl)
var sp0 = sp
var dp0 = dp
while (sp0 < sl0) {
val bits = src[sp0++].toInt() and 0xff shl 16 or (
src[sp0++].toInt() and 0xff shl 8
) or
(src[sp0++].toInt() and 0xff)
dst[dp0++] = base64[bits ushr 18 and 0x3f].code.toByte()
dst[dp0++] = base64[bits ushr 12 and 0x3f].code.toByte()
dst[dp0++] = base64[bits ushr 6 and 0x3f].code.toByte()
dst[dp0++] = base64[bits and 0x3f].code.toByte()
}
val dlen = (sl0 - sp) / 3 * 4
dp += dlen
sp = sl0
if (dlen == linemax && sp < end) {
for (b in newline!!) {
dst[dp++] = b
}
}
}
if (sp < end) { // 1 or 2 leftover bytes
val b0 = src[sp++].toInt() and 0xff
dst[dp++] = base64[b0 shr 2].code.toByte()
if (sp == end) {
dst[dp++] = base64[b0 shl 4 and 0x3f].code.toByte()
if (doPadding) {
dst[dp++] = '='.code.toByte()
dst[dp++] = '='.code.toByte()
}
} else {
val b1 = src[sp++].toInt() and 0xff
dst[dp++] = base64[b0 shl 4 and 0x3f or (b1 shr 4)].code.toByte()
dst[dp++] = base64[b1 shl 2 and 0x3f].code.toByte()
if (doPadding) {
dst[dp++] = '='.code.toByte()
}
}
}
return dp
}
companion object {
/**
* This array is a lookup table that translates 6-bit positive integer
* index values into their "Base64 Alphabet" equivalents as specified
* in "Table 1: The Base64 Alphabet" of RFC 2045 (and RFC 4648).
*/
val toBase64 = charArrayOf(
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
)
/**
* It's the lookup table for "URL and Filename safe Base64" as specified
* in Table 2 of the RFC 4648, with the '+' and '/' changed to '-' and
* '_'. This table is used when BASE64_URL is specified.
*/
val toBase64URL = charArrayOf(
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
)
private const val MIMELINEMAX = 76
private val CRLF = byteArrayOf('\r'.code.toByte(), '\n'.code.toByte())
val RFC4648 = Encoder(false, null, -1, true)
val RFC4648_URLSAFE = Encoder(true, null, -1, true)
val RFC2045 = Encoder(false, CRLF, MIMELINEMAX, true)
}
}
}
| 3 | null | 4 | 9 | 453aef6045323c1a348d7cf9c6c2d086ede5a53b | 21,250 | identus-apollo | Apache License 2.0 |
GrowthBook/src/commonMain/kotlin/com/sdk/growthbook/evaluators/GBConditionEvaluator.kt | growthbook | 445,362,249 | false | null | package com.sdk.growthbook.evaluators
import com.sdk.growthbook.Utils.GBCondition
import com.sdk.growthbook.Utils.GBUtils
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
/**
* Both experiments and features can define targeting conditions using a syntax modeled after MongoDB queries.
* These conditions can have arbitrary nesting levels and evaluating them requires recursion.
* There are a handful of functions to define, and be aware that some of them may reference function definitions further below.
*/
/**
* Enum For different Attribute Types supported by GrowthBook
*/
internal enum class GBAttributeType {
/**
* String Type Attribute
*/
GbString {
override fun toString(): String = "string"
},
/**
* Number Type Attribute
*/
GbNumber {
override fun toString(): String = "number"
},
/**
* Boolean Type Attribute
*/
GbBoolean {
override fun toString(): String = "boolean"
},
/**
* Array Type Attribute
*/
GbArray {
override fun toString(): String = "array"
},
/**
* Object Type Attribute
*/
GbObject {
override fun toString(): String = "object"
},
/**
* Null Type Attribute
*/
GbNull {
override fun toString(): String = "null"
},
/**
* Not Supported Type Attribute
*/
GbUnknown {
override fun toString(): String = "unknown"
}
}
/**
* Evaluator Class for Conditions
*/
internal class GBConditionEvaluator {
/**
* This is the main function used to evaluate a condition.
* - attributes : User Attributes
* - condition : to be evaluated
*/
fun evalCondition(attributes: JsonElement, conditionObj: GBCondition): Boolean {
if (conditionObj is JsonArray) {
return false
} else {
// If conditionObj has a key $or, return evalOr(attributes, condition["$or"])
var targetItems = conditionObj.jsonObject["\$or"] as? JsonArray
if (targetItems != null) {
return evalOr(attributes, targetItems)
}
// If conditionObj has a key $nor, return !evalOr(attributes, condition["$nor"])
targetItems = conditionObj.jsonObject["\$nor"] as? JsonArray
if (targetItems != null) {
return !evalOr(attributes, targetItems)
}
// If conditionObj has a key $and, return !evalAnd(attributes, condition["$and"])
targetItems = conditionObj.jsonObject["\$and"] as? JsonArray
if (targetItems != null) {
return evalAnd(attributes, targetItems)
}
// If conditionObj has a key $not, return !evalCondition(attributes, condition["$not"])
val targetItem = conditionObj.jsonObject["\$not"]
if (targetItem != null) {
return !evalCondition(attributes, targetItem)
}
// Loop through the conditionObj key/value pairs
for (key in conditionObj.jsonObject.keys) {
val element = getPath(attributes, key)
val value = conditionObj.jsonObject[key]
if (value != null) {
// If evalConditionValue(value, getPath(attributes, key)) is false, break out of loop and return false
if (!evalConditionValue(value, element)) {
return false
}
}
}
}
// Return true
return true
}
/**
* Evaluate OR conditions against given attributes
*/
private fun evalOr(attributes: JsonElement, conditionObjs: JsonArray): Boolean {
// If conditionObjs is empty, return true
if (conditionObjs.isEmpty()) {
return true
} else {
// Loop through the conditionObjects
for (item in conditionObjs) {
// If evalCondition(attributes, conditionObjs[i]) is true, break out of the loop and return true
if (evalCondition(attributes, item)) {
return true
}
}
}
// Return false
return false
}
/**
* Evaluate AND conditions against given attributes
*/
private fun evalAnd(attributes: JsonElement, conditionObjs: JsonArray): Boolean {
// Loop through the conditionObjects
for (item in conditionObjs) {
// If evalCondition(attributes, conditionObjs[i]) is false, break out of the loop and return false
if (!evalCondition(attributes, item)) {
return false
}
}
// Return true
return true
}
/**
* This accepts a parsed JSON object as input and returns true if every key in the object starts with $
*/
fun isOperatorObject(obj: JsonElement): Boolean {
var isOperator = true
if (obj is JsonObject && obj.keys.isNotEmpty()) {
for (key in obj.keys) {
if (!key.startsWith("$")) {
isOperator = false
break
}
}
} else {
isOperator = false
}
return isOperator
}
/**
* This returns the data type of the passed in argument.
*/
fun getType(obj: JsonElement?): GBAttributeType {
if (obj == JsonNull) {
return GBAttributeType.GbNull
}
if (obj is JsonPrimitive) {
val primitiveValue = obj.jsonPrimitive
return if (primitiveValue.isString) {
GBAttributeType.GbString
} else if (primitiveValue.content == "true" || primitiveValue.content == "false") {
GBAttributeType.GbBoolean
} else {
GBAttributeType.GbNumber
}
}
if (obj is JsonArray) {
return GBAttributeType.GbArray
}
if (obj is JsonObject) {
return GBAttributeType.GbObject
}
return GBAttributeType.GbUnknown
}
/**
* Given attributes and a dot-separated path string,
* @return the value at that path (or null if the path doesn't exist)
*/
fun getPath(obj: JsonElement, key: String): JsonElement? {
val paths: ArrayList<String>
if (key.contains(".")) {
paths = key.split(".") as ArrayList<String>
} else {
paths = ArrayList()
paths.add(key)
}
var element: JsonElement? = obj
for (path in paths) {
if (element == null || element is JsonArray) {
return null
}
if (element is JsonObject) {
element = element[path]
} else {
return null
}
}
return element
}
/**
* Evaluates Condition Value against given condition & attributes
*/
fun evalConditionValue(conditionValue: JsonElement, attributeValue: JsonElement?): Boolean {
// If conditionValue is a string, number, boolean, return true if it's "equal" to attributeValue and false if not.
if (conditionValue is JsonPrimitive && attributeValue is JsonPrimitive) {
return conditionValue.content == attributeValue.content
}
if (conditionValue is JsonPrimitive && attributeValue == null) {
return false
}
// If conditionValue is array, return true if it's "equal" - "equal" should do a deep comparison for arrays.
if (conditionValue is JsonArray) {
return if (attributeValue is JsonArray) {
if (conditionValue.size == attributeValue.size) {
val conditionArray = Json.decodeFromJsonElement(
ListSerializer(JsonElement.serializer()),
conditionValue
)
val attributeArray = Json.decodeFromJsonElement(
ListSerializer(JsonElement.serializer()),
attributeValue
)
conditionArray == attributeArray
} else {
false
}
} else {
false
}
}
// If conditionValue is an object, loop over each key/value pair:
if (conditionValue is JsonObject) {
if (isOperatorObject(conditionValue)) {
for (key in conditionValue.keys) {
// If evalOperatorCondition(key, attributeValue, value) is false, return false
if (!evalOperatorCondition(key, attributeValue, conditionValue[key]!!)) {
return false
}
}
} else if (attributeValue != null) {
return conditionValue == attributeValue
} else {
return false
}
}
// Return true
return true
}
/**
* This checks if attributeValue is an array, and if so at least one of the array items must match the condition
*/
private fun elemMatch(attributeValue: JsonElement, condition: JsonElement): Boolean {
if (attributeValue is JsonArray) {
// Loop through items in attributeValue
for (item in attributeValue) {
// If isOperatorObject(condition)
if (isOperatorObject(condition)) {
// If evalConditionValue(condition, item), break out of loop and return true
if (evalConditionValue(condition, item)) {
return true
}
}
// Else if evalCondition(item, condition), break out of loop and return true
else if (evalCondition(item, condition)) {
return true
}
}
}
// If attributeValue is not an array, return false
return false
}
/**
* This function is just a case statement that handles all the possible operators
* There are basic comparison operators in the form attributeValue {op} conditionValue
*/
fun evalOperatorCondition(
operator: String,
attributeValue: JsonElement?,
conditionValue: JsonElement
): Boolean {
// Evaluate TYPE operator - whether both are of same type
if (operator == "\$type") {
return getType(attributeValue).toString() == conditionValue.jsonPrimitive.content
}
// Evaluate NOT operator - whether condition doesn't contain attribute
if (operator == "\$not") {
return !evalConditionValue(conditionValue, attributeValue)
}
// Evaluate EXISTS operator - whether condition contains attribute
if (operator == "\$exists") {
val targetPrimitiveValue = conditionValue.jsonPrimitive.content
if (targetPrimitiveValue == "false" && attributeValue == null) {
return true
} else if (targetPrimitiveValue == "true" && attributeValue != null) {
return true
}
}
/// There are three operators where conditionValue is an array
if (conditionValue is JsonArray) {
when (operator) {
// Evaluate IN operator - attributeValue in the conditionValue array
"\$in" -> {
return if (attributeValue is JsonArray) {
isIn(attributeValue, conditionValue)
} else conditionValue.contains(attributeValue)
}
// Evaluate NIN operator - attributeValue not in the conditionValue array
"\$nin" -> {
return if (attributeValue is JsonArray) {
!isIn(attributeValue, conditionValue)
} else !conditionValue.contains(attributeValue)
}
// Evaluate ALL operator - whether condition contains all attribute
"\$all" -> {
if (attributeValue is JsonArray) {
// Loop through conditionValue array
// If none of the elements in the attributeValue array pass evalConditionValue(conditionValue[i], attributeValue[j]), return false
for (con in conditionValue) {
var result = false
for (attr in attributeValue) {
if (evalConditionValue(con, attr)) {
result = true
}
}
if (!result) {
return result
}
}
return true
} else {
// If attributeValue is not an array, return false
return false
}
}
}
} else if (attributeValue is JsonArray) {
when (operator) {
// Evaluate ElemMATCH operator - whether condition matches attribute
"\$elemMatch" -> {
return elemMatch(attributeValue, conditionValue)
}
// Evaluate SIE operator - whether condition size is same as that of attribute
"\$size" -> {
return evalConditionValue(conditionValue, JsonPrimitive(attributeValue.size))
}
}
} else if (attributeValue is JsonPrimitive? && conditionValue is JsonPrimitive) {
val targetPrimitiveValue = conditionValue.content
val sourcePrimitiveValue = attributeValue?.content
val paddedVersionTarget = GBUtils.paddedVersionString(targetPrimitiveValue)
val paddedVersionSource = GBUtils.paddedVersionString(sourcePrimitiveValue ?: "0")
when (operator) {
// Evaluate EQ operator - whether condition equals to attribute
"\$eq" -> {
return sourcePrimitiveValue == targetPrimitiveValue
}
// Evaluate NE operator - whether condition doesn't equal to attribute
"\$ne" -> {
return sourcePrimitiveValue != targetPrimitiveValue
}
// Evaluate LT operator - whether attribute less than to condition
"\$lt" -> {
if (attributeValue?.doubleOrNull != null && conditionValue.doubleOrNull != null) {
return (attributeValue?.doubleOrNull!! < conditionValue.doubleOrNull!!)
}
return if (sourcePrimitiveValue == null) {
0.0 < targetPrimitiveValue.toDouble()
} else {
sourcePrimitiveValue < targetPrimitiveValue
}
}
// Evaluate LTE operator - whether attribute less than or equal to condition
"\$lte" -> {
if (attributeValue?.doubleOrNull != null && conditionValue.doubleOrNull != null) {
return (attributeValue?.doubleOrNull!! <= conditionValue.doubleOrNull!!)
}
return if (sourcePrimitiveValue == null) {
0.0 <= targetPrimitiveValue.toDouble()
} else {
sourcePrimitiveValue <= targetPrimitiveValue
}
}
// Evaluate GT operator - whether attribute greater than to condition
"\$gt" -> {
if (attributeValue?.doubleOrNull != null && conditionValue.doubleOrNull != null) {
return (attributeValue?.doubleOrNull!! > conditionValue.doubleOrNull!!)
}
return if (sourcePrimitiveValue == null) {
0.0 > targetPrimitiveValue.toDouble()
} else {
sourcePrimitiveValue > targetPrimitiveValue
}
}
// Evaluate GTE operator - whether attribute greater than or equal to condition
"\$gte" -> {
if (attributeValue?.doubleOrNull != null && conditionValue.doubleOrNull != null) {
return (attributeValue?.doubleOrNull!! >= conditionValue.doubleOrNull!!)
}
return if (sourcePrimitiveValue == null) {
0.0 >= targetPrimitiveValue.toDouble()
} else {
sourcePrimitiveValue >= targetPrimitiveValue
}
}
// Evaluate REGEX operator - whether attribute contains condition regex
"\$regex" -> {
return try {
val regex = Regex(targetPrimitiveValue)
regex.containsMatchIn(sourcePrimitiveValue ?: "0")
} catch (error: Throwable) {
false
}
}
// Evaluate VEQ operator - whether versions are equals
"\$veq" -> return paddedVersionSource == paddedVersionTarget
// Evaluate VNE operator - whether versions are not equals to attribute
"\$vne" -> return paddedVersionSource != paddedVersionTarget
// Evaluate VGT operator - whether the first version is greater than the second version
"\$vgt" -> return paddedVersionSource > paddedVersionTarget
// Evaluate VGTE operator - whether the first version is greater than or equal the second version
"\$vgte" -> return paddedVersionSource >= paddedVersionTarget
// Evaluate VLT operator - whether the first version is lesser than the second version
"\$vlt" -> return paddedVersionSource < paddedVersionTarget
// Evaluate VLTE operator - whether the first version is lesser than or equal the second version
"\$vlte" -> return paddedVersionSource <= paddedVersionTarget
}
}
return false
}
private fun isIn(actualValue: JsonElement, conditionValue: JsonArray): Boolean {
if (actualValue !is JsonArray) return conditionValue.contains(actualValue)
if (actualValue.size == 0) return false
actualValue.forEach {
if (getType(it) == GBAttributeType.GbString ||
getType(it) == GBAttributeType.GbBoolean ||
getType(it) == GBAttributeType.GbNumber
) {
if (conditionValue.contains(it)) {
return true
}
}
}
return false
}
} | 8 | null | 20 | 24 | b7bc211c29c68dc6b8361add740bbd07e475f416 | 19,468 | growthbook-kotlin | MIT License |
app/src/main/java/com/tiagohs/hqr/interceptors/FavoritesInterceptor.kt | tiagohs | 135,235,006 | false | null | package com.tiagohs.hqr.interceptors
import android.content.Context
import com.tiagohs.hqr.database.IComicsRepository
import com.tiagohs.hqr.database.IHistoryRepository
import com.tiagohs.hqr.database.ISourceRepository
import com.tiagohs.hqr.helpers.tools.ListPaginator
import com.tiagohs.hqr.helpers.tools.PreferenceHelper
import com.tiagohs.hqr.helpers.utils.LocaleUtils
import com.tiagohs.hqr.interceptors.config.BaseComicsInterceptor
import com.tiagohs.hqr.interceptors.config.Contracts
import com.tiagohs.hqr.models.view_models.ComicViewModel
import com.tiagohs.hqr.sources.SourceManager
import com.tiagohs.hqr.ui.adapters.comics_details.ComicDetailsListItem
import io.reactivex.Observable
class FavoritesInterceptor(
private val preferenceHelper: PreferenceHelper,
private val comicsRepository: IComicsRepository,
private val historyRepository: IHistoryRepository,
private val sourceRepository: ISourceRepository,
private val sourceManager: SourceManager,
private val localeUtils: LocaleUtils
): BaseComicsInterceptor(comicsRepository, preferenceHelper, sourceManager, sourceRepository), Contracts.IFavoritesInterceptor {
var listPaginator: ListPaginator<ComicDetailsListItem> = ListPaginator()
override fun onSubscribeInitializa(context: Context): Observable<ComicDetailsListItem> {
return subscribeComicDetailSubject()
.map { it.toModel(context) }
}
override fun onGetFavorites(context: Context): Observable<List<ComicDetailsListItem>> {
return comicsRepository.getFavoritesComics()
.doOnNext { comics -> initializeComics(comics) }
.map {
val comicHistoryItems = it.map { it.toModel(context) }
listPaginator.onCreatePagination(comicHistoryItems)
}
}
override fun onGetMore(): Observable<List<ComicDetailsListItem>> {
return listPaginator.onGetNextPage()
.doOnNext { comicHistoryItems -> initializeComics(comicHistoryItems.map { it.comic }) }
}
override fun hasMoreComics(): Boolean {
return listPaginator.hasMorePages
}
override fun getOriginalList(): List<ComicDetailsListItem> {
return listPaginator.originalList
}
private fun ComicViewModel.toModel(context: Context): ComicDetailsListItem {
return ComicDetailsListItem(this, localeUtils, context, historyRepository.findByComicIdRealm(id))
}
} | 1 | Kotlin | 2 | 11 | 8a86fa1c66a9ba52afcf02bea4acbb674d8a473a | 2,496 | hqr-comics-reader | Apache License 2.0 |
idea/testData/completion/smart/ConstructorForGenericType.kt | staltz | 50,647,805 | true | {"Java": 15450397, "Kotlin": 8578737, "JavaScript": 176060, "HTML": 22810, "Lex": 17327, "Protocol Buffer": 13024, "ANTLR": 9689, "CSS": 9431, "Shell": 3931, "IDL": 3257, "Groovy": 3010, "Batchfile": 2831} | class Foo<T>
fun foo(p : Any){
var a : Foo<String> = <caret>
}
// EXIST: { lookupString:"Foo", itemText:"Foo<kotlin.String>()" }
| 1 | Java | 1 | 1 | f41f48b1124e2f162295718850426193ab55f43f | 135 | kotlin | Apache License 2.0 |
src/main/kotlin/com/wynnlab/base/BaseSpell.kt | WynnLab | 375,456,791 | false | null | package com.wynnlab.base
import com.wynnlab.WynnLabAPI
import org.bukkit.Bukkit
abstract class BaseSpell(private val maxTick: Int) : Runnable {
var t = -1
private var taskId = -1
open fun onCast() {}
open fun onTick() {}
open fun onCancel() {}
override fun run() {
++t
onTick()
if (t >= maxTick)
cancel()
}
protected fun delay() {
--t
}
protected fun cancel() {
onCancel()
Bukkit.getScheduler().cancelTask(taskId)
}
fun schedule(delay: Long = 0L, period: Long = 1L) {
taskId = Bukkit.getScheduler().runTaskTimer(WynnLabAPI, this, delay, period).taskId
onCast()
}
} | 0 | Kotlin | 0 | 1 | 371ad81f90ee2db5b15cceb4bf1524ee9e697f45 | 704 | WynnLab-API | MIT License |
data/src/main/java/com/petrulak/cleankotlin/data/source/local/dao/WeatherDao.kt | Petrulak | 104,648,833 | false | null | package com.petrulak.cleankotlin.data.source.local.dao
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Insert
import android.arch.persistence.room.Query
import com.petrulak.cleankotlin.data.source.local.model.WeatherEntity
import io.reactivex.Flowable
@Dao
interface WeatherDao {
@Query("SELECT * FROM WeatherEntity")
fun getAll(): Flowable<List<WeatherEntity>>
@Query("SELECT * FROM WeatherEntity where name = :name")
fun getByName(name: String): Flowable<WeatherEntity>
@Insert
fun insert(item: WeatherEntity)
@Query("DELETE from WeatherEntity where uid =:id")
fun deleteWeatherById(id: Long): Int
} | 0 | Kotlin | 10 | 111 | 51033f30ecdb9573000454f1b8890d20c2438002 | 670 | android-kotlin-mvp-clean-architecture | MIT License |
core/src/gameobjects/JewelMove.kt | PatriotCodes | 114,823,813 | false | null | package gameobjects
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import physics.Movement
class JewelMove(xFrom: Float, yFrom: Float, xTo: Float, yTo: Float, val jewel : Jewel,
startSpeed: Float, topSpeed: Float = startSpeed, acceleration: Float = 0f) :
Movement(xFrom, yFrom, xTo, yTo, startSpeed, topSpeed, acceleration) {
var destroyOnEnd = false
fun draw(batch : SpriteBatch, size : Float, delta : Float, gridOffset : Float) {
nextPosition(delta)
jewel.draw(batch, xCurrent * size, (yCurrent * size) + gridOffset, size, delta)
}
fun drawFromPosition(batch : SpriteBatch, size : Float, delta : Float, gridOffset : Float) {
jewel.draw(batch, xFrom * size, (yFrom * size) + gridOffset, size, delta)
}
fun drawToPosition(batch : SpriteBatch, size : Float, delta : Float, gridOffset : Float) {
jewel.draw(batch, xTo * size, (yTo * size) + gridOffset, size, delta)
}
}
| 13 | Kotlin | 0 | 5 | 3c654ce4744c1e0dab9c8727c25738baabfd304f | 962 | Diamond-Story | MIT License |
ktor-io/jvm/test/io/ktor/utils/io/ByteBufferChannelTest.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.utils.io
import kotlinx.coroutines.*
import kotlinx.coroutines.debug.junit4.*
import org.junit.*
import java.io.*
import kotlin.test.*
import kotlin.test.Test
class ByteBufferChannelTest {
@get:Rule
public val timeoutRule: CoroutinesTimeout by lazy { CoroutinesTimeout.seconds(60) }
@Test
fun testCompleteExceptionallyJob() {
val channel = ByteBufferChannel(false)
Job().also { channel.attachJob(it) }.completeExceptionally(IOException("Text exception"))
assertFailsWith<IOException> { runBlocking { channel.readByte() } }
}
@Test
fun readRemainingThrowsOnClosed() = runBlocking {
val channel = ByteBufferChannel(false)
channel.writeFully(byteArrayOf(1, 2, 3, 4, 5))
channel.close(IllegalStateException("closed"))
assertFailsWith<IllegalStateException>("closed") {
channel.readRemaining()
}
Unit
}
@Test
fun testWriteWriteAvailableRaceCondition() = runBlocking {
testWriteXRaceCondition { it.writeAvailable(1) { it.put(1) } }
}
@Test
fun testWriteByteRaceCondition() = runBlocking {
testWriteXRaceCondition { it.writeByte(1) }
}
@Test
fun testWriteIntRaceCondition() = runBlocking {
testWriteXRaceCondition { it.writeInt(1) }
}
@Test
fun testWriteShortRaceCondition() = runBlocking {
testWriteXRaceCondition { it.writeShort(1) }
}
@Test
fun testWriteLongRaceCondition() = runBlocking {
testWriteXRaceCondition { it.writeLong(1) }
}
private fun testWriteXRaceCondition(writer: suspend (ByteChannel) -> Unit): Unit = runBlocking {
val channel = ByteBufferChannel(false)
val job1 = GlobalScope.async {
try {
repeat(10_000_000) {
writer(channel)
channel.flush()
}
channel.close()
} catch (cause: Throwable) {
channel.close(cause)
throw cause
}
}
val job2 = GlobalScope.async {
channel.readRemaining()
}
job1.await()
job2.await()
}
@Test
fun testReadAvailable() = runBlocking {
val channel = ByteBufferChannel(true)
channel.writeFully(byteArrayOf(1, 2))
val read1 = channel.readAvailable(4) { it.position(it.position() + 4) }
assertEquals(-1, read1)
channel.writeFully(byteArrayOf(3, 4))
val read2 = channel.readAvailable(4) { it.position(it.position() + 4) }
assertEquals(4, read2)
}
@Test
fun testAwaitContent() = runBlocking {
val channel = ByteBufferChannel(true)
var awaitingContent = false
launch {
awaitingContent = true
channel.awaitContent()
awaitingContent = false
}
yield()
assertTrue(awaitingContent)
channel.writeByte(1)
yield()
assertFalse(awaitingContent)
}
}
| 9 | null | 774 | 9,308 | 9244f9a4a406f3eca06dc05d9ca0f7d7ec74a314 | 3,170 | ktor | Apache License 2.0 |
gmaven/src/main/kotlin/ru/rzn/gmyasoedov/gmaven/project/importing/kotlin/KotlinMavenPluginDataService.kt | grisha9 | 586,299,688 | false | null | package ru.rzn.gmyasoedov.gmaven.project.importing.kotlin
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments
import org.jetbrains.kotlin.compilerRunner.ArgumentUtils
import org.jetbrains.kotlin.config.createArguments
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.facet.configureFacet
import org.jetbrains.kotlin.idea.facet.getOrCreateFacet
import org.jetbrains.kotlin.idea.facet.noVersionAutoAdvance
import org.jetbrains.kotlin.idea.facet.parseCompilerArgumentsToFacet
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import ru.rzn.gmyasoedov.gmaven.GMavenConstants.SYSTEM_ID
import ru.rzn.gmyasoedov.gmaven.extensionpoints.plugin.kotlin.KotlinMavenPluginData
class KotlinMavenPluginDataService : AbstractProjectDataService<KotlinMavenPluginData, Void>() {
override fun getTargetDataKey() = KotlinMavenPluginData.KEY
override fun postProcess(
toImport: Collection<DataNode<KotlinMavenPluginData>>,
projectData: ProjectData?,
project: Project,
modifiableModelsProvider: IdeModifiableModelsProvider
) {
for (kotlinNode in toImport) {
val moduleData = kotlinNode.parent?.data as? ModuleData ?: continue
val ideModule = modifiableModelsProvider.findIdeModule(moduleData) ?: continue
val kotlinData = kotlinNode.data
val compilerVersion = kotlinData.kotlinVersion.let(IdeKotlinVersion::opt)
?: KotlinPluginLayout.standaloneCompilerVersion
val kotlinFacet = ideModule.getOrCreateFacet(
modifiableModelsProvider,
false,
SYSTEM_ID.id
)
val defaultPlatform = JvmIdePlatformKind.defaultPlatform
kotlinFacet.configureFacet(
compilerVersion,
defaultPlatform,
modifiableModelsProvider
)
val sharedArguments = getCompilerArgumentsByConfigurationElement(kotlinData, defaultPlatform)
parseCompilerArgumentsToFacet(sharedArguments, kotlinFacet, modifiableModelsProvider)
NoArgMavenProjectImportHandler.invoke(kotlinFacet, kotlinData)
AllOpenMavenProjectImportHandler.invoke(kotlinFacet, kotlinData)
kotlinFacet.noVersionAutoAdvance()
}
}
private fun getCompilerArgumentsByConfigurationElement(
kotlinData: KotlinMavenPluginData,
platform: TargetPlatform
): List<String> {
val arguments = platform.createArguments()
arguments.apiVersion = kotlinData.apiVersion
arguments.languageVersion = kotlinData.languageVersion
arguments.multiPlatform = false
arguments.suppressWarnings = kotlinData.noWarn
when (arguments) {
is K2JVMCompilerArguments -> {
arguments.jdkHome = kotlinData.jdkHome
arguments.jvmTarget = kotlinData.jvmTarget
}
}
parseCommandLineArguments(kotlinData.arguments, arguments)
return ArgumentUtils.convertArgumentsToStringList(arguments)
}
}
| 3 | null | 0 | 12 | 824ec9cab804b12d27cd952d3cdbe7e541c162bf | 3,764 | gmaven-plugin | Apache License 2.0 |
android/src/main/kotlin/com/julow/environment_sensors/EnvironmentSensorsPlugin.kt | nhandrew | 345,823,761 | false | {"Dart": 7216, "Kotlin": 5445, "Swift": 2971, "Ruby": 2225, "Objective-C": 772} | package com.julow.environment_sensors
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
/** EnvironmentSensorsPlugin */
class EnvironmentSensorsPlugin: FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private lateinit var channel : MethodChannel
private val METHOD_CHANNEL_NAME = "environment_sensors/method"
private val TEMPERATURE_CHANNEL_NAME = "environment_sensors/temperature"
private val HUMIDITY_CHANNEL_NAME = "environment_sensors/humidity"
private val LIGHT_CHANNEL_NAME = "environment_sensors/light"
private val PRESSURE_CHANNEL_NAME = "environment_sensors/pressure"
private var sensorManager: SensorManager? = null
private var methodChannel: MethodChannel? = null
private var temperatureChannel: EventChannel? = null
private var humidityChannel: EventChannel? = null
private var lightChannel: EventChannel? = null
private var pressureChannel: EventChannel? = null
private var temperatureStreamHandler: StreamHandlerImpl? = null
private var humidityStreamHandler: StreamHandlerImpl? = null
private var lightStreamHandler: StreamHandlerImpl? = null
private var pressureStreamHandler: StreamHandlerImpl? = null
companion object {
@JvmStatic
fun registerWith(registrar: Registrar) {
val plugin = EnvironmentSensorsPlugin()
plugin.setupEventChannels(registrar.context(), registrar.messenger())
}
}
override fun onAttachedToEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
val context = binding.applicationContext
setupEventChannels(context, binding.binaryMessenger)
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
teardownEventChannels()
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "isSensorAvailable") {
result.success(sensorManager!!.getSensorList(call.arguments as Int).isNotEmpty())
} else {
result.notImplemented()
}
}
private fun setupEventChannels(context: Context, messenger: BinaryMessenger) {
sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
methodChannel = MethodChannel(messenger, METHOD_CHANNEL_NAME)
methodChannel!!.setMethodCallHandler(this)
temperatureChannel = EventChannel(messenger, TEMPERATURE_CHANNEL_NAME)
temperatureStreamHandler = StreamHandlerImpl(sensorManager!!, Sensor.TYPE_AMBIENT_TEMPERATURE)
temperatureChannel!!.setStreamHandler(temperatureStreamHandler!!)
humidityChannel = EventChannel(messenger, HUMIDITY_CHANNEL_NAME)
humidityStreamHandler = StreamHandlerImpl(sensorManager!!, Sensor.TYPE_RELATIVE_HUMIDITY)
humidityChannel!!.setStreamHandler(humidityStreamHandler!!)
lightChannel = EventChannel(messenger, LIGHT_CHANNEL_NAME)
lightStreamHandler = StreamHandlerImpl(sensorManager!!, Sensor.TYPE_LIGHT)
lightChannel!!.setStreamHandler(lightStreamHandler!!)
pressureChannel = EventChannel(messenger, PRESSURE_CHANNEL_NAME)
pressureStreamHandler = StreamHandlerImpl(sensorManager!!, Sensor.TYPE_PRESSURE)
pressureChannel!!.setStreamHandler(pressureStreamHandler!!)
}
private fun teardownEventChannels() {
methodChannel!!.setMethodCallHandler(null)
temperatureChannel!!.setStreamHandler(null)
humidityChannel!!.setStreamHandler(null)
lightChannel!!.setStreamHandler(null)
pressureChannel!!.setStreamHandler(null)
}
}
class StreamHandlerImpl(private val sensorManager: SensorManager, sensorType: Int, private var interval: Int = SensorManager.SENSOR_DELAY_NORMAL) :
EventChannel.StreamHandler, SensorEventListener {
private val sensor = sensorManager.getDefaultSensor(sensorType)
private var eventSink: EventChannel.EventSink? = null
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
if (sensor != null) {
eventSink = events
sensorManager.registerListener(this, sensor, interval)
}
}
override fun onCancel(arguments: Any?) {
sensorManager.unregisterListener(this)
eventSink = null
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
override fun onSensorChanged(event: SensorEvent?) {
val sensorValues = event!!.values[0]
eventSink?.success(sensorValues)
}
fun setUpdateInterval(interval: Int) {
this.interval = interval
if (eventSink != null) {
sensorManager.unregisterListener(this)
sensorManager.registerListener(this, sensor, interval)
}
}
}
| 2 | Dart | 6 | 6 | 6d6ba7e014c26497ee96d4d297a674c6fcebd14f | 5,303 | environment_sensors | MIT License |
compose/test-utils/src/commonMain/kotlin/androidx/compose/testutils/ModifierTestUtils.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.testutils
import androidx.compose.ui.Modifier
fun Modifier.toList(): List<Modifier.Element> =
foldIn(mutableListOf()) { acc, e -> acc.apply { acc.add(e) } }
@Suppress("ModifierFactoryReturnType")
fun Modifier.first(): Modifier.Element =
toList().first()
/**
* Asserts that creating two modifier with the same inputs will resolve to true when compared. In
* a similar fashion, toggling the inputs will resolve to false. Ideally, all modifier elements
* should preserve this property so when creating a modifier, an additional test should be included
* to guarantee that.
*/
fun assertModifierIsPure(createModifier: (toggle: Boolean) -> Modifier) {
val first = createModifier(true)
val second = createModifier(false)
val third = createModifier(true)
assert(first == third) {
"Modifier with same inputs should resolve true to equals call"
}
assert(first != second) {
"Modifier with different inputs should resolve false to equals call"
}
}
| 29 | null | 937 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 1,641 | androidx | Apache License 2.0 |
app/src/main/java/ru/maxim/barybians/ui/fragment/chat/ChatRecyclerAdapter.kt | maximborodkin | 286,116,912 | false | null | package ru.maxim.barybians.ui.fragment.chat
import android.graphics.drawable.Animatable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_incoming_message.view.*
import kotlinx.android.synthetic.main.item_outgoing_message.view.*
import ru.maxim.barybians.R
import ru.maxim.barybians.ui.fragment.chat.OutgoingMessage.MessageStatus.*
class ChatRecyclerAdapter(
private val messages: ArrayList<MessageItem>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
init {
setHasStableIds(true)
}
class IncomingMessageViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView: AppCompatTextView = view.itemIncomingMessageText
val timeView: TextView = view.itemIncomingMessageTime
}
class OutgoingMessageViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textView: AppCompatTextView = view.itemOutgoingMessageText
val timeView: TextView = view.itemOutgoingMessageTime
private val messageLabel: AppCompatImageView = view.itemOutgoingMessageLabel
init { clearLabel() }
fun setSendingProcessLabel() {
messageLabel.setBackgroundResource(R.drawable.ic_sending_process_animated)
(messageLabel.background as Animatable).start()
}
fun setErrorLabel() { messageLabel.setBackgroundResource(R.drawable.ic_error) }
fun setUnreadLabel() { messageLabel.setBackgroundResource(R.drawable.unread_circle) }
fun clearLabel() { messageLabel.background = null }
}
override fun getItemId(position: Int) = messages[position].viewId
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when(viewType) {
MessageType.IncomingMessage.viewType -> IncomingMessageViewHolder(
LayoutInflater
.from(parent.context)
.inflate(R.layout.item_incoming_message, parent, false)
)
MessageType.OutgoingMessage.viewType -> OutgoingMessageViewHolder(
LayoutInflater
.from(parent.context)
.inflate(R.layout.item_outgoing_message, parent, false)
)
else -> throw IllegalStateException("Unknown view type")
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val message = messages[position]
when(getItemViewType(position)) {
MessageType.IncomingMessage.viewType -> {
val incomingMessage = message as? IncomingMessage
(holder as? IncomingMessageViewHolder)?.let {
it.textView.text = incomingMessage?.text
it.timeView.text = incomingMessage?.time
}
}
MessageType.OutgoingMessage.viewType -> {
val outgoingMessage = message as? OutgoingMessage ?: return
(holder as? OutgoingMessageViewHolder)?.let {
it.textView.text = outgoingMessage.text
it.timeView.text = outgoingMessage.time
when(outgoingMessage.status) {
Sending -> holder.setSendingProcessLabel()
Unread -> holder.setUnreadLabel()
Read -> holder.clearLabel()
Error -> holder.setErrorLabel()
}
}
}
else -> throw IllegalStateException("Unknown view type")
}
}
override fun getItemViewType(position: Int): Int = messages[position].getType()
override fun getItemCount(): Int = messages.size
} | 0 | Kotlin | 1 | 4 | eb0dbd6e0e0e732f2d2721f7bf5fbe13fe6338ad | 3,930 | Barybians-Android-App | MIT License |
shared/src/commonMain/kotlin/com/takaotech/dashboard/model/github/TagDao.kt | TakaoTech | 761,297,714 | false | {"Kotlin": 301488, "Swift": 594, "HTML": 369, "Dockerfile": 348} | package com.takaotech.dashboard.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class TagDao(
@SerialName("id")
val id: Int,
@SerialName("name")
val name: String,
@SerialName("description")
val description: String? = null
)
@Serializable
data class TagNewDao(
@SerialName("name")
val name: String,
@SerialName("description")
val description: String? = null
) | 6 | Kotlin | 0 | 2 | 10b1c4559d059234e968543dd5d975ee9b795107 | 430 | TTD | Apache License 2.0 |
src/main/kotlin/com/peasenet/mixinterface/IMinecraftClient.kt | gavinsmod | 493,304,032 | false | null | /*
* Copyright (c) 2022-2023. <NAME> and contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package com.peasenet.mixinterface
import net.minecraft.client.font.TextRenderer
import net.minecraft.client.gui.screen.Screen
import net.minecraft.client.network.ClientPlayerEntity
import net.minecraft.client.network.ClientPlayerInteractionManager
import net.minecraft.client.network.message.MessageHandler
import net.minecraft.client.option.GameOptions
import net.minecraft.client.render.WorldRenderer
import net.minecraft.client.render.entity.EntityRenderDispatcher
import net.minecraft.client.util.Window
import net.minecraft.client.world.ClientWorld
import net.minecraft.util.hit.HitResult
import java.io.File
/**
* @author gt3ch1
* @version 03-02-2023
* A mixin interface for the Minecraft client to allow access for certain members that are not public.
*/
interface IMinecraftClient {
/**
* Sets the cooldown time for using any item.
*
* @param cooldown - The cooldown time.
*/
fun setItemUseCooldown(cooldown: Int)
/**
* The current frames per second.
*
* @return The current frames per second.
*/
fun getFps(): Int
/**
* Gets the current options for the game.
*
* @return The current options for the game.
*/
val options: GameOptions
/**
* Gets the player interaction manager.
*
* @return The player interaction manager.
*/
fun getPlayerInteractionManager(): ClientPlayerInteractionManager
/**
* Gets the text renderer of the client.
*
* @return The text renderer.
*/
val textRenderer: TextRenderer
/**
* Gets the world that the player is currently in.
*
* @return The current world.
*/
fun getWorld(): ClientWorld
/**
* Sets the current in game screen to the given parameter
*
* @param s - The screen to change to.
*/
fun setScreen(s: Screen?)
/**
* Gets the current world renderer.
*
* @return The world renderer.
*/
val worldRenderer: WorldRenderer
/**
* Enables or disables chunk culling (rendering only chunks that are in the viewport).
*
* @param b - Whether to enable or disable chunk culling.
*/
fun setChunkCulling(b: Boolean)
/**
* Gets the current game window.
*
* @return The game window.
*/
val window: Window
/**
* Gets the run-directory of the game.
*
* @return The run-directory of the game.
*/
val runDirectory: File
/**
* Gets the target from the crosshair.
*
* @return The target from the crosshair.
*/
fun crosshairTarget(): HitResult
fun getPlayer(): ClientPlayerEntity
/**
* Gets the entity render dispatcher.
*
* @return The entity render dispatcher.
*/
val entityRenderDispatcher: EntityRenderDispatcher
/**
* Gets the message handler.
*
* @return The message handler.
*/
val messageHandler: MessageHandler
companion object {
/**
* Gets the player.
*
* @return The player
*/
val player: ClientPlayerEntity? = null
}
} | 1 | Kotlin | 0 | 21 | 740ecd3aff4f0fcab2aee10ffe6b9ca29d5c42f2 | 4,255 | minecraft-mod | MIT License |
arrow-inject-compiler-plugin/src/testData/box/value-arguments/a_polymorphic_provider_may_have_injection_arguments_which_are_polymorphically_resolved.kt | arrow-kt | 471,344,439 | false | null | package foo.bar
import arrow.inject.annotations.Inject
import foo.bar.annotations.Given
@Given internal fun intProvider(): Int = 42
data class Foo<A>(val n: A)
@Given internal fun <A> fooProvider(@Given x: A): Foo<A> = Foo(x)
@Inject fun <A> given(@Given value: A): A = value
fun box(): String {
val result = given<Foo<Int>>()
return if (result == Foo(42)) {
"OK"
} else {
"Fail: $result"
}
}
| 13 | Kotlin | 2 | 9 | f2d62a93fa18fc7f2944687642c8ad01a0d23bf5 | 415 | arrow-proofs | Apache License 2.0 |
app/src/main/java/com/igweze/ebi/todosqlite/CategoryActivity.kt | ebi-igweze | 126,055,743 | false | null | package com.igweze.ebi.todosqlite
import android.app.AlertDialog
import android.app.LoaderManager
import android.databinding.ObservableArrayList
import android.os.Bundle
import android.content.ContentValues
import android.content.CursorLoader
import android.content.DialogInterface
import android.content.Loader
import android.database.Cursor
import android.widget.AdapterView
import android.databinding.DataBindingUtil
import android.net.Uri
import com.igweze.ebi.todosqlite.databinding.ActivityCategoryBinding
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ListView
import kotlinx.android.synthetic.main.activity_category.*
class CategoryActivity : AppCompatActivity(), LoaderManager.LoaderCallbacks<Cursor> {
companion object {
const val URL_LOADER = 0
}
var cursor: Cursor? = null
private var category: CategoryModel? = null
private lateinit var categories: CategoryListModel
private lateinit var list: ObservableArrayList<CategoryModel>
private lateinit var adapter: CategoryListAdapter
private lateinit var binding: ActivityCategoryBinding
private lateinit var handler: TodosQueryHandler
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//inflater
val inflater = layoutInflater
//adds the custom layout
binding = DataBindingUtil.setContentView(this, R.layout.activity_category)
loaderManager.initLoader(URL_LOADER, null, this)
//get the listView and add the onclicklistener
handler = TodosQueryHandler(contentResolver)
//EVENTS
//add the click event to the list, so that the selected item goes to the
lvCategories.setOnItemClickListener { _, _, position, _ ->
category = categories.categories[position]
binding.category = category
}
//New button will add a new line on the list
btnAdd.setOnClickListener {
category = CategoryModel()
// categories.categories.add(category);
binding.category = category
}
//delete button will delete an item from the list
btnDelete.setOnClickListener {
AlertDialog.Builder(this@CategoryActivity)
.setTitle(getString(R.string.delete_categories_dialog_title))
.setMessage(getString(R.string.delete_categories_dialog))
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, { _, _ ->
categories.categories.remove(category)
val categoryId = (category!!.id.get()).toString()
val uri = Uri.withAppendedPath(TodoContract.CategoriesEntry.CONTENT_URI, categoryId)
val selection = "${TodoContract.CategoriesEntry._ID}=$categoryId"
handler.startDelete(1, null, uri, selection, null)
category = null
})
.setNegativeButton(android.R.string.no, null)
.show()
}
//save button
btnSave.setOnClickListener {
if (category != null && category?.id?.get() != null && category?.id?.get() != 0) {
//update existing category
val args = arrayOf(category!!.id.get().toString())
val values = ContentValues()
values.put(TodoContract.CategoriesEntry.COLUMN_DESCRIPTION, category!!.description.get())
handler.startUpdate(1, null, TodoContract.CategoriesEntry.CONTENT_URI,
values, TodoContract.CategoriesEntry._ID + "=?", args)
} else if (category != null && category?.id?.get() == null || category?.id?.get() == 0) {
//add new category
val values = ContentValues()
values.put(TodoContract.CategoriesEntry.COLUMN_DESCRIPTION, category!!.description.get())
handler.startInsert(1, null, TodoContract.CategoriesEntry.CONTENT_URI, values)
}
}
}
public override fun onResume() {
loaderManager.restartLoader(URL_LOADER, null, this)
super.onResume()
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
val projection = arrayOf(TodoContract.CategoriesEntry.TABLE_NAME
+ "." + TodoContract.CategoriesEntry._ID, TodoContract.CategoriesEntry.COLUMN_DESCRIPTION)
return CursorLoader(this,
TodoContract.CategoriesEntry.CONTENT_URI,
projection, null, null, null)
}
override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor) {
val lv = findViewById<View>(R.id.lvCategories) as ListView
list = ObservableArrayList()
var i = 0
//fills the observablelist of categories
// Move cursor before first so we can still iterate after config change
data.moveToPosition(-1)
while (data.moveToNext()) {
list.add(i, CategoryModel(data.getInt(0), data.getString(1)))
i++
}
adapter = CategoryListAdapter(list)
lv.adapter = adapter
//set bindings
//classes
category = CategoryModel()
categories = CategoryListModel(list)
binding.categoryList = categories
binding.category = category
}
override fun onLoaderReset(loader: Loader<Cursor>) {
adapter.list = null
}
} | 0 | Kotlin | 0 | 0 | 6a3307fa3b2accfd7cb5f27fc69316a5939e726d | 5,547 | todosqlite | MIT License |
app/src/main/java/com/example/background/workers/WorkerUtils.kt | AnaLu72651718 | 523,479,436 | false | null | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("WorkerUtils")
package com.example.background.workers
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.graphics.*
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.annotation.WorkerThread
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.renderscript.*
import com.example.background.*
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.lang.Integer.min
import java.util.*
/**
* Create a Notification that is shown as a heads-up notification if possible.
*
* For this codelab, this is used to show a notification so that you know when different steps
* of the background work chain are starting
*
* @param message Message shown on the notification
* @param context Context needed to create Toast
*/
private const val TAG = "WorkerUtils"
fun makeStatusNotification(message: String, context: Context) {
// Make a channel if necessary
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
val name = VERBOSE_NOTIFICATION_CHANNEL_NAME
val description = VERBOSE_NOTIFICATION_CHANNEL_DESCRIPTION
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(CHANNEL_ID, name, importance)
channel.description = description
// Add the channel
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
notificationManager?.createNotificationChannel(channel)
}
// Create the notification
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(NOTIFICATION_TITLE)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVibrate(LongArray(0))
// Show the notification
NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, builder.build())
}
/**
* Method for sleeping for a fixed amount of time to emulate slower work
*/
fun sleep() {
try {
Thread.sleep(DELAY_TIME_MILLIS, 0)
} catch (e: InterruptedException) {
Log.e(TAG, e.message.toString())
}
}
/**
* Blurs the given Bitmap image
* @param bitmap Image to blur
* @param applicationContext Application context
* @return Blurred bitmap image
*/
@WorkerThread
fun blurBitmap(bitmap: Bitmap, applicationContext: Context): Bitmap {
lateinit var rsContext: RenderScript
try {
// Create the output bitmap
val output = Bitmap.createBitmap(
bitmap.width, bitmap.height, bitmap.config)
// Blur the image
rsContext = RenderScript.create(applicationContext, RenderScript.ContextType.DEBUG)
val inAlloc = Allocation.createFromBitmap(rsContext, bitmap)
val outAlloc = Allocation.createTyped(rsContext, inAlloc.type)
val theIntrinsic = ScriptIntrinsicBlur.create(rsContext, Element.U8_4(rsContext))
theIntrinsic.apply {
setRadius(10f)
theIntrinsic.setInput(inAlloc)
theIntrinsic.forEach(outAlloc)
}
outAlloc.copyTo(output)
return output
} finally {
rsContext.finish()
}
}
/**
* Blurs the given Bitmap image
* @param bitmap Image to blur
* @param applicationContext Application context
* @return Resized bitmap image
*/
@WorkerThread
fun circleBitmap(bitmap: Bitmap, applicationContext: Context): Bitmap {
lateinit var rsContext: RenderScript
try {
// Select whichever of width or height is minimum
val squareBitmapWidth = min(bitmap!!.width, bitmap.height)
rsContext = RenderScript.create(applicationContext, RenderScript.ContextType.DEBUG)
// Generate a bitmap with the above value as dimensions
val dstBitmap = Bitmap.createBitmap(
squareBitmapWidth,
squareBitmapWidth,
Bitmap.Config.ARGB_8888
)
// Initializing a Canvas with the above generated bitmap
val canvas = Canvas(dstBitmap)
// initializing Paint
val paint = Paint()
paint.isAntiAlias = true
// Generate a square (rectangle with all sides same)
val rect = Rect(0, 0, squareBitmapWidth, squareBitmapWidth)
val rectF = RectF(rect)
// Operations to draw a circle
canvas.drawOval(rectF, paint)
paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
val left = ((squareBitmapWidth - bitmap.width) / 2).toFloat()
val top = ((squareBitmapWidth - bitmap.height) / 2).toFloat()
canvas.drawBitmap(bitmap, left, top, paint)
bitmap.recycle()
// Return the bitmap
return dstBitmap
} finally {
rsContext.finish()
}
}
/**
* Writes bitmap to a temporary file and returns the Uri for the file
* @param applicationContext Application context
* @param bitmap Bitmap to write to temp file
* @return Uri for temp file with bitmap
* @throws FileNotFoundException Throws if bitmap file cannot be found
*/
@Throws(FileNotFoundException::class)
fun writeBitmapToFile(applicationContext: Context, bitmap: Bitmap): Uri {
val name = String.format("blur-filter-output-%s.png", UUID.randomUUID().toString())
val outputDir = File(applicationContext.filesDir, OUTPUT_PATH)
if (!outputDir.exists()) {
outputDir.mkdirs() // should succeed
}
val outputFile = File(outputDir, name)
var out: FileOutputStream? = null
try {
out = FileOutputStream(outputFile)
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /* ignored for PNG */, out)
} finally {
out?.let {
try {
it.close()
} catch (ignore: IOException) {
}
}
}
return Uri.fromFile(outputFile)
}
| 0 | Kotlin | 0 | 0 | cfed93d248eabea2e62db57b16a2418746d1b358 | 6,794 | android-workmanager-master | Apache License 2.0 |
ktor-http/ktor-http-cio/jvm/src/io/ktor/http/cio/Pipeline.kt | jakobkmar | 323,173,348 | false | null | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http.cio
import io.ktor.http.cio.internals.*
import io.ktor.server.cio.backend.*
import io.ktor.utils.io.*
import kotlinx.coroutines.*
@Deprecated("This is going to become private", level = DeprecationLevel.HIDDEN)
@Suppress("KDocMissingDocumentation", "unused")
public fun lastHttpRequest(http11: Boolean, connectionOptions: ConnectionOptions?): Boolean {
return isLastHttpRequest(http11, connectionOptions)
}
/**
* HTTP request handler function
*/
public typealias HttpRequestHandler = suspend ServerRequestScope.(
request: Request
) -> Unit
/**
* HTTP pipeline coroutine name
*/
@Deprecated("This is an implementation detail and will become internal in future releases.")
public val HttpPipelineCoroutine: CoroutineName = CoroutineName("http-pipeline")
/**
* HTTP pipeline writer coroutine name
*/
@Deprecated("This is an implementation detail and will become internal in future releases.")
public val HttpPipelineWriterCoroutine: CoroutineName = CoroutineName("http-pipeline-writer")
/**
* HTTP request handler coroutine name
*/
@Deprecated("This is an implementation detail and will become internal in future releases.")
public val RequestHandlerCoroutine: CoroutineName = CoroutineName("request-handler")
/**
* Start connection HTTP pipeline invoking [handler] for every request.
* Note that [handler] could be invoked multiple times concurrently due to HTTP pipeline nature
*
* @param input incoming channel
* @param output outgoing bytes channel
* @param timeout number of IDLE seconds after the connection will be closed
* @param handler to be invoked for every incoming request
*
* @return pipeline job
*/
@Deprecated(
"This is going to become internal. " +
"Start ktor server or raw cio server from ktor-server-cio module instead of constructing server from parts."
)
@OptIn(
ObsoleteCoroutinesApi::class, ExperimentalCoroutinesApi::class
)
public fun CoroutineScope.startConnectionPipeline(
input: ByteReadChannel,
output: ByteWriteChannel,
timeout: WeakTimeoutQueue,
handler: suspend CoroutineScope.(
request: Request,
input: ByteReadChannel, output: ByteWriteChannel, upgraded: CompletableDeferred<Boolean>?
) -> Unit
): Job {
val pipeline = ServerIncomingConnection(input, output, null, null)
return startServerConnectionPipeline(pipeline, timeout) { request ->
handler(this, request, input, output, upgraded)
}
}
| 0 | null | 1 | 7 | ea35658a05cc085b97297a303a7c0de37efe0024 | 2,579 | ktor | Apache License 2.0 |
android/app/src/main/java/com/pda/screenshotmatcher2/views/fragments/SettingsFragment.kt | PDA-UR | 337,995,962 | false | null | package com.pda.screenshotmatcher2.views.fragments
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.HapticFeedbackConstants
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.cardview.widget.CardView
import androidx.fragment.app.FragmentTransaction
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.pda.screenshotmatcher2.R
import com.pda.screenshotmatcher2.views.interfaces.GarbageView
/**
* A fragment allowing users to change application settings.
*
* @property mFragmentBackground The dark background behind the fragment, calls [removeThisFragment] on click
* @property containerView The container view for the fragment
*/
class SettingsFragment : GarbageView, PreferenceFragmentCompat() {
private lateinit var mFragmentBackground: FrameLayout
private lateinit var containerView: CardView
private var aboutButton: Preference? = null
/**
* Called when the fragment is created, calls [setPreferencesFromResource] to set the preferences
*/
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
}
/**
* Called on fragment view creation, returns an inflated view of this fragment.
* @return Inflated view of this fragment
*/
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
containerView = container as CardView
containerView.visibility = View.VISIBLE
return super.onCreateView(inflater, container, savedInstanceState)
}
/**
* Called when the fragment view has been created, initializes the views and listeners.
*/
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mFragmentBackground = activity?.findViewById(R.id.ca_dark_background)!!
mFragmentBackground.apply {
setOnClickListener{removeThisFragment()}
visibility = View.VISIBLE
}
aboutButton = findPreference(getString(R.string.settings_about_button))
aboutButton?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val uri: Uri =
Uri.parse("https://github.com/PDA-UR/Screenshotmatcher-2.0")
val intent = Intent(Intent.ACTION_VIEW, uri)
startActivity(intent)
true
}
}
/**
* Removes this fragment
*/
private fun removeThisFragment() {
containerView.visibility = View.INVISIBLE
mFragmentBackground.visibility = View.INVISIBLE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
activity?.window?.decorView?.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY_RELEASE)
}
activity?.supportFragmentManager?.beginTransaction()?.remove(this)
?.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE)?.commit()
clearGarbage()
}
override fun clearGarbage() {
mFragmentBackground.setOnClickListener(null)
aboutButton?.onPreferenceClickListener = null
}
} | 9 | null | 0 | 8 | 54c05298543778ad0f15a0276aa626ab84cd4522 | 3,378 | Screenshotmatcher-2.0 | MIT License |
platform/lang-impl/src/com/intellij/codeInsight/completion/OffsetsInFile.kt | tnorbye | 170,095,405 | true | {"Java": 169603963, "Python": 25582594, "Kotlin": 6740047, "Groovy": 3535139, "HTML": 2117263, "C": 214294, "C++": 180123, "CSS": 172743, "JavaScript": 148969, "Lex": 148871, "XSLT": 113036, "Jupyter Notebook": 93222, "Shell": 60209, "NSIS": 58584, "Batchfile": 49961, "Roff": 37497, "Objective-C": 32636, "TeX": 25473, "AMPL": 20665, "TypeScript": 9958, "J": 5050, "PHP": 2699, "Makefile": 2352, "Thrift": 1846, "CoffeeScript": 1759, "CMake": 1675, "Ruby": 1217, "Perl": 973, "Smalltalk": 906, "C#": 696, "AspectJ": 182, "Visual Basic": 77, "HLSL": 57, "Erlang": 10} | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.editor.impl.DocumentImpl
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.ChangedPsiRangeUtil
import com.intellij.psi.impl.source.tree.FileElement
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil
import com.intellij.psi.text.BlockSupport
/**
* @author peter
*/
class OffsetsInFile(val file: PsiFile, val offsets: OffsetMap) {
constructor(file: PsiFile) : this(file, OffsetMap(file.viewProvider.document!!))
fun toTopLevelFile(): OffsetsInFile {
val manager = InjectedLanguageManager.getInstance(file.project)
val hostFile = manager.getTopLevelFile(file)
if (hostFile == file) return this
return OffsetsInFile(hostFile, offsets.mapOffsets(hostFile.viewProvider.document!!) { manager.injectedToHost(file, it) })
}
fun toInjectedIfAny(offset: Int): OffsetsInFile {
val injected = InjectedLanguageUtil.findInjectedPsiNoCommit(file, offset) ?: return this
val documentWindow = InjectedLanguageUtil.getDocumentWindow(injected)!!
return OffsetsInFile(injected, offsets.mapOffsets(documentWindow) { documentWindow.hostToInjected(it) })
}
fun copyWithReplacement(startOffset: Int, endOffset: Int, replacement: String): OffsetsInFile {
return replaceInCopy(file.copy() as PsiFile, startOffset, endOffset, replacement)
}
fun replaceInCopy(fileCopy: PsiFile, startOffset: Int, endOffset: Int, replacement: String): OffsetsInFile {
val tempDocument = DocumentImpl(offsets.document.immutableCharSequence, true)
val tempMap = offsets.copyOffsets(tempDocument)
tempDocument.replaceString(startOffset, endOffset, replacement)
reparseFile(fileCopy, tempDocument.immutableCharSequence)
val copyOffsets = tempMap.copyOffsets(fileCopy.viewProvider.document!!)
return OffsetsInFile(fileCopy, copyOffsets)
}
private fun reparseFile(file: PsiFile, newText: CharSequence) {
val node = file.node as? FileElement ?: throw IllegalStateException("${file.javaClass} ${file.fileType}")
val range = ChangedPsiRangeUtil.getChangedPsiRange(file, node, newText) ?: return
val indicator = ProgressManager.getGlobalProgressIndicator() ?: EmptyProgressIndicator()
val log = BlockSupport.getInstance(file.project).reparseRange(file, node, range, newText, indicator, file.viewProvider.contents)
ProgressManager.getInstance().executeNonCancelableSection { log.doActualPsiChange(file) }
}
}
| 0 | Java | 0 | 1 | f01cf262fc196bf4dbb99e20cd937dee3705a7b6 | 3,239 | intellij-community | Apache License 2.0 |
visionforge-solid/src/commonMain/kotlin/space/kscience/visionforge/solid/ColorAccessor.kt | mipt-npm | 174,502,624 | false | null | package space.kscience.visionforge.solid
import space.kscience.dataforge.meta.MutableItemProvider
import space.kscience.dataforge.meta.set
import space.kscience.dataforge.meta.value
import space.kscience.dataforge.names.Name
import space.kscience.dataforge.values.Value
import space.kscience.dataforge.values.asValue
import space.kscience.dataforge.values.string
import space.kscience.visionforge.Colors
import space.kscience.visionforge.VisionBuilder
@VisionBuilder
public class ColorAccessor(private val parent: MutableItemProvider, private val colorKey: Name) {
public var value: Value?
get() = parent.getItem(colorKey).value
set(value) {
parent[colorKey] = value
}
}
public var ColorAccessor?.string: String?
get() = this?.value?.string
set(value) {
this?.value = value?.asValue()
}
/**
* Set [webcolor](https://en.wikipedia.org/wiki/Web_colors) as string
*/
public operator fun ColorAccessor?.invoke(webColor: String) {
this?.value = webColor.asValue()
}
/**
* Set color as RGB integer
*/
public operator fun ColorAccessor?.invoke(rgb: Int) {
this?.value = Colors.rgbToString(rgb).asValue()
}
/**
* Set color as RGB
*/
public operator fun ColorAccessor?.invoke(r: UByte, g: UByte, b: UByte) {
this?.value = Colors.rgbToString(r, g, b).asValue()
}
public fun ColorAccessor?.clear() {
this?.value = null
} | 11 | Kotlin | 5 | 25 | 456e01fcfa48f798a03cc5866acc5d4c557e00c3 | 1,397 | visionforge | Apache License 2.0 |
buildSrc/src/main/kotlin/AndroidTestLibs.kt | mobdev778 | 583,432,301 | false | null | sealed class AndroidTestLibs(val name: String) {
object testRunner : AndroidTestLibs("androidx.test:runner:1.2.0")
object extJUnit : AndroidTestLibs("androidx.test.ext:junit:1.1.5")
object espressoCore : AndroidTestLibs("androidx.test.espresso:espresso-core:3.5.1")
object uiTestJUnit4 : AndroidTestLibs("androidx.compose.ui:ui-test-junit4:${ProjectVersions.composeVersion}")
object jupiterApi : AndroidTestLibs("org.junit.jupiter:junit-jupiter-api:5.9.3")
object jupiterParams : AndroidTestLibs("org.junit.jupiter:junit-jupiter-params:5.9.3")
sealed class hamcrest(name: String) : AndroidTestLibs(name) {
object core : hamcrest("org.hamcrest:hamcrest-core:2.2")
}
sealed class okHttp3(name: String) : AndroidTestLibs(name) {
object okhttp : okHttp3("com.squareup.okhttp3:okhttp:${ProjectVersions.okHttp3}")
object loggingInterceptor : okHttp3("com.squareup.okhttp3:logging-interceptor:${ProjectVersions.okHttp3}")
}
}
| 1 | Kotlin | 0 | 0 | b86aaf0e86c963c098d620b649b360cfa5277ae6 | 988 | yusupova-android-app | MIT License |
buildSrc/src/main/kotlin/AndroidTestLibs.kt | mobdev778 | 583,432,301 | false | null | sealed class AndroidTestLibs(val name: String) {
object testRunner : AndroidTestLibs("androidx.test:runner:1.2.0")
object extJUnit : AndroidTestLibs("androidx.test.ext:junit:1.1.5")
object espressoCore : AndroidTestLibs("androidx.test.espresso:espresso-core:3.5.1")
object uiTestJUnit4 : AndroidTestLibs("androidx.compose.ui:ui-test-junit4:${ProjectVersions.composeVersion}")
object jupiterApi : AndroidTestLibs("org.junit.jupiter:junit-jupiter-api:5.9.3")
object jupiterParams : AndroidTestLibs("org.junit.jupiter:junit-jupiter-params:5.9.3")
sealed class hamcrest(name: String) : AndroidTestLibs(name) {
object core : hamcrest("org.hamcrest:hamcrest-core:2.2")
}
sealed class okHttp3(name: String) : AndroidTestLibs(name) {
object okhttp : okHttp3("com.squareup.okhttp3:okhttp:${ProjectVersions.okHttp3}")
object loggingInterceptor : okHttp3("com.squareup.okhttp3:logging-interceptor:${ProjectVersions.okHttp3}")
}
}
| 1 | Kotlin | 0 | 0 | b86aaf0e86c963c098d620b649b360cfa5277ae6 | 988 | yusupova-android-app | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.