Snippets Collections
Task-5:
1. Create a program with different types of dwellings (Shelters people live in like roundhut, square cabin, round tower) that are implemented as a class hierarchy.
import kotlin.math.PI
import kotlin.math.sqrt

fun main() {
    val squareCabin = SquareCabin(6, 50.0)
    val roundHut = RoundHut(3, 10.0)
    val roundTower = RoundTower(4, 15.5)

    println("\nSquare Cabin\n============")
    squareCabin.printDetails()

    println("\nRound Hut\n=========")
    roundHut.printDetails()
    println("Has room? ${roundHut.hasRoom()}")
    roundHut.getRoom()
    println("Has room? ${roundHut.hasRoom()}")
    println("Carpet size: ${roundHut.calculateMaxCarpetLength()}")

    println("\nRound Tower\n==========")
    roundTower.printDetails()
    println("Carpet Length: ${roundTower.calculateMaxCarpetLength()}")
}

// Base class for all dwellings
abstract class Dwelling(private var residents: Int) {
    abstract val buildingMaterial: String
    abstract val capacity: Int

    abstract fun floorArea(): Double

    fun hasRoom(): Boolean = residents < capacity

    fun getRoom() {
        if (hasRoom()) {
            residents++
            println("You got a room!")
        } else {
            println("Sorry, no rooms left.")
        }
    }

    fun printDetails() {
        println("Material: $buildingMaterial")
        println("Capacity: $capacity")
        println("Floor area: ${floorArea()}")
    }
}

// SquareCabin subclass
class SquareCabin(residents: Int, val length: Double) : Dwelling(residents) {
    override val buildingMaterial = "Wood"
    override val capacity = 6

    override fun floorArea(): Double = length * length
}

// RoundHut subclass
open class RoundHut(residents: Int, val radius: Double) : Dwelling(residents) {
    override val buildingMaterial = "Straw"
    override val capacity = 4

    override fun floorArea(): Double = PI * radius * radius

    fun calculateMaxCarpetLength(): Double = sqrt(2.0) * radius
}

// RoundTower subclass
class RoundTower(residents: Int, radius: Double, val floors: Int = 2) : RoundHut(residents, radius) {
    override val buildingMaterial = "Stone"
    override val capacity = floors * 4

    override fun floorArea(): Double = super.floorArea() * floors
}
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.prog2.ui.theme.Prog2Theme
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            val nav_Controller = rememberNavController()
            NavHost(navController = nav_Controller, startDestination = "fragment1")
          			{
                composable("fragment1") 
                      {
                    Fragment1(nav_Controller)
               			 }
                composable("fragment2") {
                    Fragment2(nav_Controller)
                }
            }
        }
    }
}
 
 
@Composable
fun Fragment1(navController: NavController){
    Column {
        Button(onClick={ navController.navigate("fragment2")}) {
            Text(text = "Navigate to fragment2 ")
        }
    }
}
 
 
@Composable
fun Fragment2(navController: NavController) {
    Row(horizontalArrangement = Arrangement.SpaceEvenly){
        
        Button(onClick = { navController.navigateUp() }) {
            Text(text = "Back to Fragment 1")
        }
    }
}
dependencies {
    implementation "androidx.compose.ui:ui:1.3.0"
    implementation "androidx.compose.material3:material3:1.0.0"
    implementation "androidx.navigation:navigation-compose:2.5.3"
    // Other dependencies...
}
package com.example.dwellings

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

open class Dwelling(
    val name: String,
    val capacity: Int
) {
    open fun description(): String {
        return "The $name can accommodate $capacity people."
    }
}

class RoundHut(
    capacity: Int,
    private val radius: Double
) : Dwelling("Round Hut", capacity) {

    fun floorArea(): Double {
        return Math.PI * radius * radius
    }

    override fun description(): String {
        return super.description() + " It has a floor area of ${"%.2f".format(floorArea())} square meters."
    }
}

class SquareCabin(
    capacity: Int,
    private val sideLength: Double
) : Dwelling("Square Cabin", capacity) {

    fun floorArea(): Double {
        return sideLength * sideLength
    }

    override fun description(): String {
        return super.description() + " It has a floor area of ${"%.2f".format(floorArea())} square meters."
    }
}

class RoundTower(
    capacity: Int,
    private val radius: Double,
    private val floors: Int
) : Dwelling("Round Tower", capacity) {

    fun floorArea(): Double {
        return Math.PI * radius * radius * floors
    }

    override fun description(): String {
        return super.description() + " It has $floors floors and a total floor area of ${"%.2f".format(floorArea())} square meters."
    }
}

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val roundHut = RoundHut(4, 5.0)
        val squareCabin = SquareCabin(6, 4.0)
        val roundTower = RoundTower(8, 3.5, 3)

        val dwellings = listOf(roundHut, squareCabin, roundTower)

        dwellings.forEach { dwelling ->
            println(dwelling.description())
        }
    }
}
// MainActivity.kt
package com.example.activitylifecycle

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.activitylifecycle.ui.theme.ActivityLifeCycleTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        Toast.makeText(applicationContext,"ON CREATE() IS CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStart(){
        super.onStart()
        Toast.makeText(applicationContext,"ON START() IS CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onRestart(){
        super.onRestart()
        Toast.makeText(applicationContext,"ON RESTART() IS CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onResume(){
        super.onResume()
        Toast.makeText(applicationContext,"ON RESUME() IS CALLED",Toast.LENGTH_LONG).show()
    }
    override fun onPause(){
        super.onPause()
        Toast.makeText(applicationContext,"ON PAUSE() IS CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStop(){
        super.onStop()
        Toast.makeText(applicationContext,"ON STOP() IS CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onDestroy(){
        super.onDestroy()
        Toast.makeText(applicationContext,"ON DESTROY() IS CALLED",Toast.LENGTH_SHORT).show()
    }
}
package com.example.activitylifecycle

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.activitylifecycle.ui.theme.ActivityLifeCycleTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        Toast.makeText(applicationContext,"ON CREATE() IS CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStart(){
        super.onStart()
        Toast.makeText(applicationContext,"ON START() IS CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onRestart(){
        super.onRestart()
        Toast.makeText(applicationContext,"ON RESTART() IS CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onResume(){
        super.onResume()
        Toast.makeText(applicationContext,"ON RESUME() IS CALLED",Toast.LENGTH_LONG).show()
    }
    override fun onPause(){
        super.onPause()
        Toast.makeText(applicationContext,"ON PAUSE() IS CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStop(){
        super.onStop()
        Toast.makeText(applicationContext,"ON STOP() IS CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onDestroy(){
        super.onDestroy()
        Toast.makeText(applicationContext,"ON DESTROY() IS CALLED",Toast.LENGTH_SHORT).show()
    }
}
BillTip

package com.example.billtip

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.billtip.ui.theme.BillTipTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Calculate()

        }
    }
}

//100 1% 1rs

@Composable
fun Calculate(){
    var totalBill by remember {
        mutableStateOf("0")
    }
    var tipPercentage by remember {
        mutableStateOf("0")
    }
    var ans by remember { mutableStateOf(0.0) }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        TextField(value = totalBill, onValueChange = {totalBill = it}, label = { Text(text = "Enter Total Bill Amount")} )
        TextField(value = tipPercentage, onValueChange = {tipPercentage = it}, label = { Text(text = "Enter Tip Percentage")} )

        Button(onClick = { 
            var bill = totalBill.toDouble()
            var tip = tipPercentage.toDouble()
            ans = bill*(tip/100)
            
        }) {
            Text(text = "Calculate Tip Amount")
        }
        
        Text(text = "Tip Amount is ${ans}")
    }
}
package com.example.tipcalculator

import android.os.Bundle
import android.widget.Space
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.tipcalculator.ui.theme.TipCalculatorTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            TipCalculatorTheme {
              calc()
            }
        }
    }
@Composable
fun calc(){
    var totalbill by remember { mutableStateOf("0") }
    var tip by remember { mutableStateOf("0") }
    var ans by remember { mutableStateOf(0.0) }

    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        TextField(
            value = totalbill,
            onValueChange = { totalbill = it },
            label = { Text(text = "Enter bill amount:") }
        )
        Spacer(modifier = Modifier.height(16.dp))
        TextField(
            value = tip,
            onValueChange = { tip = it },
            label = { Text(text = "Enter tip percentage:") }
        )
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = {
            val bill = totalbill.toDouble()
            val t = tip.toDouble()
            ans=bill * (t / 100)
        }) {
            Text(text = "Calculate Tip Amount")
        }
        Spacer(modifier = Modifier.height(16.dp))
        Text(
            text = "The tip amount is $ans",
            fontSize = 24.sp
        )
    }
}





}



package com.example.navigator

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.navigator.ui.theme.NavigatorTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
                val nav_Controller=rememberNavController()
                NavHost(navController=nav_Controller,startDestination="fragment1") {
                    composable("fragment1") { Fragment1(nav_Controller) }
                    composable("fragment2") { Fragment2(nav_Controller) }
            }
        }
    }
}

