path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/example/a7minutesworkout/ExerciseActivity.kt | ConnectBhawna | 480,787,925 | false | {"Kotlin": 37854} | package com.example.a7minutesworkout
import android.app.Dialog
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.provider.MediaStore
import android.speech.tts.TextToSpeech
import android.util.Log
import android.view.View
import android.widget.GridLayout
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.a7minutesworkout.databinding.ActivityExerciseBinding
import com.example.a7minutesworkout.databinding.ActivityMainBinding
import com.example.a7minutesworkout.databinding.DialogCustomBackConfirmationBinding
import java.util.*
import kotlin.collections.ArrayList
class ExerciseActivity : AppCompatActivity(), TextToSpeech.OnInitListener {
private var binding: ActivityExerciseBinding? = null
private var restTimer: CountDownTimer? = null
private var restProgress = 0
private var restTimerDuration: Long = 1
private var exerciseTimer: CountDownTimer? = null // Variable for Exercise Timer and later on we will initialize it.
private var exerciseProgress = 0 // Variable for the exercise timer progress. As initial value the exercise progress is set to 0. As we are about to start.
private var exerciseTimerDuration: Long = 1
private var exerciseList : ArrayList<ExerciseModel>? = null
private var currentExercisePosition = -1
private var tts: TextToSpeech? = null
private var player:MediaPlayer? = null
private var exerciseAdapter : ExerciseStatusAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityExerciseBinding.inflate(layoutInflater)
setContentView(binding?.root)
setSupportActionBar(binding?.toolbarExercise)
if(supportActionBar != null){
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
exerciseList = Constants.defaultExerciseList()
tts = TextToSpeech(this, this)
binding?.toolbarExercise?.setNavigationOnClickListener{
customDialogForBackButton()
}
setupRestView()
setUpExerciseStatusRecyclerView()
}
override fun onBackPressed() {
customDialogForBackButton()
//super.onBackPressed()
}
private fun customDialogForBackButton(){
val customDialog = Dialog(this)
val dialogBinding = DialogCustomBackConfirmationBinding.inflate(layoutInflater)
customDialog.setContentView(dialogBinding.root)
customDialog.setCanceledOnTouchOutside(false)
dialogBinding.btnYes.setOnClickListener{
[email protected]()
customDialog.dismiss()
}
dialogBinding.btnNo.setOnClickListener{
customDialog.dismiss()
}
customDialog.show()
}
/**
* Function is used to set the recycler View at the bottom of the exercise
*/
private fun setUpExerciseStatusRecyclerView(){
binding?.rvExerciseStatus?.layoutManager =
LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
exerciseAdapter = ExerciseStatusAdapter(exerciseList!!)
binding?.rvExerciseStatus?.adapter = exerciseAdapter
}
/**
* Function is used to set the timer for REST.
*/
private fun setupRestView() {
try{
val soundURI = Uri.parse(
"android.resource://com.example.a7minutesworkout/" +
R.raw.app_src_main_res_raw_press_start
)
player = MediaPlayer.create(applicationContext, soundURI)
player?.isLooping = false
player?.start()
}catch (e: Exception){
e.printStackTrace()
}
binding?.flRestView?.visibility = View.VISIBLE
binding?.tvTitle?.visibility = View.VISIBLE
binding?.tvExerciseName?.visibility = View.INVISIBLE
binding?.flExerciseView?.visibility = View.INVISIBLE
binding?.ivImage?.visibility = View.INVISIBLE
binding?.upcomingLabel?.visibility = View.VISIBLE
binding?.tvUpcomingExerciseName?.visibility = View.VISIBLE
/**
* Here firstly we will check if the timer is running the and it is not null then cancel the running timer and start the new one.
* And set the progress to initial which is 0.
*/
if (restTimer != null) {
restTimer!!.cancel()
restProgress = 0
}
binding?.tvUpcomingExerciseName?.text = exerciseList!![currentExercisePosition + 1].getName()
// This function is used to set the progress details.
setRestProgressBar()
}
private fun setRestProgressBar(){
binding?.progressBar?.progress = restProgress
// Here we have started a timer of 10 seconds so the 10000 is milliseconds is 10 seconds and the countdown interval is 1 second so it 1000.
restTimer = object : CountDownTimer(restTimerDuration*1000, 1000) {
override fun onTick(millisUntilFinished: Long) {
restProgress++ // It is increased by 1
binding?.progressBar?.progress = 10 - restProgress // Indicates progress bar progress
binding?.tvTimer?.text =
(10 - restProgress).toString() // Current progress is set to text view in terms of seconds.
}
override fun onFinish() {
// When the 10 seconds will complete this will get to another timer
currentExercisePosition++
exerciseList!![currentExercisePosition].setIsSelected(true)
exerciseAdapter!!.notifyDataSetChanged()
setupExerciseView()
}
}.start()
}
/**
* Function is used to set the progress of the timer using the progress for Exercise View.
*/
private fun setupExerciseView() {
// Here according to the view make it visible as this is Exercise View so exercise view is visible and rest view is not.
binding?.flRestView?.visibility = View.INVISIBLE
binding?.tvTitle?.visibility = View.INVISIBLE
binding?.tvExerciseName?.visibility = View.VISIBLE
binding?.flExerciseView?.visibility = View.VISIBLE
binding?.ivImage?.visibility = View.VISIBLE
binding?.upcomingLabel?.visibility = View.INVISIBLE
binding?.tvUpcomingExerciseName?.visibility = View.INVISIBLE
/**
* Here firstly we will check if the timer is running and it is not null then cancel the running timer and start the new one.
* And set the progress to the initial value which is 0.
*/
if (exerciseTimer != null) {
exerciseTimer?.cancel()
exerciseProgress = 0
}
speakOut(exerciseList!![currentExercisePosition].getName())
binding?.ivImage?.setImageResource(exerciseList!![currentExercisePosition].getImage())
binding?.tvExerciseName?.text = exerciseList!![currentExercisePosition].getName()
setExerciseProgressBar()
}
/**
* Function is used to set the progress of the timer using the progress for Exercise View for 30 Seconds
*/
private fun setExerciseProgressBar() {
binding?.progressBarExercise?.progress = exerciseProgress
exerciseTimer = object : CountDownTimer(exerciseTimerDuration*1000, 1000) {
override fun onTick(millisUntilFinished: Long) {
exerciseProgress++
binding?.progressBarExercise?.progress = 30 - exerciseProgress
binding?.tvTimerExercise?.text = (30 - exerciseProgress).toString()
}
override fun onFinish() {
if(currentExercisePosition < exerciseList?.size!! -1){
exerciseList!![currentExercisePosition].setIsSelected(false)
exerciseList!![currentExercisePosition].setIsCompleted(true)
exerciseAdapter!!.notifyDataSetChanged()
setupRestView()
}
else{
finish()
val intent = Intent(this@ExerciseActivity,FinishActivity::class.java)
startActivity(intent)
}
}
}.start()
}
public override fun onDestroy() {
if (restTimer != null) {
restTimer?.cancel()
restProgress = 0
}
super.onDestroy()
if(exerciseTimer != null){
exerciseTimer?.cancel()
exerciseProgress=0
}
if (tts != null) {
tts?.stop()
tts?.shutdown()
}
if(player != null){
player?.stop()
}
binding = null
}
override fun onInit(status: Int) {
if (status == TextToSpeech.SUCCESS) {
// set US English as language for tts
val result = tts!!.setLanguage(Locale.US)
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "The Language specified is not supported!")
}
} else {
Log.e("TTS", "Initialization Failed!")
}
}
/**
* Function is used to speak the text what we pass to it.
*/
private fun speakOut(text: String) {
tts?.speak(text, TextToSpeech.QUEUE_ADD, null, "")
}
} | 0 | Kotlin | 0 | 1 | b986f54da63c3e773aa826821177ae80171f92db | 9,606 | 7MinutesWorkoutApp | Apache License 2.0 |
kofu/src/test/kotlin/org/springframework/boot/kofu/beans/SimpleBean.kt | ksvasan | 151,100,484 | true | {"Kotlin": 227981, "Java": 58894, "Shell": 1265, "HTML": 15} | package org.springframework.boot.kofu.beans
class SimpleBean | 0 | Kotlin | 0 | 0 | a747b8ac4d224ca598398ae834eac53d15c2d895 | 61 | spring-fu | Apache License 2.0 |
app/src/main/java/com/imashnake/moshiadapter/MainActivity.kt | imashnake0 | 561,864,805 | false | {"Kotlin": 6410} | package com.imashnake.moshiadapter
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import com.imashnake.moshiadapter.parse.parseEnum
import com.imashnake.moshiadapter.ui.theme.MoshiAdapterTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MoshiAdapterTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Text(parseEnum().toString())
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | ab684f10c9170da5abe76c84d7072261ec5fae22 | 940 | MoshiAdapters | Apache License 2.0 |
core_library_common/src/jvmTest/kotlin/net/apptronic/core/entity/composite/LastItemCompositionTest.kt | apptronicnet | 264,405,837 | false | null | package net.apptronic.core.entity.composite
import net.apptronic.core.context.component.Component
import net.apptronic.core.context.terminate
import net.apptronic.core.entity.commons.typedEvent
import net.apptronic.core.record
import net.apptronic.core.testutils.createTestContext
import org.junit.After
import org.junit.Test
class LastItemCompositionTest : Component(createTestContext()) {
private val item1 = typedEvent<Int>()
private val item2 = typedEvent<Int>()
private val item3 = typedEvent<Int>()
private val compose = lastItemOf(item1, item2, item3)
private val records = compose.record()
@Test
fun verifyLastItem() {
records.assertItems()
item1.update(1)
item1.update(2)
item2.update(3)
item3.update(4)
item2.update(5)
item2.update(6)
item3.update(7)
item1.update(8)
records.assertItems(1, 2, 3, 4, 5, 6, 7, 8)
}
@After
fun after() {
terminate()
}
} | 2 | Kotlin | 0 | 6 | 5320427ddc9dd2393f01e75564dab126fdeaac72 | 998 | core | MIT License |
libraries/layout/src/Orientation.kt | featurea | 407,517,337 | false | null | package featurea.layout
val AllOrientations = listOf(
Orientation.Portrait,
Orientation.PortraitUpsideDown,
Orientation.LandscapeRight,
Orientation.LandscapeLeft
)
val LandscapeOrientations: List<Orientation> = listOf(Orientation.LandscapeLeft, Orientation.LandscapeRight)
val PortraitOrientations: List<Orientation> = listOf(Orientation.Portrait, Orientation.PortraitUpsideDown)
enum class Orientation {
LandscapeLeft,
LandscapeRight,
Portrait,
PortraitUpsideDown;
val isHorizontal: Boolean get() = this == LandscapeRight || this == LandscapeLeft
val isVertical: Boolean get() = this == Portrait || this == PortraitUpsideDown
}
| 30 | Kotlin | 1 | 6 | 07074dc37a838f16ece90c19a4e8d45e743013d3 | 676 | engine | MIT License |
core/domain/src/main/java/com/anilyilmaz/awesomesunsetwallpapers/core/domain/di/DomainModule.kt | uyelikanil | 636,745,887 | false | null | package com.anilyilmaz.awesomesunsetwallpapers.core.domain.di
import com.anilyilmaz.awesomesunsetwallpapers.core.domain.usecase.GetNetworkStateUseCase
import com.anilyilmaz.awesomesunsetwallpapers.core.domain.usecase.GetNetworkStateUseCaseImpl
import com.anilyilmaz.awesomesunsetwallpapers.core.domain.usecase.GetPhotoUseCase
import com.anilyilmaz.awesomesunsetwallpapers.core.domain.usecase.GetPhotoUseCaseImpl
import com.anilyilmaz.awesomesunsetwallpapers.core.domain.usecase.SetTempFileUseCase
import com.anilyilmaz.awesomesunsetwallpapers.core.domain.usecase.SetTempFileUseCaseImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
interface DomainModule {
@Binds
fun bindsGetPhotoUseCase(getPhotoUseCase: GetPhotoUseCaseImpl): GetPhotoUseCase
@Binds
fun bindsGetNetworkStateUseCase(getNetworkStateUseCase: GetNetworkStateUseCaseImpl):
GetNetworkStateUseCase
@Binds
fun bindsSetTempFileUseCase(setTempFileUseCase: SetTempFileUseCaseImpl):
SetTempFileUseCase
} | 0 | Kotlin | 0 | 0 | 26b9ed440561b90d189901704e3800e870c6d64f | 1,132 | AwesomeSunsetWallpapers | Apache License 2.0 |
compiler/tests-spec/testData/diagnostics/notLinked/annotations/type-annotations/neg/11.kt | android | 263,405,600 | true | null | // !WITH_NEW_INFERENCE
/*
* KOTLIN DIAGNOSTICS NOT LINKED SPEC TEST (NEGATIVE)
*
* SECTIONS: annotations, type-annotations
* NUMBER: 11
* DESCRIPTION: Type annotations with invalid target.
* UNEXPECTED BEHAVIOUR
* ISSUES: KT-28449
*/
// TESTCASE NUMBER: 1, 2, 3, 4, 5
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY_GETTER)
annotation class Ann(val x: Int)
// TESTCASE NUMBER: 1
abstract class Foo : @<!DEBUG_INFO_MISSING_UNRESOLVED!>Ann<!>(10) Any()
// TESTCASE NUMBER: 2
abstract class Bar<T : @Ann(10) Any>
// TESTCASE NUMBER: 3
fun case_3(a: Any) {
if (a is @Ann(10) String) return
}
// TESTCASE NUMBER: 4
open class TypeToken<T>
val case_4 = object : TypeToken<@<!OI;DEBUG_INFO_MISSING_UNRESOLVED!>Ann<!>(10) String>() {}
// TESTCASE NUMBER: 5
fun case_5(a: Any) {
a as @<!DEBUG_INFO_MISSING_UNRESOLVED!>Ann<!>(10) Int
}
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 876 | kotlin | Apache License 2.0 |
app/src/main/java/com/example/bngelbooks/ui/StatisticsLayout/StatisticsPage.kt | Bngel | 311,304,375 | false | null | package com.example.bngelbooks.ui.StatisticsLayout
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.example.bngelbooks.R
import com.example.bngelbooks.logic.dao.OrderDao
import com.example.bngelbooks.logic.database.OrderDatabase
import com.example.bngelbooks.logic.model.*
import com.example.bngelbooks.ui.WidgetSetting
import kotlinx.android.synthetic.main.statistics_page_layout.*
import java.util.*
import kotlin.concurrent.thread
class StatisticsPage: Fragment() {
lateinit var orderDao: OrderDao
lateinit var orders : List<Order>
class OrderSum(val typeName: String, var Value: Double)
companion object {
val eat_sum = OrderSum("吃喝",0.0)
val traffic_sum = OrderSum("交通",0.0)
val clothes_sum = OrderSum( "服饰",0.0)
val daily_sum = OrderSum( "日用品",0.0)
val medical_sum = OrderSum( "医疗",0.0)
val study_sum = OrderSum( "学习",0.0)
val play_sum = OrderSum( "娱乐",0.0)
val others_sum = OrderSum( "其他",0.0)
val salary_sum = OrderSum("工资",0.0)
val partjob_sum = OrderSum("兼职",0.0)
val redlope_sum = OrderSum("红包",0.0)
fun get_sum_cost_list(): List<OrderSum> = listOf(
eat_sum, traffic_sum, clothes_sum, daily_sum, medical_sum, study_sum, play_sum,
others_sum
)
fun get_sum_income_list(): List<OrderSum> = listOf(
salary_sum, partjob_sum, redlope_sum
)
fun init_sum_list() {
eat_sum.Value= 0.0
traffic_sum.Value= 0.0
clothes_sum.Value= 0.0
daily_sum.Value= 0.0
medical_sum.Value= 0.0
study_sum.Value= 0.0
play_sum.Value= 0.0
others_sum.Value= 0.0
salary_sum.Value= 0.0
partjob_sum.Value= 0.0
redlope_sum.Value= 0.0
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WidgetSetting.chart_loading.observe(this, Observer {
if (it) {
init_costChart()
init_incomeChart()
}
})
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater.inflate(R.layout.statistics_page_layout, container, false)
return view
}
override fun onAttach(context: Context) {
super.onAttach(context)
orderDao = OrderDatabase.getDatabase(context).orderDao()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
init_costChart()
init_incomeChart()
}
private fun init_data() {
val year = Calendar.getInstance().get(Calendar.YEAR).toString()
val month = (Calendar.getInstance().get(Calendar.MONTH)+1).toString()
orders = orderDao.loadOrdersByMonth(year,month).asReversed()
init_sum_list()
for (order in orders) {
if (judgeIconType(order.TypeName) == "支出") {
when (order.TypeName) {
"吃喝" -> eat_sum.Value += order.Value
"交通" -> traffic_sum.Value += order.Value
"服饰" -> clothes_sum.Value += order.Value
"日用品" -> daily_sum.Value += order.Value
"医疗" -> medical_sum.Value += order.Value
"学习" -> study_sum.Value += order.Value
"娱乐" -> play_sum.Value += order.Value
"其他" -> others_sum.Value += order.Value
}
}
else {
when (order.TypeName) {
"工资" -> salary_sum.Value += order.Value
"兼职" -> partjob_sum.Value += order.Value
"红包" -> redlope_sum.Value += order.Value
}
}
}
}
private fun init_costChart() {
thread {
roseChart_Cost.setLoading(true) //是否正在加载,数据加载完毕后置为false
init_data()
roseChart_Cost.apply {
setShowChartLable(true) //是否在图表上显示指示lable
setShowChartNum(true) //是否在图表上显示指示num
setShowNumTouched(false) //点击显示数量
setShowRightNum(true) //右侧显示数量
//参数1:数据对象class, 参数2:数量属性字段名称, 参数3:名称属性字段名称, 参数4:数据集合
setData(OrderSum::class.java, "Value", "typeName", get_sum_cost_list())
setLoading(false) //是否正在加载,数据加载完毕后置为false
}
}
WidgetSetting.chart_loading.value = false
}
private fun init_incomeChart() {
thread {
roseChart_Income.setLoading(true) //是否正在加载,数据加载完毕后置为false
init_data()
roseChart_Income.apply {
setShowChartLable(true) //是否在图表上显示指示lable
setShowChartNum(true) //是否在图表上显示指示num
setShowNumTouched(false) //点击显示数量
setShowRightNum(true) //右侧显示数量
//参数1:数据对象class, 参数2:数量属性字段名称, 参数3:名称属性字段名称, 参数4:数据集合
setData(OrderSum::class.java, "Value", "typeName", get_sum_income_list())
setLoading(false) //是否正在加载,数据加载完毕后置为false
}
}
WidgetSetting.chart_loading.value = false
}
} | 0 | Kotlin | 0 | 0 | 4931e4dc12536a7ceed6f48099f4c3f312b151cb | 5,990 | BngelBooks | Apache License 2.0 |
common/presentation/src/main/java/currencyconverter/common/presentation/requester/OutOfMemoryErrorHandler.kt | ShabanKamell | 235,781,240 | false | null | package currencyconverter.common.presentation.requester
import com.sha.rxrequester.Presentable
import com.sha.rxrequester.exception.handler.throwable.ThrowableHandler
import currencyconverter.common.presentation.R
class OutOfMemoryErrorHandler : ThrowableHandler<OutOfMemoryError>() {
override fun supportedErrors(): List<Class<OutOfMemoryError>> = listOf(OutOfMemoryError::class.java)
override fun handle(throwable: Throwable, presentable: Presentable) {
presentable.showError(R.string.no_memory_free_up_space)
}
}
| 0 | Kotlin | 3 | 9 | 40cd5f4eae27217f7f36ed24f24e9d9bb94b4bfa | 540 | CurrencyConverter | Apache License 2.0 |
noria-common/src/main/kotlin/noria/components/FlexBox.kt | JetBrains | 114,139,208 | false | null | package noria.components
import noria.*
import noria.utils.*
enum class FlexDirection {
row, column, rowReverse, columnReverse;
override fun toString() = name.hyphenize()
}
enum class FlexWrap {
nowrap, wrap, wrapReverse;
override fun toString() = name.hyphenize()
}
val HBox = PlatformComponentType<BoxProps>()
val VBox = PlatformComponentType<BoxProps>()
class BoxProps : ContainerProps() {
var flexDirection: FlexDirection = FlexDirection.row
var flexWrap: FlexWrap? = null
var justifyContent: JustifyContent? = null
var alignItems: Align? = null
var alignContent: Align? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is BoxProps) return false
if (flexDirection != other.flexDirection) return false
if (flexWrap != other.flexWrap) return false
if (justifyContent != other.justifyContent) return false
if (alignItems != other.alignItems) return false
if (alignContent != other.alignContent) return false
return true
}
}
enum class Align {
// Basic keywords
auto,
stretch,
center,
flexStart,
flexEnd,
baseline;
override fun toString() = name.hyphenize()
}
enum class JustifyContent {
center,
start,
end,
flexStart,
flexEnd,
left,
right,
baseline,
firstBaseline,
lastBaseline,
spaceBetween,
spaceAround,
spaceEvenly,
stretch,
safeCenter,
unsafeCenter;
override fun toString() = name.hyphenize()
}
inline fun RenderContext.vbox(key: String? = null, builder: BoxProps.() -> Unit) {
x(VBox, key) {
flexDirection = FlexDirection.column
builder()
}
}
inline fun RenderContext.hbox(key: String? = null, builder: BoxProps.() -> Unit) {
x(HBox, key){
flexDirection = FlexDirection.row
builder()
}
}
| 2 | Kotlin | 6 | 15 | 4020d3aa4b99a9acac0616d0647f0b3d914a3e62 | 1,916 | noria-kt | Apache License 2.0 |
analysis/analysis-api/testData/components/expressionInfoProvider/isUsedAsExpression/elvisWithReturn.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | fun test() {
val x = 45 ?: <expr>return</expr>
return
}
// IGNORE_FE10
// FIR considers all expressions of type `Nothing` as unused. | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 141 | kotlin | Apache License 2.0 |
src/commonMain/kotlin/com/github/bschramke/checksum/algorithm/AlgorithmImpl.kt | bschramke | 187,829,271 | false | null | package com.github.bschramke.checksum.algorithm
import com.github.bschramke.checksum.reverseBits
import com.github.bschramke.checksum.xor
import kotlin.math.max
internal class RefOutAlgorithm(params: Algorithm.Params): Algorithm(params) {
override fun calculate(data: ByteArray, offset: Int, length: Int): Long {
with(params) {
var crc = params.seed.reverseBits(params.width)
for(i in offset until offset + length) {
val idx = ((crc xor data[i]) and 0xFF).toInt()
crc = table[idx] xor (crc ushr 8)
crc = crc and mask
}
return (crc xor xorOut) and mask
}
}
}
internal class NoRefOutAlgorithm(params: Algorithm.Params): Algorithm(params) {
private val toRight = max(params.width - 8, 0)
override fun calculate(data: ByteArray, offset: Int, length: Int): Long {
with(params) {
var crc = params.seed
for(i in offset until offset + length) {
val idx = (((crc shr toRight) xor data[i]) and 0xFF).toInt()
crc = table[idx] xor (crc shl 8)
crc = crc and mask
}
return (crc xor xorOut) and mask
}
}
} | 0 | Kotlin | 0 | 0 | 8b058a741caccb7fddb632067807572dcce750ba | 1,244 | checksum | MIT License |
compiler/test/data/typescript/node_modules/module/exportAssignment/exportVarInNonExternalModule.d.kt | Kotlin | 159,510,660 | false | {"Kotlin": 2656346, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333} | // [test] exportVarInNonExternalModule.module_resolved_name.kt
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
import myNamespace.MyInterface
@JsModule("resolved_name")
external val classInstance: MyInterface
// ------------------------------------------------------------------------------------------
// [test] exportVarInNonExternalModule.myNamespace.module_resolved_name.kt
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
package myNamespace
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
external interface MyInterface | 242 | Kotlin | 43 | 508 | 55213ea607fb42ff13b6278613c8fbcced9aa418 | 1,301 | dukat | Apache License 2.0 |
compiler/fir/fir-serialization/src/org/jetbrains/kotlin/fir/serialization/FirAnnotationArgumentVisitor.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.serialization
import org.jetbrains.kotlin.constant.*
import org.jetbrains.kotlin.fir.serialization.constant.*
import org.jetbrains.kotlin.fir.types.ConeKotlinType
import org.jetbrains.kotlin.fir.types.arrayElementType
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.Flags
internal object FirAnnotationArgumentVisitor : AnnotationArgumentVisitor<Unit, FirAnnotationArgumentVisitorData>() {
override fun visitAnnotationValue(value: AnnotationValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.ANNOTATION
data.builder.annotation = data.serializer.serializeAnnotation(value)
}
override fun visitArrayValue(value: ArrayValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.ARRAY
for (element in value.value) {
data.builder.addArrayElement(data.serializer.valueProto(element).build())
}
}
override fun visitBooleanValue(value: BooleanValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.BOOLEAN
data.builder.intValue = if (value.value) 1 else 0
}
override fun visitByteValue(value: ByteValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.BYTE
data.builder.intValue = value.value.toLong()
}
override fun visitCharValue(value: CharValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.CHAR
data.builder.intValue = value.value.code.toLong()
}
override fun visitDoubleValue(value: DoubleValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.DOUBLE
data.builder.doubleValue = value.value
}
override fun visitEnumValue(value: EnumValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.ENUM
data.builder.classId = data.stringTable.getQualifiedClassNameIndex(value.enumClassId)
data.builder.enumValueId = data.stringTable.getStringIndex(value.enumEntryName.asString())
}
override fun visitErrorValue(value: ErrorValue, data: FirAnnotationArgumentVisitorData) {
throw UnsupportedOperationException("Error value: $value")
}
override fun visitFloatValue(value: FloatValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.FLOAT
data.builder.floatValue = value.value
}
override fun visitIntValue(value: IntValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.INT
data.builder.intValue = value.value.toLong()
}
override fun visitKClassValue(value: KClassValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.CLASS
when (val classValue = value.value) {
is KClassValue.Value.NormalClass -> {
data.builder.classId = data.stringTable.getQualifiedClassNameIndex(classValue.classId)
if (classValue.arrayDimensions > 0) {
data.builder.arrayDimensionCount = classValue.arrayDimensions
}
}
is KClassValue.Value.LocalClass -> {
var arrayDimensions = 0
var type = classValue.coneType<ConeKotlinType>()
while (true) {
type = type.arrayElementType() ?: break
arrayDimensions++
}
//val descriptor = type.constructor.declarationDescriptor as? ClassDescriptor
// ?: error("Type parameters are not allowed in class literal annotation arguments: $classValue")
// TODO: classId = stringTable.getFqNameIndex(descriptor)
if (arrayDimensions > 0) {
data.builder.arrayDimensionCount = arrayDimensions
}
}
}
}
override fun visitLongValue(value: LongValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.LONG
data.builder.intValue = value.value
}
override fun visitNullValue(value: NullValue, data: FirAnnotationArgumentVisitorData) {
throw UnsupportedOperationException("Null should not appear in annotation arguments")
}
override fun visitShortValue(value: ShortValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.SHORT
data.builder.intValue = value.value.toLong()
}
override fun visitStringValue(value: StringValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.STRING
data.builder.stringValue = data.stringTable.getStringIndex(value.value)
}
override fun visitUByteValue(value: UByteValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.BYTE
data.builder.intValue = value.value.toLong()
data.builder.flags = Flags.IS_UNSIGNED.toFlags(true)
}
override fun visitUShortValue(value: UShortValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.SHORT
data.builder.intValue = value.value.toLong()
data.builder.flags = Flags.IS_UNSIGNED.toFlags(true)
}
override fun visitUIntValue(value: UIntValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.INT
data.builder.intValue = value.value.toLong()
data.builder.flags = Flags.IS_UNSIGNED.toFlags(true)
}
override fun visitULongValue(value: ULongValue, data: FirAnnotationArgumentVisitorData) {
data.builder.type = ProtoBuf.Annotation.Argument.Value.Type.LONG
data.builder.intValue = value.value
data.builder.flags = Flags.IS_UNSIGNED.toFlags(true)
}
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 6,486 | kotlin | Apache License 2.0 |
app/src/main/java/com/anyjob/ui/explorer/search/controls/bottomSheets/addresses/AddressesBottomSheetDialog.kt | y0ung3r | 485,848,073 | false | {"Kotlin": 142952} | package com.anyjob.ui.explorer.search.controls.bottomSheets.addresses
import android.content.Context
import android.content.res.Resources
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import com.anyjob.R
import com.anyjob.databinding.AddressesBottomSheetBinding
import com.anyjob.ui.explorer.search.controls.bottomSheets.addresses.adapters.AddressesAdapter
import com.anyjob.ui.explorer.search.controls.bottomSheets.addresses.models.UserAddress
import com.anyjob.ui.extensions.afterTextChanged
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.Exception
import java.util.*
class AddressesBottomSheetDialog(
context: Context,
theme: Int,
private val onItemClick: ((UserAddress) -> Unit)? = null
) : BottomSheetDialog(context, theme) {
private val _binding: AddressesBottomSheetBinding by lazy {
AddressesBottomSheetBinding.inflate(layoutInflater)
}
private lateinit var _addressesAdapter: AddressesAdapter
private fun onAddressChanged(address: String) {
GlobalScope.launch {
try {
val maxResults = 10
val geocoder = Geocoder(
context,
Locale.getDefault()
)
// TODO: Переписать поиск адреса с использованием Google Location API
val addresses = withContext(Dispatchers.Default) {
geocoder.getFromLocationName(address, maxResults)
}
_addressesAdapter = AddressesAdapter(
addresses,
onItemClick
)
_binding.addressesList.adapter = _addressesAdapter
_addressesAdapter.notifyDataSetChanged()
}
catch (exception: Exception) {
// Ignore...
}
}
}
private fun setupFullHeight() {
val bottomSheet = findViewById<View>(R.id.design_bottom_sheet)
if (bottomSheet != null) {
val layoutParams = bottomSheet.layoutParams
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT
bottomSheet.layoutParams = layoutParams
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(_binding.root)
setupFullHeight()
_binding.addressField.afterTextChanged(::onAddressChanged)
_addressesAdapter = AddressesAdapter(
ArrayList<Address>(),
onItemClick
)
_binding.addressesList.adapter = _addressesAdapter
}
} | 0 | Kotlin | 0 | 0 | 13819fcf4ad8e944bbb025a9598c08316cdcfab7 | 2,966 | AnyJob | MIT License |
agp-7.1.0-alpha01/tools/base/wizard/template-impl/src/com/android/tools/idea/wizard/template/impl/fragments/listFragment/src/app_package/recyclerViewAdapterKt.kt | jomof | 374,736,765 | 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.listFragment.src.app_package
import com.android.tools.idea.wizard.template.Language
import com.android.tools.idea.wizard.template.getMaterialComponentName
import com.android.tools.idea.wizard.template.impl.activities.common.importViewBindingClass
import com.android.tools.idea.wizard.template.impl.activities.common.layoutToViewBindingClass
import com.android.tools.idea.wizard.template.renderIf
fun recyclerViewAdapterKt(
adapterClassName: String,
applicationPackage: String?,
fragmentLayout: String,
kotlinEscapedPackageName: String,
useAndroidX: Boolean,
isViewBindingSupported: Boolean
): String {
val onCreateViewHolderBlock = if (isViewBindingSupported) """
return ViewHolder(${layoutToViewBindingClass(fragmentLayout)}.inflate(LayoutInflater.from(parent.context), parent, false))
""" else """
val view = LayoutInflater.from(parent.context).inflate(R.layout.${fragmentLayout}, parent, false)
return ViewHolder(view)
"""
val viewHolderBlock = if (isViewBindingSupported) """
inner class ViewHolder(binding: ${layoutToViewBindingClass(fragmentLayout)}) : RecyclerView.ViewHolder(binding.root) {
val idView: TextView = binding.itemNumber
val contentView: TextView = binding.content
override fun toString(): String {
return super.toString() + " '" + contentView.text + "'"
}
}
""" else """
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val idView: TextView = view.findViewById(R.id.item_number)
val contentView: TextView = view.findViewById(R.id.content)
override fun toString(): String {
return super.toString() + " '" + contentView.text + "'"
}
}
"""
return """
package ${kotlinEscapedPackageName}
import ${getMaterialComponentName("android.support.v7.widget.RecyclerView", useAndroidX)}
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
${renderIf(applicationPackage != null) { "import ${applicationPackage}.R" }}
import ${kotlinEscapedPackageName}.placeholder.PlaceholderContent.PlaceholderItem
${importViewBindingClass(isViewBindingSupported, kotlinEscapedPackageName, fragmentLayout, Language.Kotlin)}
/**
* [RecyclerView.Adapter] that can display a [PlaceholderItem].
* TODO: Replace the implementation with code for your data type.
*/
class ${adapterClassName}(
private val values: List<PlaceholderItem>)
: RecyclerView.Adapter<${adapterClassName}.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
$onCreateViewHolderBlock
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = values[position]
holder.idView.text = item.id
holder.contentView.text = item.content
}
override fun getItemCount(): Int = values.size
$viewHolderBlock
}
"""
}
| 1 | Java | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 3,621 | CppBuildCacheWorkInProgress | Apache License 2.0 |
relateddigital-android/src/main/java/com/relateddigital/relateddigital_android/model/ExtendedProps.kt | relateddigital | 379,568,070 | false | {"Kotlin": 1485751, "HTML": 21295} | package com.relateddigital.relateddigital_android.model
import android.content.Context
import java.io.Serializable
import android.graphics.Typeface
import androidx.core.content.res.ResourcesCompat
import com.relateddigital.relateddigital_android.inapp.FontFamily
import com.relateddigital.relateddigital_android.util.AppUtils.isFontResourceAvailable
import java.util.*
class ExtendedProps : Serializable {
val title_text_color: String? = null
val title_font_family: String? = null
val title_custom_font_family_ios: String? = null
val title_custom_font_family_android: String? = null
val title_text_size: String? = null
val text_color: String? = null
val text_font_family: String? = null
val text_custom_font_family_ios: String? = null
val text_custom_font_family_android: String? = null
val text_size: String? = null
val button_color: String? = null
val button_text_color: String? = null
val button_font_family: String? = null
val button_custom_font_family_ios: String? = null
val button_custom_font_family_android: String? = null
val button_text_size: String? = null
val emailpermit_text_size: String? = null
val emailpermit_text_url: String? = null
val consent_text_size: String? = null
val consent_text_url: String? = null
val close_button_color: String? = null
val background_color: String? = null
fun getTitleFontFamily(context: Context): Typeface? {
if (title_font_family.isNullOrEmpty()) {
return Typeface.DEFAULT
}
if (FontFamily.Monospace.toString() == title_font_family.lowercase(Locale.getDefault())) {
return Typeface.MONOSPACE
}
if (FontFamily.SansSerif.toString() == title_font_family.lowercase(Locale.getDefault())) {
return Typeface.SANS_SERIF
}
if (FontFamily.Serif.toString() == title_font_family.lowercase(Locale.getDefault())) {
return Typeface.SERIF
}
if (!title_custom_font_family_android.isNullOrEmpty()) {
if (isFontResourceAvailable(context, title_custom_font_family_android)) {
val id: Int = context.resources.getIdentifier(
title_custom_font_family_android,
"font",
context.packageName
)
return ResourcesCompat.getFont(context, id)
}
}
return Typeface.DEFAULT
}
fun getTextFontFamily(context: Context): Typeface? {
if (text_font_family.isNullOrEmpty()) {
return Typeface.DEFAULT
}
if (FontFamily.Monospace.toString() == text_font_family.lowercase(Locale.getDefault())) {
return Typeface.MONOSPACE
}
if (FontFamily.SansSerif.toString() == text_font_family.lowercase(Locale.getDefault())) {
return Typeface.SANS_SERIF
}
if (FontFamily.Serif.toString() == text_font_family.lowercase(Locale.getDefault())) {
return Typeface.SERIF
}
if (!text_custom_font_family_android.isNullOrEmpty()) {
if (isFontResourceAvailable(context, text_custom_font_family_android)) {
val id: Int = context.resources.getIdentifier(
text_custom_font_family_android,
"font",
context.packageName
)
return ResourcesCompat.getFont(context, id)
}
}
return Typeface.DEFAULT
}
fun getButtonFontFamily(context: Context): Typeface? {
if (button_font_family.isNullOrEmpty()) {
return Typeface.DEFAULT
}
if (FontFamily.Monospace.toString() == button_font_family.lowercase(Locale.getDefault())) {
return Typeface.MONOSPACE
}
if (FontFamily.SansSerif.toString() == button_font_family.lowercase(Locale.getDefault())) {
return Typeface.SANS_SERIF
}
if (FontFamily.Serif.toString() == button_font_family.lowercase(Locale.getDefault())) {
return Typeface.SERIF
}
if (!button_custom_font_family_android.isNullOrEmpty()) {
if (isFontResourceAvailable(context, button_custom_font_family_android)) {
val id: Int = context.resources.getIdentifier(
button_custom_font_family_android,
"font",
context.packageName
)
return ResourcesCompat.getFont(context, id)
}
}
return Typeface.DEFAULT
}
} | 0 | Kotlin | 2 | 5 | cedee02f6ab0f05d08a34a662193d47edf55a8f8 | 4,587 | relateddigital-android | Amazon Digital Services License |
m4-hw6-vafs-biz/src/test/kotlin/auth/RuleCrudAuthTest.kt | smith1984 | 587,390,812 | false | null | package ru.beeline.vafs.biz.auth
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import ru.beeline.vafs.biz.VafsRuleProcessor
import ru.beeline.vafs.common.VafsContext
import ru.beeline.vafs.common.VafsCorSettings
import ru.beeline.vafs.common.models.*
import ru.beeline.vafs.common.permissions.VafsRulePermissionOperator
import ru.beeline.vafs.common.permissions.VafsPrincipalModel
import ru.beeline.vafs.common.permissions.VafsUserGroups
import ru.beeline.vafs.repo.inmemory.RuleRepoInMemory
import ru.beeline.vafs.stub.VafsRuleStub
import kotlin.test.*
@OptIn(ExperimentalCoroutinesApi::class)
class RuleCrudAuthTest {
@Test
fun createSuccessTest() = runTest {
val userId = VafsUserId("123")
val repo = RuleRepoInMemory()
val processor = VafsRuleProcessor(
settings = VafsCorSettings(
repoTest = repo
)
)
val context = VafsContext(
workMode = VafsWorkMode.TEST,
ruleRequest = VafsRuleStub.prepareResult {
permissionsOperator.clear()
id = VafsRuleId.NONE
},
command = VafsCommand.CREATE,
principal = VafsPrincipalModel(
id = userId,
groups = setOf(
VafsUserGroups.USER,
VafsUserGroups.TEST,
)
)
)
processor.exec(context)
assertEquals(VafsState.FINISHING, context.state)
with(context.ruleResponse) {
assertTrue { id.asString().isNotBlank() }
assertContains(permissionsOperator, VafsRulePermissionOperator.READ)
assertContains(permissionsOperator, VafsRulePermissionOperator.UPDATE)
assertContains(permissionsOperator, VafsRulePermissionOperator.DELETE)
}
}
@Test
fun readSuccessTest() = runTest {
val ruleObj = VafsRuleStub.get()
val userId = ruleObj.userId
val ruleId = ruleObj.id
val repo = RuleRepoInMemory(initObjects = listOf(ruleObj))
val processor = VafsRuleProcessor(
settings = VafsCorSettings(
repoTest = repo
)
)
val context = VafsContext(
command = VafsCommand.READ,
workMode = VafsWorkMode.TEST,
ruleRequest = VafsRule(id = ruleId),
principal = VafsPrincipalModel(
id = userId,
groups = setOf(
VafsUserGroups.USER,
VafsUserGroups.TEST,
)
)
)
processor.exec(context)
assertEquals(VafsState.FINISHING, context.state)
with(context.ruleResponse) {
assertTrue { id.asString().isNotBlank() }
assertContains(permissionsOperator, VafsRulePermissionOperator.READ)
assertContains(permissionsOperator, VafsRulePermissionOperator.UPDATE)
assertContains(permissionsOperator, VafsRulePermissionOperator.DELETE)
}
}
}
| 0 | Kotlin | 0 | 0 | 9b428e70d881e39ffc1f6b5856ea6256416c4ce3 | 3,081 | otuskotlin | Apache License 2.0 |
app/src/main/java/com/example/demotest/register/RegistrationActivity.kt | ahmedfadul123 | 534,165,660 | false | {"Kotlin": 18139} | package com.example.demotest.register
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.appcompat.widget.Toolbar
import com.example.demotest.R
import com.example.demotest.databinding.ActivityLoginBinding
import com.example.demotest.databinding.ActivityRegisterationBinding
import com.example.demotest.login.LoginActivity
class RegistrationActivity : AppCompatActivity() {
private lateinit var binding : ActivityRegisterationBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRegisterationBinding.inflate(layoutInflater)
setContentView(binding.root)
val toolbar : Toolbar = binding.toolbar;
setSupportActionBar(toolbar)
supportActionBar!!.title = ""
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
binding.Loginbtn.setOnClickListener {
finish();
val intent = Intent(this@RegistrationActivity,LoginActivity::class.java)
startActivity(intent)
}
}
} | 0 | Kotlin | 0 | 0 | f9256c7bc24ce3765d24793220aac93fd09ff4dc | 1,105 | Login-Ui | Apache License 2.0 |
app/src/main/java/org/simple/clinic/bloodsugar/entry/confirmremovebloodsugar/ConfirmRemoveBloodSugarDialogInjector.kt | simpledotorg | 132,515,649 | false | {"Kotlin": 5970450, "Shell": 1660, "HTML": 545} | package org.simple.clinic.bloodsugar.entry.confirmremovebloodsugar
interface ConfirmRemoveBloodSugarDialogInjector {
fun inject(target: ConfirmRemoveBloodSugarDialog)
}
| 4 | Kotlin | 73 | 223 | 58d14c702db2b27b9dc6c1298c337225f854be6d | 172 | simple-android | MIT License |
src/main/kotlin/io/pivotal/TestInterceptor.kt | mikfreedman | 90,070,334 | false | null | package io.pivotal
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpMethod
import org.springframework.stereotype.Component
import javax.servlet.http.HttpServletResponse
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.HandlerInterceptor
import javax.security.auth.login.CredentialException
import javax.servlet.http.HttpServletRequest
@Component
class TestInterceptor : HandlerInterceptor {
@Value("\${blobber.api_key}")
lateinit var apiKey: String
override fun postHandle(request: HttpServletRequest?, response: HttpServletResponse?, handler: Any?, modelAndView: ModelAndView?) {
}
override fun afterCompletion(request: HttpServletRequest?, response: HttpServletResponse?, handler: Any?, ex: java.lang.Exception?) {
}
@Throws(Exception::class)
override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
val supppliedApiKey = request.getHeader("X-API-KEY")
val isGet = request.method == HttpMethod.GET.toString()
if (isGet || (supppliedApiKey == apiKey)) {
return true
}
throw HttpUnauthorizedException()
}
} | 0 | Kotlin | 0 | 2 | 47cb998ed871f8606a6c6c98aa0ee5c7e5940bc7 | 1,242 | blobber | MIT License |
app/src/main/java/com/mrb/remember/presentation/levels/LevelsViewModel.kt | mrebollob | 183,808,523 | false | null | package com.mrb.remember.presentation.levels
import androidx.lifecycle.MutableLiveData
import com.mrb.remember.domain.interactor.GetCompletedDay
import com.mrb.remember.domain.interactor.GetHomework
import com.mrb.remember.domain.interactor.SaveCompletedDay
import com.mrb.remember.domain.interactor.UseCase
import com.mrb.remember.domain.model.Homework
import com.mrb.remember.domain.model.LeitnerDay
import com.mrb.remember.presentation.platform.BaseViewModel
import com.mrb.remember.testing.OpenForTesting
import javax.inject.Inject
@OpenForTesting
class LevelsViewModel @Inject constructor(
private val getCompletedDay: GetCompletedDay,
private val saveCompletedDay: SaveCompletedDay,
private val getHomework: GetHomework
) : BaseViewModel() {
var homework: MutableLiveData<Homework> = MutableLiveData()
var completedDay: MutableLiveData<LeitnerDay> = MutableLiveData()
fun init() {
showLoading()
getCompletedDay(UseCase.None()) {
it.either(::handleFailure, ::handleLeitnerDay)
}
}
fun setCompletedDay(day: LeitnerDay) {
saveCompletedDay(SaveCompletedDay.Params(day)) {
it.either(::handleFailure, ::handleCompletedDay)
}
}
private fun handleCompletedDay(day: LeitnerDay) {
this.completedDay.value = day
}
private fun handleLeitnerDay(leitnerDay: LeitnerDay) {
getHomework(GetHomework.Params(leitnerDay.dayNumber + 1)) {
it.either(::handleFailure, ::handleHomework)
}
}
private fun handleHomework(homework: Homework) {
hideLoading()
this.homework.value = homework
}
} | 0 | Kotlin | 0 | 0 | 9aa05168f4302eaba1618dce322c5959b3d9926b | 1,654 | remember | Apache License 2.0 |
ast-transformations-core/src/main/kotlin/org/jetbrains/research/ml/ast/transformations/anonymization/RenameUtil.kt | JetBrains-Research | 301,993,261 | false | {"Kotlin": 148658, "Python": 27810} | package org.jetbrains.research.ml.ast.transformations.anonymization
import com.intellij.psi.PsiElement
import com.intellij.refactoring.rename.RenamePsiElementProcessor
import com.intellij.usageView.UsageInfo
object RenameUtil {
fun renameElementDelayed(definition: PsiElement, newName: String): () -> Unit {
val processor = RenamePsiElementProcessor.forElement(definition)
val allRenames = mutableMapOf(definition to newName)
processor.prepareRenaming(definition, newName, allRenames)
val delayedRenames = allRenames.map { renameSingleElementDelayed(it.key, it.value) }
return { delayedRenames.forEach { it() } }
}
private fun renameSingleElementDelayed(definition: PsiElement, newName: String): () -> Unit {
val processor = RenamePsiElementProcessor.forElement(definition)
val useScope = definition.useScope
val references = processor.findReferences(definition, useScope, false)
val usages = references.map { UsageInfo(it) }.toTypedArray()
return { processor.renameElement(definition, newName, usages, null) }
}
}
| 0 | Kotlin | 2 | 17 | aff0459b2018f63c1295edc0022556b30113b9c5 | 1,115 | bumblebee | MIT License |
compiler/ir/serialization.common/src/org/jetbrains/kotlin/backend/common/serialization/mangle/MangleMode.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.common.serialization.mangle
enum class MangleMode(val signature: Boolean, val fqn: Boolean) {
SIGNATURE(true, false),
FQNAME(false, true),
FULL(true, true)
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 417 | kotlin | Apache License 2.0 |
src/main/kotlin/auth0/invite/InviterCommand.kt | rlconst | 508,211,283 | false | null | package auth0.invite
import io.micronaut.configuration.picocli.PicocliRunner
import io.micronaut.context.annotation.Property
import io.micronaut.http.HttpRequest.POST
import io.micronaut.http.HttpStatus
import io.micronaut.http.MediaType
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.uri.UriBuilder
import jakarta.inject.Inject
import picocli.CommandLine.Command
import picocli.CommandLine.Option
@Command(
name = "inviter", description = ["..."],
mixinStandardHelpOptions = true
)
open class InviterCommand : Runnable {
@field:Property(name = "client.id")
protected lateinit var clientId: String
@field:Property(name = "client.secret")
protected lateinit var clientSecret: String
@field:Property(name = "client.domain")
protected lateinit var clientDomain: String
@field:Property(name = "client.audience")
protected lateinit var clientAudience: String
@field:Property(name = "client.connection")
protected lateinit var clientConnection: String
@field:Property(name = "roles")
protected lateinit var userRoles: Map<String, String>
@field:Client("\${client.domain}")
@Inject
lateinit var httpClient: HttpClient
@Option(
names = ["-e", "--email"],
description = ["User email to send invite e.g. <EMAIL>"],
required = true
)
private lateinit var email: String
@Option(names = ["-n", "--name"], description = ["User name e.g. <NAME>"], required = true)
private lateinit var name: String
@Option(names = ["-r", "--roles"], description = ["Roles e.g. user"], required = true, arity = "1..*")
private lateinit var roles: List<String>
@Option(names = ["-o", "--organization"], description = ["Organization ids org_abcdefgh"], required = true)
private lateinit var organization: String
override fun run() {
try {
println("Invite $email/$name to $organization with $roles")
val authResponse = httpClient.toBlocking().retrieve(
POST(
"/oauth/token",
AuthRequest("client_credentials", clientId, clientSecret, clientAudience)
).header("content-type", MediaType.APPLICATION_FORM_URLENCODED),
AuthResponse::class.java
)
println("Token requested")
Thread.sleep(100)
val createUserResponse = httpClient.toBlocking().retrieve(
POST(
"/api/v2/users",
CreateUserRequest(email, name, clientConnection, generatePassword(), true)
)
.header("content-type", MediaType.APPLICATION_JSON)
.bearerAuth(authResponse.access_token),
CreateUserResponse::class.java
)
println("User ${createUserResponse.user_id} created")
Thread.sleep(100)
val roleIds = roles.map { userRoles[it]!! }
httpClient.toBlocking().retrieve(
POST(
UriBuilder.of("/api/v2/users/{user_id}/roles")
.expand(mutableMapOf("user_id" to createUserResponse.user_id)),
AssignRoleRequest(roleIds)
)
.header("content-type", MediaType.APPLICATION_JSON)
.bearerAuth(authResponse.access_token),
HttpStatus.NO_CONTENT::class.java
)
println("Roles $roleIds granted to ${createUserResponse.user_id}")
Thread.sleep(100)
httpClient.toBlocking().retrieve(
POST(
UriBuilder.of("/api/v2/organizations/{org_id}/members")
.expand(mutableMapOf("org_id" to organization)),
AttachToOrganizationRequest(listOf(createUserResponse.user_id))
)
.header("content-type", MediaType.APPLICATION_JSON)
.bearerAuth(authResponse.access_token),
HttpStatus.NO_CONTENT::class.java
)
println("User ${createUserResponse.user_id} invited to $organization")
Thread.sleep(100)
httpClient.toBlocking().retrieve(
POST(
"/dbconnections/change_password",
ResetPasswordRequest(clientId, clientConnection, email)
)
.header("content-type", MediaType.APPLICATION_JSON)
.bearerAuth(authResponse.access_token),
String::class.java
)
println("Password reset for ${createUserResponse.user_id}")
} catch (e: Exception) {
println(e.message)
e.printStackTrace()
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
PicocliRunner.run(InviterCommand::class.java, *args)
}
}
}
| 0 | Kotlin | 0 | 0 | 4f7a73f9185b5774a205e148f593173118007e1a | 4,995 | inviter | MIT License |
YTKJsBridge/ytkjsbridgex5/src/androidTest/java/com/fenbi/android/ytkjsbridgex5/TestCallNative.kt | yuantiku | 162,675,718 | false | null | package com.fenbi.android.ytkjsbridgex5
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import android.webkit.JavascriptInterface
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* Created by yangjw on 2019/1/9.
*/
@RunWith(AndroidJUnit4::class)
class TestCallNative {
private fun initWebView() = WebView(InstrumentationRegistry.getInstrumentation().targetContext).apply {
webViewClient = WebViewClient()
webChromeClient = WebChromeClient()
initYTKJsBridge()
}
@Test
fun testCallNative() {
val countDownLatch = CountDownLatch(1)
var ret: String? = ""
InstrumentationRegistry.getInstrumentation().runOnMainSync {
val webView = initWebView()
webView.addYTKJavascriptInterface(object {
@JavascriptInterface
fun testNative(msg: String?) {
ret = msg
countDownLatch.countDown()
}
})
webView.loadUrl("file:///android_asset/test-call-native.html")
}
countDownLatch.await(60, TimeUnit.SECONDS)
assertEquals("hello world", ret)
}
} | 0 | Kotlin | 4 | 6 | 411bd96352746addfafcfc06c973ebe8e8ddcb11 | 1,467 | YTKJsBridge-Android | MIT License |
app/src/main/java/com/techeniac/healthsample/data/DataManager.kt | Robinson2021 | 430,742,193 | false | {"Kotlin": 43593} | package com.techeniac.healthsample.data
import com.techeniac.healthsample.data.local.prefs.PreferencesHelper
import com.techeniac.healthsample.data.remote.ApiHelper
/**
* Created by Robinson on 18 Nov 2021
*/
interface DataManager: PreferencesHelper, ApiHelper {
enum class LoggedMode constructor(val type: Int) {
LOGGED_OUT(0),
LOGGED_IN(1),
}
} | 0 | Kotlin | 0 | 0 | dfd6363b60f952ef80cb21b70bb84d273ae211e4 | 375 | HealthDemo | Apache License 2.0 |
src/main/kotlin/settings/ApplicationSettings.kt | cmcpasserby | 40,443,319 | false | {"Kotlin": 60724, "Python": 3244} | package settings
import mayacomms.mayaFromMayaPy
import mayacomms.mayaPyExecutableName
import com.intellij.openapi.components.*
import com.jetbrains.python.sdk.PythonSdkUtil
import java.util.*
typealias SdkPortMap = MutableMap<String, ApplicationSettings.SdkInfo>
private val portRange = (4434..4534).toSet()
@State(
name = "MCAppSettings",
storages = [Storage(value = "mayacharm.settings.xml", roamingType = RoamingType.DISABLED)]
)
class ApplicationSettings : PersistentStateComponent<ApplicationSettings.State> {
data class SdkInfo(var mayaPyPath: String = "", var port: Int = -1) {
val mayaPath: String
get() = mayaFromMayaPy(mayaPyPath) ?: ""
}
data class State(var mayaSdkMapping: SdkPortMap = mutableMapOf())
private var myState = State()
companion object {
val INSTANCE: ApplicationSettings
get() = service()
}
init {
val mayaSdk =
PythonSdkUtil.getAllLocalCPythons().filter { it.homePath?.endsWith(mayaPyExecutableName) ?: false }
val homePaths = mayaSdk.map { it.homePath!! }
for (path in homePaths) {
mayaSdkMapping[path] = SdkInfo(path, -1)
}
assignEmptyPorts()
}
var mayaSdkMapping: SdkPortMap
get() = myState.mayaSdkMapping
set(value) {
myState.mayaSdkMapping = value
}
override fun getState(): State {
return myState
}
override fun loadState(state: State) {
val mayaPySdks =
PythonSdkUtil.getAllLocalCPythons().filter { x -> x.homePath?.endsWith(mayaPyExecutableName) ?: false }
val homePaths = mayaPySdks.map { it.homePath!! }
mayaSdkMapping.clear()
for (path in homePaths) {
if (state.mayaSdkMapping.containsKey(path)) {
mayaSdkMapping[path] = state.mayaSdkMapping[path]!!
continue
}
mayaSdkMapping[path] = SdkInfo(path, -1)
}
assignEmptyPorts()
}
fun refreshPythonSdks() {
val mayaSdk =
PythonSdkUtil.getAllLocalCPythons().filter { it.homePath?.endsWith(mayaPyExecutableName) ?: false }
val homePathsSet = mayaSdk.map { it.homePath!! }.toSet()
val sdkMappingKeySet = mayaSdkMapping.keys.toSet()
val toAdd = homePathsSet - sdkMappingKeySet
val toRemove = sdkMappingKeySet - homePathsSet
for (path in toRemove) {
mayaSdkMapping.remove(path)
}
for (path in toAdd) {
mayaSdkMapping[path] = SdkInfo(path, -1)
}
assignEmptyPorts()
}
private fun assignEmptyPorts() {
val usedPorts = mayaSdkMapping.map { it.value.port }.filter { it > 0 }.toSet()
val freePorts = PriorityQueue((portRange - usedPorts).sorted())
for (key in mayaSdkMapping.filter { it.value.port < 0 }.keys) {
mayaSdkMapping[key]!!.port = freePorts.remove()
}
}
fun getUnusedPort(): Int {
val usedPorts = mayaSdkMapping.map { it.value.port }.filter { it > 0 }.toSet()
val freePorts = PriorityQueue((portRange - usedPorts).sorted())
return freePorts.remove()
}
}
| 5 | Kotlin | 44 | 163 | 5b235c2850deec603f9295ed711aba2c249bf163 | 3,204 | MayaCharm | MIT License |
compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/scroll/BringIntoViewDemo.kt | RikkaW | 389,105,112 | true | {"Java": 49060640, "Kotlin": 36832495, "Python": 336507, "AIDL": 179831, "Shell": 150493, "C++": 38342, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343} | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.demos.scroll
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.FlingBehavior
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Blue
import androidx.compose.ui.graphics.Color.Companion.Cyan
import androidx.compose.ui.graphics.Color.Companion.DarkGray
import androidx.compose.ui.graphics.Color.Companion.Gray
import androidx.compose.ui.graphics.Color.Companion.Green
import androidx.compose.ui.graphics.Color.Companion.LightGray
import androidx.compose.ui.graphics.Color.Companion.Magenta
import androidx.compose.ui.graphics.Color.Companion.Red
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.graphics.Color.Companion.Yellow
import androidx.compose.ui.layout.RelocationRequester
import androidx.compose.ui.layout.onRelocationRequest
import androidx.compose.ui.layout.relocationRequester
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.toSize
import kotlinx.coroutines.launch
import kotlin.math.abs
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun BringIntoViewDemo() {
val greenRequester = remember { RelocationRequester() }
val redRequester = remember { RelocationRequester() }
val coroutineScope = rememberCoroutineScope()
Column {
Column(
Modifier.requiredHeight(100.dp).verticalScrollWithRelocation(rememberScrollState())
) {
Row(Modifier.width(300.dp).horizontalScrollWithRelocation(rememberScrollState())) {
Box(Modifier.background(Blue).size(100.dp))
Box(Modifier.background(Green).size(100.dp).relocationRequester(greenRequester))
Box(Modifier.background(Yellow).size(100.dp))
Box(Modifier.background(Magenta).size(100.dp))
Box(Modifier.background(Gray).size(100.dp))
Box(Modifier.background(Black).size(100.dp))
}
Row(Modifier.width(300.dp).horizontalScrollWithRelocation(rememberScrollState())) {
Box(Modifier.background(Black).size(100.dp))
Box(Modifier.background(Cyan).size(100.dp))
Box(Modifier.background(DarkGray).size(100.dp))
Box(Modifier.background(White).size(100.dp))
Box(Modifier.background(Red).size(100.dp).relocationRequester(redRequester))
Box(Modifier.background(LightGray).size(100.dp))
}
}
Button(onClick = { coroutineScope.launch { greenRequester.bringIntoView() } }) {
Text("Bring Green box into view")
}
Button(onClick = { coroutineScope.launch { redRequester.bringIntoView() } }) {
Text("Bring Red box into view")
}
}
}
// This is a helper function that users will have to use since experimental "ui" API cannot be used
// inside Scrollable, which is ihe "foundation" package. After onRelocationRequest is added
// to Scrollable, users can use Modifier.horizontalScroll directly.
@OptIn(ExperimentalComposeUiApi::class)
private fun Modifier.horizontalScrollWithRelocation(
state: ScrollState,
enabled: Boolean = true,
flingBehavior: FlingBehavior? = null,
reverseScrolling: Boolean = false
): Modifier {
return this
.onRelocationRequest(
onProvideDestination = { rect, layoutCoordinates ->
val size = layoutCoordinates.size.toSize()
rect.translate(relocationDistance(rect.left, rect.right, size.width), 0f)
},
onPerformRelocation = { source, destination ->
val offset = destination.left - source.left
state.animateScrollBy(if (reverseScrolling) -offset else offset)
}
)
.horizontalScroll(state, enabled, flingBehavior, reverseScrolling)
}
// This is a helper function that users will have to use since experimental "ui" API cannot be used
// inside Scrollable, which is ihe "foundation" package. After onRelocationRequest is added
// to Scrollable, users can use Modifier.verticalScroll directly.
@OptIn(ExperimentalComposeUiApi::class)
private fun Modifier.verticalScrollWithRelocation(
state: ScrollState,
enabled: Boolean = true,
flingBehavior: FlingBehavior? = null,
reverseScrolling: Boolean = false
): Modifier {
return this
.onRelocationRequest(
onProvideDestination = { rect, layoutCoordinates ->
val size = layoutCoordinates.size.toSize()
rect.translate(0f, relocationDistance(rect.top, rect.bottom, size.height))
},
onPerformRelocation = { source, destination ->
val offset = destination.top - source.top
state.animateScrollBy(if (reverseScrolling) -offset else offset)
}
)
.verticalScroll(state, enabled, flingBehavior, reverseScrolling)
}
// Calculate the offset needed to bring one of the edges into view. The leadingEdge is the side
// closest to the origin (For the x-axis this is 'left', for the y-axis this is 'top').
// The trailing edge is the other side (For the x-axis this is 'right', for the y-axis this is
// 'bottom').
private fun relocationDistance(leadingEdge: Float, trailingEdge: Float, parentSize: Float) = when {
// If the item is already visible, no need to scroll.
leadingEdge >= 0 && trailingEdge <= parentSize -> 0f
// If the item is visible but larger than the parent, we don't scroll.
leadingEdge < 0 && trailingEdge > parentSize -> 0f
// Find the minimum scroll needed to make one of the edges coincide with the parent's edge.
abs(leadingEdge) < abs(trailingEdge - parentSize) -> leadingEdge
else -> trailingEdge - parentSize
}
| 0 | Java | 1 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 7,266 | androidx | Apache License 2.0 |
compiler/frontend/src/org/jetbrains/kotlin/checkers/diagnostics/factories/DebugInfoDiagnosticFactory0.kt | android | 263,405,600 | true | null | /*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.checkers.diagnostics.factories
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.checkers.diagnostics.DebugInfoDiagnostic
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory0
import org.jetbrains.kotlin.diagnostics.PositioningStrategies
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
class DebugInfoDiagnosticFactory0 : DiagnosticFactory0<PsiElement>,
DebugInfoDiagnosticFactory {
private val name: String
override val withExplicitDefinitionOnly: Boolean
override fun createDiagnostic(
expression: KtExpression,
bindingContext: BindingContext,
dataFlowValueFactory: DataFlowValueFactory?,
languageVersionSettings: LanguageVersionSettings?,
moduleDescriptor: ModuleDescriptorImpl?
): Diagnostic {
return DebugInfoDiagnostic(expression, this)
}
private constructor(name: String, severity: Severity = Severity.ERROR) : super(severity, PositioningStrategies.DEFAULT) {
this.name = name
this.withExplicitDefinitionOnly = false
}
private constructor(name: String, severity: Severity, withExplicitDefinitionOnly: Boolean) : super(
severity,
PositioningStrategies.DEFAULT
) {
this.name = name
this.withExplicitDefinitionOnly = withExplicitDefinitionOnly
}
override fun getName(): String {
return "DEBUG_INFO_$name"
}
companion object {
val SMARTCAST = DebugInfoDiagnosticFactory0("SMARTCAST", Severity.INFO)
val IMPLICIT_RECEIVER_SMARTCAST =
DebugInfoDiagnosticFactory0("IMPLICIT_RECEIVER_SMARTCAST", Severity.INFO)
val CONSTANT = DebugInfoDiagnosticFactory0("CONSTANT", Severity.INFO)
val LEAKING_THIS = DebugInfoDiagnosticFactory0("LEAKING_THIS", Severity.INFO)
val IMPLICIT_EXHAUSTIVE =
DebugInfoDiagnosticFactory0("IMPLICIT_EXHAUSTIVE", Severity.INFO)
val ELEMENT_WITH_ERROR_TYPE = DebugInfoDiagnosticFactory0("ELEMENT_WITH_ERROR_TYPE")
val UNRESOLVED_WITH_TARGET = DebugInfoDiagnosticFactory0("UNRESOLVED_WITH_TARGET")
val MISSING_UNRESOLVED = DebugInfoDiagnosticFactory0("MISSING_UNRESOLVED")
val DYNAMIC = DebugInfoDiagnosticFactory0("DYNAMIC", Severity.INFO)
}
} | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 2,835 | kotlin | Apache License 2.0 |
idbdata/src/main/java/com/gmail/eamosse/idbdata/local/entities/FavoriteEntity.kt | pghirlanda | 450,258,314 | false | {"Kotlin": 77201} | package com.gmail.eamosse.idbdata.local.entities
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.android.parcel.Parcelize
import java.io.Serializable
@Entity(tableName = "favorite_movie")
@Parcelize
data class FavoriteEntity(
val id_movie: String,
val backdroppath: String?,
val original_title: String,
val overview: String?,
val poster_path: String,
val video: Boolean,
val release_date: String,
) : Serializable, Parcelable {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
val baseUrl get() = "https://image.tmdb.org/t/p/w1280"
}
// fun FavoriteEntity.toDetailMovie() = DetailMovie(
// id = id_movie.toInt(),
// title = original_title,
// backdrop_path = backdroppath,
// date = release_date,
// overview = overview,
// video = video,
// poster_path = poster_path,
// )
// fun FavoriteEntity.toMovie() = Movie(
// id = id_movie.toInt(),
// posterPath = poster_path,
// backdropPath = backdroppath,
// title = title,
// voteAverage = vote_average.toFloat(),
// releaseDate = release_date,
// overview = overview
// )
| 0 | Kotlin | 0 | 0 | c200c48548841b0be591f4fe95194e23c8686c61 | 1,162 | Appmovie | Apache License 2.0 |
Examples/src/main/kotlin/programs/d2/SpritesBatchRendering.kt | nflsilva | 436,028,397 | false | {"Kotlin": 96532, "GLSL": 6274} | package programs.d2
import core.CoreEngine
import core.CoreEngineDelegate
import core.entity.Entity2D
import core.entity.component.EntityMoveComponent
import core.entity.component2d.SpriteComponent
import core.entity.component2d.SpriteRotationComponent
import org.joml.Vector2f
import render.renderer2d.dto.Sprite
import render.renderer2d.model.SpriteAtlas
import render.renderer2d.model.SpriteSizeEnum
import ui.dto.InputStateData
fun main(args: Array<String>) {
val engine = CoreEngine()
val gameLogic = SpritesBatchRendering(engine)
engine.delegate = gameLogic
engine.start()
println("Done!")
}
class SpritesBatchRendering(private val engine: CoreEngine) : CoreEngineDelegate {
override fun onStart() {
val lowPolyAtlas = SpriteAtlas("/texture/lowPolyAtlas.png", 4, 4).apply {
setSprite(SpriteSizeEnum.X4,"purple", 3, 3)
}
val testSprite = Sprite(SpriteSizeEnum.X16,"/texture/cube.png",)
var i = 0
for(x in 0 until 100) {
for(y in 0 until 1000) {
val sprite = Entity2D(Vector2f(x * 16F, y * 16F), 0.0f, Vector2f(1f, 1f))
val ti = i++ % 2
if(ti == 1){
sprite.addComponent(SpriteComponent(lowPolyAtlas.getSprite("purple")))
}
else {
sprite.addComponent(SpriteComponent(testSprite))
}
sprite.addComponent(EntityMoveComponent())
sprite.addComponent(SpriteRotationComponent())
engine.addEntity(sprite)
}
}
}
override fun onUpdate(elapsedTime: Double, input: InputStateData) {}
override fun onFrame() {}
override fun onCleanUp() {}
} | 0 | Kotlin | 1 | 1 | f867fa6dd49ea520484da5da9d4ba332d8625694 | 1,749 | K3DGE | MIT License |
src/commonMain/kotlin/app/thelema/ui/LabelStyle.kt | zeganstyl | 275,550,896 | false | null | /*
* Copyright 2020-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 app.thelema.ui
import app.thelema.font.BitmapFont
/** The style for a label, see [Label].
* @author <NAME>, zeganstyl
*/
open class LabelStyle(block: LabelStyle.() -> Unit = {}) {
var font: BitmapFont = DSKIN.font()
var background: Drawable? = null
var fontColor: Int = -1
init {
block(this)
}
} | 3 | Kotlin | 5 | 61 | 8e2943b6d2de3376ce338025b58ff31c14097caf | 946 | thelema-engine | Apache License 2.0 |
src/backend/ci/core/process/biz-process/src/main/kotlin/com/tencent/devops/process/service/ParamService.kt | andysibyl | 246,024,266 | true | {"Kotlin": 11197947, "Vue": 3490615, "Java": 1470130, "JavaScript": 868901, "CSS": 421025, "TSQL": 287636, "Lua": 134249, "Go": 133637, "Shell": 108469, "HTML": 44161, "TypeScript": 33694, "Python": 14104, "PLSQL": 2341, "Batchfile": 2202} | /*
* Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available.
*
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-CI 蓝鲸持续集成平台 is licensed under the MIT license.
*
* A copy of the MIT License is included in this file.
*
*
* Terms of the MIT License:
* ---------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tencent.devops.process.service
import com.tencent.devops.artifactory.api.service.ServiceArtifactoryResource
import com.tencent.devops.artifactory.pojo.CustomFileSearchCondition
import com.tencent.devops.common.api.exception.OperationException
import com.tencent.devops.common.api.util.HashUtil
import com.tencent.devops.common.auth.api.AuthPermission
import com.tencent.devops.common.auth.api.AuthPermissionApi
import com.tencent.devops.common.auth.api.AuthResourceType
import com.tencent.devops.common.auth.code.CodeAuthServiceCode
import com.tencent.devops.common.auth.code.PipelineAuthServiceCode
import com.tencent.devops.common.client.Client
import com.tencent.devops.common.pipeline.enums.BuildFormPropertyType
import com.tencent.devops.common.pipeline.enums.ChannelCode
import com.tencent.devops.common.pipeline.pojo.BuildFormProperty
import com.tencent.devops.common.pipeline.pojo.BuildFormValue
import com.tencent.devops.process.engine.service.PipelineRuntimeService
import com.tencent.devops.process.pojo.SubPipeline
import com.tencent.devops.store.api.container.ServiceContainerResource
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.util.StopWatch
import java.io.File
@Service
class ParamService @Autowired constructor(
private val client: Client,
private val codeService: CodeService,
private val authPermissionApi: AuthPermissionApi,
private val codeAuthServiceCode: CodeAuthServiceCode,
private val pipelineRuntimeService: PipelineRuntimeService,
private val bsPipelineAuthServiceCode: PipelineAuthServiceCode
) {
fun filterParams(userId: String?, projectId: String, pipelineId: String?, params: List<BuildFormProperty>): List<BuildFormProperty> {
val filterParams = mutableListOf<BuildFormProperty>()
params.forEach {
if (it.type == BuildFormPropertyType.SVN_TAG && (!it.repoHashId.isNullOrBlank())) {
val svnTagBuildFormProperty = addSvnTagDirectories(projectId, it)
filterParams.add(svnTagBuildFormProperty)
} else if (it.type == BuildFormPropertyType.GIT_REF && (!it.repoHashId.isNullOrBlank())) {
val gitRefBuildFormProperty = addGitRefs(projectId, it)
filterParams.add(gitRefBuildFormProperty)
} else if (it.type == BuildFormPropertyType.CODE_LIB && it.scmType != null) {
filterParams.add(addCodelibProperties(userId, projectId, it))
} else if (it.type == BuildFormPropertyType.CONTAINER_TYPE && it.containerType != null) {
filterParams.add(addContainerTypeProperties(userId, projectId, it))
} else if (it.type == BuildFormPropertyType.ARTIFACTORY) {
filterParams.add(addArtifactoryProperties(userId, projectId, it))
} else if (it.type == BuildFormPropertyType.SUB_PIPELINE) {
filterParams.add(addSubPipelineProperties(userId, projectId, pipelineId, it))
} else {
filterParams.add(it)
}
}
return filterParams
}
private fun addGitRefs(projectId: String, formProperty: BuildFormProperty): BuildFormProperty {
val refs = codeService.getGitRefs(projectId, formProperty.repoHashId)
val options = refs.map {
BuildFormValue(it, it)
}
return copyFormProperty(formProperty, options)
}
/**
* SVN_TAG类型参数添加SVN目录作为复选参数
*/
private fun addSvnTagDirectories(projectId: String, svnTagBuildFormProperty: BuildFormProperty): BuildFormProperty {
val directories = codeService.getSvnDirectories(projectId, svnTagBuildFormProperty.repoHashId, svnTagBuildFormProperty.relativePath)
val options = directories.map {
BuildFormValue(it, it)
}
return copyFormProperty(svnTagBuildFormProperty, options)
}
/**
* 自定义仓代码库过滤参数
*/
private fun addCodelibProperties(userId: String?, projectId: String, codelibFormProperty: BuildFormProperty): BuildFormProperty {
val codeAliasName = codeService.listRepository(projectId, codelibFormProperty.scmType!!)
val aliasNames = if ((!userId.isNullOrBlank()) && codeAliasName.isNotEmpty()) {
// 检查代码库的权限, 只返回用户有权限代码库
val hasPermissionCodelibs = getPermissionCodelibList(userId!!, projectId)
logger.info("[$userId|$projectId] Get the permission code lib list ($hasPermissionCodelibs)")
codeAliasName.filter { hasPermissionCodelibs.contains(it.repositoryHashId) }
.map { BuildFormValue(it.aliasName, it.aliasName) }
} else {
codeAliasName.map { BuildFormValue(it.aliasName, it.aliasName) }
}
return copyFormProperty(codelibFormProperty, aliasNames)
}
private fun addContainerTypeProperties(
userId: String?,
projectId: String,
property: BuildFormProperty
): BuildFormProperty {
try {
if (userId.isNullOrBlank()) {
logger.warn("The user id if empty for the container type properties")
return property
}
val containerType = property.containerType!!
val containers = client.get(ServiceContainerResource::class)
.getContainers(userId!!, projectId, containerType.buildType, containerType.os)
if (containers.data == null || containers.data!!.resources == null) {
logger.warn("[$userId|$projectId|$property] Fail to get the container properties")
return property
}
val containerValue = containers.data!!.resources!!.map {
BuildFormValue(it, it)
}.toList()
return copyFormProperty(property, containerValue)
} catch (ignored: Throwable) {
logger.warn("[$userId|$projectId|$property] Fail to get the pcg container images", ignored)
}
return property
}
/**
* 自定义仓库文件过滤参数
*/
private fun addArtifactoryProperties(userId: String?, projectId: String, property: BuildFormProperty): BuildFormProperty {
try {
val glob = property.glob
if (glob.isNullOrBlank() && (property.properties == null || property.properties!!.isEmpty())) {
logger.warn("glob and properties are both empty")
return property
}
val listResult = client.get(ServiceArtifactoryResource::class).searchCustomFiles(
projectId,
CustomFileSearchCondition(
property.glob,
property.properties ?: mapOf()
)
)
if (listResult.data == null) {
logger.warn("list file result is empty")
return property
}
return copyFormProperty(
property,
listResult.data!!.map { BuildFormValue(it, File(it).name) }
)
} catch (t: Throwable) {
logger.warn("[$userId|$projectId|$property] Fail to list artifactory files", t)
}
return property
}
/**
* 自定义子流水线参数过滤
*/
private fun addSubPipelineProperties(userId: String?, projectId: String, pipelineId: String?, subPipelineFormProperty: BuildFormProperty): BuildFormProperty {
try {
val hasPermissionPipelines = getHasPermissionPipelineList(userId, projectId)
val aliasName = hasPermissionPipelines
.filter { pipelineId == null || !it.pipelineId.contains(pipelineId) }
.map { BuildFormValue(it.pipelineName, it.pipelineName) }
return copyFormProperty(subPipelineFormProperty, aliasName)
} catch (t: Throwable) {
logger.warn("[$userId|$projectId] Fail to filter the properties of subpipelines", t)
throw OperationException("子流水线参数过滤失败")
}
}
private fun copyFormProperty(property: BuildFormProperty, options: List<BuildFormValue>): BuildFormProperty {
return BuildFormProperty(
property.id,
property.required,
property.type,
property.defaultValue,
options,
property.desc,
property.repoHashId,
property.relativePath,
property.scmType,
property.containerType,
property.glob,
property.properties
)
}
private fun getPermissionCodelibList(userId: String, projectId: String): List<String> {
try {
return authPermissionApi.getUserResourceByPermission(
userId, codeAuthServiceCode,
AuthResourceType.CODE_REPERTORY, projectId, AuthPermission.LIST,
null
).map { HashUtil.encodeOtherLongId(it.toLong()) }
} catch (t: Throwable) {
logger.warn("[$userId|$projectId] Fail to get the permission code lib list", t)
throw OperationException("获取代码库列表权限失败")
}
}
private fun getHasPermissionPipelineList(userId: String?, projectId: String): List<SubPipeline> {
val watch = StopWatch()
try {
// 从权限中拉取有权限的流水线,若无userId则返回空值
watch.start("perm_r_perm")
val hasPermissionList = if (!userId.isNullOrBlank()) authPermissionApi.getUserResourceByPermission(
userId!!, bsPipelineAuthServiceCode,
AuthResourceType.PIPELINE_DEFAULT, projectId, AuthPermission.EXECUTE,
null) else null
watch.stop()
// 获取项目下所有流水线,并过滤出有权限部分,有权限列表为空时返回项目所有流水线
watch.start("s_r_summary")
val pipelineBuildSummary =
pipelineRuntimeService.getBuildSummaryRecords(projectId, ChannelCode.BS, hasPermissionList)
watch.stop()
return pipelineBuildSummary.map {
val pipelineId = it["PIPELINE_ID"] as String
val pipelineName = it["PIPELINE_NAME"] as String
SubPipeline(pipelineName, pipelineId)
}
} catch (t: Throwable) {
logger.warn("[$userId|$projectId] Fail to get the permission pipeline list", t)
throw OperationException("获取项目流水线列表权限失败")
}
}
companion object {
private val logger = LoggerFactory.getLogger(ParamService::class.java)
}
} | 4 | null | 0 | 1 | cf5b49b17525befe6d3f84ffaafa0526eea74821 | 12,263 | bk-ci | MIT License |
app/src/main/java/com/svmdev/meunchworlds/view/jogo/inexplorado/UncheckFragment.kt | saviossmg | 199,327,641 | false | null | package com.svmdev.meunchworlds.view.jogo.inexplorado
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.svmdev.meunchworlds.R
/**
* Mass Effect Uncharted Worlds
* Desenvolvido por <NAME> em 07/02/2019.
*/
class UncheckFragment: Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
//
return inflater.inflate(R.layout.fragment_uncheck, container, false)
}
override fun onPause() {
super.onPause()
}
override fun onResume() {
super.onResume()
}
}
| 0 | Kotlin | 0 | 0 | 3620c04287ea9cf1452d8abeb8d792583abf79a8 | 716 | MassEffectUnchartedWorlds | Apache License 2.0 |
src/jvmTest/kotlin/io/github/devngho/kiroksvelte/TypeGeneratorTest.kt | devngho | 698,727,804 | false | {"Kotlin": 8748, "TypeScript": 1462} | package io.github.devngho.kiroksvelte
import io.github.devngho.kirok.binding.Binding
import io.kotest.common.ExperimentalKotest
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.matchers.shouldBe
import kotlin.reflect.full.starProjectedType
@OptIn(ExperimentalKotest::class)
class TypeGeneratorTest : BehaviorSpec({
given("TypeGenerator") {
`when`("convertType") {
then("기본 타입을 올바르게 변환한다") {
TypeGenerator.convertType(Int::class.starProjectedType) shouldBe "number"
TypeGenerator.convertType(String::class.starProjectedType) shouldBe "string"
TypeGenerator.convertType(Boolean::class.starProjectedType) shouldBe "boolean"
TypeGenerator.convertType(Double::class.starProjectedType) shouldBe "number"
TypeGenerator.convertType(Float::class.starProjectedType) shouldBe "number"
TypeGenerator.convertType(Long::class.starProjectedType) shouldBe "number"
TypeGenerator.convertType(Short::class.starProjectedType) shouldBe "number"
TypeGenerator.convertType(Byte::class.starProjectedType) shouldBe "number"
TypeGenerator.convertType(Char::class.starProjectedType) shouldBe "string"
TypeGenerator.convertType(List::class.starProjectedType) shouldBe "any[]"
TypeGenerator.convertType(Map::class.starProjectedType) shouldBe "Map<any, any>"
TypeGenerator.convertType(Set::class.starProjectedType) shouldBe "Set<any>"
TypeGenerator.convertType(Collection::class.starProjectedType) shouldBe "any[]"
TypeGenerator.convertType(MutableList::class.starProjectedType) shouldBe "any[]"
TypeGenerator.convertType(MutableMap::class.starProjectedType) shouldBe "Map<any, any>"
TypeGenerator.convertType(MutableSet::class.starProjectedType) shouldBe "Set<any>"
TypeGenerator.convertType(MutableCollection::class.starProjectedType) shouldBe "any[]"
}
then("데이터 클래스를 올바르게 변환한다") {
data class TestClass(val a: Int, val b: String)
TypeGenerator.convertType(TestClass::class.starProjectedType) shouldBe "{a: number, b: string}"
}
then("중첩된 데이터 클래스를 올바르게 변환한다") {
data class TestClass(val a: Int, val b: String)
data class TestClass2(val a: Int, val b: String, val c: TestClass)
TypeGenerator.convertType(TestClass2::class.starProjectedType) shouldBe "{a: number, b: string, c: {a: number, b: string}}"
}
}
given("Binding.BindingModel") {
data class TestClass(val a: Int, val b: String)
data class TestClass2(val a: Int, val b: String, val c: TestClass)
val model = Binding.BindingModel(
"io.github.devngho.kiroksvelte.TestModel",
mapOf(
"testPrimitive" to String::class,
"testModels" to TestClass2::class
),
mapOf(
"testPrimitive" to listOf(
String::class,
Boolean::class
),
"testModels" to listOf(
TestClass2::class
)
)
)
`when`("values") {
then("값을 올바르게 변환한다") {
TypeGenerator.createValueType(model) shouldBe mapOf(
"testPrimitive" to "string",
"testModels" to "{a: number, b: string, c: {a: number, b: string}}"
)
}
}
}
}
}) | 0 | Kotlin | 0 | 0 | 30255c65b8ad86bf6ba69dea6f981a18c50ae93d | 3,859 | kirok-svelte-binding | MIT License |
src/app/src/main/java/com/gabrielbmoro/crazymath/domain/model/OperationType.kt | gabrielbmoro | 574,750,061 | false | {"Kotlin": 106512} | package com.gabrielbmoro.crazymath.domain.model
enum class OperationType(val value: String) {
SUM("+"),
SUB("-"),
MULT("X");
} | 0 | Kotlin | 0 | 0 | e747b05712ab481b33ce65487cd5674a8d1b7b8a | 139 | CrazyMath-Android | MIT License |
compiler/testData/diagnostics/tests/platformTypes/rawTypes/intermediateRecursion.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FILE: Boo.java
public class Boo<N> {}
// FILE: Foo.java
public class Foo<T extends Boo<K>, K extends Boo<X>, X extends Boo<K>> {
T test2() { return null; }
static Foo test1() { return null; }
}
// FILE: main.kt
fun main() {
val x = <!DEBUG_INFO_EXPRESSION_TYPE("raw (Foo<(Boo<(Boo<(Boo<*>..Boo<*>?)>..Boo<(Boo<*>..Boo<*>?)>?)>..Boo<(Boo<(Boo<*>..Boo<*>?)>..Boo<(Boo<*>..Boo<*>?)>?)>?), (Boo<(Boo<*>..Boo<*>?)>..Boo<(Boo<*>..Boo<*>?)>?), (Boo<*>..Boo<*>?)>..Foo<out (Boo<out (Boo<out (Boo<*>..Boo<*>?)>..Boo<out (Boo<*>..Boo<*>?)>?)>..Boo<out (Boo<out (Boo<*>..Boo<*>?)>..Boo<out (Boo<*>..Boo<*>?)>?)>?), out (Boo<out (Boo<*>..Boo<*>?)>..Boo<out (Boo<*>..Boo<*>?)>?), out (Boo<*>..Boo<*>?)>?)")!>Foo.test1()<!>.test2()
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 737 | kotlin | Apache License 2.0 |
app/src/test/java/com/exozet/android/core/extensions/StringExtensionsTest.kt | exozet | 133,497,547 | false | null | package com.exozet.android.core.extensions
import com.exozet.android.core.base.BaseTest
import com.google.common.truth.Truth
import junit.framework.Assert
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils.fromHexString
import org.junit.Test
import java.io.UnsupportedEncodingException
import java.nio.charset.Charset
import java.util.*
/**
* Created by [<NAME>](https://about.me/janrabe).
*/
class StringExtensionsTest : BaseTest() {
@Test
fun toJsonTest() {
}
@Test
@Throws(UnsupportedEncodingException::class)
fun count() {
Assert.assertEquals(5, "hallo".toByteArray(charset("UTF-8")).size)
Assert.assertEquals(5, "hallo".length)
Assert.assertEquals(6, "다렉".toByteArray(charset("UTF-8")).size)
Assert.assertEquals(2, "다렉".length)
Assert.assertEquals(9, "우주선".toByteArray(charset("UTF-8")).size)
Assert.assertEquals(3, "우주선".length)
}
@Test
@Throws(UnsupportedEncodingException::class)
fun latin() {
// The input string for this test
val string = "Hello World"
// Check length, in characters
println(string + " Length=" + string.length) // prints "11"
// Check encoded sizes
val utf8Bytes = string.toByteArray(charset("UTF-8"))
println("${java.lang.String(utf8Bytes, "UTF-8")}UTF-8 Size=" + utf8Bytes.size) // prints "11"
val utf16Bytes = string.toByteArray(charset("UTF-16"))
println("${java.lang.String(utf16Bytes, "UTF-16")} UTF-16 Size=" + utf16Bytes.size) // prints "24"
val utf32Bytes = string.toByteArray(charset("UTF-32"))
println("${java.lang.String(utf32Bytes, "UTF-32")} UTF-32 Size=" + utf32Bytes.size) // prints "44"
val iso8859Bytes = string.toByteArray(charset("ISO-8859-1"))
println("${java.lang.String(iso8859Bytes, "ISO-8859-1")} ISO-8859-1 Size=" + iso8859Bytes.size) // prints "11"
val winBytes = string.toByteArray(charset("CP1252"))
println("${winBytes.toString(Charset.forName("CP1252"))} CP1252 Size=" + winBytes.size) // prints "11"
val iso2022Bytes = string.toByteArray(charset("ISO-2022-KR"))
println("${java.lang.String(iso2022Bytes, "ISO-2022-KR")}ISO-2022-KR Size=" + iso2022Bytes.size) // prints "6"
}
@Test
@Throws(UnsupportedEncodingException::class)
fun korean() {
// The input string for this test
val string = "다렉 우주선"
// Check length, in characters
println(string + " Length=" + string.length) // prints "6"
// Check encoded sizes
val utf8Bytes = string.toByteArray(charset("UTF-8"))
println("${java.lang.String(utf8Bytes, "UTF-8")} UTF-8 Size=" + utf8Bytes.size) // prints "16"
val utf16Bytes = string.toByteArray(charset("UTF-16"))
println("${java.lang.String(utf16Bytes, "UTF-16")} UTF-16 Size=" + utf16Bytes.size) // prints "14"
val utf32Bytes = string.toByteArray(charset("UTF-32"))
println("${java.lang.String(utf32Bytes, "UTF-32")} UTF-32 Size=" + utf32Bytes.size) // prints "24"
val iso8859Bytes = string.toByteArray(charset("ISO-8859-1"))
println("${java.lang.String(iso8859Bytes, "ISO-8859-1")} ISO-8859-1 Size=" + iso8859Bytes.size) // prints "6"
val winBytes = string.toByteArray(charset("CP1252"))
println("${java.lang.String(winBytes, "CP1252")} CP1252 Size=" + winBytes.size) // prints "6"
val iso2022Bytes = string.toByteArray(charset("ISO-2022-KR"))
println("${java.lang.String(iso2022Bytes, "ISO-2022-KR")} ISO-2022-KR Size=" + iso2022Bytes.size) // prints "18"
}
@Test
fun replace() {
val placeholderText = """For your device to get connected to \"%@\" it needs to have the WIFI password."""
val expected = "<PASSWORD>k"
Assert.assertEquals(
"For your device to get connected to $expected it needs to have the WIFI password.",
placeholderText.replace("\\\"%@\\\"", expected)
)
}
@Test
fun hexStringToByteArray() {
val hexString = "00112233445566778899AABBCCDDEEFF" //getString(R.string.pubnub_cipher_key);
val expected =
byteArrayOf(0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88.toByte(), 0x99.toByte(), 0xaa.toByte(), 0xbb.toByte(), 0xcc.toByte(), 0xdd.toByte(), 0xee.toByte(), 0xff.toByte())
Assert.assertEquals(Arrays.toString(expected), Arrays.toString(fromHexString(hexString)))
}
@Test
fun sha256() {
Truth.assertThat("04-73-2F-02-93-C0".sha256())
.isEqualTo("0413e0cecd75d7bc0a463ed5593962257cfb4117b68c5fb3618ba4085721495e")
}
} | 0 | Kotlin | 2 | 11 | 72cbb02bc262b1c26450b570e41842ab65406c3e | 4,696 | AndroidCore | MIT License |
src/test/kotlin/MainTest.kt | davidisla | 514,058,070 | false | {"Kotlin": 893} | import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class MainTest {
@Test
fun firstTest() {
assertEquals(1,2)
}
} | 0 | Kotlin | 0 | 0 | 6983ef793b2acce3611dab239b63c087edc14243 | 150 | kotlin-template | Apache License 2.0 |
compiler/tests-common/tests/org/jetbrains/kotlin/fir/FirTestModuleInfo.kt | android | 263,405,600 | true | null | /*
* Copyright 2010-2018 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.fir
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices
class FirTestModuleInfo(
override val name: Name = Name.identifier("TestModule"),
val dependencies: MutableList<ModuleInfo> = mutableListOf(),
override val platform: TargetPlatform = JvmPlatforms.unspecifiedJvmPlatform,
override val analyzerServices: PlatformDependentAnalyzerServices = JvmPlatformAnalyzerServices
) : ModuleInfo {
override fun dependencies(): List<ModuleInfo> = dependencies
} | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 998 | kotlin | Apache License 2.0 |
app/src/main/java/com/zerowater/environment/ui/history/HistoryAdapter.kt | byzerowater | 264,695,996 | false | null | /*
* 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.zerowater.environment.ui.history
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.zerowater.environment.databinding.HistoryItemBinding
/**
* Environment
* Class: HistoryAdapter
* Created by ZERO on 2020-05-18.
* zero company Ltd
* <EMAIL>
* Description: Adapter for the history list. Has a reference to the [HistoryViewModel] to send actions back to it.
*/
class HistoryAdapter(private val viewModel: HistoryViewModel) :
ListAdapter<String, HistoryAdapter.ViewHolder>(HistoryDiffCallback()) {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
holder.bind(viewModel, item)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder.from(parent)
}
class ViewHolder private constructor(val binding: HistoryItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(viewModel: HistoryViewModel, item: String) {
binding.viewmodel = viewModel
binding.title.text = item
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = HistoryItemBinding.inflate(layoutInflater, parent, false)
return ViewHolder(binding)
}
}
}
}
/**
* Callback for calculating the diff between two non-null items in a list.
*
* Used by ListAdapter to calculate the minimum number of changes between and old list and a new
* list that's been passed to `submitList`.
*/
class HistoryDiffCallback : DiffUtil.ItemCallback<String>() {
override fun areItemsTheSame(oldItem: String, newItem: String): Boolean {
return oldItem.toString() == newItem.toString()
}
override fun areContentsTheSame(oldItem: String, newItem: String): Boolean {
return oldItem == newItem
}
}
| 0 | Kotlin | 0 | 0 | 3139da828c309cee13c0eaf3b8ce9a24ce151c5c | 2,809 | Environment3 | Apache License 2.0 |
test/kotlin/software/hsharp/woocommerce/DatabaseImpl.kt | idempiere-micro-archive | 133,656,879 | false | {"Kotlin": 37911, "Java": 252} | package software.hsharp.woocommerce
import org.idempiere.icommon.db.AdempiereDatabase
import pg.org.compiere.db.DB_PostgreSQL
class DatabaseImpl : DB_PostgreSQL(), AdempiereDatabase | 0 | Kotlin | 0 | 0 | c2e2ca3f9c55a94695748d735e6fc98eded98bb8 | 183 | software.hsharp.woocommerce | MIT License |
app/src/main/java/com/koma/video/widget/VideosItemDecoration.kt | komamj | 135,701,576 | false | {"Kotlin": 177378} | /*
* Copyright 2018 Koma
*
* 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.koma.video.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v7.widget.RecyclerView
import android.view.View
class VideosItemDecoration(context: Context) : RecyclerView.ItemDecoration() {
private val mDivider: Drawable
init {
val typedArray = context.obtainStyledAttributes(intArrayOf(android.R.attr.listDivider))
this.mDivider = typedArray.getDrawable(0)
typedArray.recycle()
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) {
mDivider.run {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + mDivider.intrinsicHeight
setBounds(left, top, right, bottom)
draw(c)
}
}
}
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State?
) {
outRect.set(0, 0, 0, mDivider.intrinsicHeight)
}
}
| 0 | Kotlin | 1 | 1 | be4142c9126b0e74cd1d8d1dcaae5285505294d8 | 2,006 | Video | Apache License 2.0 |
model/src/commonMain/kotlin/com/mindovercnc/model/Direction.kt | 85vmh | 543,628,296 | false | {"Kotlin": 956103, "C++": 75148, "Java": 7157, "Makefile": 2742, "HTML": 419, "Shell": 398, "CSS": 108} | package com.mindovercnc.model
enum class Direction {
Negative, Positive
} | 0 | Kotlin | 1 | 3 | 5cf42426895ba8691c9b53ba1b97c274bbdabc07 | 78 | mindovercnclathe | Apache License 2.0 |
compiler/testData/codegen/box/delegatedProperty/inTrait.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | import kotlin.reflect.KProperty
class Delegate {
operator fun getValue(t: Any?, p: KProperty<*>): Int = 1
}
interface A {
val prop: Int
}
class AImpl: A {
override val prop: Int by Delegate()
}
fun box(): String {
return if(AImpl().prop == 1) "OK" else "fail"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 279 | kotlin | Apache License 2.0 |
app/src/main/java/de/kauker/unofficial/sdk/grocy/models/GrocyLocation.kt | aimok04 | 556,343,801 | false | {"Kotlin": 114124} | package de.kauker.unofficial.sdk.grocy.models
import org.json.JSONObject
class GrocyLocation(
data: JSONObject
) {
lateinit var id: String
lateinit var name: String
lateinit var description: String
lateinit var timestamp: String
var isFreezer: Boolean = false
init {
parse(data)
}
fun parse(json: JSONObject) {
id = json.getString("id")
name = json.getString("name")
description = json.getString("description")
timestamp = json.getString("row_created_timestamp")
isFreezer = json.getString("is_freezer").equals("1")
}
override fun toString(): String {
return "GrocyLocation(id='$id', name='$name', description='$description', timestamp='$timestamp', isFreezer=$isFreezer)"
}
}
| 0 | Kotlin | 0 | 3 | 9796c5ec845d32a38b7833ef62197112a775d578 | 787 | grocy-for-wear-os | Apache License 2.0 |
fuzzer/fuzzing_output/crashing_tests/verified/exceptionHappened.kt-131147817.kt | ItsLastDay | 102,885,402 | false | null | import java.lang.reflect.InvocationTargetException
fun fail(message: String): Unit {
throw AssertionError(message)
}
fun box(): String {
try {
((::fail) ?: ((::fail)!!)).call("OK")
}catch(e: InvocationTargetException) {
return e.getTargetException().message.toString()
}
return "Fail: no exception was thrown"
} | 0 | Kotlin | 0 | 6 | bb80db8b1383a6c7f186bea95c53faff4c0e0281 | 311 | KotlinFuzzer | MIT License |
core/src/main/java/br/com/mindbet/core/simulation/create/data/repository/SimulationRepository.kt | luangs7 | 275,694,397 | false | null | package br.com.mindbet.core.simulation.create.data.repository
import br.com.mindbet.common.base.Resource
import br.com.mindbet.core.simulation.create.data.model.SimulationParams
import br.com.mindbet.core.simulation.create.data.model.SimulationValues
import kotlinx.coroutines.flow.Flow
interface SimulationRepository {
suspend fun getParams(): Flow<Resource<List<SimulationValues>>>
suspend fun setSimulate(params: SimulationParams): Flow<Resource<Unit>>
} | 0 | Kotlin | 1 | 0 | adffb2e30f6d2f678f7197277849e7aff86bac15 | 467 | Mindbet | MIT License |
buildSrc/src/main/kotlin/androidx/build/dependencyTracker/ProjectGraph.kt | RikkaW | 389,105,112 | true | {"Java": 49060640, "Kotlin": 36832495, "Python": 336507, "AIDL": 179831, "Shell": 150493, "C++": 38342, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343} | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.dependencyTracker
import androidx.build.getSupportRootFolder
import org.gradle.api.Project
import java.io.File
import org.gradle.api.logging.Logger
/**
* Creates a project graph for fast lookup by file path
*/
class ProjectGraph(project: Project, val logger: Logger? = null) {
private val rootNode: Node
init {
// always use cannonical file: b/112205561
logger?.info("initializing ProjectGraph")
rootNode = Node(logger)
val rootProjectDir = project.getSupportRootFolder().canonicalFile
val projects = if (rootProjectDir == project.rootDir.canonicalFile) {
project.subprojects
} else {
// include root project if it is not the main AndroidX project.
project.subprojects + project
}
projects.forEach {
logger?.info("creating node for ${it.path}")
val relativePath = it.projectDir.canonicalFile.toRelativeString(rootProjectDir)
val sections = relativePath.split(File.separatorChar)
logger?.info("relative path: $relativePath , sections: $sections")
val leaf = sections.fold(rootNode) { left, right ->
left.getOrCreateNode(right)
}
leaf.project = it
}
logger?.info("finished creating ProjectGraph")
}
/**
* Finds the project that contains the given file.
* The file's path prefix should match the project's path.
*/
fun findContainingProject(filePath: String): Project? {
val sections = filePath.split(File.separatorChar)
logger?.info("finding containing project for $filePath , sections: $sections")
return rootNode.find(sections, 0)
}
private class Node(val logger: Logger? = null) {
var project: Project? = null
private val children = mutableMapOf<String, Node>()
fun getOrCreateNode(key: String): Node {
return children.getOrPut(key) { Node(logger) }
}
fun find(sections: List<String>, index: Int): Project? {
logger?.info("finding $sections with index $index in ${project?.path ?: "root"}")
if (sections.size <= index) {
logger?.info("nothing")
return project
}
val child = children[sections[index]]
return if (child == null) {
logger?.info("no child found, returning ${project?.path ?: "root"}")
project
} else {
child.find(sections, index + 1)
}
}
}
}
| 11 | Java | 3 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 3,216 | androidx | Apache License 2.0 |
app/src/main/java/com/switchonkannada/switchon/ui/userProfile/UserProfileViewModel.kt | tusharyadav511 | 260,476,750 | false | null | package com.switchonkannada.switchon.ui.userProfile
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.AsyncTask
import android.os.CountDownTimer
import android.widget.EditText
import android.widget.ImageView
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.ktx.storageMetadata
import java.net.HttpURLConnection
import java.net.URL
class UserProfileViewModel():ViewModel() {
private val _userProfileResult = MutableLiveData<UserProfileResults>()
val userProfileResults : LiveData<UserProfileResults> = _userProfileResult
private val _userProfileImageResult = MutableLiveData<UploadProfileImageResult>()
val userProfileImageResult : LiveData<UploadProfileImageResult> = _userProfileImageResult
private val _puttingImageResult = MutableLiveData<PuttingImageResult>()
val puttingImageResult : LiveData<PuttingImageResult> = _puttingImageResult
private val db = Firebase.firestore
private val auth = FirebaseAuth.getInstance()
private val currentUser = auth.currentUser!!.uid
private val mStorage = FirebaseStorage.getInstance().reference.child("Profile Images")
.child(currentUser).child("profilePhoto.jpg")
private val reference =
db.collection("users").document(currentUser).addSnapshotListener {document, e ->
if (e != null){
_userProfileResult.value = UserProfileResults(error = e.message)
}else{
if (document!!.exists()){
val name = document?.getString("Name")
val email = document?.getString("Email")
val profileImage = document?.getString("ProfileImage")
_userProfileResult.value = UserProfileResults(name = name)
_userProfileResult.value = UserProfileResults(email = email)
_userProfileResult.value = UserProfileResults(imageUrl = profileImage)
}else {
_userProfileResult.value = UserProfileResults(noDataError = "No Profile Image Found")
}
}
}
fun setUserName() {
reference
}
fun uploadPhoto(data : ByteArray){
var metadata = storageMetadata {
contentType = "image/jpg"
}
mStorage.putBytes(data , metadata).addOnFailureListener {
_userProfileImageResult.value = UploadProfileImageResult(error = it.message)
}.addOnSuccessListener {
_userProfileImageResult.value = UploadProfileImageResult(success = "Successful")
}
}
fun putImage(image : ImageView){
mStorage?.downloadUrl.addOnSuccessListener {
var url = it.toString()
val task = DownloadImage()
val myImage: Bitmap
try {
myImage = task.execute(url).get()
image.setImageBitmap(myImage)
db.collection("users").document(currentUser).update("ProfileImage" , url)
} catch (e: Exception) {
e.printStackTrace()
_puttingImageResult.value = PuttingImageResult(error = e.message)
_puttingImageResult.value = PuttingImageResult(showProcess = false)
}
}.addOnFailureListener {
_puttingImageResult.value = PuttingImageResult(showProcess = false)
_puttingImageResult.value = PuttingImageResult(error = it.message)
}
}
fun updateUser(name:EditText){
db.collection("users").document(currentUser).update("Name" , name.text.toString())
object : CountDownTimer(2000, 1000) {
override fun onFinish() {
auth.currentUser?.reload()
_userProfileImageResult.value = UploadProfileImageResult(onFinish = "OnFinish")
}
override fun onTick(millisUntilFinished: Long) {
_userProfileImageResult.value = UploadProfileImageResult(onTick = "OnTick")
}
}.start()
}
override fun onCleared() {
super.onCleared()
reference.remove()
}
inner class DownloadImage : AsyncTask<String, Void, Bitmap>() {
override fun doInBackground(vararg urls: String): Bitmap? {
return try {
val url = URL(urls[0])
val connection = url.openConnection() as HttpURLConnection
connection.connect()
val `in` = connection.inputStream
BitmapFactory.decodeStream(`in`)
} catch (e: Exception) {
e.printStackTrace()
_puttingImageResult.value = PuttingImageResult(showProcess = false)
null
}
}
override fun onPreExecute() {
super.onPreExecute()
_puttingImageResult.value = PuttingImageResult(showProcess = true)
}
override fun onProgressUpdate(vararg values: Void?) {
super.onProgressUpdate(*values)
_puttingImageResult.value = PuttingImageResult(showProcess = true)
}
override fun onPostExecute(result: Bitmap?) {
super.onPostExecute(result)
_puttingImageResult.value = PuttingImageResult(showProcess = false)
}
}
} | 0 | Kotlin | 0 | 0 | a4d0766d09f50a131eba3a00848a563b462ed926 | 5,549 | SwitchOn | Creative Commons Zero v1.0 Universal |
src/commonMain/kotlin/me/devnatan/yoki/models/IdOnlyResponse.kt | DevNatan | 392,883,613 | false | {"Kotlin": 178000} | package me.devnatan.yoki.models
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
internal data class IdOnlyResponse(@SerialName("Id") val id: String)
| 7 | Kotlin | 2 | 19 | 311c8350f7f6ee26c404316d01463043615613e0 | 199 | yoki | MIT License |
app/src/main/java/com/lvaccaro/lamp/utils/LampKeys.kt | clightning4j | 219,542,033 | false | {"Kotlin": 157176} | package com.lvaccaro.lamp.utils
class LampKeys {
companion object {
val ADDRESS_KEY = "ADDRESS_KEY"
val AMOUNT_KEY = "amount"
val LABEL_KEY = "label"
val MESSAGE_KEY = "message"
val WITHDRAW_COMMAND = "withdraw"
val DECODEPAY_COMMAND = "decodepay"
val CONNECT_COMMAND = "connect"
val MESSAGE_JSON_KEY = "message"
// UI save state
const val OFF_CHAIN_BALANCE = "OFF_CHAIN_BALANCE"
const val ON_CHAIN_BALANCE = "ON_CHAIN_BALANCE"
const val OUR_CHAIN_BALANCE = "OUR_CHAIN_BALANCE"
}
}
| 8 | Kotlin | 10 | 20 | e3fe170cd3dd314222f228127fc0b9d6ca97c7ed | 588 | lamp | MIT License |
buildSrc/src/main/kotlin/versionExtensions.kt | dragossusi | 329,955,237 | false | null | import org.gradle.api.Project
val Project.kotlinVersion: String
get() {
if (hasProperty("sevens.kotlin.version")) {
property("sevens.kotlin.version")?.let {
return it.toString()
}
}
return Versions.Fallback.kotlin
}
val Project.coroutinesVersion: String
get() {
if (hasProperty("sevens.kotlin.coroutines.version")) {
property("sevens.kotlin.coroutines.version")?.let {
return it.toString()
}
}
return Versions.Fallback.coroutines
}
val Project.androidVersion: String
get() {
if (hasProperty("sevens.android.gradle.version")) {
property("sevens.android.gradle.version")?.let {
return it.toString()
}
}
return Versions.Fallback.android
} | 0 | Kotlin | 0 | 6 | 677eceb06bfe397be6879f78675e57511ed644bd | 854 | AndroidImagePicker | Apache License 2.0 |
src/test/kotlin/org/jitsi/jibri/selenium/status_checks/EmptyCallStatusCheckTest.kt | zhangjialegh | 275,100,702 | true | {"Kotlin": 292257, "Shell": 3746, "Java": 1620} | /*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jibri.selenium.status_checks
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.whenever
import io.kotlintest.IsolationMode
import io.kotlintest.minutes
import io.kotlintest.seconds
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import org.jitsi.jibri.helpers.FakeClock
import org.jitsi.jibri.selenium.SeleniumEvent
import org.jitsi.jibri.selenium.pageobjects.CallPage
import java.time.Duration
import java.util.logging.Logger
internal class EmptyCallStatusCheckTest : ShouldSpec() {
override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf
private val clock: FakeClock = spy()
private val callPage: CallPage = mock()
private val logger: Logger = mock()
private val check = EmptyCallStatusCheck(logger, clock = clock)
init {
"when the call was always empty" {
whenever(callPage.getNumParticipants()).thenReturn(1)
"the check" {
should("return empty after the timeout") {
check.run(callPage) shouldBe null
clock.elapse(15.seconds)
check.run(callPage) shouldBe null
clock.elapse(20.seconds)
check.run(callPage) shouldBe SeleniumEvent.CallEmpty
}
}
}
"when the call has participants" {
whenever(callPage.getNumParticipants()).thenReturn(3)
clock.elapse(5.minutes)
"the check" {
should("never return empty") {
check.run(callPage) shouldBe null
clock.elapse(10.minutes)
check.run(callPage) shouldBe null
}
}
"and then goes empty" {
whenever(callPage.getNumParticipants()).thenReturn(1)
clock.elapse(20.seconds)
"the check" {
should("return empty after the timeout") {
check.run(callPage) shouldBe null
clock.elapse(31.seconds)
check.run(callPage) shouldBe SeleniumEvent.CallEmpty
}
}
"and then has participants again" {
whenever(callPage.getNumParticipants()).thenReturn(3)
// Some time passed and the check ran once with no participants
clock.elapse(30.seconds)
"the check" {
should("never return empty") {
check.run(callPage) shouldBe null
clock.elapse(10.minutes)
check.run(callPage) shouldBe null
}
}
}
}
}
"when a custom timeout is passed" {
val customTimeoutCheck = EmptyCallStatusCheck(logger, Duration.ofMinutes(10), clock)
"the check" {
should("return empty after the timeout") {
customTimeoutCheck.run(callPage) shouldBe null
clock.elapse(15.seconds)
customTimeoutCheck.run(callPage) shouldBe null
clock.elapse(45.seconds)
customTimeoutCheck.run(callPage) shouldBe null
clock.elapse(8.minutes)
customTimeoutCheck.run(callPage) shouldBe null
clock.elapse(61.seconds)
customTimeoutCheck.run(callPage) shouldBe SeleniumEvent.CallEmpty
}
}
}
}
} | 0 | Kotlin | 0 | 0 | d13317531b0554276157ebadf2c3d54849d33efb | 4,275 | jibri | Apache License 2.0 |
app/src/main/java/io/homeassistant/companion/android/onboarding/discovery/DiscoveryFragment.kt | nesror | 328,856,313 | true | null | package io.homeassistant.companion.android.onboarding.discovery
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.google.android.material.composethemeadapter.MdcTheme
import dagger.hilt.android.AndroidEntryPoint
import io.homeassistant.companion.android.R
import io.homeassistant.companion.android.onboarding.OnboardingViewModel
import io.homeassistant.companion.android.onboarding.authentication.AuthenticationFragment
import io.homeassistant.companion.android.onboarding.manual.ManualSetupFragment
import javax.inject.Inject
import io.homeassistant.companion.android.common.R as commonR
@AndroidEntryPoint
class DiscoveryFragment @Inject constructor() : Fragment() {
companion object {
private const val TAG = "DiscoveryFragment"
private const val HOME_ASSISTANT = "https://www.home-assistant.io"
}
private val viewModel by activityViewModels<OnboardingViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setContent {
MdcTheme {
DiscoveryView(
onboardingViewModel = viewModel,
whatIsThisClicked = { openHomeAssistantHomePage() },
manualSetupClicked = { navigateToManualSetup() },
instanceClicked = { onInstanceClicked(it) }
)
}
}
}
}
override fun onResume() {
super.onResume()
viewModel.startSearch()
}
override fun onPause() {
super.onPause()
viewModel.stopSearch()
}
private fun openHomeAssistantHomePage() {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(HOME_ASSISTANT)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
try {
startActivity(intent)
} catch (e: Exception) {
Log.e(TAG, "Unable to load Home Assistant home page", e)
Toast.makeText(context, commonR.string.what_is_this_crash, Toast.LENGTH_LONG).show()
}
}
private fun navigateToManualSetup() {
parentFragmentManager
.beginTransaction()
.replace(R.id.content, ManualSetupFragment::class.java, null)
.addToBackStack(null)
.commit()
}
private fun onInstanceClicked(instance: HomeAssistantInstance) {
viewModel.manualUrl.value = instance.url.toString()
parentFragmentManager
.beginTransaction()
.replace(R.id.content, AuthenticationFragment::class.java, null)
.addToBackStack(null)
.commit()
}
}
| 10 | Kotlin | 15 | 61 | b36bb0f67fd884b0f8c938c048b51134063784f2 | 3,067 | Home-Assistant-Companion-for-Android | Apache License 2.0 |
buildSrc/src/main/kotlin/idea/DistModelFlattener.kt | tnorbye | 162,147,688 | true | {"Kotlin": 32763299, "Java": 7651072, "JavaScript": 152998, "HTML": 71905, "Lex": 18278, "IDL": 10641, "ANTLR": 9803, "Shell": 7727, "Groovy": 6091, "Batchfile": 5362, "CSS": 4679, "Scala": 80} | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.buildUtils.idea
class DistModelFlattener() {
val stack = mutableSetOf<DistVFile>()
val common = mutableSetOf<DistVFile>()
fun DistVFile.flatten(): DistVFile {
val new = DistVFile(parent, name, file)
copyFlattenedContentsTo(new)
return new
}
private fun DistVFile.copyFlattenedContentsTo(new: DistVFile, inJar: Boolean = false) {
if (!stack.add(this)) {
return
}
try {
contents.forEach {
if (!shouldSkip(new, it)) {
when (it) {
is DistCopy -> {
val srcName = it.customTargetName ?: it.src.name
if (it.src.file.exists()) {
DistCopy(new, it.src, srcName)
}
if (!inJar && srcName.endsWith(".jar")) {
val newChild = new.getOrCreateChild(srcName)
it.src.copyFlattenedContentsTo(newChild, inJar = true)
} else {
it.src.copyFlattenedContentsTo(new, inJar)
}
}
is DistModuleOutput -> DistModuleOutput(new, it.projectId)
}
}
}
child.values.forEach { oldChild ->
if (inJar) {
val newChild =
if (oldChild.name.endsWith(".jar")) new
else new.getOrCreateChild(oldChild.name)
oldChild.copyFlattenedContentsTo(newChild, inJar = true)
} else {
val newChild = new.getOrCreateChild(oldChild.name)
oldChild.copyFlattenedContentsTo(newChild)
}
}
} finally {
stack.remove(this)
}
}
private fun shouldSkip(
new: DistVFile,
content: DistContentElement
) =
new.name == "kotlin-jps-plugin.jar" && content is DistCopy && content.customTargetName == "kotlin-compiler-runner.jar"
}
| 6 | Kotlin | 2 | 2 | b6be6a4919cd7f37426d1e8780509a22fa49e1b1 | 2,362 | kotlin | Apache License 2.0 |
feature-add-product-impl/src/main/java/com/software/feature_add_product_impl/domain/repositories/AddProductRepository.kt | kish-dev | 514,697,121 | false | {"Kotlin": 176048} | package com.software.feature_add_product_impl.domain.repositories
import com.software.core_utils.presentation.view_objects.ProductVO
import com.software.feature_api.wrappers.ProductDTO
import com.software.feature_api.wrappers.ServerResponse
interface AddProductRepository {
suspend fun addProduct(productDTO: ProductDTO): ServerResponse<Boolean>
suspend fun restoreProduct(): ServerResponse<ProductDTO>
fun getLastSavedDraft(): ProductDTO?
fun saveDraft(productDTO: ProductDTO)
fun clearDraft()
}
| 0 | Kotlin | 0 | 0 | c2c1cfb81bac7d83e6d02185211dcf6b125c1c57 | 525 | multi-module-marketplace | Apache License 2.0 |
shared/src/commonMain/kotlin/driverView.kt | MatthysDev | 741,112,517 | false | {"Kotlin": 22628, "Swift": 580, "Shell": 228} | import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
enum class SortOrder {
NUMBER_ASC, NUMBER_DESC, NAME
}
@Composable
fun driverView() {
val apiClient = remember { ApiClient() }
var year by remember { mutableStateOf("2023") } // Default year set to 2023
var yearForEffect by remember { mutableStateOf("2023") } // Default year set to 2023
var drivers by remember { mutableStateOf<List<Driver>?>(null) }
var isLoading by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
var sortOrder by remember { mutableStateOf(SortOrder.NUMBER_ASC) }
LaunchedEffect(yearForEffect) {
if (yearForEffect.isNotEmpty()) {
isLoading = true
try {
drivers = apiClient.getDriversByYear(yearForEffect).MRData.DriverTable.Drivers
} catch (e: Exception) {
error = e.message
} finally {
isLoading = false
}
}
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Formula 1 Drivers",
color = Color.White,
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.fillMaxWidth()
.background(Color.Red)
.padding(16.dp)
)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
) {
OutlinedTextField(
value = year,
onValueChange = { year = it },
label = { Text("Enter Year") },
singleLine = true,
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = Color.Black,
unfocusedBorderColor = Color.Black
),
modifier = Modifier
.weight(1f)
.height(IntrinsicSize.Min) // Match the height to the Button
)
Spacer(modifier = Modifier.width(8.dp))
Button(
onClick = {
error = null
drivers = null
yearForEffect = year // Trigger LaunchedEffect
},
colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red),
modifier = Modifier
.height(IntrinsicSize.Min) // Match the height to the TextField
.padding(start = 8.dp)
) {
Text("Get Drivers", color = Color.White)
}
}
Spacer(modifier = Modifier.height(8.dp))
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier.fillMaxWidth()
) {
Button(onClick = { sortOrder = SortOrder.NUMBER_ASC }, colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red)
) {
Text("Number Asc", color = Color.White)
}
Button(onClick = { sortOrder = SortOrder.NUMBER_DESC }, colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red)) {
Text("Number Desc", color = Color.White)
}
Button(onClick = { sortOrder = SortOrder.NAME }, colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red)) {
Text("Alphabetic", color = Color.White)
}
}
Spacer(modifier = Modifier.height(8.dp))
when {
isLoading -> Text("Loading...", fontWeight = FontWeight.SemiBold)
error != null -> Text("Error: $error", fontWeight = FontWeight.SemiBold)
drivers.isNullOrEmpty() -> Text("No drivers found", fontWeight = FontWeight.SemiBold)
else -> DriversList(drivers!!, sortOrder)
}
}
}
@Composable
fun DriverCard(driver: Driver) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 4.dp),
elevation = 4.dp
) {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "${driver.givenName} ${driver.familyName}",
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Number: ${driver.permanentNumber}",
textAlign = TextAlign.Center
)
// Add more driver details here if needed
}
}
}
@Composable
fun DriversList(drivers: List<Driver>, sortOrder: SortOrder) {
val sortedDrivers = when (sortOrder) {
SortOrder.NUMBER_ASC -> drivers.sortedBy { it.permanentNumber }
SortOrder.NUMBER_DESC -> drivers.sortedByDescending { it.permanentNumber }
SortOrder.NAME -> drivers.sortedBy { "${it.givenName} ${it.familyName}" }
}
LazyColumn(
contentPadding = PaddingValues(top = 8.dp, bottom = 64.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(sortedDrivers) { driver ->
DriverCard(driver)
}
}
}
| 0 | Kotlin | 0 | 0 | 6eb44ab076e42815672210e5dc134ea4366fe54b | 5,893 | kotlinApi | Apache License 2.0 |
foodbanks/src/main/java/com/yuriisurzhykov/foodbanks/data/point/CloudToCachePointMapper.kt | yuriisurzhykov | 524,002,724 | false | {"Kotlin": 270404, "Java": 1165} | package com.yuriisurzhykov.foodbanks.data.point
import com.yuriisurzhykov.foodbanks.core.data.Mapper
import com.yuriisurzhykov.foodbanks.data.point.cache.PointCache
import com.yuriisurzhykov.foodbanks.data.point.cloud.PointCloud
import javax.inject.Inject
interface CloudToCachePointMapper : Mapper<List<PointCloud>, List<PointCache>> {
fun map(input: PointCloud): PointCache
class Base @Inject constructor() : CloudToCachePointMapper {
override fun map(input: List<PointCloud>): List<PointCache> {
return input.map { map(it) }
}
override fun map(input: PointCloud): PointCache {
return PointCache(
pointId = 0,
cityCodeId = input.cityCode,
address = input.address,
placeName = input.placeName,
coordinates = input.coordinates,
workingHours = input.workingHours
)
}
}
} | 1 | Kotlin | 0 | 2 | b0882a4a7f80705cff8432b3c0a2155c4650fe67 | 951 | PointDetector | MIT License |
compiler/ir/ir.tree/gen/org/jetbrains/kotlin/ir/expressions/IrConstructorCall.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2024 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.
*/
// This file was generated automatically. See compiler/ir/ir.tree/tree-generator/ReadMe.md.
// DO NOT MODIFY IT MANUALLY.
package org.jetbrains.kotlin.ir.expressions
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.ir.symbols.IrConstructorSymbol
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
/**
* A leaf IR tree element.
*
* Generated from: [org.jetbrains.kotlin.ir.generator.IrTree.constructorCall]
*/
abstract class IrConstructorCall : IrFunctionAccessExpression() {
abstract override var symbol: IrConstructorSymbol
abstract var source: SourceElement
abstract var constructorTypeArgumentsCount: Int
override fun <R, D> accept(visitor: IrElementVisitor<R, D>, data: D): R =
visitor.visitConstructorCall(this, data)
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,008 | kotlin | Apache License 2.0 |
trixnity-core/src/commonMain/kotlin/net/folivo/trixnity/core/model/events/m/key/verification/VerificationReadyEventContent.kt | benkuly | 330,904,570 | false | {"Kotlin": 4132578, "JavaScript": 5352, "TypeScript": 2906, "CSS": 1454, "Dockerfile": 1275} | package net.folivo.trixnity.core.model.events.m.key.verification
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import net.folivo.trixnity.core.model.events.m.Mentions
import net.folivo.trixnity.core.model.events.m.RelatesTo
/**
* @see <a href="https://spec.matrix.org/unstable/client-server-api/#mkeyverificationready">matrix spec</a>
*/
@Serializable
data class VerificationReadyEventContent(
@SerialName("from_device")
val fromDevice: String,
@SerialName("methods")
val methods: Set<VerificationMethod>,
@SerialName("m.relates_to")
override val relatesTo: RelatesTo.Reference?,
@SerialName("transaction_id")
override val transactionId: String?,
) : VerificationStep {
override val mentions: Mentions? = null
override val externalUrl: String? = null
} | 0 | Kotlin | 3 | 27 | 645fc08a4aa5a119ca336678ecde33f4bd7aa3e0 | 832 | trixnity | Apache License 2.0 |
actor4k/src/main/kotlin/io/github/smyrgeorge/actor4k/util/java/JRef.kt | smyrgeorge | 724,199,398 | false | {"Kotlin": 91094, "Smarty": 1752, "Shell": 1551, "Dockerfile": 120} | package io.github.smyrgeorge.actor4k.util.java
import io.github.smyrgeorge.actor4k.actor.Actor
import kotlinx.coroutines.future.future
import kotlinx.coroutines.runBlocking
import java.util.concurrent.CompletableFuture
data class JRef(val ref: Actor.Ref) {
fun tell(msg: Any): CompletableFuture<Unit> =
runBlocking { future { ref.tell(msg) } }
fun <R> ask(msg: Any): CompletableFuture<R> =
runBlocking { future { ref.ask(msg) } }
}
| 0 | Kotlin | 0 | 11 | d466240ba86e08dff7f5fdfd9a1d565b7bc54f4b | 459 | actor4k | MIT License |
app/src/main/java/eu/kanade/tachiyomi/ui/browse/migration/manga/MigrationMangaController.kt | Rattlehead15 | 330,245,026 | true | null | package eu.kanade.tachiyomi.ui.browse.migration.manga
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import dev.chrisbanes.insetter.applyInsetter
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.kanade.tachiyomi.databinding.MigrationMangaControllerBinding
import eu.kanade.tachiyomi.ui.base.controller.NucleusController
import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction
import eu.kanade.tachiyomi.ui.browse.migration.search.SearchController
import eu.kanade.tachiyomi.ui.manga.MangaController
class MigrationMangaController :
NucleusController<MigrationMangaControllerBinding, MigrationMangaPresenter>,
FlexibleAdapter.OnItemClickListener,
MigrationMangaAdapter.OnCoverClickListener {
private var adapter: MigrationMangaAdapter? = null
constructor(sourceId: Long, sourceName: String?) : super(
bundleOf(
SOURCE_ID_EXTRA to sourceId,
SOURCE_NAME_EXTRA to sourceName
)
)
@Suppress("unused")
constructor(bundle: Bundle) : this(
bundle.getLong(SOURCE_ID_EXTRA),
bundle.getString(SOURCE_NAME_EXTRA)
)
private val sourceId: Long = args.getLong(SOURCE_ID_EXTRA)
private val sourceName: String? = args.getString(SOURCE_NAME_EXTRA)
override fun getTitle(): String? {
return sourceName
}
override fun createPresenter(): MigrationMangaPresenter {
return MigrationMangaPresenter(sourceId)
}
override fun createBinding(inflater: LayoutInflater) = MigrationMangaControllerBinding.inflate(inflater)
override fun onViewCreated(view: View) {
super.onViewCreated(view)
binding.recycler.applyInsetter {
type(navigationBars = true) {
padding()
}
}
adapter = MigrationMangaAdapter(this)
binding.recycler.layoutManager = LinearLayoutManager(view.context)
binding.recycler.adapter = adapter
adapter?.fastScroller = binding.fastScroller
}
override fun onDestroyView(view: View) {
adapter = null
super.onDestroyView(view)
}
fun setManga(manga: List<MigrationMangaItem>) {
adapter?.updateDataSet(manga)
}
override fun onItemClick(view: View, position: Int): Boolean {
val item = adapter?.getItem(position) as? MigrationMangaItem ?: return false
val controller = SearchController(item.manga)
router.pushController(controller.withFadeTransaction())
return false
}
override fun onCoverClick(position: Int) {
val mangaItem = adapter?.getItem(position) as? MigrationMangaItem ?: return
router.pushController(MangaController(mangaItem.manga).withFadeTransaction())
}
companion object {
const val SOURCE_ID_EXTRA = "source_id_extra"
const val SOURCE_NAME_EXTRA = "source_name_extra"
}
}
| 9 | Kotlin | 4 | 61 | e64143ef4a3734ba60334677be0b5e70074782ec | 2,993 | tachiyomiOCR | Apache License 2.0 |
src/main/java/io/sc3/plethora/gameplay/modules/introspection/IntrospectionModuleItem.kt | SwitchCraftCC | 491,699,521 | false | {"Kotlin": 383687, "Java": 259087} | package io.sc3.plethora.gameplay.modules.introspection
import io.sc3.plethora.gameplay.modules.BindableModuleItem
import io.sc3.plethora.gameplay.registry.PlethoraModules.INTROSPECTION_M
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.item.ItemStack
import net.minecraft.screen.GenericContainerScreenHandler
import net.minecraft.screen.SimpleNamedScreenHandlerFactory
import net.minecraft.stat.Stats
import net.minecraft.text.Text
import net.minecraft.text.Text.translatable
import net.minecraft.util.Hand
import net.minecraft.util.Identifier
import net.minecraft.util.TypedActionResult
import net.minecraft.world.World
class IntrospectionModuleItem(settings: Settings) : BindableModuleItem("introspection", settings) {
override fun getModule(): Identifier = INTROSPECTION_M
override fun onBindableModuleUse(world: World, player: PlayerEntity, hand: Hand): TypedActionResult<ItemStack> {
// Allow the player to open their ender chest by using the introspection module
val inv = player.enderChestInventory
if (inv != null) {
player.openHandledScreen(SimpleNamedScreenHandlerFactory({ syncId, playerInv, _ ->
GenericContainerScreenHandler.createGeneric9x3(syncId, playerInv, inv)
}, CONTAINER_TEXT))
player.incrementStat(Stats.OPEN_ENDERCHEST)
}
return TypedActionResult.success(player.getStackInHand(hand))
}
companion object {
val CONTAINER_TEXT: Text = translatable("container.enderchest")
}
}
| 26 | Kotlin | 8 | 16 | 1309c51911a9b146218e5dae65a16dc8f932b23e | 1,481 | Plethora-Fabric | MIT License |
compiler/fir/analysis-tests/testData/resolve/problems/kt42346.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FILE: MagicConstant.java
public @interface MagicConstant {
long[] intValues() default {};
}
// FILE: kt42346.kt
class StepRequest {
companion object {
const val STEP_INTO = 0
const val STEP_OVER = 1
const val STEP_OUT = 2
}
}
@MagicConstant(intValues = [StepRequest.STEP_INTO.toLong(), StepRequest.STEP_OVER.toLong(), StepRequest.STEP_OUT.toLong()])
val depth: Int = 42
annotation class KotlinMagicConstant(val intValues: LongArray)
@KotlinMagicConstant(intValues = [StepRequest.STEP_INTO.toLong(), StepRequest.STEP_OVER.toLong(), StepRequest.STEP_OUT.toLong()])
val kotlinDepth: Int = 42
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 634 | kotlin | Apache License 2.0 |
autofill/autofill-impl/src/main/java/com/duckduckgo/autofill/jsbridge/response/AutofillResponseWriter.kt | llopisdon | 394,658,125 | true | {"Kotlin": 6660609, "HTML": 63669, "Java": 35154, "Ruby": 9660, "JavaScript": 8281, "C++": 1820, "CMake": 1298, "Shell": 784} | /*
* Copyright (c) 2022 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.autofill.jsbridge.response
import com.duckduckgo.autofill.domain.javascript.JavascriptCredentials
import com.duckduckgo.di.scopes.AppScope
import com.squareup.anvil.annotations.ContributesBinding
import com.squareup.moshi.Moshi
import javax.inject.Inject
interface AutofillResponseWriter {
fun generateResponseGetAutofillData(credentials: JavascriptCredentials): String
fun generateEmptyResponseGetAutofillData(): String
fun generateResponseGetAvailableInputTypes(credentialsAvailable: Boolean, emailAvailable: Boolean): String
fun generateContentScope(): String
fun generateUserUnprotectedDomains(): String
fun generateUserPreferences(autofillCredentials: Boolean, showInlineKeyIcon: Boolean = false): String
}
@ContributesBinding(AppScope::class)
class AutofillJsonResponseWriter @Inject constructor(val moshi: Moshi) : AutofillResponseWriter {
private val availableInputTypesAdapter = moshi.adapter(AvailableInputSuccessResponse::class.java).indent(" ")
private val autofillDataAdapterCredentialsAvailable = moshi.adapter(ContainingCredentials::class.java).indent(" ")
private val autofillDataAdapterCredentialsUnavailable = moshi.adapter(EmptyResponse::class.java).indent(" ")
override fun generateResponseGetAutofillData(credentials: JavascriptCredentials): String {
val credentialsResponse = ContainingCredentials.CredentialSuccessResponse(credentials)
val topLevelResponse = ContainingCredentials(success = credentialsResponse)
return autofillDataAdapterCredentialsAvailable.toJson(topLevelResponse)
}
override fun generateEmptyResponseGetAutofillData(): String {
val credentialsResponse = EmptyResponse.EmptyCredentialResponse()
val topLevelResponse = EmptyResponse(success = credentialsResponse)
return autofillDataAdapterCredentialsUnavailable.toJson(topLevelResponse)
}
override fun generateResponseGetAvailableInputTypes(credentialsAvailable: Boolean, emailAvailable: Boolean): String {
val availableInputTypes = AvailableInputSuccessResponse(credentialsAvailable, emailAvailable)
return availableInputTypesAdapter.toJson(availableInputTypes)
}
/*
* hardcoded for now, but eventually will be a dump of the most up-to-date privacy remote config, untouched by us
*/
override fun generateContentScope(): String {
return """
contentScope = {
"features": {
"autofill": {
"state": "enabled",
"exceptions": []
}
},
"unprotectedTemporary": []
};
""".trimIndent()
}
/*
* userUnprotectedDomains: any sites for which the user has chosen to disable privacy protections (leave empty for now)
*/
override fun generateUserUnprotectedDomains(): String {
return """
userUnprotectedDomains = [];
""".trimIndent()
}
override fun generateUserPreferences(
autofillCredentials: Boolean,
showInlineKeyIcon: Boolean
): String {
return """
userPreferences = {
"debug": false,
"platform": {
"name": "android"
},
"features": {
"autofill": {
"settings": {
"featureToggles": {
"inputType_credentials": $autofillCredentials,
"inputType_identities": false,
"inputType_creditCards": false,
"emailProtection": true,
"password_generation": false,
"credentials_saving": $autofillCredentials,
"inlineIcon_credentials": $showInlineKeyIcon
}
}
}
}
};
""".trimIndent()
}
}
| 0 | Kotlin | 0 | 0 | 6a29341775094037eae7802167129d240bc2790e | 4,542 | Android | Apache License 2.0 |
compiler/testData/codegen/box/coroutines/tailCallOptimizations/tryCatchTailCall.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // TARGET_BACKEND: JVM
// FULL_JDK
// WITH_STDLIB
// WITH_COROUTINES
// CHECK_TAIL_CALL_OPTIMIZATION
// JVM_ABI_K1_K2_DIFF: KT-63864
import helpers.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
suspend fun catchException(): String {
try {
return suspendWithException()
}
catch(e: Exception) {
return e.message!!
}
}
suspend fun suspendWithException(): String = "OK".also { TailCallOptimizationChecker.saveStackTrace() }
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
fun box(): String {
var res = "FAIL"
builder {
res = catchException()
}
TailCallOptimizationChecker.checkStateMachineIn("catchException")
return res
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 736 | kotlin | Apache License 2.0 |
app/src/main/java/com/github/michaljaz/messenger/adapters/UsersAdapter.kt | michaljaz | 357,497,333 | false | null | package com.github.michaljaz.messenger.adapters
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.github.michaljaz.messenger.R
import com.github.michaljaz.messenger.utils.RoundedTransformation
import com.github.michaljaz.messenger.utils.setIconUrl
import com.squareup.picasso.Picasso
class User(
val displayName: String,
val photoUrl: String,
val userId:String)
class UsersAdapter(
private val context: Context,
private val mUsers:ArrayList<User>
) : BaseAdapter() {
override fun getCount(): Int {
return mUsers.size
}
override fun getItem(position: Int): User{
return mUsers[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
@SuppressLint("ViewHolder")
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val row: View = inflater.inflate(R.layout.row_user, parent, false)
val i1: ImageView = row.findViewById(R.id.imgIcon) as ImageView
val title: TextView = row.findViewById(R.id.txtTitle)
title.text = mUsers[position].displayName
val image=mUsers[position].photoUrl
i1.setIconUrl(image)
return row
}
} | 10 | Kotlin | 1 | 3 | 5fd962a763da8bcfb6d90121fbc719666bc2614c | 1,548 | messenger-android | MIT License |
adapter/build.gradle.kts | wxygr | 476,135,401 | true | {"Kotlin": 181792} | import com.android.build.gradle.LibraryExtension
plugins {
id(libs.plugins.android.library.get().pluginId)
id(libs.plugins.kotlin.android.get().pluginId)
id(libs.plugins.kotlin.kapt.get().pluginId)
}
setupBase<LibraryExtension>(LibModule.Adapter)
dependencies {
api(libs.androidX.collection)
api(libs.androidX.paging)
api(libs.androidX.recyclerView)
api(libs.androidX.viewPager2)
}
| 0 | null | 0 | 0 | f484704a58c2d6db23d1185ffd9ab00579cf8bdd | 399 | DemoApp | Apache License 2.0 |
ktor-core/src/org/jetbrains/ktor/interception/InterceptCall.kt | cy6erGn0m | 40,906,748 | true | {"Kotlin": 635453} | package org.jetbrains.ktor.interception
import org.jetbrains.ktor.application.*
interface InterceptApplicationCall<C : ApplicationCall> {
fun intercept(interceptor: C.(C.() -> ApplicationCallResult) -> ApplicationCallResult)
}
| 0 | Kotlin | 0 | 0 | 2d3b4f0b813b05370b22fae4c0d83d99122f604f | 233 | ktor | Apache License 2.0 |
app/src/test/java/org/simple/clinic/selectstate/SelectableStateItemTest.kt | simpledotorg | 132,515,649 | false | {"Kotlin": 5970450, "Shell": 1660, "HTML": 545} | package org.simple.clinic.selectstate
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.simple.sharedTestCode.TestData
class SelectableStateItemTest {
private val andhraPradesh = TestData.state(displayName = "Andhra Pradesh")
private val kerala = TestData.state(displayName = "Kerala")
private val punjab = TestData.state(displayName = "Punjab")
private val states = listOf(andhraPradesh, kerala, punjab)
@Test
fun `if the user hasn't selected a state, then none of list items should be selected`() {
// when
val listItems = SelectableStateItem.from(states = states, selectedState = null)
// then
assertThat(listItems)
.containsExactly(
SelectableStateItem(state = andhraPradesh, isStateSelectedByUser = false, showDivider = true),
SelectableStateItem(state = kerala, isStateSelectedByUser = false, showDivider = true),
SelectableStateItem(state = punjab, isStateSelectedByUser = false, showDivider = false)
).inOrder()
}
@Test
fun `if the user has selected a state, then list item should be selected`() {
// when
val listItems = SelectableStateItem.from(states = states, selectedState = kerala)
// then
assertThat(listItems)
.containsExactly(
SelectableStateItem(state = andhraPradesh, isStateSelectedByUser = false, showDivider = true),
SelectableStateItem(state = kerala, isStateSelectedByUser = true, showDivider = true),
SelectableStateItem(state = punjab, isStateSelectedByUser = false, showDivider = false)
).inOrder()
}
@Test
fun `if there is only one item in the list, then divider must not be shown`() {
// when
val listItems = SelectableStateItem.from(states = listOf(andhraPradesh), selectedState = andhraPradesh)
// then
assertThat(listItems)
.containsExactly(
SelectableStateItem(state = andhraPradesh, isStateSelectedByUser = true, showDivider = false)
).inOrder()
}
}
| 4 | Kotlin | 73 | 223 | 58d14c702db2b27b9dc6c1298c337225f854be6d | 2,031 | simple-android | MIT License |
src/main/kotlin/org/mk/lanparty/repository/UserRepository.kt | michaelkrejci | 146,989,499 | false | null | package org.mk.lanparty.repository
import org.mk.lanparty.domain.User
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.repository.CrudRepository
interface UserRepository : JpaRepository<User, Long>, CrudRepository<User, Long> | 0 | Kotlin | 0 | 0 | 200e302dcc2d8008954adf51f28c784ee9961275 | 271 | lan-party-calc-backend | MIT License |
kvision-modules/kvision-onsenui/src/main/kotlin/pl/treksoft/kvision/onsenui/form/OnsDateTimeInput.kt | yankee42 | 317,164,090 | true | {"Kotlin": 2863261, "CSS": 10723, "JavaScript": 10226, "HTML": 1858} | /*
* Copyright (c) 2017-present <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package pl.treksoft.kvision.onsenui.form
import com.github.snabbdom.VNode
import pl.treksoft.kvision.core.Container
import pl.treksoft.kvision.core.StringBoolPair
import pl.treksoft.kvision.core.StringPair
import pl.treksoft.kvision.core.Widget
import pl.treksoft.kvision.form.FormInput
import pl.treksoft.kvision.form.InputSize
import pl.treksoft.kvision.form.ValidationStatus
import pl.treksoft.kvision.state.ObservableState
import pl.treksoft.kvision.types.toDateF
import pl.treksoft.kvision.types.toStringF
import pl.treksoft.kvision.utils.set
import kotlin.js.Date
/**
* Data/time input modes.
*/
enum class DateTimeMode(internal val format: String) {
DATE("YYYY-MM-DD"),
TIME("HH:mm"),
DATETIME("YYYY-MM-DDTHH:mm")
}
/**
* OnsenUI date/time input component.
*
* @constructor Creates a date/time input component.
* @param value date/time input value
* @param mode date/time input mode
* @param min minimal value
* @param max maximal value
* @param step step value
* @param inputId the ID of the input element
* @param classes a set of CSS class names
* @param init an initializer extension function
*/
open class OnsDateTimeInput(
value: Date? = null,
mode: DateTimeMode = DateTimeMode.DATETIME,
min: Date? = null,
max: Date? = null,
step: Number? = null,
inputId: String? = null,
classes: Set<String> = setOf(),
init: (OnsDateTimeInput.() -> Unit)? = null
) : Widget(classes + "kv-ons-form-control"), FormInput, ObservableState<Date?> {
protected val observers = mutableListOf<(Date?) -> Unit>()
/**
* Date/time input value.
*/
var value by refreshOnUpdate(value) { refreshState(); observers.forEach { ob -> ob(it) } }
/**
* Date/time mode.
*/
var mode by refreshOnUpdate(mode)
/**
* The value attribute of the generated HTML input element.
*
* This value is placed directly in generated HTML code, while the [value] property is dynamically
* bound to the date/time input value.
*/
var startValue by refreshOnUpdate(value) { this.value = it; refresh() }
/**
* Minimal date/time value.
*/
var min by refreshOnUpdate(min)
/**
* Maximal date/time value.
*/
var max by refreshOnUpdate(max)
/**
* Step value.
*/
var step by refreshOnUpdate(step)
/**
* The ID of the input element.
*/
var inputId: String? by refreshOnUpdate(inputId)
/**
* A modifier attribute to specify custom styles.
*/
var modifier: String? by refreshOnUpdate()
/**
* The name attribute of the generated HTML input element.
*/
override var name: String? by refreshOnUpdate()
/**
* Determines if the field is disabled.
*/
override var disabled by refreshOnUpdate(false)
/**
* Determines if the date/time input is automatically focused.
*/
var autofocus: Boolean? by refreshOnUpdate()
/**
* Determines if the date/time input is read-only.
*/
var readonly: Boolean? by refreshOnUpdate()
/**
* The size of the input.
*/
override var size: InputSize? by refreshOnUpdate()
/**
* The validation status of the input.
*/
override var validationStatus: ValidationStatus? by refreshOnUpdate()
/**
* Determines if autocomplete is enabled for the input element.
*/
var autocomplete: Boolean? by refreshOnUpdate()
init {
this.setInternalEventListener<OnsDateTimeInput> {
input = {
self.changeValue()
}
}
@Suppress("LeakingThis")
init?.invoke(this)
}
override fun render(): VNode {
return render("ons-input")
}
override fun getSnClass(): List<StringBoolPair> {
val cl = super.getSnClass().toMutableList()
validationStatus?.let {
cl.add(it.className to true)
}
size?.let {
cl.add(it.className to true)
}
return cl
}
override fun getSnAttrs(): List<StringPair> {
val sn = super.getSnAttrs().toMutableList()
when (mode) {
DateTimeMode.DATE -> sn.add("type" to "date")
DateTimeMode.TIME -> sn.add("type" to "time")
DateTimeMode.DATETIME -> sn.add("type" to "datetime-local")
}
startValue?.let {
sn.add("value" to it.toStringF(mode.format))
}
min?.let {
sn.add("min" to it.toStringF(mode.format))
}
max?.let {
sn.add("max" to it.toStringF(mode.format))
}
step?.let {
sn.add("step" to "$it")
}
inputId?.let {
sn.add("input-id" to it)
}
modifier?.let {
sn.add("modifier" to it)
}
name?.let {
sn.add("name" to it)
}
autofocus?.let {
if (it) {
sn.add("autofocus" to "autofocus")
}
}
readonly?.let {
if (it) {
sn.add("readonly" to "readonly")
}
}
if (disabled) {
sn.add("disabled" to "disabled")
}
autocomplete?.let {
if (it) {
sn.add("autocomplete" to "on")
} else {
sn.add("autocomplete" to "off")
}
}
return sn
}
override fun afterInsert(node: VNode) {
refreshState()
}
/**
* @suppress
* Internal function
*/
protected open fun refreshState() {
value?.let {
getElementJQuery()?.`val`(it.toStringF(mode.format))
} ?: getElementJQueryD()?.`val`(null)
}
/**
* @suppress
* Internal function
*/
protected open fun changeValue() {
val v = getElementJQuery()?.`val`() as String?
if (v != null && v != "") {
this.value = v.toDateF(mode.format)
} else {
this.value = null
}
}
/**
* Returns the value of the date/time input as a String.
* @return value as a String
*/
fun getValueAsString(): String? {
return value?.toStringF(mode.format)
}
/**
* Makes the input element focused.
*/
override fun focus() {
getElementJQuery()?.focus()
}
/**
* Makes the input element blur.
*/
override fun blur() {
getElementJQuery()?.blur()
}
override fun getState(): Date? = value
override fun subscribe(observer: (Date?) -> Unit): () -> Unit {
observers += observer
observer(value)
return {
observers -= observer
}
}
}
/**
* DSL builder extension function.
*
* It takes the same parameters as the constructor of the built component.
*/
fun Container.onsDateTimeInput(
value: Date? = null,
mode: DateTimeMode = DateTimeMode.DATETIME,
min: Date? = null,
max: Date? = null,
step: Number? = null,
inputId: String? = null,
classes: Set<String>? = null,
className: String? = null,
init: (OnsDateTimeInput.() -> Unit)? = null
): OnsDateTimeInput {
val onsDateTimeInput =
OnsDateTimeInput(value, mode, min, max, step, inputId, classes ?: className.set, init)
this.add(onsDateTimeInput)
return onsDateTimeInput
}
| 0 | Kotlin | 0 | 0 | 4acdc589b7265fc1c9a994e16285768dda620276 | 8,470 | kvision | MIT License |
azuredata/src/main/java/com/azure/data/model/service/Response.kt | CiskooCiskoo | 247,443,839 | true | {"Kotlin": 565872, "PowerShell": 29081, "Java": 28653, "HTML": 8933, "Batchfile": 816} | package com.azure.data.model.service
import okhttp3.Request
import java.lang.reflect.Type
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
typealias DataResponse = Response<String>
open class Response<T>(
// The request sent to the server.
val request: Request? = null,
// The server's response to the request.
val response: okhttp3.Response? = null,
// The json data returned by the server (if applicable)
val jsonData: String? = null,
// The result of response deserialization.
val result: Result<T>,
// The resourceLocation, filled out when there could be more results
val resourceLocation: ResourceLocation? = null,
// The Type of the Resource
val resourceType: Type? = null,
// Whether the response is from the local cache or not.
val fromCache: Boolean = false
) {
val metadata : ResponseMetadata by lazy {
ResponseMetadata(response)
}
constructor(
// the error
error: DataError,
// The URL request sent to the server.
request: Request? = null,
// The server's response to the URL request.
response: okhttp3.Response? = null,
// The json data returned by the server.
jsonData: String? = null,
// Whether the response is from the local cache or not.
fromCache: Boolean = false) : this(request, response, jsonData, Result<T>(error), fromCache = fromCache)
constructor(result: T) : this(result = Result(result))
/**
* Returns the associated error value if the result if it is a failure, null otherwise.
*/
val error: DataError? get() = result.error
/**
* Returns `true` if the result is a success, `false` otherwise.
*/
val isSuccessful get() = error == null
/**
* Returns `true` if the result is an error, `false` otherwise.
*/
val isErrored get() = error != null
/**
* Returns the associated value of the result if it is a success, null otherwise.
*/
val resource: T? = result.resource
}
fun <T, U> Response<T>.map(transform: (T) -> U): Response<U> {
return Response(request, response, jsonData, result.map(transform), resourceLocation, resourceType, fromCache)
}
fun <T, U> Result<T>.map(transform: (T) -> U): Result<U> {
resource?.let { return Result(transform(it)) }
error?.let { return Result(it) }
return Result(DataError(DocumentClientError.UnknownError))
} | 0 | null | 0 | 0 | 6477f880d0a7b55c0f2fda320febe307199e1ca3 | 2,583 | azure-sdk-for-android | MIT License |
app/src/main/java/com/tufusi/kotlinmvp/KKApplication.kt | LeoCheung0221 | 273,992,672 | false | null | package com.tufusi.kotlinmvp
import android.app.Application
/**
* Created by 鼠夏目 on 2020/7/22.
* @author 鼠夏目
* @see
* @description
*/
class KKApplication : Application() {
override fun onCreate() {
super.onCreate()
//初始化room
}
} | 0 | Kotlin | 0 | 0 | a77eb18d94be5688fab2384d57da00a8943a5a7e | 280 | KotlinMVP | MIT License |
compiler/util-klib-metadata/src/org/jetbrains/kotlin/serialization/konan/impl/Deprecated.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "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.
*/
@file:Suppress("unused") // The declarations below may be used outside the Kotlin repo
package org.jetbrains.kotlin.serialization.konan.impl
@Deprecated(
"This class has been moved from package org.jetbrains.kotlin.serialization.konan.impl to package org.jetbrains.kotlin.library.metadata.impl",
ReplaceWith("org.jetbrains.kotlin.library.metadata.impl.KlibMetadataModuleDescriptorFactoryImpl")
)
typealias KlibMetadataModuleDescriptorFactoryImpl = org.jetbrains.kotlin.library.metadata.impl.KlibMetadataModuleDescriptorFactoryImpl
@Deprecated(
"This class has been moved from package org.jetbrains.kotlin.serialization.konan.impl to package org.jetbrains.kotlin.library.metadata.impl",
ReplaceWith("org.jetbrains.kotlin.library.metadata.impl.KlibResolvedModuleDescriptorsFactoryImpl")
)
typealias KlibResolvedModuleDescriptorsFactoryImpl = org.jetbrains.kotlin.library.metadata.impl.KlibResolvedModuleDescriptorsFactoryImpl
@Deprecated(
"This class has been moved from package org.jetbrains.kotlin.serialization.konan.impl to package org.jetbrains.kotlin.library.metadata.impl",
ReplaceWith("org.jetbrains.kotlin.library.metadata.impl.ForwardDeclarationsPackageFragmentDescriptor")
)
typealias ForwardDeclarationsPackageFragmentDescriptor = org.jetbrains.kotlin.library.metadata.impl.ForwardDeclarationsPackageFragmentDescriptor
@Deprecated(
"This object has been moved from package org.jetbrains.kotlin.serialization.konan.impl to package org.jetbrains.kotlin.library.metadata.impl",
ReplaceWith("org.jetbrains.kotlin.library.metadata.impl.ForwardDeclarationsFqNames")
)
@Suppress("DEPRECATION_ERROR")
typealias ForwardDeclarationsFqNames = org.jetbrains.kotlin.library.metadata.impl.ForwardDeclarationsFqNames
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,959 | kotlin | Apache License 2.0 |
app/src/main/java/com/example/budget_app/view/AccountsAdapter.kt | bennettapps | 191,846,144 | false | null | package com.example.budget_app.view
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.budget_app.R
import com.example.budget_app.model.AccountDB
import com.example.budget_app.presenter.AccountsPresenter
import com.example.budget_app.presenter.DatabaseHandler
class AccountsAdapter(private val list: ArrayList<List<Any>>, private val context: Context):
RecyclerView.Adapter<AccountsAdapter.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindViews(list[position])
}
override fun onCreateViewHolder(parent: ViewGroup, position: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.accounts_card, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return list.size
}
inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val name = itemView.findViewById<TextView>(R.id.accountName)
private val amount = itemView.findViewById<TextView>(R.id.accountBalance)
private val deleteButton = itemView.findViewById<Button>(R.id.deleteAccountButton)
private val editButton = itemView.findViewById<Button>(R.id.editAccountButton)
fun bindViews(items: List<Any>) {
name.text = items[0].toString()
amount.text = "$${items[1]}.00"
deleteButton.setOnClickListener(this)
editButton.setOnClickListener(this)
}
override fun onClick(view: View?) {
val position = adapterPosition
val accountsPresenter = AccountsPresenter(context, itemView.rootView)
val db = DatabaseHandler(context, AccountDB())
val dbArray = db.readAll()
dbArray.reverse()
when(view!!.id) {
deleteButton.id -> {
accountsPresenter.deleteAccount(dbArray[position][2] as Int)
}
editButton.id -> {
accountsPresenter.editAccount(dbArray[position][2] as Int)
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 16e19cb359edaf730f317f5a043dad8a2fd38295 | 2,327 | Budget-App | MIT License |
core/src/main/kotlin/no/nav/poao_tilgang/core/policy/NavAnsattTilgangTilSkjermetPersonPolicy.kt | navikt | 491,417,288 | false | {"Kotlin": 306590, "Dockerfile": 98} | package no.nav.poao_tilgang.core.policy
import no.nav.poao_tilgang.core.domain.*
interface NavAnsattTilgangTilSkjermetPersonPolicy : Policy<NavAnsattTilgangTilSkjermetPersonPolicy.Input> {
data class Input (
val navAnsattAzureId: AzureObjectId,
val norskIdent: NorskIdent
) : PolicyInput
}
| 9 | Kotlin | 3 | 0 | e34438605052cca99819963cd204432b67417d22 | 300 | poao-tilgang | MIT License |
app/src/main/java/com/itmoldova/bookmarks/BookmarksPresenter.kt | vgrec | 141,891,134 | false | null | package com.itmoldova.bookmarks
import com.itmoldova.db.ArticleDao
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
class BookmarksPresenter(private val view: BookmarksContract.View,
private val articleDao: ArticleDao) : BookmarksContract.Presenter {
private var disposable: Disposable? = null
override fun loadBookmarks() {
disposable = articleDao.loadAllArticles()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ result -> view.showBookmarks(result) })
}
fun cancel() {
disposable?.let {
if (!it.isDisposed) {
it.dispose()
}
}
}
} | 0 | Kotlin | 1 | 2 | ef2b4d3e9ca923b572c1959f512162d11b18bbc1 | 825 | ITMoldova | Apache License 2.0 |
common/src/commonMain/kotlin/org/jetbrains/kotlinconf/login/LoginInteractor.kt | wangjiangtao | 154,785,667 | true | {"Kotlin": 108763, "Swift": 21923, "Ruby": 309} | package org.jetbrains.kotlinconf.login
class LoginInteractor {
// lateinit var presenter: LoginPresenter
// lateinit var loginService: LoginService
fun didBecomeActive() {
setNextButtonClick()
setCountryCodeClick()
}
/**
* 点击下一步按钮
*/
private fun setNextButtonClick() {
}
/**
* 设置CountryCode点击事件
*/
private fun setCountryCodeClick() {
}
/**
* 请求用户登录状态
*/
private fun requestUserLoginState(phoneNumber: String) {
}
/**
* Presenter interface implemented by this RIB's view.
*/
interface LoginPresenter {
fun nextButtonClick(callback: (String) -> Unit)
fun hideSoftKeyboard()
}
}
enum class LoginPageType {
PHONE, USERNAME_EMAIL
} | 0 | Kotlin | 1 | 0 | e76b5fc3d8fd173892f67e811704d5ea41be0ec5 | 822 | kotlinconf-app | Apache License 2.0 |
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyMeasuredItemProvider.kt | RikkaW | 389,105,112 | true | {"Java": 49060640, "Kotlin": 36832495, "Python": 336507, "AIDL": 179831, "Shell": 150493, "C++": 38342, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343} | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.lazy
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.layout.SubcomposeMeasureScope
import androidx.compose.ui.unit.Constraints
/**
* Abstracts away the subcomposition from the measuring logic.
*/
internal class LazyMeasuredItemProvider(
constraints: Constraints,
isVertical: Boolean,
private val scope: SubcomposeMeasureScope,
private val itemsProvider: LazyListItemsProvider,
private val itemContentFactory: LazyListItemContentFactory,
private val measuredItemFactory: MeasuredItemFactory
) {
// the constraints we will measure child with. the main axis is not restricted
val childConstraints = Constraints(
maxWidth = if (isVertical) constraints.maxWidth else Constraints.Infinity,
maxHeight = if (!isVertical) constraints.maxHeight else Constraints.Infinity
)
/**
* Used to subcompose items of lazy lists. Composed placeables will be measured with the
* correct constraints and wrapped into [LazyMeasuredItem].
* This method can be called only once with each [index] per the measure pass.
*/
fun getAndMeasure(index: DataIndex): LazyMeasuredItem {
val key = itemsProvider.getKey(index.value)
val content = itemContentFactory.getContent(index.value, key)
val measurables = scope.subcompose(key, content)
val placeables = Array(measurables.size) {
measurables[it].measure(childConstraints)
}
return measuredItemFactory.createItem(index, key, placeables)
}
}
// This interface allows to avoid autoboxing on index param
internal fun interface MeasuredItemFactory {
fun createItem(index: DataIndex, key: Any, placeables: Array<Placeable>): LazyMeasuredItem
}
| 4 | Java | 1 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 2,387 | androidx | Apache License 2.0 |
app/src/main/java/com/orainjistudio/ugit/data/repository/GithubUserRepositoryImpl.kt | zharfanwafiq | 708,648,980 | false | {"Kotlin": 20729} | package com.orainjistudio.ugit.data.repository
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import com.orainjistudio.ugit.data.api.ApiService
import com.orainjistudio.ugit.data.response.detailuser.DetailUser
import com.orainjistudio.ugit.utils.AppExecutors
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class GithubUserRepositoryImpl private constructor(
private val apiService: ApiService,
private val appExecutors: AppExecutors
) : GithubUserRepository {
private val listGithubUser = MediatorLiveData<Result<ArrayList<DetailUser>>>()
override fun showGithubUserList(): LiveData<Result<ArrayList<DetailUser>>> {
listGithubUser.value = Result.Loading
apiService.getAllUsers()
.enqueue(object : Callback<ArrayList<DetailUser>>{
override fun onResponse(
call: Call<ArrayList<DetailUser>>,
response: Response<ArrayList<DetailUser>>
) {
val githubUser = response.body()
listGithubUser.postValue(Result.Success(githubUser as ArrayList<DetailUser>))
}
override fun onFailure(call: Call<ArrayList<DetailUser>>, t: Throwable) {
TODO("Not yet implemented")
}
})
return listGithubUser
}
companion object {
@Volatile
private var instance: GithubUserRepositoryImpl? = null
fun getInstance(
apiService: ApiService,
appExecutors: AppExecutors
): GithubUserRepositoryImpl =
instance ?: synchronized(this) {
instance ?: GithubUserRepositoryImpl(apiService, appExecutors)
}.also { instance = it }
}
} | 0 | Kotlin | 0 | 0 | f095541cd6a82b9a133fcd4b6f786925b1392257 | 1,803 | Ugit | Apache License 2.0 |
app/src/main/java/com/example/rally/ui/components/linechart/RallyLineChart.kt | matten-rd | 446,327,102 | false | {"Kotlin": 150018} | package com.example.rally.ui.components.linechart
import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.*
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.example.rally.ui.components.linechart.LineChartUtils.calculateDrawableArea
import com.example.rally.ui.components.linechart.LineChartUtils.calculateFillPath
import com.example.rally.ui.components.linechart.LineChartUtils.calculateLinePath
import com.example.rally.ui.components.linechart.LineChartUtils.calculateXAxisDrawableArea
import com.example.rally.ui.components.linechart.LineChartUtils.calculateXAxisLabelsDrawableArea
import com.example.rally.ui.components.linechart.LineChartUtils.calculateYAxisDrawableArea
import com.example.rally.ui.components.linechart.LineChartUtils.calculateYAxisLabelsDrawableArea
import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneOffset
data class LineChartData(
val timeStamp: Long,
val amount: Float
)
@Composable
internal fun RallyLineChart(
modifier: Modifier = Modifier,
color: Color,
lineChartData: List<LineChartData>,
lineDrawer: LineDrawer = SolidLineDrawer(color = color),
lineShader: LineShader = NoLineShader,
xAxisDrawer: XAxisDrawer = SimpleXAxisDrawer(
labelRatio = 4, axisLineColor = MaterialTheme.colors.onSurface.copy(0.1f)),
yAxisDrawer: YAxisDrawer = SimpleYAxisDrawer(
axisLineColor = MaterialTheme.colors.onSurface.copy(0.1f)
),
) {
if (lineChartData.size <= 1) {
return Box(modifier, contentAlignment = Alignment.Center) {
Text(text = "Inte tillräckligt med data ännu")
}
}
val transitionAnimation = remember(lineChartData) { Animatable(initialValue = 0f) }
LaunchedEffect(lineChartData) {
transitionAnimation.snapTo(0f)
transitionAnimation.animateTo(1f,
animationSpec = TweenSpec<Float>(durationMillis = 900, delay = 300, easing = LinearOutSlowInEasing)
)
}
val maxYCoordinate = lineChartData.maxOf { it.amount }
val minYCoordinate = lineChartData.minOf { it.amount }
// TODO: Implement axis labels etc
Canvas(modifier = modifier) {
drawIntoCanvas { canvas: Canvas ->
// Y - axis and labels
val yAxisDrawableArea = calculateYAxisDrawableArea(
xAxisLabelSize = xAxisDrawer.requiredHeight(this),
size = size
)
val yAxisLabelsDrawableArea = calculateYAxisLabelsDrawableArea(
yAxisDrawableArea = yAxisDrawableArea,
offset = 10f
)
// X - axis and labels
val xAxisDrawableArea = calculateXAxisDrawableArea(
yAxisWidth = yAxisDrawableArea.width,
labelHeight = xAxisDrawer.requiredHeight(this),
size = size
)
val xAxisLabelsDrawableArea = calculateXAxisLabelsDrawableArea(
xAxisDrawableArea = xAxisDrawableArea,
offset = 10f
)
// Chart
val chartDrawableArea = calculateDrawableArea(
xAxisDrawableArea = xAxisDrawableArea,
yAxisDrawableArea = yAxisDrawableArea,
size = size,
offset = 0f
)
// Draw the line(s)
lineDrawer.drawLine(
drawScope = this,
canvas = canvas,
linePath = calculateLinePath(
drawableArea = chartDrawableArea,
lineChartData = lineChartData,
transitionProgress = transitionAnimation.value
)
)
// Only add lineShader if it's not NoLineShader
if (lineShader !is NoLineShader) {
lineShader.fillLine(
drawScope = this,
canvas = canvas,
fillPath = calculateFillPath(
drawableArea = chartDrawableArea,
lineChartData = lineChartData,
transitionProgress = transitionAnimation.value
)
)
}
// Draw the X Axis line and labels.
xAxisDrawer.drawAxisLine(
drawScope = this,
drawableArea = xAxisDrawableArea,
canvas = canvas
)
// TODO: change the labels according to the TimeInterval selected
xAxisDrawer.drawAxisLabels(
drawScope = this,
canvas = canvas,
drawableArea = xAxisLabelsDrawableArea,
labels = lineChartData.map {
OffsetDateTime
.ofInstant(Instant.ofEpochMilli(it.timeStamp), ZoneOffset.UTC)
.month.name.take(3)
}
)
// Draw the Y Axis line and labels.
yAxisDrawer.drawAxisLine(
drawScope = this,
canvas = canvas,
drawableArea = yAxisDrawableArea
)
yAxisDrawer.drawAxisLabels(
drawScope = this,
canvas = canvas,
drawableArea = yAxisLabelsDrawableArea,
minValue = minYCoordinate,
maxValue = maxYCoordinate
)
}
}
}
/**
* LineDrawer is the Interface that handles drawing the line
*/
interface LineDrawer {
fun drawLine(
drawScope: DrawScope,
canvas: Canvas,
linePath: Path
)
}
data class SolidLineDrawer(
val thickness: Dp = 3.dp,
val color: Color = Color.Green
) : LineDrawer {
private val paint = Paint().apply {
this.color = [email protected]
this.style = PaintingStyle.Stroke
this.isAntiAlias = true
}
override fun drawLine(
drawScope: DrawScope,
canvas: Canvas,
linePath: Path
) {
val lineThickness = with(drawScope) {
thickness.toPx()
}
canvas.drawPath(
path = linePath,
paint = paint.apply {
strokeWidth = lineThickness
}
)
}
}
/**
* LineShaders are used to draw under the actual line
*/
interface LineShader {
fun fillLine(
drawScope: DrawScope,
canvas: Canvas,
fillPath: Path
)
}
object NoLineShader : LineShader {
override fun fillLine(drawScope: DrawScope, canvas: Canvas, fillPath: Path) {
// Do nothing
}
}
class SolidLineShader(val color: Color = Color.Blue) : LineShader {
override fun fillLine(drawScope: DrawScope, canvas: Canvas, fillPath: Path) {
drawScope.drawPath(
path = fillPath,
color = color
)
}
}
| 0 | Kotlin | 1 | 2 | cf6190566cf1ffa973de6a20720bd8f85fc3d25b | 7,326 | Rally-compose-sample | MIT License |
compiler/testData/diagnostics/tests/annotations/cycleAnnotationOnTypeParameterProperty.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
package myPack
@Target(AnnotationTarget.TYPE_PARAMETER)
annotation class Anno(val number: Int)
val <@Anno(<!ANNOTATION_ARGUMENT_MUST_BE_CONST!>42.prop<!>) T> T.prop get() = 22
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 195 | kotlin | Apache License 2.0 |
app/src/main/java/com/javieramado/centrodeidiomassanmartn/MainActivity.kt | KamiKeys | 276,455,611 | false | null | package com.javieramado.centrodeidiomassanmartn
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.Navigation
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import com.google.android.material.navigation.NavigationView
import com.google.firebase.iid.FirebaseInstanceId
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.google.firebase.remoteconfig.ktx.remoteConfigSettings
class MainActivity : AppCompatActivity() {
private var mAppBarConfiguration: AppBarConfiguration? = null
private val aboutFragment: AboutFragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
val navigationView = findViewById<NavigationView>(R.id.nav_view)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = AppBarConfiguration.Builder(R.id.nav_home, R.id.nav_horario, R.id.nav_normas, R.id.nav_covid, R.id.nav_contacto)
.setDrawerLayout(drawer)
.build()
val navController = Navigation.findNavController(this, R.id.nav_host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration!!)
NavigationUI.setupWithNavController(navigationView, navController)
// Remote Config
val ConfigSettings: FirebaseRemoteConfigSettings = remoteConfigSettings {
minimumFetchIntervalInSeconds = 10
}
val firebaseConfig: FirebaseRemoteConfig = Firebase.remoteConfig
firebaseConfig.setConfigSettingsAsync(ConfigSettings)
}
/*
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
*/
override fun onSupportNavigateUp(): Boolean {
val navController = Navigation.findNavController(this, R.id.nav_host_fragment)
return NavigationUI.navigateUp(navController, mAppBarConfiguration!!) || super.onSupportNavigateUp()
}
} | 0 | Kotlin | 0 | 0 | c1874efa30aee5d2f48fea0fedc6ffdcbb08ae68 | 2,741 | Centro-de-Idiomas-San-Martin | Creative Commons Attribution 4.0 International |
samples/simple/shared/src/commonMain/kotlin/com/hoc081098/solivagant/sample/simple/ui/home/notifications/nested_notifications/NestedNotificationsScreenRoute.kt | hoc081098 | 736,617,487 | false | {"Kotlin": 254428, "Shell": 371} | @file:Suppress("PackageNaming")
package com.hoc081098.solivagant.sample.simple.ui.home.notifications.nested_notifications
import androidx.compose.runtime.Immutable
import com.hoc081098.kmp.viewmodel.parcelable.Parcelize
import com.hoc081098.solivagant.navigation.NavRoute
import com.hoc081098.solivagant.navigation.ScreenDestination
import kotlin.jvm.JvmField
@Immutable
@Parcelize
data object NestedNotificationsScreenRoute : NavRoute
@JvmField
val NestedNotificationsScreenDestination =
ScreenDestination<NestedNotificationsScreenRoute> { NestedNotificationsScreen() }
| 7 | Kotlin | 3 | 8 | a4092b569d2ed984b56d95736e40a7cdd5ed1590 | 577 | solivagant | Apache License 2.0 |
bootstrap-icons-compose/src/main/java/com/wiryadev/bootstrapiconscompose/bootstrapicons/filled/PersonBadge.kt | wiryadev | 380,639,096 | false | {"Kotlin": 4825599} | package com.wiryadev.bootstrapiconscompose.bootstrapicons.filled
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.wiryadev.bootstrapiconscompose.bootstrapicons.FilledGroup
public val FilledGroup.PersonBadge: ImageVector
get() {
if (_personBadge != null) {
return _personBadge!!
}
_personBadge = Builder(name = "PersonBadge", defaultWidth = 16.0.dp, defaultHeight =
16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(2.0f, 2.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f)
horizontalLineToRelative(8.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f)
verticalLineToRelative(12.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, 2.0f)
lineTo(4.0f, 16.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f)
lineTo(2.0f, 2.0f)
close()
moveTo(6.5f, 2.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, 1.0f)
horizontalLineToRelative(3.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.0f, -1.0f)
horizontalLineToRelative(-3.0f)
close()
moveTo(8.0f, 11.0f)
arcToRelative(3.0f, 3.0f, 0.0f, true, false, 0.0f, -6.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, false, 0.0f, 6.0f)
close()
moveTo(13.0f, 13.755f)
curveTo(12.146f, 12.825f, 10.623f, 12.0f, 8.0f, 12.0f)
reflectiveCurveToRelative(-4.146f, 0.826f, -5.0f, 1.755f)
lineTo(3.0f, 14.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, 1.0f)
horizontalLineToRelative(8.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.0f, -1.0f)
verticalLineToRelative(-0.245f)
close()
}
}
.build()
return _personBadge!!
}
private var _personBadge: ImageVector? = null
| 0 | Kotlin | 0 | 2 | 1c199d953dc96b261aab16ac230dc7f01fb14a53 | 2,802 | bootstrap-icons-compose | MIT License |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/plugin/mpp/MetadataDependencyTransformationTask.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle.plugin.mpp
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.artifacts.component.ComponentIdentifier
import org.gradle.api.artifacts.component.ModuleComponentIdentifier
import org.gradle.api.artifacts.component.ProjectComponentIdentifier
import org.gradle.api.file.FileCollection
import org.gradle.api.file.ProjectLayout
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.tasks.*
import org.gradle.work.DisableCachingByDefault
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.targets.metadata.dependsOnClosureWithInterCompilationDependencies
import org.jetbrains.kotlin.gradle.tasks.dependsOn
import org.jetbrains.kotlin.gradle.tasks.locateOrRegisterTask
import org.jetbrains.kotlin.gradle.tasks.locateTask
import org.jetbrains.kotlin.gradle.utils.*
import java.io.File
import javax.inject.Inject
/* Keep typealias for source compatibility */
@Suppress("unused")
@Deprecated("Task was renamed to MetadataDependencyTransformationTask", replaceWith = ReplaceWith("MetadataDependencyTransformationTask"))
typealias TransformKotlinGranularMetadata = MetadataDependencyTransformationTask
internal const val TRANSFORM_ALL_SOURCESETS_DEPENDENCIES_METADATA = "transformDependenciesMetadata"
private fun transformGranularMetadataTaskName(sourceSetName: String) =
lowerCamelCaseName("transform", sourceSetName, "DependenciesMetadata")
internal fun Project.locateOrRegisterMetadataDependencyTransformationTask(
sourceSet: KotlinSourceSet
): TaskProvider<MetadataDependencyTransformationTask> {
val transformationTask = project.locateOrRegisterTask<MetadataDependencyTransformationTask>(
transformGranularMetadataTaskName(sourceSet.name),
listOf(sourceSet)
) {
description =
"Generates serialized dependencies metadata for compilation '${sourceSet.name}' (for tooling)"
}
project.locateOrRegisterTask<Task>(TRANSFORM_ALL_SOURCESETS_DEPENDENCIES_METADATA).dependsOn(transformationTask)
return transformationTask
}
@DisableCachingByDefault(because = "Metadata Dependency Transformation Task doesn't benefit from caching as it doesn't have heavy load")
open class MetadataDependencyTransformationTask
@Inject constructor(
kotlinSourceSet: KotlinSourceSet,
private val objectFactory: ObjectFactory,
private val projectLayout: ProjectLayout
) : DefaultTask() {
//region Task Configuration State & Inputs
private val transformationParameters = GranularMetadataTransformation.Params(project, kotlinSourceSet)
@Suppress("unused") // task inputs for up-to-date checks
@get:Nested
internal val taskInputs = MetadataDependencyTransformationTaskInputs(project, kotlinSourceSet)
@get:OutputDirectory
internal val outputsDir: File get() = projectLayout.kotlinTransformedMetadataLibraryDirectoryForBuild(transformationParameters.sourceSetName)
@Transient // Only needed for configuring task inputs
private val parentTransformationTasksLazy: Lazy<List<TaskProvider<MetadataDependencyTransformationTask>>>? = lazy {
dependsOnClosureWithInterCompilationDependencies(kotlinSourceSet).mapNotNull {
project
.tasks
.locateTask(transformGranularMetadataTaskName(it.name))
}
}
private val parentTransformationTasks: List<TaskProvider<MetadataDependencyTransformationTask>>
get() = parentTransformationTasksLazy?.value
?: error(
"`parentTransformationTasks` is null. " +
"Probably it is accessed it during Task Execution with state loaded from Configuration Cache"
)
@get:OutputFile
protected val transformedLibrariesIndexFile: RegularFileProperty = objectFactory
.fileProperty()
.apply { set(outputsDir.resolve("${kotlinSourceSet.name}.libraries")) }
@get:OutputFile
protected val visibleSourceSetsFile: RegularFileProperty = objectFactory
.fileProperty()
.apply { set(outputsDir.resolve("${kotlinSourceSet.name}.visibleSourceSets")) }
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFiles
protected val parentVisibleSourceSetFiles: FileCollection = project.filesProvider {
parentTransformationTasks.map { taskProvider ->
taskProvider.flatMap { task ->
task.visibleSourceSetsFile.map { it.asFile }
}
}
}
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFiles
protected val parentTransformedLibraries: FileCollection = project.filesProvider {
parentTransformationTasks.map { taskProvider ->
taskProvider.map { task -> task.ownTransformedLibraries }
}
}
//endregion Task Configuration State & Inputs
@TaskAction
fun transformMetadata() {
val transformation = GranularMetadataTransformation(
params = transformationParameters,
parentSourceSetVisibilityProvider = ParentSourceSetVisibilityProvider { identifier: ComponentIdentifier ->
val serializableKey = identifier.serializableUniqueKey
parentVisibleSourceSetFiles.flatMap { visibleSourceSetsFile ->
readVisibleSourceSetsFile(visibleSourceSetsFile)[serializableKey].orEmpty()
}.toSet()
}
)
if (outputsDir.isDirectory) {
outputsDir.deleteRecursively()
}
outputsDir.mkdirs()
val metadataDependencyResolutions = transformation.metadataDependencyResolutions
val transformedLibraries = metadataDependencyResolutions
.flatMap { resolution ->
when (resolution) {
is MetadataDependencyResolution.ChooseVisibleSourceSets ->
objectFactory.transformMetadataLibrariesForBuild(resolution, outputsDir, true)
is MetadataDependencyResolution.KeepOriginalDependency ->
transformationParameters.resolvedMetadataConfiguration.getArtifacts(resolution.dependency).map { it.file }
is MetadataDependencyResolution.Exclude -> emptyList()
}
}
writeTransformedLibraries(transformedLibraries)
writeVisibleSourceSets(transformation.visibleSourceSetsByComponentId)
}
private fun writeTransformedLibraries(files: List<File>) {
KotlinMetadataLibrariesIndexFile(transformedLibrariesIndexFile.get().asFile).write(files)
}
private fun writeVisibleSourceSets(visibleSourceSetsByComponentId: Map<ComponentIdentifier, Set<String>>) {
val content = visibleSourceSetsByComponentId.entries.joinToString("\n") { (id, visibleSourceSets) ->
"${id.serializableUniqueKey} => ${visibleSourceSets.joinToString(",")}"
}
visibleSourceSetsFile.get().asFile.writeText(content)
}
private fun readVisibleSourceSetsFile(file: File): Map<String, Set<String>> = file
.readLines()
.associate { string ->
val (id, visibleSourceSetsString) = string.split(" => ")
id to visibleSourceSetsString.split(",").toSet()
}
@get:Internal // Warning! ownTransformedLibraries is available only after Task Execution
internal val ownTransformedLibraries: FileCollection = project.filesProvider {
transformedLibrariesIndexFile.map { regularFile ->
KotlinMetadataLibrariesIndexFile(regularFile.asFile).read()
}
}
@get:Internal // Warning! allTransformedLibraries is available only after Task Execution
val allTransformedLibraries: FileCollection get() = ownTransformedLibraries + parentTransformedLibraries
}
private typealias SerializableComponentIdentifierKey = String
/**
* This unique key can be used to lookup various info for related Resolved Dependency
* that gets serialized
*/
private val ComponentIdentifier.serializableUniqueKey
get(): SerializableComponentIdentifierKey = when (this) {
is ProjectComponentIdentifier -> "project ${build.buildPathCompat}$projectPath"
is ModuleComponentIdentifier -> "module $group:$module:$version"
else -> error("Unexpected Component Identifier: '$this' of type ${this.javaClass}")
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 8,554 | kotlin | Apache License 2.0 |
src/main/kotlin/vista/ventanas/VentanaMostrarObjetivos.kt | joaqogomez | 646,572,458 | false | null | package vista.ventanas
import javafx.scene.Group
class VentanaMostrarObjetivos(menuObjetivos: VentanaMenu) : Group() {
init {
agregarMenu()
children.add(menuObjetivos)
}
private fun agregarMenu() {
val menu = VentanaPrincipal()
children.add(menu)
}
} | 0 | Kotlin | 0 | 0 | 3af2d91168053940f8e9e52994da958a782bb9e8 | 301 | 75.31-TDL | MIT License |
app/src/main/java/com/caiheweather/android/logic/model/DailyResponse.kt | cathuub | 403,613,564 | false | {"Kotlin": 55359} | package com.caiheweather.android.logic.model
//逐天天气预报类,7天版
class DailyResponse(val code: String, val daily:List<Daily>) {
class Daily(
val fxDate:String,
val sunrise:String,
val sunset:String,
val moonrise:String,
val moonset:String,
val moonPhase:String,
val tempMax:String,
val tempMin:String,
val iconDay:String,
val textDay:String,
val iconNight:String,
val textNight:String,
val humidity:String,
val precip:String,
val pressure:String,
val vis:String,
val cloud:String,
val uvIndex:String//紫外线度
)
} | 0 | Kotlin | 0 | 0 | 9a7b53bea585602c451fc5ab40ddd4b419d30fc0 | 844 | caiheweather | Apache License 2.0 |
plugins/fir-plugin-prototype/testData/firLoadK2Compiled/annotationsGeneratedInBackend.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // PLATFORM_DEPENDANT_METADATA
// DUMP_KT_IR
package test
import org.jetbrains.kotlin.fir.plugin.AddAnnotations
@AddAnnotations
class Some(val x: Int) {
fun foo() {}
// some comment
class Derived
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 213 | kotlin | Apache License 2.0 |
compiler/tests-common-new/tests/org/jetbrains/kotlin/test/backend/ir/IrBackendInput.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.test.backend.ir
import org.jetbrains.kotlin.KtSourceFile
import org.jetbrains.kotlin.backend.common.actualizer.IrActualizedResult
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.diagnostics.impl.BaseDiagnosticsCollector
import org.jetbrains.kotlin.fir.backend.FirMangler
import org.jetbrains.kotlin.ir.backend.js.KotlinFileSerializedData
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.util.KotlinMangler
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.test.model.BackendKind
import org.jetbrains.kotlin.test.model.BackendKinds
import org.jetbrains.kotlin.test.model.ResultingArtifact
// IR backend (JVM, JS, Native, Wasm)
sealed class IrBackendInput : ResultingArtifact.BackendInput<IrBackendInput>() {
override val kind: BackendKind<IrBackendInput>
get() = BackendKinds.IrBackend
abstract val irModuleFragment: IrModuleFragment
/**
* Here plugin context can be used as a service for inspecting resulting IR module
*/
abstract val irPluginContext: IrPluginContext
/**
* The mangler instance that was used to build declaration signatures from (possibly deserialized) K1 descriptors for this backend,
* or `null` if this artifact was compiled using the K2 frontend.
*
* This instance can be used to verify signatures in tests.
*
* @see org.jetbrains.kotlin.backend.common.serialization.mangle.descriptor.DescriptorMangleComputer
* @see org.jetbrains.kotlin.ir.util.IdSignature
*/
abstract val descriptorMangler: KotlinMangler.DescriptorMangler?
/**
* The mangler instance that was used to build declaration signatures from IR declarations for this backend.
*
* @see org.jetbrains.kotlin.backend.common.serialization.mangle.ir.IrMangleComputer
* @see org.jetbrains.kotlin.ir.util.IdSignature
*/
abstract val irMangler: KotlinMangler.IrMangler
/**
* The mangler instance that was used to build declaration signatures from K2 (FIR) declarations for this backend, or `null` if
* this artifact was compiled using the classic frontend.
*
* This instance can be used to verify signatures in tests.
*
* @see org.jetbrains.kotlin.fir.backend.FirMangleComputer
* @see org.jetbrains.kotlin.ir.util.IdSignature
*/
abstract val firMangler: FirMangler?
abstract val diagnosticReporter: BaseDiagnosticsCollector
class JsIrBackendInput(
override val irModuleFragment: IrModuleFragment,
override val irPluginContext: IrPluginContext,
val sourceFiles: List<KtSourceFile>,
val icData: List<KotlinFileSerializedData>,
override val diagnosticReporter: BaseDiagnosticsCollector,
val hasErrors: Boolean,
override val descriptorMangler: KotlinMangler.DescriptorMangler?,
override val irMangler: KotlinMangler.IrMangler,
override val firMangler: FirMangler?,
val serializeSingleFile: (KtSourceFile) -> ProtoBuf.PackageFragment,
) : IrBackendInput()
data class JsIrDeserializedFromKlibBackendInput(
override val irModuleFragment: IrModuleFragment,
override val irPluginContext: IrPluginContext,
override val diagnosticReporter: BaseDiagnosticsCollector,
override val descriptorMangler: KotlinMangler.DescriptorMangler?,
override val irMangler: KotlinMangler.IrMangler,
override val firMangler: FirMangler?,
) : IrBackendInput() {
override val kind: BackendKind<IrBackendInput>
get() = BackendKinds.DeserializedIrBackend
}
class WasmBackendInput(
override val irModuleFragment: IrModuleFragment,
override val irPluginContext: IrPluginContext,
val sourceFiles: List<KtSourceFile>,
val icData: List<KotlinFileSerializedData>,
override val diagnosticReporter: BaseDiagnosticsCollector,
val hasErrors: Boolean,
override val descriptorMangler: KotlinMangler.DescriptorMangler?,
override val irMangler: KotlinMangler.IrMangler,
override val firMangler: FirMangler?,
val serializeSingleFile: (KtSourceFile) -> ProtoBuf.PackageFragment,
) : IrBackendInput()
class JvmIrBackendInput(
val state: GenerationState,
val codegenFactory: JvmIrCodegenFactory,
val backendInput: JvmIrCodegenFactory.JvmIrBackendInput,
val sourceFiles: List<KtSourceFile>,
override val descriptorMangler: KotlinMangler.DescriptorMangler?,
override val irMangler: KotlinMangler.IrMangler,
override val firMangler: FirMangler?,
) : IrBackendInput() {
override val irModuleFragment: IrModuleFragment
get() = backendInput.irModuleFragment
override val irPluginContext: IrPluginContext
get() = backendInput.pluginContext!!
override val diagnosticReporter: BaseDiagnosticsCollector
get() = state.diagnosticReporter as BaseDiagnosticsCollector
}
// Actually, class won't be used as a real input for the Native backend during blackbox testing, since such testing is done via a different engine.
// In irText tests, this class is used only to hold Native-specific FIR2IR output (module fragments) to render and dump IR.
// So, other fields are actually not needed: source files, icData, error flag, serialization lambda, etc...
class NativeBackendInput(
override val irModuleFragment: IrModuleFragment,
override val irPluginContext: IrPluginContext,
override val diagnosticReporter: BaseDiagnosticsCollector,
override val descriptorMangler: KotlinMangler.DescriptorMangler?,
override val irMangler: KotlinMangler.IrMangler,
override val firMangler: FirMangler?,
) : IrBackendInput()
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 6,225 | kotlin | Apache License 2.0 |
lib/spring-hibernate/src/main/kotlin/at/sigmoid/transaction/retry/util/TransactionUtil.kt | strassl | 350,731,832 | false | null | package at.sigmoid.transaction.retry.util
import org.aspectj.lang.reflect.MethodSignature
import org.springframework.core.annotation.AnnotatedElementUtils
import org.springframework.transaction.annotation.Transactional
fun getActiveTransactionalAnnotation(signature: MethodSignature): Transactional? {
val methodTransactionAnnotation = AnnotatedElementUtils.findMergedAnnotation(signature.method, Transactional::class.java)
val classTransactionalAnnotation = AnnotatedElementUtils.findMergedAnnotation(signature.declaringType, Transactional::class.java)
val transactionAnnotation = (methodTransactionAnnotation ?: classTransactionalAnnotation)
return transactionAnnotation
} | 0 | Kotlin | 0 | 0 | 01de18cdabebaecfedc6019531467d0f87ac9e95 | 694 | transaction-retry | MIT License |
src/test/kotlin/uk/gov/justice/hmpps/offendersearch/controllers/OffenderSearchAPIIntegrationTest.kt | uk-gov-mirror | 356,783,435 | true | {"Kotlin": 361013, "Mustache": 2961, "Dockerfile": 997, "Shell": 285} | package uk.gov.justice.hmpps.offendersearch.controllers
import com.fasterxml.jackson.databind.ObjectMapper
import io.restassured.RestAssured
import io.restassured.RestAssured.given
import io.restassured.config.ObjectMapperConfig
import io.restassured.config.RestAssuredConfig
import org.assertj.core.api.Assertions.assertThat
import org.elasticsearch.client.RestHighLevelClient
import org.hamcrest.CoreMatchers
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.MediaType
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestContext
import org.springframework.test.context.TestExecutionListeners
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import org.springframework.test.context.support.AbstractTestExecutionListener
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener
import uk.gov.justice.hmpps.offendersearch.dto.OffenderDetail
import uk.gov.justice.hmpps.offendersearch.util.JwtAuthenticationHelper
import uk.gov.justice.hmpps.offendersearch.util.LocalStackHelper
import java.lang.reflect.Type
import java.util.Objects
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles(profiles = ["test", "localstack"])
@RunWith(SpringJUnit4ClassRunner::class)
@TestExecutionListeners(listeners = [DependencyInjectionTestExecutionListener::class, OffenderSearchAPIIntegrationTest::class])
@ContextConfiguration
internal class OffenderSearchAPIIntegrationTest : AbstractTestExecutionListener() {
@Autowired
private lateinit var jwtAuthenticationHelper: JwtAuthenticationHelper
override fun beforeTestClass(testContext: TestContext) {
val objectMapper = testContext.applicationContext.getBean(ObjectMapper::class.java)
val esClient = testContext.applicationContext.getBean(RestHighLevelClient::class.java)
LocalStackHelper(esClient).loadData()
RestAssured.port = Objects.requireNonNull(testContext.applicationContext.environment.getProperty("local.server.port"))!!.toInt()
RestAssured.config = RestAssuredConfig.config().objectMapperConfig(
ObjectMapperConfig().jackson2ObjectMapperFactory { _: Type?, _: String? -> objectMapper }
)
}
@Test
fun `can access info without valid token`() {
given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.`when`()["/info"]
.then()
.statusCode(200)
}
@Test
fun `can access ping without valid token`() {
given()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.`when`()["/health/ping"]
.then()
.statusCode(200)
}
@Test
fun `not allowed to do a search without COMMUNITY role`() {
given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_BINGO"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"surname\":\"smith\"}")
.`when`()["/search"]
.then()
.statusCode(403)
}
@Test
fun surnameSearch() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"surname\":\"smith\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(2)
assertThat(results).extracting("firstName").containsExactlyInAnyOrder("John", "Jane")
}
@Test
fun `can POST or GET a search request`() {
assertThat(
given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"surname\": \"smith\"}")
.post("/search")
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
).hasSize(2)
assertThat(
given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"surname\": \"smith\"}")
.get("/search")
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
).hasSize(2)
}
@Test
fun shouldFilterOutSoftDeletedRecords() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"surname\":\"Jones\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(0)
}
@Test
fun nomsNumberSearch() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"nomsNumber\":\"G8020GG\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(1)
assertThat(results).extracting("firstName").containsExactly("John")
}
@Test
fun prisonNumberSearch() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"nomsNumber\":\"G8020GG\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(1)
assertThat(results).extracting("firstName").containsExactly("John")
}
@Test
fun dateOfBirthSearch() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"dateOfBirth\": \"1978-01-06\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(1)
assertThat(results).extracting("firstName").containsExactly("John")
}
@Test
fun pncNumberShortFormatSearch() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"pncNumber\":\"18/123456X\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(1)
assertThat(results).extracting("firstName").containsExactly("John")
}
@Test
fun pncNumberLongFormatSearch() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"pncNumber\":\"2018/0123456X\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(1)
assertThat(results).extracting("firstName").containsExactly("John")
}
@Test
fun croNumberLongFormatSearch() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"croNumber\":\"SF80/777108T\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(1)
assertThat(results).extracting("firstName").containsExactly("Jane")
}
@Test
fun croNumberLongFormatSearchAndSurname() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"croNumber\":\"SF80/777108T\",\"surname\":\"SMITH\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(1)
assertThat(results).extracting("firstName").containsExactly("Jane")
}
@Test
fun pncNumberLongFormatSearchAndSurname() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"pncNumber\":\"2018/0123456X\", \"surname\":\"SMITH\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(1)
assertThat(results).extracting("firstName").containsExactly("John")
}
@Test
fun pncNumberLongFormatSearchAndWrongSurname() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"pncNumber\":\"2018/0123456X\", \"surname\":\"Denton\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(0)
}
@Test
fun allParameters() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"surname\": \"smith\",\"firstName\": \"John\",\"crn\": \"X00001\",\"croNumber\": \"SF80/655108T\", \"nomsNumber\": \"G8020GG\",\"pncNumber\": \"2018/0123456X\", \"dateOfBirth\": \"1978-01-06\"}\n")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(1)
assertThat(results).extracting("firstName").containsExactly("John")
}
@Test
fun blanksShouldBeIgnored() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"surname\": \" \",\"firstName\": \" \",\"crn\": \" \",\"croNumber\": \" \", \"nomsNumber\": \" \",\"pncNumber\": \" \", \"dateOfBirth\": \"1978-01-06\"}\n")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.body()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(1)
assertThat(results).extracting("firstName").containsExactly("John")
}
@Test
fun noSearchParameters_badRequest() {
given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{}")
.`when`()["/search"]
.then()
.statusCode(400)
.body("developerMessage", CoreMatchers.containsString("Invalid search - please provide at least 1 search parameter"))
}
@Test
fun noResults() {
val results = given()
.auth()
.oauth2(jwtAuthenticationHelper.createJwt("ROLE_COMMUNITY"))
.contentType(MediaType.APPLICATION_JSON_VALUE)
.body("{\"surname\":\"potter\"}")
.`when`()["/search"]
.then()
.statusCode(200)
.extract()
.`as`(Array<OffenderDetail>::class.java)
assertThat(results).hasSize(0)
}
}
| 0 | Kotlin | 0 | 0 | 699b9bd2462a38292343654377339b2a863ddf26 | 11,534 | probation-offender-search | Apache License 2.0 |
compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirReservedUnderscoreDeclarationChecker.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "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.fir.analysis.checkers.declaration
import org.jetbrains.kotlin.KtFakeSourceElementKind
import org.jetbrains.kotlin.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.diagnostics.reportOn
import org.jetbrains.kotlin.fir.analysis.checkers.SourceNavigator
import org.jetbrains.kotlin.fir.analysis.checkers.checkTypeRefForUnderscore
import org.jetbrains.kotlin.fir.analysis.checkers.checkUnderscoreDiagnostics
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.checkers.isUnderscore
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.isCatchParameter
import org.jetbrains.kotlin.name.SpecialNames
object FirReservedUnderscoreDeclarationChecker : FirBasicDeclarationChecker() {
override fun check(declaration: FirDeclaration, context: CheckerContext, reporter: DiagnosticReporter) {
if (
declaration is FirRegularClass ||
declaration is FirProperty && declaration.isCatchParameter != true ||
declaration is FirTypeAlias
) {
reportIfUnderscore(declaration, context, reporter)
} else if (declaration is FirTypeParameter) {
reportIfUnderscore(declaration, context, reporter)
declaration.bounds.forEach {
checkTypeRefForUnderscore(it, context, reporter)
}
} else if (declaration is FirFunction) {
if (declaration is FirSimpleFunction) {
reportIfUnderscore(declaration, context, reporter)
}
val isSingleUnderscoreAllowed = declaration is FirAnonymousFunction || declaration is FirPropertyAccessor
for (parameter in declaration.valueParameters) {
reportIfUnderscore(
parameter,
context,
reporter,
isSingleUnderscoreAllowed = isSingleUnderscoreAllowed
)
}
} else if (declaration is FirFile) {
for (import in declaration.imports) {
checkUnderscoreDiagnostics(import.aliasSource, context, reporter, isExpression = false)
}
}
}
private fun reportIfUnderscore(
declaration: FirDeclaration,
context: CheckerContext,
reporter: DiagnosticReporter,
isSingleUnderscoreAllowed: Boolean = false
) {
val declarationSource = declaration.source
if (declarationSource != null &&
declarationSource.kind !is KtFakeSourceElementKind &&
(declaration as? FirProperty)?.name != SpecialNames.UNDERSCORE_FOR_UNUSED_VAR
) {
with(SourceNavigator.forElement(declaration)) {
val rawName = declaration.getRawName()
if (rawName?.isUnderscore == true && !(isSingleUnderscoreAllowed && rawName == "_")) {
reporter.reportOn(
declarationSource,
FirErrors.UNDERSCORE_IS_RESERVED,
context
)
}
}
}
when (declaration) {
is FirValueParameter -> checkTypeRefForUnderscore(declaration.returnTypeRef, context, reporter)
is FirFunction -> {
checkTypeRefForUnderscore(declaration.returnTypeRef, context, reporter)
checkTypeRefForUnderscore(declaration.receiverParameter?.typeRef, context, reporter)
}
else -> {}
}
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 3,831 | kotlin | Apache License 2.0 |
model/src/main/kotlin/org/digma/intellij/plugin/model/rest/event/LatestCodeObjectEventsRequest.kt | digma-ai | 472,408,329 | false | {"Kotlin": 1315823, "Java": 697153, "C#": 114216, "FreeMarker": 13319, "HTML": 13271, "Shell": 6494} | package org.digma.intellij.plugin.model.rest.event
data class LatestCodeObjectEventsRequest(val environments: List<String>,val fromDate: String)
| 390 | Kotlin | 6 | 17 | 55a318082a8f8b8d3a1de7d50e83af12d1ef1657 | 146 | digma-intellij-plugin | MIT License |
step2/src/main/java/com/google/codelab/camera2/CameraActivity.kt | android | 486,507,367 | false | {"Kotlin": 24430} | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.codelab.camera2
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.hardware.display.DisplayManager
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.util.Log
import android.view.Display
import android.view.Surface
import android.view.TextureView
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
import com.google.codelab.camera2.databinding.ActivityCameraBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
const val TAG = "CAMERA_ACTIVITY"
const val CAMERA_PERMISSION_REQUEST_CODE = 1992
open class CameraActivity : AppCompatActivity() {
/** Main Looper*/
private val mainLooperHandler = Handler(Looper.getMainLooper())
/** [HandlerThread] where all camera operations run */
private val cameraThread = HandlerThread("MyCameraThread").apply { start() }
/** [Handler] corresponding to [cameraThread] */
private val cameraHandler = Handler(cameraThread.looper)
/** hardcoded back camera*/
private val cameraID = "0"
/** Detects, characterizes, and connects to a CameraDevice (used for all camera operations) */
private val cameraManager: CameraManager by lazy {
applicationContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager
}
/** The [CameraDevice] that will be opened in this Activity */
private var cameraDevice: CameraDevice? = null
/** [Surface] target of the CameraCaptureRequest*/
private var surface: Surface? = null
/** Where the camera preview is displayed */
private lateinit var textureView: TextureView
private lateinit var binding: ActivityCameraBinding
/** [DisplayManager] to listen to display changes */
private val displayManager: DisplayManager by lazy {
applicationContext.getSystemService(DISPLAY_SERVICE) as DisplayManager
}
/** Keep track of display rotations*/
private var displayRotation = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCameraBinding.inflate(layoutInflater)
setContentView(binding.root)
textureView = binding.textureView
val windowParams: WindowManager.LayoutParams = window.attributes
windowParams.rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_JUMPCUT
window.attributes = windowParams
}
override fun onStart() {
super.onStart()
openCameraWithPermissionCheck()
}
override fun onDestroy() {
super.onDestroy()
release()
cameraThread.quitSafely()
}
private fun openCameraWithPermissionCheck() {
if (ActivityCompat.checkSelfPermission(
this, Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
) {
openCamera()
} else {
ActivityCompat.requestPermissions(
this, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE
)
}
}
@SuppressLint("MissingPermission")
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
if (grantResults.getOrNull(0) == PackageManager.PERMISSION_GRANTED) {
openCamera()
} else {
finish()
}
}
}
@SuppressLint("MissingPermission")
private fun openCamera() = lifecycleScope.launch(Dispatchers.Main) {
cameraManager.openCamera(cameraID, cameraStateCallback, cameraHandler)
}
/**
* Before creating the [CameraCaptureSession] we apply a transformation to the TextureView to
* avoid distortion in the preview
*/
private fun createCaptureSession() {
if (cameraDevice == null || !textureView.isAvailable) return
val transformedTexture = CameraUtils.buildTargetTexture(
textureView, cameraManager.getCameraCharacteristics(cameraID),
displayManager.getDisplay(Display.DEFAULT_DISPLAY).rotation
)
this.surface = Surface(transformedTexture)
try {
cameraDevice?.createCaptureSession(
listOf(surface), sessionStateCallback, cameraHandler
)
} catch (t: Throwable) {
Log.e(TAG, "Failed to create session.", t)
}
}
private fun release() {
try {
surface?.release()
cameraDevice?.close()
} catch (t: Throwable) {
Log.e(TAG, "Failed to release resources.", t)
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
displayManager.registerDisplayListener(displayListener, mainLooperHandler)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
displayManager.unregisterDisplayListener(displayListener)
}
private val displayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) {}
override fun onDisplayRemoved(displayId: Int) {}
override fun onDisplayChanged(displayId: Int) {
val difference = displayManager.getDisplay(displayId).rotation - displayRotation
displayRotation = displayManager.getDisplay(displayId).rotation
if (difference == 2 || difference == -2) {
createCaptureSession()
}
}
}
private val cameraStateCallback = object : CameraDevice.StateCallback() {
override fun onOpened(camera: CameraDevice) {
cameraDevice = camera
try {
mainLooperHandler.post {
if (textureView.isAvailable) {
createCaptureSession()
}
textureView.surfaceTextureListener = surfaceTextureListener
}
} catch (t: Throwable) {
release()
Log.e(TAG, "Failed to initialize camera.", t)
}
}
override fun onDisconnected(camera: CameraDevice) {
cameraDevice = camera
release()
}
override fun onError(camera: CameraDevice, error: Int) {
cameraDevice = camera
Log.e(TAG, "on Error: $error")
}
}
private val sessionStateCallback = object : CameraCaptureSession.StateCallback() {
override fun onConfigured(cameraCaptureSession: CameraCaptureSession) {
try {
val captureRequest = cameraDevice?.createCaptureRequest(
CameraDevice.TEMPLATE_PREVIEW
)
captureRequest?.addTarget(surface!!)
cameraCaptureSession.setRepeatingRequest(
captureRequest?.build()!!, null, cameraHandler
)
} catch (t: Throwable) {
Log.e(TAG, "Failed to open camera preview.", t)
}
}
override fun onConfigureFailed(cameraCaptureSession: CameraCaptureSession) {
Log.e(TAG, "Failed to configure camera.")
}
}
/**
* Every time the size of the TextureSize changes,
* we calculate the scale and create a new session
*/
private val surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
createCaptureSession()
}
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
createCaptureSession()
}
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean = false
}
}
| 0 | Kotlin | 2 | 9 | b61062b27cef571a2aae13f6d9e667e2853d9165 | 8,994 | codelab-android-camera2-preview | Apache License 2.0 |
application/Sample-Coroutines/app/src/main/java/com/demo/code/usecases/coroutines/usecase17/UiState.kt | devrath | 339,281,472 | false | {"Kotlin": 468482, "Java": 3273} | package com.demo.code.usecases.coroutines.usecase17
sealed class UiState {
object Loading : UiState()
data class Success(val thread: String, val duration: Long) : UiState()
data class Error(val message: String) : UiState()
} | 0 | Kotlin | 2 | 15 | 788c8472244eaa76c0b013a9686749541885876f | 237 | KotlinAlchemy | Apache License 2.0 |
app/src/main/kotlin/com/thekhaeng/materialstyletemplate/widgets/PreCachingLayoutManager.kt | nontravis | 87,284,931 | false | {"Kotlin": 105356, "Java": 1197} | package com.thekhaeng.materialstyletemplate.widgets
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
/**
* Created by「 <NAME> 」on 12 May 2018 :)
*/
class PreCachingLayoutManager : LinearLayoutManager {
companion object {
const val DEFAULT_EXTRA_LAYOUT_SPACE = 600
}
private var extraLayoutSpace = DEFAULT_EXTRA_LAYOUT_SPACE
private var context: Context? = null
constructor(context: Context) : super(context) {
this.context = context
}
constructor(context: Context, extraLayoutSpace: Int) : super(context) {
this.context = context
this.extraLayoutSpace = extraLayoutSpace
}
constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout) {
this.context = context
}
fun setExtraLayoutSpace(extraLayoutSpace: Int) {
this.extraLayoutSpace = extraLayoutSpace
}
override
fun getExtraLayoutSpace(state: RecyclerView.State): Int {
return if (extraLayoutSpace > 0) extraLayoutSpace else DEFAULT_EXTRA_LAYOUT_SPACE
}
}
| 1 | Kotlin | 36 | 174 | 804e1cd36159a778a27ad4c6162b12d725c99b93 | 1,185 | material-design-guideline | Apache License 2.0 |