content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.serv1 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.serv1", appContext.packageName) } }
mobil_kursach/app/src/androidTest/java/com/example/serv1/ExampleInstrumentedTest.kt
2018236655
package com.example.serv1 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) } }
mobil_kursach/app/src/test/java/com/example/serv1/ExampleUnitTest.kt
808141998
package com.example.serv1 import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class CustomAdapterHistoryRecord(private val context: Context, val mList: ArrayList<HistoryRecord>) : RecyclerView.Adapter<CustomAdapterHistoryRecord.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapterHistoryRecord.ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.history_record_card, parent, false) return ViewHolder(view) } // binds the list items to a view override fun onBindViewHolder(holder: ViewHolder, position: Int) { val record = mList[position] holder.idView.text = (position+1).toString() holder.timeView.text = record.currentTime holder.diseaseView.text = record.disease holder.accuracyView.text = record.accuracy } override fun getItemCount(): Int { return mList.size } class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) { val idView: TextView = itemView.findViewById(R.id.id) val timeView: TextView = itemView.findViewById(R.id.time) val diseaseView: TextView = itemView.findViewById(R.id.disease) val accuracyView: TextView = itemView.findViewById(R.id.accuracy) } }
mobil_kursach/app/src/main/java/com/example/serv1/CustomAdapterHistoryRecord.kt
909894705
package com.example.serv1 import android.Manifest import android.annotation.SuppressLint import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.Settings import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.serv1.databinding.ActivityMainBinding import com.google.android.material.tabs.TabLayoutMediator import okhttp3.* private const val STORAGE_PERMISSION_CODE = 23 class MainActivity : AppCompatActivity() { private lateinit var adapter: ViewPagerAdapter private var _binding: ActivityMainBinding? = null private val binding get() = requireNotNull(_binding) private val tabTitles = arrayOf( "Главная", "История", "Справка" ) private val storageActivityResultLauncher: ActivityResultLauncher<Intent> = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { //Android is 11 (R) or above if (Environment.isExternalStorageManager()) { //Manage External Storage Permissions Granted } else { Toast.makeText( this@MainActivity, "Storage Permissions Denied", Toast.LENGTH_SHORT ).show() } } else { //Below android 11 } } @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater, null, false) setContentView(binding.root) adapter = ViewPagerAdapter(supportFragmentManager, lifecycle) binding.viewPager.adapter = adapter TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position -> tab.text = tabTitles[position] }.attach() if (!checkStoragePermissions()) { requestForStoragePermissions() } } private fun checkStoragePermissions(): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { //Android is 11 (R) or above Environment.isExternalStorageManager() } else { //Below android 11 val write = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) val read = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) read == PackageManager.PERMISSION_GRANTED && write == PackageManager.PERMISSION_GRANTED } } private fun requestForStoragePermissions() { //Android is 11 (R) or above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { try { val intent = Intent() intent.action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION val uri = Uri.fromParts("package", this.packageName, null) intent.data = uri storageActivityResultLauncher.launch(intent) } catch (e: Exception) { val intent = Intent() intent.action = Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION storageActivityResultLauncher.launch(intent) } } else { //Below android 11 ActivityCompat.requestPermissions( this, arrayOf( Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE ), STORAGE_PERMISSION_CODE ) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == STORAGE_PERMISSION_CODE) { if (grantResults.isNotEmpty()) { val write = grantResults[0] == PackageManager.PERMISSION_GRANTED val read = grantResults[1] == PackageManager.PERMISSION_GRANTED if (read && write) { Toast.makeText( this@MainActivity, "Storage Permissions Granted", Toast.LENGTH_SHORT ).show() } else { Toast.makeText( this@MainActivity, "Storage Permissions Denied", Toast.LENGTH_SHORT ).show() } } } } }
mobil_kursach/app/src/main/java/com/example/serv1/MainActivity.kt
199239976
package com.example.serv1 import android.content.SharedPreferences class HistoryRecords() { var list= arrayListOf<HistoryRecord>() fun save(preferences: SharedPreferences) { // сохраняем общее количество preferences.edit().putInt("N",list.size).apply(); (0..list.size-1).forEach{ preferences.edit().putString(Integer.toString(it)+"currentTime",list[it].currentTime).apply() preferences.edit().putString(Integer.toString(it)+"disease",list[it].disease).apply() preferences.edit().putString(Integer.toString(it)+"accuracy",list[it].accuracy).apply() preferences.edit().putString(Integer.toString(it)+"photoPath",list[it].photoPath).apply() } } fun load(preferences: SharedPreferences) { list.clear(); val n = preferences.getInt("N",0) (0..n-1).forEach{ val currentTime= preferences.getString(Integer.toString(it)+"currentTime","") val disease = preferences.getString(Integer.toString(it)+"disease","") val accuracy =preferences.getString(Integer.toString(it)+"accuracy","") val photoPath=preferences.getString(Integer.toString(it)+"photoPath","") list.add(HistoryRecord(currentTime!!,disease!!,accuracy!!,photoPath!!)) } } }
mobil_kursach/app/src/main/java/com/example/serv1/HistoryRecords.kt
3466242417
package com.example.serv1 import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.viewpager2.adapter.FragmentStateAdapter private const val NUM_TABS = 3 class ViewPagerAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) : FragmentStateAdapter(fragmentManager, lifecycle) { override fun getItemCount(): Int = NUM_TABS override fun createFragment(position: Int): Fragment = when (position) { 0 -> MainFragment() 1 -> HistoryFragment() 2 -> HelpFragment() else -> error("wrong fragment") } }
mobil_kursach/app/src/main/java/com/example/serv1/ViewPagerAdapter.kt
3031937078
package com.example.serv1 import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.example.serv1.databinding.FragmentHistoryBinding class HistoryFragment : Fragment(R.layout.fragment_history) { private var _binding: FragmentHistoryBinding? = null private val binding get() = requireNotNull(_binding) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentHistoryBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val records = HistoryRecords() val preferences = PreferenceManager.getDefaultSharedPreferences(this.requireContext()) records.load(preferences) val rvHistory = binding.rvHistory val adapterRv = CustomAdapterHistoryRecord(this.requireContext(), records.list) rvHistory.adapter = adapterRv } }
mobil_kursach/app/src/main/java/com/example/serv1/HistoryFragment.kt
4215619593
package com.example.serv1 import java.time.LocalDateTime class HistoryRecord(val currentTime: String, val disease: String,val accuracy: String,val photoPath:String) { }
mobil_kursach/app/src/main/java/com/example/serv1/HistoryRecord.kt
697461914
package com.example.serv1 import androidx.fragment.app.Fragment class HelpFragment : Fragment(R.layout.fragment_help) { }
mobil_kursach/app/src/main/java/com/example/serv1/HelpFragment.kt
3742525030
package com.example.serv1 import android.annotation.SuppressLint import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager import com.example.serv1.databinding.FragmentMainBinding import com.google.gson.Gson import okhttp3.Call import okhttp3.Callback import okhttp3.MediaType.Companion.toMediaType import okhttp3.MultipartBody import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.Response import java.io.File import java.io.FileOutputStream import java.io.IOException import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.concurrent.TimeUnit private const val PICK_IMAGE_REQUEST = 1 class MainFragment : Fragment() { private var _binding: FragmentMainBinding? = null private val binding get() = requireNotNull(_binding) private lateinit var selectedImageFile: File override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentMainBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.btnPickPhoto.setOnClickListener { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(intent, PICK_IMAGE_REQUEST) binding.tvResult.text="" } binding.btnTakePhoto.setOnClickListener { dispatchTakePictureIntent() binding.tvResult.text="" } binding.btnAnalysePhoto.setOnClickListener { if (::selectedImageFile.isInitialized) { uploadImage(selectedImageFile) binding.tvResult.text="Идёт анализ фото" } else { Toast.makeText(context, "Выберите фото из галереи", Toast.LENGTH_SHORT).show() } } } private fun dispatchTakePictureIntent() { Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent -> takePictureIntent.resolveActivity(activity?.packageManager!!)?.also { startActivityForResult(takePictureIntent, Companion.REQUEST_IMAGE_CAPTURE) } } } @Deprecated("Deprecated in Java") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { PICK_IMAGE_REQUEST -> { if (resultCode == AppCompatActivity.RESULT_OK && data != null && data.data != null) { val filePathColumn = arrayOf(MediaStore.Images.Media.DATA) val cursor = activity?.contentResolver?.query(data.data!!, filePathColumn, null, null, null) cursor?.moveToFirst() val columnIndex = cursor?.getColumnIndex(filePathColumn[0]) val picturePath = cursor?.getString(columnIndex!!) cursor?.close() selectedImageFile = File(picturePath!!) if (selectedImageFile.exists()) { binding.ivPhoto.setImageURI(Uri.fromFile(selectedImageFile)) } } } REQUEST_IMAGE_CAPTURE -> { if (resultCode == AppCompatActivity.RESULT_OK && data != null) { val imageBitmap = data.extras?.get("data") as Bitmap val tempFile = createTempImageFile() saveBitmapToFile(imageBitmap, tempFile) selectedImageFile = tempFile binding.ivPhoto.setImageBitmap(imageBitmap) } } } } private fun createTempImageFile(): File { return File.createTempFile( "temp_image", ".jpg", activity?.externalCacheDir ) } private fun saveBitmapToFile(bitmap: Bitmap, file: File) { try { FileOutputStream(file).use { out -> bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out) } } catch (e: IOException) { e.printStackTrace() } } private fun uploadImage(imageFile: File) { val preferences = PreferenceManager.getDefaultSharedPreferences(this.requireContext()) val client = OkHttpClient.Builder() .connectTimeout(100, TimeUnit.SECONDS) // Установить таймаут подключения. .readTimeout(100, TimeUnit.SECONDS) // Установить таймаут чтения. .writeTimeout(100, TimeUnit.SECONDS) // Установить таймаут записи. .build() val requestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart( "image", imageFile.name, imageFile.asRequestBody("image/*".toMediaType()) ) .addFormDataPart( "name", imageFile.name, ) .build() val request = Request.Builder() .url("http://127.0.0.1:8000/api/image") .post(requestBody) .build() val responseCallback = object : Callback { @SuppressLint("SetTextI18n") override fun onFailure(call: Call, e: IOException) { e.printStackTrace() activity?.runOnUiThread { binding.tvResult.text = "Ошибка при отправке фото: ${e.message}" } } override fun onResponse(call: Call, response: Response) { val responseData = response.body?.string() activity?.runOnUiThread { if (responseData != null) { val gson = Gson() val imageInfo = gson.fromJson(responseData, ImageInfo::class.java) val historyRecords = HistoryRecords() binding.tvResult.text = "Вероятность: ${imageInfo.accuracy}\nБолезнь: ${imageInfo.disease}" // val newYorkDateTimePattern = "dd.MM.yyyy HH:mm z" // val formatter= DateTimeFormatter.ofPattern(newYorkDateTimePattern) val time= LocalDateTime.now().toString() historyRecords.list.add(HistoryRecord(time,imageInfo.disease,imageInfo.accuracy,selectedImageFile.path.toString())) historyRecords.save(preferences) } else { binding.tvResult.text = "Пустой ответ от сервера" } } } } client.newCall(request).enqueue(responseCallback) val thread = Thread { try { val response = client.newCall(request).execute() response.use { // responseCallback.onResponse(call, response) } } catch (e: IOException) { // responseCallback.onFailure(call, e) } } thread.start() } companion object { private const val REQUEST_IMAGE_CAPTURE = 2 } }
mobil_kursach/app/src/main/java/com/example/serv1/MainFragment.kt
1185162638
package com.example.serv1 import com.google.gson.annotations.SerializedName data class ImageInfo( @SerializedName("accuracy ") val accuracy: String, val disease: String )
mobil_kursach/app/src/main/java/com/example/serv1/ImageInfo.kt
1697454418
package com.example.serv1 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.serv1", appContext.packageName) } }
mobil_kursach/src/androidTest/java/com/example/serv1/ExampleInstrumentedTest.kt
2018236655
package com.example.serv1 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) } }
mobil_kursach/src/test/java/com/example/serv1/ExampleUnitTest.kt
808141998
package com.example.serv1 import android.Manifest import android.annotation.SuppressLint import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.Settings import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.serv1.databinding.ActivityMainBinding import com.google.android.material.tabs.TabLayoutMediator import okhttp3.* private const val STORAGE_PERMISSION_CODE = 23 class MainActivity : AppCompatActivity() { private lateinit var adapter: ViewPagerAdapter private var _binding: ActivityMainBinding? = null private val binding get() = requireNotNull(_binding) private val tabTitles = arrayOf( "Главная", "История", "Справка" ) private val storageActivityResultLauncher: ActivityResultLauncher<Intent> = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { //Android is 11 (R) or above if (Environment.isExternalStorageManager()) { //Manage External Storage Permissions Granted } else { Toast.makeText( this@MainActivity, "Storage Permissions Denied", Toast.LENGTH_SHORT ).show() } } else { //Below android 11 } } @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityMainBinding.inflate(layoutInflater, null, false) setContentView(binding.root) adapter = ViewPagerAdapter(supportFragmentManager, lifecycle) binding.viewPager.adapter = adapter TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position -> tab.text = tabTitles[position] }.attach() if (!checkStoragePermissions()) { requestForStoragePermissions() } } private fun checkStoragePermissions(): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { //Android is 11 (R) or above Environment.isExternalStorageManager() } else { //Below android 11 val write = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) val read = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) read == PackageManager.PERMISSION_GRANTED && write == PackageManager.PERMISSION_GRANTED } } private fun requestForStoragePermissions() { //Android is 11 (R) or above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { try { val intent = Intent() intent.action = Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION val uri = Uri.fromParts("package", this.packageName, null) intent.data = uri storageActivityResultLauncher.launch(intent) } catch (e: Exception) { val intent = Intent() intent.action = Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION storageActivityResultLauncher.launch(intent) } } else { //Below android 11 ActivityCompat.requestPermissions( this, arrayOf( Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE ), STORAGE_PERMISSION_CODE ) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == STORAGE_PERMISSION_CODE) { if (grantResults.isNotEmpty()) { val write = grantResults[0] == PackageManager.PERMISSION_GRANTED val read = grantResults[1] == PackageManager.PERMISSION_GRANTED if (read && write) { Toast.makeText( this@MainActivity, "Storage Permissions Granted", Toast.LENGTH_SHORT ).show() } else { Toast.makeText( this@MainActivity, "Storage Permissions Denied", Toast.LENGTH_SHORT ).show() } } } } }
mobil_kursach/src/main/java/com/example/serv1/MainActivity.kt
199239976
package com.example.serv1 import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.viewpager2.adapter.FragmentStateAdapter private const val NUM_TABS = 3 class ViewPagerAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) : FragmentStateAdapter(fragmentManager, lifecycle) { override fun getItemCount(): Int = NUM_TABS override fun createFragment(position: Int): Fragment = when (position) { 0 -> MainFragment() 1 -> HistoryFragment() 2 -> HelpFragment() else -> error("wrong fragment") } }
mobil_kursach/src/main/java/com/example/serv1/ViewPagerAdapter.kt
3031937078
package com.example.serv1 import androidx.fragment.app.Fragment class HistoryFragment : Fragment(R.layout.fragment_history) { }
mobil_kursach/src/main/java/com/example/serv1/HistoryFragment.kt
2512984150
package com.example.serv1 import androidx.fragment.app.Fragment class HelpFragment : Fragment(R.layout.fragment_help) { }
mobil_kursach/src/main/java/com/example/serv1/HelpFragment.kt
3742525030
package com.example.serv1 import android.R import android.annotation.SuppressLint import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import com.example.serv1.databinding.FragmentMainBinding import com.google.gson.Gson import com.google.gson.annotations.SerializedName import okhttp3.Call import okhttp3.Callback import okhttp3.MediaType.Companion.toMediaType import okhttp3.MultipartBody import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.Response import java.io.File import java.io.FileOutputStream import java.io.IOException import java.util.concurrent.TimeUnit private const val PICK_IMAGE_REQUEST = 1 class MainFragment : Fragment() { private var _binding: FragmentMainBinding? = null private val binding get() = requireNotNull(_binding) private lateinit var selectedImageFile: File override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentMainBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.btnPickPhoto.setOnClickListener { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(intent, PICK_IMAGE_REQUEST) binding.tvResult.text="" } binding.btnTakePhoto.setOnClickListener { dispatchTakePictureIntent() binding.tvResult.text="" } binding.btnAnalysePhoto.setOnClickListener { if (::selectedImageFile.isInitialized) { uploadImage(selectedImageFile) binding.tvResult.text="Идёт анализ фото" } else { Toast.makeText(context, "Выберите фото из галереи", Toast.LENGTH_SHORT).show() } } } private fun dispatchTakePictureIntent() { Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent -> takePictureIntent.resolveActivity(activity?.packageManager!!)?.also { startActivityForResult(takePictureIntent, Companion.REQUEST_IMAGE_CAPTURE) } } } @Deprecated("Deprecated in Java") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { PICK_IMAGE_REQUEST -> { if (resultCode == AppCompatActivity.RESULT_OK && data != null && data.data != null) { val filePathColumn = arrayOf(MediaStore.Images.Media.DATA) val cursor = activity?.contentResolver?.query(data.data!!, filePathColumn, null, null, null) cursor?.moveToFirst() val columnIndex = cursor?.getColumnIndex(filePathColumn[0]) val picturePath = cursor?.getString(columnIndex!!) cursor?.close() selectedImageFile = File(picturePath!!) if (selectedImageFile.exists()) { binding.ivPhoto.setImageURI(Uri.fromFile(selectedImageFile)) } } } REQUEST_IMAGE_CAPTURE -> { if (resultCode == AppCompatActivity.RESULT_OK && data != null) { val imageBitmap = data.extras?.get("data") as Bitmap val tempFile = createTempImageFile() saveBitmapToFile(imageBitmap, tempFile) selectedImageFile = tempFile binding.ivPhoto.setImageBitmap(imageBitmap) } } } } private fun createTempImageFile(): File { return File.createTempFile( "temp_image", ".jpg", activity?.externalCacheDir ) } private fun saveBitmapToFile(bitmap: Bitmap, file: File) { try { FileOutputStream(file).use { out -> bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out) } } catch (e: IOException) { e.printStackTrace() } } private fun uploadImage(imageFile: File) { val client = OkHttpClient.Builder() .connectTimeout(100, TimeUnit.SECONDS) // Установить таймаут подключения. .readTimeout(100, TimeUnit.SECONDS) // Установить таймаут чтения. .writeTimeout(100, TimeUnit.SECONDS) // Установить таймаут записи. .build() val requestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart( "image", imageFile.name, imageFile.asRequestBody("image/*".toMediaType()) ) .addFormDataPart( "name", imageFile.name, ) .build() val request = Request.Builder() .url("http://127.0.0.1:8000/api/image") .post(requestBody) .build() val responseCallback = object : Callback { @SuppressLint("SetTextI18n") override fun onFailure(call: Call, e: IOException) { e.printStackTrace() activity?.runOnUiThread { binding.tvResult.text = "Ошибка при отправке фото: ${e.message}" } } override fun onResponse(call: Call, response: Response) { val responseData = response.body?.string() activity?.runOnUiThread { if (responseData != null) { val gson = Gson() val imageInfo = gson.fromJson(responseData, ImageInfo::class.java) binding.tvResult.text = "Вероятность: ${imageInfo.accuracy}\nБолезнь: ${imageInfo.disease}" } else { binding.tvResult.text = "Пустой ответ от сервера" } } } } client.newCall(request).enqueue(responseCallback) val thread = Thread { try { val response = client.newCall(request).execute() response.use { // responseCallback.onResponse(call, response) } } catch (e: IOException) { // responseCallback.onFailure(call, e) } } thread.start() } companion object { private const val REQUEST_IMAGE_CAPTURE = 2 } }
mobil_kursach/src/main/java/com/example/serv1/MainFragment.kt
1191160178
package com.example.serv1 import com.google.gson.annotations.SerializedName data class ImageInfo( @SerializedName("accuracy ") val accuracy: String, val disease: String )
mobil_kursach/src/main/java/com/example/serv1/ImageInfo.kt
1697454418
package com.example.fitnesshub 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.fitnesshub", appContext.packageName) } }
fitnessHub/app/src/androidTest/java/com/example/fitnesshub/ExampleInstrumentedTest.kt
964096440
package com.example.fitnesshub 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) } }
fitnessHub/app/src/test/java/com/example/fitnesshub/ExampleUnitTest.kt
2457178146
package com.example.fitnesshub import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.google.android.material.bottomnavigation.BottomNavigationView class Aprofile : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_aprofile) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) bottomNavigationView.setSelectedItemId(R.id.bottom_profile) bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.bottom_home -> { startActivity(Intent(this, Ahome::class.java)) overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) // Handle home item selection true // Return true to consume the event } R.id.bottom_event -> { // Start the Event activity with animation startActivity(Intent(this, Aevent::class.java)) overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) true // Return true to consume the event } R.id.bottom_profile -> { // Start the Profile activity with animation true // Return true to consume the event } else -> false // Return false to allow default selection } } } }
fitnessHub/app/src/main/java/com/example/fitnesshub/Aprofile.kt
1067716191
package com.example.fitnesshub import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView class fitness(private val context: Context, private var fitnessDataList: List<FitnessData>) : RecyclerView.Adapter<fitness.FitnessViewHolder>() { private lateinit var listener: fitness.OnItemClickListener inner class FitnessViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView){ val logo:ImageView = itemView.findViewById(R.id.logoUthm) val title: TextView = itemView.findViewById(R.id.titleUthm) } fun setFilteredList(mlist: List<FitnessData>){ this.fitnessDataList=mlist notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FitnessViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.each_item, parent, false) val holder = FitnessViewHolder(view) // قم بتوصيل مستمع النقرات باستخدام السياق الصحيح holder.itemView.setOnClickListener { onItemClick(holder) } return holder } fun onItemClick(holder: FitnessViewHolder) { // startActivity(Intent(context, Aevent::class.java)) val nextActivity = Aevent::class.java val intent = Intent(context, nextActivity) ContextCompat.startActivity(context, intent, null) // استخدم السياق الصحيح } override fun getItemCount(): Int { return fitnessDataList.size } override fun onBindViewHolder(holder: FitnessViewHolder, position: Int) { holder.logo.setImageResource(fitnessDataList[position].logo) holder.title.text = fitnessDataList[position].title } fun setOnItemClickListener(listener: OnItemClickListener) { this.listener = listener } interface OnItemClickListener { fun onItemClick(fitnessData: FitnessData) } fun onItemClick(holder: FitnessViewHolder, position: Int) { val fitnessData = fitnessDataList[position] // اتصل بالمستمع listener?.onItemClick(fitnessData) } }
fitnessHub/app/src/main/java/com/example/fitnesshub/fitness.kt
197436241
package com.example.fitnesshub import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.fragment.app.Fragment import com.example.fitnesshub.databinding.ActivityMainBinding import com.google.android.material.bottomnavigation.BottomNavigationView class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding=ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // replaceFragment(Home()) // binding.bottomNavigationView.setOnItemSelectedListener { // // when(it.itemId){ // R.id.home -> replaceFragment(Home()) // R.id.profile -> replaceFragment(Event()) // R.id.event -> replaceFragment(Profile()) // // else ->{ // // } // } // true // } } // private fun replaceFragment(fragment :Fragment){ // val fragmentManager=supportFragmentManager // val fragmentTransaction=fragmentManager.beginTransaction() // fragmentTransaction.replace(R.id.frame_layout,fragment) // // fragmentTransaction.commit() // // } }
fitnessHub/app/src/main/java/com/example/fitnesshub/MainActivity.kt
2631853391
package com.example.fitnesshub data class FitnessData(val title: String, val logo : Int,val nextActivity: Class<*> )
fitnessHub/app/src/main/java/com/example/fitnesshub/FitnessData.kt
3574987774
package com.example.fitnesshub import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ImageView import android.widget.Toast import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomnavigation.BottomNavigationView import java.util.Locale class Ahome : AppCompatActivity() { private lateinit var recyclerView: RecyclerView private lateinit var searchView: SearchView private var mlist = ArrayList<FitnessData>() private lateinit var adapter: fitness override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_ahome) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) bottomNavigationView.setSelectedItemId(R.id.bottom_home) bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.bottom_home -> { // Handle home item selection true // Return true to consume the event } R.id.bottom_event -> { // Start the Event activity with animation startActivity(Intent(this, Aevent::class.java)) overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) true // Return true to consume the event } R.id.bottom_profile -> { // Start the Profile activity with animation startActivity(Intent(this, Aprofile::class.java)) overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) true // Return true to consume the event } else -> false // Return false to allow default selection } } recyclerView = findViewById(R.id.recyclerView) searchView = findViewById(R.id.searchHer) recyclerView.setHasFixedSize(true) recyclerView.layoutManager = LinearLayoutManager(this) addDataToList() adapter = fitness(this, mlist) recyclerView.adapter=adapter searchView.setOnQueryTextListener(object :SearchView.OnQueryTextListener{ override fun onQueryTextSubmit(query: String?): Boolean { return false } override fun onQueryTextChange(newText: String?): Boolean { filterList(newText) return true } }) } private fun filterList(query:String?){ if(query !=null){ val filteredList = ArrayList<FitnessData>() for(i in mlist){ if(i.title.lowercase(Locale.ROOT).contains(query)){ filteredList.add(i) } } if(filteredList.isEmpty()){ Toast.makeText(this,"No Data found",Toast.LENGTH_SHORT).show() }else{ adapter.setFilteredList(filteredList) } } } private fun addDataToList(){ mlist.add(FitnessData("UTHM Fitness Club", R.drawable.uthm_fitness, Aevent::class.java)) mlist.add(FitnessData("BigBros Gym", R.drawable.big_bros, SignUp::class.java)) mlist.add(FitnessData("ActiveLife Fitness", R.drawable.active_life, Aprofile::class.java)) mlist.add(FitnessData("Dreamer's Gym", R.drawable.dreamers, Login::class.java)) mlist.add(FitnessData("Muscle Monster", R.drawable.muscle_monster, Aprofile::class.java)) } }
fitnessHub/app/src/main/java/com/example/fitnesshub/Ahome.kt
2463017701
package com.example.fitnesshub import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.google.android.material.bottomnavigation.BottomNavigationView class Aevent : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_aevent) val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView) bottomNavigationView.setSelectedItemId(R.id.bottom_event) bottomNavigationView.setOnItemSelectedListener { item -> when (item.itemId) { R.id.bottom_home -> { startActivity(Intent(this, Ahome::class.java)) overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) // Handle home item selection true // Return true to consume the event } R.id.bottom_event -> { // Start the Event activity with animation true // Return true to consume the event } R.id.bottom_profile -> { // Start the Profile activity with animation startActivity(Intent(this, Aprofile::class.java)) overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left) true // Return true to consume the event } else -> false // Return false to allow default selection } } } }
fitnessHub/app/src/main/java/com/example/fitnesshub/Aevent.kt
2583825308
package com.example.fitnesshub import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class Login : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) } }
fitnessHub/app/src/main/java/com/example/fitnesshub/Login.kt
200374919
package com.example.fitnesshub import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // 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 [Home.newInstance] factory method to * create an instance of this fragment. */ class Home : 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 return inflater.inflate(R.layout.activity_ahome, container, false) } 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 Home. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = Home().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
fitnessHub/app/src/main/java/com/example/fitnesshub/Home.kt
1490656337
package com.example.fitnesshub import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class SignUp : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sign_up) } }
fitnessHub/app/src/main/java/com/example/fitnesshub/SignUp.kt
1742637659
package com.example.fitnesshub import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // 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 [Event.newInstance] factory method to * create an instance of this fragment. */ class Event : 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 return inflater.inflate(R.layout.fragment_event, container, false) } 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 Event. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = Event().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
fitnessHub/app/src/main/java/com/example/fitnesshub/Event.kt
4291632923
package com.example.fitnesshub import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // 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 [Profile.newInstance] factory method to * create an instance of this fragment. */ class Profile : 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 return inflater.inflate(R.layout.fragment_profile, container, false) } 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 Profile. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = Profile().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
fitnessHub/app/src/main/java/com/example/fitnesshub/Profile.kt
2817726022
package com.example.wargame 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.wargame", appContext.packageName) } }
WarG/app/src/androidTest/java/com/example/wargame/ExampleInstrumentedTest.kt
2370063848
package com.example.wargame 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) } }
WarG/app/src/test/java/com/example/wargame/ExampleUnitTest.kt
4057336078
package com.example.wargame import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import kotlin.random.Random class MainActivity : AppCompatActivity() { lateinit var card1: ImageView lateinit var card2: ImageView lateinit var n_player1: TextView lateinit var n_player2: TextView lateinit var n_war: TextView lateinit var n_deal: Button lateinit var random: Random var player1 = 0 var player2 = 0 var brojPoenaIgrac1 = 0 var brojPoenaIgrac2 = 0 var cardsArray = intArrayOf( R.drawable.hearts2, R.drawable.hearts3, R.drawable.hearts4, R.drawable.hearts5, R.drawable.hearts6, R.drawable.hearts7, R.drawable.hearts8, R.drawable.hearts9, R.drawable.hearts10, R.drawable.hearts12, R.drawable.hearts13, R.drawable.hearts14, R.drawable.hearts15 ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) random = Random //init objects card1 = findViewById(R.id.iv_card1) card2 = findViewById(R.id.iv_card2) card1.setImageResource(R.drawable.card_back) card2.setImageResource(R.drawable.card_back) n_player1 = findViewById(R.id.tv_player1) n_player2 = findViewById(R.id.tv_player2) n_war = findViewById(R.id.tv_war) n_war.visibility = View.INVISIBLE n_deal = findViewById(R.id.b_deal) n_deal.setOnClickListener { //hide war label n_war.visibility = View.INVISIBLE //generate cards val card1 = random.nextInt(cardsArray.size) val card2 = random.nextInt(cardsArray.size) //set images setCardImage(card1, this.card1) setCardImage(card2, this.card2) //compare teh cards if (card1 > card2) { player1++ n_player1.text = "Player 1: $player1" } else if (card1 < card2) { player2++ n_player2.text = "Player 2: $player2" } else { //show war label n_war.visibility = View.VISIBLE } if (player1 >= 15) { val intent = Intent(this, WinnerG::class.java) intent.putExtra("pobjednik", "Igrač 1") startActivity(intent) } else if (player2 >= 15) { val intent = Intent(this, WinnerG::class.java) intent.putExtra("pobjednik", "Igrač 2") startActivity(intent) } } } private fun setCardImage(number: Int, image: ImageView) { image.setImageResource(cardsArray[number]) } }
WarG/app/src/main/java/com/example/wargame/MainActivity.kt
72275370
package com.example.wargame import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class WinnerG : AppCompatActivity() { lateinit var resultView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_winner_g) val winnerTextView = findViewById<TextView>(R.id.resultView) val pobjednik = intent.getStringExtra("pobjednik") winnerTextView.text="winner is : $pobjednik" resultView=findViewById(R.id.resultView) val button = findViewById<Button>(R.id.backButton) button.setOnClickListener { onDestroy() } } }
WarG/app/src/main/java/com/example/wargame/WinnerG.kt
55440091
package byx.matcher import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue class PerformanceTest { @Test fun test1() { // (a*)* val m = 'a'.many().many() assertTrue(m.match("a".repeat(1000))) assertFalse(m.match("${"a".repeat(1000)}b")) } @Test fun test2() { // (a+)+ val m = 'a'.many1().many1() assertTrue(m.match("a".repeat(1000))) assertFalse(m.match("${"a".repeat(1000)}b")) } @Test fun test3() { // (((((((((a*)*)*)*)*)*)*)*)*)* val m = 'a'.many().many().many().many().many().many().many().many().many().many() assertTrue(m.match("a".repeat(1000))) assertFalse(m.match("${"a".repeat(10)}b")) } @Test fun test4() { // (((((((((a+)+)+)+)+)+)+)+)+)+ val m = ch('a').many1().many1().many1().many1().many1().many1().many1().many1().many1().many1() assertTrue(m.match("a".repeat(1000))) assertFalse(m.match("${"a".repeat(10)}b")) } @Test fun test5() { // (((((((((a*)+)*)+)*)+)*)+)*)+ val m = ch('a').many().many1().many().many1().many().many1().many().many1().many().many1() assertTrue(m.match("a".repeat(1000))) assertFalse(m.match("${"a".repeat(10)}b")) } @Test fun test6() { // (((((((((a+)*)+)*)+)*)+)*)+)* val m = ch('a').many1().many().many1().many().many1().many().many1().many().many1().many() assertTrue(m.match("a".repeat(1000))) assertFalse(m.match("${"a".repeat(10)}b")) } @Test fun test7() { // .*.*=.* val m = any.many() and any.many() and '=' and any.many() assertTrue(m.match("a=${"b".repeat(1000)}")) } @Test fun test8() { // X(.+)+X val m = 'X' and any.many1().many1() and 'X' assertTrue(m.match("X========================================================================X")) assertFalse(m.match("X======================================================================X=")) } @Test fun test9() { // ((0|1)+)+b val m = chs('0', '1').many1().many1() and 'b' assertTrue(m.match("${"01".repeat(1000)}b")) assertFalse(m.match("01".repeat(50))) } @Test fun test10() { // (a|aa)* val m = strs("a", "aa").many() assertTrue(m.match("a".repeat(1000))) assertFalse(m.match("${"a".repeat(1000)}b")) } @Test fun test11() { val m = ch('a').repeat(10, 10000).repeat(10, 10000).repeat(10, 10000) assertTrue(m.match("a".repeat(1000))) assertFalse(m.match("a".repeat(100))) assertFalse(m.match("${"a".repeat(100)}b")) } @Test fun test12() { val m = 'a'.many().many().many().many().many().repeat(10) assertTrue(m.match("a".repeat(1000))) assertFalse(m.match("${"a".repeat(20)}b")) } @Test fun test13() { val m = 'a'.many1().many1().many1().many1().many1().repeat(10) assertTrue(m.match("a".repeat(1000))) assertFalse(m.match("${"a".repeat(20)}b")) } }
matcher-kotlin/src/test/kotlin/byx/matcher/PerformanceTest.kt
3241923373
package byx.matcher import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue /** * 括号匹配校验 * expr = term+ * term = "()" * | '(' expr ')' */ internal object BracketMatcher { private val term = oneOf( str("()"), '(' and lazy { expr } and ')' ) private val expr: Matcher = term.many1() fun isBracketMatch(s: String): Boolean { return expr.match(s) } } /** * 算数表达式校验 * expr = term ('+'|'-' term)+ * term = fact ('*'|'/' fact)+ * fact = [0-9]+ * | '-' fact * | '(' expr ')' */ internal object ArithmeticExprValidator { private val fact: Matcher = oneOf( range('0', '9').many1(), lazy { negExpr }, '(' and lazy { expr } and ')' ) private val negExpr = '-' and fact private val term: Matcher = fact and (chs('*', '/') and fact).many() private val expr: Matcher = term and (chs('+', '-') and term).many() fun isValidExpr(s: String): Boolean { return expr.match(s) } } /** * json字符串校验 * jsonObj = number | string | bool | arr | obj * number = integer | decimal * integer = [0-9]+ * decimal = [0-9]+ '.' [0-9]+ * string = '"' (.*) '"' * bool = "true" | "false" * arr = "[]" * | '[' jsonObj (',' jsonObj)* ']' * field = string ':' jsonObj * obj = "{}" * | '{' field (',' field)* '}' */ internal object JsonValidator { private val blank = chs(' ', '\t', '\n', '\r').many() private val objStart = ch('{').withBlank private val objEnd = ch('}').withBlank private val arrStart = ch('[').withBlank private val arrEnd = ch(']').withBlank private val colon = ch(':').withBlank private val comma = ch(',').withBlank private val jsonObj: Matcher = oneOf( lazy { number }, lazy { string }, lazy { bool }, lazy { arr }, lazy { obj } ) private val digits = range('0', '9').many1() private val integer = digits private val decimal = digits and '.' and digits private val number = integer or decimal private val string = '"' and not('"').many() and '"' private val bool = strs("true", "false") private val arr = oneOf( arrStart and arrEnd, arrStart and jsonObj.and(comma.and(jsonObj).many()) and arrEnd ) private val field = string and colon and jsonObj private val obj = oneOf( objStart and objEnd, objStart and field.and(comma.and(field).many()) and objEnd ) private val Matcher.withBlank: Matcher get() = blank and this and blank fun isValidJson(s: String): Boolean { return jsonObj.match(s) } } class RecursiveTest { @Test fun testBracketMatcher() { assertFalse(BracketMatcher.isBracketMatch("")) assertFalse(BracketMatcher.isBracketMatch("(")) assertFalse(BracketMatcher.isBracketMatch(")")) assertTrue(BracketMatcher.isBracketMatch("()")) assertFalse(BracketMatcher.isBracketMatch(")(")) assertFalse(BracketMatcher.isBracketMatch("((")) assertFalse(BracketMatcher.isBracketMatch("))")) assertTrue(BracketMatcher.isBracketMatch("()()")) assertTrue(BracketMatcher.isBracketMatch("(())")) assertFalse(BracketMatcher.isBracketMatch("(()")) assertFalse(BracketMatcher.isBracketMatch("())")) assertTrue(BracketMatcher.isBracketMatch("()()()")) assertTrue(BracketMatcher.isBracketMatch("()(())")) assertTrue(BracketMatcher.isBracketMatch("(())()")) assertTrue(BracketMatcher.isBracketMatch("(()())()")) assertTrue(BracketMatcher.isBracketMatch("(())()((()))()")) assertFalse(BracketMatcher.isBracketMatch("(())()((())()")) assertFalse(BracketMatcher.isBracketMatch("(())()(()))()")) } @Test fun testArithmeticExprValidator() { assertFalse(ArithmeticExprValidator.isValidExpr("")) assertTrue(ArithmeticExprValidator.isValidExpr("123")) assertTrue(ArithmeticExprValidator.isValidExpr("-6")) assertTrue(ArithmeticExprValidator.isValidExpr("2*(3+4)")) assertFalse(ArithmeticExprValidator.isValidExpr("abc")) assertFalse(ArithmeticExprValidator.isValidExpr("12+")) assertFalse(ArithmeticExprValidator.isValidExpr("12*")) assertFalse(ArithmeticExprValidator.isValidExpr("+3")) assertFalse(ArithmeticExprValidator.isValidExpr("/6")) assertFalse(ArithmeticExprValidator.isValidExpr("6+3-")) assertTrue(ArithmeticExprValidator.isValidExpr("(12+345)*(67-890)+10/6")) assertTrue(ArithmeticExprValidator.isValidExpr("-6*18+(-3/978)")) assertTrue(ArithmeticExprValidator.isValidExpr("24/5774*(6/357+637)-2*7/52+5")) assertFalse(ArithmeticExprValidator.isValidExpr("24/5774*(6/357+637-2*7/52+5")) assertTrue(ArithmeticExprValidator.isValidExpr("7758*(6/314+552234)-2*61/(10+2/(40-38*5))")) assertFalse(ArithmeticExprValidator.isValidExpr("7758*(6/314+552234)-2*61/(10+2/40-38*5))")) } @Test fun testJsonValidator() { assertTrue( JsonValidator.isValidJson( """ { "a": 123, "b": 3.14, "c": "hello", "d": { "x": 100, "y": "world!" }, "e": [ 12, 34.56, { "name": "Xiao Ming", "age": 18, "score": [99.8, 87.5, 60.0] }, "abc" ], "f": [], "g": {}, "h": [true, {"m": false}] } """ ) ) assertTrue(JsonValidator.isValidJson("123")) assertTrue(JsonValidator.isValidJson("34.56")) assertTrue(JsonValidator.isValidJson("\"hello\"")) assertTrue(JsonValidator.isValidJson("true")) assertTrue(JsonValidator.isValidJson("false")) assertTrue(JsonValidator.isValidJson("{}")) assertTrue(JsonValidator.isValidJson("[]")) assertTrue(JsonValidator.isValidJson("[{}]")) assertFalse(JsonValidator.isValidJson("")) assertFalse(JsonValidator.isValidJson("{")) assertFalse(JsonValidator.isValidJson("}")) assertFalse(JsonValidator.isValidJson("{}}")) assertFalse(JsonValidator.isValidJson("[1, 2 3]")) assertFalse(JsonValidator.isValidJson("{1, 2, 3}")) } }
matcher-kotlin/src/test/kotlin/byx/matcher/RecursiveTest.kt
1085299595
package byx.matcher import java.util.concurrent.atomic.AtomicInteger import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class MatcherCombinatorTest { @Test fun testCh() { val m = ch('a') assertTrue(m.match("a")) assertFalse(m.match("")) assertFalse(m.match("b")) assertFalse(m.match("aa")) assertFalse(m.match("xy")) } @Test fun testChs1() { val m = chs('a', 'b', 'c') assertTrue(m.match("a")) assertTrue(m.match("b")) assertTrue(m.match("c")) assertFalse(m.match("d")) assertFalse(m.match("1")) } @Test fun testChs2() { val arr = arrayOf('a', 'b', 'c').toCharArray() val m = chs(*arr) assertTrue(m.match("a")) assertTrue(m.match("b")) assertTrue(m.match("c")) assertFalse(m.match("d")) assertFalse(m.match("1")) } @Test fun testAny() { val m = any assertTrue(m.match("a")) assertTrue(m.match("b")) assertFalse(m.match("")) assertFalse(m.match("xyz")) } @Test fun testRange() { val m = range('0', '9') assertTrue(m.match("0")) assertTrue(m.match("5")) assertTrue(m.match("9")) assertFalse(m.match("")) assertFalse(m.match("a")) } @Test fun testNot() { val m = not('a') assertTrue(m.match("b")) assertFalse(m.match("a")) } @Test fun testStr() { val m = str("abc") assertTrue(m.match("abc")) assertFalse(m.match("")) assertFalse(m.match("a")) assertFalse(m.match("ab")) assertFalse(m.match("ax")) assertFalse(m.match("abx")) assertFalse(m.match("abcx")) } @Test fun testAnd() { val m = ch('a').and(ch('b')) assertTrue(m.match("ab")) assertFalse(m.match("a")) assertFalse(m.match("abc")) assertFalse(m.match("ba")) assertFalse(m.match("x")) assertFalse(m.match("xy")) assertFalse(m.match("")) } @Test fun testOr() { val m = ch('a').or(ch('b')) assertTrue(m.match("a")) assertTrue(m.match("b")) assertFalse(m.match("x")) assertFalse(m.match("ax")) assertFalse(m.match("by")) assertFalse(m.match("mn")) assertFalse(m.match("")) } @Test fun testRepeat1() { val m: Matcher = ch('a').repeat(3, 5) assertTrue(m.match("aaa")) assertTrue(m.match("aaaa")) assertTrue(m.match("aaaaa")) assertFalse(m.match("")) assertFalse(m.match("a")) assertFalse(m.match("aa")) assertFalse(m.match("aaaaaa")) assertFalse(m.match("aaaaaaa")) } @Test fun testRepeat2() { val m: Matcher = ch('a').repeat(3) assertTrue(m.match("aaa")) assertFalse(m.match("")) assertFalse(m.match("a")) assertFalse(m.match("aa")) assertFalse(m.match("aaaa")) assertFalse(m.match("aaaaa")) } @Test fun testRepeat3() { val m = ch('a').repeat(3, Integer.MAX_VALUE) assertTrue(m.match("aaa")) assertTrue(m.match("aaaa")) assertTrue(m.match("a".repeat(1000))) assertFalse(m.match("aa")) } @Test fun testMany() { val m = ch('a').many() assertTrue(m.match("")) assertTrue(m.match("a")) assertTrue(m.match("aaaaa")) assertFalse(m.match("b")) assertFalse(m.match("bbbb")) assertFalse(m.match("aaab")) assertFalse(m.match("aaabaaaa")) } @Test fun testMany1() { val m = ch('a').many1() assertTrue(m.match("a")) assertTrue(m.match("aaaaa")) assertFalse(m.match("")) assertFalse(m.match("b")) assertFalse(m.match("bbbb")) assertFalse(m.match("aaab")) assertFalse(m.match("aaabaaaa")) } @Test fun testMany2() { val m = ch('a').many(3) assertFalse(m.match("")) assertFalse(m.match("a")) assertFalse(m.match("aa")) assertTrue(m.match("aaa")) assertTrue(m.match("aaaa")) assertTrue(m.match("aaaaa")) } @Test fun testFlatMap1() { val m = not(' ').many1().flatMap { s -> ch(' ').and(str("xxx ")).and(str(s)) } assertTrue(m.match("m xxx m")) assertTrue(m.match("aaa xxx aaa")) assertTrue(m.match("bbbb xxx bbbb")) assertFalse(m.match("aaa xxx bbb")) assertFalse(m.match("aaaa xxx aaa")) assertFalse(m.match("aaa xxx aaaa")) } @Test fun testFlatMap2() { val m: Matcher = any.many1().flatMap { s -> any.repeat(s.length) } assertTrue(m.match("aaabbb")) assertTrue(m.match("aaaabbbb")) assertTrue(m.match("xxxxxyyyyy")) assertFalse(m.match("aaabbbb")) assertFalse(m.match("xxxxyyy")) assertFalse(m.match("mmm")) } @Test fun testLazy() { val i = AtomicInteger(123) val m = lazy { i.set(456) ch('a') } assertEquals(123, i.get()) assertTrue(m.match("a")) assertEquals(456, i.get()) } }
matcher-kotlin/src/test/kotlin/byx/matcher/MatcherCombinatorTest.kt
4150718356
package byx.matcher fun interface Matcher { /** * 从[index]位置开始解析字符串[s],返回解析后的位置集合,用Sequence表示 */ fun parse(s: String, index: Int): Sequence<Int> } /** * 判断字符串[s]是否与当前模式匹配 */ fun Matcher.match(s: String) = parse(s, 0).any { i -> i == s.length } /** * 连接两个Matcher */ infix fun Matcher.and(rhs: Matcher) = Matcher { s, index -> parse(s, index).flatMap { i -> rhs.parse(s, i) }.distinct() } /** * 将字符串[s]转换成Matcher,并与当前Matcher相连 */ infix fun Matcher.and(s: String) = and(str(s)) /** * 将字符[c]转换成Matcher,并与当前Matcher相连 */ infix fun Matcher.and(c: Char) = and(ch(c)) /** * 使用or连接两个Matcher */ infix fun Matcher.or(rhs: Matcher) = Matcher { s, index -> (parse(s, index) + rhs.parse(s, index)).distinct() } /** * 将字符串[s]转换成Matcher,并使用or与当前Matcher相连 */ infix fun Matcher.or(s: String) = or(str(s)) /** * 将字符[c]转换成Matcher,并使用or与当前Matcher相连 */ infix fun Matcher.or(c: Char) = or(ch(c)) /** * 将当前Matcher连续应用至少[minTimes]次 */ fun Matcher.many(minTimes: Int = 0) = Matcher { s, index -> sequence { // 应用minTimes次 var seq = sequenceOf(index) repeat(minTimes) { seq = seq.flatMap { i -> parse(s, i) }.distinct() } val visited = HashSet<Int>() seq.forEach { i -> yield(i) visited.add(i) } // 继续应用当前解析器,直到没有新的位置产生 val queue = ArrayDeque(visited) while (!queue.isEmpty()) { for (i in parse(s, queue.removeFirst())) { if (!visited.contains(i)) { yield(i) visited.add(i) queue.addLast(i) } } } } } /** * 将当前Matcher连续应用1次或多次 */ fun Matcher.many1() = many(1) /** * 将当前Matcher重复最少[minTimes]次,最多[maxTimes]次 */ fun Matcher.repeat(minTimes: Int, maxTimes: Int) = Matcher { s, index -> sequence { // 应用minTimes次 var set = sequenceOf(index) repeat(minTimes) { set = set.flatMap { i -> parse(s, i) }.distinct() } val visited = HashSet<Int>() set.forEach { i -> yield(i) visited.add(i) } // 继续应用直到maxTimes次 val queue = ArrayDeque(visited) var times = minTimes while (!queue.isEmpty() && times < maxTimes) { val cnt = queue.size repeat(cnt) { for (i in parse(s, queue.removeFirst())) { if (!visited.contains(i)) { yield(i) visited.add(i) queue.addLast(i) } } } times++ } } } /** * 将当前解析器重复[times]次 */ fun Matcher.repeat(times: Int) = repeat(times, times) /** * 应用当前Matcher,并调用[mapper]生成下一个Matcher,继续应用下一个Mapper */ fun Matcher.flatMap(mapper: (String) -> Matcher) = Matcher { s, index -> parse(s, index).flatMap { i -> val matchStr = s.substring(index..<i) mapper(matchStr).parse(s, i) }.distinct() } /** * 匹配满足条件的单个字符,条件由[predicate]指定 */ fun ch(predicate: (Char) -> Boolean) = Matcher { s, index -> if (index < s.length && predicate(s[index])) { sequenceOf(index + 1) } else { emptySequence() } } /** * 匹配字符集[chs]内的字符 */ fun chs(vararg chs: Char): Matcher { val set = chs.toSet() return ch { c -> set.contains(c) } } /** * 匹配任意字符 */ val any = ch { true } /** * 匹配字符[c] */ fun ch(c: Char) = ch { ch -> ch == c } /** * 匹配不等于[c]的字符 */ fun not(c: Char) = ch { ch -> ch != c } /** * 匹配范围[[c1], [c2]]内的字符 */ fun range(c1: Char, c2: Char) = ch { c -> (c - c1) * (c - c2) <= 0 } /** * 匹配指定字符串[str] */ fun str(str: String) = Matcher { s, index -> if (s.startsWith(str, index)) { sequenceOf(index + str.length) } else { emptySequence() } } /** * 匹配集合[strs]内的字符串 */ fun strs(vararg strs: String) = strs.map(::str).reduce(Matcher::or) /** * 将多个Matcher用and连接 */ fun seq(vararg matchers: Matcher) = matchers.reduce(Matcher::and) /** * 将多个Matcher用or连接 */ fun oneOf(vararg matchers: Matcher) = matchers.reduce(Matcher::or) /** * 惰性Matcher,解析时调用[matcherSupplier]获取Matcher实例并执行 */ fun lazy(matcherSupplier: () -> Matcher) = Matcher { s, index -> matcherSupplier().parse(s, index) } fun Char.many(minTimes: Int = 0) = ch(this).many(minTimes) fun Char.many1() = ch(this).many1() infix fun Char.and(matcher: Matcher) = ch(this).and(matcher) infix fun Char.or(matcher: Matcher) = ch(this).or(matcher) fun String.many(minTimes: Int = 0) = str(this).many(minTimes) fun String.many1() = str(this).many1() infix fun String.and(matcher: Matcher) = str(this).and(matcher) infix fun String.or(matcher: Matcher) = str(this).or(matcher)
matcher-kotlin/src/main/kotlin/byx/matcher/Matcher.kt
424527166
package com.example.gastion 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.gastion", appContext.packageName) } }
gastion/app/src/androidTest/java/com/example/gastion/ExampleInstrumentedTest.kt
1773082978
package com.example.gastion 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) } }
gastion/app/src/test/java/com/example/gastion/ExampleUnitTest.kt
3433997791
package com.example.gastion.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)
gastion/app/src/main/java/com/example/gastion/ui/theme/Color.kt
2866860717
package com.example.gastion.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 GastionTheme( 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 ) }
gastion/app/src/main/java/com/example/gastion/ui/theme/Theme.kt
576943786
package com.example.gastion.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 ) */ )
gastion/app/src/main/java/com/example/gastion/ui/theme/Type.kt
3900155516
package com.example.gastion.ui.main import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.gastion.ui.theme.GastionTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GastionTheme { // A surface container using the 'background' color from the theme GasMap( modifier = Modifier.fillMaxSize() ) } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { GastionTheme { Greeting("Android") } }
gastion/app/src/main/java/com/example/gastion/ui/main/MainActivity.kt
1764442948
package com.example.gastion.ui.main import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.maps.android.compose.GoogleMap import com.google.maps.android.compose.Marker import com.google.maps.android.compose.MarkerState import com.google.maps.android.compose.rememberCameraPositionState @Composable fun GasMap( modifier: Modifier = Modifier ) { val myLoc = LatLng(1.35, 103.87) val cameraPositionState = rememberCameraPositionState { position = CameraPosition.fromLatLngZoom(myLoc, 10f) } GoogleMap( modifier = modifier, cameraPositionState = cameraPositionState ) { Marker( state = MarkerState(position = myLoc), title = "Me", snippet = "Me Me Me Me" ) } }
gastion/app/src/main/java/com/example/gastion/ui/main/MapComponent.kt
275655137
package com.example.gastion.data import android.content.Context import android.location.Location import androidx.annotation.RequiresPermission import androidx.core.location.LocationCompat import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationServices import com.google.android.gms.location.Priority import com.google.android.gms.tasks.CancellationTokenSource import com.google.android.gms.tasks.Task class LocationRepositoryImpl : LocationRepository { private val locationRequest = LocationRequest.Builder(Priority.PRIORITY_BALANCED_POWER_ACCURACY, 10000).apply { setWaitForAccurateLocation(true) }.build() @RequiresPermission(anyOf = ["android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION"]) override fun getCurrentLocation(appContext: Context): Task<Location> { val fusedLocationClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(appContext) return fusedLocationClient.getCurrentLocation(locationRequest.priority, CancellationTokenSource().token) .continueWith { task -> val location = task.result if (LocationCompat.isMock(location)) throw Exception("Location is Mocked") else location } } }
gastion/app/src/main/java/com/example/gastion/data/LocationRepositoryImpl.kt
1027899880
package com.example.gastion.data import android.content.Context import android.location.Location import com.google.android.gms.tasks.Task interface LocationRepository { fun getCurrentLocation(appContext: Context): Task<Location> }
gastion/app/src/main/java/com/example/gastion/data/LocationRepository.kt
866156106
package com.mun.bonecci.lottiecompose 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.mun.bonecci.lottiecompose", appContext.packageName) } }
LottieCompose/app/src/androidTest/java/com/mun/bonecci/lottiecompose/ExampleInstrumentedTest.kt
3759794466
package com.mun.bonecci.lottiecompose 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) } }
LottieCompose/app/src/test/java/com/mun/bonecci/lottiecompose/ExampleUnitTest.kt
3410507121
package com.mun.bonecci.lottiecompose.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)
LottieCompose/app/src/main/java/com/mun/bonecci/lottiecompose/ui/theme/Color.kt
1886686130
package com.mun.bonecci.lottiecompose.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 LottieComposeTheme( 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 ) }
LottieCompose/app/src/main/java/com/mun/bonecci/lottiecompose/ui/theme/Theme.kt
451364891
package com.mun.bonecci.lottiecompose.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 ) */ )
LottieCompose/app/src/main/java/com/mun/bonecci/lottiecompose/ui/theme/Type.kt
2003430076
package com.mun.bonecci.lottiecompose import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.airbnb.lottie.LottieProperty import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.animateLottieCompositionAsState import com.airbnb.lottie.compose.rememberLottieComposition import com.airbnb.lottie.compose.rememberLottieDynamicProperties import com.airbnb.lottie.compose.rememberLottieDynamicProperty import com.airbnb.lottie.compose.rememberLottieRetrySignal import com.mun.bonecci.lottiecompose.ui.theme.LottieComposeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LottieComposeTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { LottieAnimation("Android") } } } } } @Composable fun LottieAnimation(name: String, modifier: Modifier = Modifier) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Text( text = "Hello $name!", color = Color.Blue, fontWeight = FontWeight.Bold, fontSize = 16.sp, modifier = modifier ) LottieAnimationExample() LottieAnimationURLExample() LottieAnimationColor() } } /** * A composable function demonstrating the usage of LottieAnimation to display an animated Lottie composition. * The Lottie composition is loaded from a raw resource file named "orange_skating_animation". */ @Composable fun LottieAnimationExample() { // Obtain the Lottie composition from the specified raw resource file. val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.orange_skating_animation)) // Animate the Lottie composition with a continuous loop. val progress by animateLottieCompositionAsState( composition = composition, iterations = LottieConstants.IterateForever, ) // Display the Lottie animation with specified properties. LottieAnimation( composition = composition, progress = { progress }, contentScale = ContentScale.Crop, modifier = Modifier .size(100.dp) ) } /** * A composable function demonstrating the usage of LottieAnimation to display an animated Lottie composition * loaded from a URL. It also shows how to handle retries in case of loading failures. */ @Composable fun LottieAnimationURLExample() { // Create a retry signal to control the retry mechanism. val retrySignal = rememberLottieRetrySignal() // Load the Lottie composition from the specified URL with retry handling. val composition by rememberLottieComposition( LottieCompositionSpec.Url("not a url"), // Replace with the actual URL onRetry = { failCount, exception -> // Log information about the retry attempt and exception. Log.d("FailCount: ", failCount.toString()) Log.d("Exception: ", exception.stackTraceToString()) // Request a retry using the retry signal. retrySignal.awaitRetry() // Continue retrying. Return false to stop trying. true } ) // Animate the Lottie composition with a continuous loop. val progress by animateLottieCompositionAsState( composition = composition, iterations = LottieConstants.IterateForever, ) // Display the Lottie animation with specified properties. LottieAnimation( composition = composition, progress = { progress }, ) } /** * A private composable function demonstrating the usage of LottieAnimation with dynamic properties * to change the color and apply a blur effect to specific parts of the Lottie animation. */ @Composable private fun LottieAnimationColor() { // Load the Lottie composition from the specified raw resource. val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart)) // Define a list of colors to be used for dynamic color changes. val colors = remember { listOf( Color.Red, Color.Green, Color.Blue, Color.Yellow, ) } // Track the index of the current color in the list. var colorIndex by remember { mutableIntStateOf(0) } // Retrieve the current color based on the index. val color by remember { derivedStateOf { colors[colorIndex] } } // Convert dp to pixels for blur effect. val blurRadius = with(LocalDensity.current) { 12.dp.toPx() } // Define dynamic properties for color and blur effect. val dynamicProperties = rememberLottieDynamicProperties( rememberLottieDynamicProperty( property = LottieProperty.COLOR, value = color.toArgb(), keyPath = arrayOf( "H2", "Shape 1", "Fill 1", ) ), rememberLottieDynamicProperty( property = LottieProperty.BLUR_RADIUS, value = blurRadius, keyPath = arrayOf( "**", "Stroke 1", ) ), ) // Display the Lottie animation with specified properties and interaction. LottieAnimation( composition, iterations = LottieConstants.IterateForever, dynamicProperties = dynamicProperties, contentScale = ContentScale.Crop, modifier = Modifier .size(200.dp) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = { colorIndex = (colorIndex + 1) % colors.size }, ) ) } @Preview(showBackground = true) @Composable fun LottieAnimationPreview() { LottieComposeTheme { LottieAnimation("Android") } }
LottieCompose/app/src/main/java/com/mun/bonecci/lottiecompose/MainActivity.kt
3443940445
package com.example.lantsev 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.lantsev", appContext.packageName) } }
pr8/app/src/androidTest/java/com/example/lantsev/ExampleInstrumentedTest.kt
117308431
package com.example.lantsev 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) } }
pr8/app/src/test/java/com/example/lantsev/ExampleUnitTest.kt
1124398797
package com.example.lantsev.dto data class Post( val id: Int, val author: String, val content: String, val published: String, var likes: Int, var share: Int, val likedByMe: Boolean, val shareByMe: Boolean )
pr8/app/src/main/java/com/example/lantsev/dto/Post.kt
1372263290
package com.example.lantsev.viewmodel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.lantsev.dto.Post import com.example.lantsev.repository.PostRepository import com.example.lantsev.repository.PostRepositoryInMemoryImpl private val empty = Post( id = 0, content = "", author = "", likedByMe = false, published = "", shareByMe = false, likes = 0, share = 0 ) class PostViewModel : ViewModel() { private val repository: PostRepository = PostRepositoryInMemoryImpl() val data = repository.getAll() val edited = MutableLiveData(empty) fun save() { edited.value?.let { repository.save(it) } edited.value = empty } fun edit(post:Post){ edited.value = post } fun changeContent(content: String) { val text = content.trim() if (edited.value?.content == text) { return } edited.value = edited.value?.copy(content = text) } fun likeById(id: Int)=repository.likeById(id) fun shareById(id: Int)=repository.shareById(id) fun removeById(id: Int) = repository.removeById(id) }
pr8/app/src/main/java/com/example/lantsev/viewmodel/PostViewModel.kt
1346153808
package com.example.lantsev.repository import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.lantsev.dto.Post class PostRepositoryInMemoryImpl : PostRepository{ private var nextId=1 private var posts = listOf( Post( id = nextId++, author = "Нетология. Университет интернет-профессий будущего", content = "Привет, это новая Нетология! Когда-то Нетология начиналась с интенсивов по онлайн-маркетингу. Затем появились курсы по дизайну, разработке, аналитике и управлению. Мы растём сами и помогаем расти студентам: от новичков до уверенных профессионалов. Но самое важное остаётся с нами: мы верим, что в каждом уже есть сила, которая заставляет хотеть больше, целиться выше, бежать быстрее. Наша миссия — помочь встать на путь роста и начать цепочку перемен → http://netolo.gy/fyb", published = "18 сентября в 10:12", likedByMe = false, likes = 489, share = 23, shareByMe=false ), Post( id = nextId++, author = "Нетология. Университет интернет-профессий будущего", content = "Привет, это новая Нетология! Когда-то Нетология начиналась с интенсивов по онлайн-маркетингу. Затем появились курсы по дизайну, разработке, аналитике и управлению. Мы растём сами и помогаем расти студентам: от новичков до уверенных профессионалов. Но самое важное остаётся с нами: мы верим, что в каждом уже есть сила, которая заставляет хотеть больше, целиться выше, бежать быстрее. Наша миссия — помочь встать на путь роста и начать цепочку перемен → http://netolo.gy/fyb", published = "21 мая в 18:36", likedByMe = false, likes = 999999, share = 999, shareByMe=false ) ).reversed() private val data = MutableLiveData(posts) override fun getAll(): LiveData<List<Post>> = data override fun save(post: Post) { if(post.id==0){ posts = listOf(post.copy( id = nextId++, author = "Me", likedByMe = false, published = "now", shareByMe = false ) ) + posts data.value = posts return } posts = posts.map{ if (it.id != post.id) it else it.copy (content = post.content, likes = post.likes, share = post.share) } data.value = posts } override fun likeById(id: Int) { posts = posts.map { if (it.id != id) it else it.copy(likedByMe = !it.likedByMe, likes = if (!it.likedByMe) it.likes+1 else it.likes-1) } data.value = posts } override fun shareById(id: Int) { posts = posts.map { if (it.id != id) it else it.copy(shareByMe = !it.shareByMe, share = it.share+1) } data.value = posts } override fun removeById(id: Int) { posts = posts.filter { it.id!=id } data.value = posts } }
pr8/app/src/main/java/com/example/lantsev/repository/PostRepositoryInMemoryImpl.kt
2710224871
package com.example.lantsev.repository import androidx.lifecycle.LiveData import com.example.lantsev.dto.Post interface PostRepository { fun getAll(): LiveData<List<Post>> fun likeById(id: Int) fun shareById(id: Int) fun removeById(id: Int) fun save(post: Post) }
pr8/app/src/main/java/com/example/lantsev/repository/PostRepository.kt
979735915
package com.example.lantsev.util import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager object AndroidUtils { fun hideKeyboard(view: View){ val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken,0) } }
pr8/app/src/main/java/com/example/lantsev/util/AndroidUtils.kt
936752797
package com.example.lantsev.activity import android.os.Bundle import android.view.View import android.widget.Toast import androidx.activity.ComponentActivity import androidx.appcompat.app.AppCompatActivity import com.example.lantsev.viewmodel.PostViewModel import androidx.annotation.MainThread import com.example.lantsev.dto.Post import com.example.lantsev.util.AndroidUtils import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelLazy import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewmodel.CreationExtras import com.example.lantsev.R import com.example.lantsev.adapter.OnInteractionListener import com.example.lantsev.adapter.PostsAdapter import com.example.lantsev.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val viewModel: PostViewModel by viewModels() val adapter = PostsAdapter(object : OnInteractionListener { override fun onEdit(post: Post) { viewModel.edit(post) } override fun onLike(post: Post) { viewModel.likeById(post.id) } override fun onRemove(post: Post) { viewModel.removeById(post.id) } override fun onShare(post: Post) { viewModel.shareById(post.id) } }) binding.list.adapter=adapter viewModel.data.observe(this) { posts -> adapter.submitList(posts) } viewModel.edited.observe(this){ post-> if(post.id == 0){ return@observe } with(binding.content){ binding.group.visibility = View.VISIBLE requestFocus() setText(post.content) } } binding.cancel.setOnClickListener { with(binding.content){ viewModel.save() setText("") clearFocus() AndroidUtils.hideKeyboard(this) binding.group.visibility = View.GONE } } binding.save.setOnClickListener { with(binding.content){ if(text.isNullOrBlank()){ Toast.makeText( this@MainActivity, context.getString(R.string.error_empty_content), Toast.LENGTH_SHORT ).show() return@setOnClickListener } viewModel.changeContent(text.toString()) viewModel.save() setText("") clearFocus() AndroidUtils.hideKeyboard(this) } } } } @MainThread public inline fun <reified VM : ViewModel> ComponentActivity.viewModels( noinline extrasProducer: (() -> CreationExtras)? = null, noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null ): Lazy<VM> { val factoryPromise = factoryProducer ?: { defaultViewModelProviderFactory } return ViewModelLazy( VM::class, { viewModelStore }, factoryPromise, { extrasProducer?.invoke() ?: this.defaultViewModelCreationExtras } ) }
pr8/app/src/main/java/com/example/lantsev/activity/MainActivity.kt
3397186753
package com.example.lantsev.adapter import android.view.LayoutInflater import android.view.ViewGroup import android.widget.PopupMenu import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.lantsev.dto.Post import com.example.lantsev.R import com.example.lantsev.databinding.CardPostBinding import kotlin.math.ln import kotlin.math.pow interface OnInteractionListener { fun onLike(post: Post) {} fun onShare(post: Post) {} fun onEdit(post: Post) {} fun onRemove(post: Post) {} } class PostsAdapter( private val onInteractionListener: OnInteractionListener ) : ListAdapter<Post, PostViewHolder>(PostDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder { val binding = CardPostBinding.inflate(LayoutInflater.from(parent.context), parent, false) return PostViewHolder(binding, onInteractionListener) } override fun onBindViewHolder(holder: PostViewHolder, position: Int) { val post = getItem(position) holder.bind(post) } } class PostViewHolder( private val binding: CardPostBinding, private val onInteractionListener: OnInteractionListener ) : RecyclerView.ViewHolder(binding.root) { fun bind(post: Post) { binding.apply { author.text = post.author published.text = post.published textt.text = post.content textlike.text = post.likes.toString() textshare.text = post.share.toString() like.isChecked = post.likedByMe textlike.text = getFormatedNumber(post.likes.toLong()) textshare.text = getFormatedNumber(post.share.toLong()) menu.setOnClickListener { PopupMenu(it.context, it).apply { inflate(R.menu.popup_menu) setOnMenuItemClickListener { item -> when (item.itemId) { R.id.remove -> { onInteractionListener.onRemove(post) true } R.id.edit -> { onInteractionListener.onEdit(post) true } else -> false } } }.show() } like.setOnClickListener { onInteractionListener.onLike(post) } textlike.text = post.likes.toString() when { post.likes in 1000..999999 -> textlike.text = "${post.likes / 1000}K" post.likes < 1000 -> textlike.text = post.likes.toString() else -> textlike.text = String.format("%.1fM", post.likes.toDouble() / 1000000) } share.setOnClickListener { onInteractionListener.onShare(post) } textshare.text = post.share.toString() when { post.share < 1000 -> textshare.text = post.share.toString() post.share in 1000..999999 -> textshare.text = "${post.share / 1000}K" else -> textshare.text = String.format( "%.1fM", post.share.toDouble() / 1000000 ) } } } } fun getFormatedNumber(count: Long): String { if (count < 1000) return "" + count val exp = (ln(count.toDouble()) / ln(1000.0)).toInt() return String.format("%.1f %c", count / 1000.0.pow(exp.toDouble()), "KMGTPE"[exp - 1]) } class PostDiffCallback : DiffUtil.ItemCallback<Post>() { override fun areItemsTheSame(oldItem: Post, newItem: Post): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Post, newItem: Post): Boolean { return oldItem == newItem } }
pr8/app/src/main/java/com/example/lantsev/adapter/PostsAdapter.kt
2275068593
package com.aman.flicker_image_gallery 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.aman.flicker_image_gallary", appContext.packageName) } }
OnlineGalleryApp/app/src/androidTest/java/com/aman/flicker_image_gallery/ExampleInstrumentedTest.kt
743617484
package com.aman.flicker_image_gallery 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) } }
OnlineGalleryApp/app/src/test/java/com/aman/flicker_image_gallery/ExampleUnitTest.kt
3873214496
package com.aman.flicker_image_gallery.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.PagingData import androidx.paging.cachedIn import com.aman.flicker_image_gallery.model.Photo import com.aman.flicker_image_gallery.repository.ImageRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.count import javax.inject.Inject @HiltViewModel class ImageViewModel @Inject constructor(private val imageRepository: ImageRepository): ViewModel(){ var flickerRecentPhotos: Flow<PagingData<Photo>>? = null val moviesData: Flow<PagingData<Photo>> = imageRepository(viewModelScope) // fun fetchFlickerRecentPhotos(): Flow<PagingData<Photo>> { // println("Printing in view model function") // flickerRecentPhotos = imageRepository.getAllImages().cachedIn(viewModelScope) // println("Count flicker is ${flickerRecentPhotos}") // return flickerRecentPhotos!! // } }
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/viewmodel/ImageViewModel.kt
842416049
package com.aman.flicker_image_gallery.ui.extensions import android.annotation.SuppressLint import android.os.Parcel import android.os.Parcelable import androidx.compose.foundation.lazy.grid.LazyGridItemScope import androidx.compose.foundation.lazy.grid.LazyGridScope import androidx.compose.runtime.Composable import androidx.paging.compose.LazyPagingItems fun <T : Any> LazyGridScope.itemsPaging( items: LazyPagingItems<T>, key: ((item: T) -> Any)? = null, itemContent: @Composable LazyGridItemScope.(value: T?) -> Unit ) { items( count = items.itemCount, key = if (key == null) null else { index -> val item = items.peek(index) if (item == null) { PagingPlaceholderKey(index) } else { key(item) } } ) { index -> itemContent(items[index]) } } @SuppressLint("BanParcelableUsage") private data class PagingPlaceholderKey(private val index: Int) : Parcelable { override fun writeToParcel(parcel: Parcel, flags: Int) = parcel.writeInt(index) override fun describeContents(): Int = 0 companion object { @Suppress("unused") @JvmField val CREATOR: Parcelable.Creator<PagingPlaceholderKey> = object : Parcelable.Creator<PagingPlaceholderKey> { override fun createFromParcel(parcel: Parcel) = PagingPlaceholderKey(parcel.readInt()) override fun newArray(size: Int) = arrayOfNulls<PagingPlaceholderKey?>(size) } } }
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/ui/extensions/LazyVGridExtension.kt
4198675903
package com.aman.flicker_image_gallery.ui.components import android.annotation.SuppressLint import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Menu import androidx.compose.material.icons.filled.Search import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import com.aman.flicker_image_gallery.FlickerImageAPI import com.aman.flicker_image_gallery.R import com.aman.flicker_image_gallery.model.Photo import com.aman.flicker_image_gallery.ui.extensions.itemsPaging import com.aman.flicker_image_gallery.viewmodel.ImageViewModel import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi import com.bumptech.glide.integration.compose.GlideImage @OptIn(ExperimentalMaterial3Api::class, ExperimentalGlideComposeApi::class) @SuppressLint("UnusedMaterialScaffoldPaddingParameter", "UnusedMaterial3ScaffoldPaddingParameter") @Composable fun FlickerPhotosGrid(imageViewModel: ImageViewModel) { Scaffold( topBar = { TopAppBar( title = { Row() { Icon(Icons.Filled.Menu, contentDescription = null) Spacer(modifier = Modifier.width(5.dp)) Text(text = "Gallery") } }, actions = { Icon(Icons.Filled.Search, contentDescription = null) } ) } ) { val flickerRecentPhotos: LazyPagingItems<Photo> = imageViewModel.moviesData.collectAsLazyPagingItems() LazyVerticalGrid( columns = GridCells.Fixed(2), verticalArrangement = Arrangement.spacedBy(5.dp), horizontalArrangement = Arrangement.spacedBy(5.dp) ) { itemsPaging(flickerRecentPhotos) { GlideImage( model = it!!.url_s, contentDescription = "photo", contentScale = ContentScale.Crop, modifier = Modifier.height(200.dp) ) } } } }
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/ui/components/BasicGridView.kt
3120971904
package com.aman.flicker_image_gallery.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)
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/ui/theme/Color.kt
196409666
package com.aman.flicker_image_gallery.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 FlickerImageGalleryTheme( 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 ) }
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/ui/theme/Theme.kt
3509857811
package com.aman.flicker_image_gallery.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 ) */ )
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/ui/theme/Type.kt
2662623358
package com.aman.flicker_image_gallery.repository import androidx.lifecycle.ViewModel import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import androidx.paging.cachedIn import com.aman.flicker_image_gallery.FlickerImageAPI import com.aman.flicker_image_gallery.model.Photo import com.aman.flicker_image_gallery.repository.paging.PhotosPagingSource import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import okhttp3.OkHttpClient import javax.inject.Inject class ImageRepository @Inject constructor(private val flickerImageAPIClient: FlickerImageAPI) { // fun getAllImages(): Flow<PagingData<Photo>> { // println("It is in repository") // return Pager( // config = PagingConfig( // pageSize = 20, // ), // initialKey = 1, // pagingSourceFactory = { // PhotosPagingSource(imageRepository = flickerImageAPIClient) // } // ).flow // } operator fun invoke( viewModelScope: CoroutineScope ): Flow<PagingData<Photo>> { return Pager( config = PagingConfig(pageSize = 20), initialKey = 1, pagingSourceFactory = { PhotosPagingSource(imageRepository = flickerImageAPIClient) } ).flow.cachedIn(viewModelScope) } }
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/repository/ImageRepository.kt
2551074481
package com.aman.flicker_image_gallery.repository.paging import android.net.http.HttpException import android.os.Build import androidx.annotation.RequiresExtension import androidx.paging.PagingSource import androidx.paging.PagingState import com.aman.flicker_image_gallery.FlickerImageAPI import com.aman.flicker_image_gallery.FlickerImageAPIClient import com.aman.flicker_image_gallery.model.Photo import com.aman.flicker_image_gallery.repository.ImageRepository import java.io.IOException class PhotosPagingSource (private val imageRepository: FlickerImageAPI): PagingSource<Int, Photo>() { @RequiresExtension(extension = Build.VERSION_CODES.S, version = 7) override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Photo> { val currentPageNumber = params.key ?: 1 val flickerAPIImageResponse = imageRepository.getAllImages(page = currentPageNumber, perPage = 20) val nextKey = currentPageNumber + 1 return LoadResult.Page( data = flickerAPIImageResponse.body()!!.photos.photo, prevKey = null, nextKey = nextKey ) } override fun getRefreshKey(state: PagingState<Int, Photo>): Int? { return state.anchorPosition?.let { anchorPosition -> val anchorPage = state.closestPageToPosition(anchorPosition) anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1) } } }
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/repository/paging/PhotosPagingSource.kt
4261209535
package com.aman.flicker_image_gallery import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.aman.flicker_image_gallery.ui.components.FlickerPhotosGrid //import com.aman.flicker_image_gallery.ui.theme.FlickerImageGallaryTheme import com.aman.flicker_image_gallery.ui.theme.FlickerImageGalleryTheme import com.aman.flicker_image_gallery.viewmodel.ImageViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { private val flickerPhotosViewModel: ImageViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { FlickerPhotosGrid(imageViewModel = flickerPhotosViewModel) } } }
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/MainActivity.kt
3206179644
package com.aman.flicker_image_gallery import com.aman.flicker_image_gallery.model.FlickerAPIImageResponse import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityRetainedComponent import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface FlickerImageAPI { @GET(value = "services/rest") suspend fun getAllImages( @Query(value = "method") method : String = "flickr.photos.getRecent", @Query(value = "per_page") perPage: Int, @Query(value = "page") page: Int, @Query(value = "api_key") apiKey: String = "6f102c62f41998d151e5a1b48713cf13", @Query(value = "format") format: String = "json", @Query(value = "nojsoncallback") noJsonCallback: Int = 1, @Query(value = "extras") extras: String = "url_s", ) : Response<FlickerAPIImageResponse> } @Module @InstallIn(ActivityRetainedComponent::class) object FlickerImageAPIModel { @Provides fun provideFlickerImageAPI(): FlickerImageAPI = FlickerImageAPIClient.getFlickerImageAPIClient() }
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/FlickerImageAPI.kt
3280627399
package com.aman.flicker_image_gallery import com.google.gson.GsonBuilder import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit object FlickerImageAPIClient { private lateinit var flickerImageAPIClient: FlickerImageAPI fun getFlickerImageAPIClient(): FlickerImageAPI { if (!this::flickerImageAPIClient.isInitialized) { val gson = GsonBuilder() .setLenient() .create() val okHttpClient = OkHttpClient.Builder() .readTimeout(5000, TimeUnit.SECONDS) .connectTimeout(100,TimeUnit.SECONDS) .build() flickerImageAPIClient = Retrofit.Builder() .baseUrl(Config.BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .build() .create(FlickerImageAPI::class.java) } return flickerImageAPIClient } }
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/FlickerImageAPIClient.kt
3483309414
package com.aman.flicker_image_gallery object Config { const val BASE_URL = "https://api.flickr.com/" }
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/Config.kt
3960703720
package com.aman.flicker_image_gallery.model data class Photo( val farm: Int, val height_s: Int, val id: String, val isfamily: Int, val isfriend: Int, val ispublic: Int, val owner: String, val secret: String, val server: String, val title: String, val url_s: String, val width_s: Int )
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/model/Photo.kt
3750930613
package com.aman.flicker_image_gallery.model data class Photos( val page: Int, val pages: Int, val perpage: Int, val photo: List<Photo>, val total: Int )
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/model/Photos.kt
2451513400
package com.aman.flicker_image_gallery.model data class FlickerAPIImageResponse( val photos: Photos, val stat: String )
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/model/FlickerAPIImageResponse.kt
1258093149
package com.aman.flicker_image_gallery import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class FIGApplication: Application() { }
OnlineGalleryApp/app/src/main/java/com/aman/flicker_image_gallery/FIGApplication.kt
1467108462
package nl.bjornvanderlaan.eventdrivenscaling.producer.simulation import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.currentTime import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import java.util.concurrent.atomic.AtomicInteger @ExperimentalCoroutinesApi @TestInstance(TestInstance.Lifecycle.PER_CLASS) class SimulationTest { private val simulation = Simulation() @Test fun `Test constant requests pattern`() = runTest { val startTime = currentTime simulation.addConstantRequestsStep(2, 5) val counter = AtomicInteger(0) simulation.executeWith { counter.incrementAndGet() } val endTime = currentTime assertEquals(endTime - startTime, 2000L, "Expected elapsed time equals 2 seconds") assertEquals(10, counter.get(), "Expected 10 requests") } @Test fun `Test linear requests pattern`() = runTest { val startTime = currentTime simulation.addLinearRequestsStep(2, 2, 4) val counter = AtomicInteger(0) simulation.executeWith { counter.incrementAndGet() } val endTime = currentTime assertEquals(endTime - startTime, 2000L, "Expected elapsed time equals 2 seconds") assertEquals(6, counter.get(), "Expected 6 requests") } @Test fun `Test pause pattern`() = runTest { val startTime = currentTime simulation.addPauseStep(5) val counter = AtomicInteger(0) simulation.executeWith { counter.incrementAndGet() } val endTime = currentTime assertEquals(endTime - startTime, 5000L, "Expected elapsed time equals 5 seconds") assertEquals(0, counter.get(), "Expected 0 requests") } @Test fun `Test all patterns together`() = runTest { val startTime = currentTime simulation.addConstantRequestsStep(3, 5) simulation.addPauseStep(5) simulation.addLinearRequestsStep(2, 2, 4) val counter = AtomicInteger(0) simulation.executeWith { counter.incrementAndGet() } val endTime = currentTime assertEquals(endTime - startTime, 10000L, "Expected elapsed time equals 10 seconds") assertEquals(21, counter.get(), "Expected 16 requests") } }
event-driven-keda-kubernetes/producer/src/test/kotlin/nl/bjornvanderlaan/eventdrivenscaling/producer/simulation/SimulationTest.kt
4115630173
package nl.bjornvanderlaan.eventdrivenscaling.producer.simulation import kotlinx.coroutines.delay import kotlin.system.measureTimeMillis typealias RequestAction = () -> Unit typealias SimulationStep = suspend (RequestAction) -> Unit class Simulation { private val steps: MutableList<SimulationStep> = mutableListOf() fun addConstantRequestsStep(durationSeconds: Int, requestsPerSecond: Int) { steps.add { requestAction -> repeat(durationSeconds) { val executionTime = measureTimeMillis { repeat(requestsPerSecond) { requestAction.invoke() } } delay(1000L - executionTime) } println("""Applied constant traffic of $requestsPerSecond requests per second for $durationSeconds seconds.""") } } fun addLinearRequestsStep(durationSeconds: Int, startRequestsPerSecond: Int, endRequestsPerSecond: Int) { steps.add { requestAction -> val slope = (endRequestsPerSecond - startRequestsPerSecond) / (durationSeconds - 1) repeat(durationSeconds) { val executionTime = measureTimeMillis { repeat(startRequestsPerSecond + (slope * it)) { requestAction.invoke() } } delay(1000L - executionTime) } println("""Applied linear traffic, growing from $startRequestsPerSecond to to $endRequestsPerSecond requests per second for $durationSeconds seconds.""") } } fun addPauseStep(durationSeconds: Int) { steps.add { delay(durationSeconds * 1000L) println("Paused for $durationSeconds seconds.") } } suspend fun start(requestAction: RequestAction) { println(""" +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+ |S|i|m|u|l|a|t|i|o|n| |s|t|a|r|t|e|d|.|.|.| +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+ """.trimIndent()) val executionTime = measureTimeMillis { steps.map { it.invoke(requestAction) println("") } } println(""" +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+ |S|i|m|u|l|a|t|i|o|n| |c|o|m|p|l|e|t|e|d|!| |Run time: $executionTime milliseconds. +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+ """.trimIndent()) } } suspend fun Simulation.executeWith(requestAction: RequestAction) { this.start(requestAction) }
event-driven-keda-kubernetes/producer/src/main/kotlin/nl/bjornvanderlaan/eventdrivenscaling/producer/simulation/Simulation.kt
3879320907
package nl.bjornvanderlaan.eventdrivenscaling.producer.simulation class SimulationDsl { private val simulation = Simulation() inner class SimulationStepDsl(private val durationSeconds: Int) { infix fun linearlyGrowingNumberOfRequestsFrom(startAndEndRequestsPerSecond: Pair<Int, Int>) { val (start, end) = startAndEndRequestsPerSecond simulation.addLinearRequestsStep(durationSeconds, start, end) } infix fun constantNumberOfRequests(requestsPerSecond: Int) { simulation.addConstantRequestsStep(durationSeconds, requestsPerSecond) } fun pause() { simulation.addPauseStep(durationSeconds) } } val Int.seconds get() = SimulationStepDsl(this) fun build() = simulation } fun simulation(description: SimulationDsl.() -> Unit): Simulation { val simulationBuilder = SimulationDsl() simulationBuilder.apply(description) return simulationBuilder.build() }
event-driven-keda-kubernetes/producer/src/main/kotlin/nl/bjornvanderlaan/eventdrivenscaling/producer/simulation/SimulationDsl.kt
989745541
package nl.bjornvanderlaan.eventdrivenscaling.producer import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.scheduling.annotation.EnableScheduling @EnableScheduling @SpringBootApplication class ProducerApplication fun main(args: Array<String>) { runApplication<ProducerApplication>(*args) }
event-driven-keda-kubernetes/producer/src/main/kotlin/nl/bjornvanderlaan/eventdrivenscaling/producer/ProducerApplication.kt
1581268658
package nl.bjornvanderlaan.eventdrivenscaling.producer import nl.bjornvanderlaan.eventdrivenscaling.producer.queue.QueueService import nl.bjornvanderlaan.eventdrivenscaling.producer.simulation.simulation import nl.bjornvanderlaan.eventdrivenscaling.producer.simulation.executeWith import org.slf4j.LoggerFactory import org.springframework.boot.context.event.ApplicationReadyEvent import org.springframework.context.event.EventListener import org.springframework.stereotype.Component @Component class TaskProducer(val queueService: QueueService) { @EventListener(ApplicationReadyEvent::class) suspend fun startSimulation() { val simulation = simulation { 10.seconds constantNumberOfRequests 10 5.seconds.pause() 15.seconds linearlyGrowingNumberOfRequestsFrom (1 to 3) } simulation.executeWith { produceRandomTask()} } fun produceRandomTask() { val result = queueService.publishTask(Task.randomTask()) return if (result != null) { LOGGER.info("Task is successfully published in message ${result.messageId}.") } else { LOGGER.error("Task publishing failed.") } } companion object { private val LOGGER = LoggerFactory.getLogger(QueueService::class.java) } }
event-driven-keda-kubernetes/producer/src/main/kotlin/nl/bjornvanderlaan/eventdrivenscaling/producer/TaskProducer.kt
3081948702
package nl.bjornvanderlaan.eventdrivenscaling.producer.queue import com.amazonaws.services.sqs.AmazonSQS import com.amazonaws.services.sqs.model.* import nl.bjornvanderlaan.eventdrivenscaling.producer.Task import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.boot.context.event.ApplicationReadyEvent import org.springframework.context.event.EventListener import org.springframework.stereotype.Service import java.util.* @Service class QueueService(private val amazonSQS: AmazonSQS, @Value("\${aws.base-url}\${aws.queue.url}") private val queueUrl: String) { @EventListener fun createQueueJustInCase(event: ApplicationReadyEvent) { amazonSQS.createQueue("task-queue") } fun publishTask(task: Task): SendMessageResult? { return publishMessage(Json.encodeToString(task)) } fun publishMessage(message: String): SendMessageResult? { return try { val sendMessageRequest = SendMessageRequest() .withQueueUrl(queueUrl) .withMessageBody(message) return amazonSQS.sendMessage(sendMessageRequest) } catch (e: Exception) { LOGGER.error("Exception e : {}", e.message) null } } companion object { private val LOGGER = LoggerFactory.getLogger(QueueService::class.java) } }
event-driven-keda-kubernetes/producer/src/main/kotlin/nl/bjornvanderlaan/eventdrivenscaling/producer/queue/QueueService.kt
2808597799
package nl.bjornvanderlaan.eventdrivenscaling.producer.queue import com.amazonaws.auth.AWSCredentials import com.amazonaws.auth.AWSStaticCredentialsProvider import com.amazonaws.auth.BasicAWSCredentials import com.amazonaws.client.builder.AwsClientBuilder import com.amazonaws.regions.Regions import com.amazonaws.services.sqs.AmazonSQS import com.amazonaws.services.sqs.AmazonSQSClientBuilder import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class AWSConfig { fun credentials(): AWSCredentials { return BasicAWSCredentials( "accesskey", "secretkey" ) } @Bean fun amazonSQS(@Value("\${aws.base-url}") baseUrl: String): AmazonSQS { return AmazonSQSClientBuilder .standard() .withEndpointConfiguration(getEndpointConfiguration(baseUrl)) .withCredentials(AWSStaticCredentialsProvider(credentials())) .build() } private fun getEndpointConfiguration(url: String): AwsClientBuilder.EndpointConfiguration { return AwsClientBuilder.EndpointConfiguration(url, Regions.EU_WEST_1.getName()) } }
event-driven-keda-kubernetes/producer/src/main/kotlin/nl/bjornvanderlaan/eventdrivenscaling/producer/queue/AWSConfig.kt
3857269008
package nl.bjornvanderlaan.eventdrivenscaling.producer import kotlinx.serialization.Serializable import java.util.* import kotlin.random.Random @Serializable data class Task(val id: String, val taskNumber: Int) { companion object { fun randomTask() = Task(UUID.randomUUID().toString(), Random.nextInt()) } }
event-driven-keda-kubernetes/producer/src/main/kotlin/nl/bjornvanderlaan/eventdrivenscaling/producer/Task.kt
956845197
package com.xebia.carbonaware.consumer import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.scheduling.annotation.EnableScheduling @EnableScheduling @SpringBootApplication class ConsumerApplication fun main(args: Array<String>) { runApplication<ConsumerApplication>(*args) }
event-driven-keda-kubernetes/consumer/src/main/kotlin/com/xebia/carbonaware/consumer/ConsumerApplication.kt
465237876
package com.xebia.carbonaware.consumer import com.xebia.carbonaware.consumer.queue.QueueService import com.xebia.carbonaware.consumer.task.TaskProcessor import org.slf4j.LoggerFactory import org.springframework.boot.context.event.ApplicationReadyEvent import org.springframework.context.event.EventListener import org.springframework.stereotype.Component @Component class QueueConsumer( val taskProcessor: TaskProcessor, val queueService: QueueService ) { @EventListener fun consume(event: ApplicationReadyEvent) { while (true) { val task = queueService.receiveTask() task?.let { val result = taskProcessor.process(it) LOGGER.info("Task ${it.id} executed successfully. Result = ${result}.") } } } companion object { private val LOGGER = LoggerFactory.getLogger(QueueConsumer::class.java) } }
event-driven-keda-kubernetes/consumer/src/main/kotlin/com/xebia/carbonaware/consumer/QueueConsumer.kt
1781282939
package com.xebia.carbonaware.consumer.task import org.springframework.stereotype.Component @Component class TaskProcessor { fun process(task: Task): Int = task.taskNumber * task.taskNumber }
event-driven-keda-kubernetes/consumer/src/main/kotlin/com/xebia/carbonaware/consumer/task/TaskProcessor.kt
3001478368
package com.xebia.carbonaware.consumer.task import kotlinx.serialization.Serializable @Serializable data class Task(val id: String, val taskNumber: Int)
event-driven-keda-kubernetes/consumer/src/main/kotlin/com/xebia/carbonaware/consumer/task/Task.kt
2815229792
package com.xebia.carbonaware.consumer.queue import com.amazonaws.services.sqs.AmazonSQS import com.amazonaws.services.sqs.model.* import com.xebia.carbonaware.consumer.task.Task import kotlinx.serialization.json.Json import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.boot.context.event.ApplicationReadyEvent import org.springframework.context.event.EventListener import org.springframework.stereotype.Service @Service class QueueService( private val amazonSQS: AmazonSQS, @Value("\${aws.base-url}\${aws.queue.url}") private val queueUrl: String ) { @EventListener fun createQueueJustInCase(event: ApplicationReadyEvent) { amazonSQS.createQueue("task-queue") } fun receiveTask(): Task? { val message = receiveMessage() return if (message != null) { LOGGER.info("Task received with id ${message.messageId}.") Json.decodeFromString<Task>(message.body) } else { LOGGER.error("No tasks waiting in the queue.") null } } fun receiveMessage(): Message? { val receiveMessageRequest = ReceiveMessageRequest() receiveMessageRequest.queueUrl = queueUrl receiveMessageRequest.waitTimeSeconds = 5 receiveMessageRequest.maxNumberOfMessages = 1 return amazonSQS.receiveMessage(receiveMessageRequest).messages.firstOrNull()?.also { message -> amazonSQS.deleteMessage(queueUrl, message.receiptHandle) } } companion object { private val LOGGER = LoggerFactory.getLogger(QueueService::class.java) } }
event-driven-keda-kubernetes/consumer/src/main/kotlin/com/xebia/carbonaware/consumer/queue/QueueService.kt
1632064607
package com.xebia.carbonaware.consumer.queue import com.amazonaws.auth.AWSCredentials import com.amazonaws.auth.AWSStaticCredentialsProvider import com.amazonaws.auth.BasicAWSCredentials import com.amazonaws.client.builder.AwsClientBuilder import com.amazonaws.regions.Regions import com.amazonaws.services.sqs.AmazonSQS import com.amazonaws.services.sqs.AmazonSQSClientBuilder import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class AWSConfig { fun credentials(): AWSCredentials { return BasicAWSCredentials( "accesskey", "secretkey" ) } @Bean fun amazonSQS(@Value("\${aws.base-url}") baseUrl: String): AmazonSQS { return AmazonSQSClientBuilder .standard() .withEndpointConfiguration(getEndpointConfiguration(baseUrl)) .withCredentials(AWSStaticCredentialsProvider(credentials())) .build() } private fun getEndpointConfiguration(url: String): AwsClientBuilder.EndpointConfiguration { return AwsClientBuilder.EndpointConfiguration(url, Regions.EU_WEST_1.getName()) } }
event-driven-keda-kubernetes/consumer/src/main/kotlin/com/xebia/carbonaware/consumer/queue/AWSConfig.kt
3510457900
package com.darrenr21.helloworld 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.darrenr21.helloworld", appContext.packageName) } }
HelloWorldKotlin/app/src/androidTest/java/com/darrenr21/helloworld/ExampleInstrumentedTest.kt
2044297751
package com.darrenr21.helloworld 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) } }
HelloWorldKotlin/app/src/test/java/com/darrenr21/helloworld/ExampleUnitTest.kt
1392246621
package com.darrenr21.helloworld.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)
HelloWorldKotlin/app/src/main/java/com/darrenr21/helloworld/ui/theme/Color.kt
1881863825
package com.darrenr21.helloworld.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 HelloWorldTheme( 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 ) }
HelloWorldKotlin/app/src/main/java/com/darrenr21/helloworld/ui/theme/Theme.kt
164240038