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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Drafts/D3/Awake/core/src/com/cs446/awake/model/State.kt | kew6688 | 697,904,297 | false | null | package com.cs446.awake.model
import kotlin.random.Random
class State(val stateName: String,
var effectiveRound: Int
) {
var releaseProbability = 0.0 // prob of getting rid of the status
var moveProbability = 1.0 // probability of making of move
var damage = 0.0
var energyEffect = 0.0
var strengthEffect = 0.0
var releaseList: MutableList<String> = mutableListOf() // release from other states when cur state is added
var description = ""
var img = ""
init {
when(stateName) {
Burn -> setBurn()
Freeze -> setFreeze()
Poison -> setPoison()
Paralysis -> setParalysis()
Sleep -> setSleep()
}
}
private fun setBurn(){
releaseProbability = 0.2
energyEffect = -0.5
damage = -0.0625
releaseList.add(Freeze)
// add description
img = "burn.png"
description = Burn
}
private fun setFreeze(){
releaseProbability = 0.2
moveProbability = 0.0
strengthEffect = -0.5
releaseList.add(Burn)
img = "freeze.png"
description = "Freeze"
}
private fun setPoison(){
damage = -0.0625
img = "poison.png"
description = "Poison"
}
private fun setParalysis(){
moveProbability = 0.75
img = "paralysis.png"
description = "Paralysis"
}
private fun setSleep(){
moveProbability = 0.0
releaseList.addAll(listOf("Burn", "Freeze", "Poison", "Paralysis"))
img = "sleep.png"
description = "Sleep"
}
private fun random_event(prob:Double): Boolean{
val oneNums = (prob * 100).toInt()
val randomIndex = Random.nextInt(100)
if (randomIndex < oneNums) {
return true
}
return false
}
fun extend(extendedState: State){
effectiveRound += extendedState.effectiveRound
}
// Return true to stop character using cards. (Freeze Character)
fun apply(target: Character): Boolean {
//target.removeState(releaseList)
// check if the state can be released
//if (releaseProbability > 0 && random_event(releaseProbability)) {
// target.removeState(mutableListOf(stateName))
// return
//}
var freezePlayer = false
// check if player can move
if (moveProbability == 0.0) {
freezePlayer = true
} else if (moveProbability < 1.0 && !random_event(moveProbability)) {
freezePlayer = true
}
// damage
val damageAmount = (damage * target.HP).toInt()
target.updateHealth(damageAmount)
println(stateName + " deals $damageAmount damage")
// strength effect
val strengthAmount = (strengthEffect * target.strength).toInt()
target.updateStrength(strengthAmount)
// energy effect
val energyAmount = (energyEffect * target.strength).toInt()
target.updateEnergy(energyAmount)
effectiveRound -= 1
// check effective round
//if (effectiveRound <= 0){
// target.removeState(mutableListOf(stateName))
//}
return freezePlayer
}
} | 0 | Kotlin | 0 | 0 | eb6e81b303f40b2041093741cbce36595e68b7df | 3,283 | CS446 | MIT License |
app/src/main/java/com/example/mymovieapp/viewmodel/RegisterViewModel.kt | rezakardan | 695,951,652 | false | {"Kotlin": 54831} | package com.example.mymovieapp.viewmodel
import com.example.mymovieapp.models.register.BodyRegister
import com.example.mymovieapp.models.register.ResponseRegister
import com.example.mymovieapp.repository.RegisterRepository
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class RegisterViewModel @Inject constructor(private val repository: RegisterRepository) : ViewModel() {
val registerUser = MutableLiveData<ResponseRegister>()
val loading = MutableLiveData<Boolean>()
fun sendRegisterUser(body: BodyRegister) = viewModelScope.launch {
loading.postValue(true)
val response = repository.registerUser(body)
if (response.isSuccessful) {
registerUser.postValue(response.body())
}
loading.postValue(false)
}
} | 0 | Kotlin | 0 | 0 | ee4e2e8b965604b5a825218b6239f0255e9923b2 | 976 | MovieApp_G | Apache License 2.0 |
presentation/src/main/java/com/whatthefar/presentation/ui/main/di/MainActivityAbstractModule.kt | WhatTheFar | 143,834,013 | false | null | package com.whatthefar.presentation.ui.main.di
import com.whatthefar.presentation.ui.main.MainContract
import com.whatthefar.presentation.ui.main.MainPresenter
import dagger.Binds
import dagger.Module
@Module
abstract class MainActivityAbstractModule {
@Binds
internal abstract fun bindMainPresenter(mainPresenter: MainPresenter): MainContract.Presenter
} | 1 | Kotlin | 3 | 13 | 2c46f1263885b69f6689d2d9be653440e1a2341e | 366 | android-clean-mvp-vm | Apache License 2.0 |
webui/src/main/kotlin/com/simiacryptus/skyenet/apps/general/CmdPatchApp.kt | SimiaCryptus | 619,329,127 | false | {"Kotlin": 858336, "JavaScript": 60406, "SCSS": 31588, "HTML": 8067, "Scala": 5538, "Java": 2053} | package com.simiacryptus.skyenet.apps.general
import com.simiacryptus.diff.FileValidationUtils
import com.simiacryptus.jopenai.ChatClient
import com.simiacryptus.jopenai.models.OpenAITextModel
import com.simiacryptus.skyenet.core.platform.Session
import com.simiacryptus.skyenet.set
import com.simiacryptus.skyenet.webui.session.SessionTask
import org.slf4j.LoggerFactory
import java.io.File
import java.nio.file.Path
import java.util.concurrent.TimeUnit
class CmdPatchApp(
root: Path,
session: Session,
settings: Settings,
api: ChatClient,
val files: Array<out File>?,
model: OpenAITextModel
) : PatchApp(root.toFile(), session, settings, api, model) {
companion object {
private val log = LoggerFactory.getLogger(CmdPatchApp::class.java)
val String.htmlEscape: String
get() = this.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """)
.replace("'", "'")
fun truncate(output: String, kb: Int = 32): String {
var returnVal = output
if (returnVal.length > 1024 * 2 * kb) {
returnVal = returnVal.substring(0, 1024 * kb) +
"\n\n... Output truncated ...\n\n" +
returnVal.substring(returnVal.length - 1024 * kb)
}
return returnVal
}
}
private fun getFiles(
virtualFiles: Array<out File>?
): MutableSet<Path> {
val codeFiles = mutableSetOf<Path>() // Set to avoid duplicates
virtualFiles?.forEach { file ->
if (file.isDirectory) {
if (file.name.startsWith(".")) return@forEach
if (FileValidationUtils.isGitignore(file.toPath())) return@forEach
codeFiles.addAll(getFiles(file.listFiles()))
} else {
codeFiles.add((file.toPath()))
}
}
return codeFiles
}
override fun codeFiles() = getFiles(files)
.filter { it.toFile().length() < 1024 * 1024 / 2 } // Limit to 0.5MB
.map { root.toPath().relativize(it) ?: it }.toSet()
override fun codeSummary(paths: List<Path>): String = paths
.filter {
val file = settings.workingDirectory?.resolve(it.toFile())
file?.exists() == true && !file.isDirectory && file.length() < (256 * 1024)
}
.joinToString("\n\n") { path ->
try {
"""
|# ${path}
|${tripleTilde}${path.toString().split('.').lastOrNull()}
|${settings.workingDirectory?.resolve(path.toFile())?.readText(Charsets.UTF_8)}
|${tripleTilde}
""".trimMargin()
} catch (e: Exception) {
log.warn("Error reading file", e)
"Error reading file `${path}` - ${e.message}"
}
}
override fun projectSummary(): String {
val codeFiles = codeFiles()
val str = codeFiles
.asSequence()
.filter { settings.workingDirectory?.toPath()?.resolve(it)?.toFile()?.exists() == true }
.distinct().sorted()
.joinToString("\n") { path ->
"* ${path} - ${
settings.workingDirectory?.toPath()?.resolve(path)?.toFile()?.length() ?: "?"
} bytes".trim()
}
return str
}
override fun output(task: SessionTask): OutputResult = run {
val command =
listOf(settings.executable.absolutePath) + settings.arguments.split(" ").filter(String::isNotBlank)
val processBuilder = ProcessBuilder(command).directory(settings.workingDirectory)
val buffer = StringBuilder()
val taskOutput = task.add("")
val process = processBuilder.start()
Thread {
var lastUpdate = 0L
process.errorStream.bufferedReader().use { reader ->
var line: String?
while (reader.readLine().also { line = it } != null) {
buffer.append(line).append("\n")
if (lastUpdate + TimeUnit.SECONDS.toMillis(15) < System.currentTimeMillis()) {
taskOutput?.set("<pre>\n${truncate(buffer.toString()).htmlEscape}\n</pre>")
task.append("", true)
lastUpdate = System.currentTimeMillis()
}
}
task.append("", true)
}
}.start()
process.inputStream.bufferedReader().use { reader ->
var line: String?
var lastUpdate = 0L
while (reader.readLine().also { line = it } != null) {
buffer.append(line).append("\n")
if (lastUpdate + TimeUnit.SECONDS.toMillis(15) < System.currentTimeMillis()) {
taskOutput?.set("<pre>\n${outputString(buffer).htmlEscape}\n</pre>")
task.append("", true)
lastUpdate = System.currentTimeMillis()
}
}
task.append("", true)
}
task.append("", false)
if (!process.waitFor(5, TimeUnit.MINUTES)) {
process.destroy()
throw RuntimeException("Process timed out")
}
val exitCode = process.exitValue()
var output = outputString(buffer)
taskOutput?.clear()
OutputResult(exitCode, output)
}
private fun outputString(buffer: StringBuilder): String {
var output = buffer.toString()
output = output.replace(Regex("\\x1B\\[[0-?]*[ -/]*[@-~]"), "") // Remove terminal escape codes
output = truncate(output)
return output
}
override fun searchFiles(searchStrings: List<String>): Set<Path> {
return searchStrings.flatMap { searchString ->
FileValidationUtils.filteredWalk(settings.workingDirectory!!) { !FileValidationUtils.isGitignore(it.toPath()) }
.filter { FileValidationUtils.isLLMIncludable(it) }
.filter { it.readText().contains(searchString, ignoreCase = true) }
.map { it.toPath() }
.toList()
}.toSet()
}
} | 1 | Kotlin | 0 | 1 | cb480aea02ea5297cadd19a5524a2d92c0ba5fd4 | 6,263 | SkyeNet | Apache License 2.0 |
alligator/src/main/java/me/aartikov/alligator/helpers/FragmentStack.kt | aartikov | 82,198,753 | false | {"Gradle": 12, "Java Properties": 2, "YAML": 1, "Shell": 1, "Text": 1, "Ignore List": 11, "Batchfile": 1, "Markdown": 1, "Proguard": 9, "Java": 101, "XML": 116, "Kotlin": 79} | package me.aartikov.alligator.helpers
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import me.aartikov.alligator.animations.TransitionAnimation
/**
* Custom implementation of a fragment backstack with flexible animation control.
*/
class FragmentStack(fragmentManager: FragmentManager, containerId: Int) {
private val mFragmentManager: FragmentManager
private val mContainerId: Int
init {
require(containerId > 0) { "ContainerId is not set." }
mFragmentManager = fragmentManager
mContainerId = containerId
}
val fragments: List<Fragment>
get() {
val result: MutableList<Fragment> = ArrayList()
var index = 0
while (true) {
val tag = getFragmentTag(index)
val fragment = mFragmentManager.findFragmentByTag(tag) ?: break
if (!fragment.isRemoving) {
result.add(fragment)
}
index++
}
return result
}
val fragmentCount get() = fragments.size
val currentFragment get() = mFragmentManager.findFragmentById(mContainerId)
fun pop(animation: TransitionAnimation) {
val fragments = fragments
val count = fragments.size
check(count != 0) { "Can't pop fragment when stack is empty." }
val currentFragment = fragments[count - 1]
val previousFragment = if (count > 1) fragments[count - 2] else null
val transaction = mFragmentManager.beginTransaction()
if (previousFragment != null) {
animation.applyBeforeFragmentTransactionExecuted(
transaction,
previousFragment,
currentFragment
)
}
transaction.remove(currentFragment)
if (previousFragment != null) {
transaction.attach(previousFragment)
}
transaction.commitNow()
if (previousFragment != null) {
animation.applyAfterFragmentTransactionExecuted(previousFragment, currentFragment)
}
}
fun popUntil(fragment: Fragment, animation: TransitionAnimation) {
val fragments = fragments
val count = fragments.size
val index = fragments.indexOf(fragment)
require(index != -1) { "Fragment is not found." }
if (index == count - 1) {
return // nothing to do
}
val transaction = mFragmentManager.beginTransaction()
for (i in index + 1 until count) {
if (i == count - 1) {
animation.applyBeforeFragmentTransactionExecuted(
transaction,
fragment,
fragments[i]
)
}
transaction.remove(fragments[i])
}
transaction.attach(fragment)
transaction.commitNow()
animation.applyAfterFragmentTransactionExecuted(fragment, fragments[count - 1])
}
fun push(fragment: Fragment, animation: TransitionAnimation) {
val currentFragment = this.currentFragment
val transaction = mFragmentManager.beginTransaction()
if (currentFragment != null) {
animation.applyBeforeFragmentTransactionExecuted(transaction, fragment, currentFragment)
transaction.detach(currentFragment)
}
val index = this.fragmentCount
transaction.add(mContainerId, fragment, getFragmentTag(index))
transaction.commitNow()
if (currentFragment != null) {
animation.applyAfterFragmentTransactionExecuted(fragment, currentFragment)
}
}
fun replace(fragment: Fragment, animation: TransitionAnimation) {
val currentFragment = this.currentFragment
val transaction = mFragmentManager.beginTransaction()
if (currentFragment != null) {
animation.applyBeforeFragmentTransactionExecuted(transaction, fragment, currentFragment)
transaction.remove(currentFragment)
}
val count = this.fragmentCount
val index = if (count == 0) 0 else count - 1
transaction.add(mContainerId, fragment, getFragmentTag(index))
transaction.commitNow()
if (currentFragment != null) {
animation.applyAfterFragmentTransactionExecuted(fragment, currentFragment)
}
}
fun reset(fragment: Fragment, animation: TransitionAnimation) {
val fragments = fragments
val count = fragments.size
val transaction = mFragmentManager.beginTransaction()
for (i in 0 until count) {
if (i == count - 1) {
animation.applyBeforeFragmentTransactionExecuted(
transaction,
fragment,
fragments[i]
)
}
transaction.remove(fragments[i])
}
transaction.add(mContainerId, fragment, getFragmentTag(0))
transaction.commitNow()
if (count > 0) {
animation.applyAfterFragmentTransactionExecuted(fragment, fragments[count - 1])
}
}
private fun getFragmentTag(index: Int): String {
return TAG_PREFIX + mContainerId + "_" + index
}
companion object {
private const val TAG_PREFIX = "me.aartikov.alligator.FRAGMENT_STACK_TAG_"
}
} | 3 | Java | 18 | 298 | 1081210a0bd69cdd7ddd021e47cbe4b3586adde8 | 5,352 | Alligator | MIT License |
apache-avro/apache-avro-producer-v2/src/main/kotlin/com/example/apacheavro/EmployeeService.kt | luramarchanjo | 241,752,765 | false | {"Java": 7994, "Kotlin": 7915} | package com.example.apacheavro
import com.example.apacheavro.domain.Employee
import org.slf4j.LoggerFactory
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import java.util.*
@Service
class EmployeeService(val kafkaTemplate: KafkaTemplate<String, Employee>) {
private final val log = LoggerFactory.getLogger(this::class.java)
@Scheduled(initialDelay = 1000, fixedDelay = 3000)
fun producer() {
val employee = Employee()
employee.setId(Random().nextInt())
employee.setFirstName(UUID.randomUUID().toString());
employee.setLastName(UUID.randomUUID().toString())
employee.setAge(Random().nextInt())
log.info("Creating $employee")
kafkaTemplate.sendDefault(employee)
}
} | 1 | null | 1 | 1 | 70a1d1838e4ec8a756956a32c559fcb60ca5e533 | 852 | poc-kafka | Apache License 2.0 |
app/src/main/java/cc/femto/kommon/ui/transitions/Pop.kt | hpost | 78,051,620 | false | {"Kotlin": 77712} | package cc.femto.kommon.ui.transitions
import android.animation.Animator
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.content.Context
import android.transition.TransitionValues
import android.transition.Visibility
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
/**
* A transition that animates the alpha, scale X & Y of a view simultaneously.
* See https://github.com/nickbutcher/plaid/blob/master/app/src/main/java/io/plaidapp/ui/transitions/Pop.java
*/
class Pop(context: Context, attrs: AttributeSet) : Visibility(context, attrs) {
override fun onAppear(sceneRoot: ViewGroup, view: View, startValues: TransitionValues,
endValues: TransitionValues): Animator {
view.alpha = 0f
view.scaleX = 0f
view.scaleY = 0f
return ObjectAnimator.ofPropertyValuesHolder(
view,
PropertyValuesHolder.ofFloat(View.ALPHA, 1f),
PropertyValuesHolder.ofFloat(View.SCALE_X, 1f),
PropertyValuesHolder.ofFloat(View.SCALE_Y, 1f))
}
override fun onDisappear(sceneRoot: ViewGroup, view: View, startValues: TransitionValues,
endValues: TransitionValues): Animator {
return ObjectAnimator.ofPropertyValuesHolder(
view,
PropertyValuesHolder.ofFloat(View.ALPHA, 0f),
PropertyValuesHolder.ofFloat(View.SCALE_X, 0f),
PropertyValuesHolder.ofFloat(View.SCALE_Y, 0f))
}
} | 0 | Kotlin | 0 | 0 | e2c145ec0c56aa3749f574b17db9fb5d075cbc5b | 1,580 | kommon | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/js/intl/Granularity.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6272741} | // Automatically generated - do not modify!
package js.intl
import seskar.js.JsValue
sealed external interface Granularity {
companion object {
@JsValue("grapheme")
val grapheme: Granularity
@JsValue("word")
val word: Granularity
@JsValue("sentence")
val sentence: Granularity
}
}
| 0 | Kotlin | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 342 | types-kotlin | Apache License 2.0 |
app/src/main/java/org/aparoksha/app18/ca/adapters/ScratchCardsAdapter.kt | sashank27 | 110,108,431 | false | null | package org.aparoksha.app18.ca.adapters
import android.content.Context
import android.os.Bundle
import android.support.v4.app.FragmentTransaction
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.TextView
import com.bumptech.glide.Glide
import com.firebase.ui.database.FirebaseRecyclerAdapter
import com.firebase.ui.database.FirebaseRecyclerOptions
import com.google.firebase.database.DatabaseReference
import kotlinx.android.synthetic.main.cards_container.view.*
import org.aparoksha.app18.ca.R
import org.aparoksha.app18.ca.fragments.NewCardFragment
import org.aparoksha.app18.ca.models.Card
/**
* Created by sashank on 13/12/17.
*/
class ScratchCardsAdapter(options: FirebaseRecyclerOptions<Card>,
val context: Context,
val noCardsView: TextView)
: FirebaseRecyclerAdapter<Card, ScratchCardsAdapter.ScratchCardsViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ScratchCardsViewHolder {
return ScratchCardsViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.cards_container, parent, false))
}
override fun onBindViewHolder(holder: ScratchCardsViewHolder, position: Int, model: Card) {
holder.bindView(model, context, this.getRef(position))
}
class ScratchCardsViewHolder(private var mView: View) : RecyclerView.ViewHolder(mView) {
fun bindView(card: Card, mContext: Context, ref: DatabaseReference) {
if (card.revealed) {
Glide.with(mContext)
.load(if (card.value > 0) R.drawable.ic_trophy else R.drawable.ic_sad)
.into(mView.check)
mView.value.text = "You earned " + card.value.toString() + " points."
mView.setOnClickListener(null)
} else {
Glide.with(mContext)
.load(R.drawable.ic_question)
.into(mView.check)
mView.value.text = "Not Yet Revealed"
mView.setOnClickListener {
val ft = (mContext as AppCompatActivity).supportFragmentManager.beginTransaction()
mContext.window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
val bundle = Bundle()
bundle.putString("reference", ref.key)
bundle.putString("points", card.value.toString())
val frag = NewCardFragment()
frag.arguments = bundle
ft.add(R.id.frame, frag)
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
ft.commit()
}
}
}
}
override fun onDataChanged() {
super.onDataChanged()
noCardsView.visibility = if (itemCount == 0) View.VISIBLE else View.GONE
}
} | 0 | Kotlin | 0 | 2 | 08d245e147ed73d2b31b97e4bd78523c3e790afd | 3,114 | Aparoksha18-CA | MIT License |
src/main/kotlin/no/nav/hm/grunndata/db/indexer/SearchDoc.kt | navikt | 555,213,385 | false | null | package no.nav.hm.grunndata.db.indexer
interface SearchDoc {
val id: String
} | 0 | Kotlin | 0 | 1 | 72d24067e6263f57ed34f8a85bcdf1ac6cab4c93 | 82 | hm-grunndata-db | MIT License |
app/src/main/java/com/sxiaozhi/fragment/data/OrderData.kt | imifeng | 727,622,187 | false | {"Kotlin": 79917} | package com.sxiaozhi.fragment.data
data class OrderBean(
val page: Int?,
val totalPage: Int?,
val orders: List<OrderInfo>?,
val agent: AgentBean?
)
data class OrderInfo(
val id: String,
val amount: String?,
val username: String?,
val platform: String?,
val time: String?,
val mobile: String?,
val refer: String?,
val create_time: String?,
) | 0 | Kotlin | 0 | 1 | 55867cbbb59da53135a1b73c4c3548e10f589a39 | 391 | MVVM-Project-Navigation | Apache License 2.0 |
app/src/main/java/io/github/nosix/android/compose/example/composable/material3/components/IconButton.kt | nosix | 725,363,839 | false | {"Kotlin": 127844} | package io.github.nosix.android.compose.example.composable.material3.components
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.FilledIconToggleButton
import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.FilledTonalIconToggleButton
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.OutlinedIconButton
import androidx.compose.material3.OutlinedIconToggleButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.tooling.preview.Preview
import io.github.nosix.android.compose.example.ui.theme.MyTheme
import io.github.nosix.android.compose.example.utils.PrimaryIcon
@Preview(showBackground = true)
@Composable
fun IconButtonDemo() {
MyTheme {
Column {
Text("IconButton")
IconButton(
onClick = {},
enabled = true,
colors = IconButtonDefaults.iconButtonColors(),
interactionSource = remember { MutableInteractionSource() }
) {
PrimaryIcon()
}
Text("FilledIconButton")
FilledIconButton(onClick = {}) {
PrimaryIcon()
}
Text("FilledTonalIconButton")
FilledTonalIconButton(onClick = {}) {
PrimaryIcon()
}
Text("OutlinedIconButton")
OutlinedIconButton(onClick = {}) {
PrimaryIcon()
}
Text("IconToggleButton")
var iconToggleChecked by remember { mutableStateOf(false) }
IconToggleButton(
checked = iconToggleChecked,
onCheckedChange = { iconToggleChecked = it },
enabled = true,
colors = IconButtonDefaults.iconToggleButtonColors(),
interactionSource = remember { MutableInteractionSource() }
) {
PrimaryIcon()
}
Text("FilledIconToggleButton")
FilledIconToggleButton(
checked = iconToggleChecked,
onCheckedChange = { iconToggleChecked = it }
) {
PrimaryIcon()
}
Text("FilledTonalIconToggleButton")
FilledTonalIconToggleButton(
checked = iconToggleChecked,
onCheckedChange = { iconToggleChecked = it }
) {
PrimaryIcon()
}
Text("OutlinedIconToggleButton")
OutlinedIconToggleButton(
checked = iconToggleChecked,
onCheckedChange = { iconToggleChecked = it }
) {
PrimaryIcon()
}
}
}
}
| 0 | Kotlin | 0 | 0 | c24a5673e8b8e427c177d3fc9541b68bf34de5c4 | 3,187 | android-compose-example | Apache License 2.0 |
components/src/test/java/uk/gov/android/ui/components/m3/ButtonsM3Test.kt | govuk-one-login | 687,488,193 | false | {"Kotlin": 462748, "Shell": 5415} | package uk.gov.android.ui.components.m3
import androidx.compose.runtime.Composable
import com.android.resources.NightMode
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import uk.gov.android.ui.components.m3.buttons.ButtonParameters
import uk.gov.android.ui.components.m3.buttons.ButtonProvider
import uk.gov.android.ui.components.m3.buttons.GdsButton
@RunWith(Parameterized::class)
class ButtonsM3Test(
private val parameters: Pair<ButtonParameters, NightMode>
) : BaseScreenshotTest(parameters.second) {
override val generateComposeLayout: @Composable () -> Unit = {
GdsButton(buttonParameters = parameters.first)
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{index}: GdsButtonM3")
fun values(): List<Pair<ButtonParameters, NightMode>> {
val result: MutableList<Pair<ButtonParameters, NightMode>> = mutableListOf()
ButtonProvider().values.forEach(applyNightMode(result))
return result
}
}
}
| 2 | Kotlin | 1 | 5 | 004d9d11a82660a7ae53b8ea013f3081d7c48398 | 1,039 | mobile-android-ui | MIT License |
app/src/main/java/com/onurbarman/scorpcaseapp/util/RandomUtils.kt | onurbarman | 470,106,843 | false | null | package com.onurbarman.scorpcaseapp.util
import kotlin.random.Random
object RandomUtils {
fun generateRandomInt(range: ClosedRange<Int>): Int = Random.nextInt(range.start, range.endInclusive)
fun generateRandomDouble(range: ClosedRange<Double>): Double = Random.nextDouble(range.start, range.endInclusive)
fun roll(probability: Double): Boolean {
val random = Random.nextDouble(0.0, 1.0)
return random <= probability
}
} | 0 | Kotlin | 0 | 0 | 855c017b3b0ef51399da8840a4d56118fbff059f | 457 | ScorpCaseApp | Apache License 2.0 |
javalin/src/main/java/io/javalin/compression/CompressionType.kt | javalin | 87,012,358 | false | null | package io.javalin.compression
enum class CompressionType(val typeName: String, val extension: String) {
GZIP("gzip", ".gz"),
BR("br", ".br"),
NONE("", "");
}
| 24 | null | 570 | 7,573 | 6e53b6237dc54fcb05b7a8531941bcb60a17e687 | 172 | javalin | Apache License 2.0 |
app/src/main/java/com/spin/id/ui/webview/webview/WebAppHeaderConstant.kt | RifqiFadhell | 501,564,017 | false | null | package com.spin.id.ui.webview
class WebAppHeaderConstant {
companion object {
const val DEFAULT_TOKEN_KEY = "token"
const val DEFAULT_AUTHORIZATION_KEY = "Authorization"
const val DEFAULT_LIST_PPOB_HEADER_KEY = DEFAULT_TOKEN_KEY
const val DEFAULT_WHOLESALE_HEADER_KEY = DEFAULT_TOKEN_KEY
const val DEFAULT_DEPOSIT_HEADER_KEY = DEFAULT_TOKEN_KEY
const val DEFAULT_FINANCING_HEADER_KEY = DEFAULT_TOKEN_KEY
const val DEFAULT_NETWORK_HEADER_KEY = DEFAULT_TOKEN_KEY
const val DEFAULT_HISTORY_TRANSACTION_HEADER_KEY = DEFAULT_TOKEN_KEY
const val DEFAULT_KAPITAL_BOOST_HEADER_KEY = DEFAULT_AUTHORIZATION_KEY
}
} | 0 | Kotlin | 0 | 0 | ac0082e9f8ce71f3e17c758e59d925bfed2ec753 | 650 | SPIN | Apache License 2.0 |
interpreter/src/main/kotlin/io/github/apl_cornell/viaduct/protocols/Synchronization.kt | apl-cornell | 169,159,978 | false | null | package io.github.apl_cornell.viaduct.protocols
import io.github.apl_cornell.viaduct.security.Label
import io.github.apl_cornell.viaduct.syntax.Host
import io.github.apl_cornell.viaduct.syntax.HostTrustConfiguration
import io.github.apl_cornell.viaduct.syntax.Protocol
import io.github.apl_cornell.viaduct.syntax.ProtocolName
import io.github.apl_cornell.viaduct.syntax.values.HostSetValue
import io.github.apl_cornell.viaduct.syntax.values.Value
/**
* Protocol used to synchronize hosts.
* Used exclusively by the backend, not meant to be used for selection!
*/
class Synchronization(hosts: Set<Host>) : Protocol() {
companion object {
val protocolName = ProtocolName("Synchronization")
}
private val participants: HostSetValue = HostSetValue(hosts)
override val protocolName: ProtocolName
get() = Synchronization.protocolName
override val arguments: Map<String, Value>
get() = mapOf("hosts" to participants)
override fun authority(hostTrustConfiguration: HostTrustConfiguration): Label =
throw Error("Synchronization protocol has no authority label")
}
| 26 | Kotlin | 5 | 15 | e681f77562fdafa93b8fb5b929d96aca08affc1a | 1,120 | viaduct | MIT License |
interpreter/src/main/kotlin/io/github/apl_cornell/viaduct/protocols/Synchronization.kt | apl-cornell | 169,159,978 | false | null | package io.github.apl_cornell.viaduct.protocols
import io.github.apl_cornell.viaduct.security.Label
import io.github.apl_cornell.viaduct.syntax.Host
import io.github.apl_cornell.viaduct.syntax.HostTrustConfiguration
import io.github.apl_cornell.viaduct.syntax.Protocol
import io.github.apl_cornell.viaduct.syntax.ProtocolName
import io.github.apl_cornell.viaduct.syntax.values.HostSetValue
import io.github.apl_cornell.viaduct.syntax.values.Value
/**
* Protocol used to synchronize hosts.
* Used exclusively by the backend, not meant to be used for selection!
*/
class Synchronization(hosts: Set<Host>) : Protocol() {
companion object {
val protocolName = ProtocolName("Synchronization")
}
private val participants: HostSetValue = HostSetValue(hosts)
override val protocolName: ProtocolName
get() = Synchronization.protocolName
override val arguments: Map<String, Value>
get() = mapOf("hosts" to participants)
override fun authority(hostTrustConfiguration: HostTrustConfiguration): Label =
throw Error("Synchronization protocol has no authority label")
}
| 26 | Kotlin | 5 | 15 | e681f77562fdafa93b8fb5b929d96aca08affc1a | 1,120 | viaduct | MIT License |
src/main/kotlin/me/devoxin/jukebot/audio/sources/delegate/DelegateHandler.kt | devoxin | 104,263,117 | false | {"Kotlin": 284892, "Java": 40059} | package me.devoxin.jukebot.audio.sources.delegate
import com.sedmelluq.discord.lavaplayer.track.AudioTrack
class DelegateHandler(private val delegates: Set<DelegateSource>) {
fun findByIsrc(isrc: String, prefer: Class<out DelegateSource>?, vararg excluding: String): AudioTrack? {
return getDelegates(prefer)
.filter { it.name !in excluding }
.map { it.runCatching { findByIsrc(isrc) }.getOrNull() }
.firstOrNull()
}
fun findBySearch(query: String, original: AudioTrack, prefer: Class<out DelegateSource>?, vararg excluding: String): AudioTrack? {
return getDelegates(prefer)
.filter { it.name !in excluding }
.map { it.runCatching { findBySearch(query, original) }.getOrNull() }
.firstOrNull()
}
private fun getDelegates(prefer: Class<out DelegateSource>?): Sequence<DelegateSource> = sequence {
val preferredDelegate = prefer?.let { p -> delegates.firstOrNull { p.isAssignableFrom(it::class.java) } }
if (preferredDelegate != null) {
yield(preferredDelegate)
}
for (delegate in delegates) {
if (prefer == null || delegate::class.java.isAssignableFrom(prefer)) {
yield(delegate)
}
}
}
}
| 0 | Kotlin | 11 | 39 | 7754d73038ecc1657ff858a11fb2ef960b607a11 | 1,298 | JukeBot | Apache License 2.0 |
app/src/main/java/me/blog/korn123/easydiary/helper/TransitionHelper.kt | Larnicone | 233,504,978 | true | {"Kotlin": 643036} | package me.blog.korn123.easydiary.helper
import android.app.Activity
import android.content.Intent
import androidx.fragment.app.FragmentActivity
import me.blog.korn123.easydiary.R
/**
* Created by <NAME> on 2018-01-02.
*/
class TransitionHelper {
companion object {
const val DEFAULT = 0
const val BOTTOM_TO_TOP = 1
const val TOP_TO_BOTTOM = 2
fun startActivityWithTransition(activity: Activity?, intent: Intent, type: Int = DEFAULT) {
activity?.run {
startActivity(intent)
when (type) {
DEFAULT -> overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
BOTTOM_TO_TOP -> overridePendingTransition(R.anim.slide_in_up, R.anim.stay)
}
}
}
fun finishActivityWithTransition(activity: Activity?, type: Int = DEFAULT) {
activity?.run {
finish()
when (type) {
DEFAULT -> overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
TOP_TO_BOTTOM -> overridePendingTransition(R.anim.stay, R.anim.slide_in_down)
}
}
}
}
} | 0 | null | 0 | 0 | aa553bc8d2c7842984d89026b67a7560c2438770 | 1,241 | aaf-easydiary | Apache License 2.0 |
rabbit-monitor/src/main/java/com/susion/rabbit/monitor/instance/RabbitExceptionMonitor.kt | SusionSuc | 210,506,798 | false | null | package com.susion.rabbit.monitor.instance
import android.content.Context
import android.os.Looper
import com.susion.rabbit.base.RabbitLog
import com.susion.rabbit.monitor.RabbitMonitor
import com.susion.rabbit.base.RabbitMonitorProtocol
import com.susion.rabbit.base.common.RabbitUtils
import com.susion.rabbit.base.common.toastInThread
import com.susion.rabbit.base.entities.RabbitExceptionInfo
import com.susion.rabbit.storage.RabbitDbStorageManager
import java.io.PrintWriter
import java.io.StringWriter
/**
* susionwang at 2019-12-12
*
* 1. 通过 [Thread.setDefaultUncaughtExceptionHandler] 捕获Java层异常
*
*/
internal class RabbitExceptionMonitor(override var isOpen: Boolean = false) :
RabbitMonitorProtocol {
override fun open(context: Context) {
val defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
saveCrash(throwable, thread, defaultExceptionHandler)
}
isOpen = true
}
override fun close() {
isOpen = false
}
override fun getMonitorInfo() = RabbitMonitorProtocol.EXCEPTION
fun saveCrash(
e: Throwable,
thread: Thread,
defaultExceptionHandler: Thread.UncaughtExceptionHandler? = null
) {
if (!isOpen) return
toastInThread("发生异常! 日志已保存", RabbitMonitor.application)
Thread.sleep(1000) // 把toast给弹出来
val exceptionInfo = translateThrowableToExceptionInfo(e, Thread.currentThread().name)
RabbitDbStorageManager.saveSync(exceptionInfo)
//main thead 下崩溃
if (RabbitUtils.isMainThread(thread.id)) {
Thread.sleep(1500)
defaultExceptionHandler?.uncaughtException(thread, e)
}
}
private fun translateThrowableToExceptionInfo(
e: Throwable,
currentThread: String
): RabbitExceptionInfo {
val exceptionInfo = RabbitExceptionInfo()
exceptionInfo.apply {
crashTraceStr = RabbitLog.getStackTraceString(e)
exceptionName = e.javaClass.name
simpleMessage = e.message ?: ""
threadName = currentThread
time = System.currentTimeMillis()
pageName = RabbitMonitor.getCurrentPage()
}
return exceptionInfo
}
} | 9 | null | 146 | 998 | f1d1faf9f69b4ec162ae2215e9338dd1d7bdc893 | 2,317 | rabbit-client | MIT License |
feature/user/src/main/java/st/slex/csplashscreen/feature/user/ui/store/UserStore.kt | stslex | 413,161,718 | false | {"Kotlin": 324470, "Ruby": 1145} | package st.slex.csplashscreen.feature.user.ui.presenter
import androidx.compose.runtime.Stable
import androidx.paging.PagingData
import kotlinx.coroutines.flow.StateFlow
import st.slex.csplashscreen.core.collection.ui.model.CollectionModel
import st.slex.csplashscreen.core.navigation.AppArguments
import st.slex.csplashscreen.core.network.model.ui.user.UserModel
import st.slex.csplashscreen.core.photos.ui.model.PhotoModel
import st.slex.csplashscreen.core.ui.mvi.Store
interface UserStore {
@Stable
data class State(
val user: UserModel?,
val photos: (String) -> StateFlow<PagingData<PhotoModel>>,
val likes: (String) -> StateFlow<PagingData<PhotoModel>>,
val collections: (String) -> StateFlow<PagingData<CollectionModel>>
) : Store.State
@Stable
sealed interface Event : Store.Event
sealed interface Navigation : Store.Navigation {
data object PopBack : Navigation
data class User(
val username: String
) : Navigation
data class Image(
val uuid: String
) : Navigation
data class Collection(
val uuid: String
) : Navigation
}
@Stable
sealed interface Action : Store.Action {
data class Init(
val args: AppArguments.UserScreen
) : Action
data object OnBackButtonClick : Action
data class OnUserClick(
val username: String
) : Action
data class OnImageClick(
val uuid: String
) : Action
data class OnCollectionClick(
val uuid: String
) : Action
}
}
| 3 | Kotlin | 0 | 3 | 3bcac8199765dcac567e39836c53be89a9765843 | 1,651 | CSplashScreen | Apache License 2.0 |
examples/webflux/src/test/kotlin/example/spring/boot/webflux/ApplicationAcceptanceTest.kt | test-automation-in-practice | 506,693,260 | false | null | package example.spring.boot.webflux
import io.github.logrecorder.api.LogRecord
import io.github.logrecorder.assertion.LogRecordAssertion.Companion.assertThat
import io.github.logrecorder.assertion.containsExactly
import io.github.logrecorder.logback.junit5.RecordLoggers
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT
import org.springframework.http.HttpHeaders.AUTHORIZATION
import org.springframework.http.MediaType.APPLICATION_JSON
import org.springframework.test.web.reactive.server.WebTestClient
import org.zalando.logbook.Logbook
@SpringBootTest(webEnvironment = RANDOM_PORT)
internal class ApplicationAcceptanceTest(
@Autowired val webTestClient: WebTestClient
) {
@Test
fun `creating a book responds with resource representation including self link`() {
webTestClient.post()
.uri("/default-api/books")
.contentType(APPLICATION_JSON)
.bodyValue("""{ "title": "Clean Code", "isbn": "9780132350884" }""")
.exchange()
.expectStatus().isCreated
.expectHeader().contentType(APPLICATION_JSON)
.expectBody()
.jsonPath("id").exists()
.jsonPath("title").isEqualTo("Clean Code")
.jsonPath("isbn").isEqualTo("9780132350884")
}
@Test
@RecordLoggers(Logbook::class)
fun `request and response are logged with obfuscated authorization header`(log: LogRecord) {
webTestClient.post()
.uri("/default-api/books")
.header(AUTHORIZATION, "some-token")
.contentType(APPLICATION_JSON)
.bodyValue("""{ "title": "Clean Code", "isbn": "9780132350884" }""")
.exchange()
assertThat(log) containsExactly {
trace(startsWith("Incoming Request:"), contains("authorization: XXX"))
trace(startsWith("Outgoing Response:"))
}
}
}
| 0 | null | 0 | 54 | 5a4b1fc0cc693a1af50a88057d04516a1303afa9 | 2,070 | cnt-spring-boot | Apache License 2.0 |
craft/craft-api/src/main/kotlin/me/ddevil/shiroi/craft/plugin/PluginSettings.kt | BrunoSilvaFreire | 88,535,533 | false | {"Gradle": 15, "Markdown": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Kotlin": 187, "INI": 1, "Java": 1, "YAML": 3} | package me.ddevil.shiroi.craft.plugin
annotation class PluginSettings(
val primaryAcronym: String,
val aliases: Array<String>,
val ignoreMasterConfig: Boolean = false
) | 2 | null | 1 | 1 | 5060ef1b811a3fe5d86e2b3498f6814239dce6d2 | 193 | ShiroiFramework | Do What The F*ck You Want To Public License |
examples/src/main/kotlin/examples/groups/NestedGroups.kt | hiperbou | 77,711,558 | false | {"Kotlin": 456816, "HTML": 335} |
package examples.groups
import Phaser.*
class NestedGroups: State() {
//var game = Phaser.Game(800, 600, Phaser.AUTO, "phaser-example", object{ var preload= preload; var create= create; var update= update })
override fun preload() {
game.load.image("ball", "assets/sprites/pangball.png")
game.load.image("arrow", "assets/sprites/asteroids_ship.png")
}
lateinit var ballsGroup:Group
lateinit var shipsGroup:Group
override fun create() {
ballsGroup = game.add.group()
shipsGroup = game.add.group()
for(i in 0..20-1)
{
// Create some randomly placed sprites in both Groups
ballsGroup.create(game.rnd.integerInRange(0, 128), game.world.randomY, "ball")
shipsGroup.create(game.rnd.integerInRange(0, 128), game.world.randomY, "arrow")
}
// Now make the ships group a child of the balls group - so anything that happens to the balls group
// will happen to the ships group too
ballsGroup.add(shipsGroup)
}
override fun update() {
ballsGroup.x += 0.1
// Because shipsGroup is a child of ballsGroup it has already been moved 0.1px by the line above
// So the following line of code will make it appear to move twice as fast as ballsGroup
shipsGroup.x += 0.1
}
} | 2 | Kotlin | 11 | 55 | 18d247ecf44c32f5aca0560dce7727c10dfe196a | 1,242 | kotlin-phaser | MIT License |
app/src/main/java/com/nutrition/balanceme/data/local/Converters.kt | DatTrannn | 521,896,551 | false | null | package com.nutrition.balanceme.data.local
import androidx.room.TypeConverter
import com.nutrition.balanceme.domain.models.Item
import com.nutrition.balanceme.domain.models.Profile
import com.nutrition.balanceme.domain.models.Recipe
import kotlinx.serialization.*
import kotlinx.serialization.json.Json
@ExperimentalSerializationApi
class Converters {
@TypeConverter
fun recipesFromJson(json: String): List<Recipe> = Json.decodeFromString(json)
@TypeConverter
fun recipesToJson(recipes: List<Recipe>): String = Json.encodeToString(recipes)
@TypeConverter
fun profileToJson(profile: Profile): String = Json.encodeToString(profile)
@TypeConverter
fun profileFromJson(json: String): Profile = Json.decodeFromString(json)
@TypeConverter
fun stringsToJson(strings: List<String>): String = Json.encodeToString(strings)
@TypeConverter
fun stringsFromJson(json: String): List<String> = Json.decodeFromString(json)
@TypeConverter
fun itemsToJson(items: List<Item>): String = Json.encodeToString(items)
@TypeConverter
fun itemsFromJson(json: String): List<Item> = Json.decodeFromString(json)
} | 0 | Kotlin | 0 | 0 | f51d0276b1d34e00b27b44689aedf80e1580c542 | 1,157 | BalanceMeApp | MIT License |
deliverytimes/app/src/main/java/com/streetmart/deliverytimes/model/DeliveryTime.kt | progfast | 206,754,297 | false | null | package com.streetmart.deliverytimes.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class DeliveryTime(
val postalCode: String,
val deliveryDate: String,
val isGreenDelivery: Boolean
) : Parcelable | 0 | Kotlin | 0 | 0 | 3f8112bcdafd485132de695c349caa65e6d5f113 | 255 | deliverydates | MIT License |
deliverytimes/app/src/main/java/com/streetmart/deliverytimes/model/DeliveryTime.kt | progfast | 206,754,297 | false | null | package com.streetmart.deliverytimes.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class DeliveryTime(
val postalCode: String,
val deliveryDate: String,
val isGreenDelivery: Boolean
) : Parcelable | 0 | Kotlin | 0 | 0 | 3f8112bcdafd485132de695c349caa65e6d5f113 | 255 | deliverydates | MIT License |
common/core/src/main/kotlin/ru/maksonic/beresta/common/core/security/CryptoEngine.kt | maksonic | 580,058,579 | false | {"Kotlin": 1622432} | package ru.maksonic.beresta.common.core.security
/**
* @Author maksonic on 24.10.2023
*/
interface CryptoEngine {
fun encrypt(rawData: ByteArray): ByteArray
fun decrypt(encryptedData: ByteArray): Result<ByteArray>
fun deleteEntry()
} | 0 | Kotlin | 0 | 0 | 227b0a5f6c27b0f731b1f6e81b1fe2deeaa720aa | 248 | Beresta | MIT License |
compiler/cli/cli-base/src/org/jetbrains/kotlin/cli/jvm/compiler/builder/LightClassBuilder.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2023 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.cli.jvm.compiler.builder
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.impl.compiled.ClsFileImpl
import com.intellij.psi.impl.java.stubs.PsiJavaFileStub
import com.intellij.psi.impl.java.stubs.impl.PsiJavaFileStubImpl
import org.jetbrains.kotlin.asJava.builder.ClsWrapperStubPsiFactory
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
data class CodeGenerationResult(val stub: PsiJavaFileStub, val bindingContext: BindingContext, val diagnostics: Diagnostics)
fun extraJvmDiagnosticsFromBackend(
packageFqName: FqName,
files: Collection<KtFile>,
generateClassFilter: GenerationState.GenerateClassFilter,
context: LightClassConstructionContext,
generate: (state: GenerationState, files: Collection<KtFile>) -> Unit,
): CodeGenerationResult {
val project = files.first().project
try {
val classBuilderFactory = KotlinLightClassBuilderFactory(createJavaFileStub(packageFqName, files))
val state = GenerationState.Builder(
project,
classBuilderFactory,
context.module,
context.bindingContext,
context.languageVersionSettings?.let {
CompilerConfiguration().apply {
languageVersionSettings = it
put(JVMConfigurationKeys.JVM_TARGET, context.jvmTarget)
isReadOnly = true
}
} ?: CompilerConfiguration.EMPTY,
).generateDeclaredClassFilter(generateClassFilter).wantsDiagnostics(false).build()
state.beforeCompile()
state.oldBEInitTrace(files)
generate(state, files)
val javaFileStub = classBuilderFactory.result()
return CodeGenerationResult(javaFileStub, context.bindingContext, state.collectedExtraJvmDiagnostics)
} catch (e: ProcessCanceledException) {
throw e
} catch (e: RuntimeException) {
logErrorWithOSInfo(e, packageFqName, files.firstOrNull()?.virtualFile)
throw e
}
}
private fun createJavaFileStub(packageFqName: FqName, files: Collection<KtFile>): PsiJavaFileStub {
val javaFileStub = PsiJavaFileStubImpl(packageFqName.asString(), /* compiled = */true)
javaFileStub.psiFactory = ClsWrapperStubPsiFactory.INSTANCE
val fakeFile = object : ClsFileImpl(files.first().viewProvider) {
override fun getStub() = javaFileStub
override fun getPackageName() = packageFqName.asString()
override fun isPhysical() = false
override fun getText(): String = files.singleOrNull()?.text ?: super.getText()
}
javaFileStub.psi = fakeFile
return javaFileStub
}
private fun logErrorWithOSInfo(cause: Throwable?, fqName: FqName, virtualFile: VirtualFile?) {
val path = virtualFile?.path ?: "<null>"
LOG.error(
"Could not generate LightClass for $fqName declared in $path\n" +
"System: ${SystemInfo.OS_NAME} ${SystemInfo.OS_VERSION} Java Runtime: ${SystemInfo.JAVA_RUNTIME_VERSION}",
cause,
)
}
private val LOG = Logger.getInstance(CodeGenerationResult::class.java)
| 166 | null | 5771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 3,830 | kotlin | Apache License 2.0 |
kgl-vulkan/src/jvmMain/kotlin/com/kgl/vulkan/dsls/SubpassDescriptionBuilder.kt | Dominaezzz | 164,507,082 | false | null | /**
* Copyright [2019] [<NAME>]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kgl.vulkan.dsls
import com.kgl.vulkan.enums.*
import com.kgl.vulkan.utils.*
import org.lwjgl.vulkan.*
actual class SubpassDescriptionBuilder(internal val target: VkSubpassDescription) {
actual var flags: VkFlag<SubpassDescription>?
get() = SubpassDescription.fromMultiple(target.flags())
set(value) {
target.flags(value.toVkType())
}
actual var pipelineBindPoint: PipelineBindPoint?
get() = PipelineBindPoint.from(target.pipelineBindPoint())
set(value) {
target.pipelineBindPoint(value.toVkType())
}
actual fun inputAttachments(block: AttachmentReferencesBuilder.() -> Unit) {
val targets = AttachmentReferencesBuilder().apply(block).targets
target.pInputAttachments(
targets.mapToStackArray(
VkAttachmentReference::callocStack,
::AttachmentReferenceBuilder
)
)
}
actual fun colorAttachments(block: AttachmentReferencesBuilder.() -> Unit) {
val targets = AttachmentReferencesBuilder().apply(block).targets
target.pColorAttachments(
targets.mapToStackArray(
VkAttachmentReference::callocStack,
::AttachmentReferenceBuilder
)
)
target.colorAttachmentCount(targets.size)
}
actual fun resolveAttachments(block: AttachmentReferencesBuilder.() -> Unit) {
val targets = AttachmentReferencesBuilder().apply(block).targets
target.pResolveAttachments(
targets.mapToStackArray(
VkAttachmentReference::callocStack,
::AttachmentReferenceBuilder
)
)
}
actual fun depthStencilAttachment(block: AttachmentReferenceBuilder.() -> Unit) {
val subTarget = VkAttachmentReference.callocStack()
target.pDepthStencilAttachment(subTarget)
val builder = AttachmentReferenceBuilder(subTarget)
builder.init()
builder.apply(block)
}
actual fun next(block: Next<SubpassDescriptionBuilder>.() -> Unit) {
Next(this).apply(block)
}
internal actual fun init(preserveAttachments: UIntArray?) {
target.pPreserveAttachments(preserveAttachments?.toVkType())
}
}
| 13 | Kotlin | 11 | 96 | 41155a8200602535697b872232e41cfe6f5eb20e | 2,544 | kgl | Apache License 2.0 |
app/src/main/java/dev/yash/keymanager/adapters/ViewPagerAdapter.kt | Yash-Garg | 390,400,882 | false | null | package dev.yash.keymanager.adapters
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import dev.yash.keymanager.ui.gpg.GpgFragment
import dev.yash.keymanager.ui.ssh.SshFragment
class ViewPagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
override fun getItemCount(): Int = 2
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> SshFragment()
else -> GpgFragment()
}
}
}
| 1 | Kotlin | 1 | 15 | df86860005a4cea4906e64f25578a65f1a81ae19 | 520 | KeyManager | The Unlicense |
app/src/main/java/ci/projccb/mobile/adapters/LocaliteAdapter.kt | SICADEVD | 686,088,142 | false | {"Kotlin": 1388650, "Java": 20027} | package ci.projccb.mobile.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import ci.projccb.mobile.R
import ci.projccb.mobile.adapters.LocaliteAdapter.LocaliteHolder
import ci.projccb.mobile.interfaces.RecyclerItemListener
import ci.projccb.mobile.models.LocaliteModel
import kotlinx.android.synthetic.main.localite_items_list.view.*
import kotlinx.android.synthetic.main.localite_items_list.view.imgSynced
class LocaliteAdapter(private var localites: List<LocaliteModel>?) : RecyclerView.Adapter<LocaliteHolder>() {
lateinit var localiteListener: RecyclerItemListener<LocaliteModel>
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocaliteHolder {
return LocaliteHolder(LayoutInflater.from(parent.context).inflate(R.layout.localite_items_list, parent, false))
}
override fun onBindViewHolder(holder: LocaliteHolder, position: Int) {
val localiteModel = localites!![position]
holder.localiteNomLabel.text = localiteModel.nom
holder.localiteTypeLabel.text = localiteModel.type
if (localiteModel.isSynced) holder.imgSyncedStatus.setImageResource(R.drawable.ic_sync_donz)
else holder.imgSyncedStatus.setImageResource(R.drawable.ic_sync_error)
}
override fun getItemCount() = localites?.size ?: 0
class LocaliteHolder(localiteView: View) : RecyclerView.ViewHolder(localiteView) {
val localiteNomLabel = localiteView.labelLocaliteNom
val localiteTypeLabel = localiteView.labelLocaliteType
val imgSyncedStatus = localiteView.imgSynced
}
} | 0 | Kotlin | 0 | 2 | 5c4cc79c9749bdbc80744c9809434007c4eab86c | 1,669 | ccbm | Apache License 2.0 |
fuel/src/main/kotlin/fuel/core/Manager.kt | VerachadW | 40,306,098 | true | {"Kotlin": 82514, "Java": 6904} | package fuel.core
import fuel.Fuel
import fuel.toolbox.HttpClient
import fuel.util.AndroidMainThreadExecutor
import fuel.util.build
import fuel.util.readWriteLazy
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import kotlin.properties.Delegates
/**
* Created by <NAME> on 5/14/15.
*/
public class Manager {
var client: Client by Delegates.notNull()
var basePath: String? = null
var baseHeaders: Map<String, String>? = null
var baseParams: Map<String, Any?> = mapOf()
companion object Shared {
//manager
var sharedInstance by Delegates.readWriteLazy {
build(Manager()) {
this.client = HttpClient()
}
}
//background executor
var executor by Delegates.readWriteLazy {
Executors.newCachedThreadPool { command ->
Thread {
Thread.currentThread().setPriority(Thread.NORM_PRIORITY)
command.run()
}
}
}
//callback executor
var callbackExecutor: Executor by Delegates.readWriteLazy { AndroidMainThreadExecutor() }
}
fun request(method: Method, path: String, param: Map<String, Any?>? = null): Request {
return request(build(Encoding()) {
httpMethod = method
baseUrlString = basePath
urlString = path
parameters = if (param == null) baseParams else param + baseParams
})
}
fun request(method: Method, convertible: Fuel.PathStringConvertible, param: Map<String, Any?>? = null): Request {
return request(build(Encoding()) {
httpMethod = method
baseUrlString = basePath
urlString = convertible.path
parameters = if (param == null) baseParams else param + baseParams
})
}
fun download(path: String, param: Map<String, Any?>? = null): Request {
val requestConvertible = build(Encoding()) {
httpMethod = Method.GET
baseUrlString = basePath
urlString = path
parameters = if (param == null) baseParams else param + baseParams
requestType = Request.Type.DOWNLOAD
}
val request = requestConvertible.request
return request
}
fun download(convertible: Fuel.PathStringConvertible, param: Map<String, Any?>? = null): Request {
val requestConvertible = build(Encoding()) {
httpMethod = Method.GET
baseUrlString = basePath
urlString = convertible.path
parameters = if (param == null) baseParams else param + baseParams
requestType = Request.Type.DOWNLOAD
}
val request = requestConvertible.request
return request
}
fun upload(path: String, param: Map<String, Any?>? = null): Request {
val requestConvertible = build(Encoding()) {
httpMethod = Method.POST
baseUrlString = basePath
urlString = path
parameters = if (param == null) baseParams else param + baseParams
requestType = Request.Type.UPLOAD
}
val request = requestConvertible.request
return request
}
fun upload(convertible: Fuel.PathStringConvertible, param: Map<String, Any?>? = null): Request {
val requestConvertible = build(Encoding()) {
httpMethod = Method.POST
baseUrlString = basePath
urlString = convertible.path
parameters = if (param == null) baseParams else param + baseParams
requestType = Request.Type.UPLOAD
}
val request = requestConvertible.request
return request
}
fun request(convertible: Fuel.RequestConvertible): Request {
return convertible.request
}
}
| 0 | Kotlin | 0 | 0 | 645fa04034abcd4ebe40a47a60a5037228da8d1a | 3,837 | Fuel | The Unlicense |
app/src/main/java/com/example/newsapp/base/BaseFragment.kt | zabi90 | 218,226,894 | false | null | package com.example.newsapp.base
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.example.newsapp.AndroidApp
abstract class BaseFragment : Fragment() {
val Fragment.app: AndroidApp
get() = activity?.application as AndroidApp
val component by lazy {
app.appComponent
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
inject()
}
abstract fun inject()
} | 0 | null | 3 | 1 | bc287ae9ae357f0b6a9dde6f2dc0223740d9614d | 477 | NewsApp-Android | Apache License 2.0 |
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/document/FoldersLine.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.remix.remix.document
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.remix.remix.DocumentGroup
public val DocumentGroup.FoldersLine: ImageVector
get() {
if (_foldersLine != null) {
return _foldersLine!!
}
_foldersLine = Builder(name = "FoldersLine", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(6.0f, 7.0f)
verticalLineTo(4.0f)
curveTo(6.0f, 3.448f, 6.448f, 3.0f, 7.0f, 3.0f)
horizontalLineTo(13.414f)
lineTo(15.414f, 5.0f)
horizontalLineTo(21.0f)
curveTo(21.552f, 5.0f, 22.0f, 5.448f, 22.0f, 6.0f)
verticalLineTo(16.0f)
curveTo(22.0f, 16.552f, 21.552f, 17.0f, 21.0f, 17.0f)
horizontalLineTo(18.0f)
verticalLineTo(20.0f)
curveTo(18.0f, 20.552f, 17.552f, 21.0f, 17.0f, 21.0f)
horizontalLineTo(3.0f)
curveTo(2.448f, 21.0f, 2.0f, 20.552f, 2.0f, 20.0f)
verticalLineTo(8.0f)
curveTo(2.0f, 7.448f, 2.448f, 7.0f, 3.0f, 7.0f)
horizontalLineTo(6.0f)
close()
moveTo(6.0f, 9.0f)
horizontalLineTo(4.0f)
verticalLineTo(19.0f)
horizontalLineTo(16.0f)
verticalLineTo(17.0f)
horizontalLineTo(6.0f)
verticalLineTo(9.0f)
close()
moveTo(8.0f, 5.0f)
verticalLineTo(15.0f)
horizontalLineTo(20.0f)
verticalLineTo(7.0f)
horizontalLineTo(14.586f)
lineTo(12.586f, 5.0f)
horizontalLineTo(8.0f)
close()
}
}
.build()
return _foldersLine!!
}
private var _foldersLine: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 2,718 | compose-icon-collections | MIT License |
library/modulon/src/main/java/modulon/layout/recycler/manager/FixedLinearLayoutManager.kt | huskcasaca | 464,732,039 | false | null | package modulon.layout.recycler.manager
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class FixedLinearLayoutManager(context: Context) : LinearLayoutManager(context) {
override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
try { super.onLayoutChildren(recycler, state) } catch (e: Throwable) { }
}
override fun onAdapterChanged(oldAdapter: RecyclerView.Adapter<*>?, newAdapter: RecyclerView.Adapter<*>?) {
super.onAdapterChanged(oldAdapter, newAdapter)
}
}
//class CustomLayoutManager(context: Context) : LinearLayoutManager(context) {
// override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
// try { super.onLayoutChildren(recycler, state) } catch (e: Throwable) { }
// }
//
// override fun getChildAt(index: Int): View? {
// return super.getChildAt(index)
// }
//
//} | 0 | Kotlin | 4 | 5 | 2522ec7169a5fd295225caf936bae2edf09b157e | 1,002 | bitshares-oases-android | MIT License |
reposilite-backend/src/main/kotlin/com/reposilite/shared/HttpClient.kt | dzikoysk | 96,474,388 | false | null | /*
* Copyright (c) 2021 dzikoysk
*
* 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.reposilite.shared
import com.google.api.client.http.GenericUrl
import com.google.api.client.http.HttpMethods
import com.google.api.client.http.HttpRequest
import com.google.api.client.http.HttpResponse
import com.google.api.client.http.javanet.NetHttpTransport
import com.reposilite.journalist.Channel
import com.reposilite.journalist.Journalist
import com.reposilite.shared.fs.DocumentInfo
import com.reposilite.shared.fs.FileDetails
import com.reposilite.shared.fs.UNKNOWN_LENGTH
import com.reposilite.shared.fs.getExtension
import com.reposilite.shared.fs.getSimpleNameFromUri
import com.reposilite.web.http.ErrorResponse
import com.reposilite.web.http.errorResponse
import io.javalin.http.ContentType
import io.javalin.http.HttpCode.BAD_REQUEST
import io.javalin.http.HttpCode.NOT_ACCEPTABLE
import panda.std.Result
import panda.std.asSuccess
import java.io.InputStream
import java.net.Proxy
interface RemoteClient {
/**
* @param uri - full remote host address with a gav
* @param credentials - basic credentials in user:password format
* @param connectTimeout - connection establishment timeout in seconds
* @param readTimeout - connection read timeout in seconds
*/
fun head(uri: String, credentials: String?, connectTimeout: Int, readTimeout: Int): Result<FileDetails, ErrorResponse>
/**
* @param uri - full remote host address with a gav
* @param credentials - basic credentials in user:password format
* @param connectTimeout - connection establishment timeout in seconds
* @param readTimeout - connection read timeout in seconds
*/
fun get(uri: String, credentials: String?, connectTimeout: Int, readTimeout: Int): Result<InputStream, ErrorResponse>
}
interface RemoteClientProvider {
fun createClient(journalist: Journalist, proxy: Proxy?): RemoteClient
}
object HttpRemoteClientProvider : RemoteClientProvider {
override fun createClient(journalist: Journalist, proxy: Proxy?): RemoteClient =
HttpRemoteClient(journalist, proxy)
}
class HttpRemoteClient(private val journalist: Journalist, proxy: Proxy?) : RemoteClient {
private val requestFactory = NetHttpTransport.Builder()
.setProxy(proxy)
.build()
.createRequestFactory()
override fun head(uri: String, credentials: String?, connectTimeout: Int, readTimeout: Int): Result<FileDetails, ErrorResponse> =
createRequest(HttpMethods.HEAD, uri, credentials, connectTimeout, readTimeout)
.execute {
val headers = it.headers
// Nexus can send misleading for client content-length of chunked responses
// ~ https://github.com/dzikoysk/reposilite/issues/549
val contentLength =
if ("gzip" == headers.contentEncoding)
UNKNOWN_LENGTH // remove content-length header
else
headers.contentLength
val contentType = headers.contentType
?.let { ContentType.getContentType(it) }
?: ContentType.getContentTypeByExtension(uri.getExtension())
?: ContentType.APPLICATION_OCTET_STREAM
DocumentInfo(
uri.getSimpleNameFromUri(),
contentType,
contentLength
).asSuccess()
}
override fun get(uri: String, credentials: String?, connectTimeout: Int, readTimeout: Int): Result<InputStream, ErrorResponse> =
createRequest(HttpMethods.GET, uri, credentials, connectTimeout, readTimeout)
.execute { it.content.asSuccess() }
private fun createRequest(method: String, uri: String, credentials: String?, connectTimeout: Int, readTimeout: Int): HttpRequest {
val request = requestFactory.buildRequest(method, GenericUrl(uri), null)
request.throwExceptionOnExecuteError = false
request.connectTimeout = connectTimeout * 1000
request.readTimeout = readTimeout * 1000
request.authenticateWith(credentials)
return request
}
private fun <R> HttpRequest.execute(block: (HttpResponse) -> Result<R, ErrorResponse>): Result<R, ErrorResponse> =
try {
val response = this.execute()
when {
response.contentType == ContentType.HTML -> errorResponse(NOT_ACCEPTABLE, "Illegal file type (${response.contentType})")
response.isSuccessStatusCode.not() -> errorResponse(NOT_ACCEPTABLE, "Unsuccessful request (${response.statusCode})")
else -> block(response)
}
} catch (exception: Exception) {
createErrorResponse(this.url.toString(), exception)
}
private fun HttpRequest.authenticateWith(credentials: String?): HttpRequest = also {
if (credentials != null) {
val (username, password) = credentials.split(":", limit = 2)
it.headers.setBasicAuthentication(username, password)
}
}
private fun <V> createErrorResponse(uri: String, exception: Exception): Result<V, ErrorResponse> {
journalist.logger.debug("Cannot get $uri")
journalist.logger.exception(Channel.DEBUG, exception)
return errorResponse(BAD_REQUEST, "An error of type ${exception.javaClass} happened: ${exception.message}")
}
}
private typealias HeadHandler = (String, String?, Int, Int) -> Result<FileDetails, ErrorResponse>
private typealias GetHandler = (String, String?, Int, Int) -> Result<InputStream, ErrorResponse>
class FakeRemoteClientProvider(private val headHandler: HeadHandler, private val getHandler: GetHandler) : RemoteClientProvider {
override fun createClient(journalist: Journalist, proxy: Proxy?): RemoteClient =
FakeRemoteClient(headHandler, getHandler)
}
class FakeRemoteClient(private val headHandler: HeadHandler, private val getHandler: GetHandler) : RemoteClient {
override fun head(uri: String, credentials: String?, connectTimeout: Int, readTimeout: Int): Result<FileDetails, ErrorResponse> =
headHandler(uri, credentials, connectTimeout, readTimeout)
override fun get(uri: String, credentials: String?, connectTimeout: Int, readTimeout: Int): Result<InputStream, ErrorResponse> =
getHandler(uri, credentials, connectTimeout, readTimeout)
} | 17 | Kotlin | 64 | 409 | d81f897de5117d29e80acf30b252958971acb9dd | 6,964 | reposilite | Apache License 2.0 |
feature/home/src/main/java/io/github/satoshun/pino/feature/home/Main.kt | satoshun-android-example | 722,807,992 | false | {"Kotlin": 94487, "Ruby": 157} | package io.github.satoshun.pino.feature.home
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import io.github.satoshun.pino.designsystem.rememberPullToRefreshState
@Composable
internal fun Main(
parentState: HomeState,
state: HomeTabState.MainState,
paddingValues: PaddingValues,
) {
when (state) {
is HomeTabState.MainState.Loading -> {
Box(
modifier = Modifier
.padding(paddingValues)
.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
CircularProgressIndicator()
}
}
is HomeTabState.MainState.Success -> {
val pullToRefreshState = rememberPullToRefreshState(
isRefreshing = state.isRefreshing,
onRefresh = {
parentState.eventSink(HomeEvent.Refresh)
},
)
Box(
modifier = Modifier
.fillMaxSize()
.nestedScroll(pullToRefreshState.nestedScrollConnection),
) {
Images(
images = state.images,
contentPadding = paddingValues,
onImageClick = {
parentState.eventSink(HomeEvent.GoToImageDetail(it))
},
onImageLongClick = {
parentState.eventSink(HomeEvent.GoToImageModalBottom(it))
},
)
PullToRefreshContainer(
modifier = Modifier
.padding(paddingValues)
.align(Alignment.TopCenter),
state = pullToRefreshState,
)
}
}
}
}
| 3 | Kotlin | 0 | 0 | c95c56f0c99695622adb3875361dd33307499bf4 | 1,927 | template-android | Apache License 2.0 |
feature/notes-list/data/src/main/kotlin/ru/maksonic/beresta/feature/notes_list/data/list/FetchNoteByIdUseCaseImpl.kt | maksonic | 580,058,579 | false | {"Kotlin": 1587340, "Assembly": 374} | package ru.maksonic.beresta.feature.notes_list.data.list
import ru.maksonic.beresta.feature.notes_list.domain.NoteDomainItem
import ru.maksonic.beresta.feature.notes_list.domain.list.NotesRepository
import ru.maksonic.beresta.feature.notes_list.domain.list.usecase.FetchNoteByIdUseCase
/**
* @Author maksonic on 15.10.2023
*/
class FetchNoteByIdUseCaseImpl(private val repository: NotesRepository) : FetchNoteByIdUseCase {
override fun invoke(args: Long): NoteDomainItem = repository.fetchById(args)
} | 0 | Kotlin | 0 | 0 | 863585ab17882e444060e5535401c728f9fc335d | 509 | Beresta | MIT License |
app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaSimilar.kt | CarlosEsco | 182,704,531 | false | null | package eu.kanade.tachiyomi.data.database.models
import java.io.Serializable
/**
* Object containing the history statistics of a chapter
*/
interface MangaSimilar : Serializable {
/**
* Id of this similar manga object.
*/
var id: Long?
/**
* Mangadex id of manga
*/
var manga_id: String
/**
* JSONArray.toString() of our similar manga object
*/
var data: String
companion object {
fun create(): MangaSimilarImpl {
return MangaSimilarImpl()
}
}
}
| 83 | null | 70 | 934 | 317243499e4131d3c3ee3604d81f8b69067414a4 | 544 | Neko | Apache License 2.0 |
sample-app/src/main/java/com/nextgenbroadcast/mobile/middleware/sample/view/Atsc3PlayerView.kt | jjustman | 418,004,011 | false | null | package com.nextgenbroadcast.mobile.middleware.sample.view
import com.google.android.exoplayer2.Player
interface Atsc3PlayerView {
fun setPlayer(player: Player?)
fun setShowBuffering(showBuffering: Int)
} | 0 | Kotlin | 0 | 5 | f0d91240d7c68c57c7ebfd0739148c86a38ffa58 | 214 | libatsc3-middleware-sample-app | MIT License |
components/src/main/java/zzx/components/menu/contextmenu/extensions/View.kt | imurluck | 173,118,355 | false | null | package zzx.components.menu.contextmenu.extensions
import android.animation.ObjectAnimator
import android.view.View
import zzx.components.menu.contextmenu.IndexCompare
import zzx.components.menu.contextmenu.MenuGravity
/**
* depend on {@see <a href="https://github.com/Yalantis/Context-Menu.Android
* /blob/master/lib/src/main/java/com/yalantis/contextmenu/lib/extensions/View.kt">View.kt</a>}
* this file is used for build some public Animators base on {@link android.view.View},
* create by zzx
* create at 19-3-19
*/
/**
* get animator when view closes horizontally
*/
internal fun View.rotationCloseHorizontal(gravity: MenuGravity, compare: IndexCompare): ObjectAnimator {
val realPivotX = when (gravity) {
MenuGravity.START -> 0.0f
MenuGravity.END -> width.toFloat()
else -> when (compare) {
IndexCompare.SMALLER -> width.toFloat()
IndexCompare.BIGGER -> 0.0f
else -> throw IllegalAccessException("close view index must be smaller or bigger!")
}
}
val startDegrees = 0f
var endDegrees = when (gravity) {
MenuGravity.START -> 90F
MenuGravity.END -> -90F
else -> when (compare) {
IndexCompare.SMALLER -> -90f
IndexCompare.BIGGER -> 90f
else -> throw IllegalAccessException("close view index must be smaller or bigger!")
}
}
return ObjectAnimator.ofFloat(this, View.ROTATION_Y, startDegrees, endDegrees).apply {
pivotX = realPivotX
pivotY = height.toFloat()
}
}
/**
* get animator when view opens horizontally
*/
internal fun View.rotationOpenHorizontal(gravity: MenuGravity): ObjectAnimator {
val realPivotX = when (gravity) {
MenuGravity.START -> 0.0f
MenuGravity.END -> width.toFloat()
MenuGravity.BOTTOM -> 0.0f
MenuGravity.TOP -> 0.0f
}
var startDegrees = when (gravity) {
MenuGravity.START -> 90f
MenuGravity.END -> -90f
MenuGravity.BOTTOM -> 90f
MenuGravity.TOP -> 90f
}
val endDegree = 0f
return ObjectAnimator.ofFloat(this, View.ROTATION_Y, startDegrees, endDegree).apply {
pivotX = realPivotX
pivotY = height / 2.0f
}
}
/**
* get animator when view closes vertically
* [compare] means index compared with the clicked view
*/
internal fun View.rotationCloseVertical(gravity: MenuGravity, compare: IndexCompare): ObjectAnimator {
val realPivotY = when (gravity) {
MenuGravity.TOP -> 0.0f
MenuGravity.BOTTOM -> height.toFloat()
else -> when(compare) {
IndexCompare.SMALLER -> height.toFloat()
IndexCompare.BIGGER -> 0.0f
else -> throw IllegalAccessException("close view index must be smaller or bigger!")
}
}
val startDegrees = 0.0f
val endDegrees = when (gravity) {
MenuGravity.TOP -> -90f
MenuGravity.BOTTOM -> 90f
else -> when (compare) {
IndexCompare.SMALLER -> 90f
IndexCompare.BIGGER -> -90f
else -> throw IllegalAccessException("close view index must be smaller or bigger!")
}
}
return ObjectAnimator.ofFloat(this, View.ROTATION_X, startDegrees, endDegrees).apply {
pivotX = width / 2.0f
pivotY = realPivotY
}
}
/**
* get animator when view open vertically
*/
internal fun View.rotationOpenVertical(gravity: MenuGravity): ObjectAnimator {
val realPivotY = when (gravity) {
MenuGravity.BOTTOM -> height.toFloat()
else -> 0.0f
}
val startDegrees = when (gravity) {
MenuGravity.BOTTOM -> 90.0f
else -> -90.0f
}
val endDegrees = 0.0f
return ObjectAnimator.ofFloat(this, View.ROTATION_X, startDegrees, endDegrees).apply {
pivotX = width / 2.0f
pivotY = realPivotY
}
}
fun View.alphaOpen(): ObjectAnimator =
ObjectAnimator.ofFloat(this, View.ALPHA, 0.0f, 1.0f)
internal fun View.alphaClose(): ObjectAnimator =
ObjectAnimator.ofFloat(this, View.ALPHA, 1.0f, 0.0f)
| 0 | Kotlin | 0 | 0 | 5b83b397589414589e41c4dfefefa60863054c70 | 4,063 | UIComponents | Apache License 2.0 |
src/main/kotlin/SepareCorpus.kt | fcruzel | 183,215,777 | false | {"Gradle": 1, "Gradle Kotlin DSL": 1, "INI": 1, "Shell": 1, "Text": 39, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Java": 1, "Kotlin": 8, "Motorola 68K Assembly": 1, "SQL": 1} | import com.opencsv.CSVReader
import java.io.File
fun main() {
val tweets = CSVReader(File("$resourcesPath/instancia/CTR_TRAIN.csv").bufferedReader()).readAll()
val unprocessesCorpusT = File("$resourcesPath/unprocessed_corpus/unprocessed_corpusT.txt").bufferedWriter()
val unprocessesCorpusNT = File("$resourcesPath/unprocessed_corpus/unprocessed_corpusNT.txt").bufferedWriter()
for ((i, tweet) in tweets.withIndex()) {
if (tweet.isEmpty() || tweet[0].isBlank()) {
println("Empty line at ${i+1}")
continue
}
when {
tweet[1] == "troll" -> unprocessesCorpusT.writeln(tweet[0])
tweet[1] == "not_troll" -> unprocessesCorpusNT.writeln(tweet[0])
else -> println("Hey, that's weird: " + tweet[0] + " - " + tweet[1])
}
}
unprocessesCorpusT.close()
unprocessesCorpusNT.close()
} | 0 | Kotlin | 0 | 0 | ecf073f58ff077064b6fc3e021d1f5b54db128b0 | 893 | pln-iaa | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/eks/CfnClusterResourcesVpcConfigPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.eks
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.Boolean
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.eks.CfnCluster
/**
* An object representing the VPC configuration to use for an Amazon EKS cluster.
*
* When updating a resource, you must include these properties if the previous CloudFormation
* template of the resource had them:
* * `EndpointPublicAccess`
* * `EndpointPrivateAccess`
* * `PublicAccessCidrs`
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.eks.*;
* ResourcesVpcConfigProperty resourcesVpcConfigProperty = ResourcesVpcConfigProperty.builder()
* .subnetIds(List.of("subnetIds"))
* // the properties below are optional
* .endpointPrivateAccess(false)
* .endpointPublicAccess(false)
* .publicAccessCidrs(List.of("publicAccessCidrs"))
* .securityGroupIds(List.of("securityGroupIds"))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-eks-cluster-resourcesvpcconfig.html)
*/
@CdkDslMarker
public class CfnClusterResourcesVpcConfigPropertyDsl {
private val cdkBuilder: CfnCluster.ResourcesVpcConfigProperty.Builder =
CfnCluster.ResourcesVpcConfigProperty.builder()
private val _publicAccessCidrs: MutableList<String> = mutableListOf()
private val _securityGroupIds: MutableList<String> = mutableListOf()
private val _subnetIds: MutableList<String> = mutableListOf()
/**
* @param endpointPrivateAccess Set this value to `true` to enable private access for your
* cluster's Kubernetes API server endpoint. If you enable private access, Kubernetes API
* requests from within your cluster's VPC use the private VPC endpoint. The default value for
* this parameter is `false` , which disables private access for your Kubernetes API server.
* If you disable private access and you have nodes or AWS Fargate pods in the cluster, then
* ensure that `publicAccessCidrs` includes the necessary CIDR blocks for communication with
* the nodes or Fargate pods. For more information, see
* [Amazon EKS cluster endpoint access control](https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html)
* in the **Amazon EKS User Guide** .
*/
public fun endpointPrivateAccess(endpointPrivateAccess: Boolean) {
cdkBuilder.endpointPrivateAccess(endpointPrivateAccess)
}
/**
* @param endpointPrivateAccess Set this value to `true` to enable private access for your
* cluster's Kubernetes API server endpoint. If you enable private access, Kubernetes API
* requests from within your cluster's VPC use the private VPC endpoint. The default value for
* this parameter is `false` , which disables private access for your Kubernetes API server.
* If you disable private access and you have nodes or AWS Fargate pods in the cluster, then
* ensure that `publicAccessCidrs` includes the necessary CIDR blocks for communication with
* the nodes or Fargate pods. For more information, see
* [Amazon EKS cluster endpoint access control](https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html)
* in the **Amazon EKS User Guide** .
*/
public fun endpointPrivateAccess(endpointPrivateAccess: IResolvable) {
cdkBuilder.endpointPrivateAccess(endpointPrivateAccess)
}
/**
* @param endpointPublicAccess Set this value to `false` to disable public access to your
* cluster's Kubernetes API server endpoint. If you disable public access, your cluster's
* Kubernetes API server can only receive requests from within the cluster VPC. The default
* value for this parameter is `true` , which enables public access for your Kubernetes API
* server. For more information, see
* [Amazon EKS cluster endpoint access control](https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html)
* in the **Amazon EKS User Guide** .
*/
public fun endpointPublicAccess(endpointPublicAccess: Boolean) {
cdkBuilder.endpointPublicAccess(endpointPublicAccess)
}
/**
* @param endpointPublicAccess Set this value to `false` to disable public access to your
* cluster's Kubernetes API server endpoint. If you disable public access, your cluster's
* Kubernetes API server can only receive requests from within the cluster VPC. The default
* value for this parameter is `true` , which enables public access for your Kubernetes API
* server. For more information, see
* [Amazon EKS cluster endpoint access control](https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html)
* in the **Amazon EKS User Guide** .
*/
public fun endpointPublicAccess(endpointPublicAccess: IResolvable) {
cdkBuilder.endpointPublicAccess(endpointPublicAccess)
}
/**
* @param publicAccessCidrs The CIDR blocks that are allowed access to your cluster's public
* Kubernetes API server endpoint. Communication to the endpoint from addresses outside of the
* CIDR blocks that you specify is denied. The default value is `0.0.0.0/0` . If you've
* disabled private endpoint access, make sure that you specify the necessary CIDR blocks for
* every node and AWS Fargate `Pod` in the cluster. For more information, see
* [Amazon EKS cluster endpoint access control](https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html)
* in the **Amazon EKS User Guide** .
*/
public fun publicAccessCidrs(vararg publicAccessCidrs: String) {
_publicAccessCidrs.addAll(listOf(*publicAccessCidrs))
}
/**
* @param publicAccessCidrs The CIDR blocks that are allowed access to your cluster's public
* Kubernetes API server endpoint. Communication to the endpoint from addresses outside of the
* CIDR blocks that you specify is denied. The default value is `0.0.0.0/0` . If you've
* disabled private endpoint access, make sure that you specify the necessary CIDR blocks for
* every node and AWS Fargate `Pod` in the cluster. For more information, see
* [Amazon EKS cluster endpoint access control](https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html)
* in the **Amazon EKS User Guide** .
*/
public fun publicAccessCidrs(publicAccessCidrs: Collection<String>) {
_publicAccessCidrs.addAll(publicAccessCidrs)
}
/**
* @param securityGroupIds Specify one or more security groups for the cross-account elastic
* network interfaces that Amazon EKS creates to use that allow communication between your
* nodes and the Kubernetes control plane. If you don't specify any security groups, then
* familiarize yourself with the difference between Amazon EKS defaults for clusters deployed
* with Kubernetes. For more information, see
* [Amazon EKS security group considerations](https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html)
* in the **Amazon EKS User Guide** .
*/
public fun securityGroupIds(vararg securityGroupIds: String) {
_securityGroupIds.addAll(listOf(*securityGroupIds))
}
/**
* @param securityGroupIds Specify one or more security groups for the cross-account elastic
* network interfaces that Amazon EKS creates to use that allow communication between your
* nodes and the Kubernetes control plane. If you don't specify any security groups, then
* familiarize yourself with the difference between Amazon EKS defaults for clusters deployed
* with Kubernetes. For more information, see
* [Amazon EKS security group considerations](https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html)
* in the **Amazon EKS User Guide** .
*/
public fun securityGroupIds(securityGroupIds: Collection<String>) {
_securityGroupIds.addAll(securityGroupIds)
}
/**
* @param subnetIds Specify subnets for your Amazon EKS nodes. Amazon EKS creates cross-account
* elastic network interfaces in these subnets to allow communication between your nodes and
* the Kubernetes control plane.
*/
public fun subnetIds(vararg subnetIds: String) {
_subnetIds.addAll(listOf(*subnetIds))
}
/**
* @param subnetIds Specify subnets for your Amazon EKS nodes. Amazon EKS creates cross-account
* elastic network interfaces in these subnets to allow communication between your nodes and
* the Kubernetes control plane.
*/
public fun subnetIds(subnetIds: Collection<String>) {
_subnetIds.addAll(subnetIds)
}
public fun build(): CfnCluster.ResourcesVpcConfigProperty {
if (_publicAccessCidrs.isNotEmpty()) cdkBuilder.publicAccessCidrs(_publicAccessCidrs)
if (_securityGroupIds.isNotEmpty()) cdkBuilder.securityGroupIds(_securityGroupIds)
if (_subnetIds.isNotEmpty()) cdkBuilder.subnetIds(_subnetIds)
return cdkBuilder.build()
}
}
| 3 | null | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 9,608 | awscdk-dsl-kotlin | Apache License 2.0 |
library/src/main/kotlin/com/jaredrummler/html/Attribute.kt | jaredrummler | 77,140,259 | false | null | /*
* Copyright (C) 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jaredrummler.html
import android.text.Html
import android.text.Layout
import android.text.style.*
import android.widget.TextView
/**
* HTML Attribute. A name/value pair.
*
* Elements in HTML have attributes; these are additional values that configure the elements or
* adjust their behavior in various ways to meet the criteria the users want.
*
* @property key The name of the attribute.
* @property value A string value that configures the elements or adjust their behavior.
* @author <NAME> (<EMAIL>)
* @since July 6, 2021
*/
data class Attribute(val key: String, val value: String) {
override fun toString(): String = "$key=\"$value\""
/**
* Interface definition used for any [Enum] that maps to an attribute's value.
*
* @see Attribute.value
*/
interface Value {
/** The value of an attribute */
val value: String
}
/**
* The css attribute that [TextView] uses via [Html.fromHtml] to set a
* [ParagraphStyle]/[AlignmentSpan] on the text in the HTML node, defining
* the alignment of text at the paragraph level.
*
* @see Attribute.Value
*/
enum class Align(override val value: String) : Value {
/** @see Layout.Alignment.ALIGN_CENTER */
CENTER("center"),
/** @see Layout.Alignment.ALIGN_OPPOSITE */
RIGHT("right"),
/** @see Layout.Alignment.ALIGN_NORMAL */
LEFT("left");
}
/**
* The css attribute that [TextView] uses via [Html.fromHtml] to determine if the text
* is set to display right-to-left or left-to-right.
*
* This is used in the 'dir' global attribute of an element which indicates
* the directionality of the element's text.
*
* **See Also:** [dir][https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir]
* @see Attribute.Value
*/
enum class Direction(override val value: String) : Value {
/** Left-To-Right */
RTL("rtl"),
/** Right-to-left */
LTR("ltr");
}
/**
* Class defined for creating, adding and modifying the global 'style' CSS attribute.
*
* The 'style' attribute is used by [Html] to set the [alignment][Layout.Alignment],
* [background color][BackgroundColorSpan], [strikethrough][StrikethroughSpan], and
* [foreground color][ForegroundColorSpan].
*
* @param element The HTML Element to set the 'style' attribute on.
*/
class Style(private val element: HtmlElement) : Renderer<String> {
/**
* Set a style attribute on the 'style' attribute of the [element].
*
* @param key The CSS attribute name.
* @param value The CSS attribute value.
*/
operator fun set(key: String, value: String) {
val style = element.attributes[STYLE] ?: ""
element.attributes.remove(STYLE)
element.attributes[STYLE] = "$style$key:$value;"
}
/**
* Get the style value with the given name.
*
* @param name The CSS style attribute name.
* @return The value of the attribute or null if it has not been set.
*/
operator fun get(name: String): String? {
val style = element.attributes[STYLE] ?: return null
val pattern = STYLE_REGEX.toPattern()
val matcher = pattern.matcher(style)
while (matcher.find()) {
val key = matcher.group(1) ?: continue
if (key == name) {
return matcher.group(2) ?: continue
}
}
return null
}
/**
* Set the 'align' style attribute which sets the [AlignmentSpan] on text.
*
* @param align One of the following: [Align.CENTER], [Align.LEFT], or [Align.RIGHT].
* @return This [Style] instance for chaining calls.
*/
fun align(align: Align) = apply {
this[ALIGN] = align.value
}
/**
* Set the 'background-color' style attribute which sets the [BackgroundColorSpan] on text.
*
* @param color The color integer.
* @return This [Style] instance for chaining calls.
*/
fun background(color: Int) = apply {
this[BACKGROUND_COLOR] = color.hex
}
/**
* Set the 'color' style attribute which sets the [ForegroundColorSpan] on text.
*
* @param color The color integer.
* @return This [Style] instance for chaining calls.
*/
fun color(color: Int) = apply {
this[COLOR] = color.hex
}
/**
* Set the 'text-decoration' style attribute to 'line-through' which sets the
* [StrikethroughSpan] on text.
*
* @return This [Style] instance for chaining calls.
*/
fun strikethrough() = apply {
this[TEXT_DECORATION] = LINE_THROUGH
}
/**
* Set the 'text-align' style attribute which sets the [AlignmentSpan] on text.
*
* @param align One of the following: [Align.CENTER], [Align.LEFT], or [Align.RIGHT].
* @return This [Style] instance for chaining calls.
*/
fun textAlign(align: Align) = apply {
this[TEXT_ALIGN] = align.value
}
override fun render(): String {
return element.attributes[STYLE] ?: ""
}
override fun toString(): String = render()
companion object {
private const val STYLE = "style"
private const val ALIGN = "align"
private const val BACKGROUND_COLOR = "background-color"
private const val COLOR = "color"
private const val TEXT_DECORATION = "text-decoration"
private const val TEXT_ALIGN = "text-align"
private const val LINE_THROUGH = "line-through"
//-------------------------------- CSS NAME -------------------------- VALUE ---
private const val STYLE_REGEX = "(-?[_a-zA-Z]+[_a-zA-Z0-9-]*)\\s*:\\s*([^;]+);?"
/** Convert an integer to a hex color code. */
private val Int.hex: String get() = '#' + String.format("%06X", 0xFFFFFF and this)
}
}
}
| 3 | Kotlin | 61 | 534 | b38aed837090e2439d328e935fb66ccf3958bfbb | 6,904 | HtmlDsl | Apache License 2.0 |
app/src/main/java/com/domatix/yevbes/nucleus/customer/CustomerProfileFragment.kt | sm2x | 234,568,179 | true | {"Kotlin": 782306} | package com.domatix.yevbes.nucleus.customer
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.widget.Toolbar
import android.view.*
import android.widget.Toast
import com.domatix.yevbes.nucleus.R
import com.domatix.yevbes.nucleus.core.Odoo
import com.domatix.yevbes.nucleus.customer.entities.Customer
import com.domatix.yevbes.nucleus.databinding.FragmentCustomerProfileBinding
import com.domatix.yevbes.nucleus.gson
import com.domatix.yevbes.nucleus.utils.PreferencesManager
import com.google.gson.Gson
import io.reactivex.disposables.CompositeDisposable
import timber.log.Timber
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
/**
* A simple [Fragment] subclass.
* Activities that contain this fragment must implement the
* [CustomerProfileFragment.OnFragmentInteractionListener] interface
* to handle interaction events.
* Use the [CustomerProfileFragment.newInstance] factory method to
* create an instance of this fragment.
*
*/
class CustomerProfileFragment : Fragment() {
//private var listener: OnFragmentInteractionListener? = null
private lateinit var binding: FragmentCustomerProfileBinding
private lateinit var customerGsonAsAString: String
lateinit var prefs: PreferencesManager private set
private lateinit var compositeDisposable: CompositeDisposable
private lateinit var activityCustomerProfile: CustomerProfileActivity
lateinit var customer: Customer private set
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
customerGsonAsAString = arguments!!.getString(ARG_PARAM1)
val customerGson = Gson()
customer = customerGson.fromJson(customerGsonAsAString, Customer::class.java)
}
private fun readCustomer(id: Int) {
Odoo.load(id, "res.partner") {
onSubscribe { disposable ->
compositeDisposable.add(disposable)
}
onNext { response ->
if (response.isSuccessful) {
val load = response.body()!!
if (load.isSuccessful) {
val result = load.result
val item: Customer = gson.fromJson(result.value, Customer::class.java)
customer = item // ...
} else {
// Odoo specific error
Timber.w("load() failed with ${load.errorMessage}")
}
} else {
Timber.w("request failed with ${response.code()}:${response.message()}")
}
}
onError { error ->
error.printStackTrace()
}
onComplete {
setBindings(customer)
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_customer_profile, container, false)
prefs = PreferencesManager
compositeDisposable = CompositeDisposable()
/*if (prefs.isContainsProfileContact() && prefs.isContactProfileEdited()) {
readCustomer(customer.id)
prefs.isContactProfileEdited(false)
}else{
setBindings(customer)
}*/
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
activityCustomerProfile = (activity as CustomerProfileActivity)
readCustomer(customer.id)
}
private fun setBindings(customer: Customer) {
if (customer.countryId.isJsonArray) {
binding.country = customer.countryId.asJsonArray.get(1).asString
} else {
binding.country = getString(R.string.country)
}
if (customer.stateId.isJsonArray) {
binding.state = customer.stateId.asJsonArray.get(1).asString
} else {
binding.state = getString(R.string.state)
}
if (customer.isCompany) {
binding.company = "Is Company"
} else {
binding.imageViewCompany.visibility = View.GONE
binding.tvCompany.visibility = View.GONE
/* binding.linearLayoutCustomerProfile.removeView(binding.imageViewCompany)
binding.linearLayoutCustomerProfile.removeView(binding.tvCompany)*/
}
if (!customer.fullAddress.equals("\n\n \n")) {
val gmmIntentUri = Uri.parse("geo:0,0?q=${customer.fullAddress}")
val intent = Intent(android.content.Intent.ACTION_VIEW, gmmIntentUri)
intent.setPackage("com.google.android.apps.maps")
binding.tvFullAddress.setOnClickListener {
startActivity(intent)
}
binding.tvFullAddress.setTextColor(context?.let { ContextCompat.getColor(it, R.color.colorCustomerAddress) }!!)
}
customerGsonAsAString = gson.toJson(customer)
binding.customer = customer
if (::activityCustomerProfile.isInitialized) {
activityCustomerProfile.binding.name = customer.name
activityCustomerProfile.binding.imageSmall = customer.imageSmall
activityCustomerProfile.binding.executePendingBindings()
}
binding.executePendingBindings()
}
// TODO: Rename method, update argument and hook method into UI event
/*fun onButtonPressed(uri: Uri) {
listener?.onFragmentInteraction(uri)
}*/
private var listener: CustomerProfileFragment.OnFragmentInteractionListener? = null
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnFragmentInteractionListener) {
listener = context
} else {
throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")
}
}
interface OnFragmentInteractionListener {
fun onBackPressFragm()
}
override fun onDetach() {
super.onDetach()
listener = null
}
override fun onResume() {
super.onResume()
val toolbar = activity!!.findViewById<View>(R.id.toolbar) as Toolbar
toolbar.setNavigationOnClickListener {
listener?.onBackPressFragm()
}
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @return A new instance of fragment CustomerProfileFragment.
*/
@JvmStatic
fun newInstance(param1: String) =
CustomerProfileFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
compositeDisposable.dispose()
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.menu_customer_profile, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item != null) {
when (item.itemId) {
R.id.action_customer_profile_edit -> {
val customerProfileEditFragment = CustomerProfileEditFragment.newInstance(customerGsonAsAString)
fragmentManager!!.beginTransaction()
.replace(R.id.container, customerProfileEditFragment, CustomerProfileActivity.CUSTOMER_PROFILE_EDIT_FRAG_TAG)
.addToBackStack(null)
.commit()
}
R.id.action_customer_profile_refresh -> {
readCustomer(customer.id)
}
R.id.action_customer_profile_share -> {
Toast.makeText(context, "Shared", Toast.LENGTH_SHORT).show()
}
R.id.action_customer_profile_import -> {
Toast.makeText(context, "Imported", Toast.LENGTH_SHORT).show()
}
else -> {
}
}
}
return super.onOptionsItemSelected(item)
}
}
| 0 | null | 0 | 0 | 237e9496b5fb608f543e98111269da9b91a06ed3 | 8,788 | nucleus | MIT License |
framework/src/main/kotlin/dev/alpas/auth/BaseUser.kt | racharya | 235,246,550 | true | {"Kotlin": 381871, "Shell": 1497, "JavaScript": 622, "CSS": 402} | package dev.alpas.auth
import me.liuwj.ktorm.entity.Entity
import java.time.Instant
interface BaseUser<E : BaseUser<E>> : Entity<E>, Authenticatable {
override var id: Long
override var password: String
override var email: String?
var name: String?
var createdAt: Instant?
var updatedAt: Instant?
}
| 0 | null | 0 | 0 | d0fe0d2ebba60a506afd893e46396a61e2e28837 | 325 | alpas | MIT License |
backend/src/test/kotlin/ase/athlete_view/unit/ActivityServiceMapAndStatisticsUnitTests.kt | bastianferch | 753,047,760 | false | {"Kotlin": 895253, "TypeScript": 217992, "HTML": 75240, "Python": 44465, "SCSS": 25875, "JavaScript": 9353, "Dockerfile": 1329, "Shell": 203} | /*-
* #%L
* athlete_view
* %%
* Copyright (C) 2023 - 2024 TU Wien INSO ASE GROUP 5 WS2023
* %%
* 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.
* #L%
*/
package ase.athlete_view.unit
import ase.athlete_view.AthleteViewApplication
import ase.athlete_view.common.exception.entity.NoMapDataException
import ase.athlete_view.common.exception.entity.NotFoundException
import ase.athlete_view.domain.activity.persistence.ActivityRepository
import ase.athlete_view.domain.activity.persistence.FitDataRepositoryImpl
import ase.athlete_view.domain.activity.persistence.PlannedActivityRepository
import ase.athlete_view.domain.activity.pojo.dto.FitData
import ase.athlete_view.domain.activity.service.ActivityService
import ase.athlete_view.domain.user.persistence.AthleteRepository
import ase.athlete_view.domain.user.persistence.TrainerRepository
import ase.athlete_view.domain.user.persistence.UserRepository
import ase.athlete_view.util.ActivityCreator
import ase.athlete_view.util.UserCreator
import ase.athlete_view.util.WithCustomMockUser
import com.ninjasquad.springmockk.MockkBean
import io.mockk.every
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.context.ActiveProfiles
import org.springframework.transaction.annotation.Transactional
import java.io.ByteArrayInputStream
import java.time.LocalDateTime
import java.util.*
@SpringBootTest(classes = [AthleteViewApplication::class])
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@ActiveProfiles("test")
class ActivityServiceMapAndStatisticsUnitTests {
@Autowired
private lateinit var activityService: ActivityService
@MockkBean
private lateinit var plannedActivityRepo: PlannedActivityRepository
@MockkBean
private lateinit var userRepository: UserRepository
@MockkBean
private lateinit var activityRepository: ActivityRepository
@MockkBean
private lateinit var athleteRepository: AthleteRepository
@MockkBean
private lateinit var trainerRepository: TrainerRepository
@MockkBean
private lateinit var fitRepository: FitDataRepositoryImpl // for... reasons, cannot specify interface here
@Test
@WithCustomMockUser(id = -2)
fun fetchingMapDataOfNonEmptyActivity_shouldSucceed() {
val mockUserObj = UserCreator.getAthlete(-2)
val fileBytes = this::class.java.classLoader.getResource("fit-files/7x(1km P2').fit")?.readBytes()
val act = ActivityCreator.getDefaultActivity()
act.user = mockUserObj
act.fitData = "totallyfitdata"
every { userRepository.findById(any<Long>()) } returns Optional.of(mockUserObj)
every { athleteRepository.findById(any()) } returns Optional.of(mockUserObj)
every { activityRepository.findById(any<Long>()) } returns Optional.of(act)
every { activityRepository.findActivitiesByUserId(any<Long>()) } returns listOf(act)
every { fitRepository.getFitData(any<String>()) } returns FitData("totallyfitdata", ByteArrayInputStream(fileBytes))
val mapData = activityService.prepareMapDataForActivity(-2, 1)
assertThat(mapData).isNotNull
assertThat(mapData.size).isGreaterThan(0)
assertThat(mapData).noneMatch { it.latitude == 0.0 && it.longitude == 0.0 }
}
@Test
@WithCustomMockUser(id = -2)
fun fetchingMapDataOfEmptyActivity_shouldThrowException() {
val mockUserObj = UserCreator.getAthlete(-2)
val act = ActivityCreator.getDefaultActivity()
act.user = mockUserObj
act.fitData = null
every { userRepository.findById(any<Long>()) } returns Optional.of(mockUserObj)
every { athleteRepository.findById(any()) } returns Optional.of(mockUserObj)
every { activityRepository.findById(any<Long>()) } returns Optional.of(act)
every { activityRepository.findActivitiesByUserId(any<Long>()) } returns listOf(act)
assertThrows<NoMapDataException> { activityService.prepareMapDataForActivity(-2, 1) }
}
@Test
@WithCustomMockUser(id = -2)
fun fetchingMapDataOfActivityOfOtherUser_shouldThrowException() {
val mockUserObj = UserCreator.getAthlete(-2)
val act = ActivityCreator.getDefaultActivity()
act.user = UserCreator.getTrainer()
act.fitData = null
every { userRepository.findById(any<Long>()) } returns Optional.of(mockUserObj)
every { athleteRepository.findById(any()) } returns Optional.of(mockUserObj)
every { activityRepository.findById(any<Long>()) } returns Optional.of(act)
every { activityRepository.findActivitiesByUserId(any<Long>()) } returns listOf(act)
assertThrows<NoMapDataException> { activityService.prepareMapDataForActivity(-2, 1) }
}
@Test
@WithCustomMockUser(id = -2)
fun fetchingMapDataOfEmptyActivity_shouldSucceed() {
val mockUserObj = UserCreator.getAthlete(-2)
val act = ActivityCreator.getDefaultActivity()
act.user = mockUserObj
act.fitData = "asdf123"
val fileBytes = this::class.java.classLoader.getResource(("fit-files/no-coords.fit"))?.readBytes()
every { userRepository.findById(any<Long>()) } returns Optional.of(mockUserObj)
every { athleteRepository.findById(any()) } returns Optional.of(mockUserObj)
every { activityRepository.findById(any<Long>()) } returns Optional.of(act)
every { activityRepository.findActivitiesByUserId(any<Long>()) } returns listOf(act)
every { fitRepository.getFitData(any<String>()) } returns FitData("asdf123", ByteArrayInputStream(fileBytes))
val coords = activityService.prepareMapDataForActivity(-2, 1)
assertThat(coords).isNotNull
assertThat(coords.size).isZero()
}
@Test
@WithCustomMockUser(id = -3)
fun fetchingMapDataFromAthleteActivityAsTrainer_shouldSucceed() {
val mockUserObj = UserCreator.getAthlete(-2)
val act = ActivityCreator.getDefaultActivity()
act.user = mockUserObj
act.fitData = "asdf123"
val fileBytes = this::class.java.classLoader.getResource(("fit-files/no-coords.fit"))?.readBytes()
val mockTrainer = UserCreator.getTrainer()
mockTrainer.id = -3
mockTrainer.athletes.add(mockUserObj)
every { userRepository.findById(any<Long>()) } returns Optional.of(mockTrainer)
every { trainerRepository.findById(any()) } returns Optional.of(mockTrainer)
every { activityRepository.findById(any<Long>()) } returns Optional.of(act)
every { activityRepository.findActivitiesByUserId(any<Long>()) } returns listOf(act)
every { fitRepository.getFitData(any<String>()) } returns FitData("asdf123", ByteArrayInputStream(fileBytes))
val coords = activityService.prepareMapDataForActivity(-3, 1)
assertThat(coords).isNotNull
assertThat(coords.size).isZero()
}
@Test
@Transactional
@WithCustomMockUser(id = -2)
fun fetchingStatisticsOfNonEmptyActivity_shouldSucceed() {
val mockUserObj = UserCreator.getAthlete(-2)
val fileBytes = this::class.java.classLoader.getResource(("fit-files/7x(1km P2').fit"))?.readBytes()
val act = ActivityCreator.getDefaultActivity()
act.user = mockUserObj
act.fitData = "totallyfitdata"
every { userRepository.findById(any<Long>()) } returns Optional.of(mockUserObj)
every { athleteRepository.findById(any()) } returns Optional.of(mockUserObj)
every { activityRepository.findById(any<Long>()) } returns Optional.of(act)
every { activityRepository.findActivitiesByUserId(any<Long>()) } returns listOf(act)
every { fitRepository.getFitData(any<String>()) } returns FitData("totallyfitdata", ByteArrayInputStream(fileBytes))
val stats = activityService.prepareStatisticsForActivity(-2, 1)
assertThat(stats).isNotNull
assertThat(stats.size).isGreaterThan(0)
assertThat(stats).noneMatch { it.speed == 0.0f && it.cadence == 0.toShort() && it.power == 0 && it.bpm == 0 }
// verify no duplicates (by timestamp)
val timeSet = mutableSetOf<LocalDateTime>()
stats.forEach { timeSet.add(it.timestamp) }
assertThat(stats.size).isEqualTo(timeSet.size)
}
@Test
@WithCustomMockUser(id = -2)
fun fetchStatisticsOfActivityWithoutFitData_shouldReturnEmptyList() {
val mockUserObj = UserCreator.getAthlete(-2)
val act = ActivityCreator.getDefaultActivity()
act.user = mockUserObj
act.fitData = null
every { userRepository.findById(any<Long>()) } returns Optional.of(mockUserObj)
every { athleteRepository.findById(any()) } returns Optional.of(mockUserObj)
every { activityRepository.findById(any<Long>()) } returns Optional.of(act)
every { activityRepository.findActivitiesByUserId(any<Long>()) } returns listOf(act)
val data = activityService.prepareStatisticsForActivity(-2, 1)
assertThat(data).isNotNull
assertThat(data.size).isZero()
}
@Test
@WithCustomMockUser(id = -2)
fun attemptToFetchStatisticsOfActivityOfAnotherUser_shouldThrowException() {
val mockUserObj = UserCreator.getAthlete(-2)
val act = ActivityCreator.getDefaultActivity()
act.id = 10
act.user = UserCreator.getTrainer()
act.fitData = "test213"
every { userRepository.findById(any<Long>()) } returns Optional.of(mockUserObj)
every { athleteRepository.findById(any()) } returns Optional.of(mockUserObj)
every { activityRepository.findById(any<Long>()) } returns Optional.of(act)
every { activityRepository.findActivitiesByUserId(any<Long>()) } returns listOf(ActivityCreator.getDefaultActivity())
assertThrows<NotFoundException> { activityService.prepareStatisticsForActivity(-2, 10) }
}
@Test
@WithCustomMockUser(id = -2)
fun attemptToFetchStatisticsOfInvalidActivity_shouldThrowException() {
val mockUserObj = UserCreator.getAthlete(-2)
val act = ActivityCreator.getDefaultActivity()
act.user = mockUserObj
act.fitData = "test213"
every { userRepository.findById(any<Long>()) } returns Optional.of(mockUserObj)
every { athleteRepository.findById(any()) } returns Optional.of(mockUserObj)
every { activityRepository.findById(any<Long>()) } returns Optional.empty()
assertThrows<NotFoundException> { activityService.prepareStatisticsForActivity(-2, 1) }
}
@Test
@WithCustomMockUser(id = -2)
fun attemptToFetchStatisticsOfInvalidUser_shouldThrowException() {
val mockUserObj = UserCreator.getAthlete(-2)
val act = ActivityCreator.getDefaultActivity()
act.user = mockUserObj
act.fitData = "test213"
every { userRepository.findById(any<Long>()) } returns Optional.empty()
every { athleteRepository.findById(any()) } returns Optional.of(mockUserObj)
assertThrows<NotFoundException> { activityService.prepareStatisticsForActivity(-2, 1) }
}
@Test
@WithCustomMockUser(id = -3)
fun fetchStatisticsForAthleteActivityAsTrainer_shouldSucceed() {
val mockUserObj = UserCreator.getAthlete(-2)
val act = ActivityCreator.getDefaultActivity()
act.user = mockUserObj
act.fitData = null
val trainer = UserCreator.getTrainer()
trainer.id = -3
trainer.athletes = mutableSetOf(mockUserObj)
every { userRepository.findById(any<Long>()) } returns Optional.of(trainer)
every { trainerRepository.findById(any()) } returns Optional.of(trainer)
every { activityRepository.findById(any<Long>()) } returns Optional.of(act)
every { activityRepository.findActivitiesByUserId(any<Long>()) } returns listOf(act)
val data = activityService.prepareStatisticsForActivity(trainer.id!!, act.id!!)
assertThat(data).isNotNull
assertThat(data.size).isZero()
}
}
| 0 | Kotlin | 0 | 3 | bb6edd91d50f4944948d194f2b300ec9d2ec818a | 13,295 | AthleteView | MIT License |
data/src/main/java/com/luckhost/data/network/dto/AccountParams.kt | solutions-architects | 850,385,932 | false | {"Kotlin": 174818} | package com.luckhost.data.network.dto
data class AccountParams(
val username: String,
val firstName: String,
val lastName: String,
val email: String,
val isStuff: Boolean,
)
| 0 | Kotlin | 0 | 2 | c03c60f79d5259f3d0d27e9dcb6f749f6dfe735c | 195 | anynote_android | The Unlicense |
java/dzjforex/src/main/kotlin/com/jforex/dzjforex/history/T6Data.kt | juxeii | 81,964,776 | false | null | package com.jforex.dzjforex.history
data class T6Data(
val time: Double,
val high: Float,
val low: Float,
val open: Float,
val close: Float,
val value: Float,
val volume: Float
) | 1 | C++ | 6 | 8 | 9894a872441fd38d2e2b42029941f72c7d30ea52 | 207 | dztools | MIT License |
app/src/main/java/name/lmj0011/courierlocker/workers/CreateBackupWorker.kt | lmj0011 | 213,748,690 | false | null | package name.lmj0011.courierlocker.workers
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.ParcelFileDescriptor
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toFile
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import kotlinx.coroutines.delay
import name.lmj0011.courierlocker.CourierLockerApplication
import name.lmj0011.courierlocker.R
import name.lmj0011.courierlocker.database.CourierLockerDatabase
import name.lmj0011.courierlocker.helpers.AppDataImportExportHelper
import name.lmj0011.courierlocker.helpers.NotificationHelper
import name.lmj0011.courierlocker.helpers.PreferenceHelper
import name.lmj0011.courierlocker.helpers.Util
import name.lmj0011.courierlocker.receivers.CancelWorkerByTagReceiver
import org.kodein.di.instance
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.lang.Exception
class CreateBackupWorker (private val appContext: Context, parameters: WorkerParameters) :
CoroutineWorker(appContext, parameters) {
companion object {
const val Progress = "Progress"
}
private lateinit var preferences: PreferenceHelper
private var notificationCancelWorkerPendingIntent: PendingIntent
init {
val notificationCancelWorkerIntent = Intent(appContext, CancelWorkerByTagReceiver::class.java).apply {
val tagArray = [email protected]()
putExtra(appContext.getString(R.string.intent_extra_key_worker_tags), tagArray)
}
notificationCancelWorkerPendingIntent = PendingIntent.getBroadcast(appContext, 0, notificationCancelWorkerIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_CANCEL_CURRENT)
}
override suspend fun doWork(): Result {
val application = appContext.applicationContext as CourierLockerApplication
preferences = application.kodein.instance()
val settingsDao = CourierLockerDatabase.getInstance(application).settingsDao
val notification = NotificationCompat.Builder(applicationContext, NotificationHelper.APP_BACKUP_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_sync_24)
.setContentTitle(appContext.getString(R.string.creating_app_backup))
.setOnlyAlertOnce(true)
.setColor(application.colorPrimaryResId)
.addAction(0, appContext.getString(R.string.notification_action_button_cancel), notificationCancelWorkerPendingIntent)
.build()
val foregroundInfo = ForegroundInfo(NotificationHelper.CREATE_APP_BACKUP_NOTIFICATION_ID, notification)
setForeground(foregroundInfo)
try {
val trips = settingsDao.getAllTrips()
val apartments = settingsDao.getAllApartments()
val gatecodes = settingsDao.getAllGateCodes()
val customers = settingsDao.getAllCustomers()
val gigLabels = settingsDao.getAllGigs()
showProgress(25, "25%")
setProgress(workDataOf(Progress to 25))
val rootObj = AppDataImportExportHelper.appModelsToJson(trips, apartments, gatecodes, customers, gigLabels)
showProgress(50, "50%")
setProgress(workDataOf(Progress to 50))
preferences.defaultBackupDir.toFile().mkdirs()
var targetDocFile: DocumentFile? = null
var fd: ParcelFileDescriptor?
var targetFile = File(preferences.defaultBackupDir.toFile().absolutePath + "/${Util.getUniqueFileNamePrefix()}-courierlocker-backup.json")
targetFile.createNewFile()
try {
val tree = DocumentFile.fromTreeUri(appContext, Uri.parse(preferences.automaticBackupLocation()))!!
targetDocFile = tree.createFile("application/json", "${Util.getUniqueFileNamePrefix()}-courierlocker-backup.json")
} catch (ex: IllegalArgumentException) {
// this error should only be thrown, if the User hasn't selected a directory yet
}
if (targetDocFile != null) { // we will write a backup to the user selected directory
fd = appContext.contentResolver.openFileDescriptor(targetDocFile.uri, "w")
targetFile.delete()
} else { // we will write a backup to the default directory
fd = appContext.contentResolver.openFileDescriptor(targetFile.toUri(), "w")
}
fd?.use { p ->
rootObj.toString().toByteArray()?.let {
FileOutputStream(p.fileDescriptor).use { outputStream ->
outputStream.write(it)
outputStream.close()
}
}
}
} catch (ex: Exception) {
Timber.e(ex)
}
showProgress(100, "100%")
setProgress(workDataOf(Progress to 100))
delay(1000)
return Result.success()
}
private fun showProgress(progress: Int, message: String = "") {
val notification = NotificationCompat.Builder(applicationContext, NotificationHelper.APP_BACKUP_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_sync_24)
.setContentTitle(appContext.getString(R.string.creating_app_backup))
.setContentText(message)
.setProgress(100, progress, false)
.setColor((applicationContext as CourierLockerApplication).colorPrimaryResId)
.addAction(0, appContext.getString(R.string.notification_action_button_cancel), notificationCancelWorkerPendingIntent)
.build()
NotificationManagerCompat.from(appContext).apply {
notify(NotificationHelper.CREATE_APP_BACKUP_NOTIFICATION_ID, notification)
}
}
} | 1 | null | 3 | 2 | 930974f6dba1a6ab516d6c4f95813ba0c6668570 | 6,071 | courier-locker | Apache License 2.0 |
android/umenglib/src/main/java/org/hyn/titan/umenglib/xiaomi/MipushActivity.kt | hyperion-hyn | 187,755,032 | false | {"Shell": 9, "Git Config": 1, "YAML": 2, "Text": 1, "Ignore List": 4, "Markdown": 2, "Dart": 774, "JSON": 11, "JavaScript": 5, "Gradle": 5, "Java Properties": 2, "Proguard": 3, "XML": 24, "Kotlin": 37, "Java": 18, "INI": 2, "Ruby": 2, "OpenStep Property List": 5, "Objective-C": 12, "Swift": 23, "Roff": 2, "C": 1} | package org.hyn.titan.umenglib.xiaomi
import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.hyn.titan.tools.AppPrintTools
import org.android.agoo.common.AgooConstants
import com.umeng.message.UmengNotifyClickActivity
import org.hyn.titan.umenglib.R
class MipushActivity : UmengNotifyClickActivity() {
override fun onCreate(p0: Bundle?) {
super.onCreate(p0)
setContentView(R.layout.activity_mipush)
}
override
fun onMessage(intent: Intent) {
super.onMessage(intent) //此方法必须调用,否则无法统计打开数
val body = intent.getStringExtra(AgooConstants.MESSAGE_BODY)
AppPrintTools.printLog("MipushActivity onMessage $body")
Log.i(TAG, "register success:deviceToken:-------->clickclick")
Log.i(TAG, body)
}
companion object {
private val TAG = MipushActivity::class.java.name
}
} | 1 | null | 1 | 1 | 8c68a99a155ea245b8d1ea26027f25a51ee9d5ae | 893 | titan_flutter | MIT License |
app/src/main/java/com/wreckingballsoftware/design/ui/map/MapScreen.kt | leewaggoner | 698,812,124 | false | {"Kotlin": 108052} | package com.wreckingballsoftware.design.ui.map
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.wreckingballsoftware.design.R
import com.wreckingballsoftware.design.database.INVALID_CAMPAIGN_ID
import com.wreckingballsoftware.design.repos.UserRepo
import com.wreckingballsoftware.design.ui.compose.DeSignErrorAlert
import com.wreckingballsoftware.design.ui.compose.DeSignFab
import com.wreckingballsoftware.design.ui.framework.FrameworkStateItem
import com.wreckingballsoftware.design.ui.map.models.MapScreenState
import com.wreckingballsoftware.design.ui.theme.dimensions
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.androidx.compose.koinViewModel
import org.koin.core.parameter.ParametersHolder
@Composable
fun MapScreen(
campaignId: Long,
viewModel: MapViewModel = koinViewModel(
parameters = { ParametersHolder(mutableListOf(campaignId)) }
)
) {
val campaignWithMarkers = viewModel.campaignWithMarkers.collectAsStateWithLifecycle(
initialValue = null
)
MapScreenContent(
state = viewModel.state
)
if (MapViewModel.showAddSignBottomSheet) {
AddSignMarkerBottomSheet(
state = viewModel.state,
campaignName = viewModel.getCurrentCampaignName(),
onNotesValueChanged = viewModel::onNotesValueChanged,
onAddSignMarker = viewModel::onAddSignMarker,
onDismissBottomSheet = viewModel::onDismissBottomSheet,
)
}
if (MapViewModel.showAddCampaignMessage) {
DeSignErrorAlert(
message = stringResource(id = R.string.please_add_campaign),
onDismissAlert = viewModel::onDismissAddCampaignMessage,
)
}
}
@Composable
fun MapScreenContent(
state: MapScreenState,
viewModel: MapViewModel = koinViewModel()
) {
Column(
modifier = Modifier
.fillMaxSize(),
) {
viewModel.DeSignMap(latLng = state.latLng)
}
}
@Composable
fun getMapFrameworkStateItem(userRepo: UserRepo): FrameworkStateItem.MapFrameworkStateItem {
val scope = rememberCoroutineScope()
return FrameworkStateItem.MapFrameworkStateItem() {
DeSignFab(
modifier = Modifier.padding(end = MaterialTheme.dimensions.MapZoomOffset)
) {
scope.launch(Dispatchers.Main) {
if (userRepo.getSelectedCampaignId() == INVALID_CAMPAIGN_ID) {
MapViewModel.showAddCampaignMessage()
} else {
MapViewModel.showAddMarkerBottomSheet()
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | e50de819b5d568124a1c982fb09209e197691a0e | 3,011 | design | Apache License 2.0 |
src/schema-generator/src/main/kotlin/org/icpclive/generator/schema/json.kt | icpc | 447,849,919 | false | null | package org.icpclive.generator.schema
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.EmptySerializersModule
import java.io.File
import kotlin.reflect.KClass
fun PrimitiveKind.toJsonTypeName(): String = when (this) {
PrimitiveKind.BOOLEAN -> "boolean"
PrimitiveKind.BYTE -> "number"
PrimitiveKind.CHAR -> "number"
PrimitiveKind.DOUBLE -> "number"
PrimitiveKind.FLOAT -> "number"
PrimitiveKind.INT -> "number"
PrimitiveKind.LONG -> "number"
PrimitiveKind.SHORT -> "number"
PrimitiveKind.STRING -> "string"
}
@OptIn(ExperimentalSerializationApi::class, InternalSerializationApi::class)
fun SerialDescriptor.toJsonSchemaType(
processed: MutableSet<String>,
definitions: MutableMap<String, JsonElement>,
extras: Map<String, JsonElement> = emptyMap(),
extraTypeProperty: String? = null,
title: String? = null,
): JsonElement {
if (kind is PrimitiveKind) {
require(extraTypeProperty == null)
return JsonObject(mapOf("type" to JsonPrimitive((kind as PrimitiveKind).toJsonTypeName())))
}
if (kind == SerialKind.CONTEXTUAL) {
val kclass = capturedKClass ?: error("Contextual serializer $serialName doesn't have class")
val defaultSerializer = serializer(kclass, emptyList(), isNullable)
return defaultSerializer.descriptor.toJsonSchemaType(processed, definitions, extras, extraTypeProperty)
}
if (isInline) {
return getElementDescriptor(0).toJsonSchemaType(processed, definitions, extras, extraTypeProperty)
}
// Before processing, check for recursion
val paramNamesWithTypes = elementDescriptors.map { it.serialName }
val name = serialName + if (paramNamesWithTypes.isEmpty()) "" else "<${paramNamesWithTypes.joinToString(",")}>"
val id = title ?: name
if (!processed.contains(id)) {
processed.add(id)
val data = when (kind) {
PolymorphicKind.OPEN -> TODO("Open polymorphic types are not supported")
is PrimitiveKind, SerialKind.CONTEXTUAL -> error("Already handled")
PolymorphicKind.SEALED -> {
require(extraTypeProperty == null)
val typeFieldName = getElementName(0)
val contextualDescriptor = getElementDescriptor(1)
mapOf(
"oneOf" to JsonArray(
contextualDescriptor.elementDescriptors
.sortedBy { it.serialName }
.map {
it.toJsonSchemaType(
processed,
definitions,
title = it.serialName.split(".").last(),
extraTypeProperty = typeFieldName
)
}
)
)
}
SerialKind.ENUM -> {
require(extraTypeProperty == null)
mapOf("enum" to JsonArray(elementNames.map { JsonPrimitive(it) }))
}
StructureKind.CLASS -> {
JsonObject(
mapOf(
"type" to JsonPrimitive("object"),
"properties" to JsonObject(
listOfNotNull(extraTypeProperty).associateWith {
JsonObject(
mapOf(
"const" to JsonPrimitive(serialName),
"default" to JsonPrimitive(serialName),
)
)
} +
(0 until elementsCount).associate {
getElementName(it) to
getElementDescriptor(it).toJsonSchemaType(processed, definitions)
}
),
"additionalProperties" to JsonPrimitive(false),
"required" to JsonArray(
(listOfNotNull(extraTypeProperty) +
(0 until elementsCount).filterNot { isElementOptional(it) }
.map { getElementName(it) }).map { JsonPrimitive(it) }
)
)
)
}
StructureKind.LIST -> {
mapOf(
"type" to JsonPrimitive("array"),
"items" to getElementDescriptor(0).toJsonSchemaType(processed, definitions)
)
}
StructureKind.MAP -> {
val keysSerializer = getElementDescriptor(0)
val valuesSerializer = getElementDescriptor(1)
when (keysSerializer.kind) {
PrimitiveKind.STRING -> {
JsonObject(
mapOf(
"type" to JsonPrimitive("object"),
"patternProperties" to JsonObject(
mapOf(
".*" to valuesSerializer.toJsonSchemaType(
processed,
definitions
)
)
)
)
)
}
SerialKind.ENUM -> {
JsonObject(mapOf(
"type" to JsonPrimitive("object"),
"properties" to JsonObject(
(0 until keysSerializer.elementsCount).associate {
keysSerializer.getElementName(it) to valuesSerializer.toJsonSchemaType(
processed,
definitions
)
}
)
))
}
else -> error("Unsupported map key: $keysSerializer")
}
}
StructureKind.OBJECT -> TODO("Object types are not supported")
}.let {
if (isNullable) {
val schemaNull = JsonObject(mapOf("type" to JsonPrimitive("null")))
if (it.keys.singleOrNull() == "oneOf") {
mapOf("oneOf" to JsonArray((it.values.single() as JsonArray).toList() + schemaNull))
} else {
mapOf("oneOf" to JsonArray(listOf(JsonObject(it), schemaNull)))
}
} else {
it
}
}
val content = (extras + data).toMutableMap()
if (title != null) {
content["title"] = JsonPrimitive(title)
}
definitions[id] = JsonObject(content)
}
return JsonObject(mapOf("\$ref" to JsonPrimitive("#/\$defs/$id")))
}
fun SerialDescriptor.toJsonSchema(title: String): JsonElement {
val definitions = mutableMapOf<String, JsonElement>()
val mainSchema = toJsonSchemaType(
title = title,
processed = mutableSetOf(),
definitions = definitions,
)
return JsonObject(
(mainSchema as JsonObject) +
mapOf(
"\$defs" to JsonObject(definitions),
)
)
}
private val json = Json {
prettyPrint = true
}
class JsonCommand : CliktCommand(name = "json") {
private val className by option(help = "Class name for which schema should be generated")
private val output by option("--output", "-o", help = "File to print output").required()
private val title by option("--title", "-t", help = "Title inside schema file").required()
override fun run() {
val thing = serializer(Class.forName(className))
val serializer = thing.descriptor
val schema = json.encodeToString(serializer.toJsonSchema(title))
File(output).printWriter().use {
it.println(schema)
}
}
}
| 17 | null | 10 | 35 | 0fc437753084c015b63045673af2284b6aca40f7 | 8,553 | live-v3 | MIT License |
feature/poke/android/src/main/kotlin/com/taetae98/codelab/feature/poke/android/PokeNav.kt | taetae98coding | 776,446,644 | false | {"Kotlin": 15055} | package com.taetae98.codelab.feature.poke.android
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.navigation
import com.taetae98.codelab.navigation.android.poke.PokeListNav
import com.taetae98.codelab.navigation.android.poke.PokeNav
public fun NavGraphBuilder.pokeNav(
navController: NavController,
) {
navigation(
startDestination = PokeListNav.ROUTE,
route = PokeNav.ROUTE,
) {
composable(
route = PokeListNav.ROUTE,
) {
PokeListRoute(
navigateUp = navController::navigateUp,
pagingViewModel = hiltViewModel(),
)
}
}
}
| 0 | Kotlin | 0 | 0 | af149c7d34138c5b589975dbc42f9dd4e657af8f | 810 | TaeTaeCodeLab | Apache License 2.0 |
android/app/src/main/java/com/algorand/android/modules/firebase/token/FirebaseTokenManager.kt | perawallet | 364,359,642 | false | {"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596} | /*
* Copyright 2022 <NAME>, LDA
* 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.algorand.android.modules.firebase.token
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.algorand.android.banner.domain.usecase.BannersUseCase
import com.algorand.android.core.AccountManager
import com.algorand.android.deviceregistration.domain.usecase.DeviceIdUseCase
import com.algorand.android.deviceregistration.domain.usecase.DeviceRegistrationUseCase
import com.algorand.android.deviceregistration.domain.usecase.FirebasePushTokenUseCase
import com.algorand.android.deviceregistration.domain.usecase.UpdatePushTokenUseCase
import com.algorand.android.models.Account
import com.algorand.android.models.Node
import com.algorand.android.modules.firebase.token.mapper.FirebaseTokenResultMapper
import com.algorand.android.modules.firebase.token.model.FirebaseTokenResult
import com.algorand.android.modules.firebase.token.usecase.ApplyNodeChangesUseCase
import com.algorand.android.utils.CacheResult
import com.algorand.android.utils.DataResource
import com.algorand.android.utils.launchIO
import com.google.firebase.messaging.FirebaseMessaging
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.drop
// TODO: separate this class into smaller classes
@Singleton
class FirebaseTokenManager @Inject constructor(
private val firebasePushTokenUseCase: FirebasePushTokenUseCase,
private val deviceRegistrationUseCase: DeviceRegistrationUseCase,
private val bannersUseCase: BannersUseCase,
private val deviceIdUseCase: DeviceIdUseCase,
private val updatePushTokenUseCase: UpdatePushTokenUseCase,
private val accountManager: AccountManager,
private val applyNodeChangesUseCase: ApplyNodeChangesUseCase,
private val firebaseTokenResultMapper: FirebaseTokenResultMapper
) : DefaultLifecycleObserver {
private val _firebaseTokenResultEventFlow = MutableStateFlow<FirebaseTokenResult>(FirebaseTokenResult.TokenLoading)
val firebaseTokenResultFlow: StateFlow<FirebaseTokenResult> get() = _firebaseTokenResultEventFlow
private val localAccountsCollector: suspend (value: List<Account>) -> Unit = {
refreshFirebasePushToken(null)
}
private val firebasePushTokenCollector: suspend (value: CacheResult<String>?) -> Unit = {
if (it?.data.isNullOrBlank().not()) {
registerFirebasePushToken(it?.data.orEmpty())
}
}
private val deviceRegistrationTokenCollector: suspend (value: DataResource<String>) -> Unit = {
if (it is DataResource.Success) {
onPushTokenUpdated()
bannersUseCase.initializeBanner(deviceId = it.data)
} else {
_firebaseTokenResultEventFlow.emit(firebaseTokenResultMapper.mapToTokenLoaded())
onPushTokenFailed()
}
}
private val updatePushTokenCollector: suspend (value: DataResource<String>) -> Unit = {
if (it is DataResource.Success) {
applyNodeChangesUseCase.invoke()
}
}
private var coroutineScope: CoroutineScope? = null
private var registerDeviceJob: Job? = null
private var refreshFirebasePushTokenJob: Job? = null
fun refreshFirebasePushToken(previousNode: Node?) {
refreshFirebasePushTokenJob?.cancel()
refreshFirebasePushTokenJob = coroutineScope?.launchIO {
try {
_firebaseTokenResultEventFlow.emit(firebaseTokenResultMapper.mapToTokenLoading())
if (previousNode != null) {
deletePreviousNodePushToken(previousNode)
}
FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
firebasePushTokenUseCase.setPushToken(token)
}
} catch (exception: Exception) {
// TODO: Re-active last activated node in case of failure
_firebaseTokenResultEventFlow.emit(firebaseTokenResultMapper.mapToTokenLoaded())
}
}
}
private fun initialize() {
initObservers()
refreshFirebasePushToken(null)
}
private fun initObservers() {
coroutineScope?.launchIO {
// Drop 1 added to get any list changes.
accountManager.accounts.drop(1).collectLatest(localAccountsCollector)
}
coroutineScope?.launchIO {
firebasePushTokenUseCase.getPushTokenCacheFlow().collect(firebasePushTokenCollector)
}
}
private fun registerFirebasePushToken(token: String) {
registerDeviceJob?.cancel()
registerDeviceJob = coroutineScope?.launchIO {
deviceRegistrationUseCase.registerDevice(token).collect(deviceRegistrationTokenCollector)
}
}
private suspend fun deletePreviousNodePushToken(previousNode: Node) {
val deviceId = deviceIdUseCase.getNodeDeviceId(previousNode) ?: return
updatePushTokenUseCase.updatePushToken(deviceId, null).collect(updatePushTokenCollector)
}
private suspend fun onPushTokenUpdated() {
_firebaseTokenResultEventFlow.emit(firebaseTokenResultMapper.mapToTokenLoaded())
}
private suspend fun onPushTokenFailed() {
_firebaseTokenResultEventFlow.emit(firebaseTokenResultMapper.mapToTokenFailed())
}
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
coroutineScope = CoroutineScope(Job() + Dispatchers.Main)
initialize()
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
coroutineScope?.cancel()
coroutineScope = null
}
}
| 22 | Swift | 62 | 181 | 92fc77f73fa4105de82d5e87b03c1e67600a57c0 | 6,435 | pera-wallet | Apache License 2.0 |
feeder-stock/src/main/kotlin/ru/timmson/feeder/stock/dao/StockDAO.kt | timmson | 603,205,306 | false | {"Kotlin": 94441, "Dockerfile": 376} | package ru.timmson.feeder.stock.dao
import ru.timmson.feeder.stock.model.Indicator
interface StockDAO {
@Throws(StockDAOException::class)
fun getStockByTicker(ticker: String): Indicator
}
| 0 | Kotlin | 0 | 0 | f9bf56918440bd192787a59ebeb818b8291d3c02 | 200 | feeder | MIT License |
core/src/main/kotlin/id/barakkastudio/core/data/datasource/local/db/AppDatabase.kt | im-o | 635,182,956 | false | {"Kotlin": 136103} | package id.barakkastudio.core.data.datasource.local.db
import androidx.room.Database
import androidx.room.RoomDatabase
import id.barakkastudio.core.data.datasource.local.db.dao.ProductDao
import id.barakkastudio.core.data.datasource.local.db.entity.ProductEntity
/** Created by github.com/im-o on 12/27/2022. */
@Database(
entities = [ProductEntity::class],
version = 1,
exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
abstract fun productDao(): ProductDao
} | 0 | Kotlin | 2 | 78 | ecea30212b228ed88e2a5f38b55ea4c9b107a246 | 499 | jetpack-compose-clean-architecture | MIT License |
thrift-logging/src/main/java/com/linecorp/lich/thrift/logging/ThriftLogEnabler.kt | line | 200,039,378 | false | null | /*
* Copyright 2021 LINE Corporation
*
* 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.linecorp.lich.thrift.logging
import android.content.Context
import com.linecorp.lich.thrift.ThriftClientFactory
import org.apache.thrift.TServiceClient
import org.apache.thrift.transport.TTransport
/**
* A class that enables logging for [ThriftClientFactory].
*
* @param context Android's application [Context].
* @param logger The logger to be injected into [ThriftClientFactory].
*/
class ThriftLogEnabler(context: Context, logger: ThriftLogger) {
private val injector = ThriftLoggerInjector(context, logger)
/**
* Returns a [ThriftClientFactory] that does transparent logging.
*
* @param factory A base [ThriftClientFactory].
* @return A [ThriftClientFactory] with transparent logging enabled.
*/
fun <T : TServiceClient> enableLogging(
factory: ThriftClientFactory<T>
): ThriftClientFactory<T> =
if (factory is LoggingThriftClientFactory) {
factory
} else {
LoggingThriftClientFactory(factory, injector)
}
private class LoggingThriftClientFactory<T : TServiceClient>(
private val delegate: ThriftClientFactory<T>,
private val injector: ThriftLoggerInjector
) : ThriftClientFactory<T> {
override fun newClient(transport: TTransport): T =
injector.injectLogger(delegate.newClient(transport))
}
}
| 3 | null | 20 | 165 | 2fc3ac01ed57e31208816239f6747d6cdb67de6d | 1,966 | lich | Apache License 2.0 |
ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/response/ResponseType.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.response
import io.ktor.util.*
import io.ktor.util.reflect.*
import kotlin.native.concurrent.*
private val ResponseTypeAttributeKey: AttributeKey<TypeInfo> = AttributeKey("ResponseTypeAttributeKey")
/**
* Type of the response object that was passed in [respond] function.
* Can be useful for custom serializations.
*/
public var ApplicationResponse.responseType: TypeInfo?
get() = call.attributes.getOrNull(ResponseTypeAttributeKey)
@InternalAPI set(value) {
if (value != null) {
call.attributes.put(ResponseTypeAttributeKey, value)
} else {
call.attributes.remove(ResponseTypeAttributeKey)
}
}
| 302 | null | 962 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 810 | ktor | Apache License 2.0 |
src/main/java/top/zbeboy/isy/web/vo/internship/apply/InternshipCompanyVo.kt | zbeboy | 71,459,176 | false | null | package top.zbeboy.isy.web.vo.internship.apply
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* Created by zbeboy 2017-12-23 .
**/
open class InternshipCompanyVo {
var internshipCompanyId: String? = null
@NotNull
var studentId: Int? = null
@NotNull
var studentUsername: String? = null
@NotNull
@Size(max = 100)
var internshipReleaseId: String? = null
@NotNull
@Size(max = 15)
var studentName: String? = null
@NotNull
@Size(max = 50)
var collegeClass: String? = null
@NotNull
@Size(max = 2)
var studentSex: String? = null
@NotNull
@Size(max = 20)
var studentNumber: String? = null
@NotNull
@Size(max = 15)
var phoneNumber: String? = null
@NotNull
@Size(max = 100)
var qqMailbox: String? = null
@NotNull
@Size(max = 20)
var parentalContact: String? = null
@NotNull
var headmaster: String? = null
var headmasterContact: String? = null
@NotNull
@Size(max = 200)
var internshipCompanyName: String? = null
@NotNull
@Size(max = 500)
var internshipCompanyAddress: String? = null
@NotNull
@Size(max = 10)
var internshipCompanyContacts: String? = null
@NotNull
@Size(max = 20)
var internshipCompanyTel: String? = null
@NotNull
var schoolGuidanceTeacher: String? = null
var schoolGuidanceTeacherTel: String? = null
@NotNull
var startTime: String? = null
@NotNull
var endTime: String? = null
var commitmentBook: Byte? = null
var safetyResponsibilityBook: Byte? = null
var practiceAgreement: Byte? = null
var internshipApplication: Byte? = null
var practiceReceiving: Byte? = null
var securityEducationAgreement: Byte? = null
var parentalConsent: Byte? = null
} | 7 | JavaScript | 2 | 7 | 9634602adba558dbdb945c114692019accdb50a9 | 1,826 | ISY | MIT License |
library/src/main/java/com/kernel/colibri/core/strategy/Strategy.kt | kernel0x | 199,272,056 | false | null | package com.kernel.colibri.core.strategy
import com.kernel.colibri.core.models.Condition
interface Strategy {
var condition: Condition
fun run()
} | 0 | Kotlin | 0 | 9 | 7e91341238549b41a5bb710e6706f3d3e2b16b51 | 156 | colibri | Apache License 2.0 |
app/src/main/java/com/ahmed/carefer/ui/screens/home/presentation/favoritesContentList/FavoritesViewState.kt | ahmedshaban1 | 571,586,573 | false | null | package com.ahmed.carefer.ui.screens.home.presentation.favoritesContentList
import com.ahmed.carefer.models.DayMatches
data class FavoritesViewState(
val matchesDay: MutableList<DayMatches> = mutableListOf(),
)
| 0 | Kotlin | 0 | 0 | 7b119d6495e4a406908fa2566ec3bf34f1a1fb97 | 217 | carefer | Apache License 2.0 |
domain/src/main/java/org/oppia/domain/topic/TopicController.kt | sajalasati | 269,276,236 | true | {"Kotlin": 3567791, "Starlark": 86669, "Java": 27558, "Shell": 1855} | package org.oppia.domain.topic
import android.graphics.Color
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import org.json.JSONArray
import org.json.JSONObject
import org.oppia.app.model.ChapterPlayState
import org.oppia.app.model.ChapterProgress
import org.oppia.app.model.ChapterSummary
import org.oppia.app.model.CompletedStory
import org.oppia.app.model.CompletedStoryList
import org.oppia.app.model.ConceptCard
import org.oppia.app.model.LessonThumbnail
import org.oppia.app.model.LessonThumbnailGraphic
import org.oppia.app.model.OngoingTopicList
import org.oppia.app.model.ProfileId
import org.oppia.app.model.Question
import org.oppia.app.model.RevisionCard
import org.oppia.app.model.StoryProgress
import org.oppia.app.model.StorySummary
import org.oppia.app.model.Subtopic
import org.oppia.app.model.Topic
import org.oppia.app.model.TopicProgress
import org.oppia.domain.oppialogger.exceptions.ExceptionsController
import org.oppia.domain.question.QuestionRetriever
import org.oppia.domain.util.JsonAssetRetriever
import org.oppia.util.data.AsyncResult
import org.oppia.util.data.DataProvider
import org.oppia.util.data.DataProviders
import org.oppia.util.system.OppiaClock
import javax.inject.Inject
import javax.inject.Singleton
const val TEST_SKILL_ID_0 = "test_skill_id_0"
const val TEST_SKILL_ID_1 = "test_skill_id_1"
const val TEST_SKILL_ID_2 = "test_skill_id_2"
const val FRACTIONS_SKILL_ID_0 = "5RM9KPfQxobH"
const val FRACTIONS_SKILL_ID_1 = "UxTGIJqaHMLa"
const val FRACTIONS_SKILL_ID_2 = "B39yK4cbHZYI"
const val RATIOS_SKILL_ID_0 = "NGZ89uMw0IGV"
const val TEST_QUESTION_ID_0 = "question_id_0"
const val TEST_QUESTION_ID_1 = "question_id_1"
const val TEST_QUESTION_ID_2 = "question_id_2"
const val TEST_QUESTION_ID_3 = "question_id_3"
const val FRACTIONS_QUESTION_ID_0 = "dobbibJorU9T"
const val FRACTIONS_QUESTION_ID_1 = "EwbUb5oITtUX"
const val FRACTIONS_QUESTION_ID_2 = "ryIPWUmts8rN"
const val FRACTIONS_QUESTION_ID_3 = "7LcsKDzzfImQ"
const val FRACTIONS_QUESTION_ID_4 = "gDQxuodXI3Uo"
const val FRACTIONS_QUESTION_ID_5 = "Ep2t5mulNUsi"
const val FRACTIONS_QUESTION_ID_6 = "wTfCaDBKMixD"
const val FRACTIONS_QUESTION_ID_7 = "leeSNRVbbBwp"
const val FRACTIONS_QUESTION_ID_8 = "AciwQAtcvZfI"
const val FRACTIONS_QUESTION_ID_9 = "YQwbX2r6p3Xj"
const val FRACTIONS_QUESTION_ID_10 = "NNuVGmbJpnj5"
const val RATIOS_QUESTION_ID_0 = "QiKxvAXpvUbb"
private const val FRACTIONS_SUBTOPIC_ID_1 = 1
private const val FRACTIONS_SUBTOPIC_ID_2 = 2
private const val FRACTIONS_SUBTOPIC_ID_3 = 3
private const val FRACTIONS_SUBTOPIC_ID_4 = 4
private const val SUBTOPIC_BG_COLOR = "#FFFFFF"
private const val QUESTION_DATA_PROVIDER_ID = "QuestionDataProvider"
private const val TRANSFORMED_GET_COMPLETED_STORIES_PROVIDER_ID =
"transformed_get_completed_stories_provider_id"
private const val TRANSFORMED_GET_ONGOING_TOPICS_PROVIDER_ID =
"transformed_get_ongoing_topics_provider_id"
private const val TRANSFORMED_GET_TOPIC_PROVIDER_ID = "transformed_get_topic_provider_id"
private const val TRANSFORMED_GET_STORY_PROVIDER_ID = "transformed_get_story_provider_id"
private const val COMBINED_TOPIC_PROVIDER_ID = "combined_topic_provider_id"
private const val COMBINED_STORY_PROVIDER_ID = "combined_story_provider_id"
/** Controller for retrieving all aspects of a topic. */
@Singleton
class TopicController @Inject constructor(
private val dataProviders: DataProviders,
private val jsonAssetRetriever: JsonAssetRetriever,
private val questionRetriever: QuestionRetriever,
private val conceptCardRetriever: ConceptCardRetriever,
private val revisionCardRetriever: RevisionCardRetriever,
private val storyProgressController: StoryProgressController,
private val exceptionsController: ExceptionsController,
private val oppiaClock: OppiaClock
) {
/**
* Fetches a topic given a profile ID and a topic ID.
*
* @param profileId the ID corresponding to the profile for which progress needs fetched.
* @param topicId the ID corresponding to the topic which needs to be returned.
* @return a [LiveData] for [Topic] combined with [TopicProgress].
*/
fun getTopic(profileId: ProfileId, topicId: String): LiveData<AsyncResult<Topic>> {
val topicDataProvider =
dataProviders.createInMemoryDataProviderAsync(TRANSFORMED_GET_TOPIC_PROVIDER_ID) {
return@createInMemoryDataProviderAsync AsyncResult.success(retrieveTopic(topicId))
}
val topicProgressDataProvider =
storyProgressController.retrieveTopicProgressDataProvider(profileId, topicId)
return dataProviders.convertToLiveData(
dataProviders.combine(
COMBINED_TOPIC_PROVIDER_ID,
topicDataProvider,
topicProgressDataProvider,
::combineTopicAndTopicProgress
)
)
}
/**
* Fetches a story given a profile ID, a topic ID and story ID.
*
* @param profileId the ID corresponding to the profile for which progress needs fetched.
* @param topicId the ID corresponding to the topic which contains this story.
* @param storyId the ID corresponding to the story which needs to be returned.
* @return a [LiveData] for [StorySummary] combined with [StoryProgress].
*/
fun getStory(
profileId: ProfileId,
topicId: String,
storyId: String
): LiveData<AsyncResult<StorySummary>> {
val storyDataProvider =
dataProviders.createInMemoryDataProviderAsync(TRANSFORMED_GET_STORY_PROVIDER_ID) {
return@createInMemoryDataProviderAsync AsyncResult.success(retrieveStory(topicId, storyId))
}
val storyProgressDataProvider =
storyProgressController.retrieveStoryProgressDataProvider(profileId, topicId, storyId)
return dataProviders.convertToLiveData(
dataProviders.combine(
COMBINED_STORY_PROVIDER_ID,
storyDataProvider,
storyProgressDataProvider,
::combineStorySummaryAndStoryProgress
)
)
}
/** Returns the [ConceptCard] corresponding to the specified skill ID, or a failed result if there is none. */
fun getConceptCard(skillId: String): LiveData<AsyncResult<ConceptCard>> {
return MutableLiveData(
try {
AsyncResult.success(conceptCardRetriever.loadConceptCard(skillId))
} catch (e: Exception) {
exceptionsController.logNonFatalException(e, oppiaClock.getCurrentCalendar().timeInMillis)
AsyncResult.failed<ConceptCard>(e)
}
)
}
/** Returns the [RevisionCard] corresponding to the specified topic Id and subtopic ID, or a failed result if there is none. */
fun getRevisionCard(topicId: String, subtopicId: Int): LiveData<AsyncResult<RevisionCard>> {
return MutableLiveData(
try {
AsyncResult.success(retrieveReviewCard(topicId, subtopicId))
} catch (e: Exception) {
exceptionsController.logNonFatalException(e, oppiaClock.getCurrentCalendar().timeInMillis)
AsyncResult.failed<RevisionCard>(e)
}
)
}
/** Returns the list of all completed stories in the form of [CompletedStoryList] for a specific profile. */
fun getCompletedStoryList(profileId: ProfileId): LiveData<AsyncResult<CompletedStoryList>> {
return dataProviders.convertToLiveData(
dataProviders.transformAsync(
TRANSFORMED_GET_COMPLETED_STORIES_PROVIDER_ID,
storyProgressController.retrieveTopicProgressListDataProvider(profileId)
) {
val completedStoryListBuilder = CompletedStoryList.newBuilder()
it.forEach { topicProgress ->
val topic = retrieveTopic(topicProgress.topicId)
val storyProgressList = mutableListOf<StoryProgress>()
val transformedStoryProgressList = topicProgress
.storyProgressMap.values.toList()
storyProgressList.addAll(transformedStoryProgressList)
completedStoryListBuilder.addAllCompletedStory(
createCompletedStoryListFromProgress(
topic,
storyProgressList
)
)
}
AsyncResult.success(completedStoryListBuilder.build())
}
)
}
/** Returns the list of ongoing topics in the form on [OngoingTopicList] for a specific profile. */
fun getOngoingTopicList(profileId: ProfileId): LiveData<AsyncResult<OngoingTopicList>> {
val ongoingTopicListDataProvider = dataProviders.transformAsync(
TRANSFORMED_GET_ONGOING_TOPICS_PROVIDER_ID,
storyProgressController.retrieveTopicProgressListDataProvider(profileId)
) {
val ongoingTopicList = createOngoingTopicListFromProgress(it)
AsyncResult.success(ongoingTopicList)
}
return dataProviders.convertToLiveData(ongoingTopicListDataProvider)
}
fun retrieveQuestionsForSkillIds(skillIdsList: List<String>): DataProvider<List<Question>> {
return dataProviders.createInMemoryDataProvider(QUESTION_DATA_PROVIDER_ID) {
loadQuestionsForSkillIds(skillIdsList)
}
}
private fun createOngoingTopicListFromProgress(
topicProgressList: List<TopicProgress>
): OngoingTopicList {
val ongoingTopicListBuilder = OngoingTopicList.newBuilder()
topicProgressList.forEach { topicProgress ->
val topic = retrieveTopic(topicProgress.topicId)
if (topicProgress.storyProgressCount != 0) {
if (checkIfTopicIsOngoing(topic, topicProgress)) {
ongoingTopicListBuilder.addTopic(topic)
}
}
}
return ongoingTopicListBuilder.build()
}
private fun checkIfTopicIsOngoing(topic: Topic, topicProgress: TopicProgress): Boolean {
val completedChapterProgressList = ArrayList<ChapterProgress>()
val startedChapterProgressList = ArrayList<ChapterProgress>()
topicProgress.storyProgressMap.values.toList().forEach { storyProgress ->
completedChapterProgressList.addAll(
storyProgress.chapterProgressMap.values
.filter { chapterProgress ->
chapterProgress.chapterPlayState ==
ChapterPlayState.COMPLETED
}
)
startedChapterProgressList.addAll(
storyProgress.chapterProgressMap.values
.filter { chapterProgress ->
chapterProgress.chapterPlayState ==
ChapterPlayState.STARTED_NOT_COMPLETED
}
)
}
// If there is no completed chapter, it cannot be an ongoing-topic.
if (completedChapterProgressList.isEmpty()) {
return false
}
// If there is atleast 1 completed chapter and 1 not-completed chapter, it is definitely an ongoing-topic.
if (startedChapterProgressList.isNotEmpty()) {
return true
}
if (topic.storyCount != topicProgress.storyProgressCount &&
topicProgress.storyProgressMap.isNotEmpty()
) {
return true
}
topic.storyList.forEach { storySummary ->
if (topicProgress.storyProgressMap.containsKey(storySummary.storyId)) {
val storyProgress = topicProgress.storyProgressMap[storySummary.storyId]
val lastChapterSummary = storySummary.chapterList.last()
if (!storyProgress!!.chapterProgressMap.containsKey(lastChapterSummary.explorationId)) {
return true
}
}
}
return false
}
private fun createCompletedStoryListFromProgress(
topic: Topic,
storyProgressList: List<StoryProgress>
): List<CompletedStory> {
val completedStoryList = ArrayList<CompletedStory>()
storyProgressList.forEach { storyProgress ->
val storySummary = retrieveStory(topic.topicId, storyProgress.storyId)
val lastChapterSummary = storySummary.chapterList.last()
if (storyProgress.chapterProgressMap.containsKey(lastChapterSummary.explorationId) &&
storyProgress.chapterProgressMap[lastChapterSummary.explorationId]!!.chapterPlayState ==
ChapterPlayState.COMPLETED
) {
val completedStoryBuilder = CompletedStory.newBuilder()
.setStoryId(storySummary.storyId)
.setStoryName(storySummary.storyName)
.setTopicId(topic.topicId)
.setTopicName(topic.name)
.setLessonThumbnail(storySummary.storyThumbnail)
completedStoryList.add(completedStoryBuilder.build())
}
}
return completedStoryList
}
/** Combines the specified topic without progress and topic-progress into a topic. */
private fun combineTopicAndTopicProgress(topic: Topic, topicProgress: TopicProgress): Topic {
val topicBuilder = topic.toBuilder()
if (topicProgress.storyProgressMap.isNotEmpty()) {
topic.storyList.forEachIndexed { storyIndex, storySummary ->
val updatedStorySummary =
if (topicProgress.storyProgressMap.containsKey(storySummary.storyId)) {
combineStorySummaryAndStoryProgress(
storySummary,
topicProgress.storyProgressMap[storySummary.storyId]!!
)
} else {
setFirstChapterAsNotStarted(storySummary)
}
topicBuilder.setStory(storyIndex, updatedStorySummary)
}
} else {
topic.storyList.forEachIndexed { storyIndex, storySummary ->
val updatedStorySummary = setFirstChapterAsNotStarted(storySummary)
topicBuilder.setStory(storyIndex, updatedStorySummary)
}
}
return topicBuilder.build()
}
/** Combines the specified story-summary without progress and story-progress into a new topic. */
private fun combineStorySummaryAndStoryProgress(
storySummary: StorySummary,
storyProgress: StoryProgress
): StorySummary {
if (storyProgress.chapterProgressMap.isNotEmpty()) {
val storyBuilder = storySummary.toBuilder()
storySummary.chapterList.forEachIndexed { chapterIndex, chapterSummary ->
if (storyProgress.chapterProgressMap.containsKey(chapterSummary.explorationId)) {
val chapterBuilder = chapterSummary.toBuilder()
chapterBuilder.chapterPlayState =
storyProgress.chapterProgressMap[chapterSummary.explorationId]!!.chapterPlayState
storyBuilder.setChapter(chapterIndex, chapterBuilder)
} else {
if (storyBuilder.getChapter(chapterIndex - 1).chapterPlayState ==
ChapterPlayState.COMPLETED
) {
val chapterBuilder = chapterSummary.toBuilder()
chapterBuilder.chapterPlayState = ChapterPlayState.NOT_STARTED
storyBuilder.setChapter(chapterIndex, chapterBuilder)
} else {
val chapterBuilder = chapterSummary.toBuilder()
chapterBuilder.chapterPlayState = ChapterPlayState.NOT_PLAYABLE_MISSING_PREREQUISITES
storyBuilder.setChapter(chapterIndex, chapterBuilder)
}
}
}
return storyBuilder.build()
} else {
return setFirstChapterAsNotStarted(storySummary)
}
}
// TODO(#21): Expose this as a data provider, or omit if it's not needed.
internal fun retrieveTopic(topicId: String): Topic {
return createTopicFromJson(topicId)
}
internal fun retrieveStory(topicId: String, storyId: String): StorySummary {
return createStorySummaryFromJson(topicId, storyId)
}
// TODO(#45): Expose this as a data provider, or omit if it's not needed.
private fun retrieveReviewCard(topicId: String, subtopicId: Int): RevisionCard {
return revisionCardRetriever.loadRevisionCard(topicId, subtopicId)
}
// Loads and returns the questions given a list of skill ids.
private fun loadQuestionsForSkillIds(skillIdsList: List<String>): List<Question> {
return questionRetriever.loadQuestions(skillIdsList)
}
/** Helper function for [combineTopicAndTopicProgress] to set first chapter as NOT_STARTED in [StorySummary]. */
private fun setFirstChapterAsNotStarted(storySummary: StorySummary): StorySummary {
return if (storySummary.chapterList.isNotEmpty()) {
val storyBuilder = storySummary.toBuilder()
storySummary.chapterList.forEachIndexed { index, chapterSummary ->
val chapterBuilder = chapterSummary.toBuilder()
chapterBuilder.chapterPlayState = if (index != 0) {
ChapterPlayState.NOT_PLAYABLE_MISSING_PREREQUISITES
} else {
ChapterPlayState.NOT_STARTED
}
storyBuilder.setChapter(index, chapterBuilder)
}
storyBuilder.build()
} else {
storySummary
}
}
/**
* Creates topic from its json representation. The json file is expected to have
* a key called 'topic' that holds the topic data.
*/
private fun createTopicFromJson(topicId: String): Topic {
val topicData = jsonAssetRetriever.loadJsonFromAsset("$topicId.json")!!
val subtopicList: List<Subtopic> =
createSubtopicListFromJsonArray(topicData.optJSONArray("subtopics"))
val storySummaryList: List<StorySummary> =
createStorySummaryListFromJsonArray(topicId, topicData.optJSONArray("canonical_story_dicts"))
return Topic.newBuilder()
.setTopicId(topicId)
.setName(topicData.getString("topic_name"))
.setDescription(topicData.getString("topic_description"))
.addAllStory(storySummaryList)
.setTopicThumbnail(createTopicThumbnail(topicData))
.setDiskSizeBytes(computeTopicSizeBytes(getAssetFileNameList(topicId)))
.addAllSubtopic(subtopicList)
.build()
}
/**
* Creates the subtopic list of a topic from its json representation. The json file is expected to have
* a key called 'subtopic' that contains an array of skill Ids,subtopic_id and title.
*/
private fun createSubtopicListFromJsonArray(subtopicJsonArray: JSONArray?): List<Subtopic> {
val subtopicList = mutableListOf<Subtopic>()
for (i in 0 until subtopicJsonArray!!.length()) {
val skillIdList = ArrayList<String>()
val currentSubtopicJsonObject = subtopicJsonArray.optJSONObject(i)
val skillJsonArray = currentSubtopicJsonObject.optJSONArray("skill_ids")
for (j in 0 until skillJsonArray.length()) {
skillIdList.add(skillJsonArray.optString(j))
}
val subtopic = Subtopic.newBuilder()
.setSubtopicId(currentSubtopicJsonObject.optInt("id"))
.setTitle(currentSubtopicJsonObject.optString("title"))
.setSubtopicThumbnail(
createSubtopicThumbnail(currentSubtopicJsonObject)
)
.addAllSkillIds(skillIdList).build()
subtopicList.add(subtopic)
}
return subtopicList
}
private fun computeTopicSizeBytes(constituentFiles: List<String>): Long {
// TODO(#169): Compute this based on protos & the combined topic package.
// TODO(#386): Incorporate audio & image files in this computation.
return constituentFiles.map(jsonAssetRetriever::getAssetSize).map(Int::toLong)
.reduceRight(Long::plus)
}
internal fun getAssetFileNameList(topicId: String): List<String> {
val assetFileNameList = mutableListOf<String>()
assetFileNameList.add("questions.json")
assetFileNameList.add("skills.json")
assetFileNameList.add("$topicId.json")
val topicJsonObject = jsonAssetRetriever
.loadJsonFromAsset("$topicId.json")!!
val storySummaryJsonArray = topicJsonObject
.optJSONArray("canonical_story_dicts")
for (i in 0 until storySummaryJsonArray.length()) {
val storySummaryJsonObject = storySummaryJsonArray.optJSONObject(i)
val storyId = storySummaryJsonObject.optString("id")
assetFileNameList.add("$storyId.json")
val storyJsonObject = jsonAssetRetriever
.loadJsonFromAsset("$storyId.json")!!
val storyNodeJsonArray = storyJsonObject.optJSONArray("story_nodes")
for (j in 0 until storyNodeJsonArray.length()) {
val storyNodeJsonObject = storyNodeJsonArray.optJSONObject(j)
val explorationId = storyNodeJsonObject.optString("exploration_id")
assetFileNameList.add("$explorationId.json")
}
}
val subtopicJsonArray = topicJsonObject.optJSONArray("subtopics")
for (i in 0 until subtopicJsonArray.length()) {
val subtopicJsonObject = subtopicJsonArray.optJSONObject(i)
val subtopicId = subtopicJsonObject.optInt("id")
assetFileNameList.add(topicId + "_" + subtopicId + ".json")
}
return assetFileNameList
}
/**
* Creates a list of [StorySummary]s for topic from its json representation. The json file is expected to have
* a key called 'canonical_story_dicts' that contains an array of story objects.
*/
private fun createStorySummaryListFromJsonArray(
topicId: String,
storySummaryJsonArray: JSONArray?
): List<StorySummary> {
val storySummaryList = mutableListOf<StorySummary>()
for (i in 0 until storySummaryJsonArray!!.length()) {
val currentStorySummaryJsonObject = storySummaryJsonArray.optJSONObject(i)
val storySummary: StorySummary =
createStorySummaryFromJson(topicId, currentStorySummaryJsonObject.optString("id"))
storySummaryList.add(storySummary)
}
return storySummaryList
}
/** Creates a list of [StorySummary]s for topic given its json representation and the index of the story in json. */
private fun createStorySummaryFromJson(topicId: String, storyId: String): StorySummary {
val storyDataJsonObject = jsonAssetRetriever.loadJsonFromAsset("$storyId.json")
return StorySummary.newBuilder()
.setStoryId(storyId)
.setStoryName(storyDataJsonObject?.optString("story_title"))
.setStoryThumbnail(createStoryThumbnail(topicId, storyId))
.addAllChapter(
createChaptersFromJson(
storyDataJsonObject!!.optJSONArray("story_nodes")
)
)
.build()
}
private fun createChaptersFromJson(chapterData: JSONArray): List<ChapterSummary> {
val chapterList = mutableListOf<ChapterSummary>()
for (i in 0 until chapterData.length()) {
val chapter = chapterData.getJSONObject(i)
val explorationId = chapter.getString("exploration_id")
chapterList.add(
ChapterSummary.newBuilder()
.setExplorationId(explorationId)
.setName(chapter.getString("title"))
.setSummary(chapter.getString("outline"))
.setChapterPlayState(ChapterPlayState.COMPLETION_STATUS_UNSPECIFIED)
.setChapterThumbnail(createChapterThumbnail(chapter))
.build()
)
}
return chapterList
}
private fun createStoryThumbnail(topicId: String, storyId: String): LessonThumbnail {
val topicJsonObject = jsonAssetRetriever.loadJsonFromAsset("$topicId.json")!!
val storyData = topicJsonObject.getJSONArray("canonical_story_dicts")
var thumbnailBgColor = ""
var thumbnailFilename = ""
for (i in 0 until storyData.length()) {
val storyJsonObject = storyData.getJSONObject(i)
if (storyId == storyJsonObject.optString("id")) {
thumbnailBgColor = storyJsonObject.optString("thumbnail_bg_color")
thumbnailFilename = storyJsonObject.optString("thumbnail_filename")
}
}
return if (thumbnailFilename.isNotEmpty() && thumbnailBgColor.isNotEmpty()) {
LessonThumbnail.newBuilder()
.setThumbnailFilename(thumbnailFilename)
.setBackgroundColorRgb(Color.parseColor(thumbnailBgColor))
.build()
} else if (STORY_THUMBNAILS.containsKey(storyId)) {
STORY_THUMBNAILS.getValue(storyId)
} else {
createDefaultStoryThumbnail()
}
}
private fun createChapterThumbnail(chapterJsonObject: JSONObject): LessonThumbnail {
val explorationId = chapterJsonObject.optString("exploration_id")
val thumbnailBgColor = chapterJsonObject
.optString("thumbnail_bg_color")
val thumbnailFilename = chapterJsonObject
.optString("thumbnail_filename")
return if (thumbnailFilename.isNotEmpty() && thumbnailBgColor.isNotEmpty()) {
LessonThumbnail.newBuilder()
.setThumbnailFilename(thumbnailFilename)
.setBackgroundColorRgb(Color.parseColor(thumbnailBgColor))
.build()
} else if (EXPLORATION_THUMBNAILS.containsKey(explorationId)) {
EXPLORATION_THUMBNAILS.getValue(explorationId)
} else {
createDefaultChapterThumbnail()
}
}
private fun createDefaultChapterThumbnail(): LessonThumbnail {
return LessonThumbnail.newBuilder()
.setThumbnailGraphic(LessonThumbnailGraphic.BAKER)
.setBackgroundColorRgb(0xd325ec)
.build()
}
private fun createSubtopicThumbnail(subtopicJsonObject: JSONObject): LessonThumbnail {
val subtopicId = subtopicJsonObject.optInt("id")
val thumbnailBgColor = subtopicJsonObject.optString("thumbnail_bg_color")
val thumbnailFilename = subtopicJsonObject.optString("thumbnail_filename")
return if (thumbnailFilename.isNotEmpty() && thumbnailBgColor.isNotEmpty()) {
LessonThumbnail.newBuilder()
.setThumbnailFilename(thumbnailFilename)
.setBackgroundColorRgb(Color.parseColor(thumbnailBgColor))
.build()
} else {
createSubtopicThumbnail(subtopicId)
}
}
private fun createSubtopicThumbnail(subtopicId: Int): LessonThumbnail {
return when (subtopicId) {
FRACTIONS_SUBTOPIC_ID_1 ->
LessonThumbnail.newBuilder()
.setThumbnailGraphic(LessonThumbnailGraphic.WHAT_IS_A_FRACTION)
.setBackgroundColorRgb(Color.parseColor(SUBTOPIC_BG_COLOR))
.build()
FRACTIONS_SUBTOPIC_ID_2 ->
LessonThumbnail.newBuilder()
.setThumbnailGraphic(LessonThumbnailGraphic.FRACTION_OF_A_GROUP)
.setBackgroundColorRgb(Color.parseColor(SUBTOPIC_BG_COLOR))
.build()
FRACTIONS_SUBTOPIC_ID_3 ->
LessonThumbnail.newBuilder()
.setThumbnailGraphic(LessonThumbnailGraphic.MIXED_NUMBERS)
.setBackgroundColorRgb(Color.parseColor(SUBTOPIC_BG_COLOR))
.build()
FRACTIONS_SUBTOPIC_ID_4 ->
LessonThumbnail.newBuilder()
.setThumbnailGraphic(LessonThumbnailGraphic.ADDING_FRACTIONS)
.setBackgroundColorRgb(Color.parseColor(SUBTOPIC_BG_COLOR))
.build()
else ->
LessonThumbnail.newBuilder()
.setThumbnailGraphic(LessonThumbnailGraphic.THE_NUMBER_LINE)
.setBackgroundColorRgb(Color.parseColor(SUBTOPIC_BG_COLOR))
.build()
}
}
}
| 0 | Kotlin | 0 | 0 | cb45e456caf79d5612ca4c28d8ef3bf1c25e5965 | 26,015 | oppia-android | Apache License 2.0 |
tongs-plugin-android/src/main/java/com/github/tarcv/tongs/runner/TongsRemoteAndroidTestRunner.kt | engeniousio | 262,129,936 | false | null | /*
* Copyright 2020 TarCV
*
* 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.github.tarcv.tongs.runner
import com.android.ddmlib.IShellEnabledDevice
import com.android.ddmlib.IShellOutputReceiver
import com.android.ddmlib.testrunner.ITestRunListener
import com.android.ddmlib.testrunner.InstrumentationResultParser
import com.android.ddmlib.testrunner.RemoteAndroidTestRunner
class TongsRemoteAndroidTestRunner(
packageName: String,
runnerName: String,
remoteDevice: IShellEnabledDevice
) : RemoteAndroidTestRunner(packageName, runnerName, remoteDevice) {
override fun createParser(runName: String, listeners: MutableCollection<ITestRunListener>): InstrumentationResultParser {
return TongsInstrumentationResultParser(runName, listeners)
}
} | 1 | HTML | 2 | 3 | da5ee89d7509f66fe58468eb30e03dd05a1b89c9 | 1,285 | sift-android | Apache License 2.0 |
app/src/main/java/com/pebbles/obsidiancompanion/OCWidgetReceiver.kt | pebblesoft | 547,498,004 | false | {"Kotlin": 6352} | package com.pebbles.obsidiancompanion
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetReceiver
class OCWidgetReceiver: GlanceAppWidgetReceiver() {
override val glanceAppWidget: GlanceAppWidget = OCWidget()
} | 0 | Kotlin | 0 | 0 | d7bdc63568535730bfec7b3645efb270354a1ef5 | 262 | obsidian-viewer | MIT License |
skelegro-hcl/src/main/kotlin/io/bkbn/skelegro/hcl/utils/FunctionCall.kt | bkbnio | 347,669,652 | false | null | package io.bkbn.skelegro.gradle.utils
class FunctionCall(private val name: String) {
var arguments: List<Any> = emptyList()
fun withArguments(vararg args: Any): FunctionCall {
arguments = args.toList()
return this
}
override fun toString(): String {
val guts = arguments.joinToString(", ") { arg ->
when (arg) {
is String -> "\"$arg\""
else -> arg.toString()
}
}
return "$name($guts)"
}
}
| 4 | Kotlin | 0 | 0 | 7a878d62db9e4e3ef41adc40c7360f38c0aa142e | 451 | skelegro | MIT License |
fetch2/src/main/java/com/tonyodev/fetch2/downloader/ParallelFileDownloaderImpl.kt | arifbillah786 | 461,008,171 | false | {"Java": 1164327, "Kotlin": 411546} | package com.tonyodev.fetch2.downloader
import com.tonyodev.fetch2.Download
import com.tonyodev.fetch2core.Downloader
import com.tonyodev.fetch2.Error
import com.tonyodev.fetch2core.Logger
import com.tonyodev.fetch2.exception.FetchException
import com.tonyodev.fetch2.getErrorFromThrowable
import com.tonyodev.fetch2.provider.NetworkInfoProvider
import com.tonyodev.fetch2.util.*
import com.tonyodev.fetch2core.*
import java.io.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlin.math.ceil
class ParallelFileDownloaderImpl(private val initialDownload: Download,
private val downloader: Downloader,
private val progressReportingIntervalMillis: Long,
private val downloadBufferSizeBytes: Int,
private val logger: Logger,
private val networkInfoProvider: NetworkInfoProvider,
private val retryOnNetworkGain: Boolean,
private val fileTempDir: String,
private val md5CheckingEnabled: Boolean) : FileDownloader {
@Volatile
override var interrupted = false
@Volatile
override var terminated = false
@Volatile
override var completedDownload = false
override var delegate: FileDownloader.Delegate? = null
private var downloadInfo = initialDownload.toDownloadInfo()
override val download: Download
get () {
downloadInfo.downloaded = downloaded
downloadInfo.total = total
return downloadInfo
}
@Volatile
private var downloaded = 0L
private var total = -1L
private var averageDownloadedBytesPerSecond = 0.0
private val movingAverageCalculator = AverageCalculator(5)
private var estimatedTimeRemainingInMilliseconds: Long = -1
private var executorService: ExecutorService? = null
@Volatile
private var actionsCounter = 0
private var actionsTotal = 0
private val lock = Object()
@Volatile
private var throwable: Throwable? = null
private var fileSlices = emptyList<FileSlice>()
private var outputStream: OutputStream? = null
private var randomAccessFileOutput: RandomAccessFile? = null
private var totalDownloadBlocks = 0
override fun run() {
var openingResponse: Downloader.Response? = null
try {
val openingRequest = getRequestForDownload(initialDownload, HEAD_REQUEST_METHOD)
openingResponse = downloader.execute(openingRequest, interruptMonitor)
if (!interrupted && !terminated && openingResponse?.isSuccessful == true) {
total = openingResponse.contentLength
if (total > 0) {
fileSlices = getFileSliceList(openingResponse.acceptsRanges, openingRequest)
totalDownloadBlocks = fileSlices.size
try {
downloader.disconnect(openingResponse)
} catch (e: Exception) {
logger.e("FileDownloader", e)
}
val sliceFileDownloadsList = fileSlices.filter { !it.isDownloaded }
if (!interrupted && !terminated) {
downloadInfo.downloaded = downloaded
downloadInfo.total = total
delegate?.onStarted(
download = downloadInfo,
etaInMilliseconds = estimatedTimeRemainingInMilliseconds,
downloadedBytesPerSecond = getAverageDownloadedBytesPerSecond())
fileSlices.forEach {
val downloadBlock = DownloadBlockInfo()
downloadBlock.downloadId = it.id
downloadBlock.blockPosition = it.position
downloadBlock.downloadedBytes = it.downloaded
downloadBlock.startByte = it.startBytes
downloadBlock.endByte = it.endBytes
delegate?.onDownloadBlockUpdated(downloadInfo, downloadBlock, totalDownloadBlocks)
}
if (sliceFileDownloadsList.isNotEmpty()) {
executorService = Executors.newFixedThreadPool(sliceFileDownloadsList.size)
}
downloadSliceFiles(openingRequest, sliceFileDownloadsList)
waitAndPerformProgressReporting()
downloadInfo.downloaded = downloaded
downloadInfo.total = total
if (!interrupted && !terminated) {
var fileSlicesTotal = 0L
fileSlices.forEach {
fileSlicesTotal += it.downloaded
}
if (fileSlicesTotal != total) {
throwable = FetchException(DOWNLOAD_INCOMPLETE, FetchException.Code.DOWNLOAD_INCOMPLETE)
}
throwExceptionIfFound()
completedDownload = true
if (md5CheckingEnabled) {
if (downloader.verifyContentMD5(openingResponse.request, openingResponse.md5)) {
delegate?.onProgress(
download = downloadInfo,
etaInMilliSeconds = estimatedTimeRemainingInMilliseconds,
downloadedBytesPerSecond = getAverageDownloadedBytesPerSecond())
delegate?.onComplete(
download = downloadInfo)
} else {
throw FetchException(INVALID_CONTENT_MD5, FetchException.Code.INVALID_CONTENT_MD5)
}
} else {
delegate?.onProgress(
download = downloadInfo,
etaInMilliSeconds = estimatedTimeRemainingInMilliseconds,
downloadedBytesPerSecond = getAverageDownloadedBytesPerSecond())
delegate?.onComplete(
download = downloadInfo)
}
}
if (!completedDownload) {
downloadInfo.downloaded = downloaded
downloadInfo.total = total
if (!terminated) {
delegate?.saveDownloadProgress(downloadInfo)
delegate?.onProgress(
download = downloadInfo,
etaInMilliSeconds = estimatedTimeRemainingInMilliseconds,
downloadedBytesPerSecond = getAverageDownloadedBytesPerSecond())
}
}
}
} else {
throw FetchException(EMPTY_RESPONSE_BODY,
FetchException.Code.EMPTY_RESPONSE_BODY)
}
} else if (openingResponse == null && !interrupted && !terminated) {
throw FetchException(EMPTY_RESPONSE_BODY,
FetchException.Code.EMPTY_RESPONSE_BODY)
} else if (openingResponse?.isSuccessful == false && !interrupted && !terminated) {
throw FetchException(RESPONSE_NOT_SUCCESSFUL,
FetchException.Code.REQUEST_NOT_SUCCESSFUL)
} else if (!interrupted && !terminated) {
throw FetchException(UNKNOWN_ERROR,
FetchException.Code.UNKNOWN)
}
} catch (e: Exception) {
if (!interrupted && !terminated) {
logger.e("FileDownloader", e)
var error = getErrorFromThrowable(e)
error.throwable = e
if (retryOnNetworkGain) {
var disconnectDetected = !networkInfoProvider.isNetworkAvailable
for (i in 1..10) {
try {
Thread.sleep(500)
} catch (e: InterruptedException) {
logger.e("FileDownloader", e)
break
}
if (!networkInfoProvider.isNetworkAvailable) {
disconnectDetected = true
break
}
}
if (disconnectDetected) {
error = Error.NO_NETWORK_CONNECTION
}
}
downloadInfo.downloaded = downloaded
downloadInfo.total = total
downloadInfo.error = error
if (!terminated) {
delegate?.onError(download = downloadInfo)
}
}
} finally {
try {
executorService?.shutdown()
} catch (e: Exception) {
logger.e("FileDownloader", e)
}
try {
randomAccessFileOutput?.close()
} catch (e: Exception) {
logger.e("FileDownloader", e)
}
try {
outputStream?.close()
} catch (e: Exception) {
logger.e("FileDownloader", e)
}
if (openingResponse != null) {
try {
downloader.disconnect(openingResponse)
} catch (e: Exception) {
logger.e("FileDownloader", e)
}
}
terminated = true
}
}
private fun getFileSliceList(acceptsRanges: Boolean, request: Downloader.ServerRequest): List<FileSlice> {
val file = getFile(downloadInfo.file)
if (!file.exists()) {
deleteAllTempFiles()
}
val previousSliceSize = getPreviousSliceCount(downloadInfo.id, fileTempDir)
return if (acceptsRanges) {
val fileSliceInfo = getChuckInfo(request)
if (previousSliceSize != fileSliceInfo.slicingCount) {
deleteAllTempFiles()
}
saveCurrentSliceCount(downloadInfo.id, fileSliceInfo.slicingCount, fileTempDir)
var counterBytes = 0L
val fileSlices = mutableListOf<FileSlice>()
for (position in 1..fileSliceInfo.slicingCount) {
if (!interrupted && !terminated) {
val startBytes = counterBytes
val endBytes = if (fileSliceInfo.slicingCount == position) {
total
} else {
counterBytes + fileSliceInfo.bytesPerFileSlice
}
counterBytes = endBytes
val fileSlice = FileSlice(
id = downloadInfo.id,
position = position,
startBytes = startBytes,
endBytes = endBytes,
downloaded = getSavedDownloadedInfo(downloadInfo.id, position, fileTempDir)
)
downloaded += fileSlice.downloaded
fileSlices.add(fileSlice)
} else {
break
}
}
fileSlices
} else {
if (previousSliceSize != 1) {
deleteAllTempFiles()
}
saveCurrentSliceCount(downloadInfo.id, 1, fileTempDir)
val fileSlice = FileSlice(
id = downloadInfo.id,
position = 1,
startBytes = 0,
endBytes = total,
downloaded = getSavedDownloadedInfo(downloadInfo.id, 1, fileTempDir))
downloaded += fileSlice.downloaded
listOf(fileSlice)
}
}
private fun getChuckInfo(request: Downloader.ServerRequest): FileSliceInfo {
val fileSliceSize = downloader.getFileSlicingCount(request, total)
?: DEFAULT_FILE_SLICE_NO_LIMIT_SET
return getFileSliceInfo(fileSliceSize, total)
}
private fun getAverageDownloadedBytesPerSecond(): Long {
if (averageDownloadedBytesPerSecond < 1) {
return 0L
}
return ceil(averageDownloadedBytesPerSecond).toLong()
}
private fun waitAndPerformProgressReporting() {
var reportingStopTime: Long
var downloadSpeedStopTime: Long
var downloadedBytesPerSecond = downloaded
var reportingStartTime = System.nanoTime()
var downloadSpeedStartTime = System.nanoTime()
while (actionsCounter != actionsTotal && !interrupted && !terminated) {
downloadInfo.downloaded = downloaded
downloadInfo.total = total
downloadSpeedStopTime = System.nanoTime()
val downloadSpeedCheckTimeElapsed = hasIntervalTimeElapsed(downloadSpeedStartTime,
downloadSpeedStopTime, DEFAULT_DOWNLOAD_SPEED_REPORTING_INTERVAL_IN_MILLISECONDS)
if (downloadSpeedCheckTimeElapsed) {
downloadedBytesPerSecond = downloaded - downloadedBytesPerSecond
movingAverageCalculator.add(downloadedBytesPerSecond.toDouble())
averageDownloadedBytesPerSecond =
movingAverageCalculator.getMovingAverageWithWeightOnRecentValues()
estimatedTimeRemainingInMilliseconds = calculateEstimatedTimeRemainingInMilliseconds(
downloadedBytes = downloaded,
totalBytes = total,
downloadedBytesPerSecond = getAverageDownloadedBytesPerSecond())
downloadedBytesPerSecond = downloaded
if (progressReportingIntervalMillis > DEFAULT_DOWNLOAD_SPEED_REPORTING_INTERVAL_IN_MILLISECONDS) {
delegate?.saveDownloadProgress(downloadInfo)
}
}
reportingStopTime = System.nanoTime()
val hasReportingTimeElapsed = hasIntervalTimeElapsed(reportingStartTime,
reportingStopTime, progressReportingIntervalMillis)
if (hasReportingTimeElapsed) {
if (progressReportingIntervalMillis <= DEFAULT_DOWNLOAD_SPEED_REPORTING_INTERVAL_IN_MILLISECONDS) {
delegate?.saveDownloadProgress(downloadInfo)
}
if (!terminated) {
delegate?.onProgress(
download = downloadInfo,
etaInMilliSeconds = estimatedTimeRemainingInMilliseconds,
downloadedBytesPerSecond = getAverageDownloadedBytesPerSecond())
}
reportingStartTime = System.nanoTime()
}
if (downloadSpeedCheckTimeElapsed) {
downloadSpeedStartTime = System.nanoTime()
}
}
}
private fun downloadSliceFiles(request: Downloader.ServerRequest, fileSlicesDownloadsList: List<FileSlice>) {
actionsCounter = 0
actionsTotal = fileSlicesDownloadsList.size
outputStream = downloader.getRequestOutputStream(request, 0)
if (outputStream == null) {
randomAccessFileOutput = RandomAccessFile(downloadInfo.file, "rw")
randomAccessFileOutput?.seek(0)
}
for (fileSlice in fileSlicesDownloadsList) {
if (!interrupted && !terminated) {
executorService?.execute {
val downloadBlock = DownloadBlockInfo()
downloadBlock.downloadId = fileSlice.id
downloadBlock.blockPosition = fileSlice.position
downloadBlock.downloadedBytes = fileSlice.downloaded
downloadBlock.startByte = fileSlice.startBytes
downloadBlock.endByte = fileSlice.endBytes
val downloadRequest = getRequestForDownload(downloadInfo, fileSlice.startBytes + fileSlice.downloaded)
var downloadResponse: Downloader.Response? = null
try {
downloadResponse = downloader.execute(downloadRequest, interruptMonitor)
if (!terminated && !interrupted && downloadResponse?.isSuccessful == true) {
var reportingStopTime: Long
val buffer = ByteArray(downloadBufferSizeBytes)
var read: Int = downloadResponse.byteStream?.read(buffer, 0, downloadBufferSizeBytes)
?: -1
var remainderBytes: Long = fileSlice.endBytes - (fileSlice.startBytes + fileSlice.downloaded)
var reportingStartTime = System.nanoTime()
var streamBytes: Int
var seekPosition: Long
while (remainderBytes > 0L && read != -1 && !interrupted && !terminated) {
streamBytes = if (read <= remainderBytes) {
read
} else {
read = -1
remainderBytes.toInt()
}
seekPosition = fileSlice.startBytes + fileSlice.downloaded
synchronized(lock) {
if (!interrupted && !terminated) {
val outputStream = outputStream
if (outputStream != null) {
downloader.seekOutputStreamToPosition(request, outputStream, seekPosition)
outputStream.write(buffer, 0, streamBytes)
} else {
randomAccessFileOutput?.seek(seekPosition)
randomAccessFileOutput?.write(buffer, 0, streamBytes)
}
fileSlice.downloaded += streamBytes
downloaded += streamBytes
}
}
if (!interrupted && !terminated) {
reportingStopTime = System.nanoTime()
val hasReportingTimeElapsed = hasIntervalTimeElapsed(reportingStartTime,
reportingStopTime, DEFAULT_DOWNLOAD_SPEED_REPORTING_INTERVAL_IN_MILLISECONDS)
if (hasReportingTimeElapsed) {
saveDownloadedInfo(fileSlice.id, fileSlice.position, fileSlice.downloaded, fileTempDir)
downloadBlock.downloadedBytes = fileSlice.downloaded
delegate?.onDownloadBlockUpdated(downloadInfo, downloadBlock, totalDownloadBlocks)
reportingStartTime = System.nanoTime()
}
if (read != -1) {
read = downloadResponse.byteStream?.read(buffer, 0, downloadBufferSizeBytes) ?: -1
remainderBytes = fileSlice.endBytes - (fileSlice.startBytes + fileSlice.downloaded)
}
}
}
saveDownloadedInfo(fileSlice.id, fileSlice.position, fileSlice.downloaded, fileTempDir)
downloadBlock.downloadedBytes = fileSlice.downloaded
delegate?.onDownloadBlockUpdated(downloadInfo, downloadBlock, totalDownloadBlocks)
} else if (downloadResponse == null && !interrupted && !terminated) {
throw FetchException(EMPTY_RESPONSE_BODY,
FetchException.Code.EMPTY_RESPONSE_BODY)
} else if (downloadResponse?.isSuccessful == false && !interrupted && !terminated) {
throw FetchException(RESPONSE_NOT_SUCCESSFUL,
FetchException.Code.REQUEST_NOT_SUCCESSFUL)
} else if (!interrupted && !terminated) {
throw FetchException(UNKNOWN_ERROR,
FetchException.Code.UNKNOWN)
}
} catch (e: Exception) {
throwable = e
} finally {
try {
if (downloadResponse != null) {
downloader.disconnect(downloadResponse)
}
} catch (e: Exception) {
logger.e("FileDownloader", e)
}
incrementActionCompletedCount()
}
}
}
}
}
private fun deleteAllTempFiles() {
try {
for (fileSlice in fileSlices) {
deleteTempFile(fileSlice.id, fileSlice.position, fileTempDir)
}
deleteMetaFile(downloadInfo.id, fileTempDir)
} catch (e: Exception) {
}
}
private fun incrementActionCompletedCount() {
synchronized(lock) {
actionsCounter += 1
}
}
private val interruptMonitor = object : InterruptMonitor {
override val isInterrupted: Boolean
get() {
return interrupted
}
}
private fun throwExceptionIfFound() {
val exception = throwable
if (exception != null) {
throw exception
}
}
} | 0 | Java | 0 | 0 | 4c189f48b30a7cc1de6bba0eaa70de6cb7698bc4 | 22,669 | Fetch | Apache License 2.0 |
betfair/src/main/kotlin/com/prince/betfair/betfair/betting/entities/event/Event.kt | rinkledink | 359,216,810 | false | null | package com.prince.betfair.betfair.betting.entities.event
import java.util.*
/**
* Event
*
* @property id: The unique id for the event
* @property name: The name of the event
* @property countryCode: The ISO-2 code for the event. A list of ISO-2 codes is available via
* http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
* @property timezone: This is timezone in which the event is taking place.
* @property venue: venue
* @property openDate: The scheduled start date and time of the event. This is Europe/London (GMT) by default
*/
data class Event(
val id: String?,
val name: String?,
val countryCode: String?,
val timezone: String?,
val venue: String?,
val openDate: Date?
)
| 0 | Kotlin | 0 | 0 | 41a78b8bb8d20fc8567290b986b06017caeb83bc | 713 | Kotlin-Betfair-API | MIT License |
src/main/java/org/runestar/cs2/dfa/Phase.kt | PhraZier | 182,278,555 | true | {"Kotlin": 114301, "Java": 19324} | package org.runestar.cs2.dfa
import org.runestar.cs2.ir.Func
internal interface Phase {
fun transform(func: Func)
class Composite(private vararg val ps: Phase) : Phase {
override fun transform(func: Func) = ps.forEach { it.transform(func) }
}
companion object {
val DEFAULT = Composite(
RemoveIdentityOperations,
DeleteNops,
MergeSingleStackDefs,
MergeMultiStackDefs,
AddShortCircuitOperators,
PropagateTypes
)
}
} | 0 | Kotlin | 0 | 0 | e0f04ef4943d93bf6e42d016f1b28a8e166fb5da | 560 | cs2 | MIT License |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/HomeCog.kt | walter-juan | 868,046,028 | false | null | package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
public val OutlineGroup.HomeCog: ImageVector
get() {
if (_homeCog != null) {
return _homeCog!!
}
_homeCog = Builder(name = "HomeCog", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(9.0f, 21.0f)
verticalLineToRelative(-6.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f)
horizontalLineToRelative(1.6f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(20.0f, 11.0f)
lineToRelative(-8.0f, -8.0f)
lineToRelative(-9.0f, 9.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(7.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 2.0f, 2.0f)
horizontalLineToRelative(4.159f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(18.0f, 18.0f)
moveToRelative(-2.0f, 0.0f)
arcToRelative(2.0f, 2.0f, 0.0f, true, false, 4.0f, 0.0f)
arcToRelative(2.0f, 2.0f, 0.0f, true, false, -4.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(18.0f, 14.5f)
verticalLineToRelative(1.5f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(18.0f, 20.0f)
verticalLineToRelative(1.5f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(21.032f, 16.25f)
lineToRelative(-1.299f, 0.75f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(16.27f, 19.0f)
lineToRelative(-1.3f, 0.75f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(14.97f, 16.25f)
lineToRelative(1.3f, 0.75f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(19.733f, 19.0f)
lineToRelative(1.3f, 0.75f)
}
}
.build()
return _homeCog!!
}
private var _homeCog: ImageVector? = null
| 0 | null | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 4,986 | compose-icon-collections | MIT License |
agp-7.1.0-alpha01/tools/base/wizard/template-impl/src/com/android/tools/idea/wizard/template/impl/fragments/googleMapsFragment/src/app_package/mapFragmentKt.kt | jomof | 502,039,754 | false | {"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277} | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.wizard.template.impl.fragments.googleMapsFragment.src.app_package
import com.android.tools.idea.wizard.template.getMaterialComponentName
import com.android.tools.idea.wizard.template.escapeKotlinIdentifier
fun mapFragmentKt(
fragmentClass: String,
layoutName: String,
packageName: String,
useAndroidX: Boolean
) = """
package ${escapeKotlinIdentifier(packageName)}
import ${getMaterialComponentName("android.support.v4.app.Fragment", useAndroidX)}
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
class ${fragmentClass} : Fragment() {
private val callback = OnMapReadyCallback { googleMap ->
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
* In this case, we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to
* install it inside the SupportMapFragment. This method will only be triggered once the
* user has installed Google Play services and returned to the app.
*/
val sydney = LatLng(-34.0, 151.0)
googleMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.${layoutName}, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(callback)
}
}"""
| 1 | Java | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 2,952 | CppBuildCacheWorkInProgress | Apache License 2.0 |
src/main/kotlin/com/github/ryarnyah/querydsl/GenericExporterTask.kt | ryarnyah | 325,814,306 | false | null | package com.github.ryarnyah.querydsl
open class GenericExporterTask: AbstractExporterTask() {
} | 0 | Kotlin | 0 | 1 | 254f9cecbde5e345e9cabee53df575460a712808 | 96 | querydsl-gradle-plugin | Apache License 2.0 |
shared/src/jsMain/kotlin/com/github/jetbrains/rssreader/core/JsHttpClient.kt | Kotlin | 295,411,072 | false | null | package com.github.jetbrains.rssreader.core
import io.github.aakira.napier.Napier
import io.ktor.client.*
import io.ktor.client.engine.js.*
import io.ktor.client.plugins.logging.*
internal fun jsHttpClient(withLog: Boolean) = HttpClient(Js) {
if (withLog) install(Logging) {
level = LogLevel.HEADERS
logger = object : Logger {
override fun log(message: String) {
Napier.v(tag = "JsHttpClient", message = message)
}
}
}
}
| 6 | Kotlin | 95 | 1,031 | 2d222864bcd5ab27139f1bc0a0a747e076f33545 | 495 | kmm-production-sample | MIT License |
app/src/main/java/tech/thdev/githubusersearch/view/github/GithubUserFragment.kt | taehwandev | 141,778,287 | false | null | package tech.thdev.githubusersearch.view.github
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_user_search.*
import kotlinx.android.synthetic.main.include_toast_error.view.*
import tech.thdev.githubusersearch.R
import tech.thdev.githubusersearch.data.source.search.GithubSearchRepository
import tech.thdev.githubusersearch.util.adapterScrollLinearLayoutManagerListener
import tech.thdev.githubusersearch.util.autoRelease
import tech.thdev.githubusersearch.util.createErrorToast
import tech.thdev.githubusersearch.util.inject
import tech.thdev.githubusersearch.view.github.adapter.UserRecyclerAdapter
import tech.thdev.githubusersearch.view.github.viewmodel.FilterStatusViewModel
import tech.thdev.githubusersearch.view.github.viewmodel.GithubUserFragmentViewModel
import tech.thdev.githubusersearch.view.github.viewmodel.SearchQueryViewModel
class GithubUserFragment : Fragment() {
private lateinit var githubSearchRepository: GithubSearchRepository
companion object {
private const val KEY_VIEW_TYPE = "key-view-type"
const val VIEW_TYPE_SEARCH = 100
const val VIEW_TYPE_LIKED = 200
fun getInstance(viewType: Int, githubSearchRepository: GithubSearchRepository) =
GithubUserFragment().apply {
this.githubSearchRepository = githubSearchRepository
arguments = Bundle().apply {
putInt(KEY_VIEW_TYPE, viewType)
}
}
}
private val viewType: Int
get() = arguments?.getInt(KEY_VIEW_TYPE) ?: VIEW_TYPE_SEARCH
private val searchQueryViewModel: SearchQueryViewModel by lazy(LazyThreadSafetyMode.NONE) {
SearchQueryViewModel::class.java.inject(requireActivity()) {
SearchQueryViewModel()
}
}
private val filterStatusViewModel: FilterStatusViewModel by lazy(LazyThreadSafetyMode.NONE) {
FilterStatusViewModel::class.java.inject(requireActivity()) {
FilterStatusViewModel()
}
}
private val userRecyclerAdapter: UserRecyclerAdapter by lazy(LazyThreadSafetyMode.NONE) {
UserRecyclerAdapter()
}
private var githubUserFragmentViewModel: GithubUserFragmentViewModel by autoRelease()
private fun showErrorToast(message: String) {
requireContext().createErrorToast {
LayoutInflater.from(requireContext())
.inflate(R.layout.include_toast_error, null).apply {
this.tv_error_toast.text = message
}
}.show()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
inflater.inflate(R.layout.fragment_user_search, container, false)!!
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
showDefaultView()
githubUserFragmentViewModel = GithubUserFragmentViewModel::class.java.inject(this) {
GithubUserFragmentViewModel(
viewType = viewType,
adapterViewModel = userRecyclerAdapter.viewModel,
githubSearchRepository = githubSearchRepository)
}.also {
it.viewInit()
it.loadGithubUser(searchQueryViewModel.prevSearchQuery,
filterStatusViewModel.prevFilterType)
}
viewInit()
searchQueryViewModel.viewInit()
filterStatusViewModel.viewInit()
}
private fun viewInit() {
recycler_view.run {
layoutManager = LinearLayoutManager([email protected]())
if (viewType == VIEW_TYPE_SEARCH) {
addOnScrollListener(adapterScrollListener)
}
adapter = userRecyclerAdapter
}
}
private val adapterScrollListener by lazy(LazyThreadSafetyMode.NONE) {
adapterScrollLinearLayoutManagerListener(githubUserFragmentViewModel::loadMore)
}
private fun FilterStatusViewModel.viewInit() {
updateFilterStatus = githubUserFragmentViewModel::changeFilter
}
private fun SearchQueryViewModel.viewInit() {
updateSearchQuery = githubUserFragmentViewModel::search
updateSearchQueryCommit = {
githubUserFragmentViewModel.run {
initSearchQuerySubject()
search(it)
}
}
}
private fun GithubUserFragmentViewModel.viewInit() {
showEmptyView = {
showDefaultView()
}
hideEmptyView = {
tv_user_message.visibility = View.GONE
}
noSearchItem = {
showErrorToast(getString(R.string.message_no_result_user_name))
showDefaultView()
}
onShowProgress = {
group_loading.visibility = View.VISIBLE
}
onHideProgress = {
group_loading.visibility = View.GONE
}
onShowNetworkError = {
getString(R.string.message_network_error).showErrorView()
}
onShowOtherError = {
(it ?: getString(R.string.message_unknown_error)).showErrorView()
}
}
private fun showDefaultView() {
if (userRecyclerAdapter.itemCount == 0) {
tv_user_message.run {
visibility = View.VISIBLE
setText(R.string.search_hint)
}
}
}
private fun String.showErrorView() {
showErrorToast(this)
if (userRecyclerAdapter.itemCount == 0) {
recycler_view.visibility = View.GONE
tv_user_message.run {
visibility = View.VISIBLE
text = this@showErrorView
}
btn_user_behavior.visibility = View.VISIBLE
btn_user_behavior.setOnClickListener {
recycler_view.visibility = View.VISIBLE
tv_user_message.visibility = View.GONE
btn_user_behavior.visibility = View.GONE
githubUserFragmentViewModel.run {
initSearchQuerySubject()
search(searchQueryViewModel.prevSearchQuery)
}
}
}
}
override fun onDestroy() {
super.onDestroy()
recycler_view?.removeOnScrollListener(adapterScrollListener)
}
}
| 0 | Kotlin | 0 | 5 | 0478ba09e75f9e58d2bc312fdd0ece583a8b1feb | 6,557 | GithubUserSearch | Apache License 2.0 |
src/main/kotlin/me/brightspark/mdcbot/extensions/AutoModerationExtension.kt | thebrightspark | 449,499,586 | false | null | package me.brightspark.mdcbot.extensions
import com.kotlindiscord.kord.extensions.DISCORD_RED
import com.kotlindiscord.kord.extensions.checks.isNotBot
import com.kotlindiscord.kord.extensions.components.components
import com.kotlindiscord.kord.extensions.components.publicButton
import com.kotlindiscord.kord.extensions.events.EventContext
import com.kotlindiscord.kord.extensions.extensions.event
import com.kotlindiscord.kord.extensions.utils.getJumpUrl
import dev.kord.common.entity.ButtonStyle
import dev.kord.common.entity.Permission
import dev.kord.core.behavior.channel.createMessage
import dev.kord.core.entity.Invite
import dev.kord.core.event.message.MessageCreateEvent
import dev.kord.gateway.Intent
import dev.kord.gateway.PrivilegedIntent
import dev.kord.rest.builder.message.create.embed
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import me.brightspark.mdcbot.properties.Property
import mu.KotlinLogging
import org.springframework.stereotype.Component
import java.text.NumberFormat
@Component
class AutoModerationExtension : BaseExtension("auto-moderation") {
companion object {
private val REGEX_INVITE_LINK = Regex("(?:https?://)?discord(?:app)?\\.(?:(?:gg|com)/invite|gg)/(\\w+)")
private val NUM_FORMAT = NumberFormat.getNumberInstance()
}
private val log = KotlinLogging.logger {}
@OptIn(PrivilegedIntent::class)
override suspend fun setup() {
intents(Intent.GuildMessages, Intent.MessageContent)
event<MessageCreateEvent> {
check { isNotBot() }
check { botHasPermissions(Permission.ManageMessages) }
action { handleInviteLinks() }
}
}
private suspend fun EventContext<MessageCreateEvent>.handleInviteLinks() {
val message = event.message
val inviteLinks = REGEX_INVITE_LINK.findAll(message.content)
.map { InviteLinkInfo(it.value, it.groupValues[1]) }
.toList()
if (inviteLinks.isEmpty()) return
val messageAuthor = message.author?.mention
log.info { "Found invite links in message ${message.id}: ${inviteLinks.joinToString { it.code }}" }
message.delete("Message contained ${inviteLinks.size} Discord server invite links")
inviteLinks.map { [email protected] { it.retrieveInvite() } }.joinAll()
val moderatorRole = propertyService.get(Property.ROLE_MODERATOR)?.let { "<@&$it>" } ?: "Moderator"
val logsChannelMention = propertyService.get(Property.CHANNEL_LOGS)?.let { "<#$it>" }
val responseMessage = message.channel.createMessage {
embed {
description = """
A message sent by $messageAuthor has been deleted because it contained Discord server invite links.
A $moderatorRole can use the buttons below to handle this further${logsChannelMention?.let { " (see logs for more info: $it)" } ?: ""}.
""".trimIndent()
color = DISCORD_RED
}
components {
publicButton {
label = "Send Links"
style = ButtonStyle.Primary
check { failIfNot { event.interaction.getMember().isModerator() } }
action {
this.channel.createMessage {
content = """
*Discord server invites originally posted by $messageAuthor:*
${inviteLinks.distinctBy { it.code }.joinToString("\n") { "- ${it.link}" }}
""".trimIndent()
}
this.message.delete()
}
}
publicButton {
label = "Send Original"
style = ButtonStyle.Primary
check { failIfNot { event.interaction.getMember().isModerator() } }
action {
this.channel.createMessage {
content = """
*Message originally posted by $messageAuthor:*
${message.content}
""".trimIndent()
}
this.message.delete()
}
}
publicButton {
label = "Delete"
style = ButtonStyle.Danger
check { failIfNot { event.interaction.getMember().isModerator() } }
action { this.message.delete() }
}
}
}
val invitesString = inviteLinks.distinctBy { it.code }.joinToString("\n") { inviteInfo ->
inviteInfo.invite?.let { invite ->
val sb = StringBuilder()
sb.append("|- ").append(inviteInfo.link).append("\n")
invite.partialGuild?.let { g ->
sb.append("| ").append(g.name).append(" (`").append(g.id).append("`)\n")
sb.append("| Members ~").append(NUM_FORMAT.format(invite.approximateMemberCount))
.append(" (Online ~").append(NUM_FORMAT.format(invite.approximatePresenceCount)).append(")\n")
sb.append("| Channel ").append(invite.channel?.mention)
.append(" (`").append(invite.channelId).append("`)\n")
}
sb.append("| Expiration: ")
invite.expiresAt?.let { sb.append("<t:").append(it.epochSeconds).append(":f>") } ?: sb.append("None")
sb.toString()
} ?: "|- INVALID: ${inviteInfo.link}"
}
loggingService.log(
"""
|Deleted message from $messageAuthor in ${message.channel.mention}:
|${responseMessage.getJumpUrl()}
$invitesString
""".trimMargin("|")
)
}
private inner class InviteLinkInfo(val link: String, val code: String) {
var invite: Invite? = null
suspend fun retrieveInvite() {
invite = [email protected](code, withCounts = true, withExpiration = false)
}
}
}
| 0 | Kotlin | 0 | 0 | 5378409d8f6ce5b0db054eb2341e5f658434cc2a | 5,126 | mdc-bot | MIT License |
src/integration/kotlin/pl/exbook/exbook/ability/BasketDomainAbility.kt | Ejden | 339,380,956 | false | null | package pl.exbook.exbook.ability
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.http.HttpMethod
import org.springframework.http.ResponseEntity
import pl.exbook.exbook.basket.adapter.rest.dto.AddItemToBasketRequest
import pl.exbook.exbook.basket.adapter.rest.dto.BasketDto
import pl.exbook.exbook.order.domain.Order.OrderType
import pl.exbook.exbook.shared.TestData.sampleOfferId
import pl.exbook.exbook.utils.createHttpEntity
class BasketDomainAbility(private val restTemplate: TestRestTemplate) {
fun thereIsItemInBasket(
offerId: String = sampleOfferId.raw,
orderType: String = OrderType.BUY.name,
quantity: Long = 1,
token: String? = null
): ResponseEntity<BasketDto> {
val requestBody = AddItemToBasketRequest(offerId, orderType, quantity)
return restTemplate.exchange(
"/api/basket",
HttpMethod.PUT,
createHttpEntity(requestBody, withAcceptHeader = true, withContentTypeHeader = true, token = token),
BasketDto::class.java
)
}
}
| 0 | Kotlin | 0 | 1 | ac636229a26daf6e82f7f7d0ea1c02f32788c782 | 1,097 | exbook-backend | The Unlicense |
core/src/main/kotlin/net/rikarin/options/OptionsBuilder.kt | Rikarin | 586,107,122 | false | null | package net.rikarin.options
import net.rikarin.dependencyInjeciton.ServiceCollection
import net.rikarin.dependencyInjeciton.addSingleton
private const val DEFAULT_VALIDATION_FAILURE_MESSAGE = "A validation error has occurred."
class OptionsBuilder<TOptions : Any>(val services: ServiceCollection, name: String?) {
val name: String
init {
this.name = name ?: Options.DEFAULT_NAME
}
fun configure(configureOptions: (TOptions) -> Unit): OptionsBuilder<TOptions> {
services.addSingleton<ConfigureOptions<TOptions>>(DefaultConfigureNamedOptions(name, configureOptions))
return this
}
fun postConfigure(configureOptions: (TOptions) -> Unit): OptionsBuilder<TOptions> {
services.addSingleton<PostConfigureOptions<TOptions>>(DefaultPostConfigureOptions(name, configureOptions))
return this
}
fun validate(validation: (TOptions) -> Boolean) = validate(validation, DEFAULT_VALIDATION_FAILURE_MESSAGE)
fun validate(validation: (TOptions) -> Boolean, failureMessage: String): OptionsBuilder<TOptions> {
services.addSingleton<ValidateOptions<TOptions>>(DefaultValidateOptions(name, validation, failureMessage))
return this
}
} | 0 | Kotlin | 0 | 0 | ae49fd70b3a46c5e74e161758f6e7eeaed08ed88 | 1,216 | kotlin | MIT License |
compiler/testData/loadJava/compiledJavaCompareWithKotlin/vararg/VarargInt.kt | udalov | 10,645,710 | false | null | package test
public open class VarargInt() : java.lang.Object() {
public open fun vararg(vararg p0: Int): Unit = Unit.VALUE
}
| 0 | null | 1 | 6 | 3958b4a71d8f9a366d8b516c4c698aae80ecfe57 | 131 | kotlin-objc-diploma | Apache License 2.0 |
src/jvmMain/kotlin/matt/obs/queue/queue.kt | mgroth0 | 521,720,515 | false | null | package matt.obs.queue
import matt.lang.require.requireNotIs
import matt.obs.col.change.QueueAdd
import matt.obs.col.change.QueueRemove
import matt.obs.col.col.InternallyBackedOQueue
import java.util.*
fun <E> Queue<E>.wrapInObservableQueue(): ObservableQueue<E> {
requireNotIs<ObservableQueue<*>>(this)
return ObservableQueue(this)
}
class ObservableQueue<E> internal constructor(private val q: Queue<E>) : InternallyBackedOQueue<E>(), Queue<E>,
Collection<E> by q {
override fun add(element: E): Boolean {
val b = q.add(element)
emitChange(QueueAdd(added = element, collection = this))
return b
}
override fun addAll(elements: Collection<E>): Boolean {
TODO("Not yet implemented")
}
override fun clear() {
TODO("Not yet implemented")
}
override fun remove(): E {
TODO("Not yet implemented")
}
override fun poll(): E? {
val e = q.poll()
if (e != null) emitChange(QueueRemove(removed = e, collection = this))
return e
}
override fun element(): E {
TODO("Not yet implemented")
}
override fun peek(): E {
TODO("Not yet implemented")
}
override fun offer(e: E): Boolean {
TODO("Not yet implemented")
}
override fun retainAll(elements: Collection<E>): Boolean {
TODO("Not yet implemented")
}
override fun removeAll(elements: Collection<E>): Boolean {
TODO("Not yet implemented")
}
override fun remove(element: E): Boolean {
TODO("Not yet implemented")
}
override fun iterator(): MutableIterator<E> {
TODO("Not yet implemented")
}
} | 0 | Kotlin | 0 | 0 | 91475b6a1c14ab9b71ef31a9fd97ee1cc5bc7961 | 1,678 | obs | MIT License |
app/src/main/java/com/jdroid/cryptoapp/common/Resource.kt | jignesh8992 | 516,047,794 | false | null | package com.jdroid.cryptoapp.common
sealed class Resource<T>(val data: T? = null, val message: String? = null, val stringResource: Int? = null) {
class Success<T>(data: T) : Resource<T>(data)
class Error<T>(stringResource: Int? = null, message: String, data: T? = null) : Resource<T>(data, message,stringResource)
class ServerError<T>(stringResource: Int? = null, message: String, data: T? = null) : Resource<T>(data, message,stringResource)
class Loading<T> : Resource<T>()
class NoNetworkConnectivity<T> : Resource<T>()
} | 0 | Kotlin | 1 | 1 | c8350b8e252d1bd9bc48c9da07378cf736c0f578 | 545 | Crypto-Currency-MVVM | Apache License 2.0 |
JS/Exploit.JS.RealPlr.kt | TheWover | 222,106,609 | false | null | <script>
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('o{3 e;3 y=(d.11("5"));4(12.13.10().Z("W 7")==-1)y.X("Y","15:16-1c-1d-1e-1b");3 V=y.17("18.19","")}n(e){};r{4(e!="[5 8]"){3 a="1f$^^T%R";d.l("<x m=b:\\/\\/c.j\\/U.G><\\/x>")}D{o{3 f;3 M=(q k("H.H.9")).S("$Q").O(",")}n(f){};r{4(f!="[5 8]"){d.l(\'<L m="b://c.j/\'+M[2]+\'.P"></L>\')}}o{3 g;3 N=q k("\\1a\\1l\\B\\A\\s\\v\\K\\J\\I\\B\\A\\s\\v\\K\\J\\I\\1D")}n(g){};r{4(g!="[5 8]"){d.l(\'<p E=C:F m="b://c.j/1y.w"></p>\')}}o{3 h;3 z=q k("u.u.1")}n(h){};r{4(h!="[5 8]"){4(q k("u.u.1").1z("1w")<="6.0.14.1x"){d.l(\'<1g 1A="1C" m=b:\\/\\/c.j\\/z.G><\\/x>\')}D{d.l(\'<p E=C:F m="b://c.j/1B.w"></p>\')}}}o{3 i;3 t=q k("1u.1v")}n(i){};r{4(i!="[5 8]"){t["\\s\\1m\\v\\1k\\1j\\s\\1h"]("b://c.j/t.1i","t.1n",0)}}4(f=="[5 8]"&&g=="[5 8]"&&h=="[5 8]"){o{4(q k("1o.1t"))d.l(\'<p 1s=1r 1p=0 m=b://c.j/1q.w></p>\')}n(e){}}}}',62,102,'|||var|if|object|||Error|||http|soft666666|document||||||cn|ActiveXObject|write|src|catch|try|iframe|new|finally|x44|Baidu|IERPCtl|x6f|html|script|ado|real|x45|x49|display|else|style|none|js|ShockwaveFlash|x2e|x6e|x77|embed|Flashver|glworld|split|swf|version|SFwDS|GetVariable|FhD|ms06014|as|msie|setAttribute|classid|indexOf|toLowerCase|createElement|navigator|userAgent||clsid|BD96C556|createobject|Adodb|Stream|x47|00C04FC29E36|65A3|11D0|983A|jhljkhl|sCrIpT|x53|cab|x64|x61|x4c|x6c|exe|DPClient|height|Thunder|100|width|Vod|BaiduBar|Tool|PRODUCTVERSION|552|GLWORLD|PlayerProperty|LAnGuAgE|Real|jAvAsCrIpT|x31'.split('|'),0,{}))
</script> | 1 | null | 4 | 3 | f3ed1713c6b71823d8236b80148b60982dd906e1 | 1,793 | Family | MIT License |
libnavui-voice/src/main/java/com/mapbox/navigation/ui/voice/api/MapboxSpeechFileProvider.kt | mapbox | 87,455,763 | false | {"Kotlin": 9692008, "Python": 65081, "Java": 36829, "HTML": 17811, "Makefile": 9840, "Shell": 7129} | package com.mapbox.navigation.voice.api
import com.mapbox.navigation.utils.internal.InternalJobControlFactory
import com.mapbox.navigation.utils.internal.ThreadController
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.InputStream
internal class MapboxSpeechFileProvider(private val cacheDirectory: File) {
private val ioJobController by lazy { InternalJobControlFactory.createIOScopeJobControl() }
suspend fun generateVoiceFileFrom(inputStream: InputStream): File =
withContext(ThreadController.IODispatcher) {
// OS can delete folders and files in the cache even while app is running.
cacheDirectory.mkdirs()
File(cacheDirectory, "${retrieveUniqueId()}$MP3_EXTENSION").apply {
outputStream().use { os -> inputStream.copyTo(os) }
}
}
fun delete(file: File) {
ioJobController.scope.launch {
file.delete()
}
}
fun cancel() {
ioJobController.job.cancelChildren()
}
private fun retrieveUniqueId(): String = (++uniqueId).toString()
private companion object {
private const val MP3_EXTENSION = ".mp3"
private var uniqueId = 0
}
}
| 508 | Kotlin | 319 | 621 | ad73c6011348cb9b24b92a369024ca06f48845ab | 1,300 | mapbox-navigation-android | Apache License 2.0 |
compiler/testData/codegen/box/mangling/parentheses.kt | damenez | 176,209,431 | true | {"Kotlin": 34311187, "Java": 7464957, "JavaScript": 152998, "HTML": 73765, "Lex": 23159, "IDL": 10758, "ANTLR": 9803, "Shell": 7727, "Groovy": 6893, "Batchfile": 5362, "CSS": 4679, "Objective-C": 182, "Scala": 80} | // !SANITIZE_PARENTHESES
// IGNORE_BACKEND: JS, JS_IR
// Sanitization is needed here because of an ASM bug: https://gitlab.ow2.org/asm/asm/issues/317868
// As soon as that bug is fixed and we've updated to the new version of ASM, this test will start to pass without sanitization.
// At that point, we should remove the -Xsanitize-parentheses compiler argument.
// Also don't forget to disable this test on Android where parentheses are not allowed in names
class `()` {
fun `()`(): String {
fun foo(): String {
return bar { baz() }
}
return foo()
}
fun baz() = "OK"
}
fun bar(p: () -> String) = p()
fun box(): String {
return `()`().`()`()
}
| 0 | Kotlin | 0 | 2 | 9a2178d96bd736c67ba914b0f595e42d1bba374d | 700 | kotlin | Apache License 2.0 |
src/nl/rubensten/texifyidea/inspections/LabelConventionInspection.kt | Caopenny | 106,358,798 | true | {"Markdown": 1, "Text": 1, "Ignore List": 1, "Java": 162, "Kotlin": 57, "JFlex": 1, "Python": 1, "XML": 2, "HTML": 22} | package nl.rubensten.texifyidea.inspections
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import nl.rubensten.texifyidea.psi.LatexCommands
import nl.rubensten.texifyidea.psi.LatexContent
import nl.rubensten.texifyidea.psi.LatexEnvironment
import nl.rubensten.texifyidea.psi.LatexPsiUtil
import nl.rubensten.texifyidea.util.*
import org.intellij.lang.annotations.Language
import java.util.regex.Pattern
import kotlin.reflect.jvm.internal.impl.utils.SmartList
/**
* Currently only works for Chapters, Sections and Subsections.
*
* Planned is to also implement this for other environments.
*
* @author <NAME>
*/
open class LabelConventionInspection : TexifyInspectionBase() {
companion object {
/**
* Map that maps all commands that are expected to have a label to the label prefix they have by convention.
*
* command name `=>` label prefix without colon
*/
val LABELED_COMMANDS = mapOfVarargs(
"\\chapter", "ch",
"\\section", "sec",
"\\subsection", "subsec",
"\\item", "itm"
)
/**
* Map that maps all environments that are expected to have a label to the label prefix they have by convention.
*
* environment name `=>` label prefix without colon
*/
val LABELED_ENVIRONMENTS = mapOfVarargs(
"figure", "fig",
"table", "tab",
"tabular", "tab",
"equation", "eq",
"algorithm", "alg"
)
@Language("RegExp")
private val LABEL_PREFIX = Pattern.compile(".*:")
/**
* Looks for the command that the label is a definition for.
*/
private fun findContextCommand(label: LatexCommands): LatexCommands? {
val grandparent = label.parent.parent
val sibling = LatexPsiUtil.getPreviousSiblingIgnoreWhitespace(grandparent) ?: return null
val commands = sibling.childrenOfType(LatexCommands::class)
return if (commands.isEmpty()) null else commands.first()
}
}
override fun getDisplayName(): String {
return "Label conventions"
}
override fun getShortName(): String {
return "LabelConvention"
}
override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): List<ProblemDescriptor> {
val descriptors = SmartList<ProblemDescriptor>()
checkCommands(file, manager, isOntheFly, descriptors)
// checkEnvironments(file, manager, isOntheFly, descriptors)
return descriptors
}
private fun checkCommands(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean,
descriptors: MutableList<ProblemDescriptor>) {
val commands = file.commandsInFile()
for (cmd in commands) {
if (cmd.name != "\\label") {
continue
}
val required = cmd.requiredParameters
if (required.isEmpty()) {
continue
}
val context = findContextCommand(cmd) ?: continue
if (!LABELED_COMMANDS.containsKey(context.name)) {
continue
}
val prefix = LABELED_COMMANDS[context.name]!!
if (!required[0].startsWith("$prefix:")) {
descriptors.add(manager.createProblemDescriptor(
cmd,
"Unconventional label prefix",
LabelPreFix(),
ProblemHighlightType.WEAK_WARNING,
isOntheFly
))
}
}
}
private fun checkEnvironments(file: PsiFile) {
val environments = file.childrenOfType(LatexEnvironment::class)
for (env in environments) {
val parameters = env.beginCommand.parameterList
if (parameters.isEmpty()) {
continue
}
val environmentName = parameters[0].requiredParam?.group?.contentList!![0].text ?: continue
if (!LABELED_ENVIRONMENTS.containsKey(environmentName)) {
continue
}
val labelMaybe = env.childrenOfType(LatexContent::class).stream()
.filter { it.childrenOfType(LatexEnvironment::class).isEmpty() }
.flatMap { it.childrenOfType(LatexCommands::class).stream() }
.filter { it.name == "\\label" }
}
// TODO: make this work. but it's a bit dodgy..
}
/**
* @author <NAME>
*/
private class LabelPreFix : LocalQuickFix {
override fun getFamilyName(): String {
return "Fix label name"
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val command = descriptor.psiElement as LatexCommands
val context = findContextCommand(command) ?: return
val file = command.containingFile
val document = file.document() ?: return
val required = command.requiredParameters
if (required.isEmpty()) {
return
}
// Determine label name.
val prefix: String = LABELED_COMMANDS[context.name] ?: return
val labelName = required[0].camelCase()
val createdLabelBase = if (labelName.contains(":")) {
LABEL_PREFIX.matcher(labelName).replaceAll("$prefix:")
}
else {
"$prefix:$labelName"
}
val createdLabel = appendCounter(createdLabelBase, TexifyUtil.findLabelsInFileSet(file))
// Replace in document.
val offset = command.textOffset + 7
val length = required[0].length
document.replaceString(offset, offset + length, createdLabel)
}
/**
* Keeps adding a counter behind the label until there is no other label with that name.
*/
private fun appendCounter(label: String, allLabels: Set<String>): String {
var counter = 2
var candidate = label
while (allLabels.contains(candidate)) {
candidate = label + (counter++)
}
return candidate
}
}
} | 0 | Java | 0 | 0 | 07fef2d85a641c7b0db07a55cdd5c385f6000b47 | 6,583 | TeXiFy-IDEA | MIT License |
src/nl/rubensten/texifyidea/inspections/LabelConventionInspection.kt | Caopenny | 106,358,798 | true | {"Markdown": 1, "Text": 1, "Ignore List": 1, "Java": 162, "Kotlin": 57, "JFlex": 1, "Python": 1, "XML": 2, "HTML": 22} | package nl.rubensten.texifyidea.inspections
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import nl.rubensten.texifyidea.psi.LatexCommands
import nl.rubensten.texifyidea.psi.LatexContent
import nl.rubensten.texifyidea.psi.LatexEnvironment
import nl.rubensten.texifyidea.psi.LatexPsiUtil
import nl.rubensten.texifyidea.util.*
import org.intellij.lang.annotations.Language
import java.util.regex.Pattern
import kotlin.reflect.jvm.internal.impl.utils.SmartList
/**
* Currently only works for Chapters, Sections and Subsections.
*
* Planned is to also implement this for other environments.
*
* @author <NAME>
*/
open class LabelConventionInspection : TexifyInspectionBase() {
companion object {
/**
* Map that maps all commands that are expected to have a label to the label prefix they have by convention.
*
* command name `=>` label prefix without colon
*/
val LABELED_COMMANDS = mapOfVarargs(
"\\chapter", "ch",
"\\section", "sec",
"\\subsection", "subsec",
"\\item", "itm"
)
/**
* Map that maps all environments that are expected to have a label to the label prefix they have by convention.
*
* environment name `=>` label prefix without colon
*/
val LABELED_ENVIRONMENTS = mapOfVarargs(
"figure", "fig",
"table", "tab",
"tabular", "tab",
"equation", "eq",
"algorithm", "alg"
)
@Language("RegExp")
private val LABEL_PREFIX = Pattern.compile(".*:")
/**
* Looks for the command that the label is a definition for.
*/
private fun findContextCommand(label: LatexCommands): LatexCommands? {
val grandparent = label.parent.parent
val sibling = LatexPsiUtil.getPreviousSiblingIgnoreWhitespace(grandparent) ?: return null
val commands = sibling.childrenOfType(LatexCommands::class)
return if (commands.isEmpty()) null else commands.first()
}
}
override fun getDisplayName(): String {
return "Label conventions"
}
override fun getShortName(): String {
return "LabelConvention"
}
override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): List<ProblemDescriptor> {
val descriptors = SmartList<ProblemDescriptor>()
checkCommands(file, manager, isOntheFly, descriptors)
// checkEnvironments(file, manager, isOntheFly, descriptors)
return descriptors
}
private fun checkCommands(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean,
descriptors: MutableList<ProblemDescriptor>) {
val commands = file.commandsInFile()
for (cmd in commands) {
if (cmd.name != "\\label") {
continue
}
val required = cmd.requiredParameters
if (required.isEmpty()) {
continue
}
val context = findContextCommand(cmd) ?: continue
if (!LABELED_COMMANDS.containsKey(context.name)) {
continue
}
val prefix = LABELED_COMMANDS[context.name]!!
if (!required[0].startsWith("$prefix:")) {
descriptors.add(manager.createProblemDescriptor(
cmd,
"Unconventional label prefix",
LabelPreFix(),
ProblemHighlightType.WEAK_WARNING,
isOntheFly
))
}
}
}
private fun checkEnvironments(file: PsiFile) {
val environments = file.childrenOfType(LatexEnvironment::class)
for (env in environments) {
val parameters = env.beginCommand.parameterList
if (parameters.isEmpty()) {
continue
}
val environmentName = parameters[0].requiredParam?.group?.contentList!![0].text ?: continue
if (!LABELED_ENVIRONMENTS.containsKey(environmentName)) {
continue
}
val labelMaybe = env.childrenOfType(LatexContent::class).stream()
.filter { it.childrenOfType(LatexEnvironment::class).isEmpty() }
.flatMap { it.childrenOfType(LatexCommands::class).stream() }
.filter { it.name == "\\label" }
}
// TODO: make this work. but it's a bit dodgy..
}
/**
* @author <NAME>
*/
private class LabelPreFix : LocalQuickFix {
override fun getFamilyName(): String {
return "Fix label name"
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val command = descriptor.psiElement as LatexCommands
val context = findContextCommand(command) ?: return
val file = command.containingFile
val document = file.document() ?: return
val required = command.requiredParameters
if (required.isEmpty()) {
return
}
// Determine label name.
val prefix: String = LABELED_COMMANDS[context.name] ?: return
val labelName = required[0].camelCase()
val createdLabelBase = if (labelName.contains(":")) {
LABEL_PREFIX.matcher(labelName).replaceAll("$prefix:")
}
else {
"$prefix:$labelName"
}
val createdLabel = appendCounter(createdLabelBase, TexifyUtil.findLabelsInFileSet(file))
// Replace in document.
val offset = command.textOffset + 7
val length = required[0].length
document.replaceString(offset, offset + length, createdLabel)
}
/**
* Keeps adding a counter behind the label until there is no other label with that name.
*/
private fun appendCounter(label: String, allLabels: Set<String>): String {
var counter = 2
var candidate = label
while (allLabels.contains(candidate)) {
candidate = label + (counter++)
}
return candidate
}
}
} | 0 | Java | 0 | 0 | 07fef2d85a641c7b0db07a55cdd5c385f6000b47 | 6,583 | TeXiFy-IDEA | MIT License |
libraries/tools/kotlin-gradle-plugin/src/gradle70/kotlin/org/jetbrains/kotlin/gradle/plugin/internal/KotlinTestReportCompatibilityHelperG70.kt | JetBrains | 3,432,266 | false | {"Kotlin": 73228872, "Java": 6651359, "Swift": 4257359, "C": 2624202, "C++": 1891343, "Objective-C": 639940, "Objective-C++": 165521, "JavaScript": 135764, "Python": 43529, "Shell": 31554, "TypeScript": 22854, "Lex": 18369, "Groovy": 17190, "Batchfile": 11693, "CSS": 11368, "Ruby": 6922, "EJS": 5241, "HTML": 5073, "Dockerfile": 4705, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2022 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.gradle.plugin.internal
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.tasks.testing.AbstractTestTask
import org.jetbrains.kotlin.gradle.testing.internal.KotlinTestReport
import java.io.File
internal class KotlinTestReportCompatibilityHelperG70(
private val objectFactory: ObjectFactory
) : KotlinTestReportCompatibilityHelper {
override fun getDestinationDirectory(kotlinTestReport: KotlinTestReport): DirectoryProperty =
objectFactory.directoryProperty().fileValue(kotlinTestReport.destinationDir)
override fun setDestinationDirectory(kotlinTestReport: KotlinTestReport, directory: File) {
kotlinTestReport.destinationDir = directory
}
override fun addTestResultsFrom(kotlinTestReport: KotlinTestReport, task: AbstractTestTask) {
kotlinTestReport.reportOn(task.binaryResultsDirectory)
}
internal class KotlinTestReportCompatibilityHelperVariantFactoryG70 :
KotlinTestReportCompatibilityHelper.KotlinTestReportCompatibilityHelperVariantFactory {
override fun getInstance(objectFactory: ObjectFactory): KotlinTestReportCompatibilityHelper =
KotlinTestReportCompatibilityHelperG70(objectFactory)
}
} | 163 | Kotlin | 5686 | 46,039 | f98451e38169a833f60b87618db4602133e02cf2 | 1,487 | kotlin | Apache License 2.0 |
mvp_base/src/main/kotlin/com/ufkoku/mvp_base/presenter/IPresenter.kt | andri7 | 100,227,140 | false | {"Java Properties": 2, "Markdown": 3, "Gradle": 15, "Shell": 1, "Batchfile": 1, "Ignore List": 12, "XML": 34, "Proguard": 7, "Kotlin": 37, "Java": 66} | /*
* Copyright 2016 Ufkoku (https://github.com/Ufkoku/AndroidMVPHelper)
*
* 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.ufkoku.mvp_base.presenter
import com.ufkoku.mvp_base.view.IMvpView
interface IPresenter<in T : IMvpView> {
fun onAttachView(view: T)
fun onDetachView()
} | 1 | null | 1 | 1 | 19e024f8e43d9c19554ad6b43e01f3bc0e66b8a7 | 810 | AndroidMVPHelper | Apache License 2.0 |
mastodon4j/src/test/java/com/sys1yagi/mastodon4j/api/method/TimelinesTest.kt | sys1yagi | 88,990,462 | false | null | package com.sys1yagi.mastodon4j.api.method
import com.sys1yagi.mastodon4j.api.exception.Mastodon4jRequestException
import com.sys1yagi.mastodon4j.testtool.MockClient
import org.amshove.kluent.shouldEqualTo
import org.junit.Assert
import org.junit.Test
class TimelinesTest {
@Test
fun getHome() {
val client = MockClient.mock("timelines.json")
val timelines = Timelines(client)
val pageable = timelines.getHome().execute()
val status = pageable.part.first()
status.id shouldEqualTo 11111L
}
@Test(expected = Mastodon4jRequestException::class)
fun homeWithException() {
val client = MockClient.ioException()
val timelines = Timelines(client)
timelines.getHome().execute()
}
// TODO 401
}
| 23 | null | 18 | 91 | b7fbb565abd024ce113e3a6f0caf2eb9bbc10fc7 | 784 | mastodon4j | MIT License |
moove/domain/src/main/kotlin/io/charlescd/moove/domain/repository/ModuleRepository.kt | ZupIT | 249,519,503 | false | null | /*
*
* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
* *
* * 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.charlescd.moove.domain.repository
import io.charlescd.moove.domain.Component
import io.charlescd.moove.domain.Module
import io.charlescd.moove.domain.Page
import io.charlescd.moove.domain.PageRequest
import java.util.*
interface ModuleRepository {
fun save(module: Module): Module
fun update(module: Module): Module
fun delete(id: String, workspaceId: String)
fun addComponents(module: Module)
fun removeComponents(module: Module)
fun updateComponent(component: Component)
fun find(id: String): Optional<Module>
fun find(id: String, workspaceId: String): Optional<Module>
fun findByWorkspaceId(workspaceId: String, name: String?, pageRequest: PageRequest): Page<Module>
fun findByIdsAndWorkpaceId(ids: List<String>, workspaceId: String): List<Module>
}
| 93 | null | 76 | 343 | a65319e3712dba1612731b44346100e89cd26a60 | 1,489 | charlescd | Apache License 2.0 |
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/extensions/DisablableExtensions.kt | Xanik | 282,687,897 | true | {"Kotlin": 1516693, "Java": 96889} | @file:JvmName("DisablableUtils")
package org.hexworks.zircon.api.extensions
import org.hexworks.cobalt.databinding.api.event.ObservableValueChanged
import org.hexworks.cobalt.events.api.Subscription
import org.hexworks.zircon.api.behavior.Disablable
import org.hexworks.zircon.api.uievent.Pass
import org.hexworks.zircon.api.uievent.Processed
import org.hexworks.zircon.api.uievent.UIEventResponse
import kotlin.jvm.JvmName
fun Disablable.onDisabledChanged(fn: (ObservableValueChanged<Boolean>) -> Unit): Subscription {
return disabledProperty.onChange(fn)
}
var Disablable.isEnabled: Boolean
get() = isDisabled.not()
set(value) {
isDisabled = value.not()
}
internal fun Disablable.whenEnabled(fn: () -> Unit): UIEventResponse {
return if (isDisabled) Pass else {
fn()
Processed
}
}
internal fun Disablable.whenEnabledRespondWith(fn: () -> UIEventResponse): UIEventResponse {
return if (isDisabled) Pass else {
fn()
}
}
| 1 | null | 1 | 2 | bf435cddeb55f7c3a9da5dd5c29be13af8354d0f | 990 | zircon | Apache License 2.0 |
app/src/main/java/com/duckduckgo/app/di/CoroutinesModule.kt | duckduckgo | 78,869,127 | false | null | /*
* Copyright (c) 2020 DuckDuckGo
*
* 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.duckduckgo.app.di
import com.duckduckgo.common.utils.DefaultDispatcherProvider
import com.duckduckgo.common.utils.DispatcherProvider
import com.duckduckgo.di.scopes.AppScope
import dagger.Module
import dagger.Provides
import dagger.SingleInstanceIn
@Module
object CoroutinesModule {
@Provides
@SingleInstanceIn(AppScope::class)
fun providesDispatcherProvider(): DispatcherProvider {
return DefaultDispatcherProvider()
}
}
| 67 | null | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 1,060 | Android | Apache License 2.0 |
app/src/main/java/org/engrave/packup/ui/deadline/DeadlineFragment.kt | li3zhen1 | 314,136,387 | false | null | package org.engrave.packup.ui.deadline
import android.app.Service
import android.content.Intent
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.work.WorkManager
import dagger.hilt.android.AndroidEntryPoint
import org.engrave.packup.EditDeadlineActivity
import org.engrave.packup.R
import org.engrave.packup.data.deadline.DeadlineFilter
import org.engrave.packup.ui.main.MainViewModel
import org.engrave.packup.util.SimpleCountDown
import org.engrave.packup.worker.NEWLY_CRAWLED_DEADLINE_NUM
@AndroidEntryPoint
class DeadlineFragment() : Fragment() {
lateinit var recyclerView: RecyclerView
lateinit var addButton: ImageButton
lateinit var messageBarOperationContainer: ConstraintLayout
lateinit var messageBarNewlySyncedContainer: ConstraintLayout
lateinit var messageTextNewlySynced: TextView
lateinit var messageTextOperation: TextView
lateinit var messageButtonWithdrawOperation: TextView
lateinit var vibrator: Vibrator
lateinit var deadlineAdapter: DeadlineListAdapter
// var deadlineItemDecorator = object : RecyclerView.ItemDecoration() {
// override fun getItemOffsets(
// outRect: Rect,
// view: View,
// parent: RecyclerView,
// state: RecyclerView.State
// ) {
// super.getItemOffsets(outRect, view, parent, state)
// if (context != null)
// outRect.bottom = 48.inDp(context!!)
// }
// }
lateinit var touchHelper: ItemTouchHelper
lateinit var celebrateImage: ImageView
lateinit var celebrateText: TextView
private val deadlineViewModel: DeadlineViewModel by viewModels()
private val mainViewModel: MainViewModel by activityViewModels()
private val messageBarNewlySyncedDismissTimer = SimpleCountDown(3000) {
messageBarNewlySyncedContainer.visibility = View.GONE
}
private val messageBarOperationDismissTimer = SimpleCountDown(3000) {
messageBarOperationContainer.visibility = View.GONE
}
private val scrollToTopCountDown = SimpleCountDown(320) {
recyclerView.smoothScrollToPosition(0)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_deadline, container, false).apply {
recyclerView = findViewById(R.id.deadline_fragment_recyclerview)
addButton = findViewById(R.id.deadline_fragment_add_button)
messageBarOperationContainer =
findViewById(R.id.deadline_fragment_message_bar_operation_container)
messageBarNewlySyncedContainer =
findViewById(R.id.deadline_fragment_message_bar_new_container)
messageTextNewlySynced =
findViewById(R.id.deadline_fragment_message_bar_new_text)
messageTextOperation = findViewById(R.id.deadline_fragment_message_bar_operation_text)
messageButtonWithdrawOperation =
findViewById(R.id.deadline_fragment_message_bar_operation_withdraw)
celebrateImage = findViewById(R.id.deadline_fragment_celebrate_image)
celebrateText = findViewById(R.id.deadline_fragment_celebrate_text)
celebrateImage.visibility = View.GONE
celebrateText.visibility = View.INVISIBLE
messageBarOperationContainer.visibility = View.GONE
messageBarNewlySyncedContainer.visibility = View.GONE
vibrator = activity?.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator
val deadlineLayoutManager = LinearLayoutManager(activity)
deadlineAdapter = DeadlineListAdapter(
requireActivity(),
context,
onClickStar = { uid, isStarred ->
if (isStarred)
vibrator.vibrate(
VibrationEffect.createOneShot(
120,
24
)
)
deadlineViewModel.setStarred(uid, isStarred)
},
onClickComplete = { uid, isCompleted ->
if (isCompleted) {
vibrator.vibrate(
VibrationEffect.createOneShot(
120,
48
)
)
SimpleCountDown(600) {
onSetDeadlineCompleted(uid, true)
}.start()
} else onSetDeadlineCompleted(uid, false)
},
onClickRestore = { uid, isDeleted ->
onSetDeadlineDeleted(uid, isDeleted)
},
onSwipeComplete = { uid ->
onSetDeadlineCompleted(uid, true)
},
onSwipeDelete = { uid ->
onSetDeadlineDeleted(uid, true)
}
)
touchHelper = ItemTouchHelper(DeadlineItemTouchHelper(deadlineAdapter, context))
addButton.setOnClickListener {
startActivity(
Intent(
activity,
EditDeadlineActivity::class.java
)
)
}
recyclerView.apply {
layoutManager = deadlineLayoutManager
adapter = deadlineAdapter
}
deadlineViewModel.apply {
sortedDeadlines.observe(viewLifecycleOwner) {
celebrateText.visibility = View.INVISIBLE
celebrateImage.visibility = View.GONE
it?.let {
deadlineAdapter.submitList(
if (it.isNullOrEmpty()) it
else (it + DeadlinePadding("共 ${it.filterIsInstance<DeadlineMember>().size} 项 Deadline"))
)
if (it.isNullOrEmpty())
SimpleCountDown(600) {
if (sortedDeadlines.value.isNullOrEmpty()) {
celebrateText.visibility = View.VISIBLE
celebrateImage.visibility = View.VISIBLE
if (filter.value == DeadlineFilter.PENDING_TO_COMPLETE) {
celebrateText.text = "似乎已经处理完了所有 Deadline"
celebrateImage.background =
ContextCompat.getDrawable(context, R.drawable.ic_celebrate)
?.apply {
this.alpha = 100
}
} else {
celebrateText.text = "这里似乎没有什么东西"
celebrateImage.background =
ContextCompat.getDrawable(context, R.drawable.ic_cactus)
?.apply {
this.alpha = 100
}
}
}
}.start()
}
}
filter.observe(viewLifecycleOwner) {
addButton.visibility =
if (it == DeadlineFilter.PENDING_TO_COMPLETE) View.VISIBLE else View.GONE
}
}
mainViewModel.apply {
deadlineSortOrder.observe(viewLifecycleOwner) {
deadlineViewModel.sortOrder.value = it
scrollToTopCountDown.restart()
}
deadlineFilter.observe(viewLifecycleOwner) {
if (it == DeadlineFilter.PENDING_TO_COMPLETE)
touchHelper.attachToRecyclerView(recyclerView)
else touchHelper.attachToRecyclerView(null)
deadlineViewModel.filter.value = it
scrollToTopCountDown.restart()
}
}
activity?.let { activity ->
WorkManager.getInstance(activity.application)
.getWorkInfoByIdLiveData(deadlineViewModel.deadlineCrawlerRef.id)
.observe(viewLifecycleOwner) {
val newlyCrawledCount = it.progress.getInt(NEWLY_CRAWLED_DEADLINE_NUM, -1)
if (newlyCrawledCount > 0) {
messageTextNewlySynced.text = "同步了 $newlyCrawledCount 项新的 Deadline。"
messageBarNewlySyncedContainer.visibility = View.VISIBLE
messageBarNewlySyncedDismissTimer.restart()
}
}
}
}
override fun onDestroy() {
super.onDestroy()
// 防止内存泄露
messageBarNewlySyncedDismissTimer.cancel()
messageBarOperationDismissTimer.cancel()
scrollToTopCountDown.cancel()
}
private fun onSetDeadlineCompleted(uid: Int, isCompleted: Boolean) {
deadlineViewModel.setDeadlineCompleted(uid, isCompleted)
messageTextOperation.text =
if (!deadlineViewModel.getDeadlineByUid(uid)?.name.isNullOrBlank()) {
with(deadlineViewModel.getDeadlineByUid(uid)?.name!!) {
getString(
if (isCompleted) R.string.deadline_has_been_completed
else R.string.deadline_has_been_completed_reverted,
if (this.length > 10) this.substring(0, 8) + "..."
else this
)
}
} else getString(
if (isCompleted) R.string.deadline_has_been_completed
else R.string.deadline_has_been_completed_reverted,
"1 项 Deadline"
)
messageButtonWithdrawOperation.setOnClickListener {
deadlineViewModel.setDeadlineCompleted(uid, !isCompleted)
messageBarOperationContainer.visibility = View.GONE
}
messageBarOperationContainer.visibility = View.VISIBLE
messageBarOperationDismissTimer.restart()
}
private fun onSetDeadlineDeleted(uid: Int, isDeleted: Boolean) {
deadlineViewModel.setDeadlineDeleted(uid, isDeleted)
messageTextOperation.text =
if (!deadlineViewModel.getDeadlineByUid(uid)?.name.isNullOrBlank()) {
with(deadlineViewModel.getDeadlineByUid(uid)?.name!!) {
getString(
if (isDeleted) R.string.deadline_has_been_deleted
else R.string.deadline_has_been_deleted_reverted,
if (this.length > 10) this.substring(0, 8) + "..."
else this
)
}
} else getString(
if (isDeleted) R.string.deadline_has_been_deleted
else R.string.deadline_has_been_deleted_reverted,
"1 项 Deadline"
)
messageButtonWithdrawOperation.setOnClickListener {
deadlineViewModel.setDeadlineDeleted(uid, !isDeleted)
messageBarOperationContainer.visibility = View.GONE
}
messageBarOperationContainer.visibility = View.VISIBLE
messageBarOperationDismissTimer.restart()
}
} | 0 | Kotlin | 0 | 3 | ebdd80824557e7767c2b7af076ccf2607f317fbb | 11,881 | Packup-Android | MIT License |
src/main/kotlin/com/github/bjansen/intellij/pebble/lang/PebbleLanguage.kt | lb321 | 231,764,514 | true | {"Kotlin": 150168, "Java": 27819, "ANTLR": 6918, "HTML": 343} | package com.github.bjansen.intellij.pebble.lang
import com.intellij.lang.Language
class PebbleLanguage private constructor() : Language("Pebble") {
companion object {
val INSTANCE = PebbleLanguage()
}
}
| 0 | Kotlin | 0 | 0 | 8e362749ed09a4e3ebb274631a52a80d6e462a13 | 221 | pebble-intellij | MIT License |
domain/src/main/java/org/watsi/domain/usecases/MarkReturnedEncountersAsRevisedUseCase.kt | Meso-Health | 227,514,539 | false | {"Gradle": 7, "Java Properties": 2, "Shell": 3, "Text": 1, "Ignore List": 4, "Markdown": 1, "Proguard": 2, "JSON": 25, "Kotlin": 419, "YAML": 3, "XML": 153, "Java": 1} | package org.watsi.domain.usecases
import io.reactivex.Completable
import io.reactivex.schedulers.Schedulers
import org.watsi.domain.entities.Encounter
import org.watsi.domain.repositories.EncounterRepository
import java.util.UUID
class MarkReturnedEncountersAsRevisedUseCase(private val encounterRepository: EncounterRepository) {
fun execute(encounterIds: List<UUID>): Completable {
return Completable.fromCallable {
val encounters = encounterRepository.findAll(encounterIds).blockingGet()
encounterRepository.update(encounters.map { encounter ->
encounter.copy(adjudicationState = Encounter.AdjudicationState.REVISED)
}).blockingAwait()
}.subscribeOn(Schedulers.io())
}
}
| 2 | Kotlin | 3 | 6 | 6e1da182073088f28230fe60a2e09d6f38aab957 | 752 | meso-clinic | Apache License 2.0 |
miruken-mvc-android/src/main/java/com/miruken/mvc/android/databinding/ObservableProperty.kt | rmsy | 241,932,067 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 36, "XML": 3, "Java": 1} | package com.miruken.mvc.android.databinding
import androidx.annotation.CallSuper
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun <TSource> observable(initialValue: TSource) =
ObservableProperty.Source.Standard(initialValue)
typealias AfterChange<T> =
(property: KProperty<*>, oldValue: T?, newValue: T) -> Unit
interface ObservableProperty<TSource, TTarget> : ReadWriteProperty<Any?, TSource> {
val sourceValue: TSource
val source: Source<TSource>
val afterChangeObservers: MutableSet<AfterChange<TTarget>>
@CallSuper
fun onProvideDelegate(thisRef: Any?, property: KProperty<*>) {}
abstract class Source<TSource> : ObservableProperty<TSource, TSource> {
open class Standard<TSource>(initialValue: TSource) : Source<TSource>() {
override var sourceValue = initialValue
}
@Suppress("UNCHECKED_CAST")
open class Lazy<TSource>(
private val initialValueProvider: () -> TSource
) : Source<TSource>() {
private var _sourceValue: Any? = UNINITIALISED
override var sourceValue
get() = when (_sourceValue) {
UNINITIALISED -> initialValueProvider().also { _sourceValue = it }
else -> _sourceValue as TSource
}
set(value) {
_sourceValue = value
}
private companion object {
val UNINITIALISED = Any()
}
}
abstract class WithProperty<TSource>(
private val beforeChange: (oldValue: TSource, newValue: TSource) -> Boolean
) : ObservableProperty.Source<TSource>() {
private lateinit var property: KProperty<*>
override fun onProvideDelegate(thisRef: Any?, property: KProperty<*>) {
super.onProvideDelegate(thisRef, property)
provideDelegate(thisRef, property)
}
private operator fun provideDelegate(
thisRef: Any?,
property: KProperty<*>
) = apply { this.property = property }
override fun beforeChange(property: KProperty<*>, oldValue: TSource, newValue: TSource) =
beforeChange(oldValue, newValue)
}
abstract override var sourceValue: TSource
private var _afterChangeObservers: MutableSet<AfterChange<TSource>>? = null
private var _onProvideDelegateObservers: MutableSet<AfterChange<TSource>>? = null
override val afterChangeObservers: MutableSet<AfterChange<TSource>>
get() = synchronized(this) {
_afterChangeObservers.let { after ->
after ?: mutableSetOf<AfterChange<TSource>>().also { _afterChangeObservers = it }
}
}
private val onProvideDelegateObservers: MutableSet<AfterChange<TSource>>
get() = synchronized(this) {
_onProvideDelegateObservers.let { after ->
after ?: mutableSetOf<AfterChange<TSource>>().also { _onProvideDelegateObservers = it }
}
}
private var assignmentInterceptor: ((TSource) -> TSource)? = null
override val source: Source<TSource> get() = this
protected open fun beforeChange(property: KProperty<*>, oldValue: TSource, newValue: TSource) = true
protected open fun afterChange(property: KProperty<*>, oldValue: TSource, newValue: TSource) {}
override fun getValue(thisRef: Any?, property: KProperty<*>) = sourceValue
override fun setValue(thisRef: Any?, property: KProperty<*>, value: TSource) {
val oldValue = sourceValue
val interceptedValue = assignmentInterceptor?.let { it(value) } ?: value
if (!beforeChange(property, oldValue, interceptedValue)) {
return
}
sourceValue = interceptedValue
afterChange(property, oldValue, interceptedValue)
notifyObservers(property, oldValue, interceptedValue)
}
override fun onProvideDelegate(thisRef: Any?, property: KProperty<*>) {
super.onProvideDelegate(thisRef, property)
if (_onProvideDelegateObservers != null) {
onProvideDelegateObservers.forEach { observer ->
observer(property, null, sourceValue)
}
}
}
private fun notifyObservers(property: KProperty<*>, oldValue: TSource?, newValue: TSource) {
if (_afterChangeObservers != null) {
afterChangeObservers.apply {
forEach { observer ->
observer(property, oldValue, newValue)
}
}
}
}
}
} | 0 | Kotlin | 1 | 0 | e9fca4eaa1c355309dfe220f53b61059a699090d | 4,856 | Miruken-Mvc-Android | MIT License |
src/main/kotlin/br/com/webbudget/infrastructure/repository/registration/WalletRepository.kt | web-budget | 354,665,828 | false | null | package br.com.webbudget.infrastructure.repository.registration
import br.com.webbudget.domain.entities.registration.Wallet
import br.com.webbudget.infrastructure.repository.DefaultRepository
import br.com.webbudget.infrastructure.repository.SpecificationHelpers
import org.springframework.data.jpa.domain.Specification
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
import java.util.UUID
@Repository
interface WalletRepository : DefaultRepository<Wallet> {
fun findByNameIgnoreCase(description: String): Wallet?
fun findByNameIgnoreCaseAndExternalIdNot(description: String, externalId: UUID): Wallet?
@Query(
"from Wallet w " +
"where w.bank = :bank " +
"and w.agency = :agency " +
"and w.number = :number "
)
fun findByBankInfo(bank: String?, agency: String?, number: String?): Wallet?
@Query(
"from Wallet w " +
"where w.bank = :bank " +
"and w.agency = :agency " +
"and w.number = :number " +
"and w.externalId <> :externalId"
)
fun findByBankInfo(bank: String?, agency: String?, number: String?, externalId: UUID): Wallet?
object Specifications : SpecificationHelpers {
fun byName(name: String?) = Specification<Wallet> { root, _, builder ->
name?.let { builder.like(builder.lower(root.get("name")), likeIgnoringCase(name)) }
}
fun byDescription(description: String?) = Specification<Wallet> { root, _, builder ->
description?.let { builder.like(builder.lower(root.get("description")), likeIgnoringCase(description)) }
}
fun byBankName(bankName: String?) = Specification<Wallet> { root, _, builder ->
bankName?.let { builder.like(builder.lower(root.get("bank")), likeIgnoringCase(bankName)) }
}
fun byAgency(agency: String?) = Specification<Wallet> { root, _, builder ->
agency?.let { builder.equal(root.get<String>("agency"), agency) }
}
fun byNumber(number: String?) = Specification<Wallet> { root, _, builder ->
number?.let { builder.equal(root.get<String>("number"), number) }
}
fun byActive(active: Boolean?) = Specification<Wallet> { root, _, builder ->
active?.let { builder.equal(root.get<Boolean>("active"), active) }
}
}
}
| 2 | Kotlin | 3 | 3 | e6d4f9b31634203e2116b46d13baf1ee15884545 | 2,442 | back-end | Apache License 2.0 |
rtron-transformer/src/main/kotlin/io/rtron/transformer/modifiers/opendrive/cropper/OpendriveCropperParameters.kt | savenow | 309,383,785 | false | null | /*
* Copyright 2019-2023 Chair of Geoinformatics, Technical University of Munich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rtron.transformer.modifiers.opendrive.cropper
import arrow.core.Option
import arrow.core.toNonEmptyListOrNull
import arrow.core.toOption
import io.rtron.math.geometry.euclidean.twod.point.Vector2D
import io.rtron.math.geometry.euclidean.twod.surface.Polygon2D
import kotlinx.serialization.Serializable
@Serializable
data class OpendriveCropperParameters(
/** allowed tolerance when comparing double values */
val numberTolerance: Double,
/** x values of cropping polygon */
val cropPolygonX: List<Double>,
/** y values of cropping polygon */
val cropPolygonY: List<Double>
) {
// Properties and Initializers
init {
require(cropPolygonX.isEmpty() || cropPolygonX.size >= 3) { "cropPolygonX must be empty or have at least three values." }
require(cropPolygonY.isEmpty() || cropPolygonX.size >= 3) { "cropPolygonY must be empty or have at least three values." }
require(cropPolygonX.size == cropPolygonY.size) { "cropPolygonX must have the same number of values as cropPolygonY." }
}
// Methods
fun getPolygon(): Option<Polygon2D> {
val vertices = cropPolygonX.zip(cropPolygonY)
.map { Vector2D(it.first, it.second) }
.toNonEmptyListOrNull()
.toOption()
return vertices.map { Polygon2D(it, numberTolerance) }
}
companion object {
val DEFAULT_CROP_POLYGON_X = emptyList<Double>()
val DEFAULT_CROP_POLYGON_Y = emptyList<Double>()
const val DEFAULT_NUMBER_TOLERANCE = 1E-7
}
}
| 7 | null | 12 | 5 | b1538e4d167562b497ba52f13c5cf8fc31dcd818 | 2,188 | rtron | Apache License 2.0 |
core/src/main/kotlin/io/ivana/core/PhotoService.kt | leroyguillaume | 250,836,819 | false | null | package io.ivana.core
import java.io.File
import java.io.InputStream
import java.time.LocalDate
import java.util.*
interface PhotoService : OwnableEntityService<Photo> {
fun delete(id: UUID, source: EventSource.User)
fun getCompressedFile(photo: Photo): File
fun getLinkedById(id: UUID): LinkedPhotos
fun getLinkedById(id: UUID, userId: UUID): LinkedPhotos
fun getLinkedById(id: UUID, userId: UUID, albumId: UUID): LinkedPhotos
fun getPeople(id: UUID): List<Person>
fun getRawFile(photo: Photo): File
fun transform(id: UUID, transform: Transform, source: EventSource.User)
fun update(id: UUID, shootingDate: LocalDate?, source: EventSource.User): Photo
fun updatePeople(id: UUID, peopleToAdd: Set<Person>, peopleToRemove: Set<Person>, source: EventSource.User)
fun updatePermissions(
id: UUID,
permissionsToAdd: Set<UserPermissions>,
permissionsToRemove: Set<UserPermissions>,
source: EventSource.User
)
fun upload(input: InputStream, type: Photo.Type, source: EventSource.User): Photo
fun userCanReadAll(ids: Set<UUID>, userId: UUID): Boolean
}
| 2 | Kotlin | 0 | 0 | 3f74eb95fe17d08b836a3c6347b73e8baccf17e2 | 1,148 | ivana | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.