This demo is to introduce ways of defining static methods in ruby. Generally utility classes will not store any state information and thread safe.
# Demo for defining utility methods in ruby
# In Java it is known as static methods
module Universe
module Earth
def sayHello
puts "Hello from earth!"
end
def sayHi
puts "Hi from earth!"
end
def sayBye
puts "Bye from earth!"
end
end
end
module Universe
module Moon
class << self
include Universe::Earth
private
def foobar
puts "Hello from foobar!"
end
end
end
end
Universe::Moon.sayHello
package designpatterns;
/*
* Observer Pattern example
*/
class WeatherData {
float temperature;
float humidity;
public float getTemperature(){
return temperature;
}
public float getHumidity() {
return humidity;
}
public void setTemperature(float t) {
temperature = t;
}
public void setHumidity(float h) {
humidity = h;
}
}
/*
* The below interface adds functionality to add, remove subscribers/clients
* to the internal list so that they can be notified whenever the state of
* the weather changes.
*/
interface WeatherNotifier {
public void notify();
public void addListener(Object client);
public void removeListener(Object client);
}
/*
* WeatherData after implementing the above interface
*/
class WeatherData implements WeatherNotifier {
private List subscribers;
{
subscribers = new ArrayList();
}
public void notify() {
// notify/wake up all the subscribers to update their view with latest state information
Iterator iterator = subscribers.iterator();
while (iterator.hasNext()) {
iterator.next().update();
}
}
@Override
public void addListener(Object client) {
subscribers.add(client);
}
@Override
public void removeListener(Object client) {
subscribers.remove(client);
}
public void setTemperature(float t) {
temperature = t;
dataChanged();
}
public void setHumidity(float h) {
humidity = h;
dataChanged();
}
private void dataChanged() {
notify();
}
public float getTemperature(){
return temperature;
}
public float getHumidity() {
return humidity;
}
}
interface WeatherReader {
public void update();
}
class WeatherClient implements WeatherReader{
WeatherData source;
public void update() {
System.out.println("Temperature is " + source.getTemperature());
System.out.println("Humidity is " + source.getHumidity());
}
}
It gives an immense pleasure to share my technical experience with fellow people. I started pushing all my local code fragments/programs to github as a way of helping young/new programmers on how to code in Java.
Github link to my program list that helped me to attain "Oracle Certified Java Professional".
The below code finds the rectangle with maximum area in a histogram with O(n) time complexity.
public static void maxRectArea(int a[], int b[]) {
// this is a maximization problem
// irrespective of the height of the the next bar
// we have to compare the area if including next bar exceeds the current area then we have to include the bar.
// stop the expansion and proceed further until end of input.
// 6 2 5 4 5 1 6
// 6 2 5 8 12 1 6
int i = 0;
int max = -1;
int e = 0;
while (i < a.length) {
if (i == 0)
e = b[i] = a[i];
else {
if (a[i] < a[i-1]) {
int t = b[i-1] / e;
if (((t+1) * a[i]) < b[i-1])
e = b[i] = a[i];
else {
e = a[i];
b[i] = (t+1) * a[i];
}
}
else if (a[i] == a[i-1]) {
b[i] = b[i-1] + e;
}
else if (a[i] > a[i-1]) {
if ((b[i-1] + e) > a[i]) {
b[i] = b[i-1] + e;
}
else {
e = b[i] = a[i];
}
}
}
i++;
}
}
After the advent of database technology, the quantum of data generated is increasing in exponential fashion. Is all the data being generated is unique, consistent and stored securely? The answer is No. We create multiple accounts in Google, Twitter, Facebook etc and it is more or less redundant. Also it is possible that un-necessary/un-wanted information being used by various Data Analytic firms that holds several billion dollar value. Are we interested in only finding a short term marketing solution by compromising the value of data.
Imagine a world organized with people's data uniformly, consistently and securely. The advantage of this paradigm is that we can reduce disk space consumption (Environment friendly), preserve the integrity of our data (Fraud elimination), avoid entering our name/address/dob etc while requesting for a new online service (Consistent and fool-proof) and most importantly we can limit the spread of our data to malicious users.
OUTPUT MODE IS FOR WRITING (FOR THE FIRST TIME WHEN THE FILE IS EMPTY)
INPUT MODE IS FOR READING
EXTEND MODE IS FOR APPENDING
KSDS - HAS INDEX AND DATA COMPONENTS, HAS FREE SPACE
SEQUENCE, RANDOM AND DYNAMIC ACCESS MODES ARE POSSIBLE
- SIMILAR TO INDEXED SEQUENTIAL
ESDS - HAS NO INDEX, RECORDS CANT BE DELETED, RECORDS ARE STORED SEQUENTIALLY AND RETRIEVED IN ORDER OF HOW IT IS STORED,
RECORDS ARE IDENTIFIED BY RBA - RELATIVE BYTE ORDER, NO FREE SPACE
- SIMILAR TO PHYSICAL SEQUENTIAL
RRDS - RECORDS ARE ACCESSED USING RRN - RELATIVE RECORD NUMBER, VARIABLE RECORD LENGHT IS POSSIBLE ONLY IN RRDS.
- SIMILAR TO DIRECT ACCESS
LDS - SEQUENCE OF BYTES
*****************************************
POINTS TO REMEMBER
+++++++++++++++++++
# WE SHOULD NOT USE 'EXTEND' OPEN MODE IN 'RANDOM' ACCESS MODE. (APPENDING MAY NOT BE POSSIBLE BECAUSE OF KEY VIOLATION)
# INPUT OR I-O(FOR UPDATING/DELETING) SHOULD BE USED FOR FETCHING RECORDS IN RANDOM/DYNAMIC MODE
# WHILE DELETING TRY TO LOCATE THE RECORD USING 'READ' AND THEN DO A 'DELETE'
# A MAXIMUM OF 255 GDG VERSIONS CAN BE CREATED
# A MAXIMUM OF 255 STEPS CAN BE PLACED AFTER A JOB CARD IN A SINGLE JCL FILE
#
If a new generation is created using (+1) in the fist step and we are
accessing the generation in consecutive steps we should use (+1)
# VERIFY command is used to perform two functions
a) Close files that are open after abnormal termination
b) Syncs the index and data components of VSAM fiels
# For copying records to a KSDS from a PS through COBOL, the records should be in sorted order.
#
To continue the input in more than one line in 'PARM' parameter we have
to give any character from A to Z in column 72 and in the next line we
have to start from 16th column
How to store the similar records to a separate file using SORT utility?
To delete a member inside a PDS use IEBCOPY with Scratch option.
Compiler Option
+++++++++++++++
DYNAM - Dynamic linking
NODYNAM - Static linking
SSRANGE - It will make the program to abend if arrary overflow occurs.
NOSSRANGE
- It will not make the program to abend, we can access outside the
memory we have allocated for the program. If we really want to do
efficient program we should use, SSRANGE
FAQs
++++
TIOT - Task Input Output Table
DFSMS - Data Facility Storage Management Subsystem
HURBA - High Used Relative Byte Address
JCL statement is coded in 80 byte records.
The first 71 columns are used for coding the JCL and we give a blank
space in the 72nd column and the last 8 columns contains the sequence
number.
Maximum primary key length in ksds,AIX is 255
The terminal we are using is 3278, total no of PF keys 24,
The
Share Option in VSAM file is specified for cross-region(within one
computer) and cross-system(between two or more computers). The default
is (1,3). The cross-system won't also 1 or 2.
1 - Total integrity, 2 - Write but no Read integrity
3 - No Integrity, 4 - same as option 3 but refreshes buffer after every read.
The functions of IDCAMS utility are
Creating VSAM objects,
Alter Dataset attributes,
Delete VSAM objects,
Loading/Unloading(Import/Export),
Print Datasets,
List catalog information and
Copying (REPRO)
The
Export/Import done using IDCAMS differs from typical REPRO command
since it backups the catalog information also. PERMANENT, INHIBITSOURCE,
INHIBITTARGET, PURGE, ERASE(inserts binary zeros before deletion).
During Import if the catalog has no information it creates new cluster
by the name. If it is present in the catalog then.................
The PRINT command prints both VSAM and non-VSAM datasets.
The LISTCAT is used to list contents of a master or user catalogs.
A maximum of 3273 DD statements can be placed inside a job step.
Max no of CONCATENATED sequential dataset is 255 and for PDS it is 16
Concatenation has meaning only for sequential processing - true
In VSAM the Minimum size of one CA is one Track and the maximum size is 15 or 16 (when stripped)
If two jobs have same job class and priority, they will be executed as if they are submitted - True (I have done this)
Accounting information max size : 142
Formatted Dump of the process program and system control blocks: SYSABEND
Step will always be executed within or not a preceding step abnormally terminateswhen coded as COND=EVEN
Region specifes the largest amount of main memory for any job step within a job.
REGION = 0K / 0M means all available space allocated to the job.
jOB or STEP has unlimited amount of time if TIME=1440
For variable length, un-blocked records logical record-length equals to BLOCKSIZE - False
IDCAMS is used to create a GDG.
In GDG same JCL code can be used to process every cycle with a single application - True
DFSORT is used for sorting and merging records
We
can't give Exit Program in main program since it wont give control back
to system. The Stop Run statement terminates the program (closes all
the opened files and performs some cleaning activity) and gives control
back to OS.
Maximum
record size of non-spanned control interval size is 32761 and the
maximum data component control interval size is 32768 (32761+7).
If
the record size is greater than CISZ we have to use 'SPANNED' option
and the maximum record size is MAXRECL = CI/CA * (CISZ - 10)
The
Edited Picture clause 'P' (Numeric Place Holder) is used to change the
precision. Ex 9PP can hold values like 1, 100 to 199 however when we
print the variable only the most significant digit will be shown.
Similarly, they can be used to tell the precision of decimal digits.
The ',' is used to print comma after the numeric digits. We can give the comma in normal pic clause variable.
If
the value stored in a numeric variable (PIC 9(3)CR.) is negative, it
will show the CR after the end otherwise blank is displayed.
The '*' is used to display '*' in the leading zero positions only.
If
we try to access a table/array element like arr[0] during compilation
the cobol compiler will find that as error. However, if we give a index 0
at run-time, the program will work without any abend. I don't know how
this is working.
CREATE UNIQUE INDEX EMPID_IDX ON TB_EMPLOYEE(EMPID);
Create Table without primary key then alter the table
+++++++++++++++++++++++++++++++++++++++
CREATE TABLE TB_EMPLOYEE(
EMP_ID INTEGER NOT NULL,
EMP_NAME CHAR(10) NOT NULL,
EMP_DESIGNATION CHAR(5) NOT NULL,
EMP_DEPT CHAR(3) NOT NULL
) IN DBTCHN01.TSCEP02;
CREATE UNIQUE INDEX IN_TB_EMPLOYEE
ON TB_EMPLOYEE(EMP_ID);
ALTER TABLE TB_EMPLOYEE
ADD PRIMARY KEY (EMP_ID);
Note:
++++
The PRIMARY Key field should be given NOT NULL otherwise it will not accept the alter command.
Unique Key
+++++++++
CREATE UNIQUE INDEX ON ()
The pre-requisites for the above statement is
1) The table can have only one NULL value
2) It should be unique with no duplicate values
'NULL' is also considered as a value here.
Add a new field to an existing table
+++++++++++++++++++++++++
ALTER TABLE TB_EMPLOYEE ADD
EMPADDR VARCHAR(50);
Using ALTER TABLE we can do the following
Add New Column
Add/Drop constraints
Increase the length of a column
However, we cant rename a column name
Add Foriegn Key
++++++++++++
CREATE TABLE TB_WAH(
EMPID VARCHAR(10) REFERENCES TB_EMPLOYEE(EMPID),
POINTS INTEGER
) IN DBCHN01.TSCEP01;
ALTER TABLE TB_WAH ADD
AWARDED_ON DATE;
Using GROUP BY
+++++++++++++
SELECT MAX(EMPSALARY), EMPADDR FROM TB_EMPLOYEE GROUP BY EMPADDR;
Select Timestamp
+++++++++++++
SELECT CURRENT TIMESTAMP FROM SYSIBM.SYSDUMMY1;
CREATE TABLE TB_COURSE_REG(
SCORE DECIMAL(5,2) CHECK (SCORE BETWEEN 60 AND 99),
AGE SMALLINT CHECK (AGE IN (18,19,20)),
GENDER CHAR(1) CHECK (GENDER IN ('M','F'))
) IN DBTCHN01.TSCEP02;
Static SQL
++++++++
Using Cursor to select, update, delete multiple records
Declaring a Cursor for select query
+++++++++++++++++++++++++
EXEC SQL
DECLARE
CURSOR
[WITH HOLD]
FOR
[FOR UPDATE OF]
END-EXEC
Opening a Cursor
++++++++++++
EXEC SQL
OPEN
END-EXEC
Fetch a Cursor
+++++++++++
EXEC SQL
FETCH
INTO
END-EXEC
Closing a Cursor
++++++++++++
EXEC SQL
OPEN
END-EXEC
Procedures in DB2
+++++++++++++++
CREATE PROCEDURE proc1
(IN var1 VARCHAR(10), OUT rc INTEGER)
SPECIFIC myproc LANGUAGE SQL
To call the above procedure from the CLP (Command Language Processor) we have to use
CALL PROC1('ATHIRUBAN', ?)
Isolation Level
++++++++++++
Repeatable
Read - Other transactions has to wait for the lock release acquired by
the current transaction for all the rows it refers.
Terminated by either COMMIT/ROLLBACK
Read
Stability - If some 1000 records are referred and 100 rows are
processed, locks are held only for the 100 rows and other transaction
can add/iinsert new rows.
Cursor
Stability - If some 1000 records are referred and 100 rows are
processed, lock is held by the current row pointed by the cursor.
This is useful for running concurrent transaction
Uncommitted read - No locks are acquired
Security
++++++
We can restrict the user to update on a single column alone using the following statement
GRANT UPDATE () ON TABLE TO
To give user the permission to drop an index, use the following statement
GRANT CONTROL ON INDEX TO
There is a difference between the following two statements
GRANT ALL PRIVILEGES ON TO PUBLIC/ (except CONTROL)
GRANT CONTROL ON TO (includes all)
The specific use of CONTROL allows the user to drop a table and also revoke a privilege from others + the normal privileges
The
person who creates a table automatically receives the CONTROL
privilege, only the DB/SYS Admin can give the CONTROL privilege to other
users
Pre-compilation and bind process
+++++++++++++++++++++++++++
The DCLGEN is used to check the SQL statements
The embedded SQL statements in COBOL are stripped and put into DBRM
The SQL code in COBOL is converted into COBOL equivalent calls
During
BIND, the DBRM is converted into PLAN after checking the SQL in DBRM
with SYSCATLG and optiimization (this needs a BIND authority)
If we have more than one programs we have to use PACKAGE
IRLM - Inter System Resource Lock Manager - controls locking process in DB2
Types of table Space
++++++++++++++++
Simple Table Space (rows are stored in not a sequence order)
Segmented Table Space (pages are grouped in segments)
Partitioned Table Space (pages are grouped in partitions)
Maximum no of tables that can be joined ?
Collections in DB2 - name for a set of logically related packages ?
Secondary key in RI ?
Grant command in SQL - refer
Subquery operator compares a single value to every member of set of value - Any ?
Explain
purpose in DB2 - allows the user to obtain information regarding the
optimizer's choice of access strategy for a given sql statements ?
Stored procedure is stored in which location?
SYSADM ?
SYSCAT.PACKAGES
What is BINDADD, CREATE_EXTERNAL_ROUTINE? (They are database privileges)
FAQs
++++
All plans are stored in SYSIBM db2 directory SYSPL
GroupBy doesn't do any sorting
Maximum no of tables that can be joined is 15 tables
SQL Code -922 Authorization failure
Storage group is a db2 object
Storage group is a set of volume on DASD.
Maximum no of volumes per storage group is 133
In DB2, data is physically stored in VSAM LDS
Different modes of locking ? - shared, exclusive and update
Every SQL statement is not always executable
We can use MAX on CHAR type
PACKAGE is a single bound DBRM with optimized access path
SUM returns NULL and COUNT, MAX returns zero
DBRM - Database Request Module
UNION operator eliminates the duplicate rows
If we try to SELECT from two tables, the result will contain a cartesian product of the two tables.
If a CURSOR is declared with the WITH HOLD option it is not closed by an explicit COMMIT statement.
A sub-query doesn't return NULL value (present in the table)to the result set
A VIEW created with a CHECK OPTION, is used ensure the inserted rows conforms with the defnition
The NULL values are displayed as a '-' in DB2 and 'NULL' in MySQL
It is possible to access data using VIEW, ALIAS or SYNONYM from a source table
After a failure, the DB Manager tries to rollback the transaction (that are not yet committed) after a restart
SELECT * FROM tab1 FETCH FIRST 50 ROWS ONLY - is the syntax to fetch n rows from a table regardless of how many rows present in the table
The wildcard '%' stands for any alphanumeric character and '_' stands for a single alphanumeric character
FULL OUTER JOIN combines INNER JOIN, RIGHT OUTER JOIN AND LEFT OUTER JOIN
LCASE('string') / LOWER('string') - is for converting string to lower-case form