@Composable
fun Fragment1(navController: NavController){
    Column(modifier=Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center) {
        Spacer(modifier = Modifier.height(120.dp))
        Text(text = "this is fragment 1", color = Color.Green, fontSize = 30.sp)
    }
    Box(contentAlignment= Alignment.Center,
        modifier=Modifier.fillMaxSize()){
        Button(onClick={navController.navigate("fragment2")}){
            Text(text="Go to fragment 2", fontSize = 30.sp)
        }
    }
}
@Composable
fun Fragment2(navController: NavController){
    Column(modifier=Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center){
        Spacer(modifier=Modifier.height(120.dp))
        Text(text="this is fragment 2",color=Color.Green, fontSize = 30.sp)
    }
    Box(contentAlignment=Alignment.Center,modifier=Modifier.fillMaxSize()){
        Button(onClick={navController.navigateUp()}){
            Text(text="Go to fragment 1", fontSize = 30.sp)
        }
    }

}
package com.example.dwelling

import android.os.Bundle

import androidx.activity.ComponentActivity

import androidx.activity.compose.setContent

import androidx.activity.enableEdgeToEdge

import androidx.compose.foundation.layout.Arrangement

import androidx.compose.foundation.layout.Column

import androidx.compose.foundation.layout.Spacer

import androidx.compose.foundation.layout.fillMaxSize

import androidx.compose.foundation.layout.height

import androidx.compose.foundation.layout.padding

import androidx.compose.material3.Scaffold

import androidx.compose.material3.Text

import androidx.compose.runtime.Composable

import androidx.compose.ui.Alignment

import androidx.compose.ui.Modifier

import androidx.compose.ui.tooling.preview.Preview

import androidx.compose.ui.unit.dp

import com.example.dwelling.ui.theme.DwellingTheme

open class Dwelling(val resident:Int){

    open val buildingMaterial:String = "Genericmateril"

    open val capacity:Int =0

    fun hasRoom():Boolean{return resident<capacity}

    open fun description():String{

        return "This is dwelling is made of $buildingMaterial and has space for $capacity"

    }

}

class roundhut(resident: Int):Dwelling(resident){

    override val buildingMaterial: String = "straw"

    override val capacity: Int = 4

    fun floorArea(radius:Double):Double{

        return Math.PI*radius*radius

    }

    override fun description(): String {

        return "This is roundhut is made of $buildingMaterial and has space for $capacity"

    }

}

class squareCabin(resident: Int):Dwelling(resident){

    override val buildingMaterial: String = "wood"

    override val capacity: Int = 6

    fun floorArea(length:Double):Double{

        return length*length

    }

    override fun description(): String {

        return "This is squareCabin is made of $buildingMaterial and has space for $capacity"

    }

}

class roundtower(resident: Int,val floors:Int):Dwelling(resident){

    override val buildingMaterial: String = "wood"

    override val capacity: Int = 4 * floors

    fun floorArea(radius:Double):Double{

        return Math.PI*radius*radius*floors

    }

    override fun description(): String {

        return "This is roundtower is made of $buildingMaterial and has space for $capacity"

    }

}

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        enableEdgeToEdge()

        setContent {

            DwellingApp()

        }

    }

}

@Composable

fun DwellingApp(){

    val hut = roundhut(3)

    val cabin = squareCabin(5)

    val tower = roundtower(4,3)

    Column(modifier = Modifier.fillMaxSize().padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {

        Text(text=hut.description())

        Spacer(modifier = Modifier.height(8.dp))

        Text(text="FloorArea:${hut.floorArea(4.5)}")

        Spacer(modifier = Modifier.height(8.dp))

        Text(text=cabin.description())

        Spacer(modifier = Modifier.height(8.dp))

        Text(text="FloorArea:${cabin.floorArea(4.5)}")

        Spacer(modifier = Modifier.height(8.dp))

        Text(text=tower.description())

        Spacer(modifier = Modifier.height(8.dp))

        Text(text="FloorArea:${tower.floorArea(4.5)}")

        Spacer(modifier = Modifier.height(8.dp))

    }

}
package com.example.dicerollerapp

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.dicerollerapp.ui.theme.DiceRollerAppTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            DiceRollerAppTheme {
                Surface(modifier = Modifier.fillMaxSize(),color = MaterialTheme.colorScheme.background){
                        DiceRollerApp()
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun DiceRollerApp() {
    DiceWithButtonAndImage(modifier = Modifier.fillMaxSize().wrapContentSize(Alignment.Center)
    )
}

@Composable
fun DiceWithButtonAndImage(modifier: Modifier = Modifier) {
    var result by remember { mutableStateOf(1) }
    var imageResource = when(result){
        1 -> R.drawable.dice_1
        2 -> R.drawable.dice_2
        3 -> R.drawable.dice_3
        4 -> R.drawable.dice_4
        5 -> R.drawable.dice_5
        else -> R.drawable.dice_6
    }
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            painterResource(imageResource),
            contentDescription = result.toString()
        )
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = { result = (1..6).random() }) {
            Text(stringResource(R.string.roll), fontSize = 24.sp)
        }
    }
}


in xml file:
<resource>
  <string name="roll">Roll</String>
</resource>
activity main.xml
****
  <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LIFE CYCLE"
        android:textSize="18sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintVertical_bias="0.5"
        app:layout_constraintHorizontal_bias="0.5"
        tools:ignore="MissingConstraints" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
*******
     main activity.kt
*****
       package com.example.myapplication
 
 
 
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
 
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, false) // Enables edge-to-edge
        setContentView(R.layout.activity_main)
        Toast.makeText(applicationContext, "onCreate() called", Toast.LENGTH_SHORT).show()
    }
 
    override fun onStart() {
        super.onStart()
        Toast.makeText(applicationContext, "onStart() called", Toast.LENGTH_SHORT).show()
    }
 
    override fun onResume() {
        super.onResume()
        Toast.makeText(applicationContext, "onResume() called", Toast.LENGTH_SHORT).show()
    }
 
    override fun onPause() {
        super.onPause()
        Toast.makeText(applicationContext, "onPause() called", Toast.LENGTH_SHORT).show()
    }
 
    override fun onStop() {
        super.onStop()
        Toast.makeText(applicationContext, "onStop() called", Toast.LENGTH_SHORT).show()
    }
 
    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(applicationContext, "onDestroy() called", Toast.LENGTH_SHORT).show()
    }
}
******
package com.example.dwelling

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.dwelling.ui.theme.DwellingTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            DwellingApp()
        }
    }
}

open class Dwelling(val residents: Int) {
    open val buildingMaterial: String = "Generic Material"
    open val capacity: Int = 0

    fun hasRoom(): Boolean {
        return residents < capacity
    }

    open fun description(): String {
        return "This dwelling is made of $buildingMaterial and has space for $capacity."
    }
}

class RoundHut(residents: Int) : Dwelling(residents) {
    override val buildingMaterial: String = "Straw"
    override val capacity: Int = 4

    fun floorArea(radius: Double): Double {
        return Math.PI * radius * radius
    }

    override fun description(): String {
        return "This is a round hut made of $buildingMaterial with space for $capacity people."
    }
}

class SquareCabin(residents: Int) : Dwelling(residents) {
    override val buildingMaterial: String = "Wood"
    override val capacity: Int = 6

    fun floorArea(length: Double): Double {
        return length * length
    }

    override fun description(): String {
        return "This is a square cabin made of $buildingMaterial with space for $capacity people."
    }
}

class RoundTower(residents: Int, val floors: Int) : Dwelling(residents) {
    override val capacity: Int = 4 * floors

    fun floorArea(radius: Double): Double {
        return Math.PI * radius * radius * floors
    }

    override fun description(): String {
        return "This is a round tower made of $buildingMaterial with $floors floors and space for $capacity people."
    }
}

