Archives November 2022

HOW TO USE TYPECASTING IN PYTHON

Type casting is a method of converting a datatype into a different form to provide meaningful results as per programmer needs.

Basically, python (pvm) either convert the datatypes implicitly or a human should explicitly convert the datatypes

Example: If person X understands english language and X has a computer which understands binary language 0 and 1. In this case, the computer needs to understands as a result of voice recognition of X’s language, then there should be some conversion of letters to binary numbers for the computer to respond. Typecasting also work’s similar to this.

There is an inbuilt function in python called type() which print the datatype of an object.

A real world example will be converting seconds in decimal to integers

time_in_sec = 1.6
print(type(time_in_sec))
print(int(time_in_sec),"second")
O/P:
<class 'float'>
1 second

Any of the datatype can be converted using python functions with the arguments.

There are different ways to convert a datatype to other datatype in python using this feature called typecasting. Using inbuilt functions of python, this can be achieved in a simple way.

To convert string to integer, use ‘int’ function. Here there is a number inside a string which is converted to exact integer by casting.

In this example,

A variable ‘string’ is declared which has been assigned a string ‘1’ object which is automatically recognized by python as string which is called implicit conversion.

In another line, ‘int’ function is added to the variable string which convert the string variable to integer explicitly which is called explicit conversion

#Typecasting of string to integer 

string = '1'

print(type(int(string))) #Explicit conversion
print(type(string)) #implicit conversion
O/P:
1
<class 'int'>
<class 'str'>

Integer can also be converted to string using ‘str’ function. Even though 1 is an integer, which is transformed to string ‘1’

#Typecasting of integer to string

integer = 1

print(str(integer))
print(type(str(integer)))
print(type(integer))
O/P:
1
<class 'str'>
<class 'int'>

Since object with quotes are considered as string, the below string was converted to string again

#Typecasting of integer to string

integer = '1'

print(type(str(integer)))
print(type(integer))
O/P:
<class 'str'>
<class 'str'>

String with letters cannot be converted to integer, which is expected. There should be numbers inside the quotes to be converted.

string = 'string'

print(int(string))

O/P:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7236/3795652633.py in <module>
      1 string = 'string'
      2 
----> 3 print(int(string))

ValueError: invalid literal for int() with base 10: 'string'

Similar to integers, decimal’s can also be converted to integer or string

#Typecasting of decimal to string

decimal = 1.0

print(type(str(decimal)))
print(type(decimal))
O/P:
<class 'str'>
<class 'float'>
#Typecasting of decimal to integer 

decimal = '1.0'

print(type(int(decimal)))
print(type(decimal))
O/P:
<class 'int'>
<class 'float'>

#Typecasting of decimal to integer

decimal = 1.0
print(decimal)
print(type(int(decimal)))
print(type(decimal))
O/P:
1.0
<class 'int'>
<class 'float'>
#Typecasting of a boolean value to String or Integer
boolean = True

print(str(boolean))
print(type(boolean))
print(int(boolean))
print(type(boolean))
O/P:
True
<class 'bool'>
1
<class 'bool'>

#Convert string to boolean
str_bool = 'True'
print(str_bool)
print(type(bool(str_bool)))
print(type(str_bool))
O/P:
True
<class 'bool'>
<class 'str'>

Integers can also be converted to binary, octal and hexadecimal values using bin(), oct() and hex() functions

#Convert integer to Binary, Octal and hexadeximal
integer = 1
print(bin(integer))
print(oct(integer))
print(hex(integer))

oct(integer)
O/P:
0o1
0b1
0x1

A typical example which shows that a string and integer cannot be concatenated. This is where typecasting plays a major role.

name = 'kishan'
age = 28
print(name + " you are "+ age + " years old")
O/P:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_24324/783362701.py in <module>
      1 name = 'kishan'
      2 age = 28
----> 3 print(name + "you are"+ age + "years old")

TypeError: can only concatenate str (not "int") to str

After converting ‘age’ variable to string using str() function, the output is printed without errors

name = 'kishan'
age = 28
print(name + " you are "+ str(age) + " years old")
O/P:
kishan you are 28 years old

A simple function which convert the datatype based on the arguments provided

#Function to convert the datatype of an object in variable
def typecast(var,dt):
#Check the current datatype
    dtype = type(var)
#Convert string to integer
    if dtype == str and dt == 'integer' or dtype == int and dt == 'integer':
        try:
            return int(var)
        except ValueError:
            print("Provide an integer inside quotes")
#Convert integer to string
    elif dtype == int and dt == 'string' or dtype == str and dt == 'string':
            return str(var)

#Convert string to decimal
    elif dtype == str and dt == 'decimal':
        return float(var)
#Convert decimal to integer 
    elif dtype == float and dt == 'integer' or dtype == int and dt == 'decimal':
        return float(var)
    elif var.startswith('0x') or var.startswith('0X'):
        return hex(var)
    elif var.startswith('0b') or var.startswith('0B'):
        return bin(var)
    elif var.startswith('0o') or var.startswith('0O'):
        return oct(var)
    else:
        return "Invalid input"



        
print(typecast('0xA180',None))

Also lists,tuples and sets can also be converted to its counterparts using list(),tuple() and set() functions

l = [1,2,3,4]

print(tuple(l))
print(set(l))

print(type(tuple(l)))
print(type(set(l)))

