BCS Guruji: VB

Ad

Showing posts with label VB. Show all posts
Showing posts with label VB. Show all posts

Friday, December 8, 2023

Blockchain:PYQ's

December 08, 2023 0
Blockchain:PYQ's

- Who published a white paper proposing Ethereum in 2013?
Ethereum was proposed by Vitalik Buterin. He published the white paper in late 2013.


- What is EVM?
EVM is the runtime environment for smart contracts in Ethereum.

-What happens if someone loses the private key of his wallet?
If someone loses the private key of their wallet, they lose access to the associated funds permanently. Recovery is usually impossible, emphasizing the importance of securely storing and backing up private keys.

- Which institute standardized AES algorithm?
The Advanced Encryption Standard (AES) algorithm was standardized by the National Institute of Standards and Technology (NIST).

 -What is Nonce?
In blockchain, a nonce is a number that is used only once. It is often employed in the mining process to vary the output of hash functions.

- What is Non-repudiation?
Non-repudiation refers to the assurance that a party involved in a communication cannot deny the authenticity or origin of a message or transaction.

- What is ICO?
ICO is a fundraising method in which new cryptocurrency projects sell their underlying crypto tokens to early investors. It is a way to raise capital for a new blockchain-based project.

 -Who owns the Blockchain?
No single entity owns the entire blockchain. It is a decentralized and distributed ledger maintained by a network of nodes.

 -What is Gas & Gas limit?
Gas is the unit used to measure the computational effort required to execute operations or contracts on the Ethereum network. Gas limit is the maximum amount of gas a user is willing to pay for a transaction or contract execution.

-What are the advantages of smart contract? Explain any four.

Advantages of Smart Contracts:

Trust: Smart contracts execute automatically based on predefined rules, eliminating the need for trust in a third party. The decentralized and transparent nature of blockchain builds trust.

Efficiency: Automation reduces the time and costs associated with traditional contract execution, as there's no need for intermediaries or manual verification.

Accuracy: Since smart contracts operate on code, the execution is precise, minimizing errors and misunderstandings that can arise in traditional contracts.

Security: Smart contracts are secured by blockchain's cryptographic features. Once deployed, they cannot be altered, providing a high level of security.

- What are the layers of blockchain?

Network Layer: Manages network communication, peer discovery, and data synchronization among nodes.

Consensus Layer: Determines how nodes agree on the state of the blockchain. It includes algorithms like Proof-of-Work (PoW) or Proof-of-Stake (PoS).

Smart Contract Layer: Facilitates the creation, execution, and enforcement of smart contracts. Ethereum is a prominent example with its EVM (Ethereum Virtual Machine).

Application Layer: Houses decentralized applications (DApps) that utilize the underlying blockchain infrastructure.

-What is the formula to calculate transaction fee in Etheream?

Transaction Fee = Gas Used (units) * Gas Price (wei per unit)

Gas represents computational effort, and the fee is calculated based on the amount of gas consumed and the gas price set by the user.

-What is plain text and cipher text?

Plain Text: The original, readable data before any encryption is applied.

Cipher Text: The encrypted data that results from applying an encryption algorithm to the plain text. It appears as random and unreadable without the decryption key.

- What is FPGA?

FPGA is a hardware device with reconfigurable logic gates and circuits.

Unlike ASICs, FPGAs can be programmed and reprogrammed, making them versatile for different applications, including cryptocurrency mining.

 -What is smart contract?

A self-executing contract with the terms directly written into code.

Smart contracts automatically enforce and execute the terms when predefined conditions are met, without the need for intermediaries.

-What is the size of encryption key in DES?
DES (Data Encryption Standard) uses a 56-bit key. The key length influences the security of the encryption.

 What is ASIC?

ASIC is a hardware designed for a specific task or application, such as cryptocurrency mining.

It offers high performance for a specific function but lacks flexibility compared to general-purpose processors.

- Which algorithm is used by Bitcoin to verify transactions?
Bitcoin uses the SHA-256 hashing algorithm to verify transactions. Miners must find a nonce that, when hashed with the transaction data, produces a hash with a specific pattern.

- Which is a unique PoS cryptocurrency that is aimed at delivering ateroperability among other blockchains

Unique PoS Cryptocurrency for Interoperability:

Cardano (ADA) is known for its Proof-of-Stake consensus algorithm and focuses on providing interoperability and scalability in the blockchain space.

What is DAPP?

A DApp operates on a decentralized network and is built on blockchain technology.

DApps use smart contracts to automate processes, ensuring transparency and security.

-What is the difference between public and private blockchains?

Public Blockchain: Open to anyone, decentralized, and transparent (e.g., Bitcoin, Ethereum).

Private Blockchain: Restricted access, often controlled by a single entity for specific purposes like business applications.

-What is P2P сrypto Exchange?

A Peer-to-Peer (P2P) crypto exchange allows users to trade directly with each other without intermediaries.

It provides more control and ownership over assets compared to centralized exchanges.

Whis is 'BFT?

BFT (Byzantine Fault Tolerance):

BFT is a consensus algorithm that ensures the integrity of a distributed system, even when some nodes fail or act maliciously.