@Composable
fun DwellingApp() {
    val roundHut = RoundHut(3)
    val squareCabin = SquareCabin(5)
    val roundTower = RoundTower(4, 3)

    Column {
        Text(
            text = roundHut.description(),
            style = MaterialTheme.typography.bodyMedium
        )
        Text(
            text = "Floor Area: ${roundHut.floorArea(4.5)}"
        )
        Spacer(modifier = Modifier.height(16.dp))
        Text(
            text = squareCabin.description()
        )
        Text(
            text = "Floor Area: ${squareCabin.floorArea(5.0)}"
        )
        Text(
            text = roundTower.description()
        )
        Text(
            text = "Floor Area: ${roundTower.floorArea(4.0)}"
        )
    }
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Demonstrating Activity Lifecycle"
        android:textColor="#3C3232"
        android:textSize="18sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt:

package com.example.activitylifecycle

import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        Toast.makeText(applicationContext,"ONCREATE() CALLED",Toast.LENGTH_SHORT).show()
    }

    override fun onStart() {
        super.onStart()
        Toast.makeText(applicationContext,"ONSTART() CALLED",Toast.LENGTH_SHORT).show()
    }

    override fun onRestart() {
        super.onRestart()
        Toast.makeText(applicationContext,"ONRESTART() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onResume() {
        super.onResume()
        Toast.makeText(applicationContext,"ONRESUME() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onPause() {
        super.onPause()
        Toast.makeText(applicationContext,"ONPAUSE() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStop() {
        super.onStop()
        Toast.makeText(applicationContext,"ONSTOP() CALLED",Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(applicationContext,"ONDESTROY() CALLED",Toast.LENGTH_SHORT).show()
    }
}
# Basic installation
pip install praisonai

# Framework-specific installations
pip install "praisonai[crewai]"    # Install with CrewAI support
pip install "praisonai[autogen]"   # Install with AutoGen support
pip install "praisonai[crewai,autogen]"  # Install both frameworks

# Additional features
pip install "praisonai[ui]"        # Install UI support
pip install "praisonai[chat]"      # Install Chat interface
pip install "praisonai[code]"      # Install Code interface
pip install "praisonai[realtime]"  # Install Realtime voice interaction
pip install "praisonai[call]"      # Install Call feature
# UI support
pip install "praisonai[ui]"

# Chat interface
pip install "praisonai[chat]"

# Code interface
pip install "praisonai[code]"

# Realtime voice interaction
pip install "praisonai[realtime]"

# Call feature
pip install "praisonai[call]"
pip install "praisonai[crewai,autogen]"
//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/bt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click here"
        android:textSize="25dp"
        android:textColor="@color/design_default_color_primary"
        />


</LinearLayout>
//MainActivity.kt


import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val b1:Button = findViewById(R.id.bt1)

        b1.setOnClickListener {
            val intent = Intent(this, DetailsActivity::class.java)

            Toast.makeText(this, "Hello Details Activity", Toast.LENGTH_SHORT).show()
            startActivity(intent)
        }
    }
}
//DetailsActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class DetailsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)
    }
}

//activity_details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DetailsActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to second activity"
        android:textSize="35dp"
        android:textColor="@color/black"
        />

</LinearLayout>

//In the manifest.xml file below the <activity/> insert the code
<activity android:name=".DetailsActivity"></activity>
//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/bt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click here"
        android:textSize="25dp"
        android:textColor="@color/design_default_color_primary"
        />


</LinearLayout>
//MainActivity.kt


import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val b1:Button = findViewById(R.id.bt1)

        b1.setOnClickListener {
            val intent = Intent(this, DetailsActivity::class.java)

            Toast.makeText(this, "Hello Details Activity", Toast.LENGTH_SHORT).show()
            startActivity(intent)
        }
    }
}
//DetailsActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class DetailsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)
    }
}

//activity_details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DetailsActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to second activity"
        android:textSize="35dp"
        android:textColor="@color/black"
        />

</LinearLayout>

//In the manifest.xml file below the <activity/> insert the code
<activity android:name=".DetailsActivity"></activity>
//Explicit Intent

MainActivity.kt

package com.example.intent

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val b1:Button = findViewById(R.id.bt1)

        b1.setOnClickListener {
            val intent = Intent(this, DetailsActivity::class.java)

            Toast.makeText(this, "Hello Details Activity", Toast.LENGTH_SHORT).show()
            startActivity(intent)
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/bt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click here"
        android:textSize="25dp"
        android:textColor="@color/teal_200"
        />


</LinearLayout>

DetailsActivity.kt

package com.example.intent

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class DetailsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)
    }
}

activity_deatils.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DetailsActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to second activity"
        android:textSize="35dp"
        android:textColor="@color/purple_700"
        />

</LinearLayout>


/*
Add this line below </activity> in AndroidManifest.xml

<activity android:name=".DetailsActivity"></activity>

*/
package com.example.external

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.example.external.ui.theme.ExternalTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Surface(modifier=Modifier.fillMaxSize(),color = Color.White) {
                Box(contentAlignment = Alignment.Center,modifier = Modifier.fillMaxSize()){
                    Text(text = "HelloWorld", color = Color.Red, fontSize = 32.sp)
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    ExternalTheme {
        Greeting("World")
    }
}
hello world
package com.example.tipcalculatorkt

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.unit.times
import com.example.tipcalculatorkt.ui.theme.TipCalculatorktTheme
import kotlin.time.times

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            TipCalculatorktTheme {
               calc()
            }
        }
    }
}
@Composable
fun calc(){
    var totalbill by remember{
        mutableStateOf("0")
    }
    var tipp by remember {
        mutableStateOf("0")
    }
    var ans by remember {
        mutableStateOf("0.0")
    }
    Column (modifier = Modifier.fillMaxSize().padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center){
        TextField(value = totalbill, onValueChange = {totalbill =it},
            label = {Text(text = "Enter the total bill amount")})
        TextField(value = tipp, onValueChange = {tipp =it},
            label = {Text(text = "Enter the tip percentage")})
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = {var bill = totalbill.toDouble()
                            var tip = tipp.toDouble()
                            ans = (bill*(tip/100)).toString()
               }){
            Text(text="Calculate the tip")
        }
        if(ans=="0.0"){
            Text(text="Tip amount is $ans", fontSize = 30.sp)
        }
        else{
            Text(text = "Tip amount is $ans",fontSize = 20.sp)
        }
    }
}
//.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scientific Calculator</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="calculator">
        <input type="text" id="display" disabled>
        <div class="buttons">
            <button onclick="clearDisplay()">C</button>
            <button onclick="appendToDisplay('7')">7</button>
            <button onclick="appendToDisplay('8')">8</button>
            <button onclick="appendToDisplay('9')">9</button>
            <button onclick="appendToDisplay('/')">/</button>
            <button onclick="appendToDisplay('4')">4</button>
            <button onclick="appendToDisplay('5')">5</button>
            <button onclick="appendToDisplay('6')">6</button>
            <button onclick="appendToDisplay('')"></button>
            <button onclick="appendToDisplay('1')">1</button>
            <button onclick="appendToDisplay('2')">2</button>
            <button onclick="appendToDisplay('3')">3</button>
            <button onclick="appendToDisplay('-')">-</button>
            <button onclick="appendToDisplay('0')">0</button>
            <button onclick="appendToDisplay('.')">.</button>
            <button onclick="calculateResult()">=</button>
            <button onclick="appendToDisplay('+')">+</button>
            <button onclick="appendToDisplay('Math.sqrt(')">√</button>
            <button onclick="appendToDisplay('Math.pow(')">x²</button>
            <button onclick="appendToDisplay('Math.sin(')">sin</button>
            <button onclick="appendToDisplay('Math.cos(')">cos</button>
            <button onclick="appendToDisplay('Math.tan(')">tan</button>
            <button onclick="appendToDisplay('Math.PI')">π</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>


//.css
body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

.calculator {
    background: white;
    border-radius: 10px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    padding: 20px;
    width: 300px;
}

#display {
    width: 100%;
    height: 40px;
    font-size: 24px;
    margin-bottom: 10px;
    text-align: right;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.buttons {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
}

button {
    padding: 15px;
    font-size: 18px;
    border: none;
    border-radius: 5px;
    background-color: #007bff;
    color: white;
    cursor: pointer;
    transition: background-color 0.3s;
}

button:hover {
    background-color: #0056b3;
}


//.js
function appendToDisplay(value) {
    const display = document.getElementById('display');
    display.value += value;
}

function clearDisplay() {
    const display = document.getElementById('display');
    display.value = '';
}

function calculateResult() {
    const display = document.getElementById('display');
    try {
        display.value = eval(display.value);
    } catch (e) {
        display.value = 'Error';
    }
}
//,html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Grid & Flexbox Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>My Web Page</h1>
    </header>
    <main>
        <section class="grid-container">
            <div class="grid-item">Item 1</div>
            <div class="grid-item">Item 2</div>
            <div class="grid-item">Item 3</div>
            <div class="grid-item">Item 4</div>
            <div class="grid-item">Item 5</div>
            <div class="grid-item">Item 6</div>
        </section>
        <section class="flex-container">
            <div class="flex-item">Flex Item 1</div>
            <div class="flex-item">Flex Item 2</div>
            <div class="flex-item">Flex Item 3</div>
        </section>
    </main>
    <footer>
        <p>© 2024 My Web Page</p>
    </footer>
</body>
</html>
 
 
 
 
 
 
//.cc
* {
    box-sizing: border-box;
}
 
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f0f0f0;
}
 
header {
    background: #4CAF50;
    color: white;
    padding: 20px;
    text-align: center;
}
 
main {
    padding: 20px;
}
 
.grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 15px;
}
 
.grid-item {
    background: #ffeb3b;
    padding: 20px;
    text-align: center;
    transition: transform 0.3s ease, background-color 0.3s ease;
}
 
.grid-item:hover {
    transform: scale(1.05);
    background-color: #ffc107;
}
 
.flex-container {
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
}
 
.flex-item {
    background: #2196F3;
    color: white;
    padding: 20px;
    transition: transform 0.3s ease, opacity 0.3s ease;
    opacity: 0.8;
}
 