O/P:
(1, 2, 3, 4)
{1, 2, 3, 4}
<class 'tuple'>
<class 'set'>

t = (1,2,3,4)
print(list(t))
print(set(t))
print(type(list(t)))
print(type(set(t)))

O/P:
[1, 2, 3, 4]
{1, 2, 3, 4}
<class 'list'>
<class 'set'>

s = {1,2,3,4}
print(list(s))
print(tuple(s))
print(type(list(s)))
print(type(tuple(s)))

O/P:
[1, 2, 3, 4]
(1, 2, 3, 4)
<class 'list'>
<class 'tuple'>

Summary:

  • Typecasting will be always useful to convert a datatype to another
  • In a real world scenario, there are lot of conversions which happen from number to text, text to number etc.. which depend on casting of datatypes
  • Typecasting may be useful in string concatenation areas, where a number need to concatenated with a string

HOW TO VIEW THE BYTE CODE IN PYTHON

A translator is the one which translates the source code into object code.

Translator which convert high level language into a byte code which is further converted into machine understandable format by a Compiler.

Translator which implicitly convert the source program line by line into byte code and interpret the code at same time without the need for explicit byte code generation by Interpreter.

In python, the byte code is generated internally by PVM(python virtual machine) in the memory heap which is not visible to programmers eyes.

There are different types of compiler that are used for python

  • CPython(C compiler)
  • PyPy(JIT compiler)

JIT compiler is faster compared to C compiler during interpretation phase.

Below example in linux shows the procedure to peep through the byte code files generated by python3 compiler.

Here python3 calls the compiler to display the results directly to the screen rather than generating the byte code files.

Create a test code called test.py

[hydra@hydrupgrd hydrapy]$ cat test.py
#!/usr/bin/python3


print("Hello")

Execute the python file using python3 to display the output

[hydra@hydrupgrd hydrapy]$ python3 test.py
Hello

There is a module called py_compile.py which prints the byte code information into .pyc file which is not readable using editor. Also man page provides some info about the options that can be used to generate the byte code

[hydra@hydrupgrd hydrapy]$ man python3
       -m module-name
              Searches sys.path for the named module and runs the corresponding .py file as a script.

[hydra@hydrupgrd hydrapy]$ locate py_compile.py
/usr/lib64/python3.6/py_compile.py

Generate the byte code with the following command and a new directory called __pycache__ will be created

[hydra@hydrupgrd hydrapy]$ python3 -m py_compile test.py
[hydra@hydrupgrd hydrapy]$ ls -lrt|tail -1
drwxr-xr-x 2 hydra hydra   33 Nov 24 17:57 __pycache__
[hydra@hydrupgrd hydrapy]$ cd __pycache__/
[hydra@hydrupgrd __pycache__]$ ls
test.cpython-36.pyc

Check the type of the file which shows byte compiled.

[hydra@hydrupgrd __pycache__]$ file test.cpython-36.pyc
test.cpython-36.pyc: python 3.6 byte-compiled <<<

To display the contents of the file, use the below methods

[hydra@hydrupgrd __pycache__]$ strings test.cpython-36.pyc
HelloN)
print
test.py
<module>
[hydra@hydrupgrd __pycache__]$ cd ..

To display all the internal function calls used by compiler, use the dis option

[hydra@hydrupgrd hydrapy]$ python3 -m dis test.py
  4           0 LOAD_NAME                0 (print)
              2 LOAD_CONST               0 ('Hello')
              4 CALL_FUNCTION            1
              6 POP_TOP
              8 LOAD_CONST               1 (None)
             10 RETURN_VALUE
INSTALLATION OF CASSANDRA IN UBUNTU

Cassandra is a NoSQL database management system that is free and open-source. It is made to handle massive volumes of data over multiple commodity servers while also offering high availability and eliminating single points of failure.

Considering its capability to handle volumes and cheap cost, market is slowly moving towards Cassandra

Install apt-transport-https package to access Cassandra repository over secure protocol

root@exhydra:/home/exhydra# apt install apt-transport-https
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  apt-transport-https
0 upgraded, 1 newly installed, 0 to remove and 254 not upgraded.
Need to get 4,348 B of archives.
After this operation, 154 kB of additional disk space will be used.
Get:1 http://in.archive.ubuntu.com/ubuntu bionic-updates/universe amd64 apt-transport-https all 1.6.14 [4,348 B]
Fetched 4,348 B in 1s (3,316 B/s)
Selecting previously unselected package apt-transport-https.
(Reading database ... 148579 files and directories currently installed.)
Preparing to unpack .../apt-transport-https_1.6.14_all.deb ...
Unpacking apt-transport-https (1.6.14) ...
Setting up apt-transport-https (1.6.14) ...

Install curl to fetch the Cassandra package from repository

root@exhydra:/home/exhydra# snap install curl
curl 7.86.0 from Wouter van Bommel (woutervb) installed
root@exhydra-VirtualBox:/home/exhydra# curl https://downloads.apache.org/cassandra/KEYS | sudo apt-key add -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  267k  100  267k    0     0   205k      0  0:00:01  0:00:01 --:--:--  205k

Update apt utility in Ubuntu

root@exhydra-VirtualBox:/home/exhydra# apt update

Install cassandra using the below package

root@exhydra:/home/exhydra# apt install cassandra
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  ca-certificates-java java-common libopts25 ntp openjdk-8-jre-headless sntp
Suggested packages:
  cassandra-tools default-jre ntp-doc fonts-dejavu-extra fonts-ipafont-gothic fonts-ipafont-mincho fonts-wqy-microhei fonts-wqy-zenhei
