content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.coroutinesexamples.Coroutines
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.coroutinesexamples.R
import com.example.coroutinesexamples.databinding.ActivityCoroutineBuilderBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
class CoroutineBuilderActivity : AppCompatActivity() {
private lateinit var binding : ActivityCoroutineBuilderBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setContentView(R.layout.activity_coroutine_builder)
binding= ActivityCoroutineBuilderBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.launchButton.setOnClickListener {
startCoroutineUsingLaunch()
}
binding.asyncButton.setOnClickListener {
CoroutineScope(Main).launch { startCoroutineUsingAsync() }
}
binding.runBlockingButton.setOnClickListener { startCoroutineUsingRunBlocking() }
}
private fun startCoroutineUsingLaunch() {
val job: Job = CoroutineScope(Dispatchers.IO).launch {
setText("Launch ${getStringResult()}")
}
}
private suspend fun startCoroutineUsingAsync() {
val deferred: Deferred<String> = CoroutineScope(Dispatchers.IO).async {
return@async getStringResult()
}
setText("Await ${deferred.await()}")
}
private fun startCoroutineUsingRunBlocking() {
val result = runBlocking {
getStringResult()
}
CoroutineScope(Dispatchers.IO).launch { setText("RunBlocking $result") }
}
private suspend fun setText(text: String) {
withContext(Main) {
binding.coroutineText.text = text
}
}
private suspend fun getStringResult(): String {
delay(1000)
return "Hello Paytm"
}
} | CoroutinesFlow/app/src/main/java/com/example/coroutinesexamples/Coroutines/CoroutineBuilderActivity.kt | 1890778751 |
package com.example.coroutinesexamples.Coroutines
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.example.coroutinesexamples.Coroutines.ViewModel.ScopeViewModel
import com.example.coroutinesexamples.R
import com.example.coroutinesexamples.databinding.ActivityAllScopesBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class AllScopesActivity : AppCompatActivity() {
private lateinit var viewModel: ScopeViewModel
private lateinit var binding: ActivityAllScopesBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setContentView(R.layout.activity_all_scopes)
binding = ActivityAllScopesBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
viewModel = ViewModelProvider(this).get(ScopeViewModel::class.java)
setListeners()
binding.customScope.setOnClickListener {
customScope()
finish()
}
binding.lifeCycleScope.setOnClickListener {
lifeCycleScope()
finish()
}
binding.globalScope.setOnClickListener {
globalScope()
finish()
}
binding.viewModelScope.setOnClickListener {
viewModel.getString()
}
}
fun lifeCycleScope() {
lifecycleScope.launch {
doWork()
}
}
fun globalScope() {
GlobalScope.launch {
doWork()
}
}
private fun customScope() {
CoroutineScope(IO).launch {
doWork()
}
}
private fun setListeners() {
viewModel.liveData.observe(this, Observer { binding.scopeText.text = "Result is : $it" })
}
private suspend fun doWork() {
Log.v("Paytm", "Work Started")
delay(5000)
Log.v("Paytm", "Work Ended")
}
} | CoroutinesFlow/app/src/main/java/com/example/coroutinesexamples/Coroutines/AllScopesActivity.kt | 1313674849 |
package com.example.coroutinesexamples.Coroutines
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.coroutinesexamples.R
import com.example.coroutinesexamples.databinding.ActivityJobsParallelBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.system.measureTimeMillis
class JobsParallelActivity : AppCompatActivity() {
private lateinit var parentJob: Job
private lateinit var binding: ActivityJobsParallelBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setContentView(R.layout.activity_jobs_parallel)
binding = ActivityJobsParallelBinding.inflate(layoutInflater)
val view= binding.root
setContentView(view)
binding.mainButton.setOnClickListener {
binding.sqText.text= ""
parallelApiRequestUsingJob()
}
binding.mainButton1.setOnClickListener {
binding.sqText.text =""
parallelApiRequestUsingAsyncAwait()
}
}
private fun parallelApiRequestUsingJob() {
val startTime = System.currentTimeMillis()
parentJob = CoroutineScope(Dispatchers.IO).launch {
val job1 = launch {
setTextOnMainThread("Launching Api1 in thread: ${Thread.currentThread().name}")
val result1 = getResult1FromApi()
setTextOnMainThread("Got $result1")
}
val job2 = launch {
setTextOnMainThread("Launching Api2 in thread: ${Thread.currentThread().name}")
val result2 = getResult2FromApi()
setTextOnMainThread("Got $result2")
}
}
parentJob.invokeOnCompletion {
setNewText("ElapsedTime: ${System.currentTimeMillis() - startTime}")
}
}
private fun parallelApiRequestUsingAsyncAwait() {
CoroutineScope(Dispatchers.IO).launch {
val elapsedTime = measureTimeMillis {
val result1 = async {
setTextOnMainThread("Launching Api1 in thread: ${Thread.currentThread().name}")
getResult1FromApi()
}
val result2 = async {
setTextOnMainThread("Launching Api2 in thread: ${Thread.currentThread().name}")
getResult2FromApi()
}
setTextOnMainThread("Got ${result1.await()}")
setTextOnMainThread("Got ${result2.await()}")
}
setTextOnMainThread("ElapsedTime:${elapsedTime}")
}
}
private fun setNewText(text: String) {
val newText = binding.sqText.text.toString() + "\n$text"
binding.sqText.text = newText
}
private suspend fun setTextOnMainThread(input: String) {
withContext(Dispatchers.Main) {
setNewText(input)
}
}
private suspend fun getResult1FromApi(): String {
delay(1000)
return "Result #1"
}
private suspend fun getResult2FromApi(): String {
delay(1700)
return "Result #2"
}
} | CoroutinesFlow/app/src/main/java/com/example/coroutinesexamples/Coroutines/JobsParallelActivity.kt | 1094245544 |
package com.example.coroutinesexamples
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [mainFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class mainFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val binding= inflater.inflate(R.layout.fragment_main, container, false)
return binding.rootView
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment mainFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
mainFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | CoroutinesFlow/app/src/main/java/com/example/coroutinesexamples/mainFragment.kt | 4108546615 |
package com.example.coroutinesexamples.fingerprintPattern
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.biometric.BiometricPrompt.PromptInfo
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.example.coroutinesexamples.R
import com.example.coroutinesexamples.databinding.ActivityBioMainBinding
class BioMainActivity : AppCompatActivity() {
private lateinit var binding: ActivityBioMainBinding
// creating a variable for our Executor
var executor = ContextCompat.getMainExecutor(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_bio_main)
val biometricManager: BiometricManager = BiometricManager.from(this)
when (biometricManager.canAuthenticate()) {
BiometricManager.BIOMETRIC_SUCCESS -> {
"You can use the fingerprint sensor to login".also { binding.msgtext.text = it }
binding.msgtext.setTextColor(Color.parseColor("#fafafa"))
}
BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
"This device does not have a fingerprint sensor".also { binding.msgtext.text = it }
binding.login.visibility = View.GONE
}
BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
"The biometric sensor is currently unavailable".also { binding.msgtext.text = it }
binding.login.visibility = View.GONE
}
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
"Your device doesn't have fingerprint saved,please check your security settings".also { binding.msgtext.text = it }
binding.login.visibility = View.GONE
}
BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> {
TODO()
}
BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED -> {
TODO()
}
BiometricManager.BIOMETRIC_STATUS_UNKNOWN -> {
TODO()
}
}
// this will give us result of AUTHENTICATION
// this will give us result of AUTHENTICATION
val biometricPrompt = BiometricPrompt(this@BioMainActivity,executor,object :BiometricPrompt.AuthenticationCallback(){
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
Toast.makeText(applicationContext, "Login Success", Toast.LENGTH_SHORT).show()
"Login Successful".also { binding.login.text }
}
})
// creating a variable for our promptInfo
// BIOMETRIC DIALOG
// creating a variable for our promptInfo
// BIOMETRIC DIALOG
val promptInfo = PromptInfo.Builder().setTitle("GFG")
.setDescription("Use your fingerprint to login ").setNegativeButtonText("Cancel")
.build()
binding.login.setOnClickListener {
biometricPrompt.authenticate(
promptInfo
)
}
}
} | CoroutinesFlow/app/src/main/java/com/example/coroutinesexamples/fingerprintPattern/BioMainActivity.kt | 370614983 |
package fast.part0.basic_kotlin
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("fast.part0.basic_kotlin", appContext.packageName)
}
} | basic_kotlin/app/src/androidTest/java/fast/part0/basic_kotlin/ExampleInstrumentedTest.kt | 804602328 |
package fast.part0.basic_kotlin
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | basic_kotlin/app/src/test/java/fast/part0/basic_kotlin/ExampleUnitTest.kt | 721083416 |
package fast.part0.basic_kotlin.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/ui/theme/Color.kt | 3632799111 |
package fast.part0.basic_kotlin.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun Basic_kotlinTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/ui/theme/Theme.kt | 1954149032 |
package fast.part0.basic_kotlin.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/ui/theme/Type.kt | 2353415223 |
package fast.part0.basic_kotlin
/*
λλ€
1. μ΅λͺ
ν¨μ
2. λ³μμ²λΌ μ¬μ©λμ ν¨μμ argument, returnμ΄ λ μ μλ€
3. νλ² μ¬μ©λκ³ , μ¬μ¬μ©λμ§ μλ ν¨μ
*/
fun main() {
val a = fun(){ println("hello") }
val b: (Int) -> String = { "$it μ
λλ€" }
println(b(10))
val d = { i : Int, j: Int -> i * j}
val e: (Int, String, Boolean) -> String = { _, b, _ -> b}
hello(10, b )
}
fun hello(a: Int, b: (Int) -> String): (Int) -> String {
println("a: $a")
println(b(20))
return b
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/Ramda.kt | 3222535905 |
package fast.part0.basic_kotlin
fun main() {
var name: String = "Zoe" //non nullable
var nickname: String? = null // nullable
var number: Int = 10
var secondNumber: Int? = null
val result1 = if(nickname == null) "κ°μ΄ μμ" else nickname
println("result1: $result1")
val result2 = nickname?: "κ°μ΄ μμ"
println("result2: $result2")
nickname = ""
val size = nickname?.length
println("nickname?.length: $size")
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/Example8.kt | 2200932453 |
package fast.part0.basic_kotlin
fun main() {
val num = 10
val name = "Hello"
val isHigh = true
println("$num $name ${name.length} $isHigh")
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/Example10.kt | 3192931061 |
package fast.part0.basic_kotlin
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.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import fast.part0.basic_kotlin.ui.theme.Basic_kotlinTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Basic_kotlinTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
Basic_kotlinTheme {
Greeting("Android")
}
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/MainActivity.kt | 3682427477 |
package fast.part0.basic_kotlin
fun main(){
cast("cast")
cast(10)
println(smartcast("SmartCASE"))
println(smartcast(5))
println(smartcast(true))
println(check("HELLO"))
println(check(3))
println(check(false))}
fun smartcast(a: Any): Int {
return if(a is String) {
a.length
}else if (a is Int){
a.dec()
}else {
-1
}
}
fun cast(a: Any) {
val result = (a as? String) ?: "μ€ν¨"
println(result)
}
fun check(a: Any): String{
return when (a) {
is String -> {
"λ¬Έμμ΄"
}
is Int -> {
"μ«μ"
}
else -> {
"unknown"
}
}
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/Example9.kt | 3724038388 |
package fast.part0.basic_kotlin
/*
λ²μ μ§μ ν¨μ Scope Function
- κ°μ²΄μ 컨ν
μ€νΈ λ΄μμ, μ€ν κ°λ₯ν μ½λ λΈλμ λ§λλ ν¨μ.
- νΈμΆ μ, μμ λ²μκ° μμ±λλ©°, μ΄ λ²μ μμμλ μ΄λ¦ μμ΄ κ°μ²΄μ μ κ·Ό κ°λ₯
- μμ κ°μ²΄(receiver): νμ₯ ν¨μκ° νΈμΆλλ λμμ΄ λλ κ°(κ°μ²΄)
- μμ κ°μ²΄ μ§μ λλ€: μμ κ°μ²΄λ₯Ό λͺ
μνμ§ μκ³ , λλ€μ λ³Έλ¬Έ μμμ ν΄λΉ κ°μ²΄μ λ©μλλ₯Ό νΈμΆν μ μκ² νλ κ²
- μμ κ°μ²΄ μ κ·Ό λ°©λ²: this, it
- return κ°: μμ κ°μ²΄, λ§μ§λ§ ν(lamda result)
let: null 체ν¬λ₯Ό ν΄μΌν λ, μ§μ λ³μλ₯Ό λͺ
μμ μΌλ‘ νν ν΄μΌν λ
run: κ°μ²΄λ₯Ό μ΄κΈ°ν νκ³ λ¦¬ν΄ κ°μ΄ μμ λ
apply: κ°μ²΄ μ΄κΈ°ν
also: μμ κ°μ²΄λ₯Ό λͺ
μμ μΌλ‘ μ¬μ©νκ³ μΆμ λ, λ‘κ·Έλ₯Ό λ¨κΈΈ λ
with: κ°μ²΄ μ΄κΈ°ν, λλ€ λ¦¬ν΄ κ°μ΄ νμ μμ λ
*/
fun main() {
// let, run, apply, also
// 1. let
val a = 3
a.let {}
val user1 = User2("Zoe", 10, true)
val age1 = user1.let { user -> user.age }
println("age1: $age1")
val user2: User2? = User2("Zoe", 20, false)
val age2 = user2?.let { it.age }
println("age2: $age2")
/*
2. run
μμ κ°μ²΄.run { this ->
λ§μ§λ§ μ€μ΄ return
}
*/
val kid = User2("Kid1", 4, false)
val kidAge1 = kid.run { age }
println("KidAge1: $kidAge1")
/*
3. apply
μμ κ°μ²΄.apply {
.....
}
리ν΄κ°μ μμ κ°μ²΄
*/
val female = User2("HaeYoon", 20, true, true)
val femaleValue = female.apply {
hasGlasses = false
}
println("femaleValue: ${femaleValue.hasGlasses}")
/*
4. also
μμ κ°μ²΄.also { it -> // local variable μ€μ κ°λ₯
}
return κ°μ μμ κ°μ²΄ (μκΈ° μμ )
*/
val male = User2("Felix", 23, false, true)
val maleValue = male.also {
println(it.name)
println(it.hasGlasses)
}
/*
5. with
with(μμ κ°μ²΄) {
...
λ§μ§λ§μ€μ΄ return
}
*/
val result = with(male) {
hasGlasses = false
true
}
println("result: $result")
}
class User2 (
val name: String,
val age: Int,
val gender: Boolean,
var hasGlasses: Boolean = true,
) | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/ScopeFunction.kt | 40989685 |
package fast.part0.basic_kotlin
fun main() {
for(i in IntRange(1, 10)){
print(i)
print(".")
}
println()
for(i in 1 until 10){
print(i)
print(".")
}
println()
for(i in 1..10 step(2)){
print(i)
print(".")
}
println()
for(i in 10 downTo 1){
print(i)
print(".")
}
println()
for(i in 10 downTo 1 step(2)){
print(i)
print(".")
}
println()
var c = 1
while(c < 11) {
print(c)
print(".")
c++
}
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/Example6.kt | 923295442 |
package fast.part0.basic_kotlin
import fast.part0.basic_kotlin.Book.Novel.NAME
/*
Object: ν΄λμ€λ₯Ό μ μν¨κ³Ό λμμ κ°μ²΄λ₯Ό μμ±
μ±κΈν€μ μ½κ² λ§λ€ μ μλ ν€μλ
μμ±μ μ¬μ© λΆκ°
νλ‘νΌν°, λ©μλ, μ΄κΈ°ν λΈλ‘μ μ¬μ© κ°λ₯
λ€λ₯Έ ν΄λμ€λ μΈν°νμ΄μ€λ₯Ό μμλ°μ μ μμ
Companion Object: λλ° κ°μ²΄
ν΄λμ€ λ΄μ νλλ§ μ μΈν μ μμ
javaμ staticκ³Ό λμΌν μν -> Book.name
static X -> Book().name - μμ±μλ₯Ό λ§λ€κ³ name νλ‘νΌν°μ μ κ·Όν΄μΌ ν¨
*/
fun main(){
println(Counter.count)
Counter.countUp()
Counter.countUp()
println(Counter.count)
Counter.hello()
NAME
}
object Counter: Hello() {
init {
println("Counter μ΄κΈ°ν")
}
var count = 0
fun countUp(){ count ++ }
}
open class Hello(){
fun hello() = println("Hello")
}
class Book {
companion object Novel {
const val NAME = "NANE"
fun create() = Book()
}
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/CompanionObject.kt | 3553303875 |
package fast.part0.basic_kotlin
/*
lateinit, var: λ³μ νμ
μ μ§μ ν΄μ£Όμ΄μΌ ν¨. primitive νμ
μ μ¬μ©ν μ μμ (Int X -> Integer O)
lazy, val -> μ μΈκ³Ό λμμ μ΄κΈ°νλ₯Ό ν΄μΌ ν¨. νΈμΆ μμ μμ μ΄κΈ°νκ° μ΄λ£¨μ΄μ§
*/
lateinit var text: String
val test: Int by lazy {
println("μ΄κΈ°ν μ€")
100
}
fun main() {
println("main function")
println("init value: $test")
println("second value: $test")
}
| basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/LateInit.kt | 1256788973 |
package fast.part0.basic_kotlin
fun main(){
val result = test(3, c = 5)
println("result at main: $result")
test2(name="Zoe Shin", nickname = "Zoe", id = 1)
println(times(2,3))
}
// 2. ν¨μ
fun test(a: Int, b: Int = 3, c: Int = 4) : Int{
println("$a+$b+$c")
return a + b + c
}
fun test2(id: Int, name: String, nickname: String) = println("id: $id, name: $name, nickname: $nickname")
fun times(a: Int, b: Int) = a * b | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/Example2.kt | 995248896 |
package fast.part0.basic_kotlin
fun main(){
/*
3. λ³μ
val = value(κ°)
var = variable (λ³κ²½ κ°λ₯)
*/
val num1: Int = 3
var num2: Int = 10
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/Example3.kt | 330456767 |
package fast.part0.basic_kotlin
fun main() {
val list1 = mutableListOf(1,2,3,4,5)
list1.add(6)
list1.addAll(listOf(7,8,9))
// immutable (μμ X)
val list2 = listOf(1,2,3,4)
// print("list2[0]: " + list2[0].toString())
println(list2.map { it * 10}.joinToString("/"))
val divereList = listOf(1, "μλ
", 1.78, true)
print(list1.joinToString(","))
val map1 = mapOf((1 to "μλ
"), (2 to "Hello"))
val map2 = mutableMapOf((1 to "μλ
"), (2 to "Hello"))
map2.put(3, "nice to meet you")
map2[4] = "How are you"
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/Example7.kt | 67674821 |
package fast.part0.basic_kotlin
/*
Data class: λ°μ΄ν°λ₯Ό λ΄κΈ° μν ν΄λμ€
toString(), hasCode(), equals(), copy() λ©μλλ₯Ό μλμΌλ‘ μμ±
overrideνλ©΄ μ§μ ꡬνν μ½λλ₯Ό μ¬μ©
1κ° μ΄μμ νλ‘νΌν°κ° μμ΄μΌ ν¨
λ°μ΄ν° ν΄λμ€λ abstract, open, sealed, inner λ₯Ό λΆμΌ μ μμ
μμμ΄ λΆκ°λ₯
Sealed class: μΆμ ν΄λμ€λ‘, μμλ°μ μμν΄λμ€μ μ’
λ₯λ₯Ό μ ν
μ»΄νμΌλ¬κ° sealed ν΄λμ€μ μμν΄λμ€κ° μ΄λ€ κ²μΈμ§ μ
whenκ³Ό ν¨κ» μ°μΌ λ μ₯μ μ
*/
fun main() {
val person = Person("Felix", 23)
val dog = Dog("Seungmin", 23)
println("person: ${person.toString()}")
println("dog: ${dog.toString()}")
println("copy: ${dog.copy(age = 3).toString()}")
val cat: Cat = BlueCat()
val result = when(cat) {
is BlueCat -> "blue"
is RedCat -> "red"
is GreenCat -> "green"
}
println("result: $result")
}
class Person(
val name: String,
val age: Int,
)
data class Dog(
val name: String,
val age: Int,
)
// sealed class: μΆμν΄λμ€
sealed class Cat
class BlueCat: Cat()
class RedCat: Cat()
class GreenCat: Cat() | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/DataSealedClass.kt | 1037118808 |
package fast.part0.basic_kotlin
/*
νμ₯ν¨μ Extension Function: κΈ°μ‘΄μ μ μλμ΄ μλ ν΄λμ€μ ν¨μλ₯Ό μΆκ°νλ κΈ°λ₯
*/
fun main() {
val test = Test()
test.hello()
test.hi()
}
fun Test.hi() = println("HI")
class Test() {
fun hello() = println("Hello")
fun bye() = println("Bye")
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/ExtensionFunction.kt | 4098863912 |
package fast.part0.basic_kotlin
fun main(){
val user = User("Zoe", 25, true)
// println(user.age)
Kid("Felix", 25, "male")
}
open class User(open val name: String, open var age: Int = 31, b: Boolean)
class Kid(override val name: String, override var age: Int): User(name, age, true){
var gender: String = "female"
init {
println("μ΄κΈ°ν μ€ μ
λλ€.")
}
constructor(name: String, age: Int, gender: String): this(name, age){
this.gender = gender
println("λΆμμ±μ νΈμΆ")
}
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/Example4.kt | 2203878392 |
package fast.part0.basic_kotlin
fun main(){
max(10, 3)
isHoliday(3)
}
fun max(a: Int, b: Int) {
val result = if(a > b) a else b
println("max is: $result")
}
// μ ν μ λͺ© κΈ ν μΌ
fun isHoliday(dayOfWeek: Any) {
val result =
when(val day = dayOfWeek) {
"ν ", "μΌ" -> if(day == "ν ") "ν μμΌμ μ’μ" else "μΌμμΌ λ무μ’μ"
in 2..4 -> "μ«μμ λ²μκ° 2λΆν° 4 μ¬μ΄ μ
λλ€"
in listOf<String>("μ", "ν",) -> "νμ¬ κ°μΌμ§ ^_^"
else -> "νλ΄μ"
}
println("$dayOfWeek isHoliday: $result")
} | basic_kotlin/app/src/main/java/fast/part0/basic_kotlin/Example5.kt | 3579266813 |
package com.guillaume.taffin.structurizr.dsl.kotlin
import org.junit.jupiter.api.DynamicTest
fun <T> Iterable<T>.test(bloc: (T) -> Unit): List<DynamicTest> = this.map {
DynamicTest.dynamicTest(it.toString()) { bloc(it) }
} | structurizr-dsl-kotlin/src/test/kotlin/com/guillaume/taffin/structurizr/dsl/kotlin/Helpers.kt | 2795143489 |
package com.guillaume.taffin.structurizr.dsl.kotlin.workspace
import io.kotest.matchers.maps.shouldContainExactly
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class AddingWorkspacePropertiesTest {
@Test
fun `Should not contain any properties by default`() {
val workspace = workspace { }
workspace.properties shouldBe emptyMap()
}
@Test
fun `Should allow to set properties in workspace`() {
val workspace = workspace {
properties(
"key1" to "value1",
"key2" to "value2",
)
}
workspace.properties shouldContainExactly mapOf(
"key1" to "value1",
"key2" to "value2",
)
}
} | structurizr-dsl-kotlin/src/test/kotlin/com/guillaume/taffin/structurizr/dsl/kotlin/workspace/AddingWorkspacePropertiesTest.kt | 3129070789 |
package com.guillaume.taffin.structurizr.dsl.kotlin.workspace
import com.guillaume.taffin.structurizr.dsl.kotlin.test
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestFactory
class EmptyWorkspaceTest {
@TestFactory
fun `Should create a workspace`() = listOf(
"" to "",
"name" to "",
"" to "description",
).test { (name, description) ->
val workspace = workspace(name, description)
workspace.isEmpty shouldBe true
workspace.name shouldBe name
workspace.description shouldBe description
}
@Test
fun `Should allow to pass empty closure`() {
val workspace = workspace {}
workspace.isEmpty shouldBe true
workspace.name shouldBe ""
workspace.description shouldBe ""
}
@Test
fun `Should allow to set name from the model`() {
val workspace = workspace {
name = "workspace"
}
workspace.name shouldBe "workspace"
}
@Test
fun `Should allow to set description from model`() {
val workspace = workspace {
description = "A bootiful workspace"
}
workspace.description shouldBe "A bootiful workspace"
}
}
| structurizr-dsl-kotlin/src/test/kotlin/com/guillaume/taffin/structurizr/dsl/kotlin/workspace/EmptyWorkspaceTest.kt | 281034304 |
package com.guillaume.taffin.structurizr.dsl.kotlin.workspace
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class AddingModelTest {
@Test
fun `Should have empty model by default`() {
val workspace = workspace { }
workspace.model.isEmpty shouldBe true
}
@Test
fun `Should allow to modify empty model`() {
val workspace = workspace {
model {
}
}
workspace.model.isEmpty shouldBe true
}
} | structurizr-dsl-kotlin/src/test/kotlin/com/guillaume/taffin/structurizr/dsl/kotlin/workspace/AddingModelTest.kt | 2018239348 |
package com.guillaume.taffin.structurizr.dsl.kotlin.workspace
import com.structurizr.Workspace
import com.structurizr.model.Model
fun workspace(
name: String = "",
description: String = "",
model: Workspace.() -> Unit = {},
): Workspace = Workspace(name, description).apply(model)
fun Workspace.properties(vararg properties: Pair<String, String>) = properties.forEach {
this.addProperty(it.first, it.second)
}
fun Workspace.model(bloc: Model.() -> Unit) {
} | structurizr-dsl-kotlin/src/main/kotlin/com/guillaume/taffin/structurizr/dsl/kotlin/workspace/WorkspaceKotlinDsl.kt | 3962219126 |
package com.example.myquote
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myquote", appContext.packageName)
}
} | fam_latihan1_networking_kotlin/app/src/androidTest/java/com/example/myquote/ExampleInstrumentedTest.kt | 3270932506 |
package com.example.myquote
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | fam_latihan1_networking_kotlin/app/src/test/java/com/example/myquote/ExampleUnitTest.kt | 2150139140 |
package com.example.myquote
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.example.myquote.databinding.ActivityMainBinding
import com.loopj.android.http.AsyncHttpClient
import com.loopj.android.http.AsyncHttpResponseHandler
import cz.msebera.android.httpclient.Header
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
companion object {
private val TAG = MainActivity::class.simpleName
}
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
getRandomQuote()
binding.btnAllQuotes.setOnClickListener {
startActivity(Intent(this@MainActivity, ListQuotesActivity::class.java))
}
}
private fun getRandomQuote() {
binding.progressBar.visibility = View.VISIBLE
val client = AsyncHttpClient()
val url = "https://quote-api.dicoding.dev/random"
client.get(url, object : AsyncHttpResponseHandler() {
override fun onSuccess(
statusCode: Int,
headers: Array<Header>,
responseBody: ByteArray
) {
// Jika koneksi berhasil
binding.progressBar.visibility = View.INVISIBLE
val result = String(responseBody)
Log.d(TAG, result)
try {
val responseObject = JSONObject(result)
val quote = responseObject.getString("en")
val author = responseObject.getString("author")
binding.tvQuote.text = quote
binding.tvAuthor.text = author
} catch (e: Exception) {
Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_SHORT).show()
e.printStackTrace()
}
}
override fun onFailure(
statusCode: Int,
headers: Array<Header>,
responseBody: ByteArray,
error: Throwable
) {
// Jika koneksi gagal
binding.progressBar.visibility = View.INVISIBLE
val errorMessage = when (statusCode) {
401 -> "$statusCode : Bad Request"
403 -> "$statusCode : Forbidden"
404 -> "$statusCode : Not Found"
else -> "$statusCode : ${error.message}"
}
Toast.makeText(this@MainActivity, errorMessage, Toast.LENGTH_SHORT).show()
}
})
}
} | fam_latihan1_networking_kotlin/app/src/main/java/com/example/myquote/MainActivity.kt | 2269172328 |
package com.example.myquote
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView.LayoutManager
import com.example.myquote.databinding.ActivityListQuotesBinding
import com.loopj.android.http.AsyncHttpClient
import com.loopj.android.http.AsyncHttpResponseHandler
import cz.msebera.android.httpclient.Header
import org.json.JSONArray
class ListQuotesActivity : AppCompatActivity() {
companion object {
private val TAG = ListQuotesActivity::class.simpleName
}
private lateinit var binding: ActivityListQuotesBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityListQuotesBinding.inflate(layoutInflater)
setContentView(binding.root)
val layoutManager = LinearLayoutManager(this)
binding.listQuotes.setLayoutManager(layoutManager)
val itemDecoration = DividerItemDecoration(this, layoutManager.orientation)
binding.listQuotes.addItemDecoration(itemDecoration)
getListQuotes()
}
private fun getListQuotes() {
binding.progressBar.visibility = View.VISIBLE
val client = AsyncHttpClient()
val url = "https://quote-api.dicoding.dev/list"
client.get(url, object : AsyncHttpResponseHandler() {
override fun onSuccess(
statusCode: Int,
headers: Array<out Header>?,
responseBody: ByteArray
) {
binding.progressBar.visibility = View.INVISIBLE
val listQuote = ArrayList<String>()
val result = String(responseBody)
Log.d(TAG, result)
try {
val jsonArray = JSONArray(result)
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
val quote = jsonObject.getString("en")
val author = jsonObject.getString("author")
listQuote.add("\n$quote\n - $author\n")
}
val adapter = QuoteAdapter(listQuote)
binding.listQuotes.adapter = adapter
} catch (e: Exception) {
Toast.makeText(this@ListQuotesActivity, e.message, Toast.LENGTH_SHORT).show()
e.printStackTrace()
}
}
override fun onFailure(
statusCode: Int,
headers: Array<out Header>?,
responseBody: ByteArray?,
error: Throwable?
) {
binding.progressBar.visibility = View.INVISIBLE
val errorMessage = when (statusCode) {
401 -> "$statusCode : Bad Request"
403 -> "$statusCode : Forbidden"
404 -> "$statusCode : Not Found"
else -> "$statusCode : ${error?.message}"
}
Toast.makeText(this@ListQuotesActivity, errorMessage, Toast.LENGTH_SHORT).show()
}
})
}
} | fam_latihan1_networking_kotlin/app/src/main/java/com/example/myquote/ListQuotesActivity.kt | 3352952963 |
package com.example.myquote
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class QuoteAdapter(private val listReview: ArrayList<String>) :
RecyclerView.Adapter<QuoteAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val tvItem: TextView = view.findViewById(
R.id.tvItem
)
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_quote, viewGroup, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return listReview.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.tvItem.text = listReview[position]
}
} | fam_latihan1_networking_kotlin/app/src/main/java/com/example/myquote/QuoteAdapter.kt | 1763056327 |
package com.example.kotlingoals
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.kotlingoals", appContext.packageName)
}
} | KotlinGoals/app/src/androidTest/java/com/example/kotlingoals/ExampleInstrumentedTest.kt | 1448874489 |
package com.example.kotlingoals
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | KotlinGoals/app/src/test/java/com/example/kotlingoals/ExampleUnitTest.kt | 2715149409 |
package com.example.kotlingoals.androidmvvmbasics.viewmodels
import androidx.databinding.Bindable
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.kotlingoals.androidmvvmbasics.model.LoginData
class LoginViewModel : ViewModel() {
private val _loginSuccess = MutableLiveData<Boolean>()
val loginSuccess: LiveData<Boolean>
get() = _loginSuccess
var loginData = LoginData()
fun onLoginButtonClick() {
// Implement your login logic here
val email = loginData.email
val password = loginData.password
if (isValidCredentials(email,password)) {
if (isEmailValid(email) && isPasswordValid(password)) {
// If login is successful, set loginSuccess LiveData to true
_loginSuccess.value = true
} else {
// Show error message if login fails
_loginSuccess.value = false
}
}else {
// Show error message if login fails
_loginSuccess.value = false
}
}
private fun isEmailValid(email: String): Boolean {
// Basic email validation
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
private fun isPasswordValid(password: String): Boolean {
// Simple password validation
return password.length >= 6 // Example: Minimum 6 characters
}
private fun isValidCredentials(email: String, password: String): Boolean {
// Perform your actual login validation logic here
// For demonstration purposes, we're just checking if email and password are not empty
return email.isNotEmpty() && password.isNotEmpty()
}
} | KotlinGoals/app/src/main/java/com/example/kotlingoals/androidmvvmbasics/viewmodels/LoginViewModel.kt | 2716390396 |
package com.example.kotlingoals.androidmvvmbasics.model
class LoginData {
var email: String = ""
var password: String = ""
}
| KotlinGoals/app/src/main/java/com/example/kotlingoals/androidmvvmbasics/model/LoginData.kt | 1882605693 |
package com.example.kotlingoals.androidmvvmbasics.views
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.kotlingoals.R
import com.example.kotlingoals.androidmvvmbasics.viewmodels.LoginViewModel
import com.example.kotlingoals.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityMainBinding = DataBindingUtil.setContentView(
this,
R.layout.activity_main
)
val viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
binding.viewModel = viewModel
binding.lifecycleOwner = this
viewModel.loginSuccess.observe(this, Observer { success ->
if (success) {
// Show a toast message indicating login success
Toast.makeText(this, "Login successful", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(this, "Please enter valid credentials", Toast.LENGTH_SHORT).show()
}
})
}
} | KotlinGoals/app/src/main/java/com/example/kotlingoals/androidmvvmbasics/views/MainActivity.kt | 992460935 |
package com.example.data_ghibli
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.data_ghibli", appContext.packageName)
}
} | data-ghibli/app/src/androidTest/java/com/example/data_ghibli/ExampleInstrumentedTest.kt | 3395687799 |
package com.example.data_ghibli
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | data-ghibli/app/src/test/java/com/example/data_ghibli/ExampleUnitTest.kt | 810501760 |
package com.example.data_ghibli
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | data-ghibli/app/src/main/java/com/example/data_ghibli/MainActivity.kt | 859222707 |
@file:Suppress("DEPRECATION")
package xyz.pisoj.og.nettools
import android.app.Activity
import android.app.AlertDialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.view.View
import android.view.animation.AlphaAnimation
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ListView
import android.widget.ScrollView
import android.widget.SeekBar
import android.widget.SlidingDrawer
import android.widget.Spinner
import android.widget.TabHost
import android.widget.TextView
import android.widget.Toast
import kotlinx.parcelize.Parcelize
import org.json.JSONObject
import xyz.pisoj.og.nettools.model.DnsRecord
import xyz.pisoj.og.nettools.model.DnsRecordType
import xyz.pisoj.og.nettools.model.Host
import xyz.pisoj.og.nettools.model.toHostStatus
import xyz.pisoj.og.nettools.utils.dpToPixels
import xyz.pisoj.og.nettools.utils.whois
import java.net.InetAddress
import java.net.URL
import java.net.URLEncoder
import java.net.UnknownHostException
import kotlin.concurrent.thread
class MainActivity : Activity() {
private lateinit var state: State
private lateinit var tabHost: TabHost
private lateinit var drawer: SlidingDrawer
private lateinit var mask: View
private lateinit var queryButton: ImageButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
state = savedInstanceState?.getParcelable("state") ?: State()
setupTabHost()
setupQueryButton()
setupPreferences()
if(state.isOperationActive) {
state.operation(this, shouldResetState = false)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable("state", state)
}
override fun onDestroy() {
super.onDestroy()
state = state.copy(isOperationActive = false)
}
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
if (drawer.isOpened) {
closeDrawer()
} else {
super.onBackPressed()
}
}
private fun setupTabHost() {
tabHost = findViewById(R.id.tabHost)
tabHost.setup()
Operation.entries.forEach { operation ->
tabHost.addTab(
tabHost.newTabSpec(operation.name)
.setIndicator(operation.title)
.setContent {
operation.createContent(this)
}
)
}
tabHost.setCurrentTabByTag(state.operation.name)
tabHost.setOnTabChangedListener {
state = state.copy(operation = Operation.valueOf(it), isOperationActive = false)
updateQueryButton()
}
}
private fun setupPreferences() {
mask = findViewById(R.id.mask)
drawer = findViewById(R.id.drawer)
findViewById<ImageButton>(R.id.preferences).setOnClickListener { openDrawer() }
findViewById<ImageButton>(R.id.drawerBack).setOnClickListener { closeDrawer() }
if (state.isDrawerOpened) openDrawer()
val pingDelay = findViewById<SeekBar>(R.id.pingDelay)
pingDelay.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
state = state.copy(pingDelay = progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) = Unit
override fun onStopTrackingTouch(seekBar: SeekBar?) = Unit
})
pingDelay.progress = state.pingDelay
val dnsRecordType = findViewById<Spinner>(R.id.dnsRecordType)
ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item).apply {
addAll(DnsRecordType.entries.map { it.name })
dnsRecordType.adapter = this
}
dnsRecordType.setSelection(state.dnsRecordType.ordinal)
dnsRecordType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
state = state.copy(dnsRecordType = DnsRecordType.entries[position])
}
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
}
}
private fun openDrawer() {
mask.visibility = View.VISIBLE
mask.startAnimation(AlphaAnimation(0f, 1f).apply {
duration = 200
fillAfter = true
})
drawer.animateOpen()
state = state.copy(isDrawerOpened = true)
}
private fun closeDrawer() {
mask.startAnimation(AlphaAnimation(1f, 0f).apply {
duration = 200
fillAfter = true
})
drawer.animateClose()
mask.visibility = View.GONE
state = state.copy(isDrawerOpened = false)
}
private fun setupQueryButton() {
val hostEditText = findViewById<EditText>(R.id.host)
queryButton = findViewById(R.id.query)
updateQueryButton()
val whoisServer = findViewById<EditText>(R.id.whoisServer)
val whoisPort = findViewById<EditText>(R.id.whoisPort)
queryButton.setOnClickListener {
state = state.copy(
host = hostEditText.text.toString(),
whoisServer = whoisServer.text.toString().ifBlank { "whois.iana.org" },
whoisPort = whoisPort.text.toString().ifBlank { "43" }.toInt(),
isOperationActive = !state.isOperationActive
)
updateQueryButton()
if(state.isOperationActive) {
state.operation(this, shouldResetState = true)
}
}
}
private fun updateQueryButton() {
queryButton.setImageResource(
if(state.isOperationActive) R.drawable.ic_stop else R.drawable.ic_query
)
}
@Parcelize
private data class State(
val operation: Operation = Operation.Ping,
val isOperationActive: Boolean = false,
val isDrawerOpened: Boolean = false,
val host: String = "",
val pingDelay: Int = 1000,
val dnsRecordType: DnsRecordType = DnsRecordType.ANY,
val whoisServer: String = "whois.iana.org",
val whoisPort: Int = 43,
) : Parcelable
/**
* @param title User visible name of the operation
*/
private enum class Operation(val title: String) {
Ping(title = "Ping") {
private val adapter by lazy { HostListAdapter(mutableListOf()) }
override operator fun invoke(mainActivity: MainActivity, shouldResetState: Boolean) {
if(shouldResetState) {
adapter.hosts = mutableListOf()
adapter.notifyDataSetChanged()
}
thread {
try {
ping(mainActivity) { host ->
mainActivity.runOnUiThread {
adapter.hosts.add(index = 0, host)
adapter.notifyDataSetChanged()
}
}
} catch (e: UnknownHostException) {
mainActivity.runOnUiThread {
mainActivity.state = mainActivity.state.copy(isOperationActive = false)
AlertDialog.Builder(mainActivity)
.setTitle("Failed to resolve the host name")
.setPositiveButton("Close") { _, _ -> }
.show()
mainActivity.updateQueryButton()
}
}
}
}
override fun createContent(context: Context): View {
return ListView(context).apply {
divider = null
adapter = [email protected]
}
}
private fun ping(mainActivity: MainActivity, onNewPing: (host: Host) -> Unit) {
val hostInet = InetAddress.getByName(mainActivity.state.host)
while (mainActivity.state.isOperationActive) {
val start = System.currentTimeMillis()
val status = hostInet.isReachable(1500).toHostStatus()
val latency = System.currentTimeMillis() - start
onNewPing(Host(mainActivity.state.host, if(status == Host.Status.Unavailable) null else latency, status))
(1..mainActivity.state.pingDelay / 100).forEach { _ ->
if (!mainActivity.state.isOperationActive) return
Thread.sleep(100)
}
}
}
},
Dns(title = "Dns") {
private val adapter by lazy { DnsListAdapter(mutableListOf()) }
override fun invoke(mainActivity: MainActivity, shouldResetState: Boolean) {
adapter.records = mutableListOf()
adapter.notifyDataSetChanged()
thread {
try {
val resultText = URL("https://dns.google/resolve?name=${URLEncoder.encode(mainActivity.state.host, "UTF-8")}&type=${mainActivity.state.dnsRecordType.typeId}").readText()
val records = JSONObject(resultText).getJSONArray("Answer")
for(i in 0 ..< records.length()) {
records.getJSONObject(i).apply {
adapter.records.add(
DnsRecord(
name = getString("name"),
data = getString("data"),
typeId = getInt("type"),
ttl = getInt("TTL"),
)
)
}
}
mainActivity.runOnUiThread {
adapter.notifyDataSetChanged()
}
} catch (e: Exception) {
mainActivity.runOnUiThread {
AlertDialog.Builder(mainActivity)
.setTitle("Failed to query dns.google")
.setMessage("${e::class.qualifiedName}: ${e.message.orEmpty()}")
.setPositiveButton("Close") { _, _ -> }
.show()
}
e.printStackTrace()
} finally {
mainActivity.runOnUiThread {
mainActivity.state = mainActivity.state.copy(isOperationActive = false)
mainActivity.updateQueryButton()
}
}
}
}
override fun createContent(context: Context): View {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val vibratorManager =
context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
vibratorManager.defaultVibrator
} else {
@Suppress("DEPRECATION")
context.getSystemService(VIBRATOR_SERVICE) as Vibrator
}
return ListView(context).apply {
divider = null
adapter = [email protected]
onItemLongClickListener =
AdapterView.OnItemLongClickListener { _, _, position, _ ->
val dnsRecord = getItemAtPosition(position) as DnsRecord
clipboard.setPrimaryClip(ClipData.newPlainText(dnsRecord.data, dnsRecord.data))
Toast.makeText(context, "Data copied to clipboard", Toast.LENGTH_SHORT).show()
if (Build.VERSION.SDK_INT >= 26) {
vibrator.vibrate(VibrationEffect.createOneShot(60, VibrationEffect.DEFAULT_AMPLITUDE))
} else {
@Suppress("DEPRECATION")
vibrator.vibrate(60)
}
true
}
}
}
},
Whois(title = "Whois") {
private lateinit var textView: TextView
override fun invoke(mainActivity: MainActivity, shouldResetState: Boolean) {
thread {
try {
val output = whois(
domain = mainActivity.state.host,
whoisServer = mainActivity.state.whoisServer,
whoisPort = mainActivity.state.whoisPort
)
mainActivity.runOnUiThread {
textView.text = output
}
} catch (e: UnknownHostException) {
mainActivity.runOnUiThread {
AlertDialog.Builder(mainActivity)
.setTitle("Failed to resolve the host name of the whois server")
.setMessage("Please check you internet connection and whois server configuration.")
.setPositiveButton("Close") { _, _ -> }
.show()
}
} catch (e: Exception) {
mainActivity.runOnUiThread {
AlertDialog.Builder(mainActivity)
.setTitle("Failed to query the whois server")
.setMessage("Please check you whois server configuration.\n${e::class.qualifiedName}: ${e.message.orEmpty()}")
.setPositiveButton("Close") { _, _ -> }
.show()
}
e.printStackTrace()
} finally {
mainActivity.runOnUiThread {
mainActivity.state = mainActivity.state.copy(isOperationActive = false)
mainActivity.updateQueryButton()
}
}
}
}
override fun createContent(context: Context): View {
val paddingInPixels = context.dpToPixels(16)
textView = TextView(context).apply {
setPadding(paddingInPixels, paddingInPixels, paddingInPixels, paddingInPixels)
setTextIsSelectable(true)
}
return ScrollView(context).apply { addView(textView) }
}
};
/**
* @param shouldResetState Should the operation reset the output of a previous run or should
* it just append the new output to the previous one. It's okay to ignore this when implementing a new operation if it doesn't make sense.
*/
abstract operator fun invoke(mainActivity: MainActivity, shouldResetState: Boolean)
abstract fun createContent(context: Context): View
}
} | og-nettools-droid/app/src/main/java/xyz/pisoj/og/nettools/MainActivity.kt | 665535664 |
package xyz.pisoj.og.nettools
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 xyz.pisoj.og.nettools.model.Host
import xyz.pisoj.og.nettools.utils.formatLatencyMillis
import xyz.pisoj.og.nettools.utils.getColorForStatus
class HostListAdapter(var hosts: MutableList<Host>): BaseAdapter() {
override fun getCount(): Int {
return hosts.size
}
override fun getItem(position: Int): Any {
return hosts[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView
?: LayoutInflater
.from(parent.context)
.inflate(R.layout.item_ping, parent, false)
.apply { tag = ViewHolder(this) }
val viewHolder = view.tag as ViewHolder
viewHolder.setHost(hosts[position])
return view
}
private class ViewHolder(private val root: View) {
private val hostTextView: TextView = root.findViewById(R.id.host)
private val latencyTextView: TextView = root.findViewById(R.id.latency)
private val statusView: ImageView = root.findViewById(R.id.status)
fun setHostText(value: String) {
hostTextView.text = value
}
fun setLatencyText(latency: String?) {
if (latency == null) {
latencyTextView.visibility = View.GONE
return
}
latencyTextView.visibility = View.VISIBLE
latencyTextView.text = latency
}
fun setStatus(status: Host.Status) {
statusView.setColorFilter(
root.context.getColorForStatus(status),
android.graphics.PorterDuff.Mode.SRC_IN
)
}
fun setHost(host: Host) {
setHostText(host.host)
setLatencyText(host.latencyMillis?.let { formatLatencyMillis(it) })
setStatus(host.status)
}
}
} | og-nettools-droid/app/src/main/java/xyz/pisoj/og/nettools/HostListAdapter.kt | 3734696307 |
package xyz.pisoj.og.nettools
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import xyz.pisoj.og.nettools.model.DnsRecord
class DnsListAdapter(var records: MutableList<DnsRecord>): BaseAdapter() {
override fun getCount(): Int {
return records.size
}
override fun getItem(position: Int): Any {
return records[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView
?: LayoutInflater.from(parent.context)
.inflate(R.layout.item_dns, parent, false)
.apply { tag = ViewHolder(this) }
val viewHolder = view.tag as ViewHolder
viewHolder.setDns(records[position])
return view
}
private class ViewHolder(root: View) {
private val name = root.findViewById<TextView>(R.id.name)
private val data = root.findViewById<TextView>(R.id.data)
private val ttl = root.findViewById<TextView>(R.id.ttl)
private val recordType = root.findViewById<TextView>(R.id.recordType)
fun setDns(record: DnsRecord) {
name.text = record.name
data.text = record.data
@SuppressLint("SetTextI18n")
ttl.text = "TTL: ${record.ttl}"
recordType.text = record.type.name
}
}
} | og-nettools-droid/app/src/main/java/xyz/pisoj/og/nettools/DnsListAdapter.kt | 973360816 |
package xyz.pisoj.og.nettools.utils
import android.content.Context
import android.os.Build
import xyz.pisoj.og.nettools.R
import xyz.pisoj.og.nettools.model.Host
fun Context.getColorForStatus(status: Host.Status): Int {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
resources.getColor(
when(status) {
Host.Status.Available -> R.color.available
Host.Status.Warning -> R.color.warning
Host.Status.Error -> R.color.error
Host.Status.Unavailable -> R.color.unavailable
},
null
)
} else {
@Suppress("DEPRECATION")
resources.getColor(
when(status) {
Host.Status.Available -> R.color.available
Host.Status.Warning -> R.color.warning
Host.Status.Error -> R.color.error
Host.Status.Unavailable -> R.color.unavailable
}
)
}
} | og-nettools-droid/app/src/main/java/xyz/pisoj/og/nettools/utils/getColorForStatus.kt | 2731466724 |
package xyz.pisoj.og.nettools.utils
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.Socket
import java.net.UnknownHostException
@Throws(UnknownHostException::class, IOException::class)
fun whois(domain: String, whoisServer: String, whoisPort: Int): String {
val query = domain + "\r\n"
val socket = Socket(whoisServer, whoisPort)
val writer = OutputStreamWriter(socket.getOutputStream())
writer.write(query)
writer.flush()
val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
var line: String?
var complete = ""
while (reader.readLine().also { line = it } != null) {
complete += line + "\n"
}
reader.close()
writer.close()
socket.close()
return complete
} | og-nettools-droid/app/src/main/java/xyz/pisoj/og/nettools/utils/whois.kt | 1161261113 |
package xyz.pisoj.og.nettools.utils
import android.content.Context
fun Context.dpToPixels(dp: Int): Int {
val scale: Float = resources.displayMetrics.density
return (dp * scale + 0.5f).toInt()
} | og-nettools-droid/app/src/main/java/xyz/pisoj/og/nettools/utils/dpToPixels.kt | 983970812 |
package xyz.pisoj.og.nettools.utils
fun formatLatencyMillis(latencyMillis: Long): String {
return if(latencyMillis > 1000) {
"${"%.2f".format(latencyMillis/1000f)}s"
} else {
"${latencyMillis}ms"
}
} | og-nettools-droid/app/src/main/java/xyz/pisoj/og/nettools/utils/formatLatency.kt | 3942936465 |
package xyz.pisoj.og.nettools.model
import java.security.InvalidParameterException
data class DnsRecord(
val name: String,
val data: String,
val type: DnsRecordType,
val ttl: Int,
) {
constructor(name: String, data: String, typeId: Int, ttl: Int) : this(name, data,
DnsRecordType.byTypeId(typeId), ttl)
}
enum class DnsRecordType(val typeId: Int) {
ANY(255),
A(1),
AAAA(28),
AFSDB(18),
APL(42),
CAA(257),
CDNSKEY(60),
CDS(59),
CERT(37),
CNAME(5),
CSYNC(62),
DHCID(49),
DLV(32769),
DNAME(39),
DNSKEY(48),
DS(43),
EUI48(108),
EUI64(109),
HINFO(13),
HIP(55),
HTTPS(65),
IPSECKEY(45),
KEY(25),
KX(36),
LOC(29),
MX(15),
NAPTR(35),
NS(2),
NSEC(47),
NSEC3(50),
NSEC3PARAM(51),
OPENPGPKEY(61),
PTR(12),
RRSIG(46),
RP(17),
SIG(24),
SMIMEA(53),
SOA(6),
SRV(33),
SSHFP(44),
SVCB(64),
TA(32768),
TKEY(249),
TLSA(52),
TSIG(250),
TXT(16),
URI(256),
ZONEMD(63);
companion object {
fun byTypeId(typeId: Int): DnsRecordType {
return DnsRecordType.entries.find { it.typeId == typeId } ?: throw InvalidParameterException("Invalid record type id.")
}
}
}
| og-nettools-droid/app/src/main/java/xyz/pisoj/og/nettools/model/DnsRecord.kt | 452752481 |
package xyz.pisoj.og.nettools.model
data class Host(
val host: String,
val latencyMillis: Long?,
val status: Status
) {
enum class Status {
Available,
Warning,
Error,
Unavailable
}
}
fun Boolean.toHostStatus(): Host.Status {
return if(this) Host.Status.Available else Host.Status.Unavailable
}
| og-nettools-droid/app/src/main/java/xyz/pisoj/og/nettools/model/Host.kt | 2400468599 |
package thehistoryapphelped.com
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("thehistoryapphelped.com", appContext.packageName)
}
} | MogamatSaleemSalie_ST10434444_Assignment1/app/src/androidTest/java/thehistoryapphelped/com/ExampleInstrumentedTest.kt | 939558499 |
package thehistoryapphelped.com
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | MogamatSaleemSalie_ST10434444_Assignment1/app/src/test/java/thehistoryapphelped/com/ExampleUnitTest.kt | 1362626637 |
package thehistoryapphelped.com
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val numberEditText: EditText = findViewById(R.id.numberEditText)
val button1: Button = findViewById(R.id.button1)
val button2: Button = findViewById(R.id.button2)
val textView1: TextView = findViewById(R.id.textView1)
button1.setOnClickListener {
val inputNumber = numberEditText.text.toString()
if (inputNumber.isNotEmpty()) {
val number = inputNumber.toInt()
val message = if (number <= 20 || number > 100) {
"Please enter a age between 20 and 100."
} else {
"Unknown"
}
textView1.text = message
} else {
// Handle empty input case (e.g., show a message)
Toast.makeText(this, "Please enter a number", Toast.LENGTH_SHORT).show()
}
}
button2.setOnClickListener {
numberEditText.text.clear()
}
}
// Define a function to process the input number
// fun processNumber(number: Int): String {
// // Add your processing logic here
// }
}
| MogamatSaleemSalie_ST10434444_Assignment1/app/src/main/java/thehistoryapphelped/com/MainActivity.kt | 1600610726 |
package ma.shuler.card
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("ma.shuler.card", appContext.packageName)
}
} | Card/app/src/androidTest/java/ma/shuler/card/ExampleInstrumentedTest.kt | 2849448208 |
package ma.shuler.card
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Card/app/src/test/java/ma/shuler/card/ExampleUnitTest.kt | 1885443224 |
package ma.shuler.card
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | Card/app/src/main/java/ma/shuler/card/MainActivity.kt | 3360707360 |
package sevenedge.pdfreader.filereader.composables
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("sevenedge.pdfreader.filereader.composables", appContext.packageName)
}
} | Composables/app/src/androidTest/java/sevenedge/pdfreader/filereader/composables/ExampleInstrumentedTest.kt | 3948999355 |
package sevenedge.pdfreader.filereader.composables
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Composables/app/src/test/java/sevenedge/pdfreader/filereader/composables/ExampleUnitTest.kt | 4059654625 |
package sevenedge.pdfreader.filereader.composables.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | Composables/app/src/main/java/sevenedge/pdfreader/filereader/composables/ui/theme/Color.kt | 492324151 |
package sevenedge.pdfreader.filereader.composables.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun ComposablesTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | Composables/app/src/main/java/sevenedge/pdfreader/filereader/composables/ui/theme/Theme.kt | 345887260 |
package sevenedge.pdfreader.filereader.composables.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | Composables/app/src/main/java/sevenedge/pdfreader/filereader/composables/ui/theme/Type.kt | 1278220216 |
package sevenedge.pdfreader.filereader.composables
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.ui.Modifier
import sevenedge.pdfreader.filereader.composables.components.ProfileScreen
import sevenedge.pdfreader.filereader.composables.ui.theme.ComposablesTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposablesTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
ProfileScreen()
}
}
}
}
}
| Composables/app/src/main/java/sevenedge/pdfreader/filereader/composables/MainActivity.kt | 385387294 |
package sevenedge.pdfreader.filereader.composables.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import sevenedge.pdfreader.filereader.composables.R
import sevenedge.pdfreader.filereader.composables.ui.theme.ComposablesTheme
@Composable
fun ProfileScreen(){
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(8.dp)
) {
item {
TopSection()
}
item {
AboutSection()
}
item {
ExperienceSection()
}
item {
EducationSection()
}
}
}
@Composable
fun TopSection() {
Box(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth(),
) {
Column(
modifier = Modifier
.align(Alignment.CenterStart)
.fillMaxWidth(0.5f),
) {
// Profile picture
Image(
modifier = Modifier
.size(120.dp)
.clip(CircleShape)
.shadow(elevation = 4.dp)
.clickable(onClick = { /* Open image picker/cropping dialog */ }),
painter = painterResource(id = R.drawable.profile),
contentDescription = "Profile picture",
)
// Name
Text(
text = "Tariq Hussain",
fontSize = MaterialTheme.typography.titleLarge.fontSize,
fontWeight = MaterialTheme.typography.titleLarge.fontWeight,
)
// Headline
Text(
text = "Software Engineer",
fontSize = MaterialTheme.typography.titleMedium.fontSize,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
)
}
Column(
modifier = Modifier
.align(Alignment.CenterEnd)
.fillMaxHeight(),
horizontalAlignment = Alignment.End
) {
Text(text = "Following: ___")
Text(text = "Followers: ___")
Spacer(modifier = Modifier.size(12.dp))
Button(
onClick = { /* Initiate desired action (Connect, Message, Follow) */ },
) {
Text("Follow", modifier = Modifier.padding(start = 12.dp, end = 12.dp))
}
}
// Connections and followers icons
// Call to action button
}
}
@Composable
fun AboutSection() {
Card(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
) {
Text(
text = "A passionate and results-oriented software engineer with X years of experience in ...",
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.padding(16.dp),
/* .expandableText(
trimLines = 4,
moreText = "See More",
lessText = "Close",
onExpand = { */
/* Handle expand/collapse events */
/* }
)*/
)
}
}
@Composable
fun ExperienceSection() {
Column(
modifier = Modifier.padding(16.dp),
) {
Text(
text = "Work Experience",
fontSize = MaterialTheme.typography.bodyLarge.fontSize,
fontWeight = MaterialTheme.typography.bodyLarge.fontWeight,
)
// Individual experience cards
listOf(
ExperienceCard(
logo = R.drawable.ic_launcher_background,
jobTitle = "Software Engineer",
dates = "Jan ____ - Present",
description = "Led the development of ...",
onDescriptionClick = { /* Open detail dialog */ }
),
ExperienceCard(
logo = R.drawable.ic_launcher_foreground,
jobTitle = "Mobile Developer",
dates = "Jun ___ - Dec ___",
description = "Designed and built native Android apps ...",
onDescriptionClick = { /* Open detail dialog */ }
),
).forEach {
it
}
// See All button
Button(
modifier = Modifier.align(Alignment.CenterHorizontally),
onClick = { /* Show all experiences list/grid */ },
) {
Text("See All")
}
}
}
@Composable
fun EducationSection() {
Column(
modifier = Modifier.padding(16.dp),
) {
Text(
text = "Education",
fontSize = MaterialTheme.typography.bodyLarge.fontSize,
fontWeight = MaterialTheme.typography.bodyLarge.fontWeight,
)
listOf(
EducationCard(
institution = "Comsats University Islamabad",
degree = "Bachelor of Science in Software Engineering",
dates = "2017 - 2021",
description = "Studied...",
onDescriptionClick = { /* Open detail dialog */ }
),
EducationCard(
institution = "Collage",
degree = "Pre Engineering",
dates = "___",
description = "______...",
onDescriptionClick = { /* Open detail dialog */ }
),
).forEach {
it
}
Button(
modifier = Modifier.align(Alignment.CenterHorizontally),
onClick = { /* Show all education list/grid */ },
) {
Text("See All")
}
}
}
@Composable
fun ExperienceCard(
logo: Int,
jobTitle: String,
dates: String,
description: String,
onDescriptionClick: () -> Unit,
) {
Card(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth(),
) {
Row(
modifier = Modifier.padding(16.dp),
) {
// Company logo
Image(
painter = painterResource(id = logo),
contentDescription = "Company logo",
Modifier.size(52.dp)
)
// Job title and dates
Column(
modifier = Modifier
.padding(8.dp, 0.dp, 0.dp, 0.dp)
.weight(1f)
.align(Alignment.CenterVertically),
) {
Text(
text = jobTitle,
fontSize = MaterialTheme.typography.bodyMedium.fontSize,
fontWeight = MaterialTheme.typography.bodyMedium.fontWeight,
)
Text(
text = dates,
fontSize = MaterialTheme.typography.bodySmall.fontSize,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
)
}
}
}
}
@Composable
fun EducationCard(
institution: String,
degree: String,
dates: String,
description: String,
onDescriptionClick: () -> Unit,
) {
Card(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth(),
) {
Row(
modifier = Modifier.padding(16.dp),
) {
// Degree and dates
Column(
modifier = Modifier
.padding(8.dp, 0.dp, 0.dp, 0.dp)
.weight(1f),
) {
// Institution name
Text(
text = institution,
fontSize = MaterialTheme.typography.bodyLarge.fontSize,
fontWeight = MaterialTheme.typography.bodyLarge.fontWeight,
)
Text(
text = degree,
fontSize = MaterialTheme.typography.bodyMedium.fontSize,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
)
Text(
text = dates,
fontSize = MaterialTheme.typography.bodyMedium.fontSize,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
)
}
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun GreetingPreview() {
ComposablesTheme {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(8.dp)
) {
item {
TopSection()
}
item {
AboutSection()
}
item {
ExperienceSection()
}
item {
EducationSection()
}
}
}
} | Composables/app/src/main/java/sevenedge/pdfreader/filereader/composables/components/ProfileScreen.kt | 4246769131 |
package com.example.weatherapp
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.weatherapp", appContext.packageName)
}
} | WeatherAppAndroid/app/src/androidTest/java/com/example/weatherapp/ExampleInstrumentedTest.kt | 3556047590 |
package com.example.weatherapp
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | WeatherAppAndroid/app/src/test/java/com/example/weatherapp/ExampleUnitTest.kt | 2958330916 |
package com.example.weatherapp.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/ui/theme/Color.kt | 1126046537 |
package com.example.weatherapp.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun WeatherAppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/ui/theme/Theme.kt | 3206712740 |
package com.example.weatherapp.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/ui/theme/Type.kt | 714486850 |
package com.example.weatherapp
import android.net.http.HttpException
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.weatherapp.API.RetrofitInstance
import com.example.weatherapp.API.WeatherAPI
import com.example.weatherapp.API.Forecast
import com.example.weatherapp.ui.theme.WeatherAppTheme
import kotlinx.coroutines.runBlocking
import java.io.FileInputStream
import java.util.Properties
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DisplayWeatherData()
}
}
}
@Composable
fun DisplayWeatherData() {
val retrofitService = RetrofitInstance.getRetrofitInstance().create(WeatherAPI::class.java)
var forecast : Forecast?
runBlocking {
forecast = retrofitService.getForecastByCity("Rexburg").body()
}
val forecastState by remember {
mutableStateOf(forecast)
}
forecast?.timelines?.daily?.get(0)?.values?.temperatureAvg?.toString()?.let {
Text(text = "Temperature: $it")
}
} | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/MainActivity.kt | 2759567219 |
package com.example.weatherapp.API
import com.google.gson.annotations.SerializedName
data class Location (
@SerializedName("lat" ) var lat : Double? = null,
@SerializedName("lon" ) var lon : Double? = null,
@SerializedName("name" ) var name : String? = null,
@SerializedName("type" ) var type : String? = null
) | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/API/Location.kt | 401762397 |
package com.example.weatherapp.API
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
class RetrofitInstance {
companion object {
fun getRetrofitInstance(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://api.tomorrow.io/v4/weather/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
} | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/API/RetrofitInstance.kt | 2024945183 |
package com.example.weatherapp.API
import com.google.gson.annotations.SerializedName
data class Hourly (
@SerializedName("time" ) var time : String? = null,
@SerializedName("values" ) var values : Values? = Values()
) | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/API/Hourly.kt | 3264992816 |
package com.example.weatherapp.API
import com.google.gson.annotations.SerializedName
data class Timelines (
@SerializedName("minutely" ) var minutely : ArrayList<Minutely> = arrayListOf(),
@SerializedName("hourly" ) var hourly : ArrayList<Hourly> = arrayListOf(),
@SerializedName("daily" ) var daily : ArrayList<Daily> = arrayListOf()
) | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/API/Timelines.kt | 2508752115 |
package com.example.weatherapp.API
import com.google.gson.annotations.SerializedName
data class Daily (
@SerializedName("time" ) var time : String? = null,
@SerializedName("values" ) var values : Values? = Values()
) | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/API/Daily.kt | 1660630833 |
package com.example.weatherapp.API
import com.google.gson.annotations.SerializedName
data class Forecast (
@SerializedName("timelines" ) var timelines : Timelines? = Timelines(),
@SerializedName("location" ) var location : Location? = Location()
) | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/API/Forecast.kt | 2083299422 |
package com.example.weatherapp.API
import com.google.gson.annotations.SerializedName
data class Values (
@SerializedName("cloudBaseAvg" ) var cloudBaseAvg : Double? = null,
@SerializedName("cloudBaseMax" ) var cloudBaseMax : Double? = null,
@SerializedName("cloudBaseMin" ) var cloudBaseMin : Double? = null,
@SerializedName("cloudCeilingAvg" ) var cloudCeilingAvg : Double? = null,
@SerializedName("cloudCeilingMax" ) var cloudCeilingMax : Double? = null,
@SerializedName("cloudCeilingMin" ) var cloudCeilingMin : Double? = null,
@SerializedName("cloudCoverAvg" ) var cloudCoverAvg : Double? = null,
@SerializedName("cloudCoverMax" ) var cloudCoverMax : Double? = null,
@SerializedName("cloudCoverMin" ) var cloudCoverMin : Double? = null,
@SerializedName("dewPointAvg" ) var dewPointAvg : Double? = null,
@SerializedName("dewPointMax" ) var dewPointMax : Double? = null,
@SerializedName("dewPointMin" ) var dewPointMin : Double? = null,
@SerializedName("evapotranspirationAvg" ) var evapotranspirationAvg : Double? = null,
@SerializedName("evapotranspirationMax" ) var evapotranspirationMax : Double? = null,
@SerializedName("evapotranspirationMin" ) var evapotranspirationMin : Double? = null,
@SerializedName("evapotranspirationSum" ) var evapotranspirationSum : Double? = null,
@SerializedName("freezingRainIntensityAvg" ) var freezingRainIntensityAvg : Double? = null,
@SerializedName("freezingRainIntensityMax" ) var freezingRainIntensityMax : Double? = null,
@SerializedName("freezingRainIntensityMin" ) var freezingRainIntensityMin : Double? = null,
@SerializedName("humidityAvg" ) var humidityAvg : Double? = null,
@SerializedName("humidityMax" ) var humidityMax : Double? = null,
@SerializedName("humidityMin" ) var humidityMin : Double? = null,
@SerializedName("iceAccumulationAvg" ) var iceAccumulationAvg : Double? = null,
@SerializedName("iceAccumulationLweAvg" ) var iceAccumulationLweAvg : Double? = null,
@SerializedName("iceAccumulationLweMax" ) var iceAccumulationLweMax : Double? = null,
@SerializedName("iceAccumulationLweMin" ) var iceAccumulationLweMin : Double? = null,
@SerializedName("iceAccumulationLweSum" ) var iceAccumulationLweSum : Double? = null,
@SerializedName("iceAccumulationMax" ) var iceAccumulationMax : Double? = null,
@SerializedName("iceAccumulationMin" ) var iceAccumulationMin : Double? = null,
@SerializedName("iceAccumulationSum" ) var iceAccumulationSum : Double? = null,
@SerializedName("moonriseTime" ) var moonriseTime : String? = null,
@SerializedName("moonsetTime" ) var moonsetTime : String? = null,
@SerializedName("precipitationProbabilityAvg" ) var precipitationProbabilityAvg : Double? = null,
@SerializedName("precipitationProbabilityMax" ) var precipitationProbabilityMax : Double? = null,
@SerializedName("precipitationProbabilityMin" ) var precipitationProbabilityMin : Double? = null,
@SerializedName("pressureSurfaceLevelAvg" ) var pressureSurfaceLevelAvg : Double? = null,
@SerializedName("pressureSurfaceLevelMax" ) var pressureSurfaceLevelMax : Double? = null,
@SerializedName("pressureSurfaceLevelMin" ) var pressureSurfaceLevelMin : Double? = null,
@SerializedName("rainAccumulationAvg" ) var rainAccumulationAvg : Double? = null,
@SerializedName("rainAccumulationLweAvg" ) var rainAccumulationLweAvg : Double? = null,
@SerializedName("rainAccumulationLweMax" ) var rainAccumulationLweMax : Double? = null,
@SerializedName("rainAccumulationLweMin" ) var rainAccumulationLweMin : Double? = null,
@SerializedName("rainAccumulationMax" ) var rainAccumulationMax : Double? = null,
@SerializedName("rainAccumulationMin" ) var rainAccumulationMin : Double? = null,
@SerializedName("rainAccumulationSum" ) var rainAccumulationSum : Double? = null,
@SerializedName("rainIntensityAvg" ) var rainIntensityAvg : Double? = null,
@SerializedName("rainIntensityMax" ) var rainIntensityMax : Double? = null,
@SerializedName("rainIntensityMin" ) var rainIntensityMin : Double? = null,
@SerializedName("sleetAccumulationAvg" ) var sleetAccumulationAvg : Double? = null,
@SerializedName("sleetAccumulationLweAvg" ) var sleetAccumulationLweAvg : Double? = null,
@SerializedName("sleetAccumulationLweMax" ) var sleetAccumulationLweMax : Double? = null,
@SerializedName("sleetAccumulationLweMin" ) var sleetAccumulationLweMin : Double? = null,
@SerializedName("sleetAccumulationLweSum" ) var sleetAccumulationLweSum : Double? = null,
@SerializedName("sleetAccumulationMax" ) var sleetAccumulationMax : Double? = null,
@SerializedName("sleetAccumulationMin" ) var sleetAccumulationMin : Double? = null,
@SerializedName("sleetIntensityAvg" ) var sleetIntensityAvg : Double? = null,
@SerializedName("sleetIntensityMax" ) var sleetIntensityMax : Double? = null,
@SerializedName("sleetIntensityMin" ) var sleetIntensityMin : Double? = null,
@SerializedName("snowAccumulationAvg" ) var snowAccumulationAvg : Double? = null,
@SerializedName("snowAccumulationLweAvg" ) var snowAccumulationLweAvg : Double? = null,
@SerializedName("snowAccumulationLweMax" ) var snowAccumulationLweMax : Double? = null,
@SerializedName("snowAccumulationLweMin" ) var snowAccumulationLweMin : Double? = null,
@SerializedName("snowAccumulationLweSum" ) var snowAccumulationLweSum : Double? = null,
@SerializedName("snowAccumulationMax" ) var snowAccumulationMax : Double? = null,
@SerializedName("snowAccumulationMin" ) var snowAccumulationMin : Double? = null,
@SerializedName("snowAccumulationSum" ) var snowAccumulationSum : Double? = null,
@SerializedName("snowDepthAvg" ) var snowDepthAvg : Double? = null,
@SerializedName("snowDepthMax" ) var snowDepthMax : Double? = null,
@SerializedName("snowDepthMin" ) var snowDepthMin : Double? = null,
@SerializedName("snowDepthSum" ) var snowDepthSum : Double? = null,
@SerializedName("snowIntensityAvg" ) var snowIntensityAvg : Double? = null,
@SerializedName("snowIntensityMax" ) var snowIntensityMax : Double? = null,
@SerializedName("snowIntensityMin" ) var snowIntensityMin : Double? = null,
@SerializedName("sunriseTime" ) var sunriseTime : String? = null,
@SerializedName("sunsetTime" ) var sunsetTime : String? = null,
@SerializedName("temperatureApparentAvg" ) var temperatureApparentAvg : Double? = null,
@SerializedName("temperatureApparentMax" ) var temperatureApparentMax : Double? = null,
@SerializedName("temperatureApparentMin" ) var temperatureApparentMin : Double? = null,
@SerializedName("temperatureAvg" ) var temperatureAvg : Double? = null,
@SerializedName("temperatureMax" ) var temperatureMax : Double? = null,
@SerializedName("temperatureMin" ) var temperatureMin : Double? = null,
@SerializedName("uvHealthConcernAvg" ) var uvHealthConcernAvg : Double? = null,
@SerializedName("uvHealthConcernMax" ) var uvHealthConcernMax : Double? = null,
@SerializedName("uvHealthConcernMin" ) var uvHealthConcernMin : Double? = null,
@SerializedName("uvIndexAvg" ) var uvIndexAvg : Double? = null,
@SerializedName("uvIndexMax" ) var uvIndexMax : Double? = null,
@SerializedName("uvIndexMin" ) var uvIndexMin : Double? = null,
@SerializedName("visibilityAvg" ) var visibilityAvg : Double? = null,
@SerializedName("visibilityMax" ) var visibilityMax : Double? = null,
@SerializedName("visibilityMin" ) var visibilityMin : Double? = null,
@SerializedName("weatherCodeMax" ) var weatherCodeMax : Double? = null,
@SerializedName("weatherCodeMin" ) var weatherCodeMin : Double? = null,
@SerializedName("windDirectionAvg" ) var windDirectionAvg : Double? = null,
@SerializedName("windGustAvg" ) var windGustAvg : Double? = null,
@SerializedName("windGustMax" ) var windGustMax : Double? = null,
@SerializedName("windGustMin" ) var windGustMin : Double? = null,
@SerializedName("windSpeedAvg" ) var windSpeedAvg : Double? = null,
@SerializedName("windSpeedMax" ) var windSpeedMax : Double? = null,
@SerializedName("windSpeedMin" ) var windSpeedMin : Double? = null
) | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/API/Values.kt | 520935408 |
package com.example.weatherapp.API
import com.google.gson.annotations.SerializedName
data class Minutely (
@SerializedName("time" ) var time : String? = null,
@SerializedName("values" ) var values : Values? = Values()
) | WeatherAppAndroid/app/src/main/java/com/example/weatherapp/API/Minutely.kt | 1938126574 |
package com.example.weatherapp.API
import retrofit2.http.GET
import retrofit2.Response
import retrofit2.http.Path
import retrofit2.http.Query
interface WeatherAPI {
@GET("forecast?")
suspend fun getForecastByCity(
@Query("location")
city : String,
@Query("apikey")
apikey : String = "p7dA97aismeORMUUAMdpjnWT3uDzvsRW",
@Query("units")
units : String = "imperial"
) : Response<Forecast>
}
| WeatherAppAndroid/app/src/main/java/com/example/weatherapp/API/WeatherAPI.kt | 3359875065 |
package io.github.renegrob.gradle.plugin
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.util.PatternSet
abstract class CustomCopy() : Copy() {
@get:Input
val includeFilenames: ListProperty<String> = project.objects.listProperty(String::class.java)
@get:Input
val shouldCopyWrapper: Property<Boolean> = project.objects.property(Boolean::class.java)
init {
mainSpec.from("buildSrc") {
into("special")
include {
PatternSet().include(includeFilenames.get()).asSpec.isSatisfiedBy(it)
}
}
mainSpec.from(project.rootDir) {
into("wrapper")
include {
if (shouldCopyWrapper.get()) PatternSet().include("gradlew", "gradlew.bat").asSpec.isSatisfiedBy(it) else false
}
}
mainSpec.from("gradle") {
into("/wrapper/gradle")
include {
shouldCopyWrapper.get()
}
}
}
} | gradle-kotlin-buildsrc/buildSrc/src/main/kotlin/io/github/renegrob/gradle/plugin/CustomCopy.kt | 1384618472 |
package io.github.renegrob.gradle.plugin;
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.provider.Property
interface ExamplePluginExtension {
val message: Property<String>
}
class ExamplePlugin : Plugin<Project> {
override fun apply(project: Project) {
// Add the 'greeting' extension object
val extension = project.extensions.create("example", ExamplePluginExtension::class.java)
// Add a task that uses configuration from the extension object
project.task("example") {
doLast {
println(extension.message.get())
}
}
}
}
| gradle-kotlin-buildsrc/buildSrc/src/main/kotlin/io/github/renegrob/gradle/plugin/ExamplePlugin.kt | 498673650 |
package com.keak.composeinstagramstory
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.keak.composeinstagramstory", appContext.packageName)
}
} | compose-instagram-story/app/src/androidTest/java/com/keak/composeinstagramstory/ExampleInstrumentedTest.kt | 1947224056 |
package com.keak.composeinstagramstory
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | compose-instagram-story/app/src/test/java/com/keak/composeinstagramstory/ExampleUnitTest.kt | 3154040792 |
package com.keak.composeinstagramstory.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | compose-instagram-story/app/src/main/java/com/keak/composeinstagramstory/ui/theme/Color.kt | 4243321057 |
package com.keak.composeinstagramstory.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun ComposeInstagramStoryTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | compose-instagram-story/app/src/main/java/com/keak/composeinstagramstory/ui/theme/Theme.kt | 3693503613 |
package com.keak.composeinstagramstory.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | compose-instagram-story/app/src/main/java/com/keak/composeinstagramstory/ui/theme/Type.kt | 2132956717 |
package com.keak.composeinstagramstory
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.keak.composeinstagramstory.ui.theme.ComposeInstagramStoryTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
ComposeInstagramStoryTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Greeting(
name = "Android",
modifier = Modifier.padding(innerPadding)
)
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
ComposeInstagramStoryTheme {
Greeting("Android")
}
}
} | compose-instagram-story/app/src/main/java/com/keak/composeinstagramstory/MainActivity.kt | 4042395728 |
package com.keak.instagramstory
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.keak.instagramstory.test", appContext.packageName)
}
} | compose-instagram-story/instagramstory/src/androidTest/java/com/keak/instagramstory/ExampleInstrumentedTest.kt | 435562726 |
package com.keak.instagramstory
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | compose-instagram-story/instagramstory/src/test/java/com/keak/instagramstory/ExampleUnitTest.kt | 3880561741 |
package com.keak.instagramstory
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationVector1D
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun InstagramSlicedProgressBar(
modifier: Modifier = Modifier,
steps: Int,
currentStep: Int,
paused: Boolean,
onFinished: () -> Unit,
beforeDurationEnd: () -> Unit,
percent: Animatable<Float, AnimationVector1D>
) {
LaunchedEffect(currentStep, paused) {
if (paused.not()) {
percent.animateTo(
targetValue = 1f,
animationSpec = tween(
durationMillis = (8000 * (1f - percent.value)).toInt(),
easing = LinearEasing
)
) {
//before time end
if (value in 0.80f..0.90f) {
beforeDurationEnd.invoke()
}
}
if (percent.value == 1f) {
onFinished()
}
}
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier,
) {
for (index in 1..steps) {
Row(
modifier = Modifier
.height(4.dp)
.clip(RoundedCornerShape(50, 50, 50, 50))
.weight(1f)
.background(Color.White.copy(alpha = 0.4f))
) {
Box(
modifier = Modifier
.background(Color.Red)
.fillMaxHeight()
.let {
when (index) {
currentStep -> it.fillMaxWidth(percent.value)
in 0..currentStep -> it.fillMaxWidth(1f)
else -> it
}
},
) {}
}
if (index != steps) {
Spacer(modifier = Modifier.width(4.dp))
}
}
}
}
| compose-instagram-story/instagramstory/src/main/java/com/keak/instagramstory/SlicedProgressBar.kt | 3982957274 |
package com.keak.instagramstory
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerDefaults
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun InstagramStory(
modifier: Modifier = Modifier,
imageList: List<String>,
screenDuration: Long = 4000,
durationEnd: () -> Unit = {},
beforeDurationEnd: () -> Unit = {},
content: @Composable (page: Int) -> Unit,
) {
var currentStep by remember { mutableIntStateOf(0) }
var paused by remember {
mutableStateOf(false)
}
val isPressed = remember { mutableStateOf(false) }
val pagerState = rememberPagerState(
pageCount = { imageList.size },
)
val percent = remember { Animatable(0f) }
val scope = rememberCoroutineScope()
LaunchedEffect(key1 = pagerState.currentPage) {
percent.snapTo(0f)
currentStep = pagerState.currentPage + 1
delay(screenDuration) // Screen duration
}
Column(modifier = modifier
.fillMaxSize()
.pointerInput(Unit) {
val maxWidth = this.size.width
detectTapGestures(
onPress = {
val pressStartTime = System.currentTimeMillis()
isPressed.value = true
this.tryAwaitRelease()
paused = false
val pressEndTime = System.currentTimeMillis()
val totalPressTime = pressEndTime - pressStartTime
if (totalPressTime < 200) {
val isTapOnRightThreeQuarters = (it.x > (maxWidth / 4))
if (isTapOnRightThreeQuarters) {
if ((currentStep >= imageList.size).not()) {
currentStep = pagerState.currentPage + 1
pagerState.animateScrollToPage(currentStep)
}
} else {
if ((currentStep <= 1).not()) {
currentStep = pagerState.currentPage - 1
pagerState.animateScrollToPage(currentStep)
}
}
}
isPressed.value = false
},
onLongPress = {
paused = true
}
)
}) {
Box(modifier = Modifier.fillMaxSize()) {
Spacer(modifier = Modifier.height(8.dp))
InstagramSlicedProgressBar(
modifier = Modifier
.height(48.dp)
.padding(24.dp, 0.dp)
.zIndex(2f),
steps = imageList.size,
currentStep = currentStep,
paused = paused,
onFinished = {
durationEnd.invoke()
scope.launch {
if ((currentStep >= imageList.size).not()) {
pagerState.animateScrollToPage(currentStep)
}
}
},
beforeDurationEnd = {
beforeDurationEnd.invoke()
},
percent = percent
)
HorizontalPager(
state = pagerState,
modifier = Modifier.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically,
userScrollEnabled = false,
pageNestedScrollConnection = PagerDefaults.pageNestedScrollConnection(
orientation = Orientation.Horizontal
)
) { page ->
content.invoke(page)
}
}
}
}
| compose-instagram-story/instagramstory/src/main/java/com/keak/instagramstory/InstagramStory.kt | 3009159915 |
package com.base.meddueducationproject
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.base.meddueducationproject", appContext.packageName)
}
} | Login_Register_RoomDB/app/src/androidTest/java/com/base/meddueducationproject/ExampleInstrumentedTest.kt | 3025242150 |
package com.base.meddueducationproject
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Login_Register_RoomDB/app/src/test/java/com/base/meddueducationproject/ExampleUnitTest.kt | 85602669 |
package com.base.meddueducationproject.data.repository
import android.util.Log
import androidx.lifecycle.LiveData
import com.base.meddueducationproject.data.roomdb.MedduDatabaseDao
import com.base.meddueducationproject.data.roomdb.MedduEntity
class MedduRepository(private val dao: MedduDatabaseDao) {
fun getUser(email: String, password: String): LiveData<List<MedduEntity>> {
return dao.getUser(email, password)
}
fun getUserByEmail(email: String): LiveData<List<MedduEntity>> {
return dao.getUserByEmail(email)
}
val users = dao.getAllUsers()
suspend fun insert(user: MedduEntity) {
return dao.insert(user)
}
suspend fun getUserName(userName: String):MedduEntity?{
Log.i("MYTAG", "inside Repository Getusers fun ")
return dao.getUsername(userName)
}
} | Login_Register_RoomDB/app/src/main/java/com/base/meddueducationproject/data/repository/MedduRepository.kt | 464637571 |
package com.base.meddueducationproject.data.roomdb
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface MedduDatabaseDao {
@Insert
suspend fun insert(entity: MedduEntity)
@Query("SELECT * FROM Register_users_table ORDER BY user_id ASC")
fun getAllUsers(): LiveData<List<MedduEntity>>
@Query("SELECT * FROM Register_users_table WHERE email LIKE :email AND password LIKE :password")
fun getUser(email: String, password: String): LiveData<List<MedduEntity>>
@Query("SELECT * FROM Register_users_table WHERE email LIKE :email")
fun getUserByEmail(email: String): LiveData<List<MedduEntity>>
@Query("SELECT * FROM Register_users_table WHERE user_name LIKE :userName")
suspend fun getUsername(userName: String): MedduEntity?
} | Login_Register_RoomDB/app/src/main/java/com/base/meddueducationproject/data/roomdb/MedduDatabaseDao.kt | 2489248953 |
package com.base.meddueducationproject.data.roomdb
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "Register_users_table")
data class MedduEntity(
@ColumnInfo(name = "user_id", typeAffinity = ColumnInfo.INTEGER)
@PrimaryKey(autoGenerate = true)
var userId: Int = 0,
@ColumnInfo(name = "user_name", typeAffinity = ColumnInfo.TEXT)
var userName: String,
@ColumnInfo(name = "mobile", typeAffinity = ColumnInfo.TEXT)
var mobile: String,
@ColumnInfo(name = "email", typeAffinity = ColumnInfo.TEXT)
var email: String,
@ColumnInfo(name = "password", typeAffinity = ColumnInfo.TEXT)
var password: String
) | Login_Register_RoomDB/app/src/main/java/com/base/meddueducationproject/data/roomdb/MedduEntity.kt | 3208119408 |
package com.base.meddueducationproject.data.roomdb
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [MedduEntity::class], version = 1, exportSchema = false)
abstract class MedduDatabase : RoomDatabase() {
abstract val registerDatabaseDao: MedduDatabaseDao
companion object {
@Volatile
private var INSTANCE: MedduDatabase? = null
fun getInstance(context: Context): MedduDatabase {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = Room.databaseBuilder(
context,
MedduDatabase::class.java,
"user_details_database"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
}
return instance
}
}
}
}
| Login_Register_RoomDB/app/src/main/java/com/base/meddueducationproject/data/roomdb/MedduDatabase.kt | 4266113297 |
package com.base.meddueducationproject.data.model
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class UserList(
var name: String,
var mobileNumber: Int,
var email: String
) : Parcelable
| Login_Register_RoomDB/app/src/main/java/com/base/meddueducationproject/data/model/UserList.kt | 654112455 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.