.flex-item:hover {
    transform: translateY(-5px);
    opacity: 1;
}
 
footer {
    background: #4CAF50;
    color: white;
    text-align: center;
    padding: 10px;
    position: relative;
    bottom: 0;
    width: 100%;
}
MainActivity.kt

package com.example.intent

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        val button : Button = findViewById(R.id.button)
        button.setOnClickListener {
            val intent = Intent(this, DetailsActivity::class.java)
//            intent.putExtra("message", "hello details activity")
            Toast.makeText(this, "hello details activity", Toast.LENGTH_LONG).show()
            startActivity(intent)
        }
    }
}



DetailsActivity.kt

package com.example.intent

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class DetailsActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_details)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.details)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }
}



activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Go to 2nd activity"
        android:textSize="35sp"
        android:textColor="@color/design_default_color_error"
        />
</LinearLayout>


activit_details.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/details"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DetailsActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Display Message here"
        android:textSize="35sp"
        android:textColor="@color/black"
        />

</LinearLayout>
HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Register</h1>
    <form id="registrationForm">
        <input type="text" id="username" placeholder="Username" required>
        <input type="email" id="email" placeholder="Email" required>
        <input type="password" id="password" placeholder="Password" required>
        <button type="submit">Register</button>
        <div id="message" class="error-message"></div>
    </form>
    <script src="script.js"></script>
</body>
</html>

script.js
document.getElementById("registrationForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent form submission
    validateRegistration();
});

function validateRegistration() {
    const username = document.getElementById("username").value;
    const email = document.getElementById("email").value;
    const password = document.getElementById("password").value;
    const messageDiv = document.getElementById("message");
    messageDiv.textContent = "";

    // Simple validation
    if (username.length < 3) {
        messageDiv.textContent = "Username must be at least 3 characters.";
        return;
    }
    if (!/\S+@\S+\.\S+/.test(email)) {
        messageDiv.textContent = "Email is not valid.";
        return;
    }
    if (password.length < 6) {
        messageDiv.textContent = "Password must be at least 6 characters.";
        return;
    }

    messageDiv.textContent = "Registration successful!";
    // You can proceed to send the data to the server here
}

User Login Page(HTML)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Login</h1>
    <form id="loginForm">
        <input type="email" id="loginEmail" placeholder="Email" required>
        <input type="password" id="loginPassword" placeholder="Password" required>
        <button type="submit">Login</button>
        <div id="loginMessage" class="error-message"></div>
    </form>
    <script src="script.js"></script>
</body>
</html>
script.js
document.getElementById("loginForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent form submission
    validateLogin();
});

function validateLogin() {
    const email = document.getElementById("loginEmail").value;
    const password = document.getElementById("loginPassword").value;
    const loginMessageDiv = document.getElementById("loginMessage");
    loginMessageDiv.textContent = "";

    // Simple validation
    if (!/\S+@\S+\.\S+/.test(email)) {
        loginMessageDiv.textContent = "Email is not valid.";
        return;
    }
    if (password.length < 6) {
        loginMessageDiv.textContent = "Password must be at least 6 characters.";
        return;
    }

    loginMessageDiv.textContent = "Login successful!";
    // You can proceed to authenticate the user here
}

 User Profile Page(HTML)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Profile</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>User Profile</h1>
    <form id="profileForm">
        <input type="text" id="profileUsername" placeholder="Username" required>
        <input type="email" id="profileEmail" placeholder="Email" required>
        <button type="submit">Update Profile</button>
        <div id="profileMessage" class="error-message"></div>
    </form>
    <script src="script.js"></script>
</body>
</html>

script.js
document.getElementById("profileForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent form submission
    validateProfile();
});

function validateProfile() {
    const username = document.getElementById("profileUsername").value;
    const email = document.getElementById("profileEmail").value;
    const profileMessageDiv = document.getElementById("profileMessage");
    profileMessageDiv.textContent = "";

    // Simple validation
    if (username.length < 3) {
        profileMessageDiv.textContent = "Username must be at least 3 characters.";
        return;
    }
    if (!/\S+@\S+\.\S+/.test(email)) {
        profileMessageDiv.textContent = "Email is not valid.";
        return;
    }

    profileMessageDiv.textContent = "Profile updated successfully!";
    // You can proceed to update the user profile on the server here
}
Payment page(HTML)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Payment</h1>
    <form id="paymentForm">
        <input type="text" id="cardNumber" placeholder="Card Number" required>
        <input type="text" id="expiryDate" placeholder="MM/YY" required>
        <input type="text" id="cvv" placeholder="CVV" required>
        <button type="submit">Pay</button>
        <div id="paymentMessage" class="error-message"></div>
    </form>
    <script src="script.js"></script>
</body>
</html>

script.js
document.getElementById("paymentForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Prevent form submission
    validatePayment();
});

function validatePayment() {
    const cardNumber = document.getElementById("cardNumber").value;
    const expiryDate = document.getElementById("expiryDate").value;
    const cvv = document.getElementById("cvv").value;
    const paymentMessageDiv = document.getElementById("paymentMessage");
    paymentMessageDiv.textContent = "";

    // Simple validation
    if (!/^\d{16}$/.test(cardNumber)) {
        paymentMessageDiv.textContent = "Card number must be 16 digits.";
        return;
    }
    if (!/^(0[1-9]|1[0-2])\/\d{2}$/.test(expiryDate)) {
        paymentMessageDiv.textContent = "Expiry date must be in MM/YY format.";
        return;
    }
    if (!/^\d{3}$/.test(cvv)) {
        paymentMessageDiv.textContent = "CVV must be 3 digits.";
        return;
    }

    paymentMessageDiv.textContent = "Payment successful!";
    // You can proceed to process the payment here
}
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val database = UserDatabase.getInstance(this)
            insertRecord(database)
        }
    }
}
 
@Composable
fun insertRecord(database: UserDatabase) {
    val context = LocalContext.current
    val userDao = database.userDao()
    var name by remember { mutableStateOf("") }
    var phone by remember { mutableStateOf("") }
    val scope = rememberCoroutineScope()
 
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        Text(text = "Enter your details here")
        Spacer(modifier = Modifier.height(16.dp))
        OutlinedTextField(
            value = name,
            onValueChange = { name = it },
            label = { Text(text = "Enter your name") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(8.dp))
        OutlinedTextField(
            value = phone,
            onValueChange = { phone = it },
            label = { Text(text = "Enter your phone number") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(16.dp))
        Button(
            onClick = {
                scope.launch(Dispatchers.IO) {
                    userDao.insert(User(userName = name, userPhone = phone))
                }
                Toast.makeText(context, "Record Inserted successfully", Toast.LENGTH_LONG).show()
            }
        ) {
            Text(text = "Insert Now")
        }
    }
}
//User.kt(create Data Class )
import androidx.room.Entity
import androidx.room.PrimaryKey
 
@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val userName: String,
    val userPhone: String
)
// UserDAO.kt(create interface)
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.*
@Dao
interface UserDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(user: User)
}
//class UserDatabase.kt
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
 
@Database(entities = [User::class], version = 1, exportSchema = false)
abstract class UserDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
 
    companion object {
        @Volatile
        private var INSTANCE: UserDatabase? = null
 
        fun getInstance(context: Context): UserDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    UserDatabase::class.java,
                    "user_database"
                ).build()
                INSTANCE = instance
                instance
            }
        }
    }
}
//dependencies
plugins-kotlin("kapt")
val room_version="2.6.1"
    implementation("androidx.room:room-runtime:$room_version")
    kapt("androidx.room:room-compiler:$room_version") // for annotation processing
    implementation("androidx.room:room-ktx:$room_version")
package com.example.image

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.image.ui.theme.ImageTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {



                    ImageAndText()

            
        }
    }
}





@Composable
fun ImageAndText() {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Image(
            painter = painterResource(id = R.drawable.rev),
            contentDescription = "Image description",
            modifier = Modifier.fillMaxWidth().padding(16.dp)
        )
        Spacer(modifier = Modifier.height(16.dp))
        Text(text = "Description about the image", fontSize = 30.sp)
    }
}


//MainActivity.kt

package com.example.lifecycle

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.lifecycle.R

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main) // Set the content view to the layout file
        Toast.makeText(applicationContext, "ONCREATE() CALLED", Toast.LENGTH_SHORT).show()
    }


    override fun onStart() {
        super.onStart()
        Toast.makeText(applicationContext, "ONSTART() CALLED", Toast.LENGTH_SHORT).show()
    }


    override fun onRestart() {
        super.onRestart()
        Toast.makeText(applicationContext, "ONRESTART() CALLED", Toast.LENGTH_SHORT).show()
    }


    override fun onResume() {
        super.onResume()
        Toast.makeText(applicationContext, "ONRESUME() CALLED", Toast.LENGTH_SHORT).show()
    }


    override fun onStop() {
        super.onStop()
        Toast.makeText(applicationContext, "ONSTOP() CALLED", Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(applicationContext, "ONDESTROY() CALLED", Toast.LENGTH_SHORT).show()
    }
}


//activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:gravity="center">


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Demonstration of ACTIVITY LIFE CYCLE Methods"
        android:textSize="18sp"
        android:textColor="@android:color/black"
        android:layout_marginBottom="16dp" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me" />

</LinearLayout>
//mainactivity.kt
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val database = UserDatabase.getInstance(this)
            insertRecord(database)
        }
    }
}

@Composable
fun insertRecord(database: UserDatabase) {
    val context = LocalContext.current
    val userDao = database.userDao()
    var name by remember { mutableStateOf("") }
    var phone by remember { mutableStateOf("") }
    val scope = rememberCoroutineScope()

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        Text(text = "Enter your details here")
        Spacer(modifier = Modifier.height(16.dp))
        OutlinedTextField(
            value = name,
            onValueChange = { name = it },
            label = { Text(text = "Enter your name") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(8.dp))
        OutlinedTextField(
            value = phone,
            onValueChange = { phone = it },
            label = { Text(text = "Enter your phone number") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(16.dp))
        Button(
            onClick = {
                scope.launch(Dispatchers.IO) {
                    userDao.insert(User(userName = name, userPhone = phone))
                }
                Toast.makeText(context, "Record Inserted successfully", Toast.LENGTH_LONG).show()
            }
        ) {
            Text(text = "Insert Now")
        }
    }
}
//User.kt(create Data Class )
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val userName: String,
    val userPhone: String
)
// UserDAO.kt(create interface)
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.*
@Dao
interface UserDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(user: User)
}
//class UserDatabase.kt
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

@Database(entities = [User::class], version = 1, exportSchema = false)
abstract class UserDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {
        @Volatile
        private var INSTANCE: UserDatabase? = null

        fun getInstance(context: Context): UserDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    UserDatabase::class.java,
                    "user_database"
                ).build()
                INSTANCE = instance
                instance
            }
        }
    }
}
//dependencies
plugins-kotlin("kapt")
val room_version="2.6.1"
    implementation("androidx.room:room-runtime:$room_version")
    kapt("androidx.room:room-compiler:$room_version") // for annotation processing
    implementation("androidx.room:room-ktx:$room_version")
//Empty Activity
 
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.example.myapplication.ui.theme.MyApplicationTheme
 
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Surface(modifier = Modifier.fillMaxSize(),
                color = Color.White
 
            ) {
                Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier.fillMaxSize()
                ){
                    Text(text = "Hello World",
                        color = Color.Red,
                        fontSize = 32.sp
                    )
 
                }
 
            }
        }
 
    }
}
package com.example.dice
 
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.dice.ui.theme.DiceTheme
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            DiceRoller()
        }
    }
}
 
@Composable
fun DiceRoller(modifier: Modifier = Modifier){
    var result by remember { mutableStateOf(1) }
 
    val imageResource = when(result){
        1 -> R.drawable.dice_1
        2 -> R.drawable.dice_2
        3 -> R.drawable.dice_3
        4 -> R.drawable.dice_4
        5 -> R.drawable.dice_5
        else -> R.drawable.dice_6
    }
 
    Column(
        modifier = modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ){
        Image(painter = painterResource(imageResource), contentDescription = result.toString())
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = {result = (1..6).random()}){
            Text(text = "Roll  Dice"+result)
 
        }
        Text(text = "Number"+result)
    }
}
////Then extract it
//Now come to android studio
//In Android Studio, click View > Tool Windows > Resource Manager.
//Click + > Import Drawables to open a file browser.
//Click Next.
//Click Import to confirm that you want to import the six images
//Empty Activity
 
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.example.myapplication.ui.theme.MyApplicationTheme
 
 
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Surface(modifier = Modifier.fillMaxSize(),
                color = Color.White
 
            ) {
                Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier.fillMaxSize()
                ){
                    Text(text = "Hello World",
                        color = Color.Red,
                        fontSize = 32.sp
                    )
 
                }
 
            }
        }
 
    }
}
class Greeting {
    var name:String=" "
    get() = field
    set(value){
        field = value
    }
    
    var msg:String=" "
    get() = field
    set(value){
        field = value
    }
}

fun main(args: Array<String>) {
    val obj = Greeting()
    obj.name = "abc"
    obj.msg = "Hello"
    println(obj.msg)
    println(obj.name)
}
fun greet(name:String,msg:String="Hello"){
    println(" $msg   $name")
}
fun main() {
    
    greet("cse","welcome")
    greet("mad")
}
import kotlin.random.Random
fun main() {
    
    var guess:Int?
    var targetNum=Random.nextInt(1,100)
    var attempts=0
    do{
        guess=readLine()?.toIntOrNull();
        attempts++
        if(guess==null){
            println("Enter valid number")
            
        }
        else{
        when{
            guess < targetNum -> println("Too low")
            guess > targetNum -> println("To high")
            else->println("Your have guess the nummber in $attempts attempts")
        }
        }
        
    }
    while(guess!=targetNum && guess != null)
    
}
fun main() {
    val inp:Int?=readLine()?.toIntOrNull();
    if(inp!=null){
        val sqr=inp*inp;
        println("Ssquare of given number is:$sqr")
    }
    else{
        println("Input is null");
    }
}
SELECT
EmailAddress, SubscriberKey, Consent_Level_Summary__c,
Business_Unit__c, Region, Cat_Campaign_Most_Recent__c , Mailing_Country__c, LastModifiedDate, System_Language__c, CreatedDate,
FirstName
 
FROM (
SELECT
DISTINCT LOWER(Email__c) AS EmailAddress, i.Region__c AS Region, c.Id AS SubscriberKey, c.Consent_Level_Summary__c, i.Business_Unit__c,i.Cat_Campaign_Most_Recent__c , i.Mailing_Country__c, i.LastModifiedDate, i.System_Language__c, i.CreatedDate,
c.FirstName,
 
ROW_NUMBER() OVER(PARTITION BY c.Id ORDER BY i.LastModifiedDate DESC) as RowNum
 
FROM ent.Interaction__c_Salesforce i
JOIN ent.Contact_Salesforce_1 c ON LOWER(c.Email) = LOWER(i.Email__c)
JOIN TEST_ps_an_en_us_s190010_Retail_TA_Segment_sendable_NEW new ON LOWER(new.EmailAddress) = LOWER(i.Email__c)
INNER JOIN ent.ContactPointConsent_Salesforce AS cpc ON c.Id = cpc.Contact__c
INNER JOIN ent.DataUsePurpose_Salesforce AS dup ON cpc.DataUsePurposeId = dup.Id

WHERE
     Email__c IS NOT NULL
    AND i.Business_Unit__c IN  ('CISD','GASD','Product Support','PS')
    AND Email__c NOT LIKE '%@cat.com'
    AND i.Mailing_Country__c IS NOT NULL
    AND cpc.CaptureContactPointType = 'Email'
    AND cpc.MATM_Owner__c = 'Caterpillar'
    AND dup.Name = 'Caterpillar Marketing'
    AND cpc.PrivacyConsentStatus = 'OptIn' 
    AND (cpc.EffectiveTo IS NULL OR cpc.EffectiveTo < GetDate())
 
    AND ((c.AMC_Last_Activity_Record_ID__c IS NULL) OR (c.AMC_Last_Activity_Record_ID__c <> 'Not Marketable'))
    AND (i.Mailing_State_Province__c != 'QC' OR (i.Mailing_Country__c != 'CA' AND i.Mailing_State_Province__c IS NULL))
    AND  (i.System_Language__c like 'en_%' OR (i.Mailing_Country__c != 'CA' AND i.System_Language__c is null))
    AND c.AMC_Status__c = 'Active'
    AND i.Cat_Campaign_Most_Recent__c NOT IN (
'PCC eNews',
'OHTE Offers',
'Mid America Trucking Show',
'Product Support On-Highway Legacy Engines Initiate Dealer',
'Million Miler',
'Iron Planet Auction - On Highway Legacy Machine',
'Product_Support_ECommerce_Contact',
'Iron Planet Auction - On Highway Legacy Engine',
'EP Spec Sizer Nurture',
'Parts.cat.com Account Registration',
'EP General Nurture',
'Drivecat.com - Mini Survey',
'OHTE Independent Shop Sweepstakes',
'Product Support Million Miler',
'OHTE Trucking Is Life eNews'
)

        )t2
 
WHERE RowNum = 1
SELECT i.SubscriberKey
	,i.EmailAddress
	,i.System_Language__c
	,i.Mailing_Country__c
	,i.First_Name__c
	,i.Cat_Campaign_Most_Recent__c
	,i.Business_Unit__c
	,i.System_Opt_in_for_eMail__c
	,i.DateAdded
	,i.PCCReg