It's crucial for maintaining the reliability and security of blockchain networks.

-What is Hybrid Blockchain?

Combines features of both public and private blockchains.

Offers flexibility, allowing certain data to be private while utilizing the security and transparency of a public blockchain.

-Write a short note on life cycle of smart contract 

Creation: Developers write the code for the smart contract.

Execution: The smart contract is deployed on the blockchain and operates based on predefined conditions.

Termination: The smart contract completes its tasks, and outcomes are recorded on the blockchain.

-What is HArd & Soft forks?

Hard Fork: Involves a fundamental change that is not backward-compatible. All nodes must upgrade to continue participating.

Soft Fork: Involves a backward-compatible change, allowing non-upgraded nodes to still participate in the network.

-What is POW?

POW (Proof-of-Work):

POW is a consensus algorithm where participants (miners) solve complex mathematical problems to validate transactions and create new blocks.

It's resource-intensive and helps secure the network against attacks.

-Write a short note on challenges of blockchain

Challenges of Blockchain:

Challenges include scalability issues, interoperability concerns between different blockchains, regulatory uncertainties, and the environmental impact of energy-intensive consensus mechanisms like PoW.


 -Write a short note on ICO?

ICO (Initial Coin Offering):

ICO is a fundraising method where new cryptocurrency tokens are sold to investors before being listed on exchanges.

It allows projects to raise capital by selling a portion of their cryptocurrency.

-Which are the different value data types in solidity?

Solidity, the programming language for Ethereum smart contracts, includes data types like uint (unsigned integer), int (signed integer), address, bool, string, and more.


- Describe EVM with the help of neat diagram.

Stream Cipher and Block Cipher:

Stream Cipher: Operates on individual bits or bytes of data, encrypting or decrypting one at a time. It is often used for real-time communication and is more efficient for streaming data.

Block Cipher: Operates on fixed-size blocks of data, encrypting or decrypting the entire block at once. It is commonly used for securing stored data and messages.

 -Define transaction and explain its structure.

- What are the uses of SHA algorithm?

The Secure Hash Algorithm (SHA) family of cryptographic hash functions, designed by the National Security Agency (NSA) and published by the National Institute of Standards and Technology (NIST), has several important uses:

Data Integrity: SHA algorithms generate fixed-size hash values (digests) that uniquely represent input data. By comparing hash values, one can verify the integrity of the original data. Any change to the data will result in a different hash value.

Digital Signatures: SHA is commonly used in combination with asymmetric encryption algorithms to create digital signatures. These signatures provide authentication and verify the origin and integrity of digital messages.

Password Hashing: SHA algorithms are employed to securely hash passwords. Storing hashed passwords instead of plaintext enhances security, as it makes it more challenging for attackers to reverse-engineer passwords.

Blockchain Technology: In blockchain, SHA algorithms are used to create cryptographic hashes for blocks and transactions. For example, Bitcoin's PoW consensus relies on SHA-256 to generate a hash that meets specific criteria, contributing to the security of the network.

 -What is Public & Private blockchain?

Public Blockchain:

Accessibility: Open to anyone; anyone can join the network, participate in transactions, and validate blocks.

Decentralization: Multiple nodes (computers) maintain the network, and no single entity controls it.

Transparency: All transactions are visible to all participants, enhancing transparency and accountability.

Examples: Bitcoin and Ethereum are examples of public blockchains.

Private Blockchain:

Accessibility: Restricted to a specific group of participants, usually within a single organization or consortium.

Decentralization: Controlled by a centralized entity or a limited number of nodes.

Privacy: Access to data and transactions is restricted, providing privacy among participants.

Examples: Hyperledger Fabric and R3 Corda are examples of private blockchains.

- Write a short note on crypto wallet.

A crypto wallet is a digital tool that allows users to securely store and manage their cryptocurrency assets.

It consists of a public key (for receiving funds) and a private key (for authorizing transactions).

Wallets can be software-based (online, desktop, or mobile) or hardware-based (physical devices).

Wallets enable users to send, receive, and monitor their cryptocurrency balances.

.

 -What are the tasks of miners?

Tasks of Miners:

Transaction Verification: Miners verify transactions by solving complex mathematical problems using computational power.

Block Creation: Verified transactions are grouped into blocks, and miners compete to solve the proof-of-work problem to create a new block.

Consensus: Miners participate in the consensus mechanism (e.g., Proof-of-Work) to agree on the state of the blockchain.

Incentive: Miners are rewarded with newly created cryptocurrency and transaction fees for their efforts.

 -Which are the components of blockchain?

Blocks: Containers for transaction data and other information.

Transactions: Records of data exchanges between participants.

Chain: The linkage of blocks through cryptographic hashes, forming a secure and chronological sequence.

Consensus Mechanism: Rules or algorithms that facilitate agreement on the state of the blockchain.

Decentralized Network: Nodes that maintain copies of the entire blockchain, ensuring redundancy and security.

- Write a short note on DES.

DES (Data Encryption Standard):

DES is a symmetric-key block cipher used for encryption and decryption of electronic data.

