Search Results
30 items found for ""
- BCC IMP MCA Sem-1
MCQ: What is the full name of FAT? = File Allocation Table BIOS is used by ______. = By operating System Which type of operating system is the Linux? = Open Source Operating System Convert(312)8 into decimal = (202)10 Which of these sets of logic gates are known as universal gates? = NAND, NOR Which of the following options can be considered as the Cloud? = Hadoop Which of the following cloud concepts is related to sharing and pooling the resources? = Virtualization BLANKS: Wireless mouse communicates through Radio waves. The full form of USB port is Universal Serial Bus . AI is a branch of computer science focused on creating intelligent machines that can simulate Human Intelligence. AI-powered chatbots are increasingly used in Customer services to provide customer support. Data-Mining is the application of machine learning methods to a large databse. Data held in RDBMS is typically Structured data. Artificial intelligence (AI) is predicted to play an important role in the decision making. Q(2) Explain the components of a computer system in details. 1. Hardware: Hardware refers to the physical components of a computer. It includes the following subcomponents: a) Input Devices: Devices that allow users to interact with the system by entering data or commands. Examples: Keyboard, Mouse, Scanner, Microphone, Webcam. b) Output Devices: Devices that enable the computer to communicate results to the user. Examples: Monitor (displays visuals), Printer (produces hard copies), Speakers (outputs audio). c) Central Processing Unit (CPU): Known as the brain of the computer, it performs calculations and executes instructions. Components of the CPU: Arithmetic Logic Unit (ALU): Handles mathematical and logical operations. Control Unit (CU): Directs data flow and controls operations. Registers: Temporary storage inside the CPU for instructions and data. d) Memory/Storage: Temporary and permanent storage components used for data retention. Primary Memory (RAM): Short-term memory for immediate data and instruction access. Secondary Storage: Long-term storage for data and programs. Examples: Hard Disk Drives (HDD), Solid State Drives (SSD), USB drives. e) Motherboard: A central circuit board connecting all the hardware components. It facilitates communication between the CPU, memory, and peripherals. f) Power Supply Unit (PSU): Converts electrical power from an outlet to usable power for computer components. 2. Software: Software consists of instructions and programs that enable hardware to perform specific tasks.Two main types of software: System Software: Includes operating systems (e.g., Windows, Linux) and utilities that manage hardware resources. Application Software: Programs designed to perform specific user tasks, such as Microsoft Word, Photoshop, or web browsers. 3. Data: Data represents the raw facts and figures that are processed to produce meaningful information. It can be text, numbers, images, audio, or video, and it serves as the input for computations and decision-making. 4. Users: The users interact with the computer system to perform tasks. Users provide inputs, control system behavior, and analyze the generated output. They are also responsible for maintaining the system. 5. Communication Devices: These components facilitate connectivity and communication between computers or networks. Examples include modems, network interface cards (NICs), routers, and Wi-Fi adapters. Q2(B) Brief the classification of computers. 1. Classification by Purpose: a) General-Purpose Computers Designed to perform a wide variety of tasks such as word processing, gaming, and data analysis. Examples: PCs, Laptops, Smartphones. b) Special-Purpose Computers Designed for specific tasks like controlling machinery or processing signals. Examples: ATM machines, Industrial robots, Embedded systems. 2. Classification by Size and Capacity: a) Supercomputers The fastest and most powerful computers. Used for complex and resource-intensive tasks like climate modeling, cryptography, and scientific simulations. Example: IBM Summit, Fugaku. b) Mainframe Computers High-capacity computers used by large organizations for bulk data processing, such as census data and financial transactions. Example: IBM Z Series. c) Minicomputers Mid-range systems smaller and less powerful than mainframes, used in small to medium businesses for specific tasks. Often called "mid-range computers." Example: PDP-11. d) Microcomputers (Personal Computers) The most common type of computer for individual users. Includes desktops, laptops, tablets, and smartphones. Examples: Apple MacBook, Dell Inspiron. e) Embedded Computers Small computers integrated into other devices for specific functions. Examples: Computers in cars, washing machines, and medical devices. 3. Classification by Data Handling: a) Analog Computers Process continuous data and are used in scientific and industrial applications. Example: Speedometers, Analog simulators. b) Digital Computers Process discrete data in binary form. These are the most widely used computers. Example: PCs, Laptops, Smartphones. c) Hybrid Computers Combine features of both analog and digital computers. Used in medical equipment like CT scanners and industrial control systems. 4. Classification by Functionality: a) Servers Designed to provide services like data sharing, hosting, and applications to other devices on a network. Example: Web servers, Application servers. b) Workstations High-performance computers designed for tasks requiring substantial computing power, like 3D rendering or CAD. Example: HP Z Workstations. OR Q2(A) Explain the various stages of computer evolution. 1. First Generation (1940–1956): Vacuum Tubes: Used vacuum tubes for circuitry and magnetic drums for memory. These were bulky, expensive, and consumed significant power. Machine-level language (binary code) was used. Input via punched cards, and output was through printers. ENIAC (Electronic Numerical Integrator and Calculator). UNIVAC (Universal Automatic Computer). Generated excessive heat, limited processing speed, and high maintenance requirements. 2. Second Generation (1956–1963): Transistors Replaced vacuum tubes with transistors, which were smaller, faster, and more energy-efficient. Used magnetic core memory. Assembly language and some early high-level languages (e.g., FORTRAN, COBOL) became prominent. Used punched cards and printers. IBM 1401, PDP-1. Reduced size, increased reliability, and lower costs compared to first-generation computers. 3. Third Generation (1964–1971): Integrated Circuits (ICs) Introduced integrated circuits (ICs), where multiple transistors were placed on a single silicon chip. Allowed significant miniaturization of hardware. Development of high-level programming languages such as BASIC, Pascal, and C. Introduction of operating systems enabling multitasking. IBM System/360, Honeywell 6000 Series. Made computers smaller, faster, and more affordable, enabling wider adoption. 4. Fourth Generation (1971–Present): Microprocessors Microprocessors combined thousands of ICs into a single chip, drastically reducing size and cost. Introduction of personal computers (PCs). The development of GUI-based operating systems like Windows and macOS. Incorporation of RAM and hard disks for enhanced storage and faster performance. Intel 4004 (the first microprocessor), IBM PCs, Apple Macintosh. The era of computers accessible to individuals, revolutionizing businesses and personal computing. 5. Fifth Generation (Present and Beyond): Artificial Intelligence (AI) Incorporates AI, machine learning, and quantum computing. Focus on natural language processing, robotics, and advanced parallel processing. Use of superconductors and nanotechnology for powerful and energy-efficient systems. Examples include AI assistants like Alexa, self-driving cars, and AI-driven systems. Quantum computing could revolutionize fields like cryptography and simulations. Q2(B) Compare and contrast computer organization and architecture. 1. Definition: Computer Organization Refers to the operational units and their interconnections that realize the architectural specifications. It deals with the physical aspects of a computer system, including hardware and circuit design. Computer Architecture Refers to the abstract and conceptual structure of a computer system, focusing on how the system is programmed and its functional characteristics. 2. Focus: Computer Organization Deals with how hardware components are implemented and interact. Includes elements like control signals, data paths, memory types, and physical implementation. Example: Whether a CPU uses cache memory or how pipelines are structured. Computer Architecture Focuses on what the system should do and the functionality it provides. Concerns include instruction set design, addressing modes, and data types. Example: RISC vs. CISC instruction sets. 3. Level of Abstraction: Computer Organization: Operates at a lower level of abstraction. Involves practical design issues, including the specifics of hardware components. Computer Architecture: Operates at a higher level of abstraction. Focuses on the system's logical structure and capabilities. 4. Key Components: Computer Organization: Central Processing Unit (CPU) design. Input/output mechanisms and data paths. Memory organization (e.g., cache and RAM). Computer Architecture: Instruction set design (machine language). Data formats and addressing modes. Performance features (e.g., throughput, scalability). 5. Example Questions Addressed: Computer Organization: How is data transferred between components? How does the processor interact with memory and I/O devices? Computer Architecture: What operations should be performed by the CPU? What data types and formats should the system support? 6. Example Scope: Computer Organization: Aimed at the engineers implementing a physical system. Example: Implementation of a pipelined processor or adding support for parallel execution. Computer Architecture: Geared toward designers defining the overall blueprint. Example: Choosing whether the architecture supports floating-point operations or virtual memory. Aspect Computer Organization Computer Architecture Definition Physical hardware implementation details. Logical design and system functionality. Focus Implementation and interaction of parts. Design and capabilities of the system. Abstraction Level Low level (hardware-centric). High level (conceptual/design-centric). Key Elements Hardware components, memory, I/O. Instruction sets, addressing, logic. Purpose Efficiently building physical systems. Enhancing performance and usability. Q3(A) Explain various types of Operating system. 1. Batch Operating System: Definition: Executes batches of jobs sequentially without user interaction. Characteristics: Users submit jobs to the operator. The system processes these jobs in batches. Examples: Early IBM mainframe systems. Advantages: Efficient for long-running jobs. Disadvantages: No direct user interaction during execution. 2. Time-Sharing Operating System: Definition: Allows multiple users to share computer resources simultaneously. Characteristics: Uses a scheduling algorithm to assign a fixed time slot (quantum) to each user or task. Supports multitasking. Examples: UNIX, Multics. Advantages: Interactive user experience. Effective resource utilization. Disadvantages: Performance may degrade with too many users. 3. Distributed Operating System: Definition: Manages multiple systems connected via a network as a single cohesive system. Characteristics: Tasks are distributed across multiple machines. Ensures transparency in resource sharing. Examples: Google File System, Plan 9. Advantages: High reliability and resource sharing. Scalability. Disadvantages: Complex design and implementation. Security concerns in a networked environment. 4. Real-Time Operating System (RTOS): Definition: Designed to process data and provide results within a strict time constraint. Characteristics: Used in systems requiring immediate response. Two types: Hard Real-Time: Strict timing guarantees. Soft Real-Time: Timing is important but not critical. Examples: VxWorks, QNX, FreeRTOS. Advantages: High reliability in critical tasks like aviation or medical devices. Disadvantages: Limited task scope. Expensive implementation. 5. Network Operating System: Definition: Designed to manage and provide network services to connected systems. Characteristics: Centralized control over user and data security. Enables communication and resource sharing between devices on a network. Examples: Novell NetWare, Windows Server, UNIX/Linux. Advantages: Centralized resource management. Supports multi-user environments. Disadvantages: High maintenance costs and complexity. 6. Mobile Operating System: Definition: Specialized OS designed for mobile devices such as smartphones and tablets. Characteristics: Supports touchscreen interface and power management. Lightweight compared to traditional OS. Examples: Android, iOS, Windows Phone OS. Advantages: Optimized for mobility. Enhanced usability for compact devices. Disadvantages: Limited processing power compared to desktop OS. 7. Embedded Operating System: Definition: OS designed to run on embedded systems, which are part of larger devices. Characteristics: Highly specialized for specific hardware. Small size and low resource usage. Examples: Embedded Linux, FreeRTOS, Windows Embedded. Advantages: Highly efficient for dedicated tasks. Runs reliably on limited hardware. Disadvantages: Limited flexibility. Difficult to upgrade. 8. Multiprocessor Operating System: Definition: Supports multiple CPUs working together within a single system. Characteristics: Provides parallel processing. Improves performance and fault tolerance. Examples: Linux, Windows NT. Advantages: Increased speed and reliability. Efficient handling of multiple tasks. Disadvantages: Complex system design. 9. Virtualized Operating System: Definition: Creates and manages multiple virtual machines on a physical system. Characteristics: Enables multiple OS instances on a single machine. Common in data centers and cloud environments. Examples: VMware ESXi, Microsoft Hyper-V. Advantages: Reduces hardware requirements. Enhances scalability and disaster recovery. Disadvantages: May have performance overhead. Q3(B) Explain the role of OS in Processor management and Memory management. 1. Processor Management: a) Process Scheduling: The OS decides the order in which processes access the CPU using scheduling algorithms. Types of Scheduling: Long-Term Scheduler: Determines which processes are admitted into the system for processing. Short-Term Scheduler: Selects which process is assigned to the CPU next. Medium-Term Scheduler: Temporarily removes or suspends processes to manage the overall system performance. b) Multitasking and Multiprocessing: Multitasking: Allows multiple processes to share the CPU by switching between them quickly (time-sharing). Multiprocessing: Handles multiple processors working simultaneously to improve processing capacity. c) Context Switching: Saves the state of the current process and loads the state of the next process to switch between processes smoothly. d) Deadlock Prevention and Detection: The OS detects deadlocks (when multiple processes are waiting indefinitely for each other to release resources) and takes measures to prevent or resolve them. e) CPU Utilization: Ensures maximum utilization of the CPU by balancing the load across processes or processors. 2. Memory Management: a) Memory Allocation and Deallocation: Allocates memory space to processes and deallocates it once the process terminates to avoid wastage of memory resources. b) Memory Partitioning: Divides memory into fixed or variable partitions to allocate space to multiple processes. Fixed Partitioning: Memory is divided into fixed blocks. Dynamic Partitioning: Blocks of varying sizes are created based on process requirements. c) Virtual Memory Management: Uses a portion of secondary storage (e.g., hard disk) as an extension of RAM, allowing larger processes or more processes to run simultaneously. d) Paging and Segmentation: Paging: Divides memory into fixed-sized blocks called pages, ensuring non-contiguous allocation. Segmentation: Divides memory into variable-sized sections based on logical divisions like functions or modules. e) Memory Protection and Security Prevents a process from accessing memory allocated to another process or unauthorized areas. f) Swapping: Moves inactive processes or parts of them from RAM to secondary storage to free up space for active processes. g) Cache Management: Uses a small, fast memory (cache) close to the CPU to store frequently accessed data or instructions, reducing latency. Common Memory Management Techniques: Single Contiguous Allocation : Allocates one block of memory to each process. Partitioned Allocation : Divides memory into fixed or dynamic sections for allocation. OR Q3(A) Explain various types of software and their role. 1. System Software: a) Operating System (OS): Role: Manages hardware resources (CPU, memory, I/O devices). Provides user interfaces (e.g., GUI, CLI). Enables multitasking, file management, and network operations. Examples: Windows, Linux, macOS, Android. b) Utility Programs: Role: Perform specific maintenance tasks to optimize system performance. Examples include file management, disk cleanup, antivirus tools, and backup programs. Examples: WinRAR, Norton Utilities, CCleaner. 2. Application Software: Application software is designed to help users perform specific tasks or applications. It is directly used by end users for various purposes. a) General-Purpose Software: Role: Facilitates commonly used functions such as word processing, spreadsheet calculations, and multimedia playback. Examples: Microsoft Office, Google Chrome, VLC Media Player. b) Specialized Application Software: Role: Developed for specific industries or tasks. For example, AutoCAD for engineering designs and SAP for enterprise resource management. Examples: Tally (accounting), MATLAB (mathematics). c) Web Applications: Role: Accessible via web browsers, providing users the ability to access tools or services online. Examples: Gmail for email, Canva for graphic design, Google Drive for cloud storage. 3. Programming Software: Programming software aids developers in writing, testing, and debugging programs. It provides tools and environments required for software development. a) Role: Enables the creation of software through coding and debugging. Helps in automating tasks and application logic creation. b) Examples: Compilers (GCC, Turbo C++). Debuggers (GDB). Integrated Development Environments (IDEs) like Visual Studio, Eclipse. 4. Middleware: Middleware serves as a bridge between different applications, devices, or systems. It is especially important in distributed environments where components need to interact. a) Role: Enables communication between applications or between an OS and a database. Used in distributed systems and enterprise applications for data integration. b) Examples: Oracle Fusion Middleware. IBM WebSphere. 5. Driver Software: Driver software facilitates communication between the operating system and hardware devices. a) Role: Converts system instructions into a format understood by hardware devices like printers, monitors, and keyboards. Ensures compatibility between system components. b) Examples: NVIDIA GPU Drivers, HP Printer Drivers. 6. Open-Source vs. Proprietary Software: Software can also be classified based on its licensing model. a) Open-Source Software: Role: Free to use and modify, with publicly available source code. Enables transparency and collaboration. Examples: Linux, Apache, Blender. b) Proprietary Software: Role: Commercial software protected by intellectual property laws. Users require a license to use it and have limited or no access to source code. Examples: Windows OS, Adobe Photoshop. 7. Embedded Software: Embedded software is designed for embedded systems that are part of larger devices or machinery. a) Role: Controls devices such as automotive systems, appliances, and industrial machinery. Performs specific tasks without user intervention. b) Examples: Firmware in smartphones. Software in medical devices like pacemakers. Q3(B) Explain the role of OS in Device management and File management. 1. Device Management: Device management involves controlling and coordinating all hardware peripherals (input/output devices) attached to the system. The OS plays a vital role in managing device communication and ensuring resource availability. a) Device Drivers: The OS uses device drivers as intermediaries between the hardware and user applications. Drivers translate system instructions into device-specific operations. b) Device Controllers: These are hardware components that the OS communicates with to interact with devices. Example: Disk controller for hard drives. c) Tasks Performed by the OS in Device Management: Device Communication: The OS provides mechanisms for data exchange between the system and devices. Manages input/output operations via interrupt handling. Device Allocation and Deallocation: Allocates devices to processes as needed and releases them once tasks are complete. Buffering and Spooling: Buffering: Temporarily stores data during input/output to handle speed mismatches. Spooling: Queues data for devices that operate sequentially, like printers. Device Scheduling: The OS decides the order of tasks for devices to optimize performance. Examples: First Come, First Served (FCFS) Priority Scheduling Error Detection and Handling: Identifies device malfunctions and takes corrective actions like retries or alerts. d) Examples of Devices Managed by the OS: Input devices: Keyboard, mouse, scanner. Output devices: Monitor, printer, speakers. Storage devices: Hard drives, SSDs, USB drives. 2. File Management: File management is a crucial function of the OS to handle data storage and access systematically. The OS organizes data into files and directories, manages storage locations, and enforces access controls. a) Tasks Performed by the OS in File Management: File Creation and Deletion: Enables users and applications to create or delete files on storage devices. File Organization: Files are organized into logical structures like directories and folders for easy navigation. File Naming: Ensures unique naming of files within a directory. Supports extensions to identify file types (e.g., .txt, .pdf). File Access: Provides mechanisms for reading, writing, and modifying files. Access Methods: Sequential Access: Data is read in a fixed order. Direct Access: Data is retrieved from any position in the file. File Permissions and Security: Controls access through permissions for users or groups (e.g., read, write, execute). Provides encryption and password protection to secure files. File Storage and Retrieval: Manages where and how files are stored (e.g., in blocks, sectors, or clusters on disks). Uses file allocation methods like: Contiguous Allocation Linked Allocation Indexed Allocation File System Management: The OS supports file systems to manage how data is stored and retrieved. Examples: FAT32, NTFS, ext4. File Backup and Recovery: Provides tools to back up data and recover it in case of accidental deletion or corruption. b) File Attributes: Metadata includes information like file size, creation date, permissions, and last modified time. c) Examples of File Types Managed by the OS: Documents: .txt, .docx. Images: .jpg, .png. Programs: .exe, .sh. Data Files: .csv, .json. Q4(A) Do the following conversation: (i) (265)10= (___)2 Division by 2 Quotient Remainder (Digit) Bit # (265)/2 132 1 0 (132)/2 66 0 1 (66)/2 33 0 2 (33)/2 16 1 3 (16)/2 8 0 4 (8)/2 4 0 5 (4)/2 2 0 6 (2)/2 1 0 7 (1)/2 0 1 8 = (100001001)2 (ii) (5634C)16= (___)2 5=0101 6=0110 3=0011 4=0100 C=1100 (5634C)16=(01010110001101001100)2 Q4(B) Explain the structure of Octal to Binary encoder in details. Components of the Encoder: Inputs: 8 input lines (I0I_0I0 to I7I_7I7) represent octal digits (000 to 777). Only one input is active (logic HIGH, i.e., 1) at a time. Outputs: 3 output lines (Y2,Y1,Y0Y_2, Y_1, Y_0Y2,Y1,Y0) give the corresponding 3-bit binary code. Enable Line (Optional): Used in some designs to enable or disable the encoder. Input Lines Output Lines i0=1 000 (Binary for 0) i1=1 001 (Binary for 1) i2=1 010 (Binary for 2) i3=1 011 (Binary for 3) i4=1 100 (Binary for 4) i5=1 101 (Binary for 5) i6=1 110 (Binary for 6) i7=1 111 (Binary for 7) Applications of Octal to Binary Encoder: Data Compression: Encodes multiple inputs into fewer output lines for efficient data representation. Digital Systems: Widely used in digital systems where octal data inputs need to be converted into binary format. Input Handling: Simplifies handling of multiple inputs (such as switches or keys) by reducing the number of output lines required for processing. OR Q4(A) Explain various types of logic gates. AND Gate: D-shaped with flat input side. Symbol: A dot (...) or multiplication (∗*∗) represents the AND operation. Operation: The output is HIGH (1) only if all inputs are HIGH (1). OR Gate: Curved input side and pointed output. Symbol: A plus (+++) represents the OR operation. Operation: The output is HIGH (1) if any one or more inputs are HIGH (1). NOT Gate: Triangle with a circle at the output. Symbol: A bar (A‾\overline{A}A) or negation ( ~ ) represents the NOT operation. Operation: The output is the inverse of the input. NAND Gate: Same as AND with a circle at the output. Operation: The output is HIGH (1) if any input is LOW (0) NOR Gate: Same as OR with a circle at the output. Operation: The output is HIGH (1) only if all inputs are LOW (0). XOR Gate: OR symbol with an extra curved input. Operation: The output is HIGH (1) only if exactly one input is HIGH (1) XNOR Gate: XOR with a circle at the output. Operation: The output is HIGH (1) if both inputs are either HIGH (1) or LOW (0). It is the complement of XOR. Q5(A) What are the different types of cloud computing services? 1. Infrastructure as a Service (IaaS): IaaS provides virtualized computing resources over the internet. Users can rent infrastructure components such as servers, storage, and networking hardware without owning or maintaining physical equipment. Key Features: Virtual machines (VMs), storage, and network configurations are managed by the provider. Users are responsible for installing and managing their operating systems and applications. Scalable to meet changing business needs. Examples: Amazon Web Services (AWS) EC2 Microsoft Azure Virtual Machines Google Compute Engine Use Cases: Hosting websites and web applications. Disaster recovery and backup solutions. Development and testing environments. 2. Platform as a Service (PaaS): Definition: PaaS provides a platform allowing developers to build, deploy, and manage applications without worrying about underlying infrastructure. Key Features: Includes middleware, operating systems, development tools, and databases. Simplifies application development by removing the need for hardware and software management. Focuses on improving development efficiency. Examples: Heroku Google App Engine Microsoft Azure App Service Use Cases: Software development and deployment. API integration and custom application creation. Rapid application prototyping and scaling. 3. Software as a Service (SaaS): Definition: SaaS provides fully functional software applications over the internet. Users access applications through a web browser without needing to install or manage software locally. Key Features: Delivered as a subscription-based service. Maintenance, updates, and management are handled by the service provider. Accessible from any device with internet access. Examples: Google Workspace (Google Docs, Gmail) Microsoft Office 365 Salesforce Use Cases: Collaboration tools (e.g., Google Workspace). Customer Relationship Management (CRM) software. Enterprise Resource Planning (ERP) systems. 4. Function as a Service (FaaS) (Part of Serverless Computing): Definition: FaaS allows developers to execute code in response to specific events without managing servers or infrastructure. Key Features: Users focus solely on writing and deploying application functions. Scales automatically based on demand. Pay-per-execution model. Examples: AWS Lambda Google Cloud Functions Microsoft Azure Functions Use Cases: Event-driven tasks, like processing data from IoT devices. Running lightweight, on-demand functions. Creating microservices-based applications. 5. Other Cloud Service Models: a) Communication as a Service (CaaS): Focuses on enabling communication tools like VoIP, video conferencing, and messaging over the cloud. Examples: Twilio, Zoom, Slack. b) Database as a Service (DBaaS): Provides database management systems without requiring users to set up their servers. Examples: Amazon RDS, Google Cloud Spanner. Q5(B) What is IOT? Explain any 2 applications of IOT. The Internet of Things (IoT) refers to the network of interconnected devices embedded with sensors, software, and other technologies that enable them to collect, exchange, and act on data over the internet. These devices range from household appliances, wearable gadgets, and vehicles to industrial equipment, all of which can interact autonomously or semi-autonomously to perform specific tasks. Key Characteristics of IoT: Connectivity: Devices are interconnected via wired or wireless communication protocols (e.g., Wi-Fi, Bluetooth, Zigbee). Sensors and Actuators: Sensors collect real-world data, and actuators take actions based on the data processed. Intelligence: IoT devices often employ AI and data analytics for autonomous decision-making. Scalability: IoT systems can easily adapt to new devices and scaling needs. Real-time Insights: Continuous monitoring and analysis offer valuable real-time information. Applications of IoT: 1. Smart Home Systems: Description: IoT transforms homes into "smart homes" by enabling automation and remote control of devices like lights, thermostats, security cameras, and kitchen appliances through smartphones or voice assistants. Benefits: Energy efficiency and cost savings. Improved safety and convenience. 2. Healthcare (IoT in Medicine): Description: IoT-powered devices are widely used in healthcare for remote monitoring, diagnostics, and improving patient care. Wearable devices collect real-time health data such as heart rate, oxygen levels, and blood pressure. Benefits: Reduces hospital visits through remote healthcare. Early detection of critical conditions through continuous monitoring. OR Q5(A) Compare and contrast AI and ML. Comparison Between AI (Artificial Intelligence) and ML (Machine Learning) Feature Artificial Intelligence (AI) Machine Learning (ML) Definition The simulation of human intelligence processes by machines to perform tasks that usually require human intelligence. A subset of AI focused on enabling systems to learn and improve from data without being explicitly programmed. Scope Broader field encompassing various technologies, including ML, expert systems, and natural language processing. A specific field of AI focused solely on building models to learn patterns in data and make predictions. Purpose Develop intelligent systems capable of decision-making, problem-solving, and simulating human behavior. Focus on creating systems that can analyze data, identify patterns, and make data-driven decisions. Core Techniques - Knowledge representation - Reasoning - Search algorithms - Expert systems - Robotics - Machine learning itself is a technique of AI. - Supervised learning - Unsupervised learning - Reinforcement learning - Algorithms like decision trees, neural networks, etc. Human-Like Abilities Includes decision-making, learning, problem-solving, perception, and language understanding. Limited to learning from data and making accurate predictions. Data Dependency May or may not involve large datasets. Uses rules, algorithms, and pre-programmed intelligence. Requires significant volumes of structured or unstructured data for training. Autonomy Seeks complete autonomy in reasoning and decision-making. Focuses on specific tasks defined by the input data and training. Examples - Voice assistants (e.g., Siri, Alexa) - Chess-playing systems - Autonomous cars - AI in medical diagnosis. - Recommendation systems (e.g., Netflix, Amazon) - Email spam filtering - Fraud detection in banking. Relationship AI is the broader concept or field that encompasses ML as a technique. ML is a subset and method for achieving AI goals. Level of Complexity Highly complex and multifaceted as it tries to emulate human intelligence. Relatively less complex; focuses on creating specific models for learning from data. Q5(B) How does big data analytics work? Big data analytics involves the examination of large and complex datasets (referred to as big data) to uncover hidden patterns, trends, correlations, and actionable insights. The process relies on advanced technologies, tools, and methodologies to manage and analyze vast amounts of structured, semi-structured, and unstructured data efficiently. Steps Involved in Big Data Analytics: 1. Data Collection: Description: Data is gathered from various sources such as sensors, social media, transactional systems, IoT devices, and databases. Techniques/Tools: Real-time streaming tools (e.g., Apache Kafka). Batch data import methods using ETL (Extract, Transform, Load) processes. 2. Data Storage: Description: Collected data is stored in a scalable storage system designed for large volumes of diverse data. Storage methods depend on the nature of the data (structured or unstructured). Key Technologies: Distributed file systems (e.g., Hadoop Distributed File System (HDFS)). NoSQL databases (e.g., MongoDB, Cassandra). Data lakes for unstructured data. 3. Data Processing: Description: Data is cleaned, formatted, and processed to make it suitable for analysis. Processing can be done in batch or real time. Techniques/Tools: Batch processing (e.g., Apache Hadoop). Real-time processing (e.g., Apache Spark, Apache Flink). 4. Data Analysis: Description: Analyzing the data involves applying various statistical, machine learning, and AI techniques to extract meaningful insights. Types of Analysis: Descriptive Analytics: Identifies past trends and patterns. Predictive Analytics: Uses models to predict future outcomes (e.g., customer behavior). Prescriptive Analytics: Suggests optimal decisions based on analysis. Key Tools: Machine learning libraries (e.g., TensorFlow, PyTorch). Statistical analysis tools (e.g., R, Python libraries). 5. Visualization and Interpretation: Description: Insights derived from analysis are presented using data visualization tools to make them understandable and actionable. Tools: Tableau, Power BI, Google Data Studio for dashboards and reports. Matplotlib, D3.js for custom data visualizations. 6. Decision-Making and Actions: Description: Organizations use the insights to make informed decisions, optimize operations, improve customer experiences, or develop strategies.
- Python MCA sem-1
Blanks: In Python, a method that is used to handle exception cases is known as a try block. The lambda function in Python allows you to define anonymous functions. In Python, super is used to indicate that a method belongs to the parent class. In Python, the special variable __name__ is used to check if a module is being run directly or imported as a module . A Python function that returns a sequence of results rather than a single value is called a generator function. In Python, the filter function is used to filter a list based on a condition provided by a lambda function. The built-in Python function os.path.exists is used to check if a file exists in the file system. QUE. & ANS : 2(A) Give a comparison between List, Tuple and Dictionaries in Python. Feature List Tuple Dictionary Definition Ordered collection of items. Ordered, immutable collection of items. Unordered collection of key-value pairs. Mutability Mutable (modifiable). Immutable (cannot be modified). Mutable (keys and values can be changed). Syntax Defined using square brackets [ ]. Defined using parentheses ( ). Defined using curly braces { } with key-value pairs separated by :. Examples [1, 2, 3] (1, 2, 3) {'key1': 'value1', 'key2': 'value2'} Order Maintains insertion order. Maintains insertion order (as of Python 3.7+). Maintains insertion order (as of Python 3.7+). Indexing Accessible via index. Accessible via index. Accessible via keys (not indexable). Duplicates Allows duplicate values. Allows duplicate values. Keys must be unique, but values can be duplicates. Use Cases Used for collections of items that may need modifications. Used for fixed collections of items. Used for mappings between unique keys and values. Performance Faster than a dictionary for simple data. Slightly faster than lists because they are immutable. Slower for lookups than lists/tuples, but optimized for key-based access. Functions Supports append, extend, insert, remove, pop, and more. Limited to operations like count, index. Supports methods like keys(), values(), items(), update(), get(). Immutability Items can be added, removed, or changed. Once created, items cannot be altered. Both keys and values can be changed, but keys must remain hashable. 2(B) Explain Slicing of strings in python using examples. Slicing in Python refers to extracting a portion (substring) of a string using indexing. Strings are immutable, so slicing creates a new string. Basic Syntax of Slicing: string[start:end:step] start : The starting index of the slice (inclusive). Defaults to 0 if omitted. end : The ending index of the slice (exclusive). If omitted, slices up to the end of the string. step : The interval or step between indices (defaults to 1). OR 2(A) What is lambda function in Python? Explain lambda function with example. Explain filter(), map() and reduce() functions in brief. Lambda Function in Python: A lambda function in Python is a small anonymous function that can have any number of arguments, but can only have one expression. It is defined using the lambda keyword. Syntax: lambda arguments: expression arguments : The input parameters (optional, can be none). expression : A single expression that is evaluated and returned. This cannot contain multiple expressions or statements. Example of Lambda Function: # Regular function def add(x, y): return x + y # Lambda function equivalent add_lambda = lambda x, y: x + y print(add(3, 5)) # Output: 8 print(add_lambda(3, 5)) # Output: 8 1. filter() Function: The filter() function filters elements from an iterable based on a condition defined by a lambda function. It returns an iterator with only the elements for which the condition is True. Syntax: filter(function, iterable) function : A function that tests each element in the iterable. It should return True or False. iterable : The iterable (like a list or tuple) to be filtered. 2. map() Function: The map() function applies a specified function to each item in an iterable and returns an iterator with the modified items. Syntax: map(function, iterable) function : A function to apply to each element of the iterable. iterable : The iterable to process. 3. reduce() Function: The reduce() function, from the functools module, applies a rolling computation to sequential pairs of values in an iterable. It reduces the iterable to a single cumulative value. Syntax: from functools import reduce reduce(function, iterable) function : A function that takes two inputs and returns a value (e.g., addition, multiplication). iterable : The iterable to be reduced. 2(B) Explain Dictionaries and associated methods. get() : Retrieves a value safely. keys() : Returns the dictionary keys. values() : Returns the dictionary values. items() : Returns key-value pairs. update() : Adds or updates key-value pairs. pop() : Removes a key-value pair and returns the value. clear() : Clears all items in the dictionary. copy() : Makes a shallow copy of the dictionary. setdefault() : Gets a value or sets a default value. fromkeys() : Creates a dictionary from keys with the same initial value. 3(A) What is function? How it differs from methods? Discuss use of default parameters in function using suitable example. A function in Python is a block of reusable code that is designed to perform a specific task. Functions take input parameters, perform some operations, and return a result. Functions help in avoiding redundancy in code and make it more organized. Syntax for Defining a Function: def function_name(parameters): # Function body return result # Optional def : The keyword used to define a function. function_name : The name of the function. parameters : Input to the function, these are optional. return : A statement to return a result (optional). The key difference between a function and a method lies in their association: Function : A function is a standalone block of code that performs a task. It does not belong to any object or class. Method : A method is similar to a function, but it is associated with an object (or class). It operates on data that belongs to that object. Methods are always called on instances (objects) of a class or on the class itself. Use of Default Parameters in Functions: Default parameters allow you to specify default values for parameters when defining a function. If the caller does not pass an argument for that parameter, the function uses the default value. Syntax for Default Parameters: def function_name(parameter1=default_value1, parameter2=default_value2): # function body If no argument is passed for a parameter, the default value will be used. Example with Default Parameters: def greet(name, age=25): # Default age is 25 if not specified return f"Hello, {name}. You are {age} years old." print(greet("Alice")) # Output: Hello, Alice. You are 25 years old. print(greet("Bob", 30)) # Output: Hello, Bob. You are 30 years old. 3(B) What is Exception? Explain how to handle user defined exception in python ? An exception in Python is an event or error that disrupts the normal flow of a program’s execution. When an error occurs, Python raises an exception, which typically results in the program stopping unless it is properly handled. Exceptions are caused by situations such as division by zero, incorrect data types, file not found, etc. Types of Exceptions: Common types of exceptions include: ZeroDivisionError: Raised when dividing by zero. ValueError: Raised when a function receives an argument of the correct type, but an inappropriate value. FileNotFoundError: Raised when attempting to open a file that doesn’t exist. TypeError: Raised when an operation or function is applied to an object of inappropriate type. Python has a built-in set of exceptions, but you can define your own as well. Handling exceptions properly ensures that your program doesn't crash unexpectedly and can take corrective actions. How to Handle User-Defined Exceptions in Python? In Python, you can define your own exceptions using classes that inherit from the built-in Exception class. By creating custom exceptions, you can provide more meaningful error messages and handle unique situations in your programs. Steps to Define and Handle a User-Defined Exception: Define the Exception : Create a new class that inherits from Python’s Exception class (or a subclass of it). Raise the Exception : Use the raise keyword to manually raise the exception. Handle the Exception : Use try, except, and else blocks to catch and handle the user-defined exception. OR 3(A) What is module? Why we need module? Discuss various ways to use module. A module in Python is a file that contains Python code, which can define functions, classes, and variables, as well as include runnable code. Modules allow you to organize and reuse code across multiple programs. In essence, a module is a way of grouping related code together. A Python module is simply a .py file that contains Python definitions and statements. Why do We Need Modules? Modules provide several benefits in programming: Code Reusability : Modules allow you to write code once and reuse it in multiple programs. This helps to avoid code duplication and makes the code more modular. Organization : Large programs can be broken down into smaller, more manageable modules. This improves code readability, maintainability, and ease of debugging. Separation of Concerns : Different parts of a program can be handled by different modules, ensuring that each module only handles a particular aspect of the problem domain (e.g., database operations, file handling, etc.). Namespace Management : Modules create their own namespace, meaning that functions and variables in a module won't interfere with those in other parts of the program. Ways to Use a Module in Python: Import Entire Module : import module_name Import Specific Elements : from module_name import element_name Use Aliases : import module_name as alias Dynamic Importing : import importlib and importlib.import_module('module_name')s 3(B) What do you mean by Assertion? Explain with examexample. Assertion in Python is a debugging aid that tests a condition as part of the code, raising an exception if the condition evaluates to False. It is primarily used during development and debugging to ensure that certain conditions hold true at specific points in the program. Assertions help catch bugs early by providing a way to automatically check for correctness. In Python, assertions are implemented using the assert keyword. Syntax: assert condition, "Optional error message" Example: def check_age(age): assert age > 0, "Age must be positive" print(f"Age is {age}") check_age(25) # Output: Age is 25 check_age(-5) # Raises AssertionError: Age must be positive Assertions in Python are used to test if a condition in the code is true. If it's false, an AssertionError is raised. They're used to catch bugs early by ensuring that certain conditions hold at specific points in the program. The assert keyword is used with a condition and an optional error message to perform the check. Assertions should primarily be used for debugging and development purposes, not for handling runtime errors or production-level exceptions. 4(A) Define : readline(), writeline() with example. 1. readline() Method: The readline() method is used to read one line at a time from a file. It reads from the current file position and moves the pointer to the next line. Syntax : file_object.readline(size=-1) size : (Optional) The number of bytes to read. If not specified, the method will read one complete line. The readline() method will return the next line from the file, including the newline character (\n), which signifies the end of a line in text files. If the file pointer reaches the end of the file, readline() returns an empty string (""). Example: # Open a file in read mode with open("example.txt", "r") as file: line1 = file.readline() # Reads the first line line2 = file.readline() # Reads the second line print("First Line:", line1) print("Second Line:", line2) # Read another line (this would return an empty string if there's no more lines) last_line = file.readline() print("Last Line:", last_line) # Will print an empty string if it's at the end 2. writeline() Method: The writeline() method is used to write a single line to a file . This method is generally used to write text to a file object in a line-by-line manner. Syntax : file_object.writeline(string) string : The string to be written to the file. It can also be a list or any iterable of strings. When using writeline(), you have to manually handle the newlines (i.e., you need to add \n at the end of the string if required). Example: # Open a file in write mode with open("output.txt", "w") as file: file.writeline("Hello, this is the first line.\n") file.writeline("Here comes the second line.\n") file.writeline("Final line in the file.\n") # Reading the written content with open("output.txt", "r") as file: print(file.read()) 4(B) Write a program to read a text file in Python and print no. of lines and no. of unique words. *Program: def read_file_and_count(file_path): # Initialize counters line_count = 0 unique_words = set() # Set to hold unique words # Open the file in read mode with open(file_path, 'r') as file: for line in file: line_count += 1 # Count each line # Split the line into words (you can customize the split logic if needed) words = line.split() for word in words: # Convert to lowercase and remove punctuation to ensure unique words are counted properly cleaned_word = ''.join(char.lower() for char in word if char.isalnum()) if cleaned_word: # Avoid counting empty strings unique_words.add(cleaned_word) # Print the results print("Number of lines:", line_count) print("Number of unique words:", len(unique_words)) # Provide the path to your text file file_path = "sample.txt" # Replace with your file path read_file_and_count(file_path) OR 4(A) Discuss various file handling methods available in python with suitable code. Opening a File: The file path (including the filename). The mode in which you want to open the file. Modes: r: Opens the file for reading (default). w: Opens the file for writing, truncating the file first. a: Opens the file for appending, writing at the end of the file. x: Opens the file for exclusive creation, failing if the file already exists. r+: Opens the file for both reading and writing. w+: Opens the file for both reading and writing, truncating the file first. a+: Opens the file for both reading and writing, appending at the end of the file. b: Opens the file in binary mode (for images, videos, etc.). Example: # Open a file for reading with open('my_file.txt', 'r') as file: content = file.read() print(content) # Open a file for writing with open('new_file.txt', 'w') as file: file.write('Hello, World!') # Open a file for appending with open('my_file.txt', 'a') as file: file.write('\nThis is a new line.') Reading from a File: read(): Reads the entire file content as a string. readline(): Reads a single line from the file. readlines(): Reads all lines into a list of strings. Example: with open('my_file.txt', 'r') as file: # Read the entire file content = file.read() print(content) # Read one line at a time line = file.readline() while line: print(line.strip()) # Remove trailing newline line = file.readline() # Read all lines into a list lines = file.readlines() print(lines) Writing to a File: write(): Writes a string to the file. writelines(): Writes a list of strings to the file. Example: with open('my_file.txt', 'w') as file: file.write('This is a test.') lines = ['Line 1\n', 'Line 2\n'] file.writelines(lines) Closing a File: It is important to close a file after you're done with it. This releases system resources and ensures data is written to disk. close(): Closes the file object. Example: file = open('my_file.txt', 'r') # ... do something with the file ... file.close() 4(B) Write a program to read email ids from a file. Program : def read_emails_from_file(file_path): try: # Open the file in read mode with open(file_path, 'r') as file: # Read each line in the file emails = file.readlines() # Iterate and print each email address print("List of Email IDs in the file:") for email in emails: print(email.strip()) # .strip() is used to remove leading/trailing whitespace or newline characters except FileNotFoundError: print(f"Error: The file at {file_path} does not exist.") except Exception as e: print(f"An error occurred: {str(e)}") # Specify the file path file_path = 'emails.txt' # Replace with your file path read_emails_from_file(file_path) 5(A) Write the general syntax of class declaration in Python. Explain declaration of class and its object with example. In Python, a class is declared using the class keyword, followed by the class name and a colon. The body of the class contains the class methods and attributes (variables). class ClassName: # Constructor Method def __init__(self, parameter1, parameter2): self.parameter1 = parameter1 self.parameter2 = parameter2 # Other methods def some_method(self): # Code for method pass Declaration of Class and its Object: After the class is defined, an object is created by calling the class name like a function. Each object will have its own instance of the class's attributes. Steps for Class Declaration and Object Creation : Declare a class. Define its constructor (__init__) to initialize its attributes. Define other methods within the class. Create an object by invoking the class. Access object attributes and methods using dot notation. init() method : The constructor method (__init__) is used to initialize the object attributes when the object is created. self : It represents the instance of the object and allows the object to refer to its own attributes and methods. Object Creation : An object is created by calling the class and passing the required arguments. Method Calling : Methods can be called on the object using the dot notation. 5(B) What is Inheritance? Explain multiple level inheritance with example. Inheritance is a feature of object-oriented programming (OOP) that allows one class (child class) to inherit the properties and methods of another class (parent class). The purpose of inheritance is to promote code reusability and establish a relationship between classes. Parent class (also called base class or superclass ) is the class whose properties and methods are inherited. Child class (also called derived class or subclass ) is the class that inherits the properties and methods from the parent class. What is Inheritance? Inheritance is a feature of object-oriented programming (OOP) that allows one class (child class) to inherit the properties and methods of another class (parent class). The purpose of inheritance is to promote code reusability and establish a relationship between classes. Parent class (also called base class or superclass ) is the class whose properties and methods are inherited. Child class (also called derived class or subclass ) is the class that inherits the properties and methods from the parent class. Advantages of Inheritance : Code Reusability : Inheritance allows you to reuse the code from the parent class, avoiding redundancy. Extensibility : A child class can extend or override the functionality of the parent class. Improved Code Organization : Organizing common functionalities in the parent class allows for cleaner and more manageable code. Multiple Level Inheritance in Python: In multiple level inheritance , a class (called the grandchild class) inherits from another class (the child class), which, in turn, inherits from a parent class. Thus, the inheritance forms a chain of relationships between three or more classes. Parent class → Child class → Grandchild class In this case, the grandchild class inherits methods and attributes from both the parent class and child class. Multiple Level Inheritance is the type of inheritance where a subclass inherits from another subclass, forming a hierarchy. The hierarchy allows a class to inherit attributes and methods from its ancestor classes, promoting reusability and extensibility. Syntax: class Parent: # Parent class constructor and methods pass class Child(Parent): # Child class inherits from Parent pass class Grandchild(Child): # Grandchild class inherits from Child (and indirectly from Parent) pass OR 5(A) Discuss Encapsulation and Information Hiding. Encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, or class. This means that the internal representation of an object is hidden from outside manipulation and access. Instead, access to the data is provided through methods that form an interface between the object and the outside world. In essence, encapsulation ensures that the object's data and operations are kept together, but access to the data can be controlled and managed. Key Points of Encapsulation: It allows you to define the object's interface for interacting with the object while hiding the implementation details. Encapsulation protects the object's internal state from accidental changes. It improves code modularity, maintainability, and reusability. 2. Information Hiding: Information hiding is a design principle closely tied to encapsulation. It refers to the idea of hiding the internal details or implementation of a class from outside users (other classes, external systems, etc.). In other words, the internals of a class should not be exposed unnecessarily—only the essential functionalities that a class performs should be made accessible. Information hiding encourages focusing on "what" an object does rather than "how" it does it. Internal implementation (such as details of calculations, data structures, etc.) is hidden from users, making it easier to modify the class’s internal workings without affecting external code that uses the class. This hides complexity, reduces dependencies, and prevents accidental misuse of the class's internal data. Conclusion: Encapsulation and Information Hiding are essential principles in OOP to create robust, flexible, and maintainable systems. Encapsulation helps in bundling data and operations into a cohesive unit (class), while Information Hiding controls access to data and hides unnecessary details, focusing on essential interactions. 5(B) What is Class Variable and Instance Variable? Explain both and give one small example. 1. Class Variable: Class variables are variables that are shared by all instances of the class. They are defined within the class construction and are usually used to store values that should be consistent for all instances of that class. Class variables are created within the class but outside any methods , typically using the class definition itself. Since class variables are shared by all objects of that class, they can be accessed by any object of that class. Access : You can access class variables via the class name (ClassName.variable) or directly through an instance (objectName.variable). 2. Instance Variable: Instance variables are variables that belong to a particular instance or object of a class. They are created inside the init () method (constructor) using the self keyword. Each instance of the class has its own copy of these variables. Instance variables are initialized within the init() method and are specific to the object created. Access : Instance variables are accessed using the self keyword inside class methods and by accessing the object itself (objectName.variable). Differences Between Class Variables and Instance Variables: Aspect Class Variables Instance Variables Defined in Inside the class but outside methods. Inside methods, typically in the init method. Access Accessed via class name or through object instances. Accessed through object instances only. Scope Shared by all instances of the class. Specific to the instance of the class. Modification Modifying a class variable via any instance affects all instances. Modifying an instance variable only affects that particular object. Purpose Used for values that should be the same across all instances (common). Used for values that are unique to each instance (specific).
- RDBMS Que. & Ans. MCA
Explain the advantages of Database systems. Explain the three-level architecture of DBMS. Explain different data models. Explain the advantages of Database systems. Explain different data types in SQL. Explain DDL/DML commands in SQL. Explain different types of joins in SQL with examples: MCQS OR ONE LINEAR: Explain the advantages of Database systems. Relational Database Management Systems (RDBMS) offer several advantages that make them a preferred choice for storing, organizing, and managing data. Here's an overview of the primary benefits of RDBMS systems: 1. Data Integrity: RDBMS enforces constraints like primary keys, foreign keys, unique constraints, and checks, which help ensure the accuracy and consistency of the data. 2. Data Redundancy Control: Through normalization, RDBMS minimizes data redundancy (duplicate data) and ensures a more efficient database structure. 3. Data Security: RDBMS provides robust mechanisms for user authentication and authorization, ensuring that only authorized individuals can access or modify the data. 4. Data Abstraction: With its schema-based architecture, RDBMS separates the physical data storage from how it’s accessed and represented to users, simplifying application development and management. 5. Transaction Management: RDBMS supports ACID (Atomicity, Consistency, Isolation, Durability) properties, ensuring reliable transaction processing and preventing data inconsistencies in cases of system failures. 6. Data Sharing: Multiple users can access and manipulate data concurrently in a controlled manner through features like locking and multi-user transactions. 7. Structured Query Language (SQL): SQL provides a standard way to interact with the database, allowing for efficient querying, data manipulation, and administrative tasks. 8. Scalability: RDBMS systems can handle small to very large amounts of data. They support horizontal and vertical scaling, depending on the need and architecture. 9. Backup and Recovery: Most RDBMS systems include automated backup and recovery mechanisms, ensuring data can be restored in case of failure or corruption. 10. Data Consistency: Integrity constraints and relationships (like foreign keys) maintain consistent data across related tables, reducing errors and increasing data reliability. 11. Performance Optimization: Features like indexing, caching, and query optimization in RDBMS can significantly improve data retrieval speed and overall performance. 12. Compatibility: RDBMS often supports integration with various tools, applications, and platforms, making it easier to incorporate into diverse software environments. 13. Support for Relationships: The tabular structure of RDBMS, with rows and columns, effectively models and maintains relationships among different entities, enabling meaningful queries and data analysis. Explain the three-level architecture of DBMS. 1. External Level (User Views): Description :This is the topmost layer where individual users or user groups interact with the database using customized views of the data that meet their specific needs. Characteristics : Provides multiple views of the database, ensuring only relevant data is accessible to each user or application. Hides the complexity of the underlying schema and physical storage. Uses relational constructs such as tables, views, and queries based on SQL. 2. Conceptual Level (Logical Schema): Description :This middle layer provides a unified logical representation of the entire database. It focuses on organizing the relationships, constraints, and logical structure without dealing with physical details. Characteristics : Defines tables (relations), attributes (columns), and constraints like primary keys , foreign keys , and unique keys . Ensures data integrity, consistency , and correctness. Hides internal storage structures while presenting a consistent view of the data for all external levels. 3. Internal Level (Physical Schema) : Description :The internal level deals with the physical storage of data on the hardware, such as how tables, indexes, and relationships are stored and retrieved efficiently. Characteristics : Focuses on storage techniques like B-tree indexing , hashing , and data compression . Handles details like page sizes, storage locations, and the organization of records in memory. Aims to optimize database performance through efficient storage and retrieval mechanisms. Explain different data models. Hierarchical - Hierarchical data (tree structures) Network - Complex relationships (many-to-many) Relational - Tabular data with constraints ER - Database design and visualization Object-Oriented - Complex data types and behavior Semi-Structured - Dynamic or evolving schemas Key-Value - Simple key-based access Column-Oriented - Analytical workloads and big data Graph - Highly interconnected data Explain different data types in SQL. INT / INTEGER : Stores whole numbers (e.g., -2,147,483,648 to 2,147,483,647 for 32-bit systems). SMALLINT : Smaller range than INT (e.g., -32,768 to 32,767). TINYINT : Very small integers (e.g., 0 to 255). BIGINT : Very large whole numbers (e.g., 64-bit range). DECIMAL(p, s) / NUMERIC(p, s) : Fixed precision and scale numbers BIT : Represents boolean values as 0 (false) or 1 (true) FLOAT(n) : Floating-point numbers with optional precision. REAL : Single-precision floating-point numbers. CHAR(n) : Fixed-length string of n characters VARCHAR(n) : Variable-length string up to n characters TEXT : Stores large amounts of text (not standardized in all databases). DATE : Stores dates in YYYY-MM-DD format. TIME : Stores times in HH:MM:SS format (optional precision for fractional seconds). DATETIME / TIMESTAMP : Stores both date and time (YYYY-MM-DD HH:MM:SS). YEAR : Stores a four-digit year (YYYY). BINARY(n) : Fixed-length binary data of n bytes. VARBINARY(n) : Variable-length binary data of up to n bytes. BLOB (Binary Large Object) : Used for large binary data such as multimedia files BOOLEAN : Stores TRUE/FALSE values (standardized as BIT in some databases). ENUM : Used to store predefined string values SET : A string object that can store multiple predefined values GEOMETRY : Represents spatial data (points, lines, polygons). POINT : Represents a single point in space. LINESTRING : Represents a line. POLYGON : Represents an area. Explain DDL/DML commands in SQL. 1. Data Definition Language (DDL): DDL commands are used to define and manage the structure of database objects such as tables, views, indexes, and schemas. These commands primarily deal with the database schema and its components. CREATE: Used to create new database objects such as tables, views, indexes, or databases. Syntax : CREATE TABLE TableName ( Column1 DataType Constraints, Column2 DataType Constraints, ... ); ALTER: Used to modify an existing database object (e.g., add/remove columns, change data types). Syntax : ALTER TABLE TableName ADD ColumnName DataType; DROP: Used to delete an existing database object, including its structure and data. Syntax : DROP TABLE TableName; TRUNCATE: Removes all rows from a table without logging individual row deletions. The table structure remains intact. Syntax : TRUNCATE TABLE TableName; RENAME: Used to rename an existing database object. Syntax : RENAME TABLE OldTableName TO NewTableName; 2. Data Manipulation Language (DML): DML commands are used to manipulate data stored in the database. These commands allow users to perform CRUD (Create, Read, Update, Delete) operations. INSERT: Adds new records (rows) to a table. Syntax : INSERT INTO TableName (Column1, Column2, ...) VALUES (Value1, Value2, ...); SELECT: Retrieves data from one or more tables. Syntax : SELECT Column1, Column2, ... FROM TableName WHERE Condition; UPDATE: Modifies existing records in a table. Syntax : UPDATE TableName SET Column1 = Value1, Column2 = Value2, ... WHERE Condition; DELETE: Removes one or more records from a table. Syntax : DELETE FROM TableName WHERE Condition; Explain different types of joins in SQL with examples: Type Description Key Example Output INNER JOIN Only matching rows from both tables. Matching employees and departments. LEFT JOIN All rows from left table, unmatched rows in right are NULL. All employees, even those without a department. RIGHT JOIN All rows from right table, unmatched rows in left are NULL. All departments, even those without employees. FULL JOIN All rows from both tables, unmatched rows filled with NULLs. All employees and all departments. CROSS JOIN Cartesian product of rows (no filtering). Every employee paired with every department. SELF JOIN Joins a table with itself (useful for hierarchies like manager-subordinate relationships). Employees who report to the same or related managers. MCQS OR ONE LINEAR: Which of the following is generally used for performing tasks like creating the structure of the relations, deleting relation? DDL(Data Definition Language) Which of the following provides the ability to query information from the database and insert tuples into, delete tuples from, and modify tuples in the database? DML(Data Manipulation Language) The given Query can also be replaced with_______: SELECT name, course_id FROM instructor, teaches WHERE instructor_ID = teaches_ID ; Ans. Select name, course_id from instructor natural join teaches; Which one of the following given statements possibly contains the error? select empid where empid = 1009 and Lastname = 'GELLER'; What do you mean by one to many relationships? One teacher can have many classes A Database Management System is a type of _________software. It is a type of system software The term "FAT" is stands for_____. File Allocation Table Which of the following can be considered as the maximum size that is supported by FAT? 4 GB The term "NTFS" refers to which one of the following? New Technology File System Which of the following can be considered as the maximum size that is supported by NTFS? 4 GB A huge collection of the information or data accumulated form several different sources is known as ________: Data Warehouse Which of the following can be used to extract or filter the data & information from the data warehouse? Data mining Which of the following refers to the level of data abstraction that describes exactly how the data actually stored? Physical Level What is RDBMS? RDBMS stands for Relational Database Management System. RDBMS is a program used to maintain a relational database. RDBMS is the basis for all modern database systems such as MySQL, Microsoft SQL Server, Oracle, and Microsoft Access. RDBMS uses SQL queries to access the data in the database. What is a Database Table? A table is a collection of related data entries, and it consists of columns and rows. A column holds specific information about every record in the table. A record (or row) is each individual entry that exists in a table. What is a Relational Database? A relational database defines database relationships in the form of tables. The tables are related to each other - based on data common to each. What is SQL? SQL is the standard language for dealing with Relational Databases. SQL is used to insert, search, update, and delete database records. Semicolon after SQL Statements? Some database systems require a semicolon at the end of each SQL statement. Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server. In this tutorial, we will use semicolon at the end of each SQL statement. Some of The Most Important SQL Commands: SELECT - extracts data from a database UPDATE - updates data in a database DELETE - deletes data from a database INSERT INTO - inserts new data into a database CREATE DATABASE - creates a new database ALTER DATABASE - modifies a database CREATE TABLE - creates a new table ALTER TABLE - modifies a table DROP TABLE - deletes a table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index The MySQL SELECT Statement: The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set. The MySQL AND, OR and NOT Operators The WHERE clause can be combined with AND , OR , and NOT operators. The AND and OR operators are used to filter records based on more than one condition: The AND operator displays a record if all the conditions separated by AND are TRUE. The OR operator displays a record if any of the conditions separated by OR is TRUE. The NOT operator displays a record if the condition(s) is NOT TRUE. The MySQL ORDER BY Keyword: The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword. THANK YOU
- RDBMS MCA
RDBMS DBMS & RDBMS Diffrence Database Integrity Databse Languages SQL SQL Commands SQL Arithmaric Operator SQL Logical Operatos What is RDBMS (Relational Database Management System): RDBMS stands for Relational Database Management System. All modern database management systems like SQL, MS SQL Server, IBM DB2, ORACLE, My-SQL, and Microsoft Access are based on RDBMS. It is called Relational Database Management System (RDBMS) because it is based on the relational model introduced by E.F. Codd. Cardinality: The total number of tuples at any one time in a relation is known as the table's cardinality. The relation whose cardinality is 0 is called an empty table. NULL Values: The NULL value of the table specifies that the field has been left blank during record creation. It is different from the value filled with zero or a field that contains space. Data Integrity: There are the following categories of data integrity exist with each RDBMS: Entity integrity : It specifies that there should be no duplicate rows in a table. Domain integrity : It enforces valid entries for a given column by restricting the type, the format, or the range of values. Referential integrity specifies that rows cannot be deleted, which are used by other records. User-defined integrity : It enforces some specific business rules defined by users. These rules are different from the entity, domain, or referential integrity. Difference between DBMS and RDBMS : DBMS RDBMS DBMS applications store data as file . RDBMS applications store data in a tabular form . In DBMS, data is generally stored in either a hierarchical form or a navigational form. In RDBMS, the tables have an identifier called primary key and the data values are stored in the form of tables. Normalization is not present in DBMS. Normalization is present in RDBMS. DBMS does not apply any security with regards to data manipulation. RDBMS defines the integrity constraint for the purpose of ACID (Atomocity, Consistency, Isolation and Durability) property. DBMS is meant to be for small organization and deal with small data . it supports single user . RDBMS is designed to handle large amount of data . it supports multiple users . DBMS does not support distributed database . RDBMS supports distributed database . Examples of DBMS are file systems, xml etc. E xample of RDBMS are mysql , postgre , sql server , oracle etc. Types of DBMS Architecture: Database architecture can be seen as a single tier or multi-tier. But logically, database architecture is of two types like: 2-tier architecture and 3-tier architecture . 1-Tier Architecture: In this architecture, the database is directly available to the user. It means the user can directly sit on the DBMS and uses it. Any changes done here will directly be done on the database itself. It doesn't provide a handy tool for end users. The 1-Tier architecture is used for development of the local application, where programmers can directly communicate with the database for the quick response. 2-Tier Architecture: The 2-Tier architecture is same as basic client-server. In the two-tier architecture, applications on the client end can directly communicate with the database at the server side. For this interaction, API's like: ODBC , JDBC are used. The user interfaces and application programs are run on the client-side. The server side is responsible to provide the functionalities like: query processing and transaction management. To communicate with the DBMS, client-side application establishes a connection with the server side. 3-Tier Architecture: The 3-Tier architecture contains another layer between the client and server. In this architecture, client can't directly communicate with the server. The application on the client-end interacts with an application server which further communicates with the database system. End user has no idea about the existence of the database beyond the application server. The database also has no idea about any other user beyond the application. The 3-Tier architecture is used in case of large web application. Data Models: Data Model is the modeling of the data description, data semantics, and consistency constraints of the data. It provides the conceptual tools for describing the design of a database at each level of data abstraction. 1) Relational Data Model: 2) Entity-Relationship Data Model: 3) Object-based Data Model: 4) Semistructured Data Model: Data Independence: Logical Data Independence Physical Data Independence Types of Database Languages: 1. Data Definition Language (DDL): DDL stands for D ata D efinition L anguage. It is used to define database structure or pattern. It is used to create schema, tables, indexes, constraints, etc. in the database. Using the DDL statements, you can create the skeleton of the database. Create: It is used to create objects in the database. Alter: It is used to alter the structure of the database. Drop: It is used to delete objects from the database. Truncate: It is used to remove all records from a table. Rename: It is used to rename an object. Comment: It is used to comment on the data dictionary. 2. Data Manipulation Language (DML): DML stands for D ata M anipulation L anguage. It is used for accessing and manipulating data in a database. It handles user requests. Select: It is used to retrieve data from a database. Insert: It is used to insert data into a table. Update: It is used to update existing data within a table. Delete: It is used to delete all records from a table. Merge: It performs UPSERT operation, i.e., insert or update operations. Call: It is used to call a structured query language or a Java subprogram. Explain Plan: It has the parameter of explaining data. Lock Table: It controls concurrency. 3. Data Control Language (DCL): DCL stands for D ata C ontrol L anguage. It is used to retrieve the stored or saved data. The DCL execution is transactional. It also has rollback parameters. Grant: It is used to give user access privileges to a database. Revoke: It is used to take back permissions from the user. 4. Transaction Control Language (TCL): TCL is used to run the changes made by the DML statement. TCL can be grouped into a logical transaction. Commit: It is used to save the transaction on the database. Rollback: It is used to restore the database to original since the last Commit. SQL: SQL stands for Structured Query Language. It is used for storing and managing data in relational database management system (RDMS). In RDBMS data stored in the form of the tables. It is a standard language for Relational Database System. It enables a user to create, read, update and delete relational databases and tables. All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as their standard database language. SQL allows users to query the database in a number of ways, using English-like statements. SQL Commands: SQL commands are instructions. It is used to communicate with the database. It is also used to perform specific tasks, functions, and queries of data. SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table, set permission for users. 1. Data Definition Language (DDL): CREATE TABLE TABLE_NAME (COLUMN_NAMES DATATYPES [ ...]); CREATE TABLE EMPLOYEE(Name VARCHAR2( 20 ), Email VARCHAR2( 100 ), DOB DATE); DROP TABLE table_name [cascade constraint]; DROP TABLE EMPLOYEE; ALTER TABLE table_name ADD column_name column-definition; ALTER TABLE STU_DETAILS ADD (ADHAR_NUM VARCHAR2 ( 15 )); ALTER TABLE STU_DETAILS ADD ADHAR_NUM, NAME; ALTER TABLE table_name MODIFY (column definitions....); ALTER TABLE STU_DETAILS MODIFY (ADHAR_NUM VARCHAR2 ( 20 )); ALTER TABLE STU_DETAILS MODIFY (ADHAR_NUM VARCHAR2 ( 20 ) NOT NULL); TRUNCATE: It is used to delete all the rows from the table and free the space containing the table. TRUNCATE TABLE table_name; TRUNCATE TABLE EMPLOYEE; Rename to ; Rename STU_NAME to STUDENT_NAME; 2. Data Manipulation Language: INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN); INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS"); INSERT INTO TABLE_NAME (col1, col2, col3,.... col N) VALUES (value1, value2, value3, .... valueN), (value1, value2, value3, .... valueN); INSERT INTO javatpoint (Author, Subject) VALUES ( "Sonoo", "DBMS"), ("Raman", "DBMS"), ("Priya", "DBMS"); UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION] DELETE FROM table_name [WHERE condition]; DELETE FROM javatpoint WHERE Author="Sonoo"; SELECT expressions FROM TABLES WHERE conditions; SELECT emp_name FROM employee WHERE age > 20 ; 3. Data Control Language: GRANT ON To ; GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER; REVOKE ON FROM ; REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2; 4. Transaction Control Language: COMMIT; DELETE FROM CUSTOMERS WHERE AGE = 25 ; COMMIT; ROLLBACK; DELETE FROM CUSTOMERS WHERE AGE = 25 ; ROLLBACK; SAVEPOINT SAVEPOINT_NAME; Rollback TO DELETE FROM CUSTOMERS WHERE AGE = 15 ; SAVEPOINT A; DELETE FROM CUSTOMERS WHERE AGE = 35 ; ROLLBCAK TO A; SQL Arithmetic Operators: Operator Description Example + It adds the value of both operands. a+b will give 30 - It is used to subtract the right-hand operand from the left-hand operand. a-b will give 10 * It is used to multiply the value of both operands. a*b will give 200 / It is used to divide the left-hand operand by the right-hand operand. a/b will give 2 % It is used to divide the left-hand operand by the right-hand operand and returns reminder. a%b will give 0 SQL Logical Operatos: Operator Description ALL It compares a value to all values in another value set. AND It allows the existence of multiple conditions in an SQL statement. ANY It compares the values in the list according to the condition. BETWEEN It is used to search for values that are within a set of values. IN It compares a value to that specified list value. NOT It reverses the meaning of any logical operator. OR It combines multiple conditions in SQL statements. EXISTS It is used to search for the presence of a row in a specified table. LIKE It compares a value to similar values using wildcard operator. SQL SELECT Statement: SELECT * FROM table_name; SELECT * FROM EMPLOYEE; SELECT column_name1, columnN FROM table_name; SELECT EMP_ID FROM EMPLOYEE; SELECT EMP_NAME, SALARY FROM EMPLOYEE; SELECT DISTINCT CITY, SALARY FROM EMPLOYEE; SQL INSERT Statement: The SQL INSERT statement is used to insert a single or multiple data in a table. In SQL, You can insert the data in two ways: Without specifying column name By specifying column name INSERT INTO TABLE_NAME VALUES (value1, value2, value 3, .... Value N); INSERT INTO EMPLOYEE VALUES (6, 'Marry', 'Canada', 600000, 48); INSERT INTO TABLE_NAME [(col1, col2, col3,.... col N)] VALUES (value1, value2, value 3, .... Value N); INSERT INTO EMPLOYEE (EMP_ID, EMP_NAME, AGE) VALUES (7, 'Jack', 40); SQL Update Statement: UPDATE table_name SET column1 = value1 , column2 = value2 , ...WHERE condition; UPDATE table_name SET column_name = value WHERE condition; UPDATE EMPLOYEE SET EMP_NAME = 'Emma' WHERE SALARY = 500000 ; UPDATE table_name SET column_name = value1 , column_name2 = value2 WHERE condition; UPDATE EMPLOYEE SET EMP_NAME = 'Kevin' , City = 'Boston' WHERE EMP_ID = 5 ; DELETE FROM table_name WHERE some_condition; DELETE FROM EMPLOYEE WHERE EMP_NAME = 'Kristen' ; DELETE FROM EMPLOYEE WHERE AGE = 30 ; DELETE * FROM table_name; or DELETE FROM table_name; DELETE FROM EMPLOYEE; SQL Aggregate Functions: SQL aggregation function is used to perform the calculations on multiple rows of a single column of a table. It returns a single value. It is also used to summarize the data. Types of SQL Aggregation Function: 1. COUNT FUNCTION: COUNT function is used to Count the number of rows in a database table. It can work on both numeric and non-numeric data types. COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table. COUNT(*) considers duplicate and Null. Syntax: SELECT COUNT(*) FROM PRODUCT_MAST; SELECT COUNT(*) FROM PRODUCT_MAST; WHERE RATE>= 20 ; 2. SUM Function: Sum function is used to calculate the sum of all selected columns. It works on numeric fields only. Syntax: SUM() or SUM( [ALL|DISTINCT] expression ) SELECT SUM(COST) FROM PRODUCT_MAST; SELECT SUM(COST) FROM PRODUCT_MAST WHERE QTY> 3 ; 3. AVG function: The AVG function is used to calculate the average value of the numeric type. AVG function returns the average of all non-Null values. Syntax: AVG() or AVG( [ALL|DISTINCT] expression ) SELECT AVG(COST) FROM PRODUCT_MAST; 4. MAX Function: MAX function is used to find the maximum value of a certain column. This function determines the largest value of all selected values of a column. Syntax: MAX() or MAX( [ALL|DISTINCT] expression ) SELECT MAX(RATE) FROM PRODUCT_MAST; 5. MIN Function: MIN function is used to find the minimum value of a certain column. This function determines the smallest value of all selected values of a column. Syntax: MIN() or MIN( [ALL|DISTINCT] expression ) SELECT MIN(RATE) FROM PRODUCT_MAST; SQL JOIN: As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to combine two or more tables". Types of SQL JOIN: INNER JOIN NATURAL JOIN LEFT JOIN RIGHT JOIN FULL JOIN SELF JOIN CARTESIAN JOIN SQL Set Operation: Types of Set Operation: Union UnionAll Intersect Minus 1. Union: The SQL Union operation is used to combine the result of two or more SQL SELECT queries. In the union operation, all the number of datatype and columns must be same in both the tables on which UNION operation is being applied. The union operation eliminates the duplicate rows from its resultset. 2. Union All: Union All operation is equal to the Union operation. It returns the set without removing duplication and sorting the data. 3. Intersect: It is used to combine two SELECT statements. The Intersect operation returns the common rows from both the SELECT statements. In the Intersect operation, the number of datatype and columns must be the same. It has no duplicates and it arranges the data in ascending order by default. 4. Minus: It combines the result of two SELECT statements. Minus operator is used to display the rows which are present in the first query but absent in the second query. It has no duplicates and data arranged in ascending order by default. Thank You
- Python Theory Assignment 3 (Exception)(MCA Sem-i)
What is exceptions? Discuss how exceptions simplify programs. ANS: In Python, an exception is an event that occurs during the execution of a program, disrupting the normal flow of instructions. Exceptions are often raised when an error occurs, such as a division by zero, file not found, or an invalid input. How exceptions simplify programs: Separation of Error Handling: Exceptions allow you to separate the error-handling code from the main logic of your program. This makes your code more readable, maintainable, and easier to understand. Graceful Handling of Errors: Without exceptions, you would need to manually check for potential errors at every step of your program. This can be tedious and error-prone. Exceptions provide a structured way to handle errors, ensuring that your program doesn't crash unexpectedly. Specific Error Handling: You can catch specific types of exceptions and handle them differently. This allows you to provide more tailored error messages and take appropriate actions depending on the nature of the error. Propagation of Errors: Exceptions can be propagated up the call stack, allowing higher-level functions to handle them. This means that you don't need to handle every possible error in every function. Built-in Exception Hierarchy: Python provides a rich hierarchy of built-in exceptions, making it easy to identify and handle different types of errors. Example: try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") What do you mean by Assertion ? Explain with example. ANS: Assertions in Python: In Python, an assertion is a statement that declares a condition that should always be true during program execution. It's essentially a debugging tool that helps you catch errors early in the development process. Syntax: assert condition, error_message How it works: Condition Check: The condition is evaluated. True: If the condition is True, the program continues to the next line. False: If the condition is False, an AssertionError is raised, along with the optional error_message. Example: def divide(a, b): assert b != 0, "Division by zero error" return a / b result = divide(10, 2) # This will work print(result) result2 = divide(10, 0) # This will raise an AssertionError print(result2) What is exception? Explain how to handle user defined exception in python (Give example)? ANS: In Python, an exception is an event that occurs during the execution of a program that disrupts the normal flow of control. When an exception occurs, the Python interpreter raises an exception object, and if not handled properly, the program terminates abruptly. Handling Exceptions To handle exceptions, we use a try-except block. Syntax: try: # Code that might raise an exception except ExceptionType: # Code to handle the exception Example: def divide(x, y): try: result = x / y except ZeroDivisionError: print("Error: Division by zero") else: print("Result:", result) finally: print("This block always executes") divide(10, 2) # Output: Result: 5.0 divide(10, 0) # Output: Error: Division by zero User-Defined Exceptions You can define your own custom exceptions by creating a new class that inherits from the built-in Exception class. Example: class NegativeNumberError(Exception): pass def factorial(n): if n < 0: raise NegativeNumberError("Factorial is not defined for negative numbers") elif n == 0: return 1 else: return n * factorial(n - 1) try: print(factorial(-5)) except NegativeNumberError as e: print(e) Say TRUE of FALSE with justification. a) While doing exception handling, “else” is the block which executes in all the situations whether exception occurs or not. b) There is nothing rare about exceptions in Python c) While doing exception handling, “else” is the block which executes in all the situations whether exception occurs or not. ANS: a) FALSE. The else block in a try-except block only executes when no exceptions are raised within the try block. b) FALSE. While exceptions are common in Python and other programming languages, they should be handled gracefully to prevent program crashes. Well-written code should minimize the likelihood of exceptions occurring. c) FALSE. As explained in (a), the else block only executes when no exceptions are raised within the try block. Discuss use of assert statement. ANS: The assert statement in Python is a powerful tool for debugging and testing code. It's used to verify assumptions and conditions within your code. How it works: Condition Check: The assert statement evaluates a specified condition. True: If the condition is True, the program continues to the next line. False: If the condition is False, an AssertionError is raised, along with an optional error message. Syntax: assert condition, error_message Common Use Cases: Debugging: Early Error Detection: Identify errors early in development. Assumption Verification: Ensure that assumptions about your code's behavior are correct. Invariant Checking: Verify conditions that should always hold true. Testing: Unit Tests: Use assert to check the correctness of specific functions or methods. Integration Tests: Verify the interaction between different parts of your code. Example: def divide(a, b): assert b != 0, "Division by zero error" return a / b result = divide(10, 2) # This will work print(result) result2 = divide(10, 0) # This will raise an AssertionError print(result2) What is Exception? Explain exception handling with example. ANS: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. In simpler terms, it's an error that happens while your program is running. Exception Handling Exception handling is a mechanism to deal with these exceptions gracefully, preventing your program from crashing and providing a more robust and user-friendly experience. Example: def divide(x, y): try: result = x / y print("Result:", result) except ZeroDivisionError: print("Error: Division by zero") divide(10, 0) Explanation: try block: This block contains the code that might throw an exception. Here, we're trying to divide x by y. except block: This block specifies the type of exception we want to handle. In this case, we're handling the ZeroDivisionError exception, which occurs when you try to divide a number by zero. If this exception occurs, the code inside the except block will be executed. Write exception block in python. How to use exception as a control flow mechanism? ANS: In Python, exception blocks are defined using the try and except keywords. The try block contains the code that might raise an exception, while the except block handles the exception if it occurs. Basic Example: try: # Code that might raise an exception x = 10 / 0 except ZeroDivisionError: print("Error: Division by zero") Multiple except Blocks: You can have multiple except blocks to handle different types of exceptions: try: # Code that might raise an exception x = int(input("Enter a number: ")) y = 10 / x except ZeroDivisionError: print("Error: Division by zero") except ValueError: print("Error: Invalid input") General Exception Handling: You can use a generic except block to catch any exception that isn't specifically handled: try: # Code that might raise an exception x = int(input("Enter a number: ")) y = 10 / x except Exception as e: print("An error occurred:", e) Using Exceptions as a Control Flow Mechanism While exceptions are primarily used for error handling, they can also be used as a control flow mechanism in certain scenarios. This is often not recommended as it can make code less readable and maintainable. However, in some specific cases, it can be useful: Early Termination: You can raise an exception to immediately terminate a function or loop: def process_data(data): for item in data: if item < 0: raise ValueError("Negative value encountered") # Process the item Signaling Abnormal Conditions: You can raise a custom exception to signal an abnormal condition: class DataValidationError(Exception): pass def validate_data(data): if not data: raise DataValidationError("Data is empty") # Validate other conditions Discuss the use of raise statement with example. ANS: The raise statement in Python is used to explicitly raise an exception. This can be useful in various scenarios, such as: Signaling Errors: When a function encounters an error condition that it cannot handle, it can raise an appropriate exception to inform the caller. def divide(x, y): if y == 0: raise ZeroDivisionError("Division by zero") return x / y Custom Exceptions: You can define your own custom exceptions to represent specific error conditions: class NegativeValueError(Exception): pass def calculate_sqrt(x): if x < 0: raise NegativeValueError("Cannot calculate square root of negative number") return x**0.5 Re-raising Exceptions: You can re-raise an exception to propagate it to a higher level of the call stack: def process_data(data): try: # Process the data ... except ValueError as e: print("Error processing data:", e) raise # Re-raise the exception Explain logging in python with proper example. ANS: Logging is a powerful technique to record events, errors, and other information during the execution of a Python program. It helps in debugging, monitoring, and analyzing the behavior of your application. The logging Module Python's built-in logging module provides a flexible framework for logging. Here's a basic example: import logging # Create a logger logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Create a formatter formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') # Create a console handler console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) # Add the handler to the logger logger.addHandler(console_handler) # Log messages logger.debug('This is a debug message') logger.info('This is an info message') logger.warning('This is a warning message') logger.error('This is an error message') logger.critical('This is a critical message') Explanation: Logger Creation: getLogger(__name__): Creates a logger instance with the name of the current module. setLevel(logging.DEBUG): Sets the minimum severity level for log messages. Formatter Creation: logging.Formatter(): Creates a formatter object to specify the format of log messages. Handler Creation: logging.StreamHandler(): Creates a handler to log messages to the console. Handler Configuration: setFormatter(): Associates the formatter with the handler. Handler Addition: addHandler(): Adds the handler to the logger. Logging Messages: logger.debug(), logger.info (), logger.warning(), logger.error(), and logger.critical(): Log messages with different severity levels. Write a Python program which reads a number from user repeatedly and if number is not in range of values a, b, where a<b , it raises custom exception tooBigNumber and tooSmallNumber. when user enters number in range, it prints "Valid Number" and terminates. ANS: class TooBigNumber(Exception): pass class TooSmallNumber(Exception): pass def read_number(a, b): while True: try: num = int(input("Enter a number: ")) if num < a: raise TooSmallNumber("Number is too small") elif num > b: raise TooBigNumber("Number is too big") else: print("Valid Number") break except TooSmallNumber as e: print(e) except TooBigNumber as e: print(e) # Example usage: a = 10 b = 20 read_number(a, b) Explanation: Custom Exceptions: We define two custom exceptions, TooBigNumber and TooSmallNumber, to represent the specific error conditions. read_number Function: Takes two arguments, a and b, representing the range limits. Inside a while True loop, it repeatedly prompts the user for a number. Converts the input to an integer using int(). Checks if the number is within the range: If it's too small, raises a TooSmallNumber exception. If it's too big, raises a TooBigNumber exception. If it's within the range, prints "Valid Number" and breaks the loop. The try-except block handles the custom exceptions and prints appropriate error messages. List out keywords used in exception handling and explain with example. Write a Python program which will throw exception if the value entered by user is less than zero. ANS: Keywords Used in Exception Handling in Python: try: Encloses a block of code that might raise an exception. If no exception occurs, the except block is skipped. try: x = int(input("Enter a number: ")) except ValueError: print("Invalid input") except: Defines a block of code to be executed if a specific exception occurs. Can handle multiple exceptions using multiple except blocks. try: x = 10 / 0 except ZeroDivisionError: print("Division by zero error") finally: Defines a block of code to be executed regardless of whether an exception occurs or not. Often used for cleanup operations, like closing files or releasing resources. try: f = open("myfile.txt", "r") # ... finally: f.close() raise: Raises an exception explicitly. Can be used to create custom exceptions or re-raise exceptions. def divide(x, y): if y == 0: raise ZeroDivisionError("Division by zero") return x / y Python Program to Handle Negative Input: class NegativeValueError(Exception): pass def get_positive_number(): while True: try: num = int(input("Enter a positive number: ")) if num < 0: raise NegativeValueError("Number cannot be negative") return num except ValueError: print("Invalid input. Please enter a number.") except NegativeValueError as e: print(e) # Example usage: positive_number = get_positive_number() print("You entered:", positive_number) Explanation: Custom Exception: We define a custom exception NegativeValueError to specifically handle negative input. get_positive_number Function: A while True loop is used to repeatedly prompt the user for input. The input is converted to an integer using int(). If the number is negative, a NegativeValueError is raised. If the input is invalid (not a number), a ValueError is raised. The try-except block handles both custom and built-in exceptions. If the input is valid and positive, the function returns the number. THANK YOU
- Machine Learning Assignment Unit-4 Sem-5 BCA
Unit : 4 Supervised Learning Subject : Machine Learning Std : BCA Sem-5 1. Define : Supervised Learning. Ans. Supervised learning is the types of machine learning in which machines are trained using well "labelled" training data, and on basis of that data, machines predict the output. The labelled data means some input data is already tagged with the correct output. In supervised learning, the training data provided to the machines work as the supervisor that teaches the machines to predict the output correctly. It applies the same concept as a student learns in the supervision of the teacher. Supervised learning is a process of providing input data as well as correct output data to the machine learning model. The aim of a supervised learning algorithm is to find a mapping function to map the input variable(x) with the output variable(y). How Supervised Learning Works? In supervised learning, models are trained using labelled dataset, where the model learns about each type of data. Once the training process is completed, the model is tested on the basis of test data (a subset of the training set), and then it predicts the output. The working of Supervised learning can be easily understood by the below example and diagram: Suppose we have a dataset of different types of shapes which includes square, rectangle, triangle, and Polygon. Now the first step is that we need to train the model for each shape. If the given shape has four sides, and all the sides are equal, then it will be labelled as a Square. If the given shape has three sides, then it will be labelled as a triangle. If the given shape has six equal sides then it will be labelled as hexagon. Types of supervised Machine learning Algorithms: 1. Regression : Regression algorithms are used if there is a relationship between the input variable and the output variable. It is used for the prediction of continuous variables, such as Weather forecasting, Market Trends, etc. 2. Classification : Classification algorithms are used when the output variable is categorical, which means there are two classes such as Yes-No, Male-Female, True-false, etc. Advantages of Supervised learning: With the help of supervised learning, the model can predict the output on the basis of prior experiences. In supervised learning, we can have an exact idea about the classes of objects. Supervised learning model helps us to solve various real-world problems such as fraud detection, spam filtering, etc. Disadvantages of supervised learning: Supervised learning models are not suitable for handling the complex tasks. Supervised learning cannot predict the correct output if the test data is different from the training dataset. Training required lots of computation times. In supervised learning, we need enough knowledge about the classes of object. 2. Explain types of Supervised Learning Algorithm. Ans. Supervised learning is typically divided into two main categories: regression and classification. In regression, the algorithm learns to predict a continuous output value, such as the price of a house or the temperature of a city. Supervised learning can be further classified into two categories: Regression : Regression is a supervised learning technique used to predict continuous numerical values based on input features. It aims to establish a functional relationship between independent variables and a dependent variable, such as predicting house prices based on features like size, bedrooms, and location. The goal is to minimize the difference between predicted and actual values using algorithms like Linear Regression, Decision Trees, or Neural Networks, ensuring the model captures underlying patterns in the data. Classification : Classification is a type of supervised learning that categorizes input data into predefined labels. It involves training a model on labeled examples to learn patterns between input features and output classes. In classification, the target variable is a categorical value. For example, classifying emails as spam or not. The model’s goal is to generalize this learning to make accurate predictions on new, unseen data. Algorithms like Decision Trees, Support Vector Machines, and Neural Networks are commonly used for classification tasks. Supervised Machine Learning Algorithm : Supervised learning can be further divided into several different types, each with its own unique characteristics and applications. Here are some of the most common types of supervised learning algorithms: Linear Regression: Linear regression is a type of regression algorithm that is used to predict a continuous output value. It is one of the simplest and most widely used algorithms in supervised learning. In linear regression, the algorithm tries to find a linear relationship between the input features and the output value. The output value is predicted based on the weighted sum of the input features. Logistic Regression: Logistic regression is a type of classification algorithm that is used to predict a binary output variable. It is commonly used in machine learning applications where the output variable is either true or false, such as in fraud detection or spam filtering. In logistic regression, the algorithm tries to find a linear relationship between the input features and the output variable. The output variable is then transformed using a logistic function to produce a probability value between 0 and 1. Decision Trees: Decision tree is a tree-like structure that is used to model decisions and their possible consequences. Each internal node in the tree represents a decision, while each leaf node represents a possible outcome. Decision trees can be used to model complex relationships between input features and output variables. A decision tree is a type of algorithm that is used for both classification and regression tasks. Decision Trees Regression: Decision Trees can be utilized for regression tasks by predicting the value linked with a leaf node. Decision Trees Classification: Random Forest is a machine learning algorithm that uses multiple decision trees to improve classification and prevent overfitting. Random Forests: Random forests are made up of multiple decision trees that work together to make predictions. Each tree in the forest is trained on a different subset of the input features and data. The final prediction is made by aggregating the predictions of all the trees in the forest. Random forests are an ensemble learning technique that is used for both classification and regression tasks. Random Forest Regression: It combines multiple decision trees to reduce overfitting and improve prediction accuracy. Random Forest Classifier: Combines several decision trees to improve the accuracy of classification while minimizing overfitting. Support Vector Machine(SVM): The SVM algorithm creates a hyperplane to segregate n-dimensional space into classes and identify the correct category of new data points. The extreme cases that help create the hyperplane are called support vectors, hence the name Support Vector Machine. A Support Vector Machine is a type of algorithm that is used for both classification and regression tasks Support Vector Regression: It is a extension of Support Vector Machines (SVM) used for predicting continuous values. Support Vector Classifier: It aims to find the best hyperplane that maximizes the margin between data points of different classes. K-Nearest Neighbors (KNN): KNN works by finding k training examples closest to a given input and then predicts the class or value based on the majority class or average value of these neighbors. The performance of KNN can be influenced by the choice of k and the distance metric used to measure proximity. However, it is intuitive but can be sensitive to noisy data and requires careful selection of k for optimal results. A K-Nearest Neighbors (KNN) is a type of algorithm that is used for both classification and regression tasks. K-Nearest Neighbors Regression: It predicts continuous values by averaging the outputs of the k closest neighbors. K-Nearest Neighbors Classification: Data points are classified based on the majority class of their k closest neighbors. Gradient Boosting: Gradient Boosting combines weak learners, like decision trees, to create a strong model. It iteratively builds new models that correct errors made by previous ones. Each new model is trained to minimize residual errors, resulting in a powerful predictor capable of handling complex data relationships. A Gradient Boosting is a type of algorithm that is used for both classification and regression tasks. Gradient Boosting Regression: It builds an ensemble of weak learners to improve prediction accuracy through iterative training. Gradient Boosting Classification: Creates a group of classifiers to continually enhance the accuracy of predictions through iterations 3. Explain advantages and disadvantages of Supervised Learning. Ans. Advantages of Supervised Learning : The power of supervised learning lies in its ability to accurately predict patterns and make data-driven decisions across a variety of applications. Here are some advantages listed below: Labeled training data benefits supervised learning by enabling models to accurately learn patterns and relationships between inputs and outputs. Supervised learning models can accurately predict and classify new data. Supervised learning has a wide range of applications, including classification, regression, and even more complex problems like image recognition and natural language processing. Well-established evaluation metrics, including accuracy, precision, recall, and F1-score, facilitate the assessment of supervised learning model performance. Disadvantages of Supervised Learning : Although supervised learning methods have benefits, their limitations require careful consideration during problem formulation, data collection, model selection, and evaluation. Here are some disadvantages listed below: Overfitting: Models can overfit training data, which leads to poor performance on new, unseen data due to the capture of noise. Feature Engineering: Extracting relevant features from raw data is crucial for model performance, but this process can be time-consuming and may require domain expertise. Bias in Models: Training data biases can lead to unfair predictions. Supervised learning heavily depends on labeled training data, which can be costly, time-consuming, and may require domain expertise. 4. Discuss types of dataset in detail. Ans. These input data used to build the model are usually divided into multiple data sets. In particular, three data sets are commonly used in different stages of the creation of the model: training, validation, and test sets. Training data set : A training data set is a data set of examples used during the learning process and is used to fit the parameters (e.g., weights) of, for example, a classifier. For classification tasks, a supervised learning algorithm looks at the training data set to determine, or learn, the optimal combinations of variables that will generate a good predictive model. The goal is to produce a trained (fitted) model that generalizes well to new, unknown data. The fitted model is evaluated using “new” examples from the held-out datasets (validation and test datasets) to estimate the model’s accuracy in classifying new data. To reduce the risk of issues such as over-fitting, the examples in the validation and test datasets should not be used to train the model. Most approaches that search through training data for empirical relationships tend to overfit the data, meaning that they can identify and exploit apparent relationships in the training data that do not hold in general. Validation data set : A validation data set is a data-set of examples used to tune the hyperparameters (i.e. the architecture) of a classifier. It is sometimes also called the development set or the "dev set". An example of a hyperparameter for artificial neural networks includes the number of hidden units in each layer. It, as well as the testing set (as mentioned below), should follow the same probability distribution as the training data set. In order to avoid overfitting, when any classification parameter needs to be adjusted, it is necessary to have a validation data set in addition to the training and test datasets. For example, if the most suitable classifier for the problem is sought, the training data set is used to train the different candidate classifiers, the validation data set is used to compare their performances and decide which one to take and, finally, the test data set is used to obtain the performance characteristics such as accuracy, sensitivity, specificity, F-measure, and so on. The validation data set functions as a hybrid: it is training data used for testing, but neither as part of the low-level training nor as part of the final testing. Test data set : A test data set is a data set that is independent of the training data set, but that follows the same probability distribution as the training data set. If a model fit to the training data set also fits the test data set well, minimal overfitting has taken place (see figure below). A better fitting of the training data set as opposed to the test data set usually points to over-fitting. A test set is therefore a set of examples used only to assess the performance (i.e. generalization) of a fully specified classifier. To do this, the final model is used to predict classifications of examples in the test set. Those predictions are compared to the examples' true classifications to assess the model's accuracy. In a scenario where both validation and test datasets are used, the test data set is typically used to assess the final model that is selected during the validation process. In the case where the original data set is partitioned into two subsets (training and test datasets), the test data set might assess the model only once (e.g., in the holdout method). Note that some sources advise against such a method. However, when using a method such as cross-validation, two partitions can be sufficient and effective since results are averaged after repeated rounds of model training and testing to help reduce bias and variability. 5. Explain Classification in Detail. Ans. Classification is a supervised machine learning method where the model tries to predict the correct label of a given input data. In classification, the model is fully trained using the training data, and then it is evaluated on test data before being used to perform prediction on new unseen data. For instance, an algorithm can learn to predict whether a given email is spam or ham (no spam), as illustrated below. Before diving into the classification concept, we will first understand the difference between the two types of learners in classification: lazy and eager learners. Then we will clarify the misconception between classification and regression. Lazy Learners Vs. Eager Learners : There are two types of learners in machine learning classification: lazy and eager learners. Eager learners are machine learning algorithms that first build a model from the training dataset before making any prediction on future datasets. They spend more time during the training process because of their eagerness to have a better generalization during the training from learning the weights, but they require less time to make predictions. Most machine learning algorithms are eager learners, and below are some examples: Logistic Regression. Support Vector Machine. Decision Trees. Artificial Neural Networks. Lazy learners or instance-based learners, on the other hand, do not create any model immediately from the training data, and this is where the lazy aspect comes from. They just memorize the training data, and each time there is a need to make a prediction, they search for the nearest neighbor from the whole training data, which makes them very slow during prediction. Some examples of this kind are: K-Nearest Neighbor. Case-based reasoning. However, some algorithms, such as BallTrees and KDTrees, can be used to improve the prediction latency. Machine Learning Classification Vs. Regression : There are four main categories of Machine Learning algorithms: supervised, unsupervised, semi-supervised, and reinforcement learning. Even though classification and regression are both from the category of supervised learning, they are not the same. The prediction task is a classification when the target variable is discrete. An application is the identification of the underlying sentiment of a piece of text. The prediction task is a regression when the target variable is continuous. An example can be the prediction of the salary of a person given their education degree, previous work experience, geographical location, and level of seniority. Examples of Machine Learning Classification in Real Life : Healthcare : Training a machine learning model on historical patient data can help healthcare specialists accurately analyze their diagnoses: During the COVID-19 pandemic, machine learning models were implemented to efficiently predict whether a person had COVID-19 or not. Researchers can use machine learning models to predict new diseases that are more likely to emerge in the future. Education : Education is one of the domains dealing with the most textual, video, and audio data. This unstructured information can be analyzed with the help of Natural Language technologies to perform different tasks such as: The classification of documents per category. Automatic identification of the underlying language of students' documents during their application. Analysis of students’ feedback sentiments about a Professor. Transportation : Transportation is the key component of many countries' economic development. As a result, industries are using machine and deep learning models: To predict which geographical location will have a rise in traffic volume. Predict potential issues that may occur in specific locations due to weather conditions. Sustainable agriculture : Agriculture is one of the most valuable pillars of human survival. Introducing sustainability can help improve farmers' productivity at a different level without damaging the environment: By using classification models to predict which type of land is suitable for a given type of seed. Predict the weather to help them take proper preventive measures. Different Types of Classification Tasks in Machine Learning : There are four main classification tasks in Machine learning: binary, multi-class, multi-label, and imbalanced classifications. Binary Classification : In a binary classification task, the goal is to classify the input data into two mutually exclusive categories. The training data in such a situation is labeled in a binary format: true and false; positive and negative; O and 1; spam and not spam, etc. depending on the problem being tackled. For instance, we might want to detect whether a given image is a truck or a boat. Logistic Regression and Support Vector Machines algorithms are natively designed for binary classifications. However, other algorithms such as K-Nearest Neighbors and Decision Trees can also be used for binary classification. Multi-Class Classification : The multi-class classification, on the other hand, has at least two mutually exclusive class labels, where the goal is to predict to which class a given input example belongs to. In the following case, the model correctly classified the image to be a plane. Most of the binary classification algorithms can be also used for multi-class classification. These algorithms include but are not limited to: Random Forest, Naive Bayes, K-Nearest Neighbors, Gradient Boosting, SVM, Logistic Regression. One-versus-one: this strategy trains as many classifiers as there are pairs of labels. If we have a 3-class classification, we will have three pairs of labels, thus three classifiers. One-versus-rest: at this stage, we start by considering each label as an independent label and consider the rest combined as only one label. With 3-classes, we will have three classifiers. Multi-Label Classification : In multi-label classification tasks, we try to predict 0 or more classes for each input example. In this case, there is no mutual exclusion because the input example can have more than one label. Such a scenario can be observed in different domains, such as auto-tagging in Natural Language Processing, where a given text can contain multiple topics. Similarly to computer vision, an image can contain multiple objects, as illustrated below: the model predicted that the image contains: a plane, a boat, a truck, and a dog. It is not possible to use multi-class or binary classification models to perform multi-label classification. However, most algorithms used for those standard classification tasks have their specialized versions for multi-label classification. Imbalanced Classification : For the imbalanced classification, the number of examples is unevenly distributed in each class, meaning that we can have more of one class than the others in the training data. Let’s consider the following 3-class classification scenario where the training data contains: 60% of trucks, 25% of planes, and 15% of boats. The imbalanced classification problem could occur in the following scenario: Fraudulent transaction detections in financial industries Rare disease diagnosis Customer churn analysis 6. Explain Regression in detail. Ans. Machine Learning Regression is a technique for investigating the relationship between independent variables or features and a dependent variable or outcome. It’s used as a method for predictive modelling in machine learning, in which an algorithm is used to predict continuous outcomes. Solving regression problems is one of the most common applications for machine learning models, especially in supervised machine learning. Algorithms are trained to understand the relationship between independent variables and an outcome or dependent variable. The model can then be leveraged to predict the outcome of new and unseen input data, or to fill a gap in missing data. What are the types of regression? There are a range of different approaches used in machine learning to perform regression. Different popular algorithms are used to achieve machine learning regression. The different techniques may include different numbers of independent variables or process different types of data. Distinct types of machine learning regression models may also assume a different relationship between the independent and dependent variables. For example, linear regression techniques assume that the relationship is linear, so wouldn’t be effective with datasets with nonlinear relationships. Some of the most common regression techniques in machine learning can be grouped into the following types of regression analysis: Simple Linear Regression Multiple linear regression Logistic regression Simple Linear Regression : Simple Linear regression is a linear regression technique which plots a straight line within data points to minimise error between the line and the data points. It is one of the most simple and basic types of machine learning regression. The relationship between the independent and dependent variables is assumed to be linear in this case. This approach is simple because it is used to explore the relationship between the dependent variable and one independent variable. Outliers may be a common occurrence in simple linear regression because of the straight line of best fit. Multiple Linear regression : Multiple linear regression is a technique used when more than one independent variable is used. Polynomial regression is an example of a multiple linear regression technique. It is a type of multiple linear regression, used when there is more than one independent variable. It achieves a better fit in the comparison to simple linear regression when multiple independent variables are involved. The result when plotted on two dimensions would be a curved line fitted to the data points. Logistic regression : Logistic regression is used when the dependent variable can have one of two values, such as true or false, or success or failure. Logistic regression models can be used to predict the probability of a dependent variable occurring. Generally, the output values must be binary. A sigmoid curve can be used to map the relationship between the dependent variable and independent variables. 7. Explain Decision tree in brief. Ans. A decision tree is a non-parametric supervised learning algorithm, which is utilized for both classification and regression tasks. It has a hierarchical, tree structure, which consists of a root node, branches, internal nodes and leaf nodes. As you can see from the diagram above, a decision tree starts with a root node, which does not have any incoming branches. The outgoing branches from the root node then feed into the internal nodes, also known as decision nodes. Based on the available features, both node types conduct evaluations to form homogenous subsets, which are denoted by leaf nodes, or terminal nodes. The leaf nodes represent all the possible outcomes within the dataset. As an example, let’s imagine that you were trying to assess whether or not you should go surf, you may use the following decision rules to make a choice: This type of flowchart structure also creates an easy to digest representation of decision-making, allowing different groups across an organization to better understand why a decision was made. Decision tree learning employs a divide and conquer strategy by conducting a greedy search to identify the optimal split points within a tree. This process of splitting is then repeated in a top-down, recursive manner until all, or the majority of records have been classified under specific class labels. Whether or not all data points are classified as homogenous sets is largely dependent on the complexity of the decision tree. Smaller trees are more easily able to attain pure leaf nodes—i.e. data points in a single class. However, as a tree grows in size, it becomes increasingly difficult to maintain this purity, and it usually results in too little data falling within a given subtree. When this occurs, it is known as data fragmentation, and it can often lead to overfitting. As a result, decision trees have preference for small trees, which is consistent with the principle of parsimony in Occam’s Razor; that is, “entities should not be multiplied beyond necessity.” Said differently, decision trees should add complexity only if necessary, as the simplest explanation is often the best. To reduce complexity and prevent overfitting, pruning is usually employed; this is a process, which removes branches that split on features with low importance. The model’s fit can then be evaluated through the process of cross-validation. Another way that decision trees can maintain their accuracy is by forming an ensemble via a random forest algorithm; this classifier predicts more accurate results, particularly when the individual trees are uncorrelated with each other. 8. How does the Decision Tree algorithm Work ? Explain. Ans. In a decision tree, for predicting the class of the given dataset, the algorithm starts from the root node of the tree. This algorithm compares the values of root attribute with the record (real dataset) attribute and, based on the comparison, follows the branch and jumps to the next node. For the next node, the algorithm again compares the attribute value with the other sub-nodes and move further. It continues the process until it reaches the leaf node of the tree. The complete process can be better understood using the below algorithm: Step-1: Begin the tree with the root node, says S, which contains the complete dataset. Step-2: Find the best attribute in the dataset using Attribute Selection Measure (ASM). Step-3: Divide the S into subsets that contains possible values for the best attributes. Step-4: Generate the decision tree node, which contains the best attribute. Step-5: Recursively make new decision trees using the subsets of the dataset created in step -3. Continue this process until a stage is reached where you cannot further classify the nodes and called the final node as a leaf node. Attribute Selection Measures : While implementing a Decision tree, the main issue arises that how to select the best attribute for the root node and for sub-nodes. So, to solve such problems there is a technique which is called as Attribute selection measure or ASM. By this measurement, we can easily select the best attribute for the nodes of the tree. There are two popular techniques for ASM, which are: Information Gain Gini Index 1. Information Gain: Information gain is the measurement of changes in entropy after the segmentation of a dataset based on an attribute. It calculates how much information a feature provides us about a class. According to the value of information gain, we split the node and build the decision tree. A decision tree algorithm always tries to maximize the value of information gain, and a node/attribute having the highest information gain is split first. It can be calculated using the below formula: ➡️ Information Gain= Entropy(S)- [(Weighted Avg) *Entropy(each feature) 2. Gini Index: Gini index is a measure of impurity or purity used while creating a decision tree in the CART(Classification and Regression Tree) algorithm. An attribute with the low Gini index should be preferred as compared to the high Gini index. It only creates binary splits, and the CART algorithm uses the Gini index to create binary splits. Gini index can be calculated using the below formula: ➡️ Gini Index= 1- ∑jPj2 9. Explain advantages and disadvantages of Decision Tree. Ans. Advantages of the Decision Tree : It is simple to understand as it follows the same process which a human follow while making any decision in real-life. It can be very useful for solving decision-related problems. It helps to think about all the possible outcomes for a problem. There is less requirement of data cleaning compared to other algorithms. Disadvantages of the Decision Tree : The decision tree contains lots of layers, which makes it complex. It may have an overfitting issue, which can be resolved using the Random Forest algorithm. For more class labels, the computational complexity of the decision tree may increase.
- E-Commerce & SEO Technology Lab Manual BCA Sem-5
Subject: E-Commerce & SEO Technology Lab Manual BCA Sem-5 EXPERIMENT: 1 Aim: SEO Tasks :On page SEO and one time tasks On Page SEO Elements: Keyword Research, Title Tags, Meta tags, ALT tags, Header Tags (H1,H2), URL Structure, Internal Linking, Description: It shows the on Page SEO elements. ➡️ Steps: 1. Identify Target Keywords: Target keywords—i.e., relevant search queries—are crucial to on-page optimization. After all, the goal is to rank for relevant keywords and become more visible in search results. Perform keyword research to find what words and phrases people use to find pages like yours. Those data points include: Intent: The type of search intent or motivation behind each search Volume: Keyword search volume, the average number of monthly searches KD%: Keyword difficulty, a measure of how hard it will be to rank in the top 10 unpaid Google results 2. Optimize the Title Tag : The title tag is the page title that appears in the SERP. It should tell Google what your page is about. And entice users to click through. The title tag is one of the most important elements for on-page optimization. So make sure to include the page’s primary keyword (the main search term you want to rank for). Ideally, at the start. Tip: SEMrush's On Page SEO Checker checks your title tag for target keywords and keyword stuffing. Also, aim for a title tag length of 50 to 60 characters (including spaces). 3. Write a Meta Description That Boosts Clicks : The meta description is the page description that appears in the SERP. The meta description isn’t a direct ranking factor. It’s part of this on-page optimization checklist because it’s key to standing out on the SERP and attracting more clicks. Use it to explain what the user will get from your page and why it’s worth visiting. And make sure it includes your primary keyword. Note: Google may generate its own title tags and meta descriptions for your pages. Optimizing them can reduce the risk of this happening. We recommend sticking to a maximum of 120 characters (including spaces) for your meta descriptions. This reduces the risk of Google truncating them in desktop and mobile SERPs. Tip: SEMrush's On Page SEO Checker will check your meta description for target keywords and keyword stuffing. It will also flag if Google is rewriting your description in the search results. 4. Write Your Headline in an H1 Tag : Every page should have one H1 tag that contains the on-page title (or headline). It’s one of the simplest yet important tasks in this on-page SEO checklist. The H1 differs from a title tag because the H1 appears on your page. Not the SERP. The H1 tag should be similar to the title tag. As it’s also there to tell Google and users what the page is about. However, there’s rarely a character limit here. Just focus on creating an H1 that makes sense on your page and encourages visitors to stay. And include your primary keyword, at least. Tip: SEMrush's On Page SEO Checker checks your H1 tag for target keywords and keyword stuffing. 5. Check the URL Slug: The URL slug should be concise, clear, and descriptive. Here are some tips to keep in mind: Consider using your page’s primary keyword as the URL slug Separate words using a hyphen (“-”) Avoid mentioning years that might change (e.g., “best-headphones-2023”) If you change your URL slug, make sure to redirect the old version Check out our dedicated guide for more advice on creating SEO-friendly URLs. 6. Improve Navigation with Internal Links: Internal links are links between pages on your site. They help Google and users to find their way around. For example, Soak&Sleep has internal links to its “single duvets” and “single mattresses” categories in its “single bedding” page description. Notice how these internal links are attached to descriptive anchor text—not generic text like “Click here.” This helps Google (and users) understand what the linked page is about. Tip: Working on informational pages? Consider adding external links to your on-page optimization checklist as well. Linking out to high-quality resources indicates that you’ve done your research and have readers’ best interests in mind. Post Practical Questions: 1. Which of the following is NOT an on-page SEO task? ➡️ E (A) Keyword research (B) Title tags (C) Meta tags (D) ALT tags (E) Off-page SEO 2. Which of the following is the most important on-page SEO task? ➡️ B (A) Keyword research (B) Title tags (C) Meta tags (D) ALT tags (E) Header tags EXPERIMENT : 2 Aim: SEO Tasks : On page SEO and one time tasks On Page SEO Elements: Relevant keywords in inbound link, Content, Keyword density, Site Maps, Robots.txt, usability. ➡️ Steps: 1. Content: The content of a site must contain keywords chosen for a particular web page. These could be targeted keywords or long tail keywords or synonyms. Just make sure the keyword density is not too high, which means use them only when they make sense to the human reader. Explanation: It is often a best practice to keep your content more than 500 or 1000 words on the website as search engines love longer content. But that does not mean that you have to turn your business website into a blog with fillers everywhere. Keep your content length as long as possible but also at the same time take care that the readers get exactly what information they need without having to scroll through a long essay. If you see this research about content length affecting SERPs, you will find that the threshold is higher. But we are sure Google knows the difference between a blog and a business website while ranking them on this particular signal. This is what Google has to say about avoiding thin content, just to make things clearer. As far as, keyword density is concerned ther is no exact number to define it but all you need to know is in your average two to four paragraph content on a webpage, use keywords whenever they are relevant to the human reader. To know more about keyword density we recommend you watch this video from Google engineer Matt Cutts who talks about ideal keyword density. You can always use latent semantic indexing keywords that search engines also use to analyze the relevancy of your content to your target keywords. Read more about latent semantic indexing keywords. 2. Site Maps: Every site must have a sitemap. However, even if sites don't have one, they get indexed by search engines. The presence of  a sitemap makes it a tad easier to find and index pages, for the search engines. Explanation: A sitemap helps tell the search engines two important things: the location of all the internal links and the priority of different pages in a website. The former improves indexing of all internal pages hence paving way to search engine visibility to internal pages while the latter helps understand the information architecture. A sitemap location can also be specified in robots.txt file, which is usually the first file a search engine crawler looks for while crawling a site. Learn more about XML Sitemaps. 3. Robots.txt : Robots.txt is a file which, if present, on your website is the first file to be crawled by search engines. This contains information about pages that should not be indexed. It generally consists of information for search engines to guide them to crawl and index the site efficiently, including the sitemap location. Explanation: The presence of robots.txt does not directly affect your website's SEO. If you do have a robots.txt, make sure that no page that you want to be indexed, is blocked. If you have crawling issues reported on Google Search Console, make sure you double check your robots.txt file. Also, to increase the crawl rate of search engine bots, you can avoid unnecessary pages from being indexed by specifying them on your site's robots.txt file. Learn more from the Beginners Guide for Robots.txt. 4. Usability: Usability is a ranking factor for search engines and is controlled by on page elements. Explanation: Apart from the answers to the above questions there are more factors that affect the usability of a site. How a certain search engine user engages with the link that is returned in search is taken into consideration. For instance, image that you are a searcher and you click on a link and immediately click the back button. Your  engagement with that site is poor. This may be due to poor user-experience and such engagement metrics may cause lowering of search ranking. 5. Keyword Density: Keyword density is the proportion of times a term or phrase occurs on a web page. Search engines may mistake the keyword frequency for term stuffing when the keyword frequency is significantly over the optimal level. Consequently, we must ensure that the keyword density for any significant or secondary search keywords is not excessive. For example, if a term occurs five times in a 200-word piece, the density is 2.5 percent. Although there is no perfect keyword density, 3–4% is recommended practice for SEO. 6. Inbound Links : Inbound links, also known as backlinks, occur when another website links back to your site. Google views inbound links as an indicator that your site has high-quality content, making these links one of the most important elements in search engine optimization (SEO). In the early days of SEO, inbound links were merely a numbers game; the sites with the most links ranked the highest in the search results. This eventually led to people using spammy link building techniques to put their websites ahead of the competition, forcing Google to rethink how their algorithms responded to inbound links. Post Practical Questions: 1. What is On page SEO? ➡️ On-page SEO (sometimes called on-site SEO) is the process of optimizing parts of your webpages so they rank higher on search engines and get more search engine traffic. This includes updating on-page content, title tags, internal links, and more. Search engines like Google look at keywords and other on-page SEO cues to check whether a page matches a user’s search intent. And if the search engine decides the page will be useful to the user, it will display it higher in search results. 2.Which of the following is NOT an on-page SEO element? ➡️ (A) Relevant keywords in inbound links (B) Content (C) Keyword density (D) Site Maps (E) Robots.txt EXPERIMENT : 3 Aim: SEO Tasks : Off page SEO and Perpetual tasks: Profile Creation , Social Sharing ,Social Book-marking , Block Posting ,Image Sharing , Forum Comment. Description: It contains the off page SEO tasks ➡️ Steps: 1. Profile Creation: The process of creating a profile in SEO, or search engine optimization, typically involves several steps. These steps include conducting keyword research, optimizing website content, building backlinks, and monitoring and analyzing website traffic. First, keyword research is conducted to identify the most relevant and high-traffic keywords for a website. This can be done using tools like Google AdWords Keyword Planner or SEMrush. These tools allow you to enter a website or keyword and see the search volume, competition, and related keywords for that term. Once the keywords have been identified, the next step is to optimize the website content for those keywords. This involves incorporating the keywords in the title tags, meta descriptions, header tags, and throughout the website content. Building backlinks is another important step in the profile creation process. Backlinks are links from other websites to your website. The more backlinks a website has, the higher it will rank in search engine results. Backlinks can be built through a variety of methods, including guest blogging, social media, and outreach. Finally, monitoring and analyzing website traffic is important to track the effectiveness of the SEO campaign. This can be done using tools like Google Analytics or SEMrush. These tools allow you to track website traffic, bounce rate, and conversions. By following these steps, you can create a strong SEO profile for your website and improve your search engine rankings. 2. Social Book-Marking : Social bookmarking is a method of saving and organizing web pages or other digital content that you want to keep track of, and then sharing those bookmarks with others. In terms of SEO, social bookmarking can be beneficial because it can help to increase the visibility and exposure of your website or content. When you submit a webpage or blog post to a social bookmarking site, other users may see it and decide to share it with their own followers, which can lead to more backlinks and more traffic to your site. Additionally, many social bookmarking sites use tagging or categorization systems, which can help to optimize your content for specific keywords. 3. Social Sharing : Definition: Social sharing describes when social media users broadcast web content on a social network to their connections, groups, or specific individuals. One of the primary aims of corporate social media marketing strategies is to generate brand awareness by leveraging their existing audience to share content. Social sharing and brand : Beyond product recommendations and sales or promotions, social sharing is also a critical place to define a brand. Consumers don't only visit a company's website to understand who they are and what they offer — they also go to their Facebook Page or Twitter feed. Social media gives businesses a chance to define what they stand for, what they are trying to achieve, and how it helps the community. Social media is much more interactive than a website. Seeing how a company engages with its customers is more substantive than simply making a website claim. Most importantly, when users share a company's posts or content, it validates them in the eyes of consumers. Social proof is invaluable for a business' reputation and has the tendency to increase exponentially when a foundation is established. 4. Block Posting: Simply put, content blocks are building blocks used to integrate different forms of content to a webpage or blog post, adding functionality and visual appeal. Content blocks can be anything from plain text and images to call-to-action buttons and event count-down clocks. If you’ve ever worked on or run your own website, you’re probably already familiar with popular block-based blog builders like Elementor, Gutenberg, or Visual Composer. With these editors, each piece of content on the page–from video embeds to introductory paragraphs–is made of a different block that you can re-arrange within your post by dragging and dropping. Page builders offer several default blocks like a paragraph, heading, button, list, etc. but you can also add new blocks by installing block plugins. 5. Image Sharing : Image sharing can be beneficial for SEO in several ways. First, it can help to increase the number of backlinks to your website, which can help to improve your search engine rankings. Additionally, images can help to break up text on a webpage and make it more visually appealing, which can help to keep visitors on your site for longer and reduce bounce rates. To share images for SEO, you can use a variety of methods. One of the most popular is to use social media platforms like Instagram, Pinterest, and Flickr to share your images and include a link back to your website. Additionally, you can use image sharing websites like Imager and imgbb to share your images and include a link back to your website. It's also important to optimize your images for SEO by including relevant keywords in the file name, alt tags, and captions. This will help search engines to understand the context of your images and display them in relevant search results. It's also a good idea to make sure that your images are compressed, so they load quickly on your website, which can help to improve the user experience and reduce bounce rates. 6. Forum Comment: Forum posting refers to generating quality inbound links by participating in online discussion forums. It allows you to post new posts and reply to old ones to drive traffic to your site. There are a number of forum websites which offer a platform for online discussion, i.e. message board, discussion groups, discussion forums and bulletin boards are some of the popular types of forum websites. You need to sign up on these websites only then you can submit topics for discussion. Post Practical Questions: Q. 1 Explain Social Book Marking? ➡️ Social bookmarking is a method of saving and organizing web pages or other digital content that you want to keep track of, and then sharing those bookmarks with others. In terms of SEO, social bookmarking can be beneficial because it can help to increase the visibility and exposure of your website or content. When you submit a webpage or blog post to a social bookmarking site, other users may see it and decide to share it with their own followers, which can lead to more backlinks and more traffic to your site. Additionally, many social bookmarking sites use tagging or categorization systems, which can help to optimize your content for specific keywords. EXPERIMENT: 4 Aim: SEO Tasks : Off page SEO and Perpetual tasks: Document Comment ,Question Answer Posting ,Blog Comment , Directory Submission , Article Bookmarking ,Content Sharing Steps: 1. Blog Comment: Blog commenting in an off-page SEO type isn’t as popular as it once was, but it’s still a terrific strategy to improve traffic and obtain more backlinks. Keep in mind that blogs are still a popular resource for those wanting to learn about what matters most in their field while looking for sites to comment on. When you write blog comments on high-authority websites, you improve the chances that they will accept a link back to your site. However, you must leave only useful blog comments or risk losing the trust of your followers. Guest blogging is another method for increasing traffic to your website. 2. Directory Submission: Another popular off-page SEO tactic that will be present in 2022 is blog directory submissions. You may acquire backlinks and enhance traffic to your website by submitting your blog to these directories. When submitting your blog to these directories, keep in mind that if they approve your blog for inclusion in their directory, you will need to supply some information about your blog for them to post. There are no actual disadvantages to submitting your blog to a directory. Remember that it may take some time for the moderator to approve your blog, so be patient! Submit your blog to directories to improve blog traffic and receive backlinks. 3. Questions & Answers Posting: Query and answer sites, like article directories, require you to submit your question or response. The primary distinction is that you now have the option of including a link at the conclusion of your submission! Many individuals who use these websites are looking for answers about specific topics, which helps you to increase traffic to your website by contributing information. You have to select a question or response pertaining to your expertise and offer further information. If you can think of anything to ask, question and answer sites are wonderful for growing your website traffic! 4. Document Comment: Off-page SEO is all about getting your material out there on the internet and into people’s lives. You may share a superb document with others who do not have access to the original. 5. Article Bookmarking: Another prevalent off-page SEO type or technique that will stay popular in 2022 is article submission. You might want to think about employing article submission platforms to increase the visibility of your company and website. Several article submission websites are accessible for usage; however, not all of them regularly accept fresh articles. You should publish your content to a variety of directories, including high-quality directories that will undoubtedly be prominent in 2022. When submitting an article to these sites, make sure to add at least one backlink to your website. This will give your company more exposure and enhance the probability that people will visit it! 6. Content Sharing: SEO content is online content designed to rank in search engines (like Google). Also, content written for SEO is typically optimized around a specific keyword. And when it comes to search engine optimization, make no mistake: Content is KEY. In fact, HubSpot reports that businesses that regularly publish blog posts get 350% more traffic than those that don’t publish content on a regular basis. Post Practical Questions: 1. Explain article bookmarking? ➡️ There are many SEO benefits to social bookmarking. Search engine algorithms scour through the bookmarked websites and make a link to be indexed. This helps websites earn credibility points from search engines and get better rankings. EXPERIMENT: 5 Aim: Study about Free SEO Tools: Keyword Suggestion Tool Keyword List Generator Keyword List Cleaner Robots. Text Tools Meta Tag Generator Server Header Checker Link Suggestion Tool Spider Test Tool Keyword Density Analyzer Page Comparison Tool Ad Group Generator Keyword Wrapper Typo Generator Description: Study about free SEO tools Steps: WORKING
- Android Assignment-2 BCA Sem-5
Subject: Android Assignment-2 Unit: 2 Android Application Basics BCA Semester: 5 1. Write a note on android life cycle. Ans. Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android Activity is the subclass of ContextThemeWrapper class. An activity is the single screen in android. It is like window or frame of Java. By the help of activity, you can place all your UI components or widgets in a single screen. The 7 lifecycle method of Activity describes how activity will behave at different states. Android Activity Lifecycle methods File: activity_main.xml Android Activity Lifecycle Example File: MainActivity.java package example.javatpoint.com.activitylifecycle; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d("lifecycle","onCreate invoked"); } @Override protected void onStart() { super.onStart(); Log.d("lifecycle","onStart invoked"); } @Override protected void onResume() { super.onResume(); Log.d("lifecycle","onResume invoked"); } @Override protected void onPause() { super.onPause(); Log.d("lifecycle","onPause invoked"); } @Override protected void onStop() { super.onStop(); Log.d("lifecycle","onStop invoked"); } @Override protected void onRestart() { super.onRestart(); Log.d("lifecycle","onRestart invoked"); } @Override protected void onDestroy() { super.onDestroy(); Log.d("lifecycle","onDestroy invoked"); } } Output: You will not see any output on the emulator or device. You need to open logcat. 2. Explain Manifest File in detail. Ans. Every project in Android includes a Manifest XML file, which is AndroidManifest.xml, located in the root directory of its project hierarchy. The manifest file is an important part of our app because it defines the structure and metadata of our application, its components, and its requirements. This file includes nodes for each of the Activities, Services, Content Providers, and Broadcast Receivers that make the application, and using Intent Filters and Permissions determines how they coordinate with each other and other applications. The manifest file also specifies the application metadata, which includes its icon, version number, themes, etc., and additional top-level nodes can specify any required permissions, and unit tests, and define hardware, screen, or platform requirements. The manifest comprises a root manifest tag with a package attribute set to the project’s package. It should also include an xmls:android attribute that will supply several system attributes used within the file. We use the versionCode attribute is used to define the current application version in the form of an integer that increments itself with the iteration of the version due to update. Also, the versionName attribute is used to specify a public version that will be displayed to the users. We can also specify whether our app should install on an SD card of the internal memory using the install Location attribute. A typical manifest file looks as: XML Code: A manifest file includes the nodes that define the application components, security settings, test classes, and requirements that make up the application. Some of the manifest sub-node tags that are mainly used are: 1. manifest: The main component of the AndroidManifest.xml file is known as manifest. Additionally, the packaging field describes the activity class’s package name. It must contain an element with the xmlns:android and package attribute specified. XML CODE: 2. uses-sdk : It is used to define a minimum and maximum SDK version by means of an API Level integer that must be available on a device so that our application functions properly, and the target SDK for which it has been designed using a combination of minSdkVersion, maxSdkVersion, and targetSdkVersion attributes, respectively. It is contained within the element. XML Code: 3. uses-permission : It outlines a system permission that must be granted by the user for the app to function properly and is contained within the element. When an application is installed (on Android 5.1 and lower devices or Android 6.0 and higher), the user must grant the application permissions. XML Code: 4. application : A manifest can contain only one application node. It uses attributes to specify the metadata for your application (including its title, icon, and theme). During development, we should include a debuggable attribute set to true to enable debugging, then be sure to disable it for your release builds. The application node also acts as a container for the Activity, Service, Content Provider, and Broadcast Receiver nodes that specify the application components. The name of our custom application class can be specified using the android:name attribute. XML Code: 5. uses-library : It defines a shared library against which the application must be linked. This element instructs the system to add the library’s code to the package’s class loader. It is contained within the element. XML Code: 6. activity : The Activity sub-element of an application refers to an activity that needs to be specified in the AndroidManifest.xml file. It has various characteristics, like label, name, theme, launchMode, and others. In the manifest file, all elements must be represented by . Any activity that is not declared there won’t run and won’t be visible to the system. It is contained within the element. XML Code: 7. intent-filter : It is the sub-element of activity that specifies the type of intent to which the activity, service, or broadcast receiver can send a response. It allows the component to receive intents of a certain type while filtering out those that are not useful for the component. The intent filter must contain at least one element. XML Code: 8. action : It adds an action for the intent-filter. It is contained within the element. XML Code: 9. category : It adds a category name to an intent-filter. It is contained within the element. XML Code: 10. uses-configuration : The uses-configuration components are used to specify the combination of input mechanisms that are supported by our application. It is useful for games that require particular input controls. XML Code: 11. uses-features : It is used to specify which hardware features your application requires. This will prevent our application from being installed on a device that does not include a required piece of hardware such as NFC hardware, as follows: XML Code: 12. permission : It is used to create permissions to restrict access to shared application components. We can also use the existing platform permissions for this purpose or define your own permissions in the manifest. XML Code: 3. Explain any 10 different types of resources file andriod. Ans. 1. Bool : A Boolean value defined in XML. file location:res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. resource reference: In Java: R.bool.bool_name In XML: @[package:]bool/bool_name Syntax: [true | false] 2. Color : A color value defined in XML. The color is specified using an RGB value and alpha channel. You can use a color resource any place that accepts a hexadecimal color value. You can also use a color resource when a drawable resource is expected in XML, such as android:drawable="@color/green". file location: res/values/colors.xml The filename is arbitrary. The element's name is used as the resource ID. resource reference: In Java: R.color.color_name In XML: @[package:]color/color_name syntax: hex_color 3. Dimension : A dimension value defined in XML. A dimension is specified with a number followed by a unit of measure, such as 10px, 2in, or 5sp. The following units of measure are supported by Android: dp : Density-independent pixels: an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi (dots per inch) screen, on which 1 dp is roughly equal to 1 px. When running on a higher density screen, the number of pixels used to draw 1 dp is scaled up by a factor appropriate for the screen's dpi. sp: Scale-independent Pixels - This is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user's preference. pt: Points: 1/72 of an inch based on the physical size of the screen, assuming a 72 dpi density screen. px: Pixels: corresponds to actual pixels on the screen. We don't recommend using this unit, because the actual representation can vary across devices. Different devices can have a different number of pixels per inch and might have more or fewer total pixels available on the screen. mm: Millimeters: based on the physical size of the screen. in: Inches: based on the physical size of the screen. file location: res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. resource reference: In Java: R.dimen.dimension_name In XML: @[package:]dimen/dimension_name syntax: dimension 4. ID : A unique resource ID defined in XML. Using the name you provide in the element, the Android developer tools create a unique integer in your project's R.java class, which you can use as an identifier for an application resources, such as a View in your UI layout, or a unique integer for use in your application code, such as an ID for a dialog or a result code. file location:res/values/filename.xml The filename is arbitrary. resource reference: In Java: R.id.name In XML: @[package:]id/name syntax: 5. Integer : An integer defined in XML. file location: res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. resource reference: In Java: R.integer.integer_name In XML: @[package:]integer/integer_name syntax: integer 6. Integer array : An array of integers defined in XML. file location: res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. compiled resource datatype: Resource pointer to an array of integers. resource reference: In Java: R.array.integer_array_name In XML: @[package:]array/integer_array_name syntax: integer 7. Typed array : A TypedArray defined in XML. You can use this to create an array of other resources, such as drawables. The array isn't required to be homogeneous, so you can create an array of mixed resource types, but be aware of what and where the data types are in the array so that you can properly obtain each item with the TypedArray class's get...() methods. file location: res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. compiled resource datatype: Resource pointer to a TypedArray. resource reference: In Java: R.array.array_name In XML: @[package:]array/array_name syntax: resource 8. Layout resource: A layout resource defines the architecture for the UI in an Activity or a component of a UI. file location: res/layout/filename.xml The filename is used as the resource ID. compiled resource datatype: Resource pointer to a View (or subclass) resource reference: In Java: R.layout.filename In XML: @[package:]layout/filename syntax: 9. String: A single string that can be referenced from the application or from other resource files (such as an XML layout). file location: res/values/filename.xml The filename is arbitrary. The element's name is used as the resource ID. compiled resource datatype: Resource pointer to a String. resource reference: In Java: R.string.string_name In XML: @string/string_name syntax: text_string 10. Style resource : A style resource defines the format and look for a UI. A style can be applied to an individual View (from within a layout file) or to an entire Activity or application (from within the manifest file). file location: res/values/filename.xml The filename is arbitrary. The element's name will be used as the resource ID. resource reference: In XML: @[package:]style/style_name syntax: 4. Explain Menu and Scroll View. Ans. Android Menus: In android, Menu is an important part of the UI component which is used to provide some common functionality around the application. With the help of menu, users can experience a smooth and consistent experience throughout the application. In order to use menu, we should define it in a separate XML file and use that file in our application based on our requirements. Also, we can use menu APIs to represent user actions and other options in our android application activities. How to define Menu in XML File? Android Studio provides a standard XML format for the type of menus to define menu items. We can simply define the menu and all its items in XML menu resource instead of building the menu in the code and also load menu resource as menu object in the activity or fragment used in our android application. Here, we should create a new folder menu inside of our project directory (res/menu) to define the menu and also add a new XML file to build the menu with the following elements. Below is the example of defining a menu in the XML file (menu_example.xml). Way to create menu directory and menu resource file: To create the menu directory just right-click on res folder and navigate to res->New->Android Resource Directory. Give resource directory name as menu and resource type also menu. one directory will be created under res folder. To create xml resource file simply right-click on menu folder and navigate to New->Menu Resource File. Give name of file as menu_example. One menu_example.xml file will be created under menu folder. It is the root element that helps in defining Menu in XML file and it also holds multiple elements. It is used to create a single item in the menu. It also contains nested element in order to create a submenu. It is optional and invisible for elements to categorize the menu items so they can share properties like active state, and visibility. activity_main.xml : If we want to add a submenu in menu item, then we need to add a element as the child of an . Below is the example of defining a submenu in a menu item. XML Code: Android Different Types of Menus : In android, we have three types of Menus available to define a set of options and actions in our android applications. The Menus in android applications are the following: Android Options Menu Android Context Menu Android Popup Menu Android Options Menu is a primary collection of menu items in an android application and is useful for actions that have a global impact on the searching application. Android Context Menu is a floating menu that only appears when the user clicks for a long time on an element and is useful for elements that affect the selected content or context frame. Android Popup Menu displays a list of items in a vertical list which presents the view that invoked the menu and is useful to provide an overflow of actions related to specific content. Android Scroll View : ScrollView is a view group that we can use to create vertically scrollable views. There is only one direct child in a scroll view. Because a ScrollView can only scroll vertically, you'll need to use a Horizontal Scroll View to create a horizontally scrollable view. The ScrollView tag is used to create a Scroll View in an android application. For example: In the above example, Scroll View has one child, which is a TextView widget. Here the android:orientation of the Text View widget is set to vertical. It defines whether to display child views in a row or column. Attributes of Scroll View : Following are some of the important attributes of a Scroll View: android:id: A Unique id to identify any widget android:layout_width: It defines the width of the layout android:layout_height: It sets the layout's height android:layout_marginStart: The amount of space needed at the start of the widget android:layout_marginEnd: It represents the amount of space needed on the End of the widget android:inputType: This allows you to define the input method's behaviour android:text: Specifies the default text displayed in the field app:layout_constraintTop_toTopOf: Align the desired view's top with the top of another Horizontal Scroll View : Horizontal Scroll View is used to add horizontal scroll ability in an android application. We can use the Horizontal Scroll View tag to create the same. 5. Working with permissions android explain? Ans. Restricted data, such as system state and users' contact information Restricted actions, such as connecting to a paired device and recording audio Workflow for using permissions : If your app offers functionality that might require access to restricted data or restricted actions, determine whether you can get the information or perform the actions without needing to declare permissions. You can fulfill many use cases in your app, such as taking photos, pausing media playback, and displaying relevant ads, without needing to declare any permissions. Types of permissions : Android categorizes permissions into different types, including install-time permissions, runtime permissions, and special permissions. Each permission's type indicates the scope of restricted data that your app can access, and the scope of restricted actions that your app can perform, when the system grants your app that permission. The protection level for each permission is based on its type and is shown on the permissions API reference page. Install-time permissions: Install-time permissions give your app limited access to restricted data or let your app perform restricted actions that minimally affect the system or other apps. When you declare install-time permissions in your app, an app store presents an install-time permission notice to the user when they view an app's details page, as shown in figure 2. The system automatically grants your app the permissions when the user installs your app. Normal permissions: These permissions allow access to data and actions that extend beyond your app's sandbox but present very little risk to the user's privacy and the operation of other apps. The system assigns the normal protection level to normal permissions. Signature permissions: The system grants a signature permission to an app only when the app is signed by the same certificate as the app or the OS that defines the permission. Runtime permissions: Runtime permissions, also known as dangerous permissions, give your app additional access to restricted data or let your app perform restricted actions that more substantially affect the system and other apps. Therefore, you need to request runtime permissions in your app before you can access the restricted data or perform restricted actions. Don't assume that these permissions have been previously granted—check them and, if needed, request them before each access. Special permissions: Special permissions correspond to particular app operations. Only the platform and OEMs can define special permissions. Additionally, the platform and OEMs usually define special permissions when they want to protect access to particularly powerful actions, such as drawing over other apps. Permission groups: Permissions can belong to permission groups. Permission groups consist of a set of logically related permissions. For example, permissions to send and receive SMS messages might belong to the same group, as they both relate to the application's interaction with SMS.
- Android Lab Manual Sem-5 BCA
Subject - Android Semester - 5 BCA Table Of Content (Click to View) Experiment: 1 Experiment: 2 Experiment: 3 Experiment: 4 Experiment: 5 Experiment: 6 Experiment: 7 Experiment: 8 Experiment: 9 Experiment: 10 Experiment- 1 Aim: Create a Program of Activity Lifecycle? Description: It shows the actual features of Android activity lifecycle goes through six major lifecycle stages or callbacks. These are: onCreate() , onStart() , onResume() , onPause() , onStop() , and onDestroy() . Steps: 1. onCreate(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Bundle containing previous frozen state setContentView(R.layout.activity_main); // The content view pointing to the id of layout // in the file activity_main.xml Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } } 2. onStart(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Bundle containing previous frozen state setContentView(R.layout.activity_main); // The content view pointing to the id of layout // in the file activity_main.xml Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onStart() { // It will show a message on the screen // then onStart is invoked Toast toast = Toast.makeText(getApplicationContext(), "onStart Called", Toast.LENGTH_LONG).show(); } } 3. onResume(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.example.share.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onResume() { // It will show a message on the screen // then onResume is invoked Toast toast = Toast.makeText(getApplicationContext(), "onResume Called", Toast.LENGTH_LONG).show(); } } 4. onPause(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onPause() { // It will show a message on the screen // then onPause is invoked Toast toast = Toast.makeText(getApplicationContext(), "onPause Called", Toast.LENGTH_LONG).show(); } } 5. onStop(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onStop() { // It will show a message on the screen // then onStop is invoked Toast toast = Toast.makeText(getApplicationContext(), "onStop Called", Toast.LENGTH_LONG).show(); } } 6. onDestroy(): import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // Bundle containing previous frozen state super.onCreate(savedInstanceState); // The content view pointing to the id of layout // in the file activity_main.xml setContentView(R.layout.activity_main); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onDestroy() { // It will show a message on the screen // then onDestroy is invoked Toast toast = Toast.makeText(getApplicationContext(), "onDestroy Called", Toast.LENGTH_LONG).show(); } } Post Practical Questions: 1. Android system initiates its program within an Activity starting with a call on ? ➡️ C a) offCreate() callback b) onDrop() callback c) onCreate() callback 2.Which callback is called when the activity becomes visible to the user? ➡️ B a) onCreate() b) onStart() c) onResume() 3. Which callback is called when the activity is no longer visible? ➡️ B a) onRestart() b) onStop() c) onPause() 4. Which callback is called when the activity restarts after stopping it? ➡️ A a) onRestart() b) onPause() c) onStart() EXPERIMENT: 2 Aim: Create a program in Context and show different color and size of text? Description: In the below program you will see that we have created a textView dynamically and passed context. This context is used to get the information about the environment. Steps: This example demonstrates how do I change font color of TextView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml Step 3 − Add the following code to src/MainActivity.java import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);TextView textView1 = findViewById(R.id.textView1); textView1.setTextColor(Color.BLUE);TextView textView2 = findViewById(R.id.textView2); textView2.setTextColor(Color.parseColor("#006400"));}} Step 4 − Add the following code to androidManifest.xml This example demonstrates how do I change the font size of TextView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);}} Step 4 − Add the following code to androidManifest.xml Post Practical Questions: 1. What is a context in android? ➡️ Context is used to create new components or objects like views and it is used to start activity and services. 2. The property that is used for formatting font is ➡️ B a)Color b) typeface c) ImageView 3. What is the default font size in Android? ➡️ B a) 12sp b) 14sp c) 16sp EXPERIMENT : 3 Aim: Create option menu and shows in notify in toast? Description: Android Option Menus are the primary menus of android. They can be used for settings, search, delete item etc. Here, you will inflating the menu by calling the inflate() method of Menu Inflater class. To perform event handling on menu items, you need to override onOptionsItemSelected() method of Activity class. Steps: Android Option Menu Example: File: activity_main.xml File: context_main.xml File: menu_main.xml File: MainActivity.java package example.javatpoint.com.optionmenu; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id){ case R.id.item1: Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG).show(); return true; case R.id.item2: Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG).show(); return true; case R.id.item3: Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LONG).show(); return true; default: return super.onOptionsItemSelected(item); } } } Post Practical Questions: Q. 1 Explain Toast class and option menu? ➡️ Toast Class: Toast class is used to show notification for a particular interval of time. After sometime it disappears. It doesn't block the user interaction. Toast Option Menu: Android Toast can be used to display information for the short period of time. A toast contains message to be displayed quickly and disappears after sometime. The android. widget. EXPERIMENT: 4 Aim: Create a program of animation with XML file? Description: An animation defined in XML that modifies properties of the target object, such as background color or alpha value, over a set amount of time. Steps: Here is the modified code of res/layout/activity_main.xml. Here abc indicates about logo of tutorials point Here is the code of res/anim/myanimation.xml. Here is the code of res/anim/clockwise.xml. Here is the code of res/anim/fade.xml. Here is the modified code of res/values/string.xml. My Application Here is the default code of AndroidManifest.xml. Post Practical Questions: 1. Explain XML Layout Attributes ? ➡️ Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout. EXPERIMENT: 5 Aim: Create a program with button and chronometer? Description: The Chronometer is a subclass of TextView. This class helps us to add a timer in our app. You can give Timer start time in the elapsedRealTime() timebase and it start counting from that. If we don’t give base time then it will use the time at which time we call start() method. By default a chronometer displays the current timer value in the form of MM:SS or H:MM:SS. Steps: Step by Step Implementation: Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Step 2: Working with the activity_main.xml file Navigate to app > res > layout > activity_main.xml and add the code below. Comments are added in the code to get to know in detail. Step 3: Working with the MainActivity file Navigate to app > java > your app’s package name > Main Activity file and add the below code to it. Comments are added in the code to get to know in detail. package com.gtappdevelopers.kotlingfgproject; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Chronometer; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // on below line we are creating variables. private Chronometer chronometer; private Button chronometerBtn; boolean isRunning = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // on below line we are initializing our variables. chronometer = findViewById(R.id.idCMmeter); chronometerBtn = findViewById(R.id.idBtnChronometer); // on below line we are adding click listener for our button chronometerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are checking if // chronometer is running or not. if (isRunning) { // in this condition chronometer is running // on below line we are updating text for button chronometerBtn.setText("Start Chronometer"); // on below line we are updating boolean variable isRunning = false; // on below line we are stopping chronometer chronometer.stop(); } else { // in this condition chronometer is running // on below line we are updating text for button chronometerBtn.setText("Stop Chronometer"); // on below line we are updating boolean variable isRunning = true; // on below line we are starting chronometer chronometer.start(); } } }); } } Post Practical Questions: 1. Write it down the Android ChronoMeter Attributes ? ➡️ This attribute specifies a time format string for Chronometer. By default, Chronometer displays time in the format of "MM:SS" when the time is less than 1 hour, or "H:MM:SS" if the time is more than 1 hour. EXPERIMENT: 6 Aim: Create a program of Grid View and shows multiple subjects names? Description: Android Grid View shows items in two-dimensional scrolling grid (rows & columns) and the grid items are not necessarily predetermined but they automatically inserted to the layout using a List Adapter. Steps: XML Attributes of GridView: android:numColumns: This attribute of GridView will be used to decide the number of columns that are to be displayed in Grid. android:horizontalSpacing: This attribute is used to define the spacing between two columns of GridView. android:verticalSpacing: This attribute is used to specify the spacing between two rows of GridView. Step By Step Implementation: Step:1 Create a new Project in Android Studio: To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android. Step:2 Add the Required Dependencies : Add the Google Repository to your settings.Gradle File. dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { // add the following google() mavenCentral() } } Step:3 Working with the XML files : Create an XML Layout for each item of GridView : Create an XML file for each grid item to be displayed in GridView. Click on the app > res > layout > Right-Click > Layout Resource file and then name the file as card_item. Below is the code for the card_item.xml file. Step:5 Create a Model Class for Storing Data : Now click on app > java > apps package name > Right-Click on it. Then Click on New > Java Class. Name your Java/Kotlin Class file as CourseModel. Below is the code for the java > apps package name > Right-Click on it. Then Click on New > Java Class. Name your Java Class file as CourseGVAdapter. Below is the code for the CourseGVAdapter file. import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.ArrayList; public class CourseGVAdapter extends ArrayAdapter { public CourseGVAdapter(@NonNull Context context, ArrayList courseModelArrayList) { super(context, 0, courseModelArrayList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View listitemView = convertView; if (listitemView == null) { // Layout Inflater inflates each item to be displayed in GridView. listitemView = LayoutInflater.from(getContext()).inflate(R.layout.card_item, parent, false); } CourseModel courseModel = getItem(position); TextView courseTV = listitemView.findViewById(R.id.idTVCourse); ImageView courseIV = listitemView.findViewById(R.id.idIVcourse); courseTV.setText(courseModel.getCourse_name()); courseIV.setImageResource(courseModel.getImgid()); return listitemView; } } Step: 7 Working with the MainActivity File: Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. import android.os.Bundle; import android.widget.GridView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { GridView coursesGV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); coursesGV = findViewById(R.id.idGVcourses); ArrayList courseModelArrayList = new ArrayList(); courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("JAVA", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("C++", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("Python", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("Javascript", R.drawable.ic_gfglogo)); courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo)); CourseGVAdapter adapter = new CourseGVAdapter(this, courseModelArrayList); coursesGV.setAdapter(adapter); } } Post Practical Questions: 1. Explain Custom ArrayAdapter in GridView? ➡️ Android already provides the implementation for an ArrayAdapter, which can be used with just a single line demonstrated below. They are used when Whenever we have a list of single items we can use ArrayAdapter. For instance, a list of phone contacts, countries, or names. The problem with or limitation of this method is we cannot use complex layouts eg. Imagine we were building an app like Netflix or prime where each element is made up of many elements eg an ImageView, TextView, etc. Such complex views are not possible with the simple implementation of the ArrayAdapter for this we need to create our custom Adapter by extending the ArrayAdapter class. The following code shows the structure of the Custom ArrayAdapter. EXPERIMENT: 7 Aim: Create Simple Login Page with 3 attempt? Description: Define a button with login text and set its onClick Property. After that define the function mentioned in the onClick property in the java file. In the java file, inside the method of onClick get the username and passwords text using getText() and toString() method and match it with the text using equals() function. Steps: Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { Button b1,b2; EditText ed1,ed2; TextView tx1; int counter = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button)findViewById(R.id.button); ed1 = (EditText)findViewById(R.id.editText); ed2 = (EditText)findViewById(R.id.editText2); b2 = (Button)findViewById(R.id.button2); tx1 = (TextView)findViewById(R.id.textView3); tx1.setVisibility(View.GONE); b1.setOnClickListener(new View.OnClickListener() { @Overridepublic void onClick(View v) { if(ed1.getText().toString().equals("admin") && ed2.getText().toString().equals("admin")) { Toast.makeText(getApplicationContext(), "Redirecting...",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(), "Wrong Credentials",Toast.LENGTH_SHORT).show(); tx1.setVisibility(View.VISIBLE); tx1.setBackgroundColor(Color.RED); counter--; tx1.setText(Integer.toString(counter)); if (counter == 0) { b1.setEnabled(false); } } } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. Following is the content of the res/values/string.xml. My Application Following is the content of AndroidManifest.xml file. Post Practical Questions: 1. How many orientations does android support? ➡️ D a) 1 b) 2 c) 3 d) 4 2. How to get current location in android? ➡️ D a) Using with GPRS b) SQLite c) Network servers d) Location Provider EXPERIMENT: 8 Aim: Create Simple Database Program with fatch data from SQLite Database with (name, phone, email, street, place)? Steps: Following is the content of the modified MainActivity.java. package com.example.sairamkrishna.myapplication; import android.content.Context; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity { public final static String EXTRA_MESSAGE = "MESSAGE"; private ListView obj; DBHelper mydb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydb = new DBHelper(this); ArrayList array_list = mydb.getAllCotacts(); ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list); obj = (ListView)findViewById(R.id.listView1); obj.setAdapter(arrayAdapter); obj.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView arg0, View arg1, int arg2,long arg3) { // TODO Auto-generated method stub int id_To_Search = arg2 + 1; Bundle dataBundle = new Bundle(); dataBundle.putInt("id", id_To_Search); Intent intent = new Intent(getApplicationContext(),DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ super.onOptionsItemSelected(item); switch(item.getItemId()) { case R.id.item1:Bundle dataBundle = new Bundle(); dataBundle.putInt("id", 0); Intent intent = new Intent(getApplicationContext(),DisplayContact.class); intent.putExtras(dataBundle); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } public boolean onKeyDown(int keycode, KeyEvent event) { if (keycode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); } return super.onKeyDown(keycode, event); } } Following is the modified content of display contact activity DisplayContact.java package com.example.sairamkrishna.myapplication; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class DisplayContact extends Activity { int from_Where_I_Am_Coming = 0; private DBHelper mydb ; TextView name ; TextView phone; TextView email; TextView street; TextView place; int id_To_Update = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_contact); name = (TextView) findViewById(R.id.editTextName); phone = (TextView) findViewById(R.id.editTextPhone); email = (TextView) findViewById(R.id.editTextStreet); street = (TextView) findViewById(R.id.editTextEmail); place = (TextView) findViewById(R.id.editTextCity); mydb = new DBHelper(this); Bundle extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ //means this is the view part not the add contact part. Cursor rs = mydb.getData(Value); id_To_Update = Value; rs.moveToFirst(); String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME)); String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE)); String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL)); String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET)); String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY)); if (!rs.isClosed()) { rs.close(); } Button b = (Button)findViewById(R.id.button1); b.setVisibility(View.INVISIBLE); name.setText((CharSequence)nam); name.setFocusable(false); name.setClickable(false); phone.setText((CharSequence)phon); phone.setFocusable(false); phone.setClickable(false); email.setText((CharSequence)emai); email.setFocusable(false); email.setClickable(false); street.setText((CharSequence)stree); street.setFocusable(false); street.setClickable(false); place.setText((CharSequence)plac); place.setFocusable(false); place.setClickable(false); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. Bundle extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ getMenuInflater().inflate(R.menu.display_contact, menu); } else{ getMenuInflater().inflate(R.menu.menu_main menu); } } return true; } public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch(item.getItemId()) { case R.id.Edit_Contact: Button b = (Button)findViewById(R.id.button1); b.setVisibility(View.VISIBLE); name.setEnabled(true); name.setFocusableInTouchMode(true); name.setClickable(true); phone.setEnabled(true); phone.setFocusableInTouchMode(true); phone.setClickable(true); email.setEnabled(true); email.setFocusableInTouchMode(true); email.setClickable(true); street.setEnabled(true); street.setFocusableInTouchMode(true); street.setClickable(true); place.setEnabled(true); place.setFocusableInTouchMode(true); place.setClickable(true); return true; case R.id.Delete_Contact: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.deleteContact) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mydb.deleteContact(id_To_Update); Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog d = builder.create(); d.setTitle("Are you sure"); d.show(); return true; default: return super.onOptionsItemSelected(item); } } public void run(View view) { Bundle extras = getIntent().getExtras(); if(extras !=null) { int Value = extras.getInt("id"); if(Value>0){ if(mydb.updateContact(id_To_Update,name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){ Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } else{ Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show(); } } else{ if(mydb.insertContact(name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){ Toast.makeText(getApplicationContext(), "done",Toast.LENGTH_SHORT).show();} else{ Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show(); } Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } } } } Following is the content of Database class DBHelper.java package com.example.sairamkrishna.myapplication; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "MyDBName.db"; public static final String CONTACTS_TABLE_NAME = "contacts"; public static final String CONTACTS_COLUMN_ID = "id"; public static final String CONTACTS_COLUMN_NAME = "name"; public static final String CONTACTS_COLUMN_EMAIL = "email"; public static final String CONTACTS_COLUMN_STREET = "street"; public static final String CONTACTS_COLUMN_CITY = "place"; public static final String CONTACTS_COLUMN_PHONE = "phone"; private HashMap hp; public DBHelper(Context context) { super(context, DATABASE_NAME , null, 1); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("create table contacts " + "(id integer primary key, name text,phone text,email text, street text,place text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS contacts"); onCreate(db); } public boolean insertContact (String name, String phone, String email, String street,String place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("phone", phone); contentValues.put("email", email); contentValues.put("street", street); contentValues.put("place", place); db.insert("contacts", null, contentValues); return true; } public Cursor getData(int id) { SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null ); return res; } public int numberOfRows(){ SQLiteDatabase db = this.getReadableDatabase(); int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME); return numRows; } public boolean updateContact (Integer id, String name, String phone, String email, String street,String place) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("phone", phone); contentValues.put("email", email); contentValues.put("street", street); contentValues.put("place", place); db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } ); return true; } public Integer deleteContact (Integer id) { SQLiteDatabase db = this.getWritableDatabase(); return db.delete("contacts", "id = ? ", new String[] { Integer.toString(id) }); } public ArrayList getAllCotacts() { ArrayList array_list = new ArrayList(); //hp = new HashMap(); SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from contacts", null ); res.moveToFirst(); while(res.isAfterLast() == false){ array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME))); res.moveToNext(); } return array_list; } } Following is the content of the res/layout/activity_main.xml Following is the content of the res/layout/activity_display_contact.xml Following is the content of the res/value/string.xml Address Book Settings Hello world! Add New Edit Contact Delete Contact DisplayContact Name Phone Email Street City/State/Zip Save Contact Are you sure, you want to delete it. Yes No Following is the content of the res/menu/main_menu.xml Following is the content of the res/menu/display_contact.xml This is the defualt AndroidManifest.xml of this project Post Practical Questions: 1. In SQLite, files are ____ directly to disk. ➡️ C a) Read b) Written c) Both a and b d) None of the above 2. SQLite is written in ➡️ B a) C b) ANSI-C c) JAVA d) None of these 3. SQLite is a ____ database resource. ➡️ D a) Interface b) Non-interface c) Portable d) Non-portable EXPERIMENT: 9 Aim: Create an Implicit and Explicit intents Program? Description: Types of Android Intents There are two types of intents in android: implicit and explicit. 1) Implicit Intent: Implicit Intent doesn't specifiy the component. In such case, intent provides information of available components provided by the system that is to be invoked. Intent intent=new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://www.javatpoint.com")); startActivity(intent); 2) Explicit Intent: Explicit Intent specifies the component. In such case, intent provides the external class to be invoked. Intent i = new Intent(getApplicationContext(), ActivityTwo.class); startActivity(i); Steps: Implicit Intent: Creating an Android App to Open a Webpage Using Implicit Intent Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Create an XML file and Java File. Please refer to the pre-requisites to learn more about this step. Step 2: Working with the XML Files Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. Syntax: android:id="@+id/id_name" XML Code: Step 3: Working with the MainActivity File Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. Syntax: ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent); JAVA Code: import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { EditText editText; Button button; super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.btn); editText = (EditText) findViewById(R.id.editText); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url=editText.getText().toString(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); } }); } } Explicit Intent How to create an Android App to move to the next activity using Explicit Intent(with Example) Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Step 2: Working with the activity_main.xml File Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. Syntax: android:id="@+id/id_name" XML Code: Step 3: Working with the MainActivity File Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button, TextView) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. Syntax: ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent); Intent i = new Intent(getApplicationContext(), ); startActivity(i); JAVA Code: import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void newsScreen(View view) { Intent i = new Intent(getApplicationContext(), MainActivity2.class); startActivity(i); } } Step 4: Working with the activity_main2.xml File Now we have to create a second activity as a destination activity. The steps to create the second activity are File > new > Activity > Empty Activity. Next, go to the activity_main2.xml file, which represents the UI of the project. Below is the code for the activity_main2.xml file. Comments are added inside the code to understand the code in more detail. XML Code: Step 5: Working with the MainActivity2 File Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button, TextView) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID. Syntax: ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent); Intent i = new Intent(getApplicationContext(), ); startActivity(i); JAVA Code: import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity2 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); } public void homeScreen(View view) { Intent i = new Intent(getApplicationContext(), MainActivity.class); startActivity(i); } } Post Practical Questions: 1. If you want to navigate from one activity to another then android provides you which class ➡️ C a) startActivity b) Object c) Intent d) Adapter 2.The types of intents in android is\are distinguishes data classes or concepts. ➡️ D a) Explicit intents b) Implicit intents c) Start intents d) Option A and B are correct. 3.Suppose that there are two activities in an application named ActivityOne and ActivityTwo. You want to invoke ActivityTwo from ActivityOne. What code you will write? ➡️ A a) Intent intent=new Intent (this, ActivityTwo.class); startActivity(intent); b) startActivity(new Intent(this, ActivityTwo.class)); c) Option A and B are correct. d) None of the above. EXPERIMENT : 10 Aim: Make a Scientific Calculator Android App using Android Studio using multiple buttons? Steps: Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding new colors to the colors.xml file Navigate to the app > res > values > colors.xml file and add the below code to it for different colors. Comments are added in the code to get to know in more detail. XML Code: #0F9D58 #0F9D58 #0F9D58 #FF03DAC5 #FF018786 #FF000000 #FFFFFFFF #292D36 #272B33 #22252D #ffa500 Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML Code: Step 4: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin Code: import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // creating variables for our text view and button lateinit var tvsec: TextView lateinit var tvMain: TextView lateinit var bac: Button lateinit var bc: Button lateinit var bbrac1: Button lateinit var bbrac2: Button lateinit var bsin: Button lateinit var bcos: Button lateinit var btan: Button lateinit var blog: Button lateinit var bln: Button lateinit var bfact: Button lateinit var bsquare: Button lateinit var bsqrt: Button lateinit var binv: Button lateinit var b0: Button lateinit var b9: Button lateinit var b8: Button lateinit var b7: Button lateinit var b6: Button lateinit var b5: Button lateinit var b4: Button lateinit var b3: Button lateinit var b2: Button lateinit var b1: Button lateinit var bpi: Button lateinit var bmul: Button lateinit var bminus: Button lateinit var bplus: Button lateinit var bequal: Button lateinit var bdot: Button lateinit var bdiv: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // initializing all our variables. tvsec = findViewById(R.id.idTVSecondary) tvMain = findViewById(R.id.idTVprimary) bac = findViewById(R.id.bac) bc = findViewById(R.id.bc) bbrac1 = findViewById(R.id.bbrac1) bbrac2 = findViewById(R.id.bbrac2) bsin = findViewById(R.id.bsin) bcos = findViewById(R.id.bcos) btan = findViewById(R.id.btan) blog = findViewById(R.id.blog) bln = findViewById(R.id.bln) bfact = findViewById(R.id.bfact) bsquare = findViewById(R.id.bsquare) bsqrt = findViewById(R.id.bsqrt) binv = findViewById(R.id.binv) b0 = findViewById(R.id.b0) b9 = findViewById(R.id.b9) b8 = findViewById(R.id.b8) b7 = findViewById(R.id.b7) b6 = findViewById(R.id.b6) b5 = findViewById(R.id.b5) b4 = findViewById(R.id.b4) b3 = findViewById(R.id.b3) b2 = findViewById(R.id.b2) b1 = findViewById(R.id.b1) bpi = findViewById(R.id.bpi) bmul = findViewById(R.id.bmul) bminus = findViewById(R.id.bminus) bplus = findViewById(R.id.bplus) bequal = findViewById(R.id.bequal) bdot = findViewById(R.id.bdot) bdiv = findViewById(R.id.bdiv) // adding on click listener to our all buttons. b1.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "1") } b2.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "2") } b3.setOnClickListener { // on below line we are appending // the expression to our text view. tvMain.text = (tvMain.text.toString() + "3") } b4.setOnClickListener { tvMain.text = (tvMain.text.toString() + "4") } b5.setOnClickListener { tvMain.text = (tvMain.text.toString() + "5") } b6.setOnClickListener { tvMain.text = (tvMain.text.toString() + "6") } b7.setOnClickListener { tvMain.text = (tvMain.text.toString() + "7") } b8.setOnClickListener { tvMain.text = (tvMain.text.toString() + "8") } b9.setOnClickListener { tvMain.text = (tvMain.text.toString() + "9") } b0.setOnClickListener { tvMain.text = (tvMain.text.toString() + "0") } bdot.setOnClickListener { tvMain.text = (tvMain.text.toString() + ".") } bplus.setOnClickListener { tvMain.text = (tvMain.text.toString() + "+") } bdiv.setOnClickListener { tvMain.text = (tvMain.text.toString() + "/") } bbrac1.setOnClickListener { tvMain.text = (tvMain.text.toString() + "(") } bbrac2.setOnClickListener { tvMain.text = (tvMain.text.toString() + ")") } bpi.setOnClickListener { // on clicking on pi button we are adding // pi value as 3.142 to our current value. tvMain.text = (tvMain.text.toString() + "3.142") tvsec.text = (bpi.text.toString()) } bsin.setOnClickListener { tvMain.text = (tvMain.text.toString() + "sin") } bcos.setOnClickListener { tvMain.text = (tvMain.text.toString() + "cos") } btan.setOnClickListener { tvMain.text = (tvMain.text.toString() + "tan") } binv.setOnClickListener { tvMain.text = (tvMain.text.toString() + "^" + "(-1)") } bln.setOnClickListener { tvMain.text = (tvMain.text.toString() + "ln") } blog.setOnClickListener { tvMain.text = (tvMain.text.toString() + "log") } bminus.setOnClickListener { // on clicking on minus we are checking if // the user has already a minus operation on screen. // if minus operation is already present // then we will not do anything. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals("-")) { tvMain.text = (tvMain.text.toString() + "-") } } bmul.setOnClickListener { // if mul sign is not present in our // text view then only we are adding // the multiplication operator to it. val str: String = tvMain.text.toString() if (!str.get(index = str.length - 1).equals("*")) { tvMain.text = (tvMain.text.toString() + "*") } } bsqrt.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { val str: String = tvMain.text.toString() // on below line we are calculation // square root of the given number. val r = Math.sqrt(str.toDouble()) // on below line we are converting our double // to string and then setting it to text view. val result = r.toString() tvMain.setText(result) } } bequal.setOnClickListener { val str: String = tvMain.text.toString() // on below line we are calling an evaluate // method to calculate the value of expressions. val result: Double = evaluate(str) // on below line we are getting result // and setting it to text view. val r = result.toString() tvMain.setText(r) tvsec.text = str } bac.setOnClickListener { // on clicking on ac button we are clearing // our primary and secondary text view. tvMain.setText("") tvsec.setText("") } bc.setOnClickListener { // on clicking on c button we are clearing // the last character by checking the length. var str: String = tvMain.text.toString() if (!str.equals("")) { str = str.substring(0, str.length - 1) tvMain.text = str } } bsquare.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { // on below line we are getting the expression and then calculating the square of the number val d: Double = tvMain.getText().toString().toDouble() // on below line we are calculating the square. val square = d * d // after calculating the square we // are setting it to text view. tvMain.setText(square.toString()) // on below line we are setting // the d to secondary text view. tvsec.text = "$d²" } } bfact.setOnClickListener { if (tvMain.text.toString().isEmpty()) { // if the entered number is empty we are displaying an error message. Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show() } else { // on below line we are getting int value // and calculating the factorial value of the entered number. val value: Int = tvMain.text.toString().toInt() val fact: Int = factorial(value) tvMain.setText(fact.toString()) tvsec.text = "$value`!" } } } fun factorial(n: Int): Int { // this method is use to find factorial return if (n == 1 || n == 0) 1 else n * factorial(n - 1) } fun evaluate(str: String): Double { return object : Any() { // on below line we are creating variable // for tracking the position and char pos. var pos = -1 var ch = 0 // below method is for moving to next character. fun nextChar() { // on below line we are incrementing our position // and moving it to next position. ch = if (++pos < str.length) str[pos].toInt() else -1 } // this method is use to check the extra space // present int the expression and removing it. fun eat(charToEat: Int): Boolean { while (ch == ' '.toInt()) nextChar() // on below line we are checking the char pos // if both is equal then we are returning it to true. if (ch == charToEat) { nextChar() return true } return false } // below method is to parse our // expression and to get the ans // in this we are calling a parse // expression method to calculate the value. fun parse(): Double { nextChar() val x = parseExpression() if (pos < str.length) throw RuntimeException("Unexpected: " + ch.toChar()) return x } // in this method we will only perform addition and // subtraction operation on the expression. fun parseExpression(): Double { var x = parseTerm() while (true) { if (eat('+'.toInt())) x += parseTerm() // addition else if (eat('-'.toInt())) x -= parseTerm() // subtraction else return x } } // in below method we will perform // only multiplication and division operation. fun parseTerm(): Double { var x = parseFactor() while (true) { if (eat('*'.toInt())) x *= parseFactor() // multiplication else if (eat('/'.toInt())) x /= parseFactor() // division else return x } } // below method is use to parse the factor fun parseFactor(): Double { //on below line we are checking for addition // and subtraction and performing unary operations. if (eat('+'.toInt())) return parseFactor() // unary plus if (eat('-'.toInt())) return -parseFactor() // unary minus // creating a double variable for ans. var x: Double // on below line we are creating // a variable for position. val startPos = pos // on below line we are checking // for opening and closing parenthesis. if (eat('('.toInt())) { // parentheses x = parseExpression() eat(')'.toInt()) } else if (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) { // numbers while (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) nextChar() // on below line we are getting sub string from our string using start and pos. x = str.substring(startPos, pos).toDouble() } else if (ch >= 'a'.toInt() && ch <= 'z'.toInt()) { // on below function we are checking for the operator in our expression. while (ch >= 'a'.toInt() && ch <= 'z'.toInt()) nextChar() val func = str.substring(startPos, pos) // calling a method to parse our factor. x = parseFactor() // on below line we are checking for square root. x = if (func == "sqrt") Math.sqrt(x) // on below line we are checking for sin function // and calculating sin function using Math class. else if (func == "sin") Math.sin( Math.toRadians(x) // on below line we are calculating the cos value ) else if (func == "cos") Math.cos( Math.toRadians(x) // on below line we are calculating // the tan value of our expression. ) else if (func == "tan") Math.tan(Math.toRadians(x)) // on below line we are calculating // log value of the expression. else if (func == "log") Math.log10(x) // on below line we are calculating // ln value of expression. else if (func == "ln") Math.log(x) // f we get any error then // we simply return the exception. else throw RuntimeException( "Unknown function: $func" ) } else { // if the condition not satisfy then we are returning the exception throw RuntimeException("Unexpected: " + ch.toChar()) } // on below line we are calculating the power of the expression. if (eat('^'.toInt())) x = Math.pow(x, parseFactor()) // exponentiation return x } // at last calling a parse for our expression. }.parse() } } BEST OF LUCK
- Machine Learning Assign.-1 BCA sem-5
Subject: Machine Learning Assignment: 1 (BCA Sem-5) Unit: 1 Introduction to Machine Learning 1. Define machine learning and explain how it differs from traditional programming. Ans. Machine Learning is a branch of artificial intelligence that develops algorithms by learning the hidden patterns of the datasets used it to make predictions on new similar type data, without being explicitly programmed for each task. Traditional Machine Learning combines data with statistical tools to predict an output that can be used to make actionable insights. Machine learning is used in many different applications, from image and speech recognition to natural language processing, recommendation systems, fraud detection, portfolio optimization, automated task, and so on. Machine learning models are also used to power autonomous vehicles, drones, and robots, making them more intelligent and adaptable to changing environments. A typical machine learning tasks are to provide a recommendation. Recommender systems are a common application of machine learning, and they use historical data to provide personalized recommendations to users. In the case of Netflix, the system uses a combination of collaborative filtering and content-based filtering to recommend movies and TV shows to users based on their viewing history, ratings, and other factors such as genre preferences. 2. Describe the main type of Machine Learning: Supervised Learning, Unsupervised Learning and Reinforcement Learning. Include one-real world example for each type. Ans. Types of Machine Learning: Supervised Machine Learning Unsupervised Machine Learning Reinforcement Machine Learning 1. Supervised Machine Learning: Supervised learning is a type of machine learning in which the algorithm is trained on the labeled dataset. It learns to map input features to targets based on labeled training data. In supervised learning, the algorithm is provided with input features and corresponding output labels, and it learns to generalize from this data to make predictions on new, unseen data. There are two main types of supervised learning: Regression: Regression is a type of supervised learning where the algorithm learns to predict continuous values based on input features. The output labels in regression are continuous values, such as stock prices, and housing prices. The different regression algorithms in machine learning are: Linear Regression, Polynomial Regression, Ridge Regression, Decision Tree Regression, Random Forest Regression, Support Vector Regression, etc Classification: Classification is a type of supervised learning where the algorithm learns to assign input data to a specific category or class based on input features. The output labels in classification are discrete values. Classification algorithms can be binary, where the output is one of two possible classes, or multiclass, where the output can be one of several classes. The different Classification algorithms in machine learning are: Logistic Regression, Naive Bayes, Decision Tree, Support Vector Machine (SVM), K-Nearest Neighbors (KNN), etc. 2. Unsupervised Machine Learning: Unsupervised learning is a type of machine learning where the algorithm learns to recognize patterns in data without being explicitly trained using labeled examples. The goal of unsupervised learning is to discover the underlying structure or distribution in the data. There are two main types of unsupervised learning: Clustering: Clustering algorithms group similar data points together based on their characteristics. The goal is to identify groups, or clusters, of data points that are similar to each other, while being distinct from other groups. Some popular clustering algorithms include K-means, Hierarchical clustering, and DBSCAN. Dimensionality reduction: Dimensionality reduction algorithms reduce the number of input variables in a dataset while preserving as much of the original information as possible. This is useful for reducing the complexity of a dataset and making it easier to visualize and analyze. Some popular dimensionality reduction algorithms include Principal Component Analysis (PCA), t-SNE, and Autoencoders. 3. Reinforcement Machine Learning: Reinforcement learning is a type of machine learning where an agent learns to interact with an environment by performing actions and receiving rewards or penalties based on its actions. The goal of reinforcement learning is to learn a policy, which is a mapping from states to actions, that maximizes the expected cumulative reward over time. There are two main types of reinforcement learning: Model-based reinforcement learning: In model-based reinforcement learning, the agent learns a model of the environment, including the transition probabilities between states and the rewards associated with each state-action pair. The agent then uses this model to plan its actions in order to maximize its expected reward. Some popular model-based reinforcement learning algorithms include Value Iteration and Policy Iteration. Model-free reinforcement learning: In model-free reinforcement learning, the agent learns a policy directly from experience without explicitly building a model of the environment. The agent interacts with the environment and updates its policy based on the rewards it receives. Some popular model-free reinforcement learning algorithms include Q-Learning, SARSA, and Deep Reinforcement Learning. 3. Explain the steps involved in the machine learning modeling flow. Briefly describe each step. Ans. Machine learning life cycle involves seven major steps, which are given below: 1. Gathering Data: Data Gathering is the first step of the machine learning life cycle. The goal of this step is to identify and obtain all data-related problems. In this step, we need to identify the different data sources, as data can be collected from various sources such as files, database, internet, or mobile devices. It is one of the most important steps of the life cycle. The quantity and quality of the collected data will determine the efficiency of the output. The more will be the data, the more accurate will be the prediction. This step includes the below tasks: Identify various data sources Collect data Integrate the data obtained from different sources By performing the above task, we get a coherent set of data, also called as a dataset. It will be used in further steps. 2. Data preparation: After collecting the data, we need to prepare it for further steps. Data preparation is a step where we put our data into a suitable place and prepare it to use in our machine learning training. In this step, first, we put all data together, and then randomize the ordering of data. This step can be further divided into two processes: Data exploration: It is used to understand the nature of data that we have to work with. We need to understand the characteristics, format, and quality of data. A better understanding of data leads to an effective outcome. In this, we find Correlations, general trends, and outliers. Data pre-processing: Now the next step is preprocessing of data for its analysis. 3. Data Wrangling: Data wrangling is the process of cleaning and converting raw data into a useable format. It is the process of cleaning the data, selecting the variable to use, and transforming the data in a proper format to make it more suitable for analysis in the next step. It is one of the most important steps of the complete process. Cleaning of data is required to address the quality issues. It is not necessary that data we have collected is always of our use as some of the data may not be useful. In real-world applications, collected data may have various issues, including: Missing Values Duplicate data Invalid data Noise So, we use various filtering techniques to clean the data. It is mandatory to detect and remove the above issues because it can negatively affect the quality of the outcome. 4. Data Analysis: Now the cleaned and prepared data is passed on to the analysis step. This step involves: Selection of analytical techniques Building models Review the result The aim of this step is to build a machine learning model to analyze the data using various analytical techniques and review the outcome. It starts with the determination of the type of the problems, where we select the machine learning techniques such as Classification, Regression, Cluster analysis, Association, etc. then build the model using prepared data, and evaluate the model. 5. Train Model: Now the next step is to train the model, in this step we train our model to improve its performance for better outcome of the problem. We use datasets to train the model using various machine learning algorithms. Training a model is required so that it can understand the various patterns, rules, and, features. 6. Test Model: Once our machine learning model has been trained on a given dataset, then we test the model. In this step, we check for the accuracy of our model by providing a test dataset to it. Testing the model determines the percentage accuracy of the model as per the requirement of project or problem. 7. Deployment: The last step of machine learning life cycle is deployment, where we deploy the model in the real-world system. If the above-prepared model is producing an accurate result as per our requirement with acceptable speed, then we deploy the model in the real system. But before deploying the project, we will check whether it is improving its performance using available data or not. The deployment phase is similar to making the final report for a project. 4. Compare and contrast Supervised Learning and Unsupervised Learning. How do they differ in terms of data, training process, and typical use cases? Ans. 5. What is Reinforcement Learning? Provide an example scenario where reinforcement learning could be applied. Ans. Reinforcement learning is an area of Machine Learning. It is about taking suitable action to maximize reward in a particular situation. It is employed by various software and machines to find the best possible behavior or path it should take in a specific situation. Reinforcement learning differs from supervised learning in a way that in supervised learning the training data has the answer key with it so the model is trained with the correct answer itself whereas in reinforcement learning, there is no answer but the reinforcement agent decides what to do to perform the given task. In the absence of a training dataset, it is bound to learn from its experience. Reinforcement Learning (RL) is the science of decision making. It is about learning the optimal behavior in an environment to obtain maximum reward. In RL, the data is accumulated from machine learning systems that use a trial-and-error method. Data is not part of the input that we would find in supervised or unsupervised machine learning. Reinforcement learning uses algorithms that learn from outcomes and decide which action to take next. After each action, the algorithm receives feedback that helps it determine whether the choice it made was correct, neutral or incorrect. It is a good technique to use for automated systems that have to make a lot of small decisions without human guidance. Reinforcement learning is an autonomous, self-teaching system that essentially learns by trial and error. It performs actions with the aim of maximizing rewards, or in other words, it is learning by doing in order to achieve the best outcomes. Types of Reinforcement: There are two types of Reinforcement: Positive: Positive Reinforcement is defined as when an event, occurs due to a particular behavior, increases the strength and the frequency of the behavior. In other words, it has a positive effect on behavior. Negative: Negative Reinforcement is defined as strengthening of behavior because a negative condition is stopped or avoided. Example: The problem is as follows: We have an agent and a reward, with many hurdles in between. The agent is supposed to find the best possible path to reach the reward. The following problem explains the problem more easily. The above image shows the robot, diamond, and fire. The goal of the robot is to get the reward that is the diamond and avoid the hurdles that are fired. The robot learns by trying all the possible paths and then choosing the path which gives him the reward with the least hurdles. Each right step will give the robot a reward and each wrong step will subtract the reward of the robot. The total reward will be calculated when it reaches the final reward that is the diamond. Main points in Reinforcement learning – Input: The input should be an initial state from which the model will start Output: There are many possible outputs as there are a variety of solutions to a particular problem Training: The training is based upon the input, The model will return a state and the user will decide to reward or punish the model based on its output. The model keeps continues to learn. The best solution is decided based on the maximum reward. 6. List and briefly explain three challenges that machine learning faces. How might these challenges impact the accuracy and effectiveness of machine learning models? Ans. we will discuss seven major challenges faced by machine learning professionals. Let’s have a look. 1. Poor Quality of Data: Data plays a significant role in the machine learning process. One of the significant issues that machine learning professionals face is the absence of good quality data. Unclean and noisy data can make the whole process extremely exhausting. We don’t want our algorithm to make inaccurate or faulty predictions. Hence the quality of data is essential to enhance the output. Therefore, we need to ensure that the process of data preprocessing which includes removing outliers, filtering missing values, and removing unwanted features, is done with the utmost level of perfection. 2. Underfitting of Training Data: This process occurs when data is unable to establish an accurate relationship between input and output variables. It simply means trying to fit in undersized jeans. It signifies the data is too simple to establish a precise relationship. To overcome this issue: Maximize the training time Enhance the complexity of the model Add more features to the data Reduce regular parameters Increasing the training time of model 3. Machine Learning is a Complex Process: The machine learning industry is young and is continuously changing. Rapid hit and trial experiments are being carried on. The process is transforming, and hence there are high chances of error which makes the learning complex. It includes analyzing the data, removing data bias, training data, applying complex mathematical calculations, and a lot more. Hence it is a really complicated process which is another big challenge for Machine learning professionals. 4. Slow Implementation: This is one of the common issues faced by machine learning professionals. The machine learning models are highly efficient in providing accurate results, but it takes a tremendous amount of time. Slow programs, data overload, and excessive requirements usually take a lot of time to provide accurate results. Further, it requires constant monitoring and maintenance to deliver the best output.
- E-Commerce Technology & SEO Assignment BCA sem-5
UNIT : 1 Overview of E-Commerce 1. Definition E-commerce. Ans. E-commerce stands for electronic commerce. E-commerce is the activity of purchasing or selling products via the internet. E-commerce offers almost everything to buy, making it extremely competitive. Some notable examples of successful e-commerce businesses are Amazon, Flipkart, eBay, and Myntra. E-commerce utilizes technology like mobile commerce, electronic funds transfers, supply chain management, inventory management systems, internet marketing, online transaction processing, EDI(Electronic data interchange), and automated data collection mechanisms. 2. What are the functions and significance E-Commerce? Ans. E-Commerce Functions: These are the typical functions of an e-commerce system available both on back office and front office: Registration Basket Payment Product management Orders Management VAT and shipping costs Registration: In order to make a purchase, users must register with the site, providing all the information needed for shipping and billing. The data will be stored on a database and will be available from the back office. Basket: The basket is a tool that, like a shopping basket, allows users to select the products they want and then go to the checkout for payment. Managing the basket means: Summarizing user requests within the possibilities offered by the catalogue Checking the basket and possibly cancel/modify the items placed in it. Starting the payment process for the selected products Payment: The payment system is a mechanism that facilitates dialogue between the parties involved in financial transactions: the bank, the store and you with your credit card. After filling the order, the customer enters his/her credit card number that travels along a channel solely accessible to the bank. The bank checks the customer’s account and decides whether or not to authorise the payment. Product management: This is the main part of the e-commerce system and provides all the features required for product placement, order fulfilment, etc…,key to the management of online sales. In detail the features in the system are: Product code Category Subcategory Product name Description Image, zoom Sizes available Price ‘Pieces’ in stock The products can be searched by category and subcategory. Order management: The order is the card that summarizes all the delivery and order information to enable correct delivery. It includes: List of products purchased User information Details of place of delivery Delivery time information Payment information VAT and shipping costs: In addition to the cost of products purchased, the system manages the VAT(Value added tax) and the shipping charges. The e-commerce module is able to manage VAT rates in countries within and outside the EU. Shipping costs both fixed and variable based on the weight and volume of the shipment. Discounts: Discounts and promotions are managed for a single product or product category. This second phase of the site requires a detailed analysis of your current storage and order management systems with which it will be necessary to integrate. Significance and Scope of E-commerce: The scope of e-commerce encompasses a wide range of online transactions and activities, including Cross-border e-commerce: Cross-border e-commerce refers to the buying and selling of goods and services across national borders. With the rise of e-commerce, it is becoming easier for businesses and consumers to engage in cross-border transactions, even if they are located in different countries. Digital goods and services: Digital goods and services refer to products that are delivered and consumed in a digital form. Examples include software, music, e-books, and online courses. The ease of delivery and the low costs associated with distributing digital goods make them an attractive option for both businesses and consumers. E-marketing and advertising: E-marketing and advertising refers to the use of digital channels to promote and sell products. This includes activities such as email marketing, search engine optimization, social media marketing, and online advertising. 3. Explain the scope of E-Commerce and growth in India. Ans. Scope of E-Commerce: 1.Business Growth: Every business owner wants to see growth in the business. It seems so easy when saying it, but it takes dedicated time and effort to see the expansion. Product vendors and service providers can increase their revenue by making a website of their own or else list the items on other e-commerce websites to reach the vast audience. 2. Different Ecommerce Marketplaces: The Ecommerce marketplaces like Amazon, Paytm, Snapdeal, Shop clues, Flipkart, etc. have their own policies to operate in the market. By agreeing with their terms and conditions, Sellers can list the items in almost every category they are interested in. Creating more listings in the inventory also makes it possible to get good sales on the ecommerce platform. This is one of the best opportunities sellers will get to showcase their products to large audiences. 3. Offers and Discounts: Offers and discounts are also one of the reasons for soar in scope of ecommerce industry. People look for huge discounts and special promo codes when they want to shop online. As a result, they visit numerous ecommerce sites to get the best deal for them. Online sellers can promote their products on Instagram and facebook with coupon codes and target the audience to generate the additional sales. 4. Fast Shipping: There are many shipping service companies which deliver the items in a very short amount of time. However, sellers have to pay high fees for it. Customers generally want their products to arrive in a very short period of time. Nowadays, the delays in shipping only happen because of bad environmental conditions. The shipping service companies have good manpower to process all their operations in a timely manner. 5. Reach to More Audience: The best advantage of having your own website or on the ecommerce website is that your business is not limited to just a single place. The customers can visit your website through any part of the world and purchase your items or services. There are people all around the globe who regularly shops online. Social media have played a huge role in expanding e-business. 6. Advertising: In the initial stage of selling your products online, Advertising is the best and first priority option to go with. However, the advertising budget will totally depend on the sellers. Sellers can generate more sales with advertising. On the other hand promotion also helps in reaching a larger audience. It is very easy to advertise on Google, Facebook, Instagram. 7. B2C and B2B Offering: The scope of ecommerce has been extended to the next level when dealing online. Sellers can offer both pricing b2b and b2b both when listing items on the e-commerce website like Amazon. Business customers are able to see bulk pricing if they are on the platform for bulk purchasing. In this way sellers can get both type of customers at the same time. Growth of E-commerce in India After China and the US, India had the third-largest online shopper base of 150 million in FY21 and is expected to be 350 million by FY26. 4. What is E-Business? Give the difference E-Business and E-Commerce. Ans. E-Business (electronic business) is any process that a business organization conducts over a computer-mediated network. Business organizations include any for-profit, governmental, or nonprofit entity. Their processes include production-, customer-, and internal- or management-focused business processes. E-Business Vs. E-commerce 5. Explain the features of E-Commerce Technology. Ans. 1. Ubiquity: There is a physical space in the traditional business market. Where for example, the customer has to go to buy Clothes, Shoes etc. Whereas in E-commerce this is not the case. E-commerce is everywhere. Due to E-commerce, both the time and effort of the people are reduced. 2. Global Reach: Business transactions in E-commerce can also be done outside the country. Which makes it even more convenient and effective. You can scale up the E-commerce business as per your wish. This is the most accessible way to take your business globally. In E-commerce, the whole world is your market. There is potential of market scale within the E-commerce business. 3.Universal Standards : Universal Standards are standards shared by all the nations around world. These are technical standards of Internet for conducting e-commerce. 4. Richness: E-commerce is also as rich as Television Technology. Advertising and branding is an important part of commerce. E-commerce can Deliver Video, Audio, Animation, Billboards and Signs etc. 5. Interactivity: The technology of E-commerce business is interactive. In this business and consumer can communicate with each other. 6. What are the advantages and disadvantages of E-Commerce. Ans. Advantages : Available 24/7 Provides a global reach No need for intermediaries Provides user with options to compare and select best option Reduces paper work Lowers the transaction cost Disadvantages: Lack of personal touch Requires an initial setup cost for hardware, software etc. Sometimes there are problems with order fulfillment or returns Security is a key concern -Identify Theft -Malware -Denial of Services 7. What are the types of E-Business? Explain each type in details. Ans. B2C: In B2C model, a business website is a place where all the transactions take place directly between a business organization and a consumer. In the B2C model, a consumer goes to the website, selects a catalog, orders the catalog, and an email is sent to the business organization. After receiving the order, goods are dispatched to the customer. Following are the key features of the B2C model − Heavy advertising required to attract customers. High investments in terms of hardware/software. Support or good customer care service. B2B: A website following the B2B business model sells its products to an intermediate buyer who then sells the products to the final customer. As an example, a wholesaler places an order from a company's website and after receiving the consignment, it sells the end product to the final customer who comes to buy the product at the wholesaler's retail outlet. B2B identifies both the seller as well as the buyer as business entities. B2B covers a large number of applications, which enables business to form relationships with their distributors, re-sellers, suppliers, etc. C2C: A website following the C2C business model helps consumers to sell their assets like residential property, cars, motorcycles, etc., or rent a room by publishing their information on the website. Website may or may not charge the consumer for its services. Another consumer may opt to buy the product of the first customer by viewing the post/advertisement on the website. Social Ecommerce: Social commerce is the use of social media platforms like Facebook and Instagram to market and sell products and services. Shoppers can use social commerce to: Discover brands Research products Interact with customer support Purchase items Social commerce is a more convenient and interactive shopping experience which may explain why it’s becoming increasingly popular. Estimates show that the global value of social commerce will reach about $2.9 trillion by 2026: M-Commerce: Buying and selling products and services through mobile devices are the new trend. A housewife can purchase her kitchen appliances from the comfort of her living room, a busy person can order lunch from office, one can use mobile platforms to sell goods and services − all with a few clicks. Local E-commerce: A customer orders a product from a seller, and the merchant delivers the goods to the customer from the nearest location. This significantly cuts the time and expense of logistics while also establishing a degree of confidence between the two parties. This is primarily due to the fact that the consumer is purchasing from a nearby, or local, merchant or shop. Local commerce is classified as Offline-to-Online commerce (O2O). The word “O2O” refers to the possibility (should be the reality) for retailers with physical stores to market and sell to local online customers the same way online pure-plays do. 8. Explain the concept of social E-Commerce and M-Commerce. Ans. Social E-Commerce: Social commerce is the use of social media platforms like Facebook and Instagram to market and sell products and services. Shoppers can use social commerce to: Discover brands Research products Interact with customer support Purchase items Social commerce is a more convenient and interactive shopping experience which may explain why it’s becoming increasingly popular. Estimates show that the global value of social commerce will reach about $2.9 trillion by 2026: Social commerce is booming because social media usage is. Research shows the typical social media user now spends about 15% of their waking life on social platforms, with 10% of US adults having an addiction to at least one app. Social commerce is a simple way to promote and sell products. For example, while scrolling on Instagram you may see a set of skin care products, tap Shop Now, add it to your shopping cart, and check out within the app. M-Commerce: Buying and selling products and services through mobile devices are the new trend. A housewife can purchase her kitchen appliances from the comfort of her living room, a busy person can order lunch from office, one can use mobile platforms to sell goods and services − all with a few clicks. What is M-Commerce? Mobile commerce or simply M-Commerce means engaging users in a buy or sell process via a mobile device. For instance, when someone buys an Android app or an iPhone app, that person is engaged in m-commerce. There are a number of content assets that can be bought and sold via a mobile device such as games, applications, ringtones, subscriptions etc. Benefits of M-Commerce: The probability of your potential customers owning a Smartphone is very high, so you can safely assume that you will get much more positive response from mobile devices than your website. M-commerce is recommended for every business irrespective of its type, scale, and size. 9. Explain Local E-Commerce. Ans. Local E-commerce: A customer orders a product from a seller, and the merchant delivers the goods to the customer from the nearest location. This significantly cuts the time and expense of logistics while also establishing a degree of confidence between the two parties. This is primarily due to the fact that the consumer is purchasing from a nearby, or local, merchant or shop. Local commerce is classified as Offline-to-Online commerce (O2O). The word “O2O” refers to the possibility (should be the reality) for retailers with physical stores to market and sell to local online customers the same way online pure-plays do.
- Android Unit-1 Assignment Sem-5 BCA
UNIT-1 Introduction to Mobile Operating System 1. What is the life cycle of Android activity? Ans.• To work with an activity in Android, you typically: 1. Create an activity class by extending the Activity class or one of its subclasses. 2. Define the layout of the activity's user interface using XML or programmatically. 3. Implement the lifecycle methods (onCreate, onStart, onResume, etc.) to manage the activity's behavior and handle user interactions. 4. Handle events and user input within the activity, such as button clicks, menu selections, etc. 5. Perform any necessary data processing or communication with other components or services. 6. Update the UI and handle state changes as needed. 7. Handle the activity's lifecycle callbacks (onPause, onStop, onDestroy, etc.) to release resources and save or restore state when necessary. The activity lifecycle in Android refers to the sequence of states and methods that an activity goes through during its lifespan. Understanding the activity lifecycle is crucial for managing the behavior and state of an activity. The following are the key states and methods involved in the activity lifecycle: 1. onCreate(): This method is called when the activity is first created. It is typically used to initialize activity resources, set up the user interface, and perform any necessary setup tasks. 2. onStart(): This method is called when the activity becomes visible to the user. At this point, the activity is not yet in the foreground, but it's about to be. 3. onResume(): This method is called when the activity is about to start interacting with the user. The activity is now in the foreground and has user focus. 4. onPause(): This method is called when the activity is partially visible but is losing focus. It is often used to release resources or save transient data. 5. onStop(): This method is called when the activity is no longer visible to the user. It may be invoked either when another activity comes to the foreground or when the activity is being destroyed. 6. onRestart(): This method is called when the activity is being restarted after being stopped. It is followed by onStart() and onResume() to bring the activity back to the foreground. 7. onDestroy(): This method is called when the activity is being destroyed. It is the final call that the activity receives before it is removed from memory. During the lifecycle, the activity may also be affected by various system events and callbacks, such as: • onSaveInstanceState(): This method is called before an activity is paused or stopped to allow saving its current state. It is commonly used to save important data that needs to persist across configuration changes or process death. • onRestoreInstanceState(): This method is called after an activity has been recreated due to a configuration change or process death. It allows the activity to restore its previously saved state. 2. What is Android? Ans. Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android. The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 where as the first commercial version, Android 1.0, was released in September 2008. On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance. The source code for Android is available under free and open source software licenses. Google publishes most of the code under the Apache License version 2.0 and the rest, Linux kernel changes, under the GNU General Public License version 2. Why Android? Open Source Larger Developer and community reach Increased Marketing Inter app Integration Reduced Cost of Development Higher Success ratio Rich Development Environment 3. What are the features of Android architecture? Ans. Android architecture contains different number of components to support any android device needs. Android software contains an open-source Linux Kernel having collection of number of C/C++ libraries which are exposed through an application framework services. Among all the components Linux Kernel provides main functionality of operating system functions to smartphones and Dalvik Virtual Machine (DVM) provide platform for running an android application. The main components of android architecture are following:- Applications Application Framework Android Runtime Platform Libraries Linux Kernel Pictorial representation of android architecture with several main components and their sub components – 4. What is Google Android SDK? Which are the tools placed in the Android SDK? Ans. • The Android SDK (Software Development Kit) is a collection of tools, libraries, and resources required for Android development. It includes the necessary APIs and documentation for building Android applications. • After configuring the Android SDK in Android Studio, you can explore its contents, including: • Android API levels: Different versions of the Android platform, each providing new features and capabilities. • Build Tools: Tools for compiling, packaging, and signing Android applications. • Libraries: Pre-built libraries for common functionalities like database access (SQLite), networking (OkHttp), and user interface (AppCompat). • Documentation: Comprehensive documentation on various aspects of Android development, including APIs, guidelines, and best practices. • Samples and Templates: Sample projects and templates that demonstrate Android development techniques and provide a starting point for your own projects. Android SDK tools: SDK tools are platform-independent and are required to create any Android app, regardless the version you are developing for. Some of these include: Build tools, Debugging tools and Image tools, among others. Now, some of the most important SDK tools are Android SDK Manager, which provides you resources, platforms and other useful components needed to build apps and manage SDK packages. The Android Virtual Device Manager, that provides a graphical user interface to test your app on a virtual device. The Dalvik Debug Monitor Server (ddms) to debug your Android apps. Or the Draw 9-patch, which allows you to create resizable bitmap images for your app. 5. History & Versions Android Operating Systems? Ans. Android Version History The version history of the Android mobile operating system began with the public release of its first beta on November 5, 2007. The first commercial version, Android 1.0, was released on September 23, 2008. The operating system is developed by Google on a yearly cycle since at least 2011. New major releases are announced at Google I/O along with its first public beta to supported Google Pixel devices. The stable version is then released later in the year. 6. Exploring the Android SDK in brief? Ans. Android SDK stands for Android Software Development Kit which is developed by Google for Android Platform. With the help of Android SDK, we can create android Apps easily. About Android SDK: Android SDK is a collection of libraries and Software Development tools that are essential for Developing Android Applications. Whenever Google releases a new version or update of Android Software, a corresponding SDK also releases with it. In the updated or new version of SDK, some more features are included which are not present in the previous version. Android SDK consists of some tools which are very essential for the development of Android Application. These tools provide a smooth flow of the development process from developing and debugging. Android SDK is compatible with all operating systems such as Windows, Linux, macOS, etc. Components of Android SDK: Android SDK Components play a major role in the Development of Android applications. Below are the important components: 1. Android SDK Tools: Android SDK tool is an important component of Android SDK. It consists of a complete set of development and debugging tools. Below are the SDK developer tools: Android SDK Build tool. Android Emulator. Android SDK Platform-tools. Android SDK Tools. 2. Android SDK Build-Tools: Android SDK build tools are used for building actual binaries of Android App. The main functions of Android SDK Build tools are built, debug, run and test Android applications. The latest version of the Android SDK Build tool is 30.0.3. While downloading or updating Android in our System, one must ensure that its latest version is download in SDK Components. 3. Android Emulator: An Android Emulator is a device that simulates an Android device on your system. Suppose we want to run our android application that we code. One option is that we will run this on our Android Mobile by Enabling USB Debugging on our mobile. Another option is using Android Emulator. In Android Emulator the virtual android device is shown on our system on which we run the Android application that we code. 4. Android SDK Platform-tools: Android SDK Platform-tools is helpful when we are working on Project and they will show the error messages at the same time. It is specifically used for testing. It includes: Android Debug Bridge (ADB), is a command-line tool that helps to communicate with the device. It allows us to perform an action such as Installing App and Debugging App etc. Fastboot allows you to flash a device with a new system image. Systrace tools help to collect and inspect timing information. It is very crucial for App Debugging. 5. Android SDK Tools: Android SDK tool is a component of SDK tool. It consists of a set of tools which and other Utilities which are crucial for the development of Android Application. It contains the complete set of Debugging and Development tools for android. 6. SDK Platforms : These are numbered according to the android version. The new version of the SDK platform has more features and more compatible but the old version is less compatible with fewer features. Like in Android 11.0(R) have more compatible and have more feature but the below versions like Android 10.0(Q), Android4.4(KitKat) have less feature and is less compatible. 7. SDK Update Sites: In SDK Update Sites, some sites are embedded in it which will check for Android SDK Updates Tools. In this, one must ensure we don’t unclick the button below because these are checked by default which will check for updates if we will unclick it then it doesn’t check updates for those. 🤞BEST OF LUCK 🤞