FROM [Proposed_Retail_TA_News_2024_INCLUDE] i
WHERE 1 = 1
    AND NOT EXISTS (
        SELECT NULL
        FROM [Proposed_Retail_TA_News_2024_EXCLUDE] ex
        WHERE 1 = 1
            AND i.SubscriberKey = ex.SubscriberKey
    )
 
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT s.SubscriberKey,
            'Undeliverable' as reason
        FROM ENT._Subscribers s
        JOIN Proposed_Retail_TA_News_2024_INCLUDE c on c.SubscriberKey = s.SubscriberKey
        WHERE 1 = 1
            AND s.status in ('held', 'bounced', 'unsubscribe', 'unsubscribed')
            AND s.SubscriberKey IN (
                SELECT x.SubscriberKey
                FROM [Proposed_Retail_TA_News_2024_INCLUDE] x
                WHERE 1 = 1
            )
             
    ) a

    
UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,  
              'Dealer Exclusion' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
            AND LOWER(
                RIGHT (
                    b.EmailAddress,
                    LEN(b.EmailAddress) - CHARINDEX('@', b.EmailAddress)
                )
            ) IN (
                SELECT LOWER(x.Domain)
                FROM ent.[Dealer Domains] x
            )
    ) a
UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,
            'Hard bounce DE' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
            AND b.SubscriberKey IN (
                SELECT x.SubscriberKey
                FROM ent.[Hard Bounces - Exclusion] x
            )
    ) a
UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,
            'Cat Agency Exclusion' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
            AND LOWER(
                RIGHT (
                    b.EmailAddress,
                    LEN(b.EmailAddress) - CHARINDEX('@', b.EmailAddress)
                )
            ) IN (
                SELECT LOWER(x.Domain)
                FROM ent.[Cat_Agency_Domains] x
            )
    ) a
UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,
            'Competitor Exclusion' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
            AND LOWER(
                RIGHT (
                    b.EmailAddress,
                    LEN(b.EmailAddress) - CHARINDEX('@', b.EmailAddress)
                )
            ) IN (
                SELECT LOWER(x.Domain)
                FROM ent.[Competitor Domains] x
            )
    ) a 
    
    UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,
            'AMC Status' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
         AND   b.AMC_Status__c IN ('Inactive', 'Expired')
    ) a 

       UNION ALL
SELECT a.SubscriberKey,
       a.reason
FROM (
        SELECT b.SubscriberKey,
            'AMC Not Marketable' as reason
        FROM [Proposed_Retail_TA_News_2024_INCLUDE] b
        WHERE 1 = 1
         AND   b.AMC_Last_Activity_Record_ID__c LIKE 'Not Marketable' 
         AND (b.AMC_Status__c LIKE 'Active' OR b.AMC_Status__c IS NULL)
    ) a 
SELECT 
c.ID as SubscriberKey,
i.Cat_Campaign_Most_Recent__c,
i.Email__c as EmailAddress,
i.ID as Interaction_ID,
i.CreatedDate,
i.First_Name__c,
i.Last_Name__c,
i.Business_Phone__c,
i.Company_Name__c,
i.Mailing_Country__c,
i.Mailing_Zip_Postal_Code__c,
i.Purchase_Timeframe__c,
i.Level_of_Interest__c,
i.System_Opt_in_for_eMail__c,
i.Contact_Source_Details_Most_Recent__c,
i.System_Language__c,
i.Industry__c,
i.Industry_Level_2_Master__c,
i.Job_Role__c,
i.Serial_Number__c,
i.Ci_Fleet_Size__c,
i.Business_Unit__c,
c.AMC_Status__c,
c.AMC_Last_Activity_Record_ID__c

FROM ent.interaction__c_salesforce i
JOIN ent.Contact_Salesforce_1 c ON c.Email = i.Email__c
WHERE i.Email__c IS NOT NULL
AND (i.System_Language__c LIKE 'en_%' OR i.System_Language__c IS NULL)
AND (i.Mailing_Country__c = 'US' OR i.Mailing_Country__c = 'CA')
AND (i.Mailing_State_Province__c NOT LIKE 'QC' OR i.Mailing_State_Province__c IS NULL)
AND i.Business_Unit__c IN  (
    'CISD',
    'GASD',
    'Product Support',
    'PS'
    )
AND i.Cat_Campaign_Most_Recent__c NOT IN (
'PCC eNews',
'OHTE Offers',
'Mid America Trucking Show',
'Product Support On-Highway Legacy Engines Initiate Dealer',
'Million Miler',
'Iron Planet Auction - On Highway Legacy Machine',
'Product_Support_ECommerce_Contact',
'Iron Planet Auction - On Highway Legacy Engine',
'EP Spec Sizer Nurture',
'Parts.cat.com Account Registration',
'EP General Nurture',
'Drivecat.com - Mini Survey',
'OHTE Independent Shop Sweepstakes',
'Product Support Million Miler',
'OHTE Trucking Is Life eNews'
)

AND i.Id IN (
    SELECT max(i2.Id)
    FROM ent.interaction__c_salesforce i2
    GROUP BY i2.Email__c
)




/** 
 * log("sample logging statement") --> can be used to print any data in the browser console.
 * ZDK module can be used for customising the UI and other functionalities.
 * return false to prevent <SAVE> action
**/

console.log("running client script");
var accountId = ZDK.Page.getField("Operating_Company").getValue().id;
const accountDetails = ZDK.Apps.CRM.Accounts.fetchById(accountId);
const relatedContacts = ZDK.Apps.CRM.Accounts.fetchRelatedRecords(accountId, 'Contacts')
if (relatedContacts.length) {
    for (const contact of relatedContacts) {
        var mp = {
            'id': contact.id,
            'name': contact.Full_Name
        }
    }
        ZDK.Page.getField('Requested_By').setValue(mp);
}
var vendor = {
    'id': accountDetails.Referred_By().id,
    'name': accountDetails.Referred_By().Vendor_Name
}

if (vendor.id != null)  
{
    ZDK.Page.getField("Vendor").setValue(vendor);
}

ZDK.Page.getField("Request_Status").setValue("Customer Requested");
const today = new Date();
const formattedDate = today.toISOString().split('T')[0];
console.log(formattedDate);
ZDK.Page.getField("Requested_Date").setValue(formattedDate);
accountId = "575609000057932130";
/////// Fetching From Zoho Analytics ////////
var functionResp = ZDK.Apps.CRM.Functions.execute("fetch_available_tokens", { "accountId": accountId });
// console.log(response);

var message = functionResp.message;
if (message == "function executed successfully");
{
    const parsedOutput = JSON.parse(functionResp._details.output);
    const columnOrder = parsedOutput.response.result.column_order;
    const rows = parsedOutput.response.result.rows;
    console.log(columnOrder)
    console.log(rows);

    tokenDetialsList = new Array();
    
    //////////////////        ///////////////////
    for (let i = 0; i < rows.length; i++)
    {
        var row = rows[i];
        let promoterId = row[columnOrder.indexOf("Promoter Id")];
        let promoterName = row[columnOrder.indexOf("Promoter Name")];
        let tokens = parseFloat(row[columnOrder.indexOf("Tokens")]);
        let tokenValue = parseFloat(row[columnOrder.indexOf("Token Value")]);

        let amount = (tokens * tokenValue).toFixed(2); 
        console.log(amount);

        var promoterMap= {
            'id': promoterId,
            'name': promoterName
        };

        var rowMap = {
            "Promoter": promoterMap,
            "Tokens": tokens,
            "Amount": amount
        };
        
        tokenDetialsList.push(rowMap);
        ////
        
    }
    console.log(tokenDetialsList);

    ZDK.Page.getForm().setValues({
        'Token_Details': tokenDetialsList
    });
    
}
Task-9
Implement Kruskal algorithm
Algorithm:
Algorithm Kruskal(E, cost, n, t)
// E is the set of edges in G. G has n vertices. cost[u, v] is the
// cost of edge (u, v). t is the set of edges in the minimum-
// spanning tree. The final cost is returned.

{
    Construct a heap out of the edge costs using Heapify;
    for i := 1 to n do parent[i] := −1;
    // Each vertex is in a different set.
    i := 0; mincost := 0.0;
    while ((i < n − 1) and (heap not empty)) do
    {
        Delete a minimum cost edge (u, v) from the heap
        and reheapify using Adjust;
        j := Find(u); k := Find(v);
        if (j ≠ k) then
        {
            i := i + 1;
            t[i, 1] := u; t[i, 2] := v;
            mincost := mincost + cost[u, v];
            Union(j, k);
        }
    }
    if (i ≠ n − 1) then write ("No spanning tree");
    else return mincost;
}
Program:
# KRUSKAL.PY

import heapq