The following NEW packages will be installed:
  ca-certificates-java cassandra java-common libopts25 ntp openjdk-8-jre-headless sntp
0 upgraded, 7 newly installed, 0 to remove and 254 not upgraded.
Need to get 76.6 MB of archives.
After this operation, 165 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://in.archive.ubuntu.com/ubuntu bionic/universe amd64 libopts25 amd64 1:5.18.12-4 [58.2 kB]
Get:2 http://in.archive.ubuntu.com/ubuntu bionic-updates/universe amd64 ntp amd64 1:4.2.8p10+dfsg-5ubuntu7.3 [640 kB]
Get:3 http://in.archive.ubuntu.com/ubuntu bionic-updates/main amd64 java-common all 0.68ubuntu1~18.04.1 [14.5 kB]
Get:4 http://in.archive.ubuntu.com/ubuntu bionic-updates/universe amd64 openjdk-8-jre-headless amd64 8u352-ga-1~18.04 [28.3 MB]
Get:6 http://in.archive.ubuntu.com/ubuntu bionic-updates/main amd64 ca-certificates-java all 20180516ubuntu1~18.04.1 [12.2 kB]
Get:7 http://in.archive.ubuntu.com/ubuntu bionic-updates/universe amd64 sntp amd64 1:4.2.8p10+dfsg-5ubuntu7.3 [86.5 kB]
Get:5 https://downloads.apache.org/cassandra/debian 40x/main amd64 cassandra all 4.0.5 [47.5 MB]
Fetched 76.6 MB in 12s (6,527 kB/s)

Start Cassandra service post installation and enable it to start the service automatically after reboot using systemctl utility

root@exhydra:/home/exhydra# systemctl start cassandra
root@exhydra:/home/exhydra# systemctl enable cassandra
cassandra.service is not a native service, redirecting to systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable cassandra
root@exhydra:/home/exhydra# systemctl status cassandra
● cassandra.service - LSB: distributed storage system for structured data
   Loaded: loaded (/etc/init.d/cassandra; generated)
   Active: active (running) since Wed 2022-11-16 22:36:01 IST; 2min 12s ago
     Docs: man:systemd-sysv-generator(8)
    Tasks: 41 (limit: 4915)
   CGroup: /system.slice/cassandra.service
           └─2537 /usr/bin/java -ea -da:net.openhft... -XX:+UseThreadPriorities -XX:+HeapDumpOnOutOfMemoryError -Xss256k -XX:+AlwaysPreTouch -XX:-

Nov 16 22:36:01 exhydra-VirtualBox systemd[1]: Starting LSB: distributed storage system for structured data...
Nov 16 22:36:01 exhydra-VirtualBox systemd[1]: Started LSB: distributed storage system for structured data.

Check the current node status to check the service status

root@exhydra:/home/exhydra# nodetool status
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address    Load       Tokens  Owns (effective)  Host ID                               Rack
UN  127.0.0.1  69.08 KiB  16      100.0%            147efa87-4637-470a-a33a-1a237bb7fc35  rack1

Use the command line shell using cqlsh utility

root@exhydra:/home/exhydra# cqlsh
Connected to Test Cluster at 127.0.0.1:9042
[cqlsh 6.0.0 | Cassandra 4.0.5 | CQL spec 3.4.5 | Native protocol v5]
Use HELP for help.
cqlsh> help

Documented shell commands:
===========================
CAPTURE  CLS          COPY  DESCRIBE  EXPAND  LOGIN   SERIAL  SOURCE   UNICODE
CLEAR    CONSISTENCY  DESC  EXIT      HELP    PAGING  SHOW    TRACING

CQL help topics:
================
AGGREGATES               CREATE_KEYSPACE           DROP_TRIGGER      TEXT
ALTER_KEYSPACE           CREATE_MATERIALIZED_VIEW  DROP_TYPE         TIME
ALTER_MATERIALIZED_VIEW  CREATE_ROLE               DROP_USER         TIMESTAMP
ALTER_TABLE              CREATE_TABLE              FUNCTIONS         TRUNCATE
ALTER_TYPE               CREATE_TRIGGER            GRANT             TYPES
ALTER_USER               CREATE_TYPE               INSERT            UPDATE
APPLY                    CREATE_USER               INSERT_JSON       USE
ASCII                    DATE                      INT               UUID
BATCH                    DELETE                    JSON
BEGIN                    DROP_AGGREGATE            KEYWORDS
BLOB                     DROP_COLUMNFAMILY         LIST_PERMISSIONS
BOOLEAN                  DROP_FUNCTION             LIST_ROLES
COUNTER                  DROP_INDEX                LIST_USERS
CREATE_AGGREGATE         DROP_KEYSPACE             PERMISSIONS
CREATE_COLUMNFAMILY      DROP_MATERIALIZED_VIEW    REVOKE
CREATE_FUNCTION          DROP_ROLE                 SELECT
CREATE_INDEX             DROP_TABLE                SELECT_JSON

Check the version and host inside command line

cqlsh> show version;
[cqlsh 6.0.0 | Cassandra 4.0.5 | CQL spec 3.4.5 | Native protocol v5]
cqlsh> show host;
Connected to Test Cluster at 127.0.0.1:9042
INSTALL POSTGRESQL IN LINUX