Developed by IBM in the 1970s, it became a widely adopted encryption standard.

DES uses a 56-bit key, and its 64-bit block size encrypts data in 64-bit chunks.

Over time, DES became vulnerable to brute-force attacks due to its small key size, leading to the development of more secure encryption algorithms.




Python Programming :PYQ's

December 08, 2023 0
Python Programming :PYQ's

Data Science:PYQ's

December 08, 2023 0
Data Science:PYQ's

 - What is Data science?
Data science is a field that involves using scientific methods, processes, algorithms, and systems to extract insights and knowledge from structured and unstructured data.

 -Define Data source?
A data source is any location, platform, or system from which data originates or is collected.

- What is missing values?
Missing values refer to the absence of data in a specific field or variable where information is expected. 

- List the visualization libraries in python.

Matplotlib

Seaborn

Plotly

Bokeh

Pyplot

 -List applications of data science.

Climate Modeling:

Studying climate patterns and making predictions for climate change mitigation.

Recommendation Systems:

Providing personalized recommendations for products, movies, music, etc.

Social Network Analysis:

Studying relationships and patterns within social networks.

Predictive Analytics:

Forecasting future trends and outcomes based on historical data.

Fraud Detection:

Identifying and preventing fraudulent activities by analyzing patterns.

Customer Segmentation:

Grouping customers based on common characteristics for targeted marketing.

- What is data transformation?
Data transformation refers to the process of converting raw data into a more suitable format for analysis. 

- What is use of Bubble plot?
A Bubble plot is a variation of a scatter plot where a third dimension of the data is shown through the size of markers (bubbles). It is useful for visualizing three variables in a two-dimensional space, where the size of the bubbles represents the magnitude of the third variable.

 -Define Data cleaning?
Data cleaning, or data cleansing, is the process of identifying and correcting errors or inconsistencies in datasets. It involves handling missing values, removing duplicates, correcting inaccuracies, and ensuring data quality for accurate analysis.

 -Define standard deviation?
Standard Deviation is a measure of the amount of variation  in a set of values. It indicates how much individual data points differ from the mean (average) of the dataset. 

- List the tools for data scientist.

Python (with libraries like NumPy, Pandas, Scikit-learn)

Jupyter Notebooks

Tableau

Excel (for basic analysis)

- Define statistical data analysis?
Statistical Data Analysis involves using statistical methods to explore, summarize, and draw inferences from data. It includes descriptive statistics, hypothesis testing, regression analysis, and other techniques to understand patterns and relationships in the data.

 -What is data cube?
A data cube is a multidimensional representation of data, where values are organized along multiple dimensions. It allows for the analysis of data by enabling users to slice, dice, and drill down into the information

-Give the purpose of data preprocessing?
Data preprocessing is done to prepare raw data for analysis. Its purposes include cleaning and handling missing values, transforming data into a suitable format, and ensuring that data is ready for machine learning algorithms.

 -What is the purpose of data visualization?

Data visualization is used to represent data graphically, making complex patterns and trends more understandable. Its purposes include:

Communicating insights effectively

Identifying patterns and outliers

Supporting decision-making

Presenting data in a visually appealing manner.

 -What are the measures of central tendency? Explain any two of them in

 brief.

Measures of central tendency describe the center or average of a data set. Two common measures are:

Mean (Average): It is calculated by summing up all values and dividing by the total number of values.

Median: It is the middle value when data is arranged in ascending order. If there's an even number of values, the median is the average of the two middle values.

- What are the various types of data available? Give example of each?

Nominal Data: Categorical data with no inherent order (e.g., colors, types of fruit).

Ordinal Data: Categorical data with a meaningful order (e.g., ranking in a race, customer satisfaction levels).

Interval Data: Numeric data with equal intervals but no true zero point (e.g., temperature in Celsius).

Ratio Data: Numeric data with equal intervals and a true zero point (e.g., height, weight).

- What is venn diagram? How to create it? Explain with example.

A Venn diagram is a visual representation of the relationships between different sets. To create one, draw overlapping circles to represent each set, and where the circles overlap, you show the elements that belong to both sets.

Example: If Set A represents mammals and Set B represents four-legged animals, the overlapping part shows mammals that are also four-legged.

- Explain different data formats in brief.

CSV (Comma-Separated Values): Text-based format where values are separated by commas.

JSON (JavaScript Object Notation): Lightweight data interchange format.

Excel Spreadsheets: Tabular format with rows and columns.

- What is data quality? Which factors are affected data qualities?

Data quality refers to the accuracy, completeness, consistency, and reliability of data. Factors affecting data quality include:

Accuracy

Completeness

Consistency

Timeliness

Relevance

 -Write details notes on basic data visualization tools?

Matplotlib: A popular 2D plotting library for Python.

Seaborn: Built on Matplotlib, it provides a high-level interface for attractive and informative statistical graphics.

Tableau: A powerful and interactive data visualization tool.


 -What is outlier? State types of outliers.

n outlier is an observation that lies an abnormal distance from other values in a random sample from a population. Types of outliers include:

Univariate Outliers: Unusual values in a single variable.

Multivariate Outliers: Unusual combinations of values across multiple variables.

 -State and explain any three data transformation techniques

Normalization: Scaling values to a standard range, often between 0 and 1.

Log Transformation: Applying the logarithm to data to handle skewed distributions.

Standardization: Transforming data to have a mean of 0 and a standard deviation of 1.

- Define volume characteristic of data in reference to data science.
Volume refers to the sheer size of data. In data science, dealing with large volumes of data is common, and technologies like big data tools and distributed computing are employed to handle and analyze massive datasets.

- Give examples of semistructured data.

XML (eXtensible Markup Language)

JSON (JavaScript Object Notation)

- Define Data Discretization.
Data discretization involves converting continuous data into discrete intervals or categories. It's useful for simplifying complex data and can be applied to numerical variables.

- What is a quartile?
Quartiles divide a dataset into four equal parts. The three quartiles (Q1, Q2, and Q3) are the values that separate the data into quarters. Q2 is the median.

- List different types of attributes.

Nominal Attributes: Categorical with no inherent order.

Ordinal Attributes: Categorical with a meaningful order.

Interval Attributes: Numeric with equal intervals but no true zero.

Ratio Attributes: Numeric with equal intervals and a true zero point.

- Define Data object.
In data science, a data object refers to an individual unit of information, such as a row in a dataset.

 -What is Data Transformation?
Data transformation involves converting data from one format or structure into another to make it more suitable for analysis or modeling.

 -Write the tools used for geospatial data.

ArcGIS: A geographic information system for working with maps and geographic information.

QGIS (Quantum GIS): An open-source alternative for geospatial data analysis 

- State the methods of feature selection.

Filter Methods: Select features based on statistical characteristics.

Wrapper Methods: Evaluate feature subsets using a specific machine learning model.

- List any two libraries used in Python for data analysis.

Pandas: For data manipulation and analysis.

NumPy: For numerical operations and array processing.

- Explain any two ways in which data is stored in files.

CSV (Comma-Separated Values): Text-based format with values separated by commas.

JSON (JavaScript Object Notation): Lightweight data interchange format.

-  Explain role of statistics in data science.
Statistics helps in making sense of data by providing methods for summarizing, analyzing, and interpreting information.

- Explain two methods of data cleaning for missing values.

Imputation: Replacing missing values with estimated or calculated values.

Deletion: Removing rows or columns with missing values.

- Explain any two tools in data scientist tool box.

Jupyter Notebooks: For interactive and collaborative coding.

Git: Version control system for tracking changes in code.

- Write a short note on word clouds.
Word clouds visually represent the frequency of words in a text, with the size of each word indicating its frequency. They are often used for textual data exploration and visualization.

 -Explain data science life cycle with suitable diagram.
The data science life cycle typically involves stages like problem definition, data collection, data cleaning, exploration, modeling, evaluation, and deployment. It forms a cyclical process where insights drive further iterations.

-Explain concept and use of data visualisation.
Data visualization is the presentation of data in graphical or visual formats, making complex patterns and trends easily understandable. It conveys insights, patterns, and relationships within the data.

- Calculate the variance and standard deviation for the following data.

 X : 14 9 13 16 25 7 12

Mean (X̄) = (14 + 9 + 13 + 16 + 25 + 7 + 12) / 7 = 96 / 7 ≈ 13.71

Variance (σ²) = Σ(Xᵢ - X̄)² / n = (0.04 + 12.49 + 0.09 + 4.84 + 64.69 + 37.69 + 1.96) / 7 ≈ 20.70

Standard Deviation (σ) = √Variance ≈ √20.70 ≈ 4.55

- Write a short note on hypothesis testing.
Hypothesis testing is a statistical method to make inferences about a population based on a sample. It involves forming a hypothesis, collecting and analyzing data, and drawing conclusions about the validity of the hypothesis.

 -Differentiate between structured data and unstructured data.

Structured Data: Well-organized data with a clear format, often stored in databases.

Unstructured Data: Data lacking a predefined data model or structure, such as text, images, or videos.

- Explain data visualization libraries in Python.

  1. Matplotlib:

    • A versatile 2D plotting library that provides a wide range of charts and plots.
  2. Seaborn:

    • Built on top of Matplotlib, it simplifies the creation of attractive statistical graphics.
  3. Pandas Plotting:

    • Integrated with the Pandas library, it offers a simple interface for creating basic visualizations directly from DataFrames.
  4. Plotly:

    • Enables the creation of interactive, web-based visualizations and supports various chart types.
  5. Bokeh:

    • Another library for interactive visualizations, with a focus on modern web browsers and dynamic plots.

- Define data science.

Data Science is a deep study of the massive amount of data, which involes extracting meaningful insights from row,structured and unstructured data.

 -Explain any one technique of data transformation.

Normalization:

Normalization is a data transformation technique used to scale numerical features, bringing them to a standard range, typically between 0 and 1. This ensures that all features contribute equally to analyses, especially in machine learning, by preventing features with larger scales from dominating the model. The Min-Max normalization formula is commonly employed for this purpose.

-Write any two applications of data science

1)Healthcare Predictive Analytics:

Application: Predicting disease outcomes, optimizing patient care, and personalized medicine.

2)E-commerce Recommendation Systems:

Application: Enhancing user experience and driving sales through personalized product recommendations.

WEB TECH PYQ

December 08, 2023 0
WEB TECH PYQ

 -Which tag is used to set the text in Superscript format?

The <sup> tag is used for superscript text in HTML.

 - Explain the use of <Style>
The <style> tag in HTML is used to define the style information for a document, including CSS (Cascading Style Sheets) properties. 

 -How to create a directory in PHP?

The mkdir() function is used to create a directory in PHP. 

- How External CSS is used?

External CSS is applied by linking an external stylesheet file to an HTML document using the <link> tag within the document's <head> section.

Example: <link rel="stylesheet" type="text/css" href="styles.css">


-Discuss the Scope of a Variable in PHP with an example

PHP has three variable scopes: local, global, and static.

CODE:-

$globalVar = "I am global";

function exampleFunction() {

    $localVar = "I am local";

    echo $localVar;  // Accessible only inside the function

    echo $GLOBALS['globalVar'];  // Accessing a global variable

}

exampleFunction();

echo $localVar;  // Will cause an error

 


-Design HTML form that will accept user input of user name, Address, provide buttons to submit the input as -wellas to refresh it.

<form action="process.php" method="post">

  <label for="username">Username:</label>

  <input type="text" id="username" name="username" required>

  <label for="address">Address:</label>

  <textarea id="address" name="address" required></textarea>

  <button type="submit">Submit</button>

  <button type="reset">Refresh</button>

</form>

-Write PHP Script to accept associative array and sort in descending

 order. Display sorted array to user.

$array = array("John" => 30, "Jane" => 25, "Doe" => 35);

arsort($array);

foreach($array as $key => $value) {

  echo "$key: $value<br>";

}


 -Explain terms HTTP request and HTTP response.

An HTTP request is a message sent by a client (usually a web browser) to request information from a server. It includes a method (like GET or POST) and a URL.

An HTTP response is a message sent by the server back to the client in response to an HTTP request. It includes information such as status codes, headers, and the requested data.

 

-What is hyperlink?
A hyperlink is a clickable element on a web page, typically text or an image, that, when clicked, navigates the user to another location, which can be within the same document, to another web page, or to a different resource on the internet.

-  List the advantages of CSS

Separation of Concerns:

CSS separates the style and layout from the HTML structure, making the code more modular and easier to maintain.

Consistency:

CSS allows for consistent styling across multiple pages, ensuring a uniform look and feel throughout a website.

Page Load Speed:

External CSS files can be cached, reducing the load time for subsequent pages and improving overall performance.

Responsive Design:

CSS enables the creation of responsive designs that adapt to different screen sizes and devices.

- Which tag is used to set the text in superscript format?

 - State the purpose of pathinfo()

The pathinfo() function in PHP is used to extract information about a file path, such as the directory name, file name, extension, and filename without extension.

- List any two features of HTTP protocol.

Statelessness:

Each request from a client to a server is independent, and the server does not retain information about the client's state between requests.

Connectionless:

After a request is made and a response is sent, the connection between the client and server is closed. Subsequent requests require establishing a new connection.


- What is web server?
A web server is software that processes incoming network requests over HTTP or HTTPS protocols. It serves web content (HTML pages, images, CSS, etc.) to clients (web browsers) based on their requests.

 

 

 -Write any 2 features of PHP & HTML

PHP:

Server-Side Scripting:

PHP is a server-side scripting language, meaning it is executed on the server, and only the result is sent to the client. This allows for dynamic content generation.

Extensive Database Support:

PHP has robust support for interacting with databases, making it suitable for developing database-driven web applications.

HTML:

Markup Language:

HTML is a markup language used to structure content on the web. It provides a set of tags to define the structure of a web page.

Platform-Independent:

HTML is platform-independent, meaning it can be rendered and displayed consistently across different devices and browsers.

-Write the output of the following PHP Script

 <?php

 $ age = array("Anna"=>"45", "Julie"=>"38", "Benne"=>"53");

 usort($age);

 print_r($age);

 ?>

$age = array("Anna"=>"45", "Julie"=>"38", "Benne"=>"53");

usort($age);

print_r($age);
The output will be an error because usort() expects an array and usort($age) does not provide a comparison function.

 -Write the output of the following script?

 <?php

 $a='PHP';

 $b='$a interpolation ';

 echo $b;

 ?>

$a = 'PHP';

$b = '$a interpolation ';

echo $b;

The output will be: $a interpolation

 -Write the output of the following PHP Script.

 $str=' abc,pqr,lmn,xyz';

 $p=explode(',',$str,3);

 print_r($p);

$str = 'abc,pqr,lmn,xyz';

$p = explode(',', $str, 3);

print_r($p);

OUTPUT

Array

(

    [0] => abc

    [1] => pqr

    [2] => lmn,xyz

)

- What is the output of the following?

 <?php

 $p=array(1,2,3,4,5);

 $q=array(1,3,5,7,9);

 $s=array_diff($p,$q);

 print_r($s);

 ?>