class Graph():
  def __init__(self, v):
    self.V = v
    # graph contains list of edges ** (u, v, w)
    # u -> src, v -> destination, w -> weight/cost
    self.edges = []

  def add_edge(self,u,v,w):
    # add edge and override cost
    self.edges.append([u,v,w])

  def kruskal(self):
    
    # helper functions

    def find(parent, i):
      if parent[i]==i:
        return i
      # path compression technique
      return find(parent, parent[i])

    def union(parent, rank, x, y):
      # union by rank

      # finding roots of disjoint sets x and y
      x_root = find(parent,x)
      y_root = find(parent,y)

      # Attach smaller rank tree under root of 
        # high rank tree (Union by Rank)
      if rank[x_root]<rank[y_root]:
        parent[x_root] = y_root
      elif rank[x_root]>rank[y_root]:
        parent[y_root] = x_root   
      else:
        # If ranks are same, then make one as root 
        # and increment its rank by one 
        parent[y_root] = x_root
        rank[x_root] += 1

    def cout(t):
      print()
      print("Selected Edges:")
      for edge in t:
        print(edge[0]+1,edge[1]+1,edge[2])

    
    # The main function to construct MST using Kruskal's algorithm 

    # t[1:n-1,1:3] : selected edges, exactly n-1
    t = [[0,0,0] for i in range(self.V-1)]

    # Create a min-heap of edges
    min_heap = []
    for u, v, w in self.edges:
        heapq.heappush(min_heap, (w, u, v))

    parent = [i for i in range(self.V)]
    rank = [0]*self.V

    # count of edges in t / MST
    i = 0
    mincost = 0

    while i<self.V-1 and  min_heap:
      w,u,v = heapq.heappop(min_heap)
      j = find(parent,u)
      k = find(parent,v)

      if j!=k:
        t[i][0],t[i][1],t[i][2] = u,v,w
        i+=1
        mincost += w
        union(parent,rank,j,k)
    
    cout(t)
    print("mincost : ",mincost)

if __name__ == '__main__':
  v = int(input("Enter number of vertices :"))
  g = Graph(v)
  e = int(input("Enter number of Edges :"))
  for _ in range(e):
    u,v,w = map(int, input().split())
    g.add_edge(u-1,v-1,w)

  g.kruskal()


  '''

INPUT:

7
9
1 6 10
6 5 25
5 4 22
5 7 24
4 3 12
4 7 18
7 2 14
2 3 16
2 1 28

OUTPUT:

Selected Edges:
1 6 10
4 3 12
7 2 14
2 3 16
5 4 22
6 5 25
mincost :  99

'''
Task-8
Implement Prim's algorithm
Algorithm:
Algorithm Prim(E, cost, n, t)
// E is the set of edges in G. cost[1 : n, 1 : n] is the cost 
//adjacency matrix of an n-vertex graph such that cost[i, j] is 
//either a positive real number or ∞ if no edge (i, j) exists.
// A minimum spanning tree is computed and stored as a set of edges in the array t[1 : n − 1, 1 : 2].
// (t[i, 1], t[i, 2]) is an edge of 
//the minimum-cost spanning tree. The final cost is returned.
{
Let (k, l) be an edge of minimum cost in E;
mincost := cost[k, l];
t[1, 1] := k; t[1, 2] := l;

For i := 1 to n do // Initialize near.

if (cost[i, l] < cost[i, k]) then near[i] := l;  
else near[i] := k;  
near[k] := near[l] := 0;

For i := 2 to n − 1 do
{
// Find n − 2 additional edges for t.  
Let j be an index such that near[j] ≠ 0 and cost[j, near[j]] is minimum;  
t[i, 1] := j; t[i, 2] := near[j];  
mincost := mincost + cost[j, near[j]];  
near[j] := 0;  
for k := 1 to n do  
    if ((near[k] ≠ 0) and (cost[k, near[k]] > cost[k, j]))  
        then near[k] := j;  
}
Return mincost;
}

Program:
#PRIM.PY

class Graph():
  def __init__(self, v):
    self.V = v
    # graph[][] ~~~ cost [][]
    # cost = inf ~~ 1000000007 if no edge between pair
    # initially no edges
    self.cost = [[1000000007 for cols in range(v)] for rows in range(v)]

  def add_edge(self,u,v,w):
    # add edge and override cost
    self.cost[u][v] = self.cost[v][u] = w


  def prim(self):

    # helper functions

    def find_min_edge():
      min_edge = 1000000007 #~~ inf
      # initilize (k,l) to (-1,-1)
      k,l = -1,-1
      for i in range(self.V):
        for j in range(self.V):
          if i!=j and self.cost[i][j]<min_edge:
            min_edge = self.cost[i][j]
            k,l = i,j
      return k,l

    def find_next_edge(near):
      j = -1
      min_cost = 1000000007 # ~inf
      for i in range(self.V):
        if near[i]!=-1 and self.cost[i][near[i]]<min_cost:
          min_cost = self.cost[i][near[i]]
          j = i
      return j

    def update_near(near, j):
      for k in range(self.V):
        if near[k]!=-1 and self.cost[k][near[k]] > self.cost[k][j]:
          near[k] = j

    def cout(t):
      print()
      print("selected edges :")
      for edge in t:
        print(edge[0]+1,edge[1]+1,self.cost[edge[0]][edge[1]])



    # The main function to construct MST using prim's algorithm 



    # t[1:n-1,1:2] : selected edges, exactly n-1
    t = [[0,0] for i in range(self.V-1)]

    # find (k,l) an edge with minimum cost
    k,l = find_min_edge()
    mincost = self.cost[k][l]
    t[0][0], t[0][1] = k,l

    # define near[]
    near = [-1]*self.V

    for i in range(self.V):
      if self.cost[i][l]<self.cost[i][k]:
        near[i] = l
      else:
        near[i] = k
    
    near[k] = near[l] = -1

    for i in range(1,self.V-1):
      # j is the next vertex where near[j]!=0 and cost[j][near[j]] is minimum
      j = find_next_edge(near)
      # add to selected edges
      t[i][0],t[i][1] = j,near[j]
      mincost += self.cost[j][near[j]]
      # set near[j] to 0
      near[j] = -1

      # update near
      update_near(near,j)

    # print selected edges and mincost
    
    cout(t)
    print("mincost : ",mincost)
  

if __name__ == '__main__':
  v = int(input("Enter number of vertices :"))
  g = Graph(v)
  e = int(input("Enter number of Edges :"))
  for _ in range(e):
    u,v,w = map(int, input().split())
    g.add_edge(u-1,v-1,w)
  
  g.prim()

  '''

INPUT:

7
9
1 6 10
6 5 25
5 4 22
5 7 24
4 3 12
4 7 18
7 2 14
2 3 16
2 1 28

OUTPUT:

selected edges :
1 6 10
5 6 25
4 5 22
3 4 12
2 3 16
7 2 14
mincost :  99

'''

#EX1
import random
class Domino:
    def __init__(self,a,b):
        self.a=a
        self.b=b
    def affiche_points(self):
        return("face a :",self.a,"face b" , self.b)

def generer_dominos(n):
    L=[]
    for i in range (n):
        L.append(Domino.affiche_points(Domino(random.randint(1,6),random.randint(1,6))))
    return L


def afficher_dominos(L):
    for i in range(len(L)):
        print("domino Num",i,"face a" ,L[i][1],"face b", L[i][3])
    return None

def tri_dominos(L):
    for i in range (len(L)):
        for j in range(0,len(L)-i-1):
            if (L[j][1]+L[j][3])>(L[j+1][1]+L[j+1][3]):
                L[j], L[j+1] = L[j+1], L[j]
    return L
def final():
    L=generer_dominos(int(input("donner le nombre de dominos")))
    print(afficher_dominos(L))
    print(tri_dominos(L))

print(final())

#EX2
import random
class satellite():
    def __init__(self,nom,masse,vitesse):
        self.nom=nom
        self.masse=masse
        self.vitesse=vitesse
    def impulsion(self,force,duree):
        self.vitesse=self.vitesse+((force*duree)/self.masse)
        return self
    def affiche_vitesse(self):
        return("nom : ", self.nom ,"son vitesse est  : ", self.vitesse)
        
    def energie(self):
        return(0,5*(self.masse)*((self.vitesse)**2))
        
def genere_liste():
    L=[]
    for i in range(5):
        a=input("donner le nom de satellite : ")
        L.append(satellite(a,random.randint(1,50),random.randint(1,500)))
    return L

def afficher (L):
    for i in range(len(L)):
        print(satellite.affiche_vitesse(L[i]))
    return None
def ajouter_impulsion(L):
    for i in range(len(L)):
        print(satellite.affiche_vitesse(satellite.impulsion(L[i],500,15)))
    return None
def aff(L):
    for i in range (L):
        print(satellite.affiche_vitesse(L[i]),satellite.energie(L[i]))


L=genere_liste()
print(afficher(L))
print(ajouter_impulsion(L))
print(aff(L))
       
       
export function removeChar(str: string): string {
 let newString = str.split("");
  newString = newString.slice(1,-1);
 return newString.join("");
}


// Another better option:

export function removeChar(str: string): string {
  return str.slice(1,-1);
}
import os
import time
import cv2
from baseline import find_baseline
from tangent_point import find_tangent_point
from lower_limb import find_lower_limb

masks_dir = "./app/angle_utils/masks"
output_file = "./app/angle_utils/function_timings.csv"
max_masks = 100