Check the linux distribution for the postgresql to be installed

[root@DBZX21 ~]# uname -a
Linux DBZX21 5.4.17-2136.304.4.1.el8uek.x86_64 #2 SMP Tue Feb 8 11:54:24 PST 2022 x86_64 x86_64 x86_64 GNU/Linux

[root@DBZX21 ~]# cat /etc/redhat-release
Red Hat Enterprise Linux release 8.5 (Ootpa)

Based on the distribution type, use the package installation utility to install postgresql

[root@DBZX21 kish]# yum install postgresql* -y

Initialize the postgre libraries using postgresql-setup

[postgres@DBZX21 ~]$ /usr/bin/postgresql-setup --initdb
 * Initializing database in '/var/lib/pgsql/data'
 * Initialized, logs are in /var/lib/pgsql/initdb_postgresql.log

Enable the postgresql service and start the service using systemctl utility

[postgres@DBZX21 ~]$ systemctl enable postgresql
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-unit-files ====
Authentication is required to manage system service or unit files.
Authenticating as: kishan
Password:
==== AUTHENTICATION COMPLETE ====
Created symlink /etc/systemd/system/multi-user.target.wants/postgresql.service → /usr/lib/systemd/system/postgresql.service.
==== AUTHENTICATING FOR org.freedesktop.systemd1.reload-daemon ====
Authentication is required to reload the systemd state.
Authenticating as: kishan
Password:
==== AUTHENTICATION COMPLETE ====
[postgres@DBZX21 ~]$ systemctl start postgresql
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ====
Authentication is required to start 'postgresql.service'.
Authenticating as: kishan
Password:
==== AUTHENTICATION COMPLETE ====

[postgres@DBZX21 ~]$ systemctl status postgresql
● postgresql.service - PostgreSQL database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2022-11-08 21:24:36 IST; 35s ago
  Process: 70150 ExecStartPre=/usr/libexec/postgresql-check-db-dir postgresql (code=exited, status=0/SUCCESS)
 Main PID: 70152 (postmaster)
    Tasks: 8 (limit: 35835)
   Memory: 15.9M
   CGroup: /system.slice/postgresql.service
           ├─70152 /usr/bin/postmaster -D /var/lib/pgsql/data
           ├─70154 postgres: logger process
           ├─70156 postgres: checkpointer process
           ├─70157 postgres: writer process
           ├─70158 postgres: wal writer process
           ├─70159 postgres: autovacuum launcher process
           ├─70160 postgres: stats collector process
           └─70161 postgres: bgworker: logical replication launcher

Check the process related to postgre which are up to validate the status

[postgres@DBZX21 ~]$ ps -ef|grep postgre|grep -Ev 'su|grep|ps|bash'
postgres   70063   70062  0 21:24 pts/0    00:00:00 /usr/libexec/pk-command-not-found [postgres@DBZX21 ~]$ /usr/bin/postgresql-setup --initdb
postgres   70152       1  0 21:24 ?        00:00:00 /usr/bin/postmaster -D /var/lib/pgsql/data
postgres   70154   70152  0 21:24 ?        00:00:00 postgres: logger process
postgres   70156   70152  0 21:24 ?        00:00:00 postgres: checkpointer process
postgres   70157   70152  0 21:24 ?        00:00:00 postgres: writer process
postgres   70158   70152  0 21:24 ?        00:00:00 postgres: wal writer process
postgres   70159   70152  0 21:24 ?        00:00:00 postgres: autovacuum launcher process
postgres   70160   70152  0 21:24 ?        00:00:00 postgres: stats collector process
postgres   70161   70152  0 21:24 ?        00:00:00 postgres: bgworker: logical replication launcher

Use psql to login to the command line

List all the current databases

[postgres@DBZX21 ~]$ psql
postgres=# \l+
                                                                    List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   |  Size   | Tablespace |                Description

-----------+----------+----------+-------------+-------------+-----------------------+---------+------------+-------------------------------------
-------
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 7319 kB | pg_default | default administrative connection da
tabase
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +| 7185 kB | pg_default | unmodifiable empty database
           |          |          |             |             | postgres=CTc/postgres |         |            |
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +| 7185 kB | pg_default | default template for new databases
           |          |          |             |             | postgres=CTc/postgres |         |            |
(3 rows)

Use help to print all the DDL commands that can be used

postgres=# \h
Available help:
  ABORT                            CLUSTER                          CREATE VIEW                      DROP USER MAPPING
  ALTER AGGREGATE                  COMMENT                          DEALLOCATE                       DROP VIEW
  ALTER COLLATION                  COMMIT                           DECLARE                          END
  ALTER CONVERSION                 COMMIT PREPARED                  DELETE

That is it, postgresql is installed successfully!

QUERIES AND COMMANDS THAT CAN BE USED IN PSQL

Postgresql provides attractive way to check all the queries and keywords that can be used with a backslash ‘\’

Below command can be used to check all the backslash commands in psql utility

postgres=# \?
General
  \copyright             show PostgreSQL usage and distribution terms
  \crosstabview [COLUMNS] execute query and display results in crosstab
  \errverbose            show most recent error message at maximum verbosity
  \g [FILE] or ;         execute query (and send results to file or |pipe)
  \gexec                 execute query, then execute each value in its result
  \gset [PREFIX]         execute query and store results in psql variables
  \gx [FILE]             as \g, but forces expanded output mode
  \q                     quit psql
  \watch [SEC]           execute query every SEC seconds

Help
  \? [commands]          show help on backslash commands
  \? options             show help on psql command-line options
  \? variables           show help on special variables
  \h [NAME]              help on syntax of SQL commands, * for all commands

Query Buffer
  \e [FILE] [LINE]       edit the query buffer (or file) with external editor
  \ef [FUNCNAME [LINE]]  edit function definition with external editor
  \ev [VIEWNAME [LINE]]  edit view definition with external editor
  \p                     show the contents of the query buffer
  \r                     reset (clear) the query buffer
  \s [FILE]              display history or save it to file
  \w FILE                write query buffer to file

Input/Output
  \copy ...              perform SQL COPY with data stream to the client host
  \echo [STRING]         write string to standard output
  \i FILE                execute commands from file
  \ir FILE               as \i, but relative to location of current script
  \o [FILE]              send all query results to file or |pipe
  \qecho [STRING]        write string to query output stream (see \o)

Conditional
  \if EXPR               begin conditional block
  \elif EXPR             alternative within current conditional block
  \else                  final alternative within current conditional block
  \endif                 end conditional block

Informational
  (options: S = show system objects, + = additional detail)
  \d[S+]                 list tables, views, and sequences
  \d[S+]  NAME           describe table, view, sequence, or index
  \da[S]  [PATTERN]      list aggregates
  \dA[+]  [PATTERN]      list access methods
  \db[+]  [PATTERN]      list tablespaces
  \dc[S+] [PATTERN]      list conversions
  \dC[+]  [PATTERN]      list casts
  \dd[S]  [PATTERN]      show object descriptions not displayed elsewhere
  \dD[S+] [PATTERN]      list domains
  \ddp    [PATTERN]      list default privileges
  \dE[S+] [PATTERN]      list foreign tables
  \det[+] [PATTERN]      list foreign tables
  \des[+] [PATTERN]      list foreign servers
  \deu[+] [PATTERN]      list user mappings
  \dew[+] [PATTERN]      list foreign-data wrappers
  \df[antw][S+] [PATRN]  list [only agg/normal/trigger/window] functions
  \dF[+]  [PATTERN]      list text search configurations
  \dFd[+] [PATTERN]      list text search dictionaries
  \dFp[+] [PATTERN]      list text search parsers
  \dFt[+] [PATTERN]      list text search templates
  \dg[S+] [PATTERN]      list roles
  \di[S+] [PATTERN]      list indexes
  \dl                    list large objects, same as \lo_list
  \dL[S+] [PATTERN]      list procedural languages
  \dm[S+] [PATTERN]      list materialized views
  \dn[S+] [PATTERN]      list schemas
  \do[S+] [PATTERN]      list operators
  \dO[S+] [PATTERN]      list collations
  \dp     [PATTERN]      list table, view, and sequence access privileges
  \drds [PATRN1 [PATRN2]] list per-database role settings
  \dRp[+] [PATTERN]      list replication publications
  \dRs[+] [PATTERN]      list replication subscriptions
  \ds[S+] [PATTERN]      list sequences
  \dt[S+] [PATTERN]      list tables
  \dT[S+] [PATTERN]      list data types
  \du[S+] [PATTERN]      list roles
  \dv[S+] [PATTERN]      list views
  \dx[+]  [PATTERN]      list extensions
  \dy[+]  [PATTERN]      list event triggers
  \l[+]   [PATTERN]      list databases
  \sf[+]  FUNCNAME       show a function's definition
  \sv[+]  VIEWNAME       show a view's definition
  \z      [PATTERN]      same as \dp

Formatting
  \a                     toggle between unaligned and aligned output mode
  \C [STRING]            set table title, or unset if none
  \f [STRING]            show or set field separator for unaligned query output
  \H                     toggle HTML output mode (currently off)
  \pset [NAME [VALUE]]   set table output option
                         (NAME := {border|columns|expanded|fieldsep|fieldsep_zero|
                         footer|format|linestyle|null|numericlocale|pager|
                         pager_min_lines|recordsep|recordsep_zero|tableattr|title|
                         tuples_only|unicode_border_linestyle|
                         unicode_column_linestyle|unicode_header_linestyle})
  \t [on|off]            show only rows (currently off)
  \T [STRING]            set HTML <table> tag attributes, or unset if none
  \x [on|off|auto]       toggle expanded output (currently off)

Connection
  \c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}
                         connect to new database (currently "postgres")
  \conninfo              display information about current connection
  \encoding [ENCODING]   show or set client encoding
  \password [USERNAME]   securely change the password for a user

Operating System
  \cd [DIR]              change the current working directory
  \setenv NAME [VALUE]   set or unset environment variable
  \timing [on|off]       toggle timing of commands (currently off)
  \! [COMMAND]           execute command in shell or start interactive shell

Variables
  \prompt [TEXT] NAME    prompt user to set internal variable
  \set [NAME [VALUE]]    set internal variable, or list all if no parameters
  \unset NAME            unset (delete) internal variable

Large Objects
  \lo_export LOBOID FILE
  \lo_import FILE [COMMENT]
  \lo_list
  \lo_unlink LOBOID      large object operations

All DDL commands that can be used are printed using help \h