$p = array(1, 2, 3, 4, 5);

$q = array(1, 3, 5, 7, 9);

$s = array_diff($p, $q);

print_r($s);

OUTPUT:
The output will be an array containing elements not present in both arrays:
Array
(
    [1] => 2
    [3] => 4
)

 -Design HTML form that will accept user input as first name, middle

 name and last name, address, contact number. Provide buttons to submit

 the input as well as to refresh form.

<form action="process.php" method="post">

  <label for="firstName">First Name:</label>

  <input type="text" id="firstName" name="firstName" required>


  <label for="middleName">Middle Name:</label>

  <input type="text" id="middleName" name="middleName">


  <label for="lastName">Last Name:</label>

  <input type="text" id="lastName" name="lastName" required>


  <label for="address">Address:</label>

  <textarea id="address" name="address" required></textarea>


  <label for="contactNumber">Contact Number:</label>

  <input type="tel" id="contactNumber" name="contactNumber" required>

  <button type="submit">Submit</button>

  <button type="reset">Refresh</button>

</form>




 


 


-Write a PHP script to read a file abc.txt where file contains character,

 B,C,T,G and space. Count occurrences of each character and write it

 to the abccount.txt file.

<?php

$filename = 'abc.txt';

$fileContents = file_get_contents($filename);

$charCount = array_count_values(str_split($fileContents));


// Write counts to a file

file_put_contents('abccount.txt', print_r($charCount, true));

?>





 

  -Define an Introspection
 Introspection is the ability of a program to examine the type or properties of an object during runtime. It allows a program to analyze its own structure or the structure of other objects.

 



- What is use of serialization?
Serialization is the process of converting complex data types (objects, arrays) into a format that can be easily stored or transmitted. In PHP, it's commonly used to store and retrieve object states, such as when working with sessions or caching.

 -What is a constructor?

A constructor in PHP is a special method that is automatically called when an object is created from a class. It is used to initialize object properties or perform any necessary setup when an object is instantiated

class MyClass {

    public function __construct() {

        echo "Constructor called.";

    }

}

 


- Write a Php program to accept associative array of five expenses

 (electricity bill, phone bill, petrol bill property tax, college fees) and their

 respective amount of’ two persons. print the total expenditure of each

 person.

<?php

$expenses = array(

    "electricity" => 120,

    "phone" => 50,

    "petrol" => 80,

    "property_tax" => 200,

    "college_fees" => 500

);


$person1 = array_sum($expenses) / 2;

$person2 = array_sum($expenses) / 2;


echo "Total expenditure for person 1: $" . $person1 . "<br>";

echo "Total expenditure for person 2: $" . $person2;

?>


 -What is inheritance? Explain with suitable example.

Inheritance is a feature in object-oriented programming where a class inherits properties and methods from another class. Example:

class Animal {

    public function sound() {

        echo "Animal makes a sound.";

    }

}


class Dog extends Animal {

    public function sound() {

        echo "Dog barks.";

    }

}


$dog = new Dog();

$dog->sound();  // Output: Dog barks.


- Write a Php script to read a file DNA. TXT where file contains character

 A, T, C G and space. Count occurrences of each character and write it

 to the DNACOUNT. TXT file.

<?php

$filename = 'DNA.txt';

$fileContents = file_get_contents($filename);

$charCount = array_count_values(str_split($fileContents));


// Write counts to a file

file_put_contents('DNACOUNT.txt', print_r($charCount, true));

?>



  -Explain the following statements with syntax and example

 While statement

 Switch statement

 While Statement:

Executes a block of code repeatedly as long as a specified condition is true.


$i = 1;

while ($i <= 5) {

    echo $i . " ";

    $i++;

}

// Output: 1 2 3 4 5


Switch Statement:

Selects one of many blocks of code to be executed.


$day = "Monday";

switch ($day) {

    case "Monday":

        echo "It's the start of the week.";

        break;

    // More cases...

}

 

 



 -What is class? Give syntax of class declaration in Php.

class MyClass {

    // Properties and methods go here

}

A class is a blueprint or a template for creating objects. It defines a set of properties (attributes) and methods (functions) that characterize an object of the class. 


 



 -How to move back to the first entry in a given directory

 while working with it ?

 the rewinddir function to move the directory handle back to the first entry.

 -Write the output of the following PHP script :

 function change( )

 { $cnt ++; }

 $cnt = 20;

 change( );

 echo $cnt;

<?php

function change() {

    $cnt++;

}

<?php

function change() {

    $cnt++;

}

$cnt = 20;

change();

echo $cnt;

?>

OUTPUT:

20

 

 -Write a PHP script to define class vector with size and integer

 elements. Define a construction to initialize the object. Accept

 vector elements and its size from user. Also write member

 functions to display its elements.

<?php

class Vector {

    public $size;

    public $elements;


    public function __construct($size) {

        $this->size = $size;

        // Initialize other properties as needed

    }


    public function setElements($elements) {

        $this->elements = $elements;

    }


    public function displayElements() {

        print_r($this->elements);

    }

}