def time_function(func, *args):
    start_time = time.time()
    try:
        func(*args)
    except Exception as e:
        print(f"Error in {func.__name__}: {e}")
    end_time = time.time()
    return end_time - start_time


results = {
    "find_baseline": [],
    "find_lower_limb": [],
    "find_tangent_point": []
}

mask_files = [f for f in os.listdir(masks_dir) if f.endswith(".png")]

for i, mask_file in enumerate(mask_files[:max_masks]):
    mask_path = os.path.join(masks_dir, mask_file)
    mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)

    if mask is None:
        print(f"Unable to read mask {mask_file}")
        continue

    print(f"Processing {i+1}/{min(len(mask_files), max_masks)}: {mask_file}")

    baseline_time = time_function(find_baseline, mask)
    results["find_baseline"].append(baseline_time)

    lower_limb_time = time_function(find_lower_limb, mask, mask_file)
    results["find_lower_limb"].append(lower_limb_time)

    tangent_time = time_function(
        find_tangent_point, mask, mask, mask.shape, (0, 0), None, mask_file
    )
    results["find_tangent_point"].append(tangent_time)

with open(output_file, "w") as f:
    f.write("Function,Average Time (s),Max Time (s),Min Time (s)\n")

    for func_name, times in results.items():
        avg_time = sum(times) / len(times) if times else 0
        max_time = max(times) if times else 0
        min_time = min(times) if times else 0
        f.write(f"{func_name},{avg_time},{max_time},{min_time}\n")

print(f"Timing results saved to {output_file}")
import os
import time
import cv2
from baseline import find_baseline
from lower_limb_sensitivity import verify_lower_limb_sensitivity
from class_small_areas import verify_class_small_areas
from bony_roof_length import verify_bony_roof_length
from baseline_horizontality import verify_baseline_horizontality

masks_dir = "./app/angle_utils/masks"
output_file = "./app/scoring_utils/scoring_time.csv"
max_masks = 100


def time_function(func, *args):
    """Pomiar czasu działania funkcji."""
    start_time = time.time()
    try:
        result = func(*args)
    except Exception as e:
        print(f"Error in {func.__name__}: {e}")
        result = None
    end_time = time.time()
    return end_time - start_time, result


# Wyniki pomiarów
results = {
    "verify_lower_limb_sensitivity": [],
    "verify_class_small_areas": [],
    "verify_bony_roof_length": [],
    "verify_baseline_horizontality": []
}

# Pobranie plików masek
mask_files = [f for f in os.listdir(masks_dir) if f.endswith(".png")]

for i, mask_file in enumerate(mask_files[:max_masks]):
    mask_path = os.path.join(masks_dir, mask_file)
    mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)

    if mask is None:
        print(f"Unable to read mask {mask_file}")
        continue

    print(f"Processing {i+1}/{min(len(mask_files), max_masks)}: {mask_file}")

    # Najpierw obliczenie punktów baseline
    baseline_time, baseline_points = time_function(find_baseline, mask)
    if baseline_points is None or len(baseline_points) != 2:
        print(f"Skipping {mask_file} due to invalid baseline points")
        continue

    # Czas dla funkcji verify_lower_limb_sensitivity
    sensitivity_time, _ = time_function(verify_lower_limb_sensitivity, mask, baseline_points)
    results["verify_lower_limb_sensitivity"].append(sensitivity_time)

    # Czas dla funkcji verify_class_small_areas
    class_small_areas_time, _ = time_function(verify_class_small_areas, mask)
    results["verify_class_small_areas"].append(class_small_areas_time)

    # Czas dla funkcji verify_bony_roof_length
    bony_roof_time, _ = time_function(verify_bony_roof_length, mask)
    results["verify_bony_roof_length"].append(bony_roof_time)

    # Czas dla funkcji verify_baseline_horizontality
    horizontality_time, _ = time_function(verify_baseline_horizontality, baseline_points)
    results["verify_baseline_horizontality"].append(horizontality_time)

# Zapis wyników do pliku CSV
with open(output_file, "w") as f:
    f.write("Function,Average Time (s),Max Time (s),Min Time (s)\n")

    for func_name, times in results.items():
        avg_time = sum(times) / len(times) if times else 0
        max_time = max(times) if times else 0
        min_time = min(times) if times else 0
        f.write(f"{func_name},{avg_time},{max_time},{min_time}\n")

print(f"Timing results saved to {output_file}")
public Static HcmPositionId EmpPositionId(RecId  _RecId)
    {
        HcmPosition HcmPosition;

        HcmPositionWorkerAssignment HcmPositionWorkerAssignment;

        select  HcmPosition
   join HcmPositionWorkerAssignment where HcmPositionWorkerAssignment.Position==HcmPosition.RecId
    && HcmPositionWorkerAssignment.ValidTo>=DateTimeUtil::getSystemDateTime()
    && HcmPositionWorkerAssignment.Worker==_RecId ;

        return  HcmPosition.PositionId;
    }
star

Wed Nov 20 2024 19:01:29 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Nov 20 2024 18:46:47 GMT+0000 (Coordinated Universal Time)

@hi

star

Wed Nov 20 2024 18:41:19 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Nov 20 2024 18:40:11 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Nov 20 2024 18:33:04 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Nov 20 2024 18:30:48 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Nov 20 2024 18:09:12 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 17:45:26 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 17:39:28 GMT+0000 (Coordinated Universal Time)

@hi

star

Wed Nov 20 2024 17:32:45 GMT+0000 (Coordinated Universal Time)

@hi

star

Wed Nov 20 2024 17:16:28 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Nov 20 2024 17:07:54 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 20 2024 17:00:16 GMT+0000 (Coordinated Universal Time)

@hi

star

Wed Nov 20 2024 16:45:30 GMT+0000 (Coordinated Universal Time) https://docs.praison.ai/api/

@sweetmagic

star

Wed Nov 20 2024 16:43:49 GMT+0000 (Coordinated Universal Time) https://docs.praison.ai/installation/

@sweetmagic

star

Wed Nov 20 2024 16:43:14 GMT+0000 (Coordinated Universal Time) https://docs.praison.ai/installation/

@sweetmagic

star

Wed Nov 20 2024 16:00:10 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 16:00:10 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 15:46:44 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 20 2024 15:11:53 GMT+0000 (Coordinated Universal Time)

@hi

star

Wed Nov 20 2024 15:11:24 GMT+0000 (Coordinated Universal Time)

@hi

star

Wed Nov 20 2024 15:10:55 GMT+0000 (Coordinated Universal Time)

@sem

star

Wed Nov 20 2024 15:10:19 GMT+0000 (Coordinated Universal Time)

@sem

star

Wed Nov 20 2024 15:10:05 GMT+0000 (Coordinated Universal Time)

@hi

star

Wed Nov 20 2024 15:09:28 GMT+0000 (Coordinated Universal Time)

@sem

star

Wed Nov 20 2024 15:04:44 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Nov 20 2024 13:51:07 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 13:15:25 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 20 2024 13:14:24 GMT+0000 (Coordinated Universal Time) https://www.windows8facile.fr/powershell-execution-de-scripts-est-desactivee-activer/

@Hack3rmAn

star

Wed Nov 20 2024 12:54:39 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 12:07:05 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 20 2024 10:45:18 GMT+0000 (Coordinated Universal Time)

@abcd

star

Wed Nov 20 2024 10:38:32 GMT+0000 (Coordinated Universal Time)

@abcd

star

Wed Nov 20 2024 10:20:51 GMT+0000 (Coordinated Universal Time)

@abcd

star

Wed Nov 20 2024 10:14:21 GMT+0000 (Coordinated Universal Time)

@abcd

star

Wed Nov 20 2024 10:13:50 GMT+0000 (Coordinated Universal Time)

@abcd

star

Wed Nov 20 2024 10:13:06 GMT+0000 (Coordinated Universal Time)

@abcd

star

Tue Nov 19 2024 21:29:30 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Tue Nov 19 2024 19:23:10 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Tue Nov 19 2024 19:22:32 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Tue Nov 19 2024 19:21:48 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Tue Nov 19 2024 16:39:06 GMT+0000 (Coordinated Universal Time)

@varuntej #python

star

Tue Nov 19 2024 16:38:14 GMT+0000 (Coordinated Universal Time)

@varuntej #python

star

Tue Nov 19 2024 14:18:27 GMT+0000 (Coordinated Universal Time)

@Radhwen_hajri

star

Tue Nov 19 2024 14:09:25 GMT+0000 (Coordinated Universal Time)

@esmeecodes

star

Tue Nov 19 2024 13:31:33 GMT+0000 (Coordinated Universal Time)

@usertest123890

star

Tue Nov 19 2024 11:09:48 GMT+0000 (Coordinated Universal Time)

@mateusz021202

star

Tue Nov 19 2024 11:08:59 GMT+0000 (Coordinated Universal Time)

@mateusz021202

star

Tue Nov 19 2024 11:07:59 GMT+0000 (Coordinated Universal Time)

@mkhassan

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension