text:
## Bash shell programming
The **shell** is a command line interpreter which provides the user interface for terminal windows. It can also be used to run scripts, even in non-interactive sessions without a terminal window, as if the commands were being directly typed in.
```
#!/bin/bash
find /usr/lib -name "*.c" -ls
```

The first line of the script, that starts with ``#!/bin/bash`` contains the full path of the command interpreter that is to be used on the file. The command interpreter is tasked with executing statements that follow it in the script. Commonly used interpreters include:
```
/usr/bin/perl
/bin/bash
/bin/csh
/bin/tcsh
/bin/ksh
/usr/bin/python
/bin/sh
```

Scripting is not only limited to shell interpreter. It can be used for Python scripts too.
```
# ll script
-rwxr--r--. 1 root root 55 Mar  3 15:22 script
# cat script
#!/usr/bin/python
print "Welcome to the Python script"
# ./script
Welcome to the Python script
```

Scripts can be interactive too.

```
# cat script.sh
#!/bin/bash
   # Interactive reading of variables
   echo "ENTER YOUR NAME"
   read sname
   # Display of variable values
   echo "WELCOME "$sname"!"
# ./script.sh
ENTER YOUR NAME
Adriano
WELCOME Adriano!
```

All shell scripts generate a return value upon finishing execution. The value can be set with the ``exit`` statement. Return values permit a process to monitor the exit state of another process often in a parent-child relationship. This helps to determine how this process terminated and take any appropriate steps necessary, contingent on success or failure. By convention, success is returned as 0, and failure is returned as a non-zero value. The return value is always stored in the ``$?`` environment variable.
```
# cat names.txt
01 Mario Rossi
02 Antonio Esposito
03 Michele Laforca
04 Antonio Esposito
# echo $?
0
# cat names
cat: names: No such file or directory
# echo $?
1
```

### Basic syntax
Scripts require you to follow a standard language syntax. Rules delineate how to define variables and how to construct and format allowed statements, etc. The table lists some special character usages within bash scripts:

|Character|Description|
|---------|-----------|
|#|Used to add a comment, except when used as \#, or as #! when starting a script|
|\\|Used at the end of a line to indicate continuation on to the next line|
|;|Used to interpret what follows as a new command|
|$|Indicates what follows is a variable|

Sometimes you may want to group multiple commands on a single line. The semicolon character is used to separate these commands and execute them sequentially as if they had been typed on separate lines.

The three commands in the following example will all execute even if the ones preceding them fail:
```
$ make ; make install ; make clean
```
However, you may want to abort subsequent commands if one fails. You can do this using the and operator:
```
$ make && make install && make clean
```
If the first command fails the second one will never be executed. A final refinement is to use the or operator:
```
$ cat file1 || cat file2 || cat file3
```
In this case, you proceed until something succeeds and then you stop executing any further steps.

### Functions
A function is a code block that implements a set of operations. Functions are useful for executing procedures multiple times perhaps with varying input variables. Functions are also often called subroutines. Using functions in scripts requires two steps:

1. Declaring a function
2. Calling a function

The function declaration requires a name which is used to invoke it. The proper syntax is:
```
    function_name () {
       command...
    }
```
For example, the following function is named display:
```
    display () {
       echo "This is a sample function"
    }
```
The function can be as long as desired and have many statements. Once defined, the function can be called later as many times as necessary. In the full example shown in the figure, we are also showing an often-used refinement: how to pass an argument to the function.  The first, second, ..., n-th argument can be referred to as ``$1, $2, ..., $n``. The script name is referred as ``$0``. All parameters are referred as ``$*`` and the total number of arguments is ``$#``.
```
# cat script.sh
#!/bin/bash
echo The name of this program is: $0
echo The first argument passed from the command line is: $1
echo The second argument passed from the command line is: $2
echo The third argument passed from the command line is: $3
echo All of the arguments passed from the command line are : $*
echo All done with $0
exit 0
#
# ./script.sh A B C
The name of this program is: ./script.sh
The first argument passed from the command line is: A
The second argument passed from the command line is: B
The third argument passed from the command line is: C
All of the arguments passed from the command line are : A B C
All done with ./script.sh
```

### Command substitution
You may need to substitute the result of a command as a portion of another command. It can be done in two ways:

1. By enclosing the inner command with backticks (`)
2. By enclosing the inner command in $( )

No matter the method, the innermost command will be executed in a newly launched shell environment, and the standard output of the shell will be inserted where the command substitution was done. Virtually any command can be executed this way. Both of these methods enable command substitution; however, the second method allows command nesting.
```
# cat ./count.sh
#!/bin/bash
echo "The " $1 " contains " $(wc -l < $1) " lines."
echo $?
# ./count.sh /var/log/messages
The  /var/log/messages  contains  114  lines.
0
```
In the above example, the output of the inner command becomes the argument for the outer command.

### The if statement
Conditional decision making using an if statement, is a basic construct that any useful programming or scripting language must have. When an if statement is used, the ensuing actions depend on the evaluation of specified conditions such as:

*. Numerical or string comparisons
*. Return value of a command (0 for success)
*. File existence or permissions

In compact form, the syntax of an if statement is:
```
if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi
```
A more general definition is:
```
if condition
then
       statements
else
       statements
fi
```

The following statement checks for a file argument, and if it is found, then it displays a message
```
#!/bin/bash
if [ -f $1 ]
then
    echo "The " $1 " contains " $(wc -l < $1) " lines.";
    echo $?
fi
# ./count.sh /etc/passwd
The  /etc/passwd  contains  35  lines.
0
```

Following options for file check

|Option|Action|
|------|------|
|-e file|	Check if the file exists.|
|-d file|	Check if the file is a directory.|
|-f file|	Check if the file is a regular file.|
|-s file|	Check if the file is of non-zero size.|
|-g file|	Check if the file has sgid set.|
|-u file|	Check if the file has suid set.|
|-r file|	Check if the file is readable.|
|-w file|	Check if the file is writable.|
|-x file|	Check if the file is executable.|

You can use the if statement to compare strings. The syntax is as follows:
```
if [ string1 == string2 ]
then
   ACTION
fi
```

Or to compare numbers, as follows:
```
if [ exp1 OPERATOR exp2 ]
then
   ACTION
fi
```

The options for operators are:

Following options for file check

|Option|Action|
|------|------|
|-eq|Equal to|
|-ne|Not equal to|
|-gt|Greater than|
|-lt|Less than|
|-ge|Greater than or equal to|
|-le|Less than or equal to|


text:
### The file streams
When commands are executed, by default there are three standard file streams or descriptors always open for use:

1. standard input or **stdin**
2. standard output or **stdout**
3. standard error or **stderr**

Usually, **stdin** is your keyboard, **stdout** and **stderr** are printed on your terminal; often **stderr** is redirected to an error logging file. The **stdin** is often supplied by directing input to come from a file or from the output of a previous command through a pipe. The **stdout** is also often redirected into a file. Since **stderr** is where error messages are written, often nothing will go there.

In Linux, all open files are represented internally by what are called file descriptors. Simply put, these are represented by numbers starting at zero. The **stdin** is file descriptor 0, **stdout** is file descriptor 1, and **stderr** is file descriptor 2. Typically, if other files are opened in addition to these three, which are opened by default, they will start at file descriptor 3 and increase from there.

We can redirect the three standard filestreams so that we can get input from either a file or another command instead of from our keyboard, and we can write output and errors to files or send them as input for subsequent commands. For example, having a program *called do_something* that reads from **stdin** and writes to **stdout** and **stderr**, we can change its input source:
```
$ do_something < input-file
```
If you want to send the output to a file, use the this as in:
```
$ do_something > output-file
```
We can pipe the output of one command or program into another as its input.
```
$ command1 | command2 | command3
```
The above represents what we often call a _pipeline_ and allows linux to combine the actions of several commands into one.

### Search for files
The ``locate`` utility performs a search through a previously constructed database of files and directories on your system, matching all entries that contain a specified character string. The ``locate`` utilizes the database created by another program, ``updatedb``. Most Linux systems run this automatically once a day. However, you can update it at any time by just running ``updatedb`` from the command line as the root user.
```
# yum install -y mlocate
# updatedb
# locate zip
```
The result of ``locate`` utility can sometimes result in a very long list. To get a shorter more relevant list we can use the ``grep`` program as a filter. It will print only the lines that contain one or more specified strings as in:
```
$ locate zip | grep bin
/usr/bin/gpg-zip
/usr/bin/gunzip
/usr/bin/gzip
/usr/bin/zipdetails
```
which will list all files and directories with both "zip" and "bin" in their name.

Wildcards can be used in search for a filename containing specific characters.

|Wildcards|Result|
|---------|-----------|
|?     |Matches any single character|
|*     |Matches any string of characters|
|[set] |Matches any character not in the set of characters|
|[!set]|Matches any character not in the set of characters|

The ``find`` is extremely useful and often-used utility program in the daily life of a Linux system administrator. It recurses down the filesystem tree from any particular directory (or set of directories) and locates files that match specified conditions. The default <pathname> is always the present working directory.
```
$ find /var -name *.log
/var/log/audit/audit.log
/var/log/tuned/tuned.log
/var/log/anaconda/anaconda.log
/var/log/anaconda/anaconda.program.log
/var/log/anaconda/anaconda.packaging.log
/var/log/anaconda/anaconda.storage.log
```
When no arguments are given, ``find`` lists all files in the current directory and all of its subdirectories.

Searching for files and directories named "gcc":
```
$ find /usr -name gcc
```
Searching only for directories named "gcc":
```
$ find /usr -type d -name gcc
```
Searching only for regular files named "test1":
```
$ find /usr -type f -name test1
```
Another good use of ``find`` is being able to run commands on the files that match your search criteria. To find and remove all files that end with .swp:
```
$ find -name "*.swp" -exec rm {} ’;’
$ find -name "*.swp" -ok rm {} \;
```
The {} is a place holder that will be filled with all the file names that result from the find expression, and the preceding command will be run on each one individually. Note that you have to end the command with either ``‘;’`` or ``\;`` Both forms are fine. The second form behaves the same as the first one except that find will prompt you for permission before executing the command. This makes it a good way to test your results before blindly executing any potentially dangerous commands.

It is sometimes the case that you wish to find files according to attributes such as when they were created, last used, etc, or based on their size. Both are easy to accomplish.

Finding based on time:
```
$ find / -ctime 3
```

Here, _-ctime_ is when the inode meta-data (i.e., file ownership, permissions, etc) last changed; it is often, but not necessarily when the file was first created. You can also search for accessed/last read _-atime_ or modified/last written _-mtime_ times. The number is the number of days and can be expressed as either a number (n) that means exactly that value, +n which means greater than that number, or -n which means less than that number.

Finding based on sizes:
```
$ find / -size +10M
```
To find files greater than 10 MB in size.

### Manage files
Use the following utilities to view files:

|Command|Usage|
|-------|-----------|
|cat  |Used for viewing files that are not very long|
|tac  |Used to look at a file backwards, starting with the last line|
|less |Used to view larger files because it is a paging program; it pauses at each screenful of text, provides scroll-back capabilities, and lets you search and navigate within the file.|
|tail |Used to print the last 10 lines of a file by default. You can change the number of lines by doing -n 15 or just -15 if you wanted to look at the last 15 lines instead of the default|
|head |The opposite of tail; by default it prints the first 10 lines of a file|

The ``touch`` command is often used to set or update the access, change, and modify times of files. By default it resets a file's time stamp to match the current time.

However, you can also create an empty file using touch:
```
$ touch <filename>
```
This is normally done to create an empty file as a placeholder for a later purpose.
The -t option allows you to set the date and time stamp of the file.
To set the time stamp to a specific time:
```
$ touch -t 03201600 <filename>
```
This sets the file, myfile's, time stamp to 4 p.m., March 20th (03 20 1600).

The ``mkdir`` command is used to create a directory. Removing a directory is simply done with ``rmdir`` command. The directory must be empty or it will fail.
```
# mkdir ./test
# rmdir ./test
#
# mkdir ./test
# mkdir ./test/inside
# rmdir ./test
rmdir: failed to remove ‘test’: Directory not empty
# rm -rf ./test
# ls ./test
ls: cannot access ./test: No such file or directory
```

### Compare files
The ``diff`` command is used to compare files and directories.

```
$ cat file1.txt
Amor, ch'a nullo amato amar perdona,
Mi prese del costui piacer si forte,
Che, come vedi, ancor non m'abbandona.
$
$  cat file2.txt
amor, ch'a nullo amato amar perdona,
mi prese del costui piacer si forte,
che, come vedi, ancor non m'abbandona.
$
$ diff  file1.txt file2.txt
< Amor, ch'a nullo amato amar perdona,
< Mi prese del costui piacer si forte,
< Che, come vedi, ancor non m'abbandona.
---
> amor, ch'a nullo amato amar perdona,
> mi prese del costui piacer si forte,
> che, come vedi, ancor non m'abbandona.
$
$ diff -c file1.txt file2.txt
*** file1.txt   2015-02-17 16:10:03.781804799 +0100
--- file2.txt   2015-02-17 16:13:41.059088459 +0100
***************
! Amor, ch'a nullo amato amar perdona,
! Mi prese del costui piacer si forte,
! Che, come vedi, ancor non m'abbandona.
--- 1,3 ----
! amor, ch'a nullo amato amar perdona,
! mi prese del costui piacer si forte,
! che, come vedi, ancor non m'abbandona.
$
$  diff -i file1.txt file2.txt
$
```
### The file utility
In Linux, a file's extension often does not categorize it the way it might in other operating systems. One can not assume that a file named ``file.txt`` is a text file and not an executable program. In Linux a file name is generally more meaningful to the user of the system than the system itself; in fact most applications directly examine a file's contents to see what kind of object it is rather than relying on an extension. The real nature of a file can be ascertained by using the ``file`` utility. For the file names given as arguments, it examines the contents and certain characteristics to determine whether the files are plain text, shared libraries, executable programs, scripts, or something else.

```
$ file /etc/resolv.conf
/etc/resolv.conf: ASCII text
```

repo_name: MinhKMA/Linux-Tutorial

mime_type: text/plain


text:
## Cluster Basics
A cluster is two or more computers (cluster members) that work together to perform a task, for example, provide high availability of a given service. High availability clusters provide highly available services by eliminating single points of failure and by failing over services from one cluster member to another in case a node becomes inoperative.

Typically, services in a high availability cluster maintain data integrity as one cluster member takes over control of a service from another cluster member. Node failures in a high availability cluster are not visible from clients outside the cluster.

In the Linux world, there are many cluster tools to achieve High Availability of a resource. The most used is **Pacemaker**. A cluster configured with Pacemaker comprises separate component daemons that monitor cluster membership, scripts that manage the services, and resource management subsystems that monitor the resources. The following components form the Pacemaker architecture:

1. **Cluster Information Base**: the Pacemaker information daemon distributes and synchronizes the cluster configuration and status information from the Designated Coordinator (DC) of the cluster to all other cluster members. The DC is one cluster member designated to store the cluster state.

2. **Cluster Resource Management Daemon**: cluster resources managed by this component can be queried by client systems, moved, instantiated, and changed when needed. Each cluster node also includes a local resource manager daemon that acts as an interface between Cluster Resource Manager daemon and the resource itself. The local resource manager passes commands from Cluster Resource Manager to agents, such as starting and stopping and relaying resurce status information.

3. **Fencing Manager**: often deployed in conjunction with a power supply switch, this component acts as a cluster resource in Pacemaker that processes fence requests, forcefully powering down nodes and removing them from the cluster to ensure data integrity. Pacemaker use a fencing technique called **STONITH** (Shoot The Other Node In The Head) intended to prevent data corruption caused by faulty nodes in a cluster that are unresponsive but still accessing application data (the so called "Split Brain Scenario").

### Install a simple Cluster
Pacemaker requires a messaging layer daemon, called **Corosync** that provides a cluster membership and closed communication model for creating replicated state machines, on top of which Pacemaker can run. Corosync can be seen as the underlying system that connects the cluster nodes together, while Pacemaker monitors the cluster and takes action in the event of a failure. In addition, we are going to use **PCS**, a command line interface that interacts with both Corosync and Pacemaker.

This example will be also used to explain the basic concepts of Linux Clustering.

                                      |
    +----------------------+          |          +----------------------+
    | Node01               |          |          | Node02               |
    | holly.noverit.com    +----------+----------+ benji.noverit.com    |
    | 10.10.10.22          |                     | 10.10.10.24          |
    +----------------------+                     +----------------------+

Install, start and enable Pacemaker and PCS on both the nodes. Because Corosync is a dependency to Pacemaker, it's usually a better idea to simply install Pacemaker and let the system decide which Corosync version should be installed.

    [root@holly ~]# yum -y install pacemaker
    [root@holly ~]# yum -y install pcs
    [root@holly ~]# systemctl start pcsd
    [root@holly ~]# systemctl enable pcsd

    [root@benji ~]# yum -y install pacemaker
    [root@benji ~]# yum -y install pcs
    [root@benji ~]# systemctl start pcsd
    [root@benji ~]# systemctl enable pcsd

Pacemaker need to communicate beween nodes, enable the port firewall on each node, which by default is 2224 over TCP. Otherwise, disable the firewall if you are working in a secure setup.

    [root@holly ~]# systemctl stop firewalld
    [root@holly ~]# systemctl disable firewalld
    [root@benji ~]# systemctl stop firewalld
    [root@benji ~]# systemctl disable firewalld

The PCS utility creates a user during installation, named ``hacluster``, with a disabled password. We need to define a password for this user on both servers. This will enable PCS to perform tasks such as synchronizing the Corosync configuration on multiple nodes, as well as starting and stopping the cluster.

    [root@holly ~]# passwd hacluster
    Changing password for user hacluster
    [root@benji ~]# passwd hacluster
    Changing password for user hacluster

Use the same password on both servers. We are going to use this password to configure the cluster in the next step. Please, note that the user ``hacluster`` has no interactive shell or home directory associated with its account, which means it's not possible to log into the server using its credentials.

Only on a node of the cluster, authenticate the cluster nodes

    [root@holly ~]# pcs cluster auth holly benji
    Username: hacluster
    Password:
    holly: Authorized
    benji: Authorized

From the same node, generate the Corosync configuration

    [root@holly ~]# pcs cluster setup --name mycluster holly benji
    Shutting down pacemaker/corosync services...
    Redirecting to /bin/systemctl stop  pacemaker.service
    Redirecting to /bin/systemctl stop  corosync.service
    Killing any remaining services...
    Removing all cluster configuration files...
    holly: Succeeded
    benji: Succeeded
    Synchronizing pcsd certificates on nodes holly, benji...
    benji: Success
    holly: Success
    Restaring pcsd on the nodes in order to reload the certificates...
    benji: Success
    holly: Success

This will generate a cluster configuration file (i.e. the cluster information base) located at ``/etc/corosync/corosync.conf`` based on the parameters provided to the cluster setup command:

    [root@holly ~]# cat /etc/corosync/corosync.conf
    totem {
        version: 2
        secauth: off
        cluster_name: mycluster
        transport: udpu
    }
    nodelist {
        node {
            ring0_addr: holly
            nodeid: 1
        }
        node {
            ring0_addr: benji
            nodeid: 2
        }
    }
    quorum {
        provider: corosync_votequorum
        two_node: 1
    }
    logging {
        to_logfile: yes
        logfile: /var/log/cluster/corosync.log
        to_syslog: yes
    }

Start and enable the cluster

    [root@holly ~]# pcs cluster start --all
    benji: Starting Cluster...
    holly: Starting Cluster...

    [root@holly ~]# pcs cluster enable --all
    holly: Cluster Enabled
    benji: Cluster Enabled

Check the status of the cluster

    [root@holly ~]# pcs status
    Cluster name: mycluster
    WARNING: no stonith devices and stonith-enabled is not false
    Last updated: Sat Jul 16 17:20:14 2016
    Stack: corosync
    Current DC: holly (version 1.1.13-10.el7_2.2-44eb2dd) - partition with quorum
    2 nodes and 0 resources configured
    Online: [ benji holly ]
    Full list of resources: -
    PCSD Status:
        holly: Online
        benji: Online
    Daemon Status:
        corosync: active/enabled
        pacemaker: active/enabled
        pcsd: active/enabled

Some interesting info:

  1. The Designated Coordinator (DC) is the node holly where from we configured the cluster
  2. There are only 2 nodes onlyne and no resurces
  3. The name of the cluster is "mycluster"
  4. All daemons: corosync, pacemaker and pcsd are active and enabled
  5. Fencing (stonith) is enabled but no fencing devices are configured

Confirm that both nodes joined the cluster by running the following command on any of the servers

    [root@holly ~]# pcs status corosync
    Membership information
    ----------------------
        Nodeid      Votes Name
             1          1 holly (local)
             2          1 benji
    [root@holly ~]#

Because our cluster does not manage shared data resources, there is no risk to have a Split Brain Scenario and so we are going to disable fencing

    [root@holly ~]# pcs property set stonith-enabled=false

Cluster quorum as a concept (see later) makes no sense in a two-node scenario, because you only have it when more than half the nodes are available, so we'll disable it too.

    [root@holly ~]# pcs property set no-quorum-policy=ignore

To see a recap of the Cluster properties

    [root@benji ~]# pcs property list
    Cluster Properties:
     cluster-infrastructure: corosync
     cluster-name: mycluster
     dc-version: 1.1.13-10.el7_2.2-44eb2dd
     have-watchdog: false
     no-quorum-policy: ignore
     stonith-enabled: false

Cluster nodes should not be halted as other standard nodes. It's always a best practice to shutdown the cluster first and then shutdown the system.

To stop the cluster on a signle node

    [root@benji ~]# pcs cluster stop
    Stopping Cluster (pacemaker)... Stopping Cluster (corosync)...
    [root@benji ~]# pcs cluster status
    Error: cluster is not currently running on this node

Or on all nodes of the cluster

    [root@holly ~]# pcs cluster stop --all
    holly: Stopping Cluster (pacemaker)...
    benji: Stopping Cluster (pacemaker)...
    benji: Stopping Cluster (corosync)...
    holly: Stopping Cluster (corosync)...
    [root@holly ~]#

### Add a resource to the Cluster
Lets add a cluster service, we'll choose one doesn't require too much configuration and works everywhere to make things easy.

Install and configure an HTTP Server on both the nodes. Note: not need to start/enable the service.

    [root@benji ~]# yum install -y httpd
    [root@benji ~]# echo "Hello Benji" > /var/www/html/index.html
    [root@holly ~]# yum install -y httpd
    [root@holly ~]# echo "Hello Holly" > /var/www/html/index.html

Add the HTTP Server as resource of the cluster

    [root@benji ~]# pcs resource create HTTPServer ocf:heartbeat:apache \
    > configfile=/etc/httpd/conf/httpd.conf \
    > op monitor interval=1min

The name of the resource is ``HTTPServer`` of type ``ocf:heartbeat:apache``. The type defined for a resource tell the cluster which script to use for the resource, the provider of the script and what standards it conforms to. In that case, the standard is **Open Cluster Framework**. The command tells also Pacemaker to check the health of this service every 60 seconds by calling the agent's monitor action.

Add a Virtual IP address as second resource of the cluster. This IP Address will be used by clients of the cluster to access the HTTP Server resource

    [root@benji ~]# pcs resource create VirtualIP ocf:heartbeat:IPaddr2 \
    > ip=10.10.10.23 \
    > cidr_netmask=24 \
    > op monitor interval=30s

The name of the resource is ``VirtualIP`` of type ``ocf:heartbeat:IPaddr2``. The command tells also Pacemaker to check the health of this service every 30 seconds by calling the agent's monitor action. The Virtual IP resource binds the IP address specified in the command above to the network interface of the node owning the Virtual IP resources. This Virtual IP is floating from one node to the other, depending on the status of the node itself:

    [root@benji ~]# ip addr show ens32
    2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
        link/ether 00:0c:29:20:d2:dd brd ff:ff:ff:ff:ff:ff
        inet 10.10.10.24/24 brd 10.10.10.255 scope global ens32
           valid_lft forever preferred_lft forever
        inet 10.10.10.23/24 brd 10.10.10.255 scope global secondary ens32
           valid_lft forever preferred_lft forever

    [root@holly ~]# ip addr show ens32
    2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
        link/ether 00:0c:29:77:68:56 brd ff:ff:ff:ff:ff:ff
        inet 10.10.10.22/24 brd 10.10.10.255 scope global ens32
           valid_lft forever preferred_lft forever

Set that HTTPServer and VirtualIP are always on a same node

    [root@benji ~]# pcs constraint colocation add HTTPServer with VirtualIP

Set that the order of starting is VirtualIP first and then HTTPServer. This is required to assure there is always an IP Address where to send client's requests

    [root@holly ~]# pcs constraint order VirtualIP then HTTPServer
    Adding VirtualIP HTTPServer (kind: Mandatory) (Options: first-action=start then-action=start)

See the status of both the resources

    [root@benji ~]# pcs status resources
     VirtualIP      (ocf::heartbeat:IPaddr2):       Started by benji
     HTTPServer     (ocf::heartbeat:apache):        Started by holly

and resources constraints

    [root@holly ~]# pcs constraint
    Location Constraints:
    Ordering Constraints:
      start VirtualIP then start HTTPServer (kind:Mandatory)
    Colocation Constraints:
      HTTPServer with VirtualIP (score:INFINITY)

Now we can access the HTTP Server from a web client by pointing to the Virtual IP Address 10.10.10.23

    [stack@director ~]$ curl http://10.10.10.23
    Hello Benji

To test Cluster failover, stop current active node manually

    [root@benji html]# pcs cluster stop
    Stopping Cluster (pacemaker)... Stopping Cluster (corosync)...

and make sure resource will switch to the other node

    [stack@director ~]$ curl http://10.10.10.23
    Hello Holly

### Accessing the cluster management form a Web GUI
Cluster management is possible also via a Web GUI. Point the browser to the primary member node and login as the ``hacluster`` user

    https://<primary_node_ip>:2224


text:
### Linux processes
A **process** is simply an instance of one or more related tasks (**threads**) executing on the same machine. It is not the same as a program or a command; a single program may actually start several processes simultaneously. Some processes are independent of each other and others are related. A failure of one process may or may not affect the others running on the system. Processes use many system resources, such as memory, CPU cycles, and peripheral devices such as printers and displays. The operating system (especially the kernel) is responsible for allocating a proper share of these resources to each process and ensuring overall optimum utilization.

A terminal window, is a process that runs as long as needed. It allows users to execute programs and access resources in an interactive environment. You can also run programs in the background, which means they become detached from the shell. Processes can be of different types according to the task being performed.

|Type|Description|
|--------|---------|
|Interactive |Need to be started by a user, either at a command line or through a graphical interface such as an icon or a menu selection.|
|Batch |Automatic processes which are scheduled from and then disconnected from the terminal. These tasks are queued and work on a FIFO (First In, First Out) basis.|
|Daemons|Server processes that run continuously. Many are launched during system startup and then wait for a user or system request indicating that their service is required.|
|Threads|Lightweight processes. These are tasks that run under the umbrella of a main process, sharing memory and other resources, but are scheduled and run by the system on an individual basis.|
|Kernel Threads|Kernel tasks that users neither start nor terminate and have little control over. These may perform actions like moving a thread from one CPU to another, or making sure input/output operations to disk are completed.|

When a process is in the **running state**, it means it is either currently executing instructions on a CPU, or is waiting for a share (or time slice) so it can run. A critical kernel routine called the **scheduler** constantly shifts processes in and out of the CPU, sharing time according to relative priority, how much time is needed and how much has already been granted to a task. All processes in this state reside on a run queue and on a computer with multiple CPUs there is a run queue on each. Sometimes processes go into the **sleep** state, generally when they are waiting for something to happen before they can resume, perhaps for the user to type something. In this condition a process is sitting in a wait queue. There are some other less frequent process states, especially when a process is terminating. Sometimes a child process completes but its parent process has not asked about its state. Such a process is said to be in a **zombie** state; it is not really alive but still shows up in the system's list of processes.

At any given time there are always multiple processes being executed. The operating system keeps track of them by assigning each a unique process ID or **PID** number. The PID is used to track process state, cpu usage, memory use, precisely where resources are located in memory, and other characteristics. New PIDs are usually assigned in ascending order as processes are born. Thus PID 1 denotes the **init** process (initialization process), and succeeding processes are gradually assigned higher numbers.

At any given time, many processes are running on the system. However, a **CPU** can actually accommodate only one task at a time, just like a car can have only one driver at a time. Some processes are more important than others so Linux allows you to set and manipulate process priority. Higher priority processes are granted more time on the processor. The **priority** for a process can be set by specifying a nice value, or **niceness**, for the process. The lower the nice value, the higher the priority. Low values are assigned to important processes, while high values are assigned to processes that can wait longer. A process with a high nice value simply allows other processes to be executed first. In Linux, a nice value of -20 represents the highest priority and 19 represents the lowest. You can also assign a real-time priority to time-sensitive tasks, such as controlling machines or collecting incoming data. This is just a very high priority and is not to be confused with what is called hard real time which is conceptually different, and has more to do with making sure a job gets completed within a very well-defined time window.

### Running processes
The ``ps`` command provides information about currently running processes, keyed by **PID**. If you want a repetitive update of this status, you can use the ``top`` command or commonly installed variants such as ``htop`` or ``atop`` from the command line. The ``ps`` command has many options for specifying exactly which tasks to examine, what information to display about them, and precisely what output format should be used.

Without options ``ps`` will display all processes running under the current shell. You can use the `` ps -u`` to display information of processes for a specified username. The command ``ps -ef`` displays all the processes in the system in full detail. The command ``ps -eLf`` goes one step further and displays one line of information for every thread (a process can contain multiple threads).

```
# ps -u adriano
  PID TTY          TIME CMD
  847 ?        00:00:00 sshd
  848 pts/2    00:00:00 bash
 1070 ?        00:00:00 sshd
 1071 pts/3    00:00:00 bash
 6475 pts/3    00:00:00 top
```

The ``pstree`` command displays the processes running on the system in the form of a tree diagram showing the relationship between a process and its parent process and any other processes that it created. Repeated entries of a process are not displayed, and threads are displayed in curly braces.
```
# yum install -y psmisc
# pstree
# systemd─┬─agetty
          ├─auditd───{auditd}
          ├─avahi-daemon───avahi-daemon
          ├─crond
          ├─dbus-daemon───{dbus-daemon}
          ├─firewalld───{firewalld}
          ├─iprdump
          ├─iprinit
          ├─iprupdate
          ├─lvmetad
          ├─master─┬─pickup
          │        └─qmgr
          ├─polkitd───5*[{polkitd}]
          ├─rsyslogd───2*[{rsyslogd}]
          ├─sshd───sshd───bash───pstree
          ├─systemd-journal
          ├─systemd-logind
          ├─systemd-udevd
          └─tuned───4*[{tuned}]
```

To terminate a process you can type ``kill -SIGKILL <pid>`` or ``kill -9 <pid>``. Note however, you can only kill your own processes: those belonging to another user are off limits unless you are root.

While a static view of what the system is doing is useful, monitoring the system performance live over time is also valuable. One option would be to run the ``ps`` command at regular intervals. A better alternative is to use ``top`` to get constant real-time updates (every two seconds by default). The ``top`` command clearly highlights which processes are consuming the most CPU cycles and memory.
```
top - 15:40:31 up 4 days,  2:13,  1 user,  load average: 0.77, 0.66, 0.45
Tasks: 244 total,   2 running, 241 sleeping,   0 stopped,   1 zombie
%Cpu(s):  6.5 us,  1.3 sy,  0.0 ni, 88.3 id,  3.7 wa,  0.0 hi,  0.2 si,  0.0 st
KiB Mem:   3801380 total,  3642652 used,   158728 free,       24 buffers
KiB Swap:  4079612 total,     3072 used,  4076540 free.   326620 cached Mem

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
 1367 glance    20   0  351800  54996   5928 S   1.3  1.4  64:32.28 glance-api
 1373 nova      20   0  383444  73304   6768 S   1.3  1.9  68:25.51 nova-api
 1365 keystone  20   0  353108  58340   6192 S   1.0  1.5  67:16.01 keystone-all
 1369 cinder    20   0  365404  60120   6632 S   1.0  1.6  68:38.74 cinder-api
 1371 cinder    20   0  287924  30584   4924 S   1.0  0.8  68:08.01 cinder-volume
 1380 nova      20   0  348120  46568   6580 S   1.0  1.2  68:19.02 nova-conductor
 1408 ceilome+  20   0  254312  20560   4260 R   1.0  0.5  64:28.69 ceilometer-agen
...
```
The first line of the ``top`` output displays a quick summary of what is happening in the system including:

1. How long the system has been up
2. How many users are logged on
3. What is the load average

The load average determines how busy the system is. A load average of 1.00 per CPU indicates a fully subscribed, but not overloaded, system. If the load average goes above this value, it indicates that processes are competing for CPU time. If the load average is very high, it might indicate that the system is having a problem, such as a **runaway** process (a process in a non-responding state).

The second line of the ``top`` output displays the total number of processes, the number of running, sleeping, stopped and zombie processes. Comparing the number of running processes with the load average helps determine if the system has reached its capacity or perhaps a particular user is running too many processes. The stopped processes should be examined to see if everything is running correctly.

The third line of the ``top`` output indicates how the CPU time is being divided between the users (**us**) and the kernel (**sy**) by displaying the percentage of CPU time used for each. The percentage of user jobs running at a lower priority (**ni**) is then listed. Idle mode (**id**) should be low if the load average is high, and vice versa. The percentage of jobs waiting (**wa**) for I/O is listed. Interrupts include the percentage of hardware (**hi**) vs. software interrupts (**si**). Steal time (**st**) is generally used with virtual machines, which has some of its idle CPU time taken for other uses.

The fourth and fifth lines of the ``top`` output indicate memory usage, which is divided in two categories:

1. Physical memory (RAM) – displayed on line 4.
2. Swap space – displayed on line 5.
3. Both categories display total memory, used memory, and free space.

You need to monitor memory usage very carefully to ensure good system performance. Once the physical memory is exhausted, the system starts using swap space as an extended memory pool, and since accessing disk is much slower than accessing memory, this will negatively affect system performance. If the system starts using swap often, you can add more swap space. However, adding more physical memory should also be considered.

Each line in the process list of the ``top`` output displays information about a process. By default, processes are ordered by highest CPU usage. The following information about each process is displayed:

* Process Identification Number (PID)
* Process owner (USER)
* Priority (PR) and nice values (NI)
* Virtual (VIRT), physical (RES), and shared memory (SHR)
* Status (S)
* Percentage of CPU (%CPU) and memory (%MEM) used
* Execution time (TIME+)
* Command (COMMAND)

To control the healt of a system, the average load of the system should be checked first. Assuming our system is a single-CPU system, the 0.25 means that for the past minute, on average, the system has been 25% utilized. 0.12 in the next position means that over the past 5 minutes, on average, the system has been 12% utilized; and 0.15 in the final position means that over the past 15 minutes, on average, the system has been 15% utilized. If we saw a value of 1.00 in the second position, that would imply that the single-CPU system was 100% utilized, on average, over the past 5 minutes; this is good if we want to fully use a system. A value over 1.00 for a single-CPU system implies that the system was over-utilized: there were more processes needing CPU than CPU was available. If we had more than one CPU, say a quad-CPU system, we would divide the load average numbers by the number of CPUs. In this case, for example, seeing a 1 minute load average of 4.00 implies that the system as a whole was 100% (4.00/4) utilized during the last minute. Short term increases are usually not a problem. A high peak you see is likely a burst of activity, not a new level. For example, at start up, many processes start and then activity settles down. If a high peak is seen in the 5 and 15 minute load averages, it would may be cause for concern.

### Background and foreground processes
Linux supports **background** and **foreground** job processing. Foreground jobs run directly from the shell, and when one foreground job is running, other jobs need to wait for shell access until it is completed. This is fine when jobs complete quickly. But this can have an adverse effect if the current job is going to take a long time to complete. In such cases, you can run the job in the background and free the shell for other tasks. The background job will be executed at lower priority, which, in turn, will allow smooth execution of the interactive tasks, and you can type other commands in the terminal window while the background job is running. By default all jobs are executed in the foreground. This You can put a job in the background:

```
# updatedb &
[1] 7437
# jobs
[1]+  Done                    updatedb
#
```

### Scheduling processes
The ``at`` utility program is used to execute any non-interactive command at a specified time. The ``at`` jobs is picked by the ``atd`` service.
```
# yum install -y at
# systemctl start atd
# systemctl enable atd
# at now + 5 minutes
at> pstree
at> <EOT>
job 9 at Sat Feb 21 16:28:00 2015
```

The ``atq`` command is used to list the scheduled jobs by the ``at`` command.
```
# atq
9       Sat Feb 21 16:28:00 2015 a root
```

The ``cron`` utility is a time-based scheduling utility program. It can launch routine background jobs at specific times and or days on an on-going basis. cron is driven by a configuration file called ``/etc/crontab`` which contains the various shell commands that need to be run at the properly scheduled times. There are both system-wide crontab files and individual user-based ones. Each line of a crontab file represents a job, and is composed of an expression, followed by a shell command to execute. The ``crontab -e`` command will open the crontab editor to edit existing jobs or to create new jobs. Each line of the crontab file will contain 6 fields:

1. MIN	Minutes	0 to 59
2. HOUR	Hour field	0 to 23
3. DOM	Day of Month	1-31
4. MON	Month field	1-12
5. DOW	Day Of Week	0-6 (0 = Sunday)
6. CMD	Command	Any command to be executed

For example, the entry
```
* * * * * /usr/local/bin/execute/this/script.sh
```
will schedule a job to execute the script every minute of every hour of every day of the month, and every month and every day in the week. The entry
```
30 08 10 06 * /home/sysadmin/full-backup
```
will schedule a full-backup at 8.30am, 10-June irrespective of the day of the week.

### Delaying processes
Sometimes a command or job must be delayed or suspended. Suppose, for example, an application has read and processed the contents of a data file and then needs to save a report on a backup system. If the backup system is currently busy or not available, the application can be made to sleep until it can complete its work. Such a delay might be to mount the backup device and prepare it for writing. The ``sleep`` command suspends execution for at least the specified period of time, which can be given as the number of seconds (the default), minutes, hours or days. After that time has passed, the execution will resume.

```
# vi script.sh
#!/bin/bash
echo "The system will go to sleep fo 30 seconds ..."
sleep 15
echo "The system is awaked"
# chmod u+x script.sh
# ./script.sh
The system will go to sleep fo 30 seconds ...
The system is awaked
#
```


text:
## System Services
Systemd is the new init system for modern Linux distributions replacing the old init based on ``/etc/init.d/script``. It provides many powerful features for starting, stopping and managing processes. Here is an example to create a MineCraft service for systemd. MainCraft is a Java based game from Mojang.

First, install the game and its envinronment.
```
# yum install java-1.8.0-openjdk.x86_64
# which java
/bin/java
# mkdir /root/Minecraft
# cd /root/Minecraft
# wget -O minecraft_server.jar https://s3.amazonaws.com/Minecraft.Download/versions/1.8.6/minecraft_server.1.8.6.jar
# ls -lrt
-rw-r--r--. 1 root root 9780573 May 25 11:47 minecraft_server.jar
-rw-r--r--. 1 root root       2 Jun  1 11:48 whitelist.json
-rw-r--r--. 1 root root     180 Jun  1 12:01 eula.txt
drwxr-xr-x. 2 root root    4096 Jun  1 16:09 logs
-rw-r--r--. 1 root root     785 Jun  1 16:09 server.properties
-rw-r--r--. 1 root root       2 Jun  1 16:09 banned-players.json
-rw-r--r--. 1 root root       2 Jun  1 16:09 banned-ips.json
-rw-r--r--. 1 root root       2 Jun  1 16:09 ops.json
-rw-r--r--. 1 root root     109 Jun  1 16:10 usercache.json
drwxr-xr-x. 8 root root    4096 Jun  1 16:37 world
```

The MineCraft server can be started at command line, by issuing the following command
```
# java -Xmx1024M -Xms1024M -jar minecraft_server.jar nogui
```

Alternately, a systemd configuration file can be created to start, stop, and check the status of the server as a standard system service by using the ``systemctl`` utility
```
# vi /lib/systemd/system/minecraftd.service
[Unit]
Description=Minecraft Server
After=syslog.target network.target

[Service]
Type=simple
WorkingDirectory=/root/Minecraft
ExecStart=/bin/java -Xmx1024M -Xms1024M -jar minecraft_server.jar nogui
SuccessExitStatus=143
Restart=on-failure

[Install]
WantedBy=multi-user.target

# systemctl start minecraftd
# systemctl status minecraftd
minecraftd.service - Minecraft Server
   Loaded: loaded (/usr/lib/systemd/system/minecraftd.service; disabled)
   Active: active (running) since Mon 2015-06-01 16:00:12 UTC; 18s ago
 Main PID: 20975 (java)
   CGroup: /system.slice/minecraftd.service
           └─20975 /bin/java -Xmx1024M -Xms1024M -jar minecraft_server.jar nogui

# systemctl stop minecraftd
```
Note: the ``SuccessExitStatus=143`` is required when a process does not handle the exit signal properly. This is almost always due to programming errors, and is pretty common with Java applications of all types. To avoid a failed status of the MainCraft when stopping the service, the exit code 143 needs to be added into the unit file as a "success" exit status.

The ``systemctl`` utility can be used to enable/disable the service at startup
```
# systemctl enable minecraftd
ln -s '/usr/lib/systemd/system/minecraftd.service' '/etc/systemd/system/multi-user.target.wants/minecraftd.service'
# systemctl is-enabled minecraftd
enabled
# systemctl disable minecraftd
```

Here another example
```
# cat /etc/systemd/system/redmined.service
[Unit]
Description=Redmine Server
After=syslog.target network.target

[Service]
Type=simple
PermissionsStartOnly=true
WorkingDirectory=/home/redmine/redmine
ExecStartPre=/usr/sbin/iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
ExecStart=/usr/bin/ruby bin/rails server -b 0.0.0.0 -p 8080 webrick -e production
User=redmine
Group=redmine
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=redmined
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

```


text:
public class Stack {

    /
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        StackArray sa = new StackArray(6);
        sa.push(7);
        sa.push(3);
        sa.push(2);
        sa.push(9);
        sa.push(8);
        sa.display();
        sa.push(1);
        sa.push(5);
        sa.display();
        try{
        int k = sa.peek();
         System.out.println("Peek is "+k);
            System.out.println("poped an item :" + sa.pop());
            System.out.println("poped an item :" + sa.pop());
            System.out.println("poped an item :" + sa.pop());
            System.out.println("poped an item :" + sa.pop());
            System.out.println("poped an item :" + sa.pop());
            System.out.println("poped an item :" + sa.pop());
            System.out.println("poped an item :" + sa.pop());
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
       Stack s=new Stack();
       System.out.print("binary value of 50 is : ");
       s.decimalToBinary(50);
    }

    public void decimalToBinary(int no){
        int temp = no;
        int count =0;
    while(temp!=0){
    temp=temp/2;
    count++;
    }

    StackArray myStack = new StackArray(count);
    temp = no;
    while(temp!=0){
    int rem=temp%2;
    temp=temp/2;
    myStack.push(rem);
    }
      while(!myStack.isEmpty()){
          try{
          System.out.print(myStack.pop());
      }catch(Exception e){

      }
      }
        System.out.println();
   }

}
class StackArray {
 private int maxSize; //size of stack array
 private int[] stackData;
 private int top; //top of stack
//-------------------------------------------------------------------------
 public StackArray(int s) {
     this.stackData = new int[s];
     this.maxSize = s;
     this.top = -1;
 }

 public boolean isEmpty() {
    return top == -1;
 }

 public boolean isFull() {
     return top == maxSize - 1;
 }

 public void push(int item) {
     if (isFull()){
         System.out.println("Stack is full cannot push");
         return;
     }
     stackData[++top] = item;
 }
 public int pop() throws Exception{
     if(isEmpty()){
         throw new Exception ("Stack is empty cannot pop");
     }
    return stackData[top--];
 }

 public int peek() throws Exception {
     if(isEmpty()){
     throw new Exception("Stack is empty cannot peek");
     }
     return stackData[top];
 }

 public void display() {
     System.out.println("Start printing stack data.....");
     for(int i=top;i>=0;i--){
         System.out.println(stackData[i]);
     }
     System.out.println("End printing stack data.....");
     System.out.println( );
 }
}

file_name: Merge Sorted Array.cpp

mime_type: text/x-c++


text:
#include<iostream>
using namespace std;
void knapSack(int W, int weight[], int value[], int n)
{
    int a[n + 1][W + 1];
    for (int i = 0; i <= W; i++)
    {
        a[0][i] = 0;
    }
    for (int i = 0; i <= n; i++)
    {
        a[i][0] = 0;
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=W;j++){
            if(weight[i-1] > j)
                a[i][j] = a[i-1][j];
            else
                a[i][j] = max(value[i-1] + a[i-1][j - weight[i-1]], a[i-1][j]);
        }
    }
    cout<<" Matrix :"<<endl;
    for (int i = 0; i < n+1; i++)
    {
        for (int j = 0; j< W+1; j++)
        {
            cout<<a[i][j]<<" ";
        }
        cout<<endl;
    }
    cout<<" Max : "<<a[n][W];
}
int main()
{
    int n ;
    cout<<"numbers of items"<<endl;
    cin>>n;

    int W ;
    cout<<" Capacity "<<endl;
    cin>>W;
    int value[n];
    cout<<"Enter the values"<<endl;
    for (int i=0;i<n;i++){
        cin>>value[i];
    }
    int weight[n];
    cout<<"Enter the weights"<<endl;
    for (int i=0;i<n;i++){
        cin>>weight[i];
    }
    knapSack(W, weight, value, n);

    return 0;
}


text:
import java.util.Random;
import java.util.Scanner;

public class Main {
	public static void main(String args[])
	{
		System.out.print("Enter the number of dice: ");

		// Initializing the Scanner object to read input
		Scanner input = new Scanner(System.in);
		int numberOfDice = input.nextInt();

		// Initializing the Random object for
		// generating random numbers
		Random ranNum = new Random();

		System.out.print("Hey Geek! You rolled: ");
		int total = 0;
		int randomNumber = 0;

		for (int i = 0; i < numberOfDice; i++) {

			// Generating the random number and storing it
			// in the 'randomNumber' variable
			randomNumber = ranNum.nextInt(6) + 1;
			total = total + randomNumber;
			System.out.print(randomNumber);
			System.out.print(" ");
		}

		System.out.println("");
		System.out.println("Total: " + total);
		input.close();
	}
}


text:
# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our
community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
  and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
  overall community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or
  advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
  address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
  professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
me.sameer.farooq@gmail.com.
All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series
of actions.

**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior,  harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within
the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.

Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.


text:
#include <bits/stdc++.h>
using namespace std;

#define inf 100000000

int main() {
    int n;
    cin >> n;
    int adjMatrix[n][n];
    int tempMatrix[n][n];

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> adjMatrix[i][j];
            if (adjMatrix[i][j] == 0) adjMatrix[i][j] = inf;
        }
    }

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < n; j++) {
            for (int k = 0; k < n; k++) {
                tempMatrix[j][k] = min(adjMatrix[j][k], (adjMatrix[j][i] + adjMatrix[i][k]));
            }
        }

        // Copy a 2d array: https://cplusplus.com/forum/general/263317/
        mempcpy(adjMatrix, tempMatrix, n * n * sizeof(int));  // memcpy(newArray, oldArray, totalSize)
        // copy(&tempMatrix[0][0], &tempMatrix[0][0]+n*n, &adjMatrix[0][0]);  // copy(old_starting_index, old_ending_index, new_starting_index)
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cout << adjMatrix[i][j] << " ";
        }
        cout << endl;
    }
}s


text:
#include <bits/stdc++.h>
using namespace std;
double area(double a,double b,double c)
{
	double s=(a+b+c)/2.0;
	return sqrt(s*(s-a)*(s-b)*(s-c));
}
int main() {
	int t;scanf("%d",&t);
	while(t--)
	{
		double u,v,w,U,V,W;
		cin>>u>>v>>w>>W>>V>>U;
		double u1=v*v+w*w-U*U;
		double v1=u*u+w*w-V*V;
		double w1=u*u+v*v-W*W;
		double vol=(sqrt(4*u*u*v*v*w*w-u*u*u1*u1-v*v*v1*v1-w*w*w1*w1+u1*v1*w1))/12;
		double ar=0;
		ar=area(U,V,W)+area(v,u,W)+area(w,v,U)+area(u,w,V);
		double volt=3*vol/ar;
		cout<<fixed<<setprecision(4)<<volt<<endl;
	}
	return 0;
}


text:
#include<iostream>
#include<string>
using namespace std;
struct date
{
	short day;
	string mon;
	int year;
	int month;
};
int leapyear(int year)
{
	if(year%400==0)
	{
		return 0;
	}
	else if(year%100==0)
	{
		return 1;
	}
	else if(year %4==0)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}
void increment(struct date &d)
{
	int l;
	l=leapyear(d.year);
	if(d.month==2)
	{
		if(l==0)
		{
			if(d.day<29)
			d.day+=1;
			else
			d.day=1;
			d.month+=1;
		}
		else
		{
			if(d.day<28)
			d.day+=1;
			else
			{
				d.day=1;
				d.month+=1;
			}
		}

	}

	else
	{
		if(d.month % 2 == 0 && d.month < 8)
		{
			if(d.day < 30)
			{
				d.day += 1;
			}
			else
			{
				d.day = 1;
				d.month += 1;
			}
		}
		else if(d.month % 2 != 0 && d.month > 8)
		{
			if(d.day < 30)
			{
				d.day += 1;
			}
			else
			{
				d.day = 1;
				d.month += 1;
			}
		}
		else
		{
			if(d.month == 12 && d.day == 31)
			{
				d.day= 1;
				d.month = 1;
				d.year += 1;
			}
			else
			{
				if(d.day < 31)
				{
					d.day += 1;
				}
				else
				{
					d.day = 1;
					d.month += 1;
				}
			}
		}
	}

	cout << "Incremented Date : " <<  " " << d.day << '-' << d.month << '-' << d.year << endl << endl;
}
int days_of_mon(int month, int year)
{
	int l;
	l = leapyear(year);

	// if month is february
	if(l == 0)
	{
		if(month == 2)
		{
			return 29;
		}
	}
	else
	{
		if(month == 2)
		{
			return 28;
		}
	}
	if(month % 2 == 0 && month < 8)
	{
		return 30;
	}
	else if(month % 2 != 0 && month > 8)
	{
		return 30;
	}
	else
	{
		return 31;
	}
}

void difference(struct date d, struct date d1)
{
	int y, m, c, dom;
	dom = days_of_mon(d1.month, d1.year);

	if(d.month > d1.month)
	{
		y = d1.year - d.year - 1;
		m = abs((d.month + d1.month) - 12 - 1);
		c= abs((d.day + d1.day) - dom);
	}
	else
	{
		y = d1.year - d.year;
		m = d1.month - d.month;
		c = d1.day - d.day;
	}

	cout << "Difference is : " << y << " years" << m << " months" << c << " days" << endl << endl;
}
int valid_check(date d)
{
	if((d.year>1900) &&(d.year<9999))
	{
		if((d.month>=1)&&(d.month<=12))
		{
			if((d.day>=1 &&d.day<=31) &&(d.month==1||d.month==3||d.month==5||d.month==7||d.month==8||d.month==10||d.month==12))
				return 0;
			else if((d.day>=1 &&d.day<=30) &&(d.month==4||d.month==6||d.month==9||d.month==11))
				return 0;
		    else if((d.day>=1&& d.day<=28)&&(d.month==2))
			return 0;
			else if(d.day==29&& d.month==2 &&(d.year%400==0||(d.year%4==0&&d.year%100!=0)))
			return 0;
			else
			return 1;
		}
		else
		{
			return 1;
		}
	}
	else{
		return 1;
	}
}
int first_date(struct date& d)

{
	int v;

	cout << "Enter the date : ";
	cin >> d.day;

	cout << "Enter the month : ";
	cin >> d.month;

	cout << "Enter the year : ";
	cin >> d.year;

	v = valid_check(d);
	if(v == 0)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}
int second_date(struct date& d1)

{
	int v;

	cout << "Enter the date : ";
	cin >> d1.day;

	cout << "Enter the month : ";
	cin >> d1.month;

	cout << "Enter the year : ";
	cin >> d1.year;

	v = valid_check(d1);
	if(v == 0)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}
void display(date d)
{

    cout<<d.day<<"-"<<d.month<<"-"<<d.year<<endl;
	//cout<<d.day<<"-"<<d.mon<<"-"<<d.year<<endl;
	cout<<d.day<<"/"<<d.month<<"/"<<d.year<<endl;
	switch(d.day)
	{
		case 1:
			d.mon="JAN";
			break;
		case 2:
			d.mon="FEB";
			break;
		case 3:
			d.mon="MAR";
			break;
		case 4:
			d.mon="APR";
			break;
		case 5:
			d.mon="MAY";
			break;
		case 6:
			d.mon="JUN";
			break;
		case 7:
			d.mon="JUL";
			break;
		case 8:
			d.mon="AUG";
			break;
		case 9:
			d.mon="SEP";
			break;
		case 10:
			d.mon="OCT";
			break;
		case 11:
			d.mon="NOV";
			break;
		case 12:
			d.mon="DEC";
			break;
	}
	cout<<d.day<<"-"<<d.mon<<"-"<<d.year<<endl;
}
void address(date d)
{
	cout<<"DATE "<<&d.day<<endl<<"MONTH "<<&d.month<<endl<<"YEAR "<<&d.year<<endl;
}
int main()
{
int choice,c;
date d,d1;
while(1)
{
	cout<<"Enter\n1 for first date\n2 for adress\n3 for increment\n4 for display\n5 for difference\n6 for end"<<endl;
	cout<<"Enter choice"<<endl;
	cin>>choice;
	if(choice>5)
	{
		cout<<"end";
		break;
	}
	else
	{
		switch(choice)
		{
			case 1:
			c=first_date(d);
			if(c==0)
			{
				cout<<"valid ip"<<endl;
			}
			else
			{
				cout<<"ivalid date"<<endl;
			    exit(0);
			}
			break;
			case 2:
			address(d);
			break;
			case 3:
			increment(d);
			break;
			case 4:
			display(d);
			break;
			case 5:
				cout << " Enter the date to get difference from initial date : " << endl;
				c = second_date(d1);
				if(c == 0)
				{
					cout << "Input date is valid..." << endl << endl;
				}
				else
				{
					cout << "Initial date input successfull..!!" << endl << endl;
					if(d1.year < d.year)
					{
						cout << "Invalid difference...." << endl;
					}
					difference(d, d1);
					display(d);
				}
				break;

			default:
			cout<<"invalid";
			break;

		}
	}
}
	return 0;
}


text:
## Steps to follow :scroll:

### 0. Star The Repo :star2:

Star the repo by pressing the topmost-right button to start your wonderful journey.

### 1. Fork it :fork_and_knife:

You can get your own fork/copy of [HacktoberFest-2022](https://github.com/msameerfarooq/Hacktoberfest2022) by using the Fork button.

### 2. Clone it :busts_in_silhouette:

`NOTE: commands are to be executed on Linux, Mac, and Windows(using Powershell)`

You need to clone or (download) it to local machine using

```sh
$ git clone https://github.com/Your_Username/Hacktoberfest2022.git
```

> This makes a local copy of the repository in your machine.

Once you have cloned the `Hacktoberfest2022` repository in Github, move to that folder first using change directory command on Linux, Mac, and Windows(PowerShell to be used).

```sh
# This will change directory to a folder Hacktoberfest2022
$ cd Hacktoberfest2022
```

Move to this folder for all other commands.

### 3. Set it up :arrow_up:

Run the following commands to see that *your local copy* has a reference to *your forked remote repository* in Github :octocat:

```sh
$ git remote -v
origin  https://github.com/Your_Username/Hacktoberfest2022.git (fetch)
origin  https://github.com/Your_Username/Hacktoberfest2022.git (push)
```

Now, let's add a reference to the original [Hacktoberfest-2022](https://github.com/msameerfarooq/Hacktoberfest2022) repository using

```sh
$ git remote add upstream https://github.com/msameerfarooq/Hacktoberfest2022.git
```

> This adds a new remote named ***upstream***.

See the changes using

```sh
$ git remote -v
origin    https://github.com/Your_Username/Hacktoberfest2022.git (fetch)
origin    https://github.com/Your_Username/Hacktoberfest2022.git (push)
upstream  https://github.com/Remote_Username/Hacktoberfest2022.git (fetch)
upstream  https://github.com/Remote_Username/Hacktoberfest2022.git (push)
```
`In your case, you will see`
```sh
$ git remote -V
origin    https://github.com/Your_Username/Hacktoberfest2022.git (fetch)
origin    https://github.com/Your_Username/Hacktoberfest2022.git (push)
upstream  https://github.com/msameerfarooq/Hacktoberfest2022.git (fetch)
upstream  https://github.com/msameerfarooq/Hacktoberfest2022.git (push)
```

### 4. Sync it :recycle:

Always keep your local copy of the repository updated with the original repository.
Before making any changes and/or in an appropriate interval, run the following commands *carefully* to update your local repository.

```sh
# Fetch all remote repositories and delete any deleted remote branches
$ git fetch --all --prune

# Switch to `main` branch
$ git checkout main

# Reset local `main` branch to match the `upstream` repository's `main` branch
$ git reset --hard upstream/main

# Push changes to your forked `Hacktoberfest-2021` repo
$ git push origin main
```

### 5. Ready Steady Go... :turtle: :rabbit2:

Once you have completed these steps, you are ready to start contributing by checking our `Good First Issue` Issues and creating [pull requests](https://github.com/msameerfarooq/Hacktoberfest2022/pulls).

### 6. Create a new branch :bangbang:

Whenever you are going to contribute. Please create a separate branch using command and keep your `main` branch clean (i.e. synced with remote branch).

```sh
# It will create a new branch with name Branch_Name and switch to branch Folder_Name
$ git checkout -b BranchName
```

Create a separate branch for contribution and try to use the same name of the branch as of folder.

To switch to the desired branch

```sh
# To switch from one folder to other
$ git checkout BranchName
```

To add the changes to the branch. Use

```sh
# To add all files to branch Folder_Name
$ git add .
```

Type in a message relevant for the code reviewer using

```sh
# This message get associated with all files you have changed
$ git commit -m 'relevant message'
```

Now, Push your awesome work to your remote repository using

```sh
# To push your work to your remote repository
$ git push -u origin BranchName
```

Finally, go to your repository in the browser and click on `compare and pull requests`.
Then add a title and description to your pull request that explains your precious effort.


text:
#include <iostream>
#include <vector>
using namespace std;
//time complexity -> O(n^2)
void swap(vector<int>&arr, int i, int j){
  int temp = arr[i];
  arr[i] = arr[j];
  arr[j] = temp;
}
void selectionSort(vector<int>&arr){
  int n = arr.size();
  for(int i=0; i<n-1; i++){
    int minPos = i;
    for(int j=i+1; j<n; j++){
      if(arr[minPos] > arr[j]) minPos = j;
    }
    swap(arr, i, minPos);
  }
}
int main(){
  vector<int> nums = {0, 6, 7, 3, 5, 11, 36, 41, 22};
  cout<<"Array without Sorting: ";
  for(auto x: nums){
    cout<<x<<"";
  }cout<<endl;
  selectionSort(nums);
  cout<<"Array after selection Sort: ";
  for(auto x: nums){
    cout<<x<<"";
  }
}


text:
#include<iostream>
using namespace std;
int main()
{
	int num;
	cout << " Enter a number to check whether it is even ot odd ; " << endl;
	cin >> num;
	if (num % 2 == 0)
	{
		cout << num <<" is an even number " << endl;
	}
	else
	{
		cout << num << " is an odd number " << endl;
	}
	return 0;
}


text:
// C++ implementation of Cocktail Sort
#include <bits/stdc++.h>
using namespace std;

// Sorts array a[0..n-1] using Cocktail sort
void CocktailSort(int a[], int n)
{
	bool swapped = true;
	int start = 0;
	int end = n - 1;

	while (swapped) {
		// reset the swapped flag on entering
		// the loop, because it might be true from
		// a previous iteration.
		swapped = false;

		// loop from left to right same as
		// the bubble sort
		for (int i = start; i < end; ++i) {
			if (a[i] > a[i + 1]) {
				swap(a[i], a[i + 1]);
				swapped = true;
			}
		}

		// if nothing moved, then array is sorted.
		if (!swapped)
			break;

		// otherwise, reset the swapped flag so that it
		// can be used in the next stage
		swapped = false;

		// move the end point back by one, because
		// item at the end is in its rightful spot
		--end;

		// from right to left, doing the
		// same comparison as in the previous stage
		for (int i = end - 1; i >= start; --i) {
			if (a[i] > a[i + 1]) {
				swap(a[i], a[i + 1]);
				swapped = true;
			}
		}

		// increase the starting point, because
		// the last stage would have moved the next
		// smallest number to its rightful spot.
		++start;
	}
}

/* Prints the array */
void printArray(int a[], int n)
{
	for (int i = 0; i < n; i++)
		printf("%d ", a[i]);
	printf("\n");
}

// Driver code
int main()
{
	int a[] = { 5, 1, 4, 2, 8, 0, 2 };
	int n = sizeof(a) / sizeof(a[0]);
	CocktailSort(a, n);
	printf("Sorted array :\n");
	printArray(a, n);
	return 0;
}


text:
#include<iostream>
using namespace std;

bool isSafe(int** arr, int x , int y, int n){
    for(int row=0; row<x; row++){
        if(arr[row][y]==1){
            return false;
        }
    }
   int  row=x;
    int col= y;
    while(row>=0 && col>=0){
        if(arr[row][col]==1){
            return false;
        }
        row--;
        col--;
    }
     row=x;
     col= y;
    while(row>=0 && col<n){
        if(arr[row][col]==1){
            return false;
        }
        row--;
        col++;
    }
    return true;

}

bool nQueen(int** arr,int x, int n ){
    if(x>=n){
        return true;
    }
    for(int col=0 ; col<n; col++){
        if(isSafe(arr, x, col, n)){
            arr[x][col]=1;

            if(nQueen(arr, x+1, n)){
                return true;
            }
            arr[x][col]=0;
        }
    }
            return false;
}

int main(){

    int n;
    cin>>n;
    int** arr= new int*[n];
    for(int i=0; i<n; i++){
        arr[i]= new int[n];
        for(int j=0; j<n; j++){
            arr[i][j]= 0;
        }
    }

    if(nQueen(arr, 0, n)){
        for(int i=0; i<n; i++){
        for(int j=0; j<n; j++){
            cout<<arr[i][j]<<" ";
        }
            cout<<endl;
    }

    }
    return 0;
}


text:
Traveling Salesman Problem (TSP) Implementation
Travelling Salesman Problem (TSP) : Given a set of cities and distances between every pair of cities,
                              the problem is to find the shortest possible route that visits every city exactly once and returns to the starting point.

// Java program to implement
// traveling salesman problem
// using naive approach.
import java.util.*;
class GFG{

static int V = 4;

// implementation of traveling
// Salesman Problem
static int travllingSalesmanProblem(int graph[][],
									int s)
{
// store all vertex apart
// from source vertex
ArrayList<Integer> vertex =
			new ArrayList<Integer>();

for (int i = 0; i < V; i++)
	if (i != s)
	vertex.add(i);

// store minimum weight
// Hamiltonian Cycle.
int min_path = Integer.MAX_VALUE;
do
{
	// store current Path weight(cost)
	int current_pathweight = 0;

	// compute current path weight
	int k = s;

	for (int i = 0;
			i < vertex.size(); i++)
	{
	current_pathweight +=
			graph[k][vertex.get(i)];
	k = vertex.get(i);
	}
	current_pathweight += graph[k][s];

	// update minimum
	min_path = Math.min(min_path,
						current_pathweight);

} while (findNextPermutation(vertex));

return min_path;
}

// Function to swap the data
// present in the left and right indices
public static ArrayList<Integer> swap(
			ArrayList<Integer> data,
			int left, int right)
{
// Swap the data
int temp = data.get(left);
data.set(left, data.get(right));
data.set(right, temp);

// Return the updated array
return data;
}

// Function to reverse the sub-array
// starting from left to the right
// both inclusive
public static ArrayList<Integer> reverse(
			ArrayList<Integer> data,
			int left, int right)
{
// Reverse the sub-array
while (left < right)
{
	int temp = data.get(left);
	data.set(left++,
			data.get(right));
	data.set(right--, temp);
}

// Return the updated array
return data;
}

// Function to find the next permutation
// of the given integer array
public static boolean findNextPermutation(
					ArrayList<Integer> data)
{
// If the given dataset is empty
// or contains only one element
// next_permutation is not possible
if (data.size() <= 1)
	return false;

int last = data.size() - 2;

// find the longest non-increasing
// suffix and find the pivot
while (last >= 0)
{
	if (data.get(last) <
		data.get(last + 1))
	{
	break;
	}
	last--;
}

// If there is no increasing pair
// there is no higher order permutation
if (last < 0)
	return false;

int nextGreater = data.size() - 1;

// Find the rightmost successor
// to the pivot
for (int i = data.size() - 1;
		i > last; i--) {
	if (data.get(i) >
		data.get(last))
	{
	nextGreater = i;
	break;
	}
}

// Swap the successor and
// the pivot
data = swap(data,
			nextGreater, last);

// Reverse the suffix
data = reverse(data, last + 1,
				data.size() - 1);

// Return true as the
// next_permutation is done
return true;
}

// Driver Code
public static void main(String args[])
{
// matrix representation of graph
int graph[][] = {{0, 10, 15, 20},
				{10, 0, 35, 25},
				{15, 35, 0, 30},
				{20, 25, 30, 0}};
int s = 0;
System.out.println(
travllingSalesmanProblem(graph, s));
}
}


text:
# Python3 Program to print BFS traversal
# from a given source vertex. BFS(int s)
# traverses vertices reachable from s.
from collections import defaultdict

# This class represents a directed graph
# using adjacency list representation
class Graph:

	# Constructor
	def __init__(self):

		# default dictionary to store graph
		self.graph = defaultdict(list)

	# function to add an edge to graph
	def addEdge(self,u,v):
		self.graph[u].append(v)

	# Function to print a BFS of graph
	def BFS(self, s):

		# Mark all the vertices as not visited
		visited = [False] * (max(self.graph) + 1)

		# Create a queue for BFS
		queue = []

		# Mark the source node as
		# visited and enqueue it
		queue.append(s)
		visited[s] = True

		while queue:

			# Dequeue a vertex from
			# queue and print it
			s = queue.pop(0)
			print (s, end = " ")

			# Get all adjacent vertices of the
			# dequeued vertex s. If a adjacent
			# has not been visited, then mark it
			# visited and enqueue it
			for i in self.graph[s]:
				if visited[i] == False:
					queue.append(i)
					visited[i] = True

# Driver code

# Create a graph given in
# the above diagram
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)

print ("Following is Breadth First Traversal"
				" (starting from vertex 2)")
g.BFS(2)


text:
#include <bits/stdc++.h>

using namespace std;

int
main ()
{
  int n;			// initialising size of array
  cin >> n;
  int arr[n];

  unordered_map < int, int >nar;	// using unoredered_maps which works on hash table.

  for (int i = 0; i < n; i++)
    {
      int x;
      cin >> x;
      nar[x]++;
    }
  cout << "element" << " " << "frequency" << endl;
for (auto i:nar)
    {
      cout << i.first << "   --     " << i.second << endl;
    }

  return 0;
}


text:
#  Hacktoberfest-2022🔥
Contribute in this repository by raising genuine PR. Get verified, merged and earn the free swags from Hacktoberfest 2022.
![image](https://user-images.githubusercontent.com/70385488/192114009-0830321a-d227-4a4d-8411-6c03b54d7ce6.png)

[![Open Source Love](https://firstcontributions.github.io/open-source-badges/badges/open-source-v1/open-source.svg)](https://github.com/msameerfarooq/Hacktoberfest2022)

### This repository aims to help code beginners with their first successful pull request and open source contribution. :partying_face:

:star: Feel free to use this project to make your first contribution to an open-source project on GitHub. Practice making your first pull request to a public repository before doing the real thing!

:star: Make sure to grab some cool swags during Hacktoberfest by getting involved in the open-source community.

### This repository is open to all members of the GitHub community. Any member can contribute to this project! :grin:

## What is Hacktoberfest? :thinking:
A month-long celebration from October 1st to October 31st presented by [Digital Ocean](https://hacktoberfest.com/) and [DEV Community](https://dev.to/) collaborated with [GitHub](https://github.com/blog/2433-celebrate-open-source-this-october-with-hacktoberfest) to get people involved in [Open Source](https://github.com/open-source). Create your very first pull request to any public repository on GitHub and contribute to the open-source developer community.

[https://hacktoberfest.digitalocean.com/](https://hacktoberfest.com/)

## Rules :fire:
To qualify for the __official limited edition Hacktoberfest shirt__, you must register [here](https://hacktoberfest.digitalocean.com/) and make four Pull Requests (PRs) between October 1-31, 2022 (in any time zone). PRs can be made to any public repo on GitHub, not only the ones with issues labeled Hacktoberfest. This year, the __first 40,000__ participants who complete the challenge will earn a T-shirt.

:tada: :confetti_ball: :smiley: _**Happy Contributing**_ :smiley: :confetti_ball: :tada:

Readme file is originally structured by [Kishan Kumar Rai](https://github.com/kishanrajput23) and taken from repo [Hacktoberfest-2022](https://github.com/kishanrajput23/Hacktoberfest-2022)


text:
#include <bits/stdc++.h>
using namespace std;
 int gcd(int a, int b) {
    if (b == 0)
        return a;
    else
        return gcd(b, a % b);
}
void ArrayRotate(int A[], int n, int k) {
    int d = -1, i, temp, j;
    for (i = 0; i < gcd(n, k); i++) {
        j = i;
        temp = A[i];
        while (1) {
            d = (j + k) % n;
            if (d == i) break;
            A[j] = A[d];
            j = d;
        }
        A[j] = temp;
    }
}
void displayArray(int A[], int n) {
    int i;
    for (i = 0; i < n; i++)
    cout<<A[i];
    cout<<" ";
}
int main() {
    int n = 9, i, k = 3;

    cout<<"The size of the Array: "<< n<<endl;
    int A[n] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    cout<<"The Array elements";
    for (i = 0; i < n; i++)
    cout<<A[i]<<" ";
    cout<<"\nThe value of k: "<<k<<endl;

    cout<<"Original array: ";
    displayArray(A, n);
    ArrayRotate(A, n, k);
    cout<<"\nArray after rotation: ";
    displayArray(A, n);
    return 0;
}


text:
// C++ code to demonstrate star pattern
#include <iostream>
using namespace std;

// Function to demonstrate printing pattern
void triangle(int n)
{
	// number of spaces
	int k = 2 * n - 2;

	// Outer loop to handle number of rows
	// n in this case
	for (int i = 0; i < n; i++) {

		// Inner loop to handle number spaces
		// values changing acc. to requirement
		for (int j = 0; j < k; j++)
			cout << " ";

		// Decrementing k after each loop
		k = k - 1;

		// Inner loop to handle number of columns
		// values changing acc. to outer loop
		for (int j = 0; j <= i; j++) {
			// Printing stars
			cout << "* ";
		}

		// Ending line after each row
		cout << endl;
	}
}

// Driver Code
int main()
{
	int n = 5;

	// Function Call
	triangle(n);
	return 0;
}


text:
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''

---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.


text:
#include<bits/stdc++.h>
#include<cmath>
using namespace std;
int KnapsackDp(int fw, int values[], int weight[], int n)
{
    int dp[n+1][fw+1];
    for(int i=0; i<=n; i++)
        dp[i][0] = 0;
    for(int i=0; i<=fw; i++)
        dp[0][i] = 0;
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=fw; j++)
        {
            if(weight[i-1] > j)
            {
                dp[i][j] = dp[i-1][j];
            }
            else{
                dp[i][j] = max(values[i-1] + dp[i-1][j-weight[i-1]], dp[i-1][j]);
            }
        }
    }
    return dp[n][fw];
}
int main()
{
    int n, fw;
    cin>>n;
    cin>>fw;
    int values[n], weight[n];
    for(int i=0; i<n; i++)
        cin>>values[i];
    for(int i=0; i<n; i++)
        cin>>weight[i];
    cout<<KnapsackDp(fw, values, weight, n);
    return 0;
}


text:
#include <bits/stdc++.h>
using namespace std;

int coinchange(vector<int>& a, int v, int n,
			vector<vector<int> >& dp)
{
	if (v == 0)
		return dp[n][v] = 1;
	if (n == 0)
		return 0;
	if (dp[n][v] != -1)
		return dp[n][v];
	if (a[n - 1] <= v) {
		// Either Pick this coin or not
		return dp[n][v] = coinchange(a, v - a[n - 1], n, dp)
						+ coinchange(a, v, n - 1, dp);
	}
	else // We have no option but to leave this coin
		return dp[n][v] = coinchange(a, v, n - 1, dp);
}
int32_t main()
{
	int tc = 1;
	// cin >> tc;
	while (tc--) {
		int n, v;
		n = 3, v = 4;
		vector<int> a = { 1, 2, 3 };
		vector<vector<int> > dp(n + 1,
								vector<int>(v + 1, -1));
		int res = coinchange(a, v, n, dp);
		cout << res << endl;
	}
}


text:
//Top-Down Approch ( Recursive approach)

#include <bits/stdc++.h>
using namespace std;

#define mx 1000000

int dp[mx + 1];

int fib(int n)
{
    if (n == 0 || n == 1)
        return n;

    if (dp[n] != -1)
    {
        return dp[n];
    }

    int res;

    res = fib(n - 1) + fib(n - 2);

    dp[n] = res;

    return dp[n];
}

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        int n;
        cin >> n;
        for (int i = 1; i <= mx; ++i)
        {
            dp[i] = -1;
        }
        cout << fib(n) << endl;
    }
    return 0;
}


text:
#include<iostream>
using namespace std;
bool subset_sum(int arr[],int sum,int n)
{
    bool t[n+1][sum+1];
    for(int i=0;i<n+1;i++)
    {
        for(int j=0;j<sum+1;j++)
        {
            if(i==0)
            t[i][j]=false;
            if(j==0)
            t[i][j]=true;
        }
    }
     for(int i=1;i<n+1;i++)
    {
        for(int j=1;j<sum+1;j++)
        {
            if(arr[i-1]<=j)
            t[i][j]=t[i-1][j-arr[i-1]]||t[i-1][j];
            else
            t[i][j]=t[i-1][j];
        }
    }
    return t[n][sum];
}
int main()
{
    int arr[]={1,3,5,9};
    int s=0;
    int n=sizeof(arr)/sizeof(arr[0]);
    for(int i=0;i<n;i++)
    {
        s=s+arr[i];
    }
    if(s%2!=0)
    std::cout << "false" << std::endl;
    else
   { int flag=subset_sum(arr,s/2,n);
    if(flag)
    cout<<"true"<<endl;
    else
    cout<<"no"<<endl;

   }

}


text:
class Solution {
public:
    int deleteAndEarn(vector<int>& nums) {
        int n = 200001;
        vector<int> sum(n,0);

        for(int num : nums)
            sum[num] += num;

        vector<int> dp(n,0);
        dp[0] = 0;
        dp[1] = sum[1];

        for(int i=2;i<n;i++)
            dp[i] = max(dp[i-1], sum[i] + dp[i-2]);

        return dp[n-1];
    }
};


text:
#include <iostream>
using namespace std;
class starry
{
   public:

int max(int a,int b)
{
    if(a>b)
    return a;
    else
    return b;
}
};

int main() {
    // Write C++ code here
    starry ob;
    int n,w;  //n is the size of array and w is the given wt
    cin>>n>>w;
    int val[n],wt[n],t[n+1][w+1];
    for(int i=0;i<n;i++)
    {
        cin>>wt[i];  //wt array
    }
     for(int i=0;i<n;i++)
    {
        cin>>val[i];//value array
    }
     for(int i=0;i<n+1;i++)
    {
         for(int j=0;j<w+1;j++)
        {
           if(i==0||j==0)
           t[i][j]=0;
        }
    }
    for(int i=1;i<n+1;i++)
    {
         for(int j=1;j<w+1;j++)
        {
            if(wt[i-1]<=j)//given sub wt is less than actual wt

                t[i][j]=ob.max(val[i-1]+t[i-1][j-wt[i-1]],t[i-1][j]);//either we can choose or not

            else
            t[i][j]=t[i-1][j];//sub wt is more hence not choose
        }
    }
    cout<<t[n][w]<<endl;//max profit at last cell of the t array

    return 0;
}


text:
class Solution {
public:
    // Bottom-up approach
    // TC: O(N*N), SC: O(N*N)
    int longestPalindromeSubseqTabular(string& s) {
        if(s.empty())
            return 0;

        const int N = s.size();
        // dp(i, j): length of longest palindromic substring in s[i:j]
        vector<vector<int> > dp(N, vector<int>(N, 0));

        // all single chars are palindromic
        for(int i = 0; i < N; i++)
            dp[i][i] = 1;

        for(int l = 1; l < N; l++) {
            // starting index of window
            for(int i = 0; i < N - l; i++) {
                // ending index of window
                int j = i + l;

                // if there are only two chars
                if((j - i + 1) == 2) {
                    // if the chars are same, then that contributes 2, otherwise since
                    // individually they are palindromic so max length 1
                    dp[i][j] = 1 + (s[i] == s[j]);
                }
                else {
                    // for s[i:j]:
                    // longest palindrome length in s[i+1 : j-1] and +1 if s[i] == s[j]
                    // if s[i] != s[j], longest length palindrome = Max of longest palin in s[i:j-1] and s[i+1:j]
                    if(s[i] == s[j])
                        dp[i][j] = dp[i+1][j-1] + 2;
                    else
                        dp[i][j] = max(dp[i+1][j], dp[i][j-1]);
                }
            }
        }
        return dp[0][N-1];
    }


text:
#include<bits/stdc++.h>
using namespace std;

int minDistance(string s1, string s2) {
        int n=s1.length();
        int m=s2.length();
        vector<vector<int>> dp(n+1,vector<int>(m+1,0));
        for(int i=0;i<=n;i++){
            for(int j=0;j<=m;j++){
                if(i==0){
                    dp[i][j]=j;
                }
                else if(j==0){
                    dp[i][j]=i;
                }
                else if(s1[i-1]==s2[j-1]){
                    dp[i][j]=dp[i-1][j-1];
                }
                else{
                    dp[i][j]=1+min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]));
                }
            }
        }
        return dp[n][m];

    }
int main(){
    string s1,s2;
    cin>>s1;
    cin>>s2;
    cout<<"min steps required to convert "<<s1<<" into "<<s2<<" are "<<minDistance(s1,s2);
}


text:
#include <bits/stdc++.h>
using namespace std;

int lcs(int ind1, int ind2, string s, string t,vector<vector<int>> &dp) {
    if(ind1 == 0 || ind2 == 0) return 0;

    if(dp[ind1][ind2] != -1) return dp[ind1][ind2];

    if(s[ind1-1] == t[ind2-1]) return dp[ind1][ind2] = 1 + lcs(ind1-1, ind2-1, s, t, dp);
    return dp[ind1][ind2] = max(lcs(ind1-1, ind2, s, t, dp), lcs(ind1, ind2-1, s, t, dp));
}

string LCS(string s, string t) {
    int n = s.size();
    int m = t.size();

    int ind1 = n;
    int ind2 = m;

    vector<vector<int>> dp(n+1, vector<int> (m+1, -1));
    // Memoisation
    // lcs(ind1, ind2, s, t, dp);

    //Tabulation
    for(int i=0; i<=n; i++) dp[i][0] = 0;
    for(int j=0; j<=m; j++) dp[0][j] = 0;

    for(int i=1; i<=n; i++) {
        for(int j=1; j<=m; j++) {
            if(s[i-1] == t[j-1]) dp[i][j] = 1 + dp[i-1][j-1];
            else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
        }
    }

    int len = dp[n][m];
    string ans = "";
    for(int i=0; i<len; i++) ans += '&';
    int ind = len-1;

    int i=n, j=m;
    while(i>0 && j>0) {
        if(s[i-1] == t[j-1]) {
            ans[ind--] = s[i-1];
            i--, j--;
        } else if(dp[i-1][j] > dp[i][j-1]) i--;
        else j--;
    }

    return ans;
}

int main() {
    string str1 = "abcde";
    string str2 = "bdgef";
    cout<<LCS(str1, str2);
    return 0;
}


text:
class Solution {
public:
    bool isMatch(string s, string p) {
     int m=s.size();
     int n=p.size();
        vector<vector<int>>dp(m+1,vector<int>(n+1,0));
        dp[0][0]=1;
        for(int i=1;i<=n;i++){
            int f=0;
            for(int j=1;j<=i;j++){
                if(p[j-1]!='*'){
                    f=1;
                    dp[0][i]=0;
                }
            }
            if(f==0){
                dp[0][i]=1;
            }
          }
        for(int i=1;i<=m;i++){
          dp[i][0]=0;
         }
        for(int i=1;i<=m;i++){
            for(int j=1;j<=n;j++){
              if(p[j-1]=='?' || p[j-1] == s[i-1]){
                    dp[i][j] = dp[i-1][j-1];
                }else if(p[j-1]=='*'){
                    dp[i][j] = dp[i-1][j] | dp[i][j-1];
                }else{
                    dp[i][j] = 0;
                }
            }
        }
        return dp[m][n];
    }
};


text:
    //Using Dynamic Programming
    static int fib(int n)
    {
    int f[] = new int[n+2]; // 1 extra to handle case, n = 0
    int i;

    f[0] = 0;
    f[1] = 1;

    for (i = 2; i <= n; i++)
    {
        f[i] = f[i-1] + f[i-2];
    }

    return f[n];
    }


text:
#include <iostream>
#include <cmath>
using namespace std;

int main(){
	int n;
	cout << "Enter the number of elements in the given array: ";
	//taking input
	cin >> n;
	int a[n];
	cout << "Enter the elements" << endl;
	for (int i = 0; i < n; i++)
		cin >> a[i];

	//easy way to find the maximum difference between 2
	//elements in a given array is to find the difference
	//between maximum and minimum elements in the array

	int min = a[0], max = a[0];
	//applying linear search to find minimum and maximum of the given array
	for (int i = 1; i <n; i++){
		if (a[i] < min)
			min = a[i];
		if (a[i] > max)
			max = a[i];
	}

	//printing the difference
	cout << "The maximum difference between 2 elements in the given array is " << abs(max - min);
	return 0;
}


text:
// Program to find maximum sum subarray
// in a given 2D array
#include <bits/stdc++.h>
using namespace std;

#define ROW 4
#define COL 5

// Implementation of Kadane's algorithm for
// 1D array. The function returns the maximum
// sum and stores starting and ending indexes
// of the maximum sum subarray at addresses
// pointed by start and finish pointers
// respectively.
int kadane(int *arr, int *start, int *finish, int n)
{
    // initialize sum, maxSum and
    int sum = 0, maxSum = INT_MIN, i;

    // Just some initial value to check
    // for all negative values case
    *finish = -1;

    // local variable
    int local_start = 0;

    for (i = 0; i < n; ++i)
    {
        sum += arr[i];
        if (sum < 0)
        {
            sum = 0;
            local_start = i + 1;
        }
        else if (sum > maxSum)
        {
            maxSum = sum;
            *start = local_start;
            *finish = i;
        }
    }

    // There is at-least one
    // non-negative number
    if (*finish != -1)
        return maxSum;

    // Special Case: When all numbers
    // in arr[] are negative
    maxSum = arr[0];
    *start = *finish = 0;

    // Find the maximum element in array
    for (i = 1; i < n; i++)
    {
        if (arr[i] > maxSum)
        {
            maxSum = arr[i];
            *start = *finish = i;
        }
    }
    return maxSum;
}

// The main function that finds
// maximum sum rectangle in M[][]
void findMaxSum(int M[][COL])
{
    // Variables to store the final output
    int maxSum = INT_MIN,
        finalLeft,
        finalRight,
        finalTop,
        finalBottom;

    int left, right, i;
    int temp[ROW], sum, start, finish;

    // Set the left column
    for (left = 0; left < COL; ++left)
    {
        // Initialize all elements of temp as 0
        memset(temp, 0, sizeof(temp));

        // Set the right column for the left
        // column set by outer loop
        for (right = left; right < COL; ++right)
        {

            // Calculate sum between current left
            // and right for every row 'i'
            for (i = 0; i < ROW; ++i)
                temp[i] += M[i][right];

            // Find the maximum sum subarray in temp[].
            // The kadane() function also sets values
            // of start and finish. So 'sum' is sum of
            // rectangle between (start, left) and
            // (finish, right) which is the maximum sum
            // with boundary columns strictly as left
            // and right.
            sum = kadane(temp, &start, &finish, ROW);

            // Compare sum with maximum sum so far.
            // If sum is more, then update maxSum and
            // other output values
            if (sum > maxSum)
            {
                maxSum = sum;
                finalLeft = left;
                finalRight = right;
                finalTop = start;
                finalBottom = finish;
            }
        }
    }

    // Print final values
    cout << "(Top, Left) ("
         << finalTop << ", "
         << finalLeft
         << ")" << endl;
    cout << "(Bottom, Right) ("
         << finalBottom << ", "
         << finalRight << ")" << endl;
    cout << "Max sum is: " << maxSum << endl;
}

// Driver Code
int main()
{
    int M[ROW][COL] = {{1, 2, -1, -4, -20},
                       {-8, -3, 4, 2, 1},
                       {3, 8, 10, 1, 3},
                       {-4, -1, 1, 7, -6}};

    // Function call
    findMaxSum(M);

    return 0;
}

// This code is contributed by
// rathbhupendra


text:
#include<bits/stdc++.h>
using namespace std;

void LIS(vector<int> arr)
{
    int n=arr.size();
    vector<vector<int> > dp(n);

    dp[0].push_back(arr[0]);

    for (int i = 1; i < n; i++)
    {
        for (int j = 0; j < i; j++)
        {
            if ((arr[i] > arr[j]) &&
                    (dp[i].size() < dp[j].size() + 1))
                dp[i] = dp[j];
        }
        dp[i].push_back(arr[i]);
    }

    vector<int> print = dp[0];

    for (vector<int> i : dp)
        if (i.size() > print.size())
            print = i;
    cout<<"The longest increasing subsequence is: ";
    for (int i : print)
        cout << i << " ";
    cout << endl;;
    cout<<"The length of the LIS is: "<<print.size();
}

int main(){
    int n;
    cin>>n;  //taking number of elements as input
    vector<int> v(n);
    for(int i=0;i<n;i++){
        cin>>v[i]; // taking the array elements as input
    }
    LIS(v);
}


text:
class Solution {
public:

    unordered_map<string,int> dp;
    bool solve(string s1,string s2){
        if(s1 == s2) return true;
        if(s1.length() != s2.length()) return false;
        string key = s1 +"*"+ s2;
        if(dp.count(key) > 0) return dp[key];

         dp[key] = false;
        int n = s1.length();
        for(int i = 1;i<s1.length();i++){
            bool op1 = solve(s1.substr(0,i),s2.substr(n-i,i)) and solve(s1.substr(i,n-i),s2.substr(0,n-i));
            bool op2 = solve(s1.substr(0,i),s2.substr(0,i)) && solve(s1.substr(i,n-i),s2.substr(i,n-i));
            dp[key] = dp[key] || (op1 || op2);
        }
        return dp[key];
    }
    bool isScramble(string s1, string s2) {
        return solve(s1,s2);
    }
};


text:
#include <bits/stdc++.h>
using namespace std;

int climbStairs(int n)
{
    int dp[n + 2];
    dp[0] = 0;
    dp[1] = 1;
    dp[2] = 2;
    for (int i = 3; i <= n; i++)
    {
        dp[i] = dp[i - 1] + dp[i - 2];
    }
    return dp[n];
}

int main()
{
    int n;
    //Input number of stairs
    cin >> n;
    int ans = climbStairs(n);
    cout << ans << endl;
}