Age Priorities list.cpp
#include<iostream>
using namespace std;
struct Queue {
string name;
int age;
char gender;
};
struct Node {
Queue data;
Node* next;
};
class linkedlist {
private:
Node* head;
public:
linkedlist() {
head = NULL;
}
void insertQueue() {
Node* point = new Node();
cout << "\nEnter Name: ";
cin >> point->data.name;
cout << "\nEnter Age: ";
cin >> point->data.age;
cout << "\nEnter Gender (M/F): ";
cin >> point->data.gender;
point->next = NULL;
if (head == NULL || point->data.age > head->data.age) {
point->next = head;
head = point;
} else {
Node* temp = head;
while (temp->next != NULL && temp->next->data.age >= point->data.age) {
temp = temp->next;
}
point->next = temp->next;
temp->next = point;
}
}
void serveQueue() {
if (head == NULL) {
cout << "\nThe Queue is Empty!\n";
return;
}
cout << "Processing...... \n" << head->data.name << " has been served\n";
switch (head->data.gender) {
case 'M': case 'm':
cout << "Because he is " << head->data.age << " years old\n";
break;
case 'F': case 'f':
cout << "Because she is " << head->data.age << " years old\n";
break;
default:
cout << "Because (he/she) is " << head->data.age << " years old\n";
break;
}
Node* temp = head;
head = head->next;
delete temp;
}
void displayQueue() {
if (head == NULL) {
cout << "\nThe Queue is Empty!\n";
return;
}
Node* temp = head;
int i = 1;
while (temp) {
cout << "\nPerson " << i << ":\n";
cout << "Name: " << temp->data.name << "\n";
cout << "Age: " << temp->data.age << "\n";
cout << "Gender: " << temp->data.gender << "\n";
temp = temp->next;
i++;
}
}
};
int main() {
linkedlist hospital;
int n;
menu:
cout << "\n1. Enter a person in the Queue.";
cout << "\n2. Serve a person.";
cout << "\n3. Show the list.";
cout << "\n4. Exit\n";
cout << "Enter choice: ";
cin >> n;
switch (n) {
case 1:
hospital.insertQueue();
goto menu;
case 2:
hospital.serveQueue();
goto menu;
case 3:
hospital.displayQueue();
goto menu;
case 4:
return 0;
default:
cout << "\nInvalid choice! Try again.\n";
goto menu;
}
}
Assignment 2
#include <iostream>
#include <string>
using namespace std;
struct transation {
int transaction_ID = 1;
string type;
int purchase;
transation* next;
transation* prv;
};
struct accounts {
int acc_id = 1;
string user_name;
accounts* next;
transation* head;
accounts* prv;
};
class tran {
public:
void insertinlink(transation*& head) {
char ck;
do {
int purchase;
string tp;
cout << "\nEnter Purchase: ";
cin >> purchase;
cin.ignore();
cout << "\nEnter Note: ";
getline(cin, tp);
transation* node = new transation();
node->purchase = purchase;
node->type = tp;
if (head) {
transation* temp = head;
while (temp->next) {
temp = temp->next;
}
node->transaction_ID = temp->transaction_ID + 1;
temp->next = node;
node->prv = temp;
} else {
head = node;
}
node->next = NULL;
cout << "\nPress 'Y' to enter another transaction: ";
cin >> ck;
} while (ck == 'Y' || ck == 'y');
}
void searchtran(transation* head) {
transation* temp = head;
while (temp) {
cout << "\nTransaction ID: " << temp->transaction_ID << endl;
cout << "Purchase: " << temp->purchase << endl;
cout << "Note: " << temp->type << endl;
temp = temp->next;
}
}
void totaltransations(transation* head) {
transation* temp = head;
int sum = 0;
while (temp) {
sum += temp->purchase;
temp = temp->next;
}
cout << "\nThe Total amount you have spent is: " << sum << " Rs\n";
}
void display(transation* head) {
transation* temp = head;
while (temp) {
cout << "\nTransaction ID: " << temp->transaction_ID << endl;
cout << "Purchase: " << temp->purchase << endl;
cout << "Note: " << temp->type << endl;
temp = temp->next;
}
}
};
class record {
accounts* acc_head;
int count = 0;
public:
record() {
acc_head = NULL;
}
void newaccount() {
string name;
cout << "\nEnter Name: ";
cin.ignore();
getline(cin, name);
accounts* acc = new accounts();
count++;
if (acc_head) {
accounts* temp = acc_head;
while (temp->next) {
temp = temp->next;
}
acc->acc_id = temp->acc_id + 1;
temp->next = acc;
acc->prv = temp;
} else {
acc_head = acc;
acc->prv = NULL;
}
cout << "\nYour Account ID is: " << acc->acc_id << endl;
acc->user_name = name;
acc->next = NULL;
acc->head = NULL;
tran chain;
chain.insertinlink(acc->head);
}
void searchaccount() {
int acid, attempts = 3;
string pn;
while (attempts > 0) {
cout << endl << "Enter Name: ";
cin.ignore();
getline(cin, pn);
cout << endl << "Enter Account ID: ";
cin >> acid;
accounts* temp = acc_head;
while (temp) {
if (pn == temp->user_name && acid == temp->acc_id) {
cout << "\n \t Transaction records\n\n";
tran temp1;
temp1.searchtran(temp->head);
return;
}
temp = temp->next;
}
attempts--;
if (attempts > 0) {
cout << endl << "Invalid ID or Name! Attempts left: " << attempts << endl;
} else {
cout << endl << "Access limit reached! Returning to menu..." << endl;
}
}
}
void addtoaccount() {
int acid, attempts = 3;
string pn;
while (attempts > 0) {
cout << endl << "Enter Name: ";
cin.ignore();
getline(cin, pn);
cout << endl << "Enter Account ID: ";
cin >> acid;
accounts* temp = acc_head;
while (temp) {
if (pn == temp->user_name && acid == temp->acc_id) {
tran temp1;
temp1.insertinlink(temp->head);
return;
}
temp = temp->next;
}
attempts--;
if (attempts > 0) {
cout << endl << "Invalid ID or Name! Attempts left: " << attempts << endl;
} else {
cout << endl << "Access limit reached! Returning to menu..." << endl;
}
}
}
int totalacc() {
return count;
}
void totalexpense() {
int acid, attempts = 3;
string pn;
while (attempts > 0) {
cout << endl << "Enter Name: ";
cin.ignore();
getline(cin, pn);
cout << endl << "Enter Account ID: ";
cin >> acid;
accounts* temp = acc_head;
while (temp) {
if (pn == temp->user_name && acid == temp->acc_id) {
tran temp1;
temp1.totaltransations(temp->head);
return;
}
temp = temp->next;
}
attempts--;
if (attempts > 0) {
cout << endl << "Invalid ID or Name! Attempts left: " << attempts << endl;
} else {
cout << endl << "Access limit reached! Returning to menu..." << endl;
}
}
}
void display() {
accounts* temp = acc_head;
while (temp) {
cout << "\nName: " << temp->user_name << endl;
cout << "Account ID: " << temp->acc_id << endl;
char ans;
cout << "\nPress 'Y' if you want transaction details: ";
cin >> ans;
if (ans == 'y' || ans == 'Y') {
tran temp1;
temp1.display(temp->head);
}
temp = temp->next;
}
}
};
int main() {
int a, pass = 1234, p;
record m;
while (true) {
cout << "\t\tMenu\n";
cout << endl << "1. New Account.";
cout << endl << "2. Search Account.";
cout << endl << "3. Add Transaction to Existing Account.";
cout << endl << "4. Display Number of Accounts.";
cout << endl << "5. Total Transactions of an Account.";
cout << endl << "6. Display All Accounts.";
cout << endl << "7. Exit.";
cout << endl << "\nEnter choice: ";
cin >> a;
switch (a) {
case 1:
m.newaccount();
break;
case 2:
m.searchaccount();
break;
case 3:
m.addtoaccount();
break;
case 4:
cout << "\nTotal accounts are: " << m.totalacc() << endl;
break;
case 5:
m.totalexpense();
break;
case 6:
cout << "Enter Password: ";
cin >> p;
if (pass == p) m.display();
else cout << "\nInvalid password!\n";
break;
case 7:
return 0;
default: cout << "\nInvalid choice! Try again.\n";
}
}
}
Level Wise printing of nodes of Tree.cpp
#include<iostream>
#include<queue>
using namespace std;
class node {
public:
int data;
node* left;
node* right;
node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
class tree {
int a[100]; // increased array size for more flexibility
int i = 0, c = 0;
public:
node* insert(node* root, int val) {
if (root == NULL) {
return new node(val);
}
if (val < root->data) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
void display_level(node* root) {
queue<node*> q;
int l = 0;
if (root == NULL) return;
q.push(root);
q.push(NULL);
while (!q.empty()) {
node* curr = q.front();
q.pop();
if (curr == NULL) {
if (!q.empty()) {
cout << endl;
q.push(NULL);
l++;
continue;
} else {
l++;
break;
}
}
cout << curr->data << " ";
if (curr->left) q.push(curr->left);
if (curr->right) q.push(curr->right);
}
cout << "\n\nHeight of tree is: " << l << endl;
}
void cout_leafs(node* root) {
if (root == NULL) return;
if (root->left == NULL && root->right == NULL) {
a[i++] = root->data;
c++;
}
cout_leafs(root->left);
cout_leafs(root->right);
}
void display_leafs() {
cout << "\nTotal leaf nodes: " << c << endl;
cout << "Leaf nodes: ";
for (int j = 0; j < i; j++) {
cout << a[j] << " ";
}
cout << endl;
i = c = 0;
}
void count_parents(node* root) {
if (root == NULL) return;
if (root->left != NULL || root->right != NULL) {
a[i++] = root->data;
c++;
}
count_parents(root->left);
count_parents(root->right);
}
void display_parents() {
cout << "\nTotal parent nodes: " << c << endl;
cout << "Parent nodes: ";
for (int j = 0; j < i; j++) {
cout << a[j] << " ";
}
cout << endl;
i = c = 0;
}
void siblings(node* root) {
if (root == NULL) return;
if (root->left != NULL || root->right != NULL) {
cout << "\nParent: " << root->data << " => Children: ";
if (root->left) cout << root->left->data << " ";
if (root->right) cout << root->right->data << " ";
}
siblings(root->left);
siblings(root->right);
}
void count_sub_trees(node* root) {
static int s = -1;
if (root == NULL) return;
if (s != -1) {
a[i++] = root->data;
c++;
}
s++;
count_sub_trees(root->left);
count_sub_trees(root->right);
}
void display_sub_trees() {
cout << "\nTotal subtrees (excluding root): " << c << endl;
cout << "Subtree roots: ";
for (int j = 0; j < i; j++) {
cout << a[j] << " ";
}
cout << endl;
i = c = 0;
}
};
int main() {
tree t;
node* root = NULL;
int n, val;
cout << "Enter number of nodes to insert in BST: ";
cin >> n;
cout << "Enter " << n << " integers:\n";
for (int i = 0; i < n; i++) {
cin >> val;
root = t.insert(root, val);
}
cout << "\nLevel Order Traversal:\n";
t.display_level(root);
t.cout_leafs(root);
t.display_leafs();
t.count_parents(root);
t.display_parents();
t.siblings(root);
t.count_sub_trees(root);
t.display_sub_trees();
return 0;
}
README.md
# Data Structures and Algorithms Showcase
## 1. Project Overview
This repository serves as a collection of C++ and Python implementations of common data structures and algorithms. It is designed for educational purposes, providing clear examples of how these fundamental concepts are put into practice.
A key feature of this project is an HTML generation script (`generate_html.py`). This script automatically creates a browsable web page (`generated_index.html`) that lists all code files in the repository and allows you to view their content directly in your browser, making it easy to explore the various examples.
The main objectives are:
* To offer practical, understandable examples of data structures and algorithms.
* To provide a simple and convenient way to navigate and view the codebase.
## 2. Installation Instructions
To work with the examples in this repository, you'll need the appropriate compilers/interpreters.
### C++ Examples
* **Compiler:** A C++ compiler (like g++ or Clang) is required.
* **Compilation:** Navigate to the directory containing the C++ source file and compile it using a command similar to:
```bash
g++ -o <output_executable_name> <source_file_name>.cpp
```
For example, to compile `Simple Queue.cpp`:
```bash
g++ -o simple_queue "Simple Queue.cpp"
```
(Note: Files with spaces in their names, like `"Simple Queue.cpp"`, should be quoted in the terminal).
### Python Examples
* **Interpreter:** Python 3 (version 3.6 or newer recommended) must be installed on your system.
* **Dependencies:** The Python scripts in this repository generally use standard libraries and do not require separate installation of external packages.
### HTML Code Showcase Generation
* **Interpreter:** Python 3 is required to run the `generate_html.py` script.
* **Dependencies:** The script uses standard Python libraries (`os`, `html`, `argparse`) and does not require additional package installations.
* **Template:** The script uses `index.html` as a template for generating the output file `generated_index.html`.
## 3. Usage Guidelines
### Running C++ Examples
1. **Compile:** Follow the compilation instructions above.
2. **Execute:** Run the compiled executable from your terminal:
```bash
./<output_executable_name>
```
For example:
```bash
./simple_queue
```
Most C++ examples provide a command-line menu for interaction.
### Running Python Examples
1. **Execute:** Run the Python scripts directly from your terminal:
```bash
python <script_name>.py
```
For example, to run the linked list example:
```bash
python linkedlist.py
```
The `linkedlist.py` script offers an interactive command-line menu.
### Using the HTML Code Showcase
1. **Generate/Update:** To create or update the HTML showcase, run the `generate_html.py` script from the root of the repository:
```bash
python generate_html.py
```
This will process the files and create/overwrite `generated_index.html`.
2. **View:** Open the `generated_index.html` file in any modern web browser to explore the repository's code. You can click on file names in the list to view their content.
3. **Custom Directory (Advanced):** The `generate_html.py` script can also target other directories. For usage details, you can run:
```bash
python generate_html.py --help
```
### Expected Outcomes and Known Limitations
* **Standalone Examples:** Each C++ and Python example is generally self-contained and designed to demonstrate a specific concept. They do not typically interact with each other.
* **HTML Generator:**
* The `generate_html.py` script is designed for text-based code files. It might not correctly display binary files or very large files.
* It attempts to handle different character encodings but may encounter issues with highly unusual encodings.
* **File Naming:** Some C++ files have spaces in their names (e.g., `Age Priorities list.cpp`). This is generally not standard practice and might require careful handling (e.g., quoting file names) when compiling or managing them on the command line. Using quotes as shown in the compilation example is recommended.
## 4. Contribution Guidelines
We welcome contributions to enhance this collection of examples!
### Reporting Issues
* If you find a bug, a typo, or have trouble with any part of the project, please clearly describe the issue. (If this were a GitHub project, you'd "open an issue on the GitHub repository.") For now, consider documenting it if you fork the project.
### Suggesting Features or New Examples
* If you have ideas for new data structure/algorithm examples or improvements to existing ones, these are welcome.
* Provide a clear description of the feature or example and its relevance.
### Submitting Changes (e.g., Pull Requests)
1. **Fork & Branch:** (Standard Git workflow) Fork the repository and create a new branch for your changes.
2. **Code:**
* Ensure new code is well-commented and easy to understand.
* If adding new C++ or Python examples, try to keep them self-contained.
* Follow the general coding style of the existing examples or use common best practices for the respective language.
3. **Update HTML Showcase:** If you add, remove, or rename code files, **you must re-run the `generate_html.py` script** to ensure `generated_index.html` is up-to-date:
```bash
python generate_html.py
```
Include the updated `generated_index.html` in your changes.
4. **Commit Messages:** Write clear and concise commit messages, explaining the purpose of your changes.
5. **Submit:** (Standard Git workflow) Push your changes to your fork and submit a pull request to the main repository.
---
This README provides a guide to understanding, installing, using, and contributing to this project.
Simple Queue.cpp
#include<iostream>
using namespace std;
struct Queue {
string name;
int age;
char gender;
};
struct Node {
Queue data;
Node* next;
};
class linkedlist {
private:
Node* head;
int front = -1;
int rare = -1;
public:
linkedlist() {
head = NULL;
}
void insertQueue() {
rare++;
Node* point = new Node();
cout << "\nEnter Name:";
cin >> point->data.name;
cout << "\nEnter Age:";
cin >> point->data.age;
cout << "\nEnter Gender (M/F):";
cin >> point->data.gender;
point->next = NULL;
if (rare == 0) {
front = 0;
}
if (head == NULL) {
head = point;
} else {
Node* temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = point;
}
}
void serveQueue() {
if (front >= 0) {
if (head == NULL) {
cout << "\nThe Queue is Empty!\n";
return;
}
cout << "Processing...... " << head->data.name << " has been served\n";
switch (head->data.gender) {
case 'M': case 'm':
cout << "Because he is " << head->data.age << " years old\n";
break;
case 'F': case 'f':
cout << "Because she is " << head->data.age << " years old\n";
break;
default:
cout << "Because (he/she) is " << head->data.age << " years old\n";
break;
}
Node* temp = head;
head = head->next;
delete temp;
rare--;
if (rare < 0) front = -1;
} else {
cout << "\nThe Queue is Empty!\n";
}
}
void displayQueue() {
if (front >= 0 && head != NULL) {
Node* temp = head;
int i = 1;
while (temp) {
cout << "\nPerson " << i << ":\n";
cout << "Name: " << temp->data.name << "\n";
cout << "Age: " << temp->data.age << "\n";
cout << "Gender: " << temp->data.gender << "\n";
temp = temp->next;
i++;
}
} else {
cout << "\nThe Queue is Empty!\n";
}
}
};
int main() {
linkedlist hospital;
int n;
menu:
cout << "\n1. Enter a person in the Queue.";
cout << "\n2. Serve a person.";
cout << "\n3. Show the list.";
cout << "\n4. Exit\n";
cout << "Enter choice: ";
cin >> n;
switch (n) {
case 1:
hospital.insertQueue();
goto menu;
case 2:
hospital.serveQueue();
goto menu;
case 3:
hospital.displayQueue();
goto menu;
case 4:
return 0;
default:
cout << "\nInvalid choice! Try again.\n";
goto menu;
}
}
Song Playlist.cpp
#include<iostream>
using namespace std;
class Song{
public:
string name;
string title;
Song* prev;
Song* next;
Song(){
name="";
title="";
prev=NULL;
next=NULL;
}
};
class playlist{
Song* head;
Song* current;
int count=0;
public:
playlist(){
head=NULL;
current=NULL;
}
void addsong(){
Song* newsong=new Song();
cout<<"Enter Song Name:";
cin>>newsong->name;
cout<<"Enter Song Title:";
cin>>newsong->title;
if(head==NULL){
head=newsong;
newsong->next=NULL;
newsong->prev=NULL;
current=newsong;
count++;
return;
}else{
Song* temp=head;
while(temp->next){
temp=temp->next;
}
newsong->prev=temp;
temp->next=newsong;
}
current=newsong;
count++;
}
void playcurrentsong(){
if(count<1){
cout<<"\n No Song is currently in the list.\n";
return;
}
cout<<"\nPlaying Song...........\n";
cout<<"Name: "<<current->name<<endl;
cout<<"Title: "<<current->title<<endl;
}
void nextsong(){
if(current->next==NULL){
cout<<"\nThere is no Next Song\n";
return;
}
cout<<"\nMoving to the next Song.\n";
current=current->next;
}
void prevsong(){
if(current->prev==NULL){
cout<<"\nThere is no Previous Song\n";
return;
}
cout<<"\nMoving to the previous Song.\n";
current=current->prev;
}
};
int main(){
playlist youtube;
int n;
menu:
cout<<"\n----Menu----\n";
cout<<"\n1. Add a Song";
cout<<"\n2. Play Current Song";
cout<<"\n3. Previous Song";
cout<<"\n4. Next Song";
cout<<"\n5. Exit App";
cout<<"\nEnter your choice:";
cin>>n;
switch(n){
case 1:{
youtube.addsong();
goto menu;
}
case 2:{
youtube.playcurrentsong();
goto menu;
}
case 3:{
youtube.prevsong();
goto menu;
}
case 4:{
youtube.nextsong();
goto menu;
}
case 5:{
cout<<"\nThe Application is Closing..............\n";
break;
}
default:{
cout<<"\n Invalid Enter! Chose form the menu.\n";
goto menu;
}
}
}
Tree In Order Traversing.cpp
#include<iostream>
using namespace std;
class node {
public:
int d;
node *left, *right;
node(int val) : d(val), left(NULL), right(NULL) {}
};
class B {
public:
node* insert(node* r, int v) {
if (r == NULL){
return new node(v);
}
if (v < r->d){
r->left = insert(r->left, v);
}
else if (v > r->d){
r->right = insert(r->right, v);
}
return r;
}
void in_o(node* r) {
if (r == NULL) return;
in_o(r->left);
cout << r->d << " ";
in_o(r->right);
}
};
int main() {
node *r = NULL;
B c;
int n, val;
cout << "How many values? ";
cin >> n;
cout << "Enter values:\n";
for (int i = 0; i < n; ++i) {
cin >> val;
r = c.insert(r, val);
}
cout << "Inorder traversal: ";
c.in_o(r);
cout << endl;
return 0;
}
Tree Post Order Traversing.cpp
#include<iostream>
using namespace std;
class node {
public:
int d;
node *left, *right;
node(int val) : d(val), left(NULL), right(NULL) {}
};
class B {
public:
node* insert(node* r, int v) {
if (r == NULL){
return new node(v);
}
if (v < r->d){
r->left = insert(r->left, v);
}
else if (v > r->d){
r->right = insert(r->right, v);
}
return r;
}
void post_o(node* r) {
if (r == NULL) return;
post_o(r->left);
post_o(r->right);
cout << r->d << " ";
}
};
int main() {
node *r = NULL;
B c;
int n, val;
cout << "How many values? ";
cin >> n;
cout << "Enter values:\n";
for (int i = 0; i < n; ++i) {
cin >> val;
r = c.insert(r, val);
}
cout << "Postorder traversal: ";
c.post_o(r);
cout << endl;
return 0;
}
Tree Pre Order Traversing.cpp
#include<iostream>
using namespace std;
class node {
public:
int d;
node *left, *right;
node(int val) : d(val), left(NULL), right(NULL) {}
};
class B {
public:
node* insert(node* r, int v) {
if (r == NULL){
return new node(v);
}
if (v < r->d){
r->left = insert(r->left, v);
}
else if (v > r->d){
r->right = insert(r->right, v);
}
return r;
}
void pre_o(node* r) {
if (r == NULL) return;
cout << r->d << " ";
pre_o(r->left);
pre_o(r->right);
}
};
int main() {
node *r = NULL;
B c;
int n, val;
cout << "How many values? ";
cin >> n;
cout << "Enter values:\n";
for (int i = 0; i < n; ++i) {
cin >> val;
r = c.insert(r, val);
}
cout << "Preorder traversal: ";
c.pre_o(r);
cout << endl;
return 0;
}
Tree.cpp
#include<iostream>
using namespace std;
class node {
public:
int d;
node *left, *right;
node(int d) {
this->d = d;
left = right = NULL;
}
};
class B {
public:
node* insert(node* r, int v) {
if (r == NULL) {
return new node(v);
}
if (v < r->d) {
r->left = insert(r->left, v);
} else if (v > r->d) {
r->right = insert(r->right, v);
}
return r;
}
void pre_o(node* r) {
if (r == NULL) return;
cout << r->d << " ";
pre_o(r->left);
pre_o(r->right);
}
};
int main() {
node *r = NULL;
B c;
int n, val;
cout << "How many values do you want to insert? ";
cin >> n;
cout << "Enter " << n << " integer values:\n";
for (int i = 0; i < n; ++i) {
cin >> val;
r = c.insert(r, val);
}
cout << "Preorder traversal of the tree: ";
c.pre_o(r);
cout << endl;
return 0;
}
Website history forward and backward in linked list.cpp
#include<iostream>
using namespace std;
class website {
public:
website* next;
string WebName;
website* prev;
website() {
next = NULL;
WebName = "";
prev = NULL;
}
};
class browser {
private:
website* head;
website* recent;
public:
browser() {
head = NULL;
recent = NULL;
}
void search() {
website* domain = new website();
cout << "\nEnter Website you want to search: ";
cin >> domain->WebName;
cout << "\n" << domain->WebName << " is essential for nowadays. \n";
if (head == NULL) {
domain->next = NULL;
domain->prev = NULL;
head = domain;
recent = domain;
return;
}
website* temp = head;
while (temp->next) {
temp = temp->next;
}
domain->prev = temp;
temp->next = domain;
recent = domain;
}
void history() {
if (recent == NULL) {
cout << "\nNo history available.\n";
return;
}
website* temp = recent;
cout << "\nBrowsing History:\n";
while (temp != NULL) {
cout << temp->WebName << "\n";
temp = temp->prev;
}
}
void forward() {
if (recent == NULL || recent->next == NULL) {
cout << "\nThere is no Next Tab\n";
return;
}
recent = recent->next;
cout << "\nThe Next Tab: " << recent->WebName << endl;
}
void previous() {
if (recent == NULL || recent->prev == NULL) {
cout << "\nThere is no Previous Tab\n";
return;
}
recent = recent->prev;
cout << "\nThe Previous Tab: " << recent->WebName << endl;
}
void deletehistory() {
if (head == NULL) {
cout << "\nHistory is empty.\n";
return;
}
int pos;
cout << "Enter the position to delete (1-based index): ";
cin >> pos;
website* temp = head;
int count = 1;
while (temp != NULL && count < pos) {
temp = temp->next;
count++;
}
if (temp == NULL) {
cout << "\nInvalid position.\n";
return;
}
if (temp == recent) {
if (temp->prev)
recent = temp->prev;
else if (temp->next)
recent = temp->next;
else
recent = NULL;
}
if (temp == head) {
head = temp->next;
if (head)
head->prev = NULL;
} else {
temp->prev->next = temp->next;
}
if (temp->next)
temp->next->prev = temp->prev;
cout << "\nDeleted: " << temp->WebName << endl;
delete temp;
}
};
int main() {
browser google;
int n = 0;
do {
cout << "\n-----MENU-----\n";
cout << "1. Browse a Website\n";
cout << "2. Show History\n";
cout << "3. Forward Tab\n";
cout << "4. Previous Tab\n";
cout << "5. Delete History at Position\n";
cout << "6. Exit\n";
cout << "Choose Option: ";
cin >> n;
switch (n) {
case 1:
google.search();
break;
case 2:
google.history();
break;
case 3:
google.forward();
break;
case 4:
google.previous();
break;
case 5:
google.deletehistory();
break;
case 6:
cout << "\nExiting browser...\n";
break;
default:
cout << "\nInvalid Choice!\n";
break;
}
} while (n != 6);
return 0;
}
generate_html.py
import os
import html
import argparse # For command-line arguments
# --- Configuration (Defaults, can be overridden by CLI args) ---
DEFAULT_REPO_NAME = "Repository Showcase"
DEFAULT_REPO_DESCRIPTION = "Code and files from a Git repository."
DEFAULT_REPO_URL = "#" # Placeholder, should be provided
DEFAULT_LOCAL_REPO_PATH = "." # Default source of files
DEFAULT_INDEX_TEMPLATE_PATH = "index.html" # This is now our new template
DEFAULT_OUTPUT_HTML_PATH = "index.html" # Output directly to index.html
# --- Helper Functions ---
def get_repository_files(repo_path):
"""
Lists files and directories in the repository.
Ignores .git directory and other common unnecessary files/dirs.
Returns a list of relative paths.
"""
items = []
# More robust ignore list, especially for when scanning subdirectories like 'cloned_repo'
# These script names are less relevant to ignore when scanning a *different* directory.
base_ignore_list = ['.git', '.idea', '__pycache__']
# Add more if needed, e.g. specific large files, build artifacts if not in .gitignore of target repo
for root, dirs, files in os.walk(repo_path, topdown=True):
# Modify dirs in-place to skip ignored directories
dirs[:] = [d for d in dirs if d not in base_ignore_list and not d.startswith('.')]
for name in files:
if name not in base_ignore_list and not name.startswith('.'):
full_path = os.path.join(root, name)
relative_path = os.path.relpath(full_path, repo_path)
items.append(relative_path)
for name in dirs: # Also list directories
full_path = os.path.join(root, name)
relative_path = os.path.relpath(full_path, repo_path) + os.sep
items.append(relative_path)
items.sort()
return items
def read_file_content(filepath, repo_scan_path):
"""Reads the content of a specific file, ensuring it's within the scanned repo path."""
# This check is a basic security measure if paths could be manipulated.
# For this script, file_path is generated by get_repository_files, so it's already relative to repo_scan_path.
# However, constructing full_path safely is good.
absolute_repo_scan_path = os.path.abspath(repo_scan_path)
full_target_path = os.path.abspath(os.path.join(repo_scan_path, filepath))
if not full_target_path.startswith(absolute_repo_scan_path):
print(f"Security warning: Attempt to read file outside of repository path: {filepath}")
return "Error: Access denied."
try:
with open(full_target_path, 'r', encoding='utf-8', errors='ignore') as f:
return f.read()
except Exception as e:
print(f"Error reading file {full_target_path}: {e}")
return f"Error reading file: {e}"
def generate_file_list_html(files): # repo_path no longer needed here, path is for display
"""Generates HTML list items for the files."""
if not files:
return "<li>No files found in the repository.</li>"
list_items_html = []
for file_path in files:
# Ensure section_id matches what's used in generate_file_content_sections_html
# The 'file-' prefix is added to ensure valid ID and avoid conflicts if a file is named e.g. '1'
section_id = "file-" + html.escape(file_path.replace(os.sep, "-").replace(".", "_").replace(" ", "_").replace("+", "_plus_").replace("#", "_hash_"))
# Add a class if it's a directory for specific styling
is_dir = file_path.endswith(os.sep)
link_class = ' class="dir-link"' if is_dir else ''
# For directories, the link might not point to a content section, or could point to a generated listing for that dir (future enhancement)
# For now, directories won't have a clickable href that shows content, but will be listed.
# The JS in the template expects href to start with # to trigger content display.
# We make directory links non-functional for content display for now, or they could link to '#'
href_attr = f'href="#{section_id}"' if not is_dir else 'href="#" onclick="event.preventDefault(); return false;"' # Make dir links non-interactive for content display
list_items_html.append(
f'<li><a {href_attr} data-filepath="{html.escape(file_path)}"{link_class}>{html.escape(file_path)}</a></li>'
)
return "\n".join(list_items_html)
def generate_file_content_sections_html(files, repo_scan_path):
"""Generates HTML sections for each file's content, fitting the new template."""
content_sections_html = []
for file_path in files:
if file_path.endswith(os.sep): # Skip directories for content display
continue
content = read_file_content(file_path, repo_scan_path)
escaped_content = html.escape(content)
# Ensure section_id matches what's used in generate_file_list_html and JS
# The 'file-' prefix is added to ensure valid ID
section_id = "file-" + html.escape(file_path.replace(os.sep, "-").replace(".", "_").replace(" ", "_").replace("+", "_plus_").replace("#", "_hash_"))
content_sections_html.append(f"""
<section class="file-content-display" id="{section_id}" style="display: none;">
<h3>{html.escape(file_path)}</h3>
<pre><code>{escaped_content}</code></pre>
</section>""")
if not content_sections_html:
return '<h2 class="welcome-message">No viewable files found in the repository.</h2>'
return "\n".join(content_sections_html)
def main():
parser = argparse.ArgumentParser(description="Generate an HTML page from a repository's files.")
parser.add_argument("repo_path", nargs='?', default=DEFAULT_LOCAL_REPO_PATH,
help="Path to the local repository directory to scan.")
parser.add_argument("output_html_path", nargs='?', default=DEFAULT_OUTPUT_HTML_PATH,
help="Path to save the generated HTML file.")
parser.add_argument("repo_name", nargs='?', default=DEFAULT_REPO_NAME,
help="Name of the repository.")
parser.add_argument("repo_description", nargs='?', default=DEFAULT_REPO_DESCRIPTION,
help="Description of the repository.")
parser.add_argument("repo_url", nargs='?', default=DEFAULT_REPO_URL,
help="URL of the repository.")
parser.add_argument("--template", default=DEFAULT_INDEX_TEMPLATE_PATH,
help="Path to the HTML template file.")
args = parser.parse_args()
print(f"Reading HTML template from: {args.template}")
try:
with open(args.template, 'r', encoding='utf-8') as f:
template_content = f.read()
except FileNotFoundError:
print(f"Error: Template file '{args.template}' not found.")
# Simplified error handling: if template is missing, just exit.
# The dummy creation logic was more for standalone testing.
return
print(f"Scanning repository files in: {args.repo_path}")
if not os.path.isdir(args.repo_path):
print(f"Error: Repository path '{args.repo_path}' not found or not a directory.")
return
repo_files = get_repository_files(args.repo_path)
print(f"Found {len(repo_files)} files/directories.")
file_list_html = generate_file_list_html(repo_files) # repo_path was for constructing full paths, now handled in read_file_content
file_content_sections_html = generate_file_content_sections_html(repo_files, args.repo_path)
output_content = template_content.replace("{repo_name}", html.escape(args.repo_name))
output_content = output_content.replace("{repo_description}", html.escape(args.repo_description))
output_content = output_content.replace("{repo_link}", html.escape(args.repo_url))
output_content = output_content.replace("<!-- File items will be dynamically inserted here by Python -->", file_list_html)
# Replace the content of the file-content-wrapper div with the generated sections
# This is a more robust way than replacing a specific complex HTML block.
# We look for the specific div and replace its content.
# The placeholder comment inside is a good target.
placeholder_comment = "<!-- File content sections will be dynamically inserted here by Python -->"
wrapper_start_tag = '<div class="file-content-wrapper" id="file-content-wrapper">'
# Find the position of the wrapper div's content area
try:
start_index = output_content.index(wrapper_start_tag) + len(wrapper_start_tag)
# Find the end of this div. This is a bit naive; a proper parser would be better for complex HTML.
# For this template, it should work if the div is empty or contains only the placeholder comment.
end_index = output_content.index('</div>', start_index)
# Construct the new content for the wrapper
# If file_content_sections_html is empty (e.g. no files), it will insert the welcome message from that function.
# Otherwise, it inserts the file sections. The client-side JS will manage showing the initial welcome message
# if no file is selected by hash.
# The original template has a welcome message. The Python script will now embed all content sections
# and the JS will decide if the welcome message (if present and not replaced) or a content section is shown.
# So we just inject file_content_sections_html into the wrapper.
# If file_content_sections_html itself contains a welcome message (e.g., "No viewable files"), that will be shown.
# Otherwise, the JS will show the template's default welcome message if no file is auto-selected.
output_content = output_content[:start_index] + "\n" + file_content_sections_html + "\n" + output_content[end_index:]
except ValueError:
print("Error: Could not find the file-content-wrapper div or placeholder comment in the template.")
# Fallback or error handling if the specific div structure isn't found.
# For now, we'll try the old replacement method as a very basic fallback, though it's unlikely to match.
old_placeholder_section = """<section class="file-content" id="file-content-section" style="display:none;">
<h3><span id="current-file-path"></span></h3>
<pre><code id="code-display"></code></pre>
</section>"""
if old_placeholder_section in output_content:
output_content = output_content.replace(old_placeholder_section, file_content_sections_html)
else:
# If the new placeholder isn't there and the old one isn't either, there's a template mismatch.
print("Critical Error: Template structure significantly changed. Cannot inject file content.")
return
# Check if the content to be written is different from the existing file
# to minimize unnecessary rewrites (as per original user request).
existing_content = ""
if os.path.exists(args.output_html_path):
try:
with open(args.output_html_path, 'r', encoding='utf-8') as f_old:
existing_content = f_old.read()
except IOError:
pass # Ignore if can't read old file, just overwrite
if existing_content == output_content:
print(f"Generated content is identical to '{args.output_html_path}'. No rewrite needed.")
else:
print(f"Writing generated HTML to: {args.output_html_path}")
try:
with open(args.output_html_path, 'w', encoding='utf-8') as f:
f.write(output_content)
print(f"Successfully generated '{args.output_html_path}'.")
except IOError as e:
print(f"Error writing output file: {e}")
if __name__ == "__main__":
main()
generated_index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GitHub Repository Viewer</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
line-height: 1.6;
margin: 0;
padding: 0;
background-color: #f6f8fa;
color: #24292e;
}
.container {
max-width: 960px;
margin: 20px auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}
header {
border-bottom: 1px solid #e1e4e8;
padding-bottom: 16px;
margin-bottom: 24px;
}
header h1 {
font-size: 2em;
margin-bottom: 0.5em;
}
header p {
font-size: 1.1em;
color: #586069;
}
header a {
color: #0366d6;
text-decoration: none;
}
header a:hover {
text-decoration: underline;
}
.repo-info {
margin-bottom: 20px;
}
.file-list h2 {
font-size: 1.5em;
border-bottom: 1px solid #e1e4e8;
padding-bottom: 8px;
margin-bottom: 16px;
}
.file-list ul {
list-style-type: none;
padding: 0;
}
.file-list li {
padding: 8px 0;
border-bottom: 1px solid #f1f1f1;
}
.file-list li:last-child {
border-bottom: none;
}
.file-list a {
text-decoration: none;
color: #0366d6;
font-weight: 500;
}
.file-list a:hover {
text-decoration: underline;
}
.file-content {
margin-top: 30px;
padding: 15px;
background-color: #f1f1f1;
border-radius: 6px;
overflow-x: auto;
}
.file-content h3 {
margin-top: 0;
}
pre {
white-space: pre-wrap;
word-wrap: break-word;
}
footer {
text-align: center;
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid #e1e4e8;
font-size: 0.9em;
color: #586069;
}
</style>
</head>
<body>
<div class="container">
<header>
<h1><a href="https://github.com/M-Mikran-Sandhu" id="repo-name-link" target="_blank">M-Mikran-Sandhu's Showcase</a></h1>
<p id="repo-description">A collection of my projects and code experiments.</p>
<p><strong>GitHub Link:</strong> <a href="https://github.com/M-Mikran-Sandhu" id="repo-github-link" target="_blank">https://github.com/M-Mikran-Sandhu</a></p>
</header>
<section class="file-list">
<h2>Repository Files</h2>
<ul id="file-list-ul">
<li><a href="#Age Priorities list_cpp" data-filepath="Age Priorities list.cpp">Age Priorities list.cpp</a></li>
<li><a href="#Assignment 2" data-filepath="Assignment 2">Assignment 2</a></li>
<li><a href="#README_md" data-filepath="README.md">README.md</a></li>
<li><a href="#Simple Queue_cpp" data-filepath="Simple Queue.cpp">Simple Queue.cpp</a></li>
<li><a href="#Song Playlist_cpp" data-filepath="Song Playlist.cpp">Song Playlist.cpp</a></li>
<li><a href="#Tree_cpp" data-filepath="Tree.cpp">Tree.cpp</a></li>
<li><a href="#Website history forward and backward in linked list_cpp" data-filepath="Website history forward and backward in linked list.cpp">Website history forward and backward in linked list.cpp</a></li>
<li><a href="#linkedlist_py" data-filepath="linkedlist.py">linkedlist.py</a></li>
<!-- Example: <li><a href="#" data-filepath="path/to/file.py">path/to/file.py</a></li> -->
</ul>
</section>
<section class="file-content" id="Age Priorities list_cpp">
<h3>Age Priorities list.cpp</h3>
<pre><code>#include<iostream>
using namespace std;
struct Queue {
string name;
int age;
char gender;
};
struct Node {
Queue data;
Node* next;
};
class linkedlist {
private:
Node* head;
public:
linkedlist() {
head = NULL;
}
void insertQueue() {
Node* point = new Node();
cout << "\nEnter Name: ";
cin >> point->data.name;
cout << "\nEnter Age: ";
cin >> point->data.age;
cout << "\nEnter Gender (M/F): ";
cin >> point->data.gender;
point->next = NULL;
if (head == NULL || point->data.age > head->data.age) {
point->next = head;
head = point;
} else {
Node* temp = head;
while (temp->next != NULL && temp->next->data.age >= point->data.age) {
temp = temp->next;
}
point->next = temp->next;
temp->next = point;
}
}
void serveQueue() {
if (head == NULL) {
cout << "\nThe Queue is Empty!\n";
return;
}
cout << "Processing...... \n" << head->data.name << " has been served\n";
switch (head->data.gender) {
case 'M': case 'm':
cout << "Because he is " << head->data.age << " years old\n";
break;
case 'F': case 'f':
cout << "Because she is " << head->data.age << " years old\n";
break;
default:
cout << "Because (he/she) is " << head->data.age << " years old\n";
break;
}
Node* temp = head;
head = head->next;
delete temp;
}
void displayQueue() {
if (head == NULL) {
cout << "\nThe Queue is Empty!\n";
return;
}
Node* temp = head;
int i = 1;
while (temp) {
cout << "\nPerson " << i << ":\n";
cout << "Name: " << temp->data.name << "\n";
cout << "Age: " << temp->data.age << "\n";
cout << "Gender: " << temp->data.gender << "\n";
temp = temp->next;
i++;
}
}
};
int main() {
linkedlist hospital;
int n;
menu:
cout << "\n1. Enter a person in the Queue.";
cout << "\n2. Serve a person.";
cout << "\n3. Show the list.";
cout << "\n4. Exit\n";
cout << "Enter choice: ";
cin >> n;
switch (n) {
case 1:
hospital.insertQueue();
goto menu;
case 2:
hospital.serveQueue();
goto menu;
case 3:
hospital.displayQueue();
goto menu;
case 4:
return 0;
default:
cout << "\nInvalid choice! Try again.\n";
goto menu;
}
}
</code></pre>
</section>
<section class="file-content" id="Assignment 2">
<h3>Assignment 2</h3>
<pre><code>#include <iostream>
#include <string>
using namespace std;
struct transation {
int transaction_ID = 1;
string type;
int purchase;
transation* next;
transation* prv;
};
struct accounts {
int acc_id = 1;
string user_name;
accounts* next;
transation* head;
accounts* prv;
};
class tran {
public:
void insertinlink(transation*& head) {
char ck;
do {
int purchase;
string tp;
cout << "\nEnter Purchase: ";
cin >> purchase;
cin.ignore();
cout << "\nEnter Note: ";
getline(cin, tp);
transation* node = new transation();
node->purchase = purchase;
node->type = tp;
if (head) {
transation* temp = head;
while (temp->next) {
temp = temp->next;
}
node->transaction_ID = temp->transaction_ID + 1;
temp->next = node;
node->prv = temp;
} else {
head = node;
}
node->next = NULL;
cout << "\nPress 'Y' to enter another transaction: ";
cin >> ck;
} while (ck == 'Y' || ck == 'y');
}
void searchtran(transation* head) {
transation* temp = head;
while (temp) {
cout << "\nTransaction ID: " << temp->transaction_ID << endl;
cout << "Purchase: " << temp->purchase << endl;
cout << "Note: " << temp->type << endl;
temp = temp->next;
}
}
void totaltransations(transation* head) {
transation* temp = head;
int sum = 0;
while (temp) {
sum += temp->purchase;
temp = temp->next;
}
cout << "\nThe Total amount you have spent is: " << sum << " Rs\n";
}
void display(transation* head) {
transation* temp = head;
while (temp) {
cout << "\nTransaction ID: " << temp->transaction_ID << endl;
cout << "Purchase: " << temp->purchase << endl;
cout << "Note: " << temp->type << endl;
temp = temp->next;
}
}
};
class record {
accounts* acc_head;
int count = 0;
public:
record() {
acc_head = NULL;
}
void newaccount() {
string name;
cout << "\nEnter Name: ";
cin.ignore();
getline(cin, name);
accounts* acc = new accounts();
count++;
if (acc_head) {
accounts* temp = acc_head;
while (temp->next) {
temp = temp->next;
}
acc->acc_id = temp->acc_id + 1;
temp->next = acc;
acc->prv = temp;
} else {
acc_head = acc;
acc->prv = NULL;
}
cout << "\nYour Account ID is: " << acc->acc_id << endl;
acc->user_name = name;
acc->next = NULL;
acc->head = NULL;
tran chain;
chain.insertinlink(acc->head);
}
void searchaccount() {
int acid, attempts = 3;
string pn;
while (attempts > 0) {
cout << endl << "Enter Name: ";
cin.ignore();
getline(cin, pn);
cout << endl << "Enter Account ID: ";
cin >> acid;
accounts* temp = acc_head;
while (temp) {
if (pn == temp->user_name && acid == temp->acc_id) {
cout << "\n \t Transaction records\n\n";
tran temp1;
temp1.searchtran(temp->head);
return;
}
temp = temp->next;
}
attempts--;
if (attempts > 0) {
cout << endl << "Invalid ID or Name! Attempts left: " << attempts << endl;
} else {
cout << endl << "Access limit reached! Returning to menu..." << endl;
}
}
}
void addtoaccount() {
int acid, attempts = 3;
string pn;
while (attempts > 0) {
cout << endl << "Enter Name: ";
cin.ignore();
getline(cin, pn);
cout << endl << "Enter Account ID: ";
cin >> acid;
accounts* temp = acc_head;
while (temp) {
if (pn == temp->user_name && acid == temp->acc_id) {
tran temp1;
temp1.insertinlink(temp->head);
return;
}
temp = temp->next;
}
attempts--;
if (attempts > 0) {
cout << endl << "Invalid ID or Name! Attempts left: " << attempts << endl;
} else {
cout << endl << "Access limit reached! Returning to menu..." << endl;
}
}
}
int totalacc() {
return count;
}
void totalexpense() {
int acid, attempts = 3;
string pn;
while (attempts > 0) {
cout << endl << "Enter Name: ";
cin.ignore();
getline(cin, pn);
cout << endl << "Enter Account ID: ";
cin >> acid;
accounts* temp = acc_head;
while (temp) {
if (pn == temp->user_name && acid == temp->acc_id) {
tran temp1;
temp1.totaltransations(temp->head);
return;
}
temp = temp->next;
}
attempts--;
if (attempts > 0) {
cout << endl << "Invalid ID or Name! Attempts left: " << attempts << endl;
} else {
cout << endl << "Access limit reached! Returning to menu..." << endl;
}
}
}
void display() {
accounts* temp = acc_head;
while (temp) {
cout << "\nName: " << temp->user_name << endl;
cout << "Account ID: " << temp->acc_id << endl;
char ans;
cout << "\nPress 'Y' if you want transaction details: ";
cin >> ans;
if (ans == 'y' || ans == 'Y') {
tran temp1;
temp1.display(temp->head);
}
temp = temp->next;
}
}
};
int main() {
int a, pass = 1234, p;
record m;
while (true) {
cout << "\t\tMenu\n";
cout << endl << "1. New Account.";
cout << endl << "2. Search Account.";
cout << endl << "3. Add Transaction to Existing Account.";
cout << endl << "4. Display Number of Accounts.";
cout << endl << "5. Total Transactions of an Account.";
cout << endl << "6. Display All Accounts.";
cout << endl << "7. Exit.";
cout << endl << "\nEnter choice: ";
cin >> a;
switch (a) {
case 1:
m.newaccount();
break;
case 2:
m.searchaccount();
break;
case 3:
m.addtoaccount();
break;
case 4:
cout << "\nTotal accounts are: " << m.totalacc() << endl;
break;
case 5:
m.totalexpense();
break;
case 6:
cout << "Enter Password: ";
cin >> p;
if (pass == p) m.display();
else cout << "\nInvalid password!\n";
break;
case 7:
return 0;
default: cout << "\nInvalid choice! Try again.\n";
}
}
}
</code></pre>
</section>
<section class="file-content" id="README_md">
<h3>README.md</h3>
<pre><code># DATA-Structure-ALG
DATA STRUCTURE AND ALGORITHM
A Data Structure Algorithm refers to a set of instructions or steps designed to manipulate, organize, and process data efficiently using specific data structures. Below is a concise overview of key concepts:
1. Common Data Structures
Arrays: Fixed-size, sequential collection of elements.
Linked Lists: Nodes connected by pointers (e.g., singly, doubly linked lists).
Stacks: Last-In-First-Out (LIFO) structure (e.g., undo operations).
Queues: First-In-First-Out (FIFO) structure (e.g., task scheduling).
Hash Tables: Key-value pairs for fast lookups.
Trees: Hierarchical structures (e.g., binary trees, AVL trees).
Graphs: Nodes (vertices) connected by edges (e.g., social networks).
Heaps: Specialized trees for priority-based operations.
2. Key Algorithms
Sorting Algorithms:
Bubble Sort, Merge Sort, Quick Sort, Insertion Sort.
Searching Algorithms:
Linear Search, Binary Search.
Graph Algorithms:
Dijkstra’s Algorithm (shortest path), Depth-First Search (DFS), Breadth-First Search (BFS).
Dynamic Programming:
Solves problems by breaking them into overlapping subproblems (e.g., Fibonacci, Knapsack).
Divide and Conquer:
Splits problems into smaller subproblems (e.g., Merge Sort, Quick Sort).
Greedy Algorithms:
Makes locally optimal choices (e.g., Kruskal’s, Prim’s).
3. Applications
Web Development: Hash tables for caching, trees for DOM traversal.
Databases: B-trees for indexing.
Networking: Graph algorithms for routing.
AI/ML: Dynamic programming for optimization problems.
Efficient use of data structures and algorithms ensures optimal performance in software development. Let me know if you'd like a deeper dive into any specific topic!
</code></pre>
</section>
<section class="file-content" id="Simple Queue_cpp">
<h3>Simple Queue.cpp</h3>
<pre><code>#include<iostream>
using namespace std;
struct Queue {
string name;
int age;
char gender;
};
struct Node {
Queue data;
Node* next;
};
class linkedlist {
private:
Node* head;
int front = -1;
int rare = -1;
public:
linkedlist() {
head = NULL;
}
void insertQueue() {
rare++;
Node* point = new Node();
cout << "\nEnter Name:";
cin >> point->data.name;
cout << "\nEnter Age:";
cin >> point->data.age;
cout << "\nEnter Gender (M/F):";
cin >> point->data.gender;
point->next = NULL;
if (rare == 0) {
front = 0;
}
if (head == NULL) {
head = point;
} else {
Node* temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = point;
}
}
void serveQueue() {
if (front >= 0) {
if (head == NULL) {
cout << "\nThe Queue is Empty!\n";
return;
}
cout << "Processing...... " << head->data.name << " has been served\n";
switch (head->data.gender) {
case 'M': case 'm':
cout << "Because he is " << head->data.age << " years old\n";
break;
case 'F': case 'f':
cout << "Because she is " << head->data.age << " years old\n";
break;
default:
cout << "Because (he/she) is " << head->data.age << " years old\n";
break;
}
Node* temp = head;
head = head->next;
delete temp;
rare--;
if (rare < 0) front = -1;
} else {
cout << "\nThe Queue is Empty!\n";
}
}
void displayQueue() {
if (front >= 0 && head != NULL) {
Node* temp = head;
int i = 1;
while (temp) {
cout << "\nPerson " << i << ":\n";
cout << "Name: " << temp->data.name << "\n";
cout << "Age: " << temp->data.age << "\n";
cout << "Gender: " << temp->data.gender << "\n";
temp = temp->next;
i++;
}
} else {
cout << "\nThe Queue is Empty!\n";
}
}
};
int main() {
linkedlist hospital;
int n;
menu:
cout << "\n1. Enter a person in the Queue.";
cout << "\n2. Serve a person.";
cout << "\n3. Show the list.";
cout << "\n4. Exit\n";
cout << "Enter choice: ";
cin >> n;
switch (n) {
case 1:
hospital.insertQueue();
goto menu;
case 2:
hospital.serveQueue();
goto menu;
case 3:
hospital.displayQueue();
goto menu;
case 4:
return 0;
default:
cout << "\nInvalid choice! Try again.\n";
goto menu;
}
}
</code></pre>
</section>
<section class="file-content" id="Song Playlist_cpp">
<h3>Song Playlist.cpp</h3>
<pre><code>#include<iostream>
using namespace std;
class Song{
public:
string name;
string title;
Song* prev;
Song* next;
Song(){
name="";
title="";
prev=NULL;
next=NULL;
}
};
class playlist{
Song* head;
Song* current;
int count=0;
public:
playlist(){
head=NULL;
current=NULL;
}
void addsong(){
Song* newsong=new Song();
cout<<"Enter Song Name:";
cin>>newsong->name;
cout<<"Enter Song Title:";
cin>>newsong->title;
if(head==NULL){
head=newsong;
newsong->next=NULL;
newsong->prev=NULL;
current=newsong;
count++;
return;
}else{
Song* temp=head;
while(temp->next){
temp=temp->next;
}
newsong->prev=temp;
temp->next=newsong;
}
current=newsong;
count++;
}
void playcurrentsong(){
if(count<1){
cout<<"\n No Song is currently in the list.\n";
return;
}
cout<<"\nPlaying Song...........\n";
cout<<"Name: "<<current->name<<endl;
cout<<"Title: "<<current->title<<endl;
}
void nextsong(){
if(current->next==NULL){
cout<<"\nThere is no Next Song\n";
return;
}
cout<<"\nMoving to the next Song.\n";
current=current->next;
}
void prevsong(){
if(current->prev==NULL){
cout<<"\nThere is no Previous Song\n";
return;
}
cout<<"\nMoving to the previous Song.\n";
current=current->prev;
}
};
int main(){
playlist youtube;
int n;
menu:
cout<<"\n----Menu----\n";
cout<<"\n1. Add a Song";
cout<<"\n2. Play Current Song";
cout<<"\n3. Previous Song";
cout<<"\n4. Next Song";
cout<<"\n5. Exit App";
cout<<"\nEnter your choice:";
cin>>n;
switch(n){
case 1:{
youtube.addsong();
goto menu;
}
case 2:{
youtube.playcurrentsong();
goto menu;
}
case 3:{
youtube.prevsong();
goto menu;
}
case 4:{
youtube.nextsong();
goto menu;
}
case 5:{
cout<<"\nThe Application is Closing..............\n";
break;
}
default:{
cout<<"\n Invalid Enter! Chose form the menu.\n";
goto menu;
}
}
}
</code></pre>
</section>
<section class="file-content" id="Tree_cpp">
<h3>Tree.cpp</h3>
<pre><code>#include<iostream>
using namespace std;
class node {
public:
int d;
node *left, *right;
node(int d) {
this->d = d;
left = right = NULL;
}
};
class B {
public:
node* insert(node* r, int v) {
if (r == NULL) {
return new node(v);
}
if (v < r->d) {
r->left = insert(r->left, v);
} else if (v > r->d) {
r->right = insert(r->right, v);
}
return r;
}
void pre_o(node* r) {
if (r == NULL) return;
cout << r->d << " ";
pre_o(r->left);
pre_o(r->right);
}
};
int main() {
node *r = NULL;
B c;
int n, val;
cout << "How many values do you want to insert? ";
cin >> n;
cout << "Enter " << n << " integer values:\n";
for (int i = 0; i < n; ++i) {
cin >> val;
r = c.insert(r, val);
}
cout << "Preorder traversal of the tree: ";
c.pre_o(r);
cout << endl;
return 0;
}
</code></pre>
</section>
<section class="file-content" id="Website history forward and backward in linked list_cpp">
<h3>Website history forward and backward in linked list.cpp</h3>
<pre><code>#include<iostream>
using namespace std;
class website {
public:
website* next;
string WebName;
website* prev;
website() {
next = NULL;
WebName = "";
prev = NULL;
}
};
class browser {
private:
website* head;
website* recent;
public:
browser() {
head = NULL;
recent = NULL;
}
void search() {
website* domain = new website();
cout << "\nEnter Website you want to search: ";
cin >> domain->WebName;
cout << "\n" << domain->WebName << " is essential for nowadays. \n";
if (head == NULL) {
domain->next = NULL;
domain->prev = NULL;
head = domain;
recent = domain;
return;
}
website* temp = head;
while (temp->next) {
temp = temp->next;
}
domain->prev = temp;
temp->next = domain;
recent = domain;
}
void history() {
if (recent == NULL) {
cout << "\nNo history available.\n";
return;
}
website* temp = recent;
cout << "\nBrowsing History:\n";
while (temp != NULL) {
cout << temp->WebName << "\n";
temp = temp->prev;
}
}
void forward() {
if (recent == NULL || recent->next == NULL) {
cout << "\nThere is no Next Tab\n";
return;
}
recent = recent->next;
cout << "\nThe Next Tab: " << recent->WebName << endl;
}
void previous() {
if (recent == NULL || recent->prev == NULL) {
cout << "\nThere is no Previous Tab\n";
return;
}
recent = recent->prev;
cout << "\nThe Previous Tab: " << recent->WebName << endl;
}
void deletehistory() {
if (head == NULL) {
cout << "\nHistory is empty.\n";
return;
}
int pos;
cout << "Enter the position to delete (1-based index): ";
cin >> pos;
website* temp = head;
int count = 1;
while (temp != NULL && count < pos) {
temp = temp->next;
count++;
}
if (temp == NULL) {
cout << "\nInvalid position.\n";
return;
}
if (temp == recent) {
if (temp->prev)
recent = temp->prev;
else if (temp->next)
recent = temp->next;
else
recent = NULL;
}
if (temp == head) {
head = temp->next;
if (head)
head->prev = NULL;
} else {
temp->prev->next = temp->next;
}
if (temp->next)
temp->next->prev = temp->prev;
cout << "\nDeleted: " << temp->WebName << endl;
delete temp;
}
};
int main() {
browser google;
int n = 0;
do {
cout << "\n-----MENU-----\n";
cout << "1. Browse a Website\n";
cout << "2. Show History\n";
cout << "3. Forward Tab\n";
cout << "4. Previous Tab\n";
cout << "5. Delete History at Position\n";
cout << "6. Exit\n";
cout << "Choose Option: ";
cin >> n;
switch (n) {
case 1:
google.search();
break;
case 2:
google.history();
break;
case 3:
google.forward();
break;
case 4:
google.previous();
break;
case 5:
google.deletehistory();
break;
case 6:
cout << "\nExiting browser...\n";
break;
default:
cout << "\nInvalid Choice!\n";
break;
}
} while (n != 6);
return 0;
}
</code></pre>
</section>
<section class="file-content" id="linkedlist_py">
<h3>linkedlist.py</h3>
<pre><code>class Node:
"""
A class representing a node in a singly linked list.
"""
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
"""
A class to manage a singly linked list.
"""
def __init__(self):
self.head = None
def insert_at_end(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
curr = self.head
while curr.next:
curr = curr.next
curr.next = new_node
def insert_at_beginning(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_after_value(self, target, data):
curr = self.head
while curr:
if curr.data == target:
new_node = Node(data)
new_node.next = curr.next
curr.next = new_node
return
curr = curr.next
raise ValueError(f"Value '{target}' not found.")
def delete_value(self, target):
if not self.head:
raise ValueError("List is empty.")
if self.head.data == target:
self.head = self.head.next
return
curr = self.head
while curr.next:
if curr.next.data == target:
curr.next = curr.next.next
return
curr = curr.next
raise ValueError(f"Value '{target}' not found.")
def traverse(self):
elements = []
curr = self.head
while curr:
elements.append(curr.data)
curr = curr.next
return elements
def __str__(self):
return " -> ".join(map(str, self.traverse())) + " -> None"
# === Main program with user interaction ===
def main():
ll = SinglyLinkedList()
while True:
print("\n--- Singly Linked List Menu ---")
print("1. Insert at beginning")
print("2. Insert at end")
print("3. Insert after value")
print("4. Delete a value")
print("5. Display list")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
try:
if choice == '1':
val = input("Enter value to insert at beginning: ")
ll.insert_at_beginning(val)
elif choice == '2':
val = input("Enter value to insert at end: ")
ll.insert_at_end(val)
elif choice == '3':
target = input("Enter the value after which to insert: ")
val = input("Enter value to insert: ")
ll.insert_after_value(target, val)
elif choice == '4':
val = input("Enter value to delete: ")
ll.delete_value(val)
elif choice == '5':
print("Linked List:")
print(ll)
elif choice == '6':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 6.")
except ValueError as ve:
print(f"Error: {ve}")
if __name__ == "__main__":
main()
1
</code></pre>
</section>
<footer>
<p>Dynamically generated by a Python script. Updates periodically.</p>
</footer>
</div>
<script>
// Basic JavaScript to handle file clicks and display content
// This will be expanded or replaced by the Python generation logic for static display,
// or enhanced if we want client-side fetching for a more dynamic feel without page reloads.
// For now, the Python script will generate the full HTML including content.
// This script section might be more relevant if we were building a single-page app.
// For now, the Python script will handle populating everything.
// Placeholder for future client-side interactions if needed.
// For instance, if we decide to load file content on click via JS:
/*
document.addEventListener('DOMContentLoaded', () => {
const fileLinks = document.querySelectorAll('#file-list-ul a');
const fileContentSection = document.getElementById('file-content-section');
const codeDisplay = document.getElementById('code-display');
const currentFilePathDisplay = document.getElementById('current-file-path');
fileLinks.forEach(link => {
link.addEventListener('click', async (event) => {
event.preventDefault();
const filePath = link.dataset.filepath;
// In a more advanced setup, this would fetch content.
// For now, we assume Python generates separate pages or embeds content directly.
// This is a conceptual placeholder.
// const response = await fetch(`/get-file-content?path=${encodeURIComponent(filePath)}`);
// const content = await response.text();
// currentFilePathDisplay.textContent = filePath;
// codeDisplay.textContent = "Loading content for " + filePath + "..."; // Replace with actual content
// fileContentSection.style.display = 'block';
alert("Displaying content for: " + filePath + "\\n(This is a placeholder; content display will be handled by Python generation)");
});
});
});
*/
</script>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{repo_name} - Code Showcase</title>
<style>
:root {
--primary-color: #2c3e50; /* Dark Slate Blue */
--secondary-color: #8e44ad; /* Royal Purple */
--accent-color: #f1c40f; /* Sunflower Yellow/Gold */
--background-color: #ecf0f1; /* Light Greyish Blue */
--text-color: #34495e; /* Wet Asphalt (Dark Grey) */
--light-text-color: #ffffff;
--border-color: #bdc3c7; /* Silver */
--code-bg-color: #282c34; /* Dark background for code */
--code-text-color: #abb2bf; /* Light grey for code text */
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.7;
margin: 0;
padding: 0;
background-color: var(--background-color);
color: var(--text-color);
display: flex;
flex-direction: column;
min-height: 100vh;
}
.container {
display: flex;
flex-grow: 1;
width: 100%;
max-width: 1600px; /* Allow wider content */
margin: 0 auto;
}
header {
background-color: var(--primary-color);
color: var(--light-text-color);
padding: 20px 30px;
text-align: center;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
header h1 {
font-size: 2.5em;
margin-bottom: 0.2em;
font-weight: 300;
}
header h1 a {
color: var(--light-text-color);
text-decoration: none;
}
header h1 a:hover {
color: var(--accent-color);
}
header p {
font-size: 1.1em;
margin-bottom: 0.5em;
color: var(--border-color); /* Lighter text for description */
}
header .repo-link-header {
font-size: 0.9em;
}
header .repo-link-header a {
color: var(--accent-color);
text-decoration: none;
font-weight: bold;
}
header .repo-link-header a:hover {
text-decoration: underline;
}
.sidebar {
width: 25%;
min-width: 280px; /* Min width for file list */
background-color: #ffffff;
padding: 20px;
border-right: 1px solid var(--border-color);
overflow-y: auto; /* Scroll if file list is long */
box-shadow: 1px 0 3px rgba(0,0,0,0.05);
}
.sidebar h2 {
font-size: 1.6em;
color: var(--primary-color);
border-bottom: 2px solid var(--secondary-color);
padding-bottom: 10px;
margin-top: 0;
font-weight: 500;
}
.file-list ul {
list-style-type: none;
padding: 0;
margin: 0;
}
.file-list li {
margin-bottom: 8px;
}
.file-list a {
text-decoration: none;
color: var(--primary-color);
font-weight: 500;
padding: 8px 12px;
display: block;
border-radius: 4px;
transition: background-color 0.2s ease, color 0.2s ease;
}
.file-list a:hover, .file-list a.active {
background-color: var(--secondary-color);
color: var(--light-text-color);
}
.file-list a.dir-link { /* Style for directory links */
font-weight: bold;
color: var(--secondary-color);
}
.file-list a.dir-link:hover {
background-color: var(--primary-color);
}
.main-content {
flex-grow: 1;
padding: 25px 30px;
overflow-y: auto; /* Scroll for long content */
}
.main-content h2.welcome-message {
color: var(--primary-color);
text-align: center;
font-weight: 400;
}
.file-content-wrapper {
/* This div will be replaced by Python script */
}
.file-content-display { /* Class for individual file content sections */
background-color: #ffffff;
border: 1px solid var(--border-color);
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.08);
margin-bottom: 25px; /* Space between content blocks if multiple are shown */
}
.file-content-display h3 {
background-color: var(--primary-color);
color: var(--light-text-color);
padding: 12px 20px;
margin: 0;
border-top-left-radius: 7px;
border-top-right-radius: 7px;
font-size: 1.3em;
font-weight: 500;
border-bottom: 2px solid var(--accent-color);
}
.file-content-display pre {
background-color: var(--code-bg-color);
color: var(--code-text-color);
padding: 20px;
margin: 0;
overflow-x: auto;
white-space: pre-wrap;
word-wrap: break-word;
border-bottom-left-radius: 7px;
border-bottom-right-radius: 7px;
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
font-size: 0.95em;
line-height: 1.5;
}
footer {
background-color: var(--primary-color);
color: var(--border-color); /* Lighter text for footer */
text-align: center;
padding: 15px;
font-size: 0.9em;
box-shadow: 0 -2px 4px rgba(0,0,0,0.1);
}
/* Responsive Design */
@media (max-width: 992px) { /* Medium devices (tablets, less than 992px) */
.container {
flex-direction: column;
}
.sidebar {
width: 100%;
min-width: auto;
border-right: none;
border-bottom: 1px solid var(--border-color);
max-height: 40vh; /* Limit height of sidebar on small screens */
}
.main-content {
padding: 20px;
}
}
@media (max-width: 768px) { /* Small devices (landscape phones, less than 768px) */
header h1 {
font-size: 2em;
}
.sidebar h2 {
font-size: 1.4em;
}
.file-content-display h3 {
font-size: 1.15em;
}
}
</style>
</head>
<body>
<header>
<h1><a href="{repo_link}" target="_blank">{repo_name}</a></h1>
<p>{repo_description}</p>
<p class="repo-link-header">Repository Link: <a href="{repo_link}" target="_blank">{repo_link}</a></p>
</header>
<div class="container">
<aside class="sidebar">
<h2>File Explorer</h2>
<nav class="file-list">
<ul id="file-list-ul">
<!-- File items will be dynamically inserted here by Python -->
<!-- Example: <li><a href="#path/to/file.py" data-filepath="path/to/file.py">path/to/file.py</a></li> -->
</ul>
</nav>
</aside>
<main class="main-content">
<!-- This div will contain all file content sections generated by Python -->
<div class="file-content-wrapper" id="file-content-wrapper">
<h2 class="welcome-message">Select a file from the list to view its content.</h2>
<!-- File content sections will be dynamically inserted here by Python -->
<!-- Example structure for Python to generate:
<section class="file-content-display" id="file-some_file_py">
<h3>some_file.py</h3>
<pre><code>print("Hello World")</code></pre>
</section>
-->
</div>
</main>
</div>
<footer>
<p>Dynamically generated code showcase. Styled for a modern experience.</p>
</footer>
<script>
// Client-side script to handle showing/hiding content sections
document.addEventListener('DOMContentLoaded', () => {
const fileLinks = document.querySelectorAll('.file-list a');
const contentSections = document.querySelectorAll('.file-content-display');
const welcomeMessage = document.querySelector('.main-content .welcome-message');
const wrapper = document.getElementById('file-content-wrapper');
// Initially hide all content sections if JS is enabled
// Python will generate them, but JS can manage visibility
contentSections.forEach(section => {
section.style.display = 'none';
});
if (contentSections.length > 0 && welcomeMessage) {
// If there's content, but nothing selected, show welcome.
// If URL hash points to a file, it will be shown later.
} else if (contentSections.length === 0 && welcomeMessage) {
welcomeMessage.textContent = 'No file content to display. Repository might be empty or files are directories only.';
}
fileLinks.forEach(link => {
link.addEventListener('click', function(event) {
// Check if it's a directory link (ends with / or has a specific class if we add one)
// For now, assume all links point to displayable content sections or are handled by URL hash
if (this.href.includes('#')) { // Only process links with hashes
event.preventDefault();
const targetId = this.getAttribute('href').substring(1); // Get ID from href (e.g., #file-main-py)
// Hide all sections and remove active class from links
contentSections.forEach(section => section.style.display = 'none');
fileLinks.forEach(lnk => lnk.classList.remove('active'));
// Show the target section and set active class on link
const targetSection = document.getElementById(targetId);
if (targetSection) {
if(welcomeMessage) welcomeMessage.style.display = 'none';
targetSection.style.display = 'block';
this.classList.add('active');
window.location.hash = targetId; // Update URL hash
} else {
if(welcomeMessage) {
welcomeMessage.textContent = 'Content not found for ' + targetId.replace(/file-/g, '').replace(/_/g, '.');
welcomeMessage.style.display = 'block';
}
}
}
});
});
// Check URL hash on page load to show specific file
if (window.location.hash) {
const targetId = window.location.hash.substring(1);
const targetLink = document.querySelector(`.file-list a[href="#${targetId}"]`);
if (targetLink) {
targetLink.click(); // Simulate click to show content and set active state
} else if (document.getElementById(targetId)) { // If section exists but no link matched (e.g. manual hash)
contentSections.forEach(section => section.style.display = 'none');
document.getElementById(targetId).style.display = 'block';
if(welcomeMessage) welcomeMessage.style.display = 'none';
}
} else if (contentSections.length > 0 && welcomeMessage) {
// If there's content but no hash, ensure welcome message is shown
welcomeMessage.style.display = 'block';
}
});
</script>
</body>
</html>
linkedlist.py
class Node:
"""
A class representing a node in a singly linked list.
"""
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
"""
A class to manage a singly linked list.
"""
def __init__(self):
self.head = None
def insert_at_end(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
curr = self.head
while curr.next:
curr = curr.next
curr.next = new_node
def insert_at_beginning(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_after_value(self, target, data):
curr = self.head
while curr:
if curr.data == target:
new_node = Node(data)
new_node.next = curr.next
curr.next = new_node
return
curr = curr.next
raise ValueError(f"Value '{target}' not found.")
def delete_value(self, target):
if not self.head:
raise ValueError("List is empty.")
if self.head.data == target:
self.head = self.head.next
return
curr = self.head
while curr.next:
if curr.next.data == target:
curr.next = curr.next.next
return
curr = curr.next
raise ValueError(f"Value '{target}' not found.")
def traverse(self):
elements = []
curr = self.head
while curr:
elements.append(curr.data)
curr = curr.next
return elements
def __str__(self):
return " -> ".join(map(str, self.traverse())) + " -> None"
# === Main program with user interaction ===
def main():
ll = SinglyLinkedList()
while True:
print("\n--- Singly Linked List Menu ---")
print("1. Insert at beginning")
print("2. Insert at end")
print("3. Insert after value")
print("4. Delete a value")
print("5. Display list")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
try:
if choice == '1':
val = input("Enter value to insert at beginning: ")
ll.insert_at_beginning(val)
elif choice == '2':
val = input("Enter value to insert at end: ")
ll.insert_at_end(val)
elif choice == '3':
target = input("Enter the value after which to insert: ")
val = input("Enter value to insert: ")
ll.insert_after_value(target, val)
elif choice == '4':
val = input("Enter value to delete: ")
ll.delete_value(val)
elif choice == '5':
print("Linked List:")
print(ll)
elif choice == '6':
print("Exiting program.")
break
else:
print("Invalid choice. Please enter a number between 1 and 6.")
except ValueError as ve:
print(f"Error: {ve}")
if __name__ == "__main__":
main()
1
update_checker.py
import os
import subprocess
import shutil # For removing directory tree if clone fails initially
# --- Configuration ---
# IMPORTANT: Replace this with the actual repository URL you want to track
# The user M-Mikran-Sandhu does not seem to have public repositories.
# Using a placeholder for demonstration.
GIT_REPO_URL = "https://github.com/octocat/Spoon-Knife.git"
# Path to clone the repository into
LOCAL_REPO_DIR = "cloned_repo"
# Script to regenerate HTML
HTML_GENERATOR_SCRIPT = "generate_html.py"
def run_command(command, cwd=None):
"""Runs a shell command and returns its output and error code."""
print(f"Running command: {' '.join(command)} in {cwd or os.getcwd()}")
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd=cwd)
stdout, stderr = process.communicate()
if process.returncode != 0:
print(f"Error running command: {' '.join(command)}")
print(f"STDOUT: {stdout}")
print(f"STDERR: {stderr}")
return stdout, stderr, process.returncode
def clone_repo():
"""Clones the repository if it doesn't exist."""
if os.path.exists(LOCAL_REPO_DIR):
print(f"Repository already exists at {LOCAL_REPO_DIR}.")
return True
print(f"Cloning repository {GIT_REPO_URL} into {LOCAL_REPO_DIR}...")
# Ensure parent directory exists if LOCAL_REPO_DIR includes subdirectories e.g. "some_path/cloned_repo"
# os.makedirs(os.path.dirname(LOCAL_REPO_DIR), exist_ok=True) # Not needed if LOCAL_REPO_DIR is simple
stdout, stderr, returncode = run_command(["git", "clone", GIT_REPO_URL, LOCAL_REPO_DIR])
if returncode == 0:
print("Repository cloned successfully.")
return True
else:
print(f"Failed to clone repository. Error: {stderr}")
# Clean up potentially incomplete clone
if os.path.exists(LOCAL_REPO_DIR):
print(f"Cleaning up incomplete clone at {LOCAL_REPO_DIR}")
try:
shutil.rmtree(LOCAL_REPO_DIR)
except OSError as e:
print(f"Error removing directory {LOCAL_REPO_DIR}: {e}")
return False
def pull_updates():
"""
Pulls updates for the repository.
Returns True if updates were fetched or no updates were needed, False on error.
Returns a second boolean: True if changes were pulled, False otherwise.
"""
if not os.path.exists(os.path.join(LOCAL_REPO_DIR, ".git")):
print(f"Not a git repository: {LOCAL_REPO_DIR}. Attempting to clone again.")
if not clone_repo():
return False, False # Main operation failed, no changes
# If clone was successful, it's up to date, so no "new" changes from this pull.
return True, False
print(f"Fetching updates for {LOCAL_REPO_DIR}...")
# Get current HEAD commit hash before fetching/pulling
stdout_hash_before, _, ret_hash_before = run_command(["git", "rev-parse", "HEAD"], cwd=LOCAL_REPO_DIR)
if ret_hash_before != 0:
print("Could not get current HEAD hash before pull.")
# Proceed with pull, change detection might be less reliable
current_hash_before = None
else:
current_hash_before = stdout_hash_before.strip()
# Fetch changes
_, _, ret_fetch = run_command(["git", "fetch"], cwd=LOCAL_REPO_DIR)
if ret_fetch != 0:
print("Failed to fetch updates.")
return False, False
# Check for changes by comparing local HEAD with remote HEAD
# 'git status -uno' can also be useful but rev-parse is more direct for commit changes
stdout_local_hash, _, _ = run_command(["git", "rev-parse", "HEAD"], cwd=LOCAL_REPO_DIR)
stdout_remote_hash, _, _ = run_command(["git", "rev-parse", "origin/HEAD"], cwd=LOCAL_REPO_DIR) # Assumes default remote 'origin' and its default branch
if stdout_local_hash.strip() == stdout_remote_hash.strip():
print("Repository is already up-to-date.")
return True, False # Operation successful, no changes
print("Updates found. Pulling changes...")
stdout_pull, stderr_pull, ret_pull = run_command(["git", "pull"], cwd=LOCAL_REPO_DIR)
if ret_pull != 0:
print(f"Failed to pull updates. Error: {stderr_pull}")
# Handle potential merge conflicts here if necessary, though script assumes clean pulls.
return False, False
print("Updates pulled successfully.")
# Confirm HEAD changed after pull
stdout_hash_after, _, ret_hash_after = run_command(["git", "rev-parse", "HEAD"], cwd=LOCAL_REPO_DIR)
if ret_hash_after != 0:
print("Could not get current HEAD hash after pull.")
return True, True # Assume changes if pull seemed successful but hash check failed
new_hash_after = stdout_hash_after.strip()
if current_hash_before and new_hash_after != current_hash_before:
print(f"Repository updated. New HEAD: {new_hash_after}")
return True, True # Operation successful, changes detected
elif not current_hash_before: # If we couldn't get hash before, but pull succeeded
print("Repository updated (unable to compare hashes directly).")
return True, True # Assume changes
else:
# This case (pull succeeded but hash didn't change) should be rare if fetch indicated changes
print("Pull completed, but no new commits detected (hash unchanged). This might happen with fast-forwards of branches not currently checked out.")
return True, False
def trigger_html_regeneration():
"""Calls the HTML generator script."""
print(f"Triggering HTML regeneration using {HTML_GENERATOR_SCRIPT}...")
# This assumes generate_html.py knows where to find the cloned repo
# or we pass it as an argument.
# For now, we need to modify generate_html.py to accept LOCAL_REPO_DIR.
# Simplest way: modify generate_html.py to use an environment variable or a fixed path
# that update_checker.py also knows.
# Or, pass as command line argument.
# Let's assume generate_html.py is modified to use LOCAL_REPO_DIR
# We can modify generate_html.py to take LOCAL_REPO_DIR as a parameter.
# For now, I'll call it and it will use its own configured path.
# This will require an update to generate_html.py.
# We need to ensure generate_html.py operates on the files within LOCAL_REPO_DIR.
# And that its output (generated_index.html) is at the top level.
# Let's pass the repo path and output path to generate_html.py
# python generate_html.py <repo_source_path> <output_html_file> <repo_name_override> <repo_desc_override> <repo_url_override>
# This makes generate_html.py more flexible.
repo_name_from_url = GIT_REPO_URL.split('/')[-1].replace('.git', '')
command = [
"python", HTML_GENERATOR_SCRIPT,
LOCAL_REPO_DIR, # input path for files
"generated_index.html", # output html file name
repo_name_from_url, # repo name
f"Content of {repo_name_from_url}", # repo description
GIT_REPO_URL # repo url
]
stdout, stderr, returncode = run_command(command, cwd=os.getcwd()) # Run from script's dir
if returncode == 0:
print("HTML regeneration script completed successfully.")
else:
print(f"HTML regeneration script failed. Error: {stderr}")
def main():
print("--- Starting Repository Update Check ---")
if not clone_repo(): # Clones if not exists
print("Exiting due to cloning issues.")
return
success, has_changes = pull_updates()
if not success:
print("Exiting due to issues pulling updates.")
return
if has_changes:
print("Repository has new changes. Regenerating HTML.")
trigger_html_regeneration()
else:
print("No new changes in repository. HTML regeneration not required.")
print("--- Repository Update Check Finished ---")
if __name__ == "__main__":
# For now, just run once. Scheduling will be added later.
main()
write a cpp program that prints only the leaf nodes in a tree.cpp
//write a cpp program that prints only the leaf nodes in a tree
#include<iostream>
using namespace std;
class node {
public:
int d;
node *left, *right;
node(int val) : d(val), left(NULL), right(NULL) {}
};
class B {
public:
node* insert(node* r, int v) {
if (r == NULL) {
return new node(v);
}
if (v < r->d) {
r->left = insert(r->left, v);
} else if (v > r->d) {
r->right = insert(r->right, v);
}
return r;
}
void printLeafNodes(node* r) {
if (r == NULL) return;
if (r->left == NULL && r->right == NULL) {
cout << r->d << " ";
return;
}
printLeafNodes(r->left);
printLeafNodes(r->right);
}
};
int main() {
node *r = NULL;
B c;
int n, val;
cout << "How many values? ";
cin >> n;
cout << "Enter values:\n";
for (int i = 0; i < n; ++i) {
cin >> val;
r = c.insert(r, val);
}
cout << "Leaf nodes: ";
c.printLeafNodes(r);
cout << endl;
return 0;
}