1.1 Bashshell Directory Manipulation
|
Name of the current directory |
|
change the directory to cd
|
|
Change to home directory |
|
Change to parent directory |
|
Change to current directory |
|
Creates a new directory |
|
removes a directory |
|
Removes non-empty directory dir and all of its subdirectories and files |
|
Rename dir1 to dir2 |
1.2 Bashshell File Manipulation
|
Starts the gedit program to edit file hello.cpp |
|
compile hello.cpp to create executable a.o |
|
|
|
Copy file1 into file2 |
|
Copy dir1 (including its subdirectories) to dir2 |
|
|
|
remove file |
|
remove all files and directories in dir
|
|
Create an empty file called file
|
|
Display the content of file
|
File Security and Permission
ls -lt
print in long form with security level indication |
chmod [who] [operator] [permissions] filename
|
[who] u
= user; g
= group; o
= other; a
= all |
[operator] +
= add; -
= remove; =
set |
[permission] r
= read; w
= write; x
= execute |
1.3 Bash Shell Searching
find . -name "hello.txt" -type f
|
Search by name for a file |
find . -name "hello.*" -type f
|
Search any file type with the name "hello" |
find . -name "hello" -type d
|
Search for a directory called "hello" |
|
find .c files |
`find . -name "*.[ch]" |
find .c and .h files |
|
match beginning of a line |
|
match the end of a line |
|
match the exact contents of a line |
|
match zero or one occurrence |
|
match one or more occurrences |
|
match zero or more occurrences |
|
match a single character "p" |
|
match any character enclosed by [] |
|
3 occurrences of "ab" |
|
1 to 3 occurrences of "ab" |
|
3 or more occurrences of "ab" |
|
no. of occurrence for "UNIX" |
sed s/UNIX/Unix/g bar.txt
|
replace all "UNIX" to "Unix" |
Note that (ab) can also be other valid patterns
1.4 Useful Bash Shell Commands
|
return no. of bytes |
|
returns no. of lines |
|
returns no. of words |
|
sort file in alphabetical order and output the sorted texts |
|
numerical sort |
|
-r for reverse sort |
|
sort by field no. 3 |
|
sort by field no.3 but the delimiter is comma |
cut -d ' ' -f 1,3 example1
|
return 1st and 3rd columns where the delimiter is a space |
|
remove adjacent duplicate lines |
|
how to transform fileA to fileB |
|
add the line1 of fileB after line0 of fileA |
|
change line2,3 of fileA to line3 of fileB |
|
display all incorrect words in file |
|
change to super user mode |
|
install program |
1.5 Standard I/O and pipe
wc data.txt 1> result.txt
|
send standard output to file |
|
same as above |
|
append result of [command] to the file |
|
send standard error to file |
./add.o < input.txt > output.txt
|
add.o takes input from input.txt and output to output.txt |
|
C user input
int a; float b;
scanf("%d%f", &a, &b);
printf("%g", a*b);
|
C++ const keyword
BigInteger add(const BigInteger & a, const BigInteger & b)
{
// Cannot modify any of the parameters
}
string BigInteger::setNumber(string number) const {
// setNumber is a read-only function.
sign = "-"; // error because sign is a member variable of BigInteger
}
|
C++ Constructor
class Point{
private:
int x, y;
public:
Point() { // default
a = 10; b=20
}
Point(int x1, int y1){ // parameterised
x = x1; y = y1;
}
}
int main(){
Point p; // default
Point q(10, 20); // parameterised
}
|
Constructor is a member function that shares the same name as the class
C++ friend
// --- In .h file ---
class BigInteger{
public:
void setNumber( string );
string getNumber();
private:
char sign;
int length;
int value[100];
friend BigInteger add(BigInteger a, BigInteger b);
};
BigInteger add(BigInteger a, BigInteger b);
// add declaration of friend function AFTER the declaration fo the big integer class
// --- in .cpp file --- //
BigInteger add(BigInteger a, BigInteger {
// implement the function
}
|
|
|
2.1 Shell Script basics
|
print without \n |
|
read user input and store it in a var called "name" |
|
no quote |
|
single quote (strings) |
|
can handle special characters |
$ |
variable substitution |
\ |
escape special characters |
|
enclose bash commands |
a="`wc -l file | cut -d\"\" -f1`"
|
echo "there are $a lines in file"
|
2.2.1 Shell Script - Using Strings
|
length of string |
|
substring (assume index 0) |
|
change part of string |
a="Apple pie"; from="pie"; to="juice";
|
2.2.4 Shell Scripting - Variable as numbers
2.3 Shell Scripting - Control Flow
# --- if-else statements --- #
if [ condition ]
then
echo "Action 1"
elif [ condition2 ]
then
echo "Action2"
else
echo "Action neither"
fi
#example
#!/bin/bash
echo "Do you want to remove all .cpp files (Y/N)"
read ans
if [ "$ans" == "Y" ]
then
rm -rf *.cpp
echo "All .cpp files are removed"
fi
# --- for-in loop --- #
#!/bin/bash
list="1 2 3 4 5"
for i in $list
do
echo "This is iteration $i"
done
# --- for-loop with a range --- #
for ((i=0; i<=100; i=i+3))
do
echo $i
done
|
2.4 Shell Scripting - Useful techniques
|
number of arguments input by user |
|
1st argument, 2nd argument, etc |
cp file123 fileabc 1> /dev/null 2> &1
|
/dev/null
is system dust bin |
&1
is the standard output |
echo "$0:error:Copy failed" >&2
|
|
Shell Script Conditions
String comparison |
|
iff length of s is non-zero |
|
|
|
s1 sorted after s2 |
|
File Checking |
|
iff exists |
|
iff is a file |
|
iff is a directory |
Number Comparison |
|
iff a = b |
|
iff a!=b |
|
iff a<b |
|
iff a<=b |
|
iff a>b |
|
iff a>=b |
Iterate words in a file
list=`cat wordlist.txt`
for line in $list
do
echo "$line"
done
|
C++ Misc
void func(int array[]);
// array as parameter |
C++ Dynamic Array
int * a = NULL; int n;
cin >> n; a = new int[n];
...
delete[] a; // free memory
|
Pointers C++
|
define a pointer |
|
address of foo |
|
value pointed by baz |
|
parameter is a pointer |
|
parameter is address of pointer |
modifying the parameter modifies the original variable |
C++ Linked List and Various functions
int main(){ Node *head = NULL; ... }
void headInsert(Node *&head, int k, int v){
Node *newNode = new Node;
newNode -> key = k;
newNode -> value = v;
newNode -> next = head;
head = newNode;
}
void printList(Node *head){
Node *current = head;
while (current!=NULL){
cout << "Key:" << current->key << ",value:" << current->value << endl;
current = current->next;
}
}
bool isSorted(Node *head){
Node *current = head;
Node *previous = NULL;
while (current!=NULL){
if (previous !=NULL){
if (previous->key > current->key)
return false;
}
previous = current;
current = current->next;
}
return true;
}
void insertInOrder(Node *&head, int k){
Node *newNode = new Node;
newNode->key = k;
if (head == NULL)
{
newNode->next = NULL;
head = newNode;
}
else
{
Node *current= head;
Node *previous = NULL;
while(current!=NULL)
{
if (current->key > k)
break;
previous = current;
current=current->next;
}
newNode->next = current;
if (previous!=NULL)
previous->next = newNode;
else
head = newNode;
}
}
|
4. Separate Compilation and Makefile
census.o: census.cpp BigInteger.h Country.h
g++ -c census.cpp
BigInteger.o:BigInteger.h BigInteger.cpp
g++ -c BigInteger.cpp
Country.o:BigInteger.h Country.h Country.cpp
g++ -c Country.cpp
census:census.o BigInteger.o Country.o
g++ census.o BigInteger.o Country.o -o census
|
C++ Traverse Linked List using for-loop
void TraverseList(Node *head){
for(Node *n = head; n -> next != NULL; n = n -> next){//do something to n}
}
|
C++ Operator overloading
// Using friend functions
BigInteger operator+(const BigInteger &a, const BigInteger &b);
istream &operator >> (istream &cin, BigInteger &b);
ostream &operator << ostream &cout, BigInteger &b);
|
C AVL Tree - Node and maximum
struct treeNode {
int key; struct treeNode * left;
struct treeNode * right;
}
typedef struct treeNode treeNode;
int maximum(int a, int b){
return (a > b ? a : b);
}
|
C AVL - Rotation Functions
treeNode* R_rotation(treeNode *parent){
treeNode *child = parent -> left;
parent -> left = child -> right;
child -> right = parent; return child;}
treeNode* L_rotation(treeNode *parent){
treeNode *child = parent -> right;
parent -> right = child -> left;
child -> left = parent; return child;}
treeNode* LR_rotation(treeNode *parent){
treeNode *child = parent -> left;
parent -> left = L_rotation(child);
return R_rotation(parent);}
treeNode* RL_rotation(treeNode *parent){
treeNode *child = parent -> right;
parent -> right = R_rotation(child);
return L_rotation(parent);}
|
C AVL - Insert()
treeNode* Insert(treeNode *currentNode, int key){
if(currentNode == NULL){
currentNode = (treeNode*)malloc(sizeof(treeNode));
currentNode -> key = key;
currentNode -> left = currentNode -> right = NULL;
}
else if(key > currentNode -> key){
currentNode -> right = Insert(currentNode -> right, key);
currentNode = balance_tree(currentNode);
}
else if(key < currentNode -> key) {
currentNode -> left = Insert(currentNode -> left, key);
currentNode = balance_tree(currentNode);
}
else {
printf("fail! - duplicated key \n");
exit(-1);
}
return currentNode;
}
|
C AVL - get_height
int get_height(treeNode *currentNode)
{
if(currentNode == NULL)
return 0;
else{
int height = 1 + maximum(get_height(currentNode->left), get_height(currentNode->height));
return height;
}
}
|
C AVL - getBalance()
int get_balance(treeNode * currentNode){
if(currentNode == NULL) return 0;
else return get_height(currentNode->left) - get_height(currentNode->height);
}
|
C AVL - balance_tree()
treeNode* balance_tree(treeNode * currentNode){
int height_diff = get_balance(currentNode);
if(height_diff > 1)
{
if(get_balance(currentNode -> left) > 0){
currentNode = R_rotation(currentNode);
} else {
currentNode = LR_rotation(currentNode);
}
} else if(height_diff < -1){
if(get_balance(currentNode->right) < 0){
currentnode = L_rotation(currentNode);
} else {
currentNode = RL_rotation(currentNode);
}
}
return currentNode;
}
|
C AVL - main()
int main(){
treeNode *root = NULL; root = Insert(root, 5);}
|
|
|
5.1 Containers
|
vector definition |
|
i-th item in the vector |
|
remove last item |
|
size of vector |
|
list definition |
|
insert item at front |
|
insert item at back |
|
remove the first item |
|
remove last item |
|
access the first item |
|
access the last item |
|
return num of items |
|
map definition |
|
i-th item in the list |
|
return no. of pairs in the map with key = k |
|
no. of items |
Using map with user define objects
bool operator<(const Record& a, const Record& b){
return a.name < b.name;
}
|
Must overload "<" operator
Directives for STL
#include<vector>; #include<list>; #include<map>; #include<algorithm>;
|
Algorithms
Sorting |
sort(v.begin(), v.end())
// vector |
|
c.sort()
// list and maps |
sort(v,begin(), v.end(), compare);
// descend |
bool compare(int a, int b){ return a > b; }
|
overload operator<()
for special tricks |
Binary Search |
binary_search(v.begin(), v.end(), target); //returns bool
|
"target" is what you are looking for in v |
Upper & lower bound |
`lower_bound(v.begin(), v.end(), target); // returns ForwardIterator" |
upper_bound(v.begin(), v.end(), target);
|
lower_bound()
returns the earliest postion |
upper_bound()
returns the lastest position |
binary_search()
, upper_bound()
and lower_bound()
can be used with vectors
, lists
, and maps
|
Random Shuffle (see appendix) |
need <cstdlib>
, <ctime>
, srand(time(NULL))
|
C++ STL Template Class
template <class T>
class MyCollection{
vector<T> data;
public:
void Add(const T &);
};
template <class T>
void MyCollection <T> :: Add(const T & d){
data.push_back(d);
}
|
C++ Template Operator Overloading (One-to-one)
template <class T>
class MyCollection{
vector<T> data;
public:
void Add(T const &);
T & Draw();
friend ostream & operator<<(ostream & cout, const MyCollection<T> &q){
cout << "Collection" << endl;
typename vector<T>::const_iterator itr;
for(itr =q.data.begin(); itr != q.data.end(); itr++)
cout << " " << *itr << endl;
return cout;
}
}
|
C++ Template Overloading (many-to-many)
template <class T>
class MyCollection{
vector<T> data;
public:
void Add(T const &);
T & Draw();
template <class U>
friend ostream & operator<<(ostream & cout, const MyCollection<U>& q);
};
template <class U>
ostream & operator<<(ostream &cout, const MyCollection<U> & q)
{
typename vector<U>::const_iterator itr;
... (same)
}
|
C Conversion Specifier
int |
%d |
float |
%f |
double |
%lf |
char |
%c |
string |
%s |
C string
|
char name[100]; scanf("%s", name);
|
|
more functions |
strcopy(char s1[], char s2[])
|
copy s2 to s1 |
strcat(char s1[], char s2[])
|
append s2 to end of s1 |
strcmp(char s1[], char s2[])
|
return -ive if s1<s2. return +ive if s1>s2. return 0 if s1==s2 |
|
return length of string |
C Functions
Pass by reference |
void swap(double *a, double *b){...}
|
Using this function: pass the address |
|
C Arrays
|
a[i]
is the same as *(a+i)
|
C Memory Allocation
int size; int *a; scanf("%d", &size);
|
a = malloc(size*sizeof(int));
|
|
C Structure and typedef
struct student { char name[20]; int uid; }
typedef struct student student;
int main(){ student a; ... }
|
Python
|
type casting |
|
concatenation |
|
access i-th |
|
substring s[1] to s[4] |
|
s[1] to end |
|
start to s[3] |
|
length of the string |
|
print without newline |
|
take user input as strings |
Python File Input
with open("filename", "mode") as f:
|
open file. define scope |
|
end of scope |
|
read from file |
|
write to the file |
file modes |
r |
read only |
r+ |
reading and writing |
w |
write only |
w+ |
writing and reading (overwrite) |
a |
appending |
a+ |
appending and reading |
Python Flow of Control
#if-else statement
if condition:
statement
elif condition:
statement
else:
statement
|
Conditions are not enclosed by brackets
Python For-loops
for i in list:
statement
statement
#Example 1
i = 1
for dir in [ "n", "e", "w", "s" ]:
print "the" + str(i) + "-th direction is" + dir
i+=1
#Example2
for i in range(0, 71):
if i % 7 == 0:
print i,
|
Python Array
|
empty array with size i |
|
i-th item in array |
|