postgres=# \h
Available help:
  ABORT                            CLUSTER                          CREATE VIEW                      DROP USER MAPPING
  ALTER AGGREGATE                  COMMENT                          DEALLOCATE                       DROP VIEW
  ALTER COLLATION                  COMMIT                           DECLARE                          END
  ALTER CONVERSION                 COMMIT PREPARED                  DELETE                           EXECUTE
  ALTER DATABASE                   COPY                             DISCARD                          EXPLAIN
  ALTER DEFAULT PRIVILEGES         CREATE ACCESS METHOD             DO                               FETCH
  ALTER DOMAIN                     CREATE AGGREGATE                 DROP ACCESS METHOD               GRANT
  ALTER EVENT TRIGGER              CREATE CAST                      DROP AGGREGATE                   IMPORT FOREIGN SCHEMA
  ALTER EXTENSION                  CREATE COLLATION                 DROP CAST                        INSERT
  ALTER FOREIGN DATA WRAPPER       CREATE CONVERSION                DROP COLLATION                   LISTEN
  ALTER FOREIGN TABLE              CREATE DATABASE                  DROP CONVERSION                  LOAD
  ALTER FUNCTION                   CREATE DOMAIN                    DROP DATABASE                    LOCK
  ALTER GROUP                      CREATE EVENT TRIGGER             DROP DOMAIN                      MOVE
  ALTER INDEX                      CREATE EXTENSION                 DROP EVENT TRIGGER               NOTIFY
  ALTER LANGUAGE                   CREATE FOREIGN DATA WRAPPER      DROP EXTENSION                   PREPARE
  ALTER LARGE OBJECT               CREATE FOREIGN TABLE             DROP FOREIGN DATA WRAPPER        PREPARE TRANSACTION
  ALTER MATERIALIZED VIEW          CREATE FUNCTION                  DROP FOREIGN TABLE               REASSIGN OWNED
  ALTER OPERATOR                   CREATE GROUP                     DROP FUNCTION                    REFRESH MATERIALIZED VIEW
  ALTER OPERATOR CLASS             CREATE INDEX                     DROP GROUP                       REINDEX
  ALTER OPERATOR FAMILY            CREATE LANGUAGE                  DROP INDEX                       RELEASE SAVEPOINT
  ALTER POLICY                     CREATE MATERIALIZED VIEW         DROP LANGUAGE                    RESET
  ALTER PUBLICATION                CREATE OPERATOR                  DROP MATERIALIZED VIEW           REVOKE
  ALTER ROLE                       CREATE OPERATOR CLASS            DROP OPERATOR                    ROLLBACK
  ALTER RULE                       CREATE OPERATOR FAMILY           DROP OPERATOR CLASS              ROLLBACK PREPARED
  ALTER SCHEMA                     CREATE POLICY                    DROP OPERATOR FAMILY             ROLLBACK TO SAVEPOINT
  ALTER SEQUENCE                   CREATE PUBLICATION               DROP OWNED                       SAVEPOINT
  ALTER SERVER                     CREATE ROLE                      DROP POLICY                      SECURITY LABEL
  ALTER STATISTICS                 CREATE RULE                      DROP PUBLICATION                 SELECT
  ALTER SUBSCRIPTION               CREATE SCHEMA                    DROP ROLE                        SELECT INTO
  ALTER SYSTEM                     CREATE SEQUENCE                  DROP RULE                        SET
  ALTER TABLE                      CREATE SERVER                    DROP SCHEMA                      SET CONSTRAINTS
  ALTER TABLESPACE                 CREATE STATISTICS                DROP SEQUENCE                    SET ROLE
  ALTER TEXT SEARCH CONFIGURATION  CREATE SUBSCRIPTION              DROP SERVER                      SET SESSION AUTHORIZATION
  ALTER TEXT SEARCH DICTIONARY     CREATE TABLE                     DROP STATISTICS                  SET TRANSACTION
  ALTER TEXT SEARCH PARSER         CREATE TABLE AS                  DROP SUBSCRIPTION                SHOW
  ALTER TEXT SEARCH TEMPLATE       CREATE TABLESPACE                DROP TABLE                       START TRANSACTION
  ALTER TRIGGER                    CREATE TEXT SEARCH CONFIGURATION DROP TABLESPACE                  TABLE
  ALTER TYPE                       CREATE TEXT SEARCH DICTIONARY    DROP TEXT SEARCH CONFIGURATION   TRUNCATE
  ALTER USER                       CREATE TEXT SEARCH PARSER        DROP TEXT SEARCH DICTIONARY      UNLISTEN
  ALTER USER MAPPING               CREATE TEXT SEARCH TEMPLATE      DROP TEXT SEARCH PARSER          UPDATE
  ALTER VIEW                       CREATE TRANSFORM                 DROP TEXT SEARCH TEMPLATE        VACUUM
  ANALYZE                          CREATE TRIGGER                   DROP TRANSFORM                   VALUES
  BEGIN                            CREATE TYPE                      DROP TRIGGER                     WITH
  CHECKPOINT                       CREATE USER                      DROP TYPE
  CLOSE                            CREATE USER MAPPING              DROP USER
HOW TO CREATE A DATABASE IN POSTGRESQL

Creating a database in postgres is pretty simple in postgres

Create a basic role first for the database

[postgres@DBZX21 ~]$ psql
psql (10.21)
Type "help" for help.

postgres=# CREATE ROLE prole
postgres-# SUPERUSER
postgres-# LOGIN
postgres-# PASSWORD 'prole';
CREATE ROLE