// Usage example

$obj = new Vector(5);

$obj->setElements([1, 2, 3, 4, 5]);

$obj->displayElements();

?>






 


 


- Explain the concept of extends and implements with

 class.

extends: Used for inheritance, allowing a class to inherit properties and methods from another class.

class ParentClass {

    // Properties and methods

}


class ChildClass extends ParentClass {

    // Additional properties and methods

}

implements: Used to implement an interface, ensuring that the class contains the methods specified by the interface.

interface MyInterface {

    public function method1();

    public function method2();

}


class MyClass implements MyInterface {

    public function method1() {

        // Implementation

    }


    public function method2() {

        // Implementation

    }

}


- How do you define constant PI with value 3.142 in PHP ?

define('PI', 3.142);

echo PI;  // Output: 3.142

 -What is type casting ?

Type casting is the conversion of a variable from one data type to another.

Example: Converting a string to an integer.

$strNumber = "123";

$intNumber = (int)$strNumber;

echo $intNumber;  // Output: 123



 -How to create object in PHP ?

To create an object in PHP, you need to define a class and then instantiate it. Here's a simple example:

class MyClass {

    public $property;


    public function myMethod() {

        echo "Hello, I'm a method!";

    }

}

// Instantiate the class

$obj = new MyClass();

// Access the property and call the method

$obj->property = "Some value";

$obj->myMethod();

 -What will be output of the following :

 <?php

 ?>

 $a = “LK9”;

 $a++;

 Echo $a;

 -List any four web browser names.

Google Chrome

Mozilla Firefox

Microsoft Edge

Safari

 -List and explain (any three)the functions of PCRE.

preg_match(): Used to perform a regular expression match.

preg_replace(): Used to perform a regular expression search and replace.

preg_split(): Splits a string into an array using a regular expression.

- Write a PHP script to accept filename from the user and

 print total number of words.

 -Write a php script display the student details in table

 format.

<?php

$filename = readline("Enter the filename: ");

$fileContent = file_get_contents($filename);

$wordCount = str_word_count($fileContent);

echo "Total number of words: $wordCount";

?>


- Explain anonymous function concept in PHP.

Anonymous functions, also known as closures, allow the creation of functions without giving them a specific name. They can be assigned to variables and used as arguments in functions. Example:

$add = function($a, $b) {

    return $a + $b;

};

echo $add(3, 4); // Output: 7

- Write a short note on Interface
An interface in PHP is a contract specifying a set of methods that a class must implement. It allows for multiple inheritance and helps achieve abstraction. Classes implementing an interface must provide definitions for all the methods declared in the interface.

- State the features of PHP.

Open source.

Cross-platform (works on Windows, Linux, macOS).

Supports various databases.

Easy integration with HTML.

- State true or false :

 "Include "abc.php" can be written two times in a PHP

 script."
True. You can include a file multiple times in a PHP script.

- What is serialization ?
Serialization is the process of converting a data structure or object into a format that can be easily stored or transmitted, such as converting a PHP array into a string. This string can then be reversed back into the original data structure through deserialization.

-Write the output of the following PHP script :

 $white="show";

 $black=&$while;

 unset($white);

 print$black;

$white = "show";

$black = &$white;

unset($white);

print $black;

- Explain the PHP functions used to convert array into variables

 and vice versa.

To convert an array into variables: extract()

To convert variables into an array: compact()

- Write a PHP script to accept three strings str1, str2, str3

 from user. Search str2 in str1 and replace all occurrences

 of str2 by str3. Also display total number of occurrences.

<?php

$str1 = readline("Enter the main string: ");

$str2 = readline("Enter the string to search: ");

$str3 = readline("Enter the string to replace with: ");

// Perform the search and replace

$result = str_replace($str2, $str3, $str1, $count);

// Display the result and count

echo "Result: $result\n";

echo "Total occurrences replaced: $count\n";

?>

- How to call a constructor of a parent class from a child

 class ? Explain with suitable example.
Using  the parent::__construct()

class ParentClass {

    public function __construct() {

        echo "Parent constructor\n";

    }

}


class ChildClass extends ParentClass {

    public function __construct() {

        parent::__construct();

        echo "Child constructor\n";

    }

}


// Creating an object of the child class

$obj = new ChildClass();


 -Write the difference between break and continue statement

break: Exits the current loop or switch statement.

continue: Skips the rest of the current loop iteration and continues with the next one.

 - Write a PHP script to implement any two set operations.

 eg. union, intersection, difference.

<?php

$array1 = [1, 2, 3, 4, 5];

$array2 = [3, 4, 5, 6, 7];


// Union

$union = array_merge($array1, $array2);


// Intersection

$intersection = array_intersect($array1, $array2);


// Difference

$difference = array_diff($array1, $array2);


// Displaying results

echo "Union: " . implode(", ", $union) . "\n";

echo "Intersection: " . implode(", ", $intersection) . "\n";

echo "Difference: " . implode(", ", $difference) . "\n";

?>


- What is abstract class ? Write features of it.

An abstract class in PHP is a class that cannot be instantiated and may contain abstract methods. Features:

May have abstract methods with no implementation.

Can have both abstract and concrete methods.

Can't be instantiated; requires subclassing.

Provides a way to define a common interface for multiple classes.

-  Discuss PCRE preg_match( ) and preg_grep( ) with

 example.

preg_match(): Used to perform a regular expression match against a string.

$pattern = "/[0-9]+/";

$string = "The year is 2023.";

if (preg_match($pattern, $string, $matches)) {

    echo "Match found: " . $matches[0];

} else {

    echo "No match found.";

}


preg_grep(): Used to perform a regular expression search in an array.

$pattern = "/^John/";

$array = ["John Doe", "Jane Smith", "Doe John"];

$result = preg_grep($pattern, $array);

print_r($result);

- Give two examples of web browsers

- Abstract class must contain all abstract methods" Justify True/False. 
False. An abstract class may contain abstract methods, but it is not required to have only abstract methods. It can also have concrete (implemented) methods.

- Write a PHP program to acrept a string and print string divided into equal number of characters. (Consider spaces and enter character in calculation).

<?php

$string = readline("Enter a string: ");

$length = readline("Enter the length of each part: ");


// Using str_split to divide the string

$parts = str_split($string, $length);


// Displaying the result

echo "Result: " . implode(", ", $parts) . "\n";

?>


-Accept directory name from user. Write a PHP program to change norrent directory to acceptod directory name and count number of files and directories in it.

<?php

$directory = readline("Enter the directory path: ");

chdir($directory);


// Counting files and directories

$files = glob("*");

$fileCount = count($files);

$dirCount = count(array_filter($files, 'is_dir'));


echo "Number of files: $fileCount\n";

echo "Number of directories: $dirCount\n";

?>


-What in serialization? How is it used in PHPT

Serialization is the process of converting data into a format that can be easily stored or transmitted. In PHP, serialize() is used to convert data into a storable string, and unserialize() is used to reconstruct the original data from the serialized string.

Example:

$data = array("name" => "John", "age" => 25);

$serializedData = serialize($data);

// Store $serializedData in a file or transmit over the network

// Later, retrieve and unserialize the data

$originalData = unserialize($serializedData);

-Write a PHP program to sort array on marka (Array emtains names and marks)

<?php

$students = array(

    array("name" => "Alice", "marks" => 85),

    array("name" => "Bob", "marks" => 72),

    array("name" => "Charlie", "marks" => 95),

);


// Sorting the array based on marks

usort($students, function($a, $b) {

    return $b['marks'] - $a['marks'];

});


// Displaying the sorted array

print_r($students);

?>


- Write a short note en prepare and execute functions in databases

<?php

$students = array(

    array("name" => "Alice", "marks" => 85),

    array("name" => "Bob", "marks" => 72),

    array("name" => "Charlie", "marks" => 95),

);


// Sorting the array based on marks

usort($students, function($a, $b) {

    return $b['marks'] - $a['marks'];

});


// Displaying the sorted array

print_r($students);

?>

$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");


// Prepare a statement

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");


// Bind parameters

$stmt->bindParam(':username', $username);


// Execute the statement

$stmt->execute();


// Fetch results

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);


-Write a PHP program to create class college and derive class science from it with accept and print methods. -Accept. information from user assign it la class members and print 141

<?php

class College {

    protected $name;


    public function acceptInfo($name) {

        $this->name = $name;

    }


    public function printInfo() {

        echo "College Name: " . $this->name . "\n";

    }

}


class Science extends College {

    // Additional properties or methods specific to the Science class can be added here.

}


// Example usage

$scienceCollege = new Science();

$scienceCollege->acceptInfo("Science College");

$scienceCollege->printInfo();

?>


- Write a short note in directory manipulation.
Directory manipulation in PHP involves operations such as creating, reading, updating, and deleting directories. Functions like mkdir (create directory), rmdir (remove directory), opendir (open directory), and scandir (scan directory) are commonly used.

-Write role of web server in internet programming. 121
A web server handles requests from clients (usually browsers), processes them, and sends back responses. It interprets server-side scripts, manages resources, and communicates with databases. Common web servers include Apache, Nginx, and Microsoft IIS.

-Stats the advantages of PHP.

-What will be output of the following

<?php

$a= "K9;

$a++;

Echo $a;

?>

<?php

$a = "K9";

$a++;

echo $a;

?>


- What is interface?
An interface in PHP is a contract that defines a set of methods a class must implement. It provides a way to achieve abstraction and multiple inheritance in PHP.

-Keywords are ense sensitive in PHP Justify True or False
True. Keywords like if, else, class, etc., are case-sensitive in PHP. For example, IF or Else would not be recognized.

What is a scientific array? Explain with an example how it's different from an indexed array. Explain a French function.

An associative array in PHP is an array where each key is associated with a specific value. Unlike indexed arrays that use numeric indices, associative arrays use named keys.

Example:

$student = array(

    "name" => "John",

    "age" => 20,

    "grade" => "A"

);

In the example, "name," "age," and "grade" are keys associated with their respective values. A French function might be a function written in French, but it's not a standard term in PHP.