Create a directory for datafiles to be physically stored and give permissions

[oracle@DBZX21 ~]$ mkdir -p /u01/postgre/datafile
[root@DBZX21 u01]# chmod -R 775 postgre/
[root@DBZX21 u01]# chown -R postgres:postgres postgre/

[root@DBZX21 u01]# ls -lrt postgre/
total 0
drwx------ 3 postgres postgres 29 Nov  9 15:26 datafile

Create a tablespace to be used by default for application data

postgres=# CREATE TABLESPACE ptab
postgres-# OWNER prole
postgres-# LOCATION '/u01/postgre/datafile';
CREATE TABLESPACE

Create a database with all the above specified values for parameters

postgres=# CREATE DATABASE pgre
postgres-# WITH
postgres-#     OWNER = prole
postgres-#     ENCODING = 'UTF8'
postgres-#     TABLESPACE = ptab
postgres-#     CONNECTION LIMIT = 30;
CREATE DATABASE
SIMPLE PROGRAM FOR ATM TRANSACTION IN PYTHON

A simple program to simulate an ATM transaction as per real time scenario.

#ATM transaction
#Declare the variables

denomination = [3000,6000,9000]
password = 'eXhydra@369'
amount = 100000

#Initialize the value of i

i = 0

#Ask the user to enter the password or pin for ATM 

while i < 3:
    usrpwd = input("Please enter the password : ")
    #If the password is correct, then ask the amount to be withdrawn otherwise prompt to reenter the password
    if usrpwd == password:
        withdraw = int(input("Enter transaction amount to be withdrawn : "))
        #Withdraw the correct amount as per the balance available
        if withdraw > 100000 or withdraw < 1:
            print("Enter an amount 'greater than 0' or 'less than or equal to balance'",amount)
            continue
        else:
            #Print the withdraw message and ask for repeat of transaction
            balance = amount - withdraw
            print("Transaction is successfully completed, account balance is :",balance)
            #If another transaction need to be performed, then enter the amount again
            rewithdraw = input("Do you need to perform another transaction? Yes or No: ")
            if rewithdraw == 'Yes' or rewithdraw == 'YES' or rewithdraw == 'yes':
                amount = balance
                continue
            #If the transaction need to be closed, print the thanks message
            elif rewithdraw == 'no' or rewithdraw == 'No' or rewithdraw == 'NO':
                print("Thanks for using XYZ bank. Please visit us next time")
                break
            #If any invalid input is provided, then break out of the loop
            else:
                print('*xxxxxxx* Invalid response! Transaction cancelled *xxxxxxx*')
                break
    #Three attempts are allowed for wrong password and post that transaction will be cancelled for security reasons
    else:
        print("Wrong password provided, enter the correct password again!")
        i += 1
        if i > 2:
            print('*' * 40)
            print("Password attempts exceeded closing the transaction...")
            print('*' * 40)
        
        
DEFAULT OR RESERVED KEYWORDS IN PYTHON

Keywords in python are the reserved words which cannot be customized for individual variables.

Python Interpreter throws “SyntaxError: invalid syntax” error during parse phase if a variable is declared with a reserved keyword. Each keyword has its own purpose in python which are system related internal code.

help(keyword.kwlist)

Code:

#import keywords
import keyword

#Print them
print("Reserved keywords are: ")
for resrvd_words in keyword.kwlist:
    print(resrvd_words)

Output:

False
None
True
__peg_parser__
and
as
assert
async
await
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield

A simple function to check reserved keywords. keyword has a function iskeyword() which takes one argument for word to check if the entered string is keyword or not.

#Library for keyword 
import keyword
#w = ['abc','efg','True']

#Function which checks if the entered string is keyword or not
def _CRKW_(w):
    if keyword.iskeyword(w):
        return "Reserved keywords"
    else:
        return "Non reserved words"
            
_CRKW_('T')

ARITHMETIC OPERATORS IN PYTHON

What is Operator?

Operators are characters which denotes a special symbol to accomplish mathematical operations or logical or comparisons etc.

Operands are the objects used in the expression which is connected with operators to provide valuable results post calculation

Below are the types of operators used in python

  • Arithmetic
  • Assignment
  • Comparison
  • Logical
  • Identity
  • Membership
  • Bitwise

In this article, arithmetic operators in python are going to be discussed.

ARITHMETIC OPERATORS:

BODMAS (brackets, division, multiplication, addition, subtraction) is the rules which is used to calculate the arithmetic operations in an order. Always the operators are used from left to right in the expression for equal precedence of same symbols.

BEDMAS(Brackets, exponential, division, multiplication, addition, subtraction) is similar to BODMAS rules which is used to calculate the arithmetic operations in an order. But there is slight difference in the operators used like exponential and modulus. Always the operators are used from left to right in the expression for equal precedence of same symbols.

Below are the arithmetic operators which are calculated in pythonic way which has two positive integers

#Declare variable
 x = 3
 y = 6
 
#print the operations done by arithmetic operators for each value
print('Addition : {0}\
      \nSubtraction : {1}\
      \nProduct : {2}\
      \nFloat Division : {3}\
      \nFloor Division : {4}\
      \nModulo : {5}\
      \nPower : {6}'.format(x+y,\
                          x-y,\
                          x*y,\
                          x/y,\
                          x//y,\
                          x%y,\
                          x**y))

Output:

Addition : 9      
Subtraction : -3      
Product : 18      
Float Division : 0.5      
Floor Division : 0      
Modulo : 3      
Power : 729

Below are the arithmetic operators which are calculated in pythonic way which has one decimal and one negative integer

#Declare variable

 x1 = 0.3
 y1 = -6

#print the operations done by arithmetic operators for each value

print('Addition : {0}\
      \nSubtraction : {1}\
      \nProduct : {2}\
      \nFloat Division : {3}\
      \nFloor Division : {4}\
      \nModulo : {5}\
      \nPower : {6}'.format(x1 + y1,\
                          x1 - y1,\
                          x1 * y1,\
                          x1 / y1,\
                          x1 // y1,\
                          x1 % y1,\
                          x1 ** y1))

Output:

Addition : -5.7      
Subtraction : 6.3      
Product : -1.7999999999999998      
Float Division : -0.049999999999999996      
Floor Division : -1.0      
Modulo : -5.7      
Power : 1371.7421124828536

If there is a floating point value or operand in an expression in any one of the position, then the result will always be floating point.

Below are the arithmetic operators which are calculated in pythonic way which has one negative decimal and one negative integer

#Declare variable

 x2 = -0.6
 y2 = -9

#print the operations done by arithmetic operators for each value

print('Addition : {0}\
      \nSubtraction : {1}\
      \nProduct : {2}\
      \nFloat Division : {3}\
      \nFloor Division : {4}\
      \nModulo : {5}\
      \nPower : {6}'.format(x2 + y2,\
                          x2 - y2,\
                          x2 * y2,\
                          x2 / y2,\
                          x2 // y2,\
                          x2 % y2,\
                          x2 ** y2))

Output:

Addition : -9.6      
Subtraction : 8.4      
Product : 5.3999999999999995      
Float Division : 0.06666666666666667      
Floor Division : 0.0      
Modulo : -0.6      
Power : -99.22903012752124

Expression with multiple operators with multiple operands

#Declare variable

x3 = -0.6
y3 = -9
z3 = 3

#print the operations done by arithmetic operators for each value

print(x3 + y3 - z3 * x3 / y3 // z3 % x3 ** y3)

Output:

-9.6

Real World Use Cases:

Code:

#How much total mark is scored by a student xyz in exam
#Addition operator
outof = 400
maths = 80
science = 50
computer = 90
biology = 30

total_marks = maths + science + computer + biology
print('Student xyz scored ',total_marks,'out of ',outof)

Output:

Student xyz scored  250 out of  400

Code:

#Product Use case
#Check the validity of the internet pack by converting it from day to hours, minutes and seconds

internet_validity_days = 30
hours = 24 * internet_validity_days
minutes = 1440 * hours 
seconds = 86400 * minutes

print("There are {0} hours, {1} minutes and {2} seconds validity for internet pack to expire".format(hours, minutes, seconds))

Output:

There are 720 hours, 1036800 minutes and 89579520000 seconds validity for internet pack to expire

Code:

#Floor Division
#Check the number of people who need to share money for a new year party

people = 10
party_charge = 100000
individual_share = party_charge // people
print("Each individual should contribute ${}".format(individual_share))

Output:

Each individual should contribute $10000

Summary:

In real world, there are lot of applications which depend on simple arithmetic operators which acts as a solution in many ways like

  • basic amenities which are purchased daily
  • time or distance taken to reach a destination
  • money withdrawal from atm

Every thing that happens in a day to day real world, are based on numbers and numbers are from mathematics.

ORA-00932: inconsistent datatypes: expected NUMBER got DATE

kIsH@STAX<>CREATE INDEX rp_gbl_ind ON kish.rp(R_ID)
GLOBAL PARTITION BY RANGE(R_ID)
(PARTITION ind_date_p1 VALUES LESS THAN (TO_DATE(' 2022-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')),
 PARTITION ind_date_p2 VALUES LESS THAN (TO_DATE(' 2022-02-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS' )),
 PARTITION ind_date_p3 VALUES LESS THAN (TO_DATE(' 2022-03-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')),
 PARTITION ind_date_p4 VALUES LESS THAN (MAXVALUE));
  2    3    4    5    6  (PARTITION ind_date_p1 VALUES LESS THAN (TO_DATE(' 2022-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')),
                                         *
ERROR at line 3:
ORA-00932: inconsistent datatypes: expected NUMBER got DATE

kIsH@STAX<>oerr ora 00932
SP2-0734: unknown command beginning “oerr ora 0…” – rest of line ignored.
kIsH@STAX<>!oerr ora 00932
00932, 00000, “inconsistent datatypes: expected %s got %s”
// *Cause: One of the following:
// – An attempt was made to perform an operation on incompatible
// datatypes. For example, adding a character field to a date
// field (dates may only be added to numeric fields) or
// concatenating a character field with a long field.
// – An attempt was made to perform an operation on a database
// object (such as a table or view) that was not intended for
// normal use. For example, system tables cannot be modified by
// a user. Note that on rare occasions this error occurs
// because a misspelled object name matched a restricted
// object’s name.
// – An attempt was made to use an undocumented view.
// *Action: If the cause is
// – different datatypes, then use consistent datatypes. For
// example, convert the character field to a numeric field with
// the TO_NUMBER function before adding it to the date field.
// Functions may not be used with long fields.
// – an object not intended for normal use, then do not access
// the restricted object.