Wednesday, 20 March 2024

Leveraging Python to Parse and Upload OneNote Content to Azure Blob Storage Container


                              



 Leveraging Python to Parse and Upload OneNote Content to Azure Blob Storage Container

In today's digital age, managing and accessing data efficiently is paramount for businesses and individuals alike. With the abundance of digital sources like Microsoft OneNote, organizing and extracting valuable insights from such data can be challenging. However, by combining the power of Python with Azure services, we can automate these tasks seamlessly. In this blog post, we'll explore how to fetch, parse, and upload OneNote content to Azure Blob Storage Container, facilitating better data management and accessibility.


Introduction

Microsoft OneNote serves as a versatile platform for capturing and organizing notes, ideas, and information. Nevertheless, integrating OneNote's content into larger workflows or applications programmatically can be daunting. Fortunately, through the integration of Python and Azure services, we can streamline this process effectively.



 Fetching OneNote Content

Our journey begins with fetching the content of a OneNote notebook. Leveraging Python's `requests` library, we can interact with the Microsoft Graph API, which provides endpoints to access various resources within OneNote. By authenticating with the Graph API and specifying the desired notebook ID, we can retrieve the notebook's sections and pages programmatically.


Parsing HTML Content

OneNote stores its content in HTML format, making it accessible but not necessarily easy to work with programmatically. Here's where Python's `BeautifulSoup` library comes into play. By parsing the HTML content obtained from OneNote, we can extract relevant information and convert it into a more manageable format, such as plain text. This process allows us to distill the essential insights from the rich HTML structure of OneNote pages.



Uploading to Azure Blob Storage

Once we have parsed the OneNote content and transformed it into a suitable format, the next step is to store it securely. Azure Blob Storage offers a robust solution for storing unstructured data, such as text files, with scalability and reliability. Leveraging Python's `azure-storage-blob` library, we can easily upload our parsed content to an Azure Blob Storage Container. By specifying the appropriate connection string, container name, and file path, we ensure seamless integration with Azure's storage infrastructure.

                     



Conclusion

In this blog post, we've explored how Python can be harnessed to automate the process of fetching, parsing, and uploading OneNote content to Azure Blob Storage Container. By combining the capabilities of Python libraries such as `requests`, `BeautifulSoup`, and `azure-storage-blob`, we can streamline data management tasks and enhance overall efficiency. This integration empowers businesses and individuals to harness the wealth of information stored in OneNote and leverage Azure's scalable storage infrastructure for enhanced accessibility and reliability.


Stay tuned for more insightful tutorials and guides on leveraging Python and Azure services for data manipulation and automation!


Thursday, 7 March 2024

Demystifying Access to Shared OneNote Files: Navigating Challenges and Solutions







Navigating Shared OneNote Files: Overcoming Access Challenges


OneNote stands as a versatile tool for collaboration and organization, allowing users to share notebooks effortlessly. However, when it comes to programmatically accessing shared OneNote files, developers often encounter unique challenges. In this comprehensive blog, we'll delve into the complexities of accessing shared OneNote files, understand the encountered errors, and explore strategies for overcoming these obstacles.


 Understanding the Scenario

Imagine being granted full access to a shared OneNote notebook, with the expectation of retrieving its contents programmatically. However, attempts to fetch content may yield unexpected errors, leaving developers puzzled. These errors often manifest as "404 - itemNotFound" responses, indicating the inability to locate the shared OneNote file.


Unraveling the Error

The "404 - itemNotFound" error hints at the underlying complexities involved. It suggests that despite having the necessary permissions, the resource sought, i.e., the shared OneNote file, remains elusive. This discrepancy can stem from various factors, including permission settings, request structures, or limitations inherent in the interaction between scripts and the OneNote API.


Delving into Permission Limitations

OneNote files boast intricate permission structures, distinguishing them from more straightforward file formats like PDFs or Word documents. Even with full access granted to a shared OneNote file, equivalent accessibility may not be conferred, posing a significant challenge for developers. Additionally, the distinction between personal and shared sections within OneNote further complicates access, as shared files may not be readily visible in personal sections.






When we try to accessing the onenote file which is shared by someone to you so its not available on your one-drive stored section you need to access those file in Shared with me section.




Conclusion: Navigating the Maze

Accessing shared OneNote files programmatically demands meticulous attention to detail and a nuanced understanding of OneNote's ecosystem. While errors may initially seem daunting, armed with insights into permission limitations and file structure intricacies, developers can devise effective strategies for overcoming these challenges.


In conclusion, by embracing the complexities of accessing shared OneNote files and adopting informed approaches, developers can unlock the full potential of OneNote integration, facilitating seamless collaboration and data retrieval. As the digital landscape continues to evolve, mastering the art of navigating shared OneNote files becomes an invaluable skill, empowering developers to harness the power of collaboration with confidence and efficiency.

Sunday, 25 February 2024

Simplifying OneNote File Parsing with Python and Microsoft Graph API





Simplifying OneNote File Parsing with Python and Microsoft Graph API


Managing and extracting content from OneNote files programmatically can be a daunting task, especially without the right tools and approaches. In this guide, we'll explore how to simplify this process using Python scripts and Microsoft Graph API integration.


1. Initial Approach:


Traditionally, accessing OneNote files through Python relied on libraries like the OneNote parser. However, this approach often lacked robustness and efficiency, as shown below:


python

from onenote_parser import parse_onenote


2. Microsoft Graph API Integration:

To streamline access to OneNote files, leveraging the Microsoft Graph API offers a more reliable solution. This API enables seamless interaction with OneNote resources, ensuring efficient data retrieval and manipulation.


3. Key Steps for Access:

To successfully parse OneNote files using Python and Microsoft Graph API, follow these key steps:


   a. File Upload to OneDrive: Begin by uploading relevant files to OneDrive, Microsoft's cloud storage platform, which serves as a bridge for accessing OneNote content.

   

   b. Utilization of Microsoft Graph API: Interface with OneNote notebooks programmatically using Microsoft Graph API. This API provides robust mechanisms for data retrieval, ensuring seamless integration.

   

   c. Permission Configuration: Grant necessary permissions within the OneNote section of the Graph API to ensure proper access to desired resources, ensuring secure data retrieval.

   

   d. Access Token Retrieval: Collect the access token directly from the Microsoft Graph API. This token, along with the notebook ID, is crucial for extracting content from OneNote pages securely.


4. Caution on Token Generation:


While it's possible to generate access tokens independently, this approach often yields incorrect tokens. It's advisable to obtain access tokens directly from the Microsoft Graph API for a reliable and secure means of accessing OneNote file content.


Python Script Example:


python

import requests

from bs4 import BeautifulSoup


# Replace with your own access token

access_token = 'your_access_token'


# Replace with the OneNote page ID

page_id = 'your_page_id'


# Construct the URL for the OneNote page's content

content_url = f'https://graph.microsoft.com/v1.0/me/onenote/pages/{page_id}/content'


# Set the request headers, including the access token

headers = {

    'Authorization': 'Bearer ' + access_token,

}


# Make the GET request to retrieve the content of the OneNote page

response = requests.get(content_url, headers=headers)


if response.status_code == 200:

    page_content = response.text

    soup = BeautifulSoup(page_content, 'html.parser')


    # Extract and print all text content

    text_content = soup.get_text()

    print("Text content:")

    print(text_content)


    # Extract and print table content

    tables = soup.find_all('table')

    for table in tables:

        print("Table:")

        for row in table.find_all('tr'):

            cells = row.find_all('td')

            row_data = [cell.get_text() for cell in cells]

            print(row_data)


    # Extract and print bulleted and numbered list items

    lists = soup.find_all(['ul', 'ol'])

    for ulist in lists:

        list_items = ulist.find_all('li')

        for item in list_items:

            print("List item:", item.get_text())


    # Extract and print hyperlinks

    links = soup.find_all('a')

    for link in links:

        print("Hyperlink:", link['href'])


else:

    print(f"Failed to retrieve driveItem content: {response.status_code}")





Final output



Parsed Content:




By following these steps and leveraging Python alongside the Microsoft Graph API, parsing OneNote files becomes simpler and more efficient, opening up possibilities for seamless integration and automation in various applications.

Thursday, 15 February 2024

Maximizing OneNote Integration: A Guide to Access Tokens in Microsoft Graph API


                                  



Title: Maximizing OneNote Integration: A Guide to Access Tokens in Microsoft Graph API


Access Token Essentials

Client ID, Secret ID, and Tenant ID

When registering an application on Azure for Graph API integration, you'll receive essential credentials:

Client ID: A unique identifier for your application.

Secret ID: A confidential key used for authentication.

Tenant ID: Identifies the organization that owns the application.

These IDs authenticate your application's identity and grant access to Microsoft Graph API resources.


Redirect URI

During app registration, you specify a Redirect URI. This URI serves as a callback endpoint where the authorization server redirects users after authentication. It plays a vital role in the OAuth 2.0 authorization flow, facilitating the exchange of authorization codes for access tokens.


---------------------------------------------------------------------------------------------------------------------------

1. Client ID, Secret ID, and Tenant ID


These credentials are obtained during the registration of your application in the Azure portal:





Client ID: After creating an Azure AD application, navigate to the "App registrations" section in the Azure portal. Select your application to view its details, including the Client ID.


Secret ID: Also known as the Application Secret or Client Secret, you can generate this key under the "Certificates & secrets" section within your application's settings in the Azure portal.


Tenant ID: This ID represents the Azure AD tenant associated with your organization. You can find it in the Azure portal by navigating to "Azure Active Directory" > "Properties" and locating the Directory (tenant) ID.



2. Redirect URI


During app registration, you specify a Redirect URI where the authorization server redirects users after authentication. You can define this URI based on your application's requirements. Typically, it's a route within your application where the authorization code is received and processed.





3. Obtaining Access Tokens

To retrieve access tokens for Microsoft Graph API:


Authentication Flow: Implement OAuth 2.0 authorization flow in your application, which involves redirecting users to the Microsoft login page for authentication and consent.


Authorization Request: Construct an authorization request URL with parameters such as Client ID, Redirect URI, and requested scopes.


User Authentication: Users log in with their Microsoft credentials and grant consent for your application to access their data.


 Access Token Retrieval: After successful authentication and consent, the authorization server issues an authorization code to your Redirect URI. Exchange this code for an access token by sending a token request to the token endpoint, including Client ID, Secret ID, Redirect URI, and Tenant ID.


Cautionary Note

Relying solely on direct token generation outside the OAuth 2.0 flow can lead to security risks and issues. It's essential to adhere to best practices by following the OAuth 2.0 authorization flow and obtaining access tokens directly from Microsoft Graph API.


By navigating through the Azure portal and integrating these credentials and flows into your application, you can ensure secure and reliable access to OneNote and other Microsoft services via Microsoft Graph API.

Friday, 2 February 2024

Unveiling OneNote Files: Understanding the Dynamics and Microsoft's Shift in Access Policies







Title: Unveiling OneNote Files: Understanding the Dynamics and Microsoft's Shift in Access Policies


Introduction:


OneNote, Microsoft's versatile note-taking platform, has become an integral part of personal and professional productivity. Understanding the intricacies of OneNote files and the recent shifts in Microsoft's access policies is crucial for users and developers alike. In this blog post, we will delve into what OneNote files are, how they work, and the reasons behind Microsoft's decision to restrict direct access to OneNote files.



1. What is a OneNote File ?

A OneNote file is essentially a notebook, a digital space where users can create and organize notes, drawings, clippings, and multimedia content. These files are stored in a proprietary format, combining sections, pages, and metadata to create a cohesive digital notebook experience.


2. How OneNote Files Work:

OneNote files employ a hierarchical structure, with notebooks containing sections, sections containing pages, and pages hosting various types of content. The dynamic nature of OneNote allows users to collaborate in real-time, making it a versatile tool for both individuals and teams.


3. Microsoft's Shift: Blocking Direct Access to OneNote Files

In the earlier days, developers often attempted to access OneNote files directly using Python libraries like the OneNote parser. However, as technology evolves and security becomes a paramount concern, Microsoft implemented a shift in access policies.


4. The Rise of Microsoft Graph API:

To enhance security, Microsoft encouraged developers to leverage the Microsoft Graph API for OneNote integration. This API serves as a gateway, allowing programmatic access to OneNote resources while ensuring secure authentication and controlled permissions.


5. Why the Change?

Microsoft's decision to block direct access to OneNote files stems from the need to enhance security, prevent unauthorized access, and streamline the integration process. The Microsoft Graph API provides a standardized, secure approach, reducing the risk of vulnerabilities associated with direct file access.


6. The Impact on Developers:

For developers, this shift necessitates a change in approach. While direct access may have been simpler, integrating with the Microsoft Graph API provides a more robust, standardized, and secure way to interact with OneNote files programmatically.


7. Benefits of Microsoft Graph API Integration:

Embracing the Microsoft Graph API brings numerous benefits, including enhanced security, better collaboration features, and compatibility with other Microsoft 365 services. Developers can now create more seamless and integrated solutions within the Microsoft ecosystem.


Conclusion:

Understanding the nature of OneNote files, their hierarchical structure, and the recent shift in Microsoft's access policies is crucial for users and developers. While the change may pose challenges initially, the adoption of the Microsoft Graph API ultimately enhances security and brings about a more standardized and efficient integration experience. Stay informed, adapt your approaches, and continue to unlock the full potential of OneNote in the evolving digital landscape.



                               




Tuesday, 23 January 2024

Mastering OneNote Integration in Python: A Comprehensive Guide

 



Title: Mastering OneNote Integration in Python: A Comprehensive Guide


Introduction:

OneNote, Microsoft's powerful note-taking platform, has become an indispensable tool for individuals and organizations alike. However, integrating OneNote functionality into Python scripts can be challenging. In this comprehensive guide, we will navigate through the hurdles of accessing, uploading, and sharing OneNote files using the Microsoft Graph API. Buckle up as we embark on a journey to seamlessly integrate OneNote with Python.


1. The Initial Challenge:

Python developers often attempt to access OneNote files directly using libraries like the OneNote parser. Unfortunately, this approach falls short, highlighting the need for a more robust and effective solution.


2. Embracing the Microsoft Graph API:

The key to overcoming the initial challenges lies in leveraging the Microsoft Graph API. This API opens up a world of possibilities, allowing for seamless integration and interaction with OneNote resources programmatically.


3. Essential Steps for Access:

3.1 File Upload to OneDrive:

Begin by uploading your relevant OneNote files to OneDrive, Microsoft's cloud storage platform. This sets the stage for easy retrieval through the Graph API.


3.2 Utilization of Microsoft Graph API:

Tap into the power of the Microsoft Graph API to interface with OneNote notebooks. This step serves as a robust mechanism for data retrieval and interaction with the contents of your OneNote pages.


3.3 Permission Configuration:

Grant the necessary permissions within the OneNote section of the Graph API. Proper configuration is vital to ensure secure access to your desired OneNote resources, specifying the level of access needed for your Python script or application.


3.4 Access Token Retrieval:

Retrieve the access token directly from the Microsoft Graph API. Combine this token with the notebook ID to establish a secure and authenticated means of extracting content from your OneNote pages.


4. Caution on Token Generation:

While it's tempting to generate an access token independently, doing so often leads to incorrect tokens. Our guide strongly recommends obtaining the access token directly from the Microsoft Graph API for a reliable and secure method of accessing OneNote file content.


Output of content after Parsing



Conclusion:

By following this comprehensive guide, Python developers can overcome the challenges associated with accessing, uploading, and sharing OneNote files. Embracing the Microsoft Graph API opens up a world of possibilities, making the integration of OneNote functionality into Python scripts more effective and secure. Navigate with confidence as you master the art of seamlessly connecting Python with OneNote, unlocking a new realm of possibilities for your development projects. Happy coding!









Wednesday, 3 May 2023

DAA

 DAA



PRIMS


// A C++ program for Prim's Minimum

// Spanning Tree (MST) algorithm. The program is

// for adjacency matrix representation of the graph


#include <bits/stdc++.h>

using namespace std;


// Number of vertices in the graph

#define V 5


// A utility function to find the vertex with

// minimum key value, from the set of vertices

// not yet included in MST

int minKey(int key[], bool mstSet[])

{

// Initialize min value

int min = INT_MAX, min_index;


for (int v = 0; v < V; v++)

if (mstSet[v] == false && key[v] < min)

min = key[v], min_index = v;


return min_index;

}


// A utility function to print the

// constructed MST stored in parent[]

void printMST(int parent[], int graph[V][V])

{

cout << "Edge \tWeight\n";

for (int i = 1; i < V; i++)

cout << parent[i] << " - " << i << " \t"

<< graph[i][parent[i]] << " \n";

}


// Function to construct and print MST for

// a graph represented using adjacency

// matrix representation

void primMST(int graph[V][V])

{

// Array to store constructed MST

int parent[V];


// Key values used to pick minimum weight edge in cut

int key[V];


// To represent set of vertices included in MST

bool mstSet[V];


// Initialize all keys as INFINITE

for (int i = 0; i < V; i++)

key[i] = INT_MAX, mstSet[i] = false;


// Always include first 1st vertex in MST.

// Make key 0 so that this vertex is picked as first

// vertex.

key[0] = 0;


// First node is always root of MST

parent[0] = -1;


// The MST will have V vertices

for (int count = 0; count < V - 1; count++) {

// Pick the minimum key vertex from the

// set of vertices not yet included in MST

int u = minKey(key, mstSet);


// Add the picked vertex to the MST Set

mstSet[u] = true;


// Update key value and parent index of

// the adjacent vertices of the picked vertex.

// Consider only those vertices which are not

// yet included in MST

for (int v = 0; v < V; v++)


// graph[u][v] is non zero only for adjacent

// vertices of m mstSet[v] is false for vertices

// not yet included in MST Update the key only

// if graph[u][v] is smaller than key[v]

if (graph[u][v] && mstSet[v] == false

&& graph[u][v] < key[v])

parent[v] = u, key[v] = graph[u][v];

}


// Print the constructed MST

printMST(parent, graph);

}


// Driver's code

int main()

{

int graph[V][V] = { { 0, 4, 0, 1, 0 },-

{ 2, 0, 6, 8, 5 },

{ 0, 7, 0, 0, 4 },

{ 2, 8, 0, 0, 9 },

{ 0, 5, 6, 8, 0 } };


// Print the solution

primMST(graph);


return 0;

}



---------------------------------------------------------------------------

ACTIVITY CABS


#include<iostream>

using namespace std;

// Prints a maximum set of activities that can be done by a single

// person, one at a time.

// n --> Total number persons

// s[] --> An array that contains start time of all person

// f[] --> An array that contains finish time of all persons

int printMaxcabs(int s[], int f[], int n)

{

 int i, j, count =1;

 printf ("No of person selected \n");

 // The first activity always gets selected

 i = 0;

 printf("%d ", i);

 // Consider rest of the activities

 for (j = 1; j < n; j++)

 {

 // If this activity has start time greater than or

 // equal to the finish time of previously selected

 // activity, then select it

 if (s[j] >= f[i])

 {

 printf ("%d ", j);

 i = j;

 count++;

 }

 }

 return count;

}

int main()

{

 int s[30],f[30], n

 ;

 cout<<"\n Enter the number of person :";

 cin>>n;

 for (int i=0;i<n;i++)

 {

 cout<<"\n Start time for "<<i<<" person :";

 cin>>s[i];

 cout<<"\n Finish time for "<<i<<" person :";

 cin>>f[i];

 }

 int result= printMaxcabs(s, f, n);

 cout<<"\n Number of Cabs required :"<<result;

 return 0;

}



-------------------------------------------------------------------------------------
RABIN KARP


/* Following program is a C++ implementation of Rabin Karp
Algorithm given in the CLRS book */
#include <bits/stdc++.h>
using namespace std;

// d is the number of characters in the input alphabet
#define d 256

/* pat -> pattern
txt -> text
q -> A prime number  
*/
void search(char pat[], char txt[], int q)-


{
int M = strlen(pat);
int N = strlen(txt);
int i, j;
int p = 0; // hash value for pattern
int t = 0; // hash value for txt
int h = 1;

// The value of h would be "pow(d, M-1)%q"
for (i = 0; i < M - 1; i++)
h = (h * d) % q;

// Calculate the hash value of pattern and first
// window of text
for (i = 0; i < M; i++) {
p = (d * p + pat[i]) % q;
t = (d * t + txt[i]) % q;
}

// Slide the pattern over text one by one
for (i = 0; i <= N - M; i++) {

// Check the hash values of current window of text
// and pattern. If the hash values match then only
// check for characters one by one
if (p == t) {
/* Check for characters one by one */
for (j = 0; j < M; j++) {
if (txt[i + j] != pat[j]) {
break;
}
}

// if p == t and pat[0...M-1] = txt[i, i+1,
// ...i+M-1]

if (j == M)
cout << "Pattern found at index " << i
<< endl;
}

// Calculate hash value for next window of text:
// Remove leading digit, add trailing digit
if (i < N - M) {
t = (d * (t - txt[i] * h) + txt[i + M]) % q;

// We might get negative value of t, converting
// it to positive
if (t < 0)
t = (t + q);
}
}
}

/* Driver code */
int main()
{
char txt[] = "i never learned to read your mind , never learned to read my mind";
char pat[] = "mind";

// we mod to avoid overflowing of value but we should
// take as big q as possible to avoid the collison
int q = INT_MAX;

// Function Call
search(pat, txt, q);
return 0;
}

// This is code is contributed by rathbhupendra




-------------------------------------------------------------------------------------


HUFFMAN






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

struct MinHeapNode
{
    char d;
    unsigned frequency;
    MinHeapNode *lChild, *rChild;
//constructor
    MinHeapNode(char d, unsigned frequency)

    {

        lChild = rChild = NULL;
        this->d = d;
        this->frequency = frequency;
    }
};

//function to compare
struct compare
{
    bool operator()(MinHeapNode *l, MinHeapNode *r)
    {
        return (l->frequency > r->frequency);
    }
};

void printCodes(struct MinHeapNode *root, string str)
{
    if (!root)
        return;

    if (root->d != '$')
        cout << root->d << ": " << str << "\n";

    printCodes(root->lChild, str + "0");
    printCodes(root->rChild, str + "1");
}

void HuffmanCodes(char d[], int frequency[], int size)
{
    struct MinHeapNode *lChild, *rChild, *top;

    priority_queue<MinHeapNode *, vector<MinHeapNode *>, compare> minHeap;

    for (int i = 0; i < size; ++i)
        minHeap.push(new MinHeapNode(d[i], frequency[i]));

    while (minHeap.size() != 1)
    {
        lChild = minHeap.top();
        minHeap.pop();

        rChild = minHeap.top();
        minHeap.pop();

        top = new MinHeapNode('$', lChild->frequency + rChild->frequency);

        top->lChild = lChild;
        top->rChild = rChild;

        minHeap.push(top);
    }
    printCodes(minHeap.top(), "");
}

int main()
{

    char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'};
    int frequency[] = {5, 9, 12, 13, 16, 45};

    int size = sizeof(arr) / sizeof(arr[0]);

    HuffmanCodes(arr, frequency, size);

    return 0;
}






-------------------------------------------------------------------------------------

TSP

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 4;
const int INF = 1e9;

int dist[N][N] = {{0, 10, 15, 20},
          {10, 0, 35, 25},
          {15, 35, 0, 30},
          {20, 25, 30, 0}};

int tsp(int start, int visited, int current, int cnt, int path[]) {
    if(cnt == N) { // all cities visited
        return dist[current][start];
    }
    int ans = INF;
    for(int i = 0; i < N; i++) {
        if(!(visited & (1<<i))) { // if i-th city is not visited
            path[cnt] = i;
            ans = min(ans, dist[current][i] + tsp(start, visited | (1<<i), i, cnt+1, path));
        }
    }
    return ans;
}

int main() {
    int path[N];
    int ans = INF;
    int start = 0; // starting city
    for(int i = 0; i < N; i++) {
        path[0] = i; // set first city in path
        ans = min(ans, dist[start][i] + tsp(start, 1<<i, i, 1, path));
    }
    cout << "Minimum distance: " << ans << endl;
    cout << "Path: ";
    cout <<endl<< start <<" " ; // add starting city at the end
    for(int i = 0; i < N; i++) {
        cout << path[i] << " ";
    }
    
    return 0;
}


----------------------------------------------------------------------------------


COINS CHANGING


#include<bits/stdc++.h>

using namespace std;

const int INF = 100000;

//k is number of denominations of the coin or length of d
int dynamic(int d[], int n, int k) {
  int M[n+1];
  M[0] = 0;

  int S[n+1];
  S[0] = 0;

  int i, j;
  for(j=1; j<=n; j++) {
    int minimum = INF;
    int coin=0;

    for(i=1; i<=k; i++) {
      if(j >= d[i]) {
        if((1+M[j-d[i]]) < minimum) {
          minimum = 1+M[j-d[i]];
          coin = i;
        }
      }
    }
    M[j] = minimum;
    S[j] = coin;
  }

  int l = n;
  while(l>0) {
    printf("\n Coins used are  : %d\n",d[S[l]]);
    l = l-d[S[l]];
  }
  return 0;
}

int greedy(int coins[], int num, int amount) 
{
int coin_counter = 0;
int j = num - 1;
sort(coins, coins + num);
while(amount != 0)
{
if(amount >= coins[j])
{
coin_counter++;
cout << "\nCoin " << coins[j] << " used\n";
amount = amount - coins[j];
}
else
{
j--;
}
}
return coin_counter;
}

/*
int dynamic(int coins[], int n, int amount) {
  int dp[amount + 1];
  dp[0] = 0;
  for (int i = 1; i <= amount; i++) {
    dp[i] = INT_MAX;
    for (int j = 0; j < n; j++) {
      if (coins[j] <= i && dp[i - coins[j]] != INT_MAX) {
        dp[i] = min(dp[i], dp[i - coins[j]] + 1);
      }
      if(dp[i] == coins[j])
      {
      cout << "\nCoin " << coins[j] << " used\n";
  }
    }
  }
  return dp[amount];
}
*/

int main() {
  int choice;
  do {
    cout << "1. Dynamic Programming approach\n";
    cout << "2. Greedy approach\n";
    cout << "3. Exit\n";
    cout << "Enter your choice: ";
    cin >> choice;
    switch (choice) {
    case 1: {
      int n, amount;
      cout << "Enter the number of coins denominations: ";
      cin >> n;
      int coins[n];
      cout << "Enter the coins denominations: ";
      for (int i = 0; i < n; i++) {
        cin >> coins[i];
      }
      cout << "Enter the amount: ";
      cin >> amount;
      dynamic(coins, amount, n);
      cout<<endl;
      break;
    }
    case 2: {
      int n, amount;
      cout << "Enter the number of coins denominations: ";
      cin >> n;
      int coins[n];
      cout << "Enter the coins denominations: ";
      for (int i = 0; i < n; i++) {
        cin >> coins[i];
      }
      cout << "Enter the amount: ";
      cin >> amount;
      cout << "Minimum number of coins required using Greedy Approach: " << greedy(coins, n, amount) << endl;
      break;
    }
    case 3: {
      cout<<"Exiting ! byee ! "<<endl;
      break;
    }
    default: {
      cout << "Invalid choice! Please try again.\n";
    }
    }
  } while (choice != 3);
  return 0;
}






--------------------------------------------------------------------------------------------

KRURKSHAL




// C++ program for Kruskal's algorithm to find Minimum
// Spanning Tree of a given connected, undirected and
// weighted graph
#include<bits/stdc++.h>
using namespace std;

// Creating shortcut for an integer pair
typedef pair<int, int> iPair;

// Structure to represent a graph
struct Graph
{
int V, E;
vector< pair<int, iPair> > edges;

// Constructor
Graph(int V, int E)
{
this->V = V;
this->E = E;
}

// Utility function to add an edge
void addEdge(int u, int v, int w)
{
edges.push_back({w, {u, v}});
}

// Function to find MST using Kruskal's
// MST algorithm
int kruskalMST();
};

// To represent Disjoint Sets
struct DisjointSets
{
int *parent, *rnk;
int n;

// Constructor.
DisjointSets(int n)
{
// Allocate memory
this->n = n;
parent = new int[n+1];
rnk = new int[n+1];

// Initially, all vertices are in
// different sets and have rank 0.
for (int i = 0; i <= n; i++)
{
rnk[i] = 0;

//every element is parent of itself
parent[i] = i;
}
}

// Find the parent of a node 'u'
// Path Compression
int find(int u)
{
/* Make the parent of the nodes in the path
from u--> parent[u] point to parent[u] */
if (u != parent[u])
parent[u] = find(parent[u]);
return parent[u];
}

// Union by rank
void merge(int x, int y)
{
x = find(x), y = find(y);

/* Make tree with smaller height
a subtree of the other tree */
if (rnk[x] > rnk[y])
parent[y] = x;
else // If rnk[x] <= rnk[y]
parent[x] = y;

if (rnk[x] == rnk[y])
rnk[y]++;
}
};

/* Functions returns weight of the MST*/

int Graph::kruskalMST()
{
int mst_wt = 0; // Initialize result

// Sort edges in increasing order on basis of cost
sort(edges.begin(), edges.end());

// Create disjoint sets
DisjointSets ds(V);

// Iterate through all sorted edges
vector< pair<int, iPair> >::iterator it;
for (it=edges.begin(); it!=edges.end(); it++)
{
int u = it->second.first;
int v = it->second.second;

int set_u = ds.find(u);
int set_v = ds.find(v);

// Check if the selected edge is creating
// a cycle or not (Cycle is created if u
// and v belong to same set)
if (set_u != set_v)
{
// Current edge will be in the MST
// so print it
cout << u << " - " << v << endl;

// Update MST weight
mst_wt += it->first;

// Merge two sets
ds.merge(set_u, set_v);
}
}

return mst_wt;
}

// Driver program to test above functions
int main()
{
/* Let us create above shown weighted
and undirected graph */
int V = 9, E = 14;
Graph g(V, E);

// making above shown graph
g.addEdge(0, 2, 4);
g.addEdge(0, 5, 8);
g.addEdge(1, 2, 8);
g.addEdge(1, 7, 11);
g.addEdge(2, 8, 7);
g.addEdge(2, 3, 2);
g.addEdge(2, 5, 4);
g.addEdge(3, 4, 9);
g.addEdge(3, 5, 14);
g.addEdge(4, 3, 10);
g.addEdge(5, 6, 2);
g.addEdge(6, 7, 1);
g.addEdge(6, 2, 6);
g.addEdge(7, 8, 7);

cout << "Edges of MST are \n";
int mst_wt = g.kruskalMST();

cout << "\nWeight of MST is " << mst_wt;

return 0;
}





--------------------------------------------------------------------------------------------


BOYE MOOREE


/* C++ Program for Bad Character Heuristic of Boyer
Moore String Matching Algorithm */
#include <bits/stdc++.h>
using namespace std;
# define NO_OF_CHARS 256

// The preprocessing function for Boyer Moore's
// bad character heuristic
void badCharHeuristic( string str, int size,
int badchar[NO_OF_CHARS])
{
int i;

// Initialize all occurrences as -1
for (i = 0; i < NO_OF_CHARS; i++)
badchar[i] = -1;

// Fill the actual value of last occurrence
// of a character
for (i = 0; i < size; i++)
badchar[(int) str[i]] = i;
}

/* A pattern searching function that uses Bad
Character Heuristic of Boyer Moore Algorithm */
void search( string txt, string pat)
{
int m = pat.size();
int n = txt.size();

int badchar[NO_OF_CHARS];

/* Fill the bad character array by calling
the preprocessing function badCharHeuristic()
for given pattern */
badCharHeuristic(pat, m, badchar);

int s = 0; // s is shift of the pattern with
// respect to text
while(s <= (n - m))
{
int j = m - 1;

/* Keep reducing index j of pattern while
characters of pattern and text are
matching at this shift s */
while(j >= 0 && pat[j] == txt[s + j])
j--;

/* If the pattern is present at current
shift, then index j will become -1 after
the above loop */
if (j < 0)
{
cout << "pattern occurs at shift = " << s << endl;

/* Shift the pattern so that the next
character in text aligns with the last
occurrence of it in pattern.
The condition s+m < n is necessary for
the case when pattern occurs at the end
of text */
s += (s + m < n)? m-badchar[txt[s + m]] : 1;

}

else
/* Shift the pattern so that the bad character
in text aligns with the last occurrence of
it in pattern. The max function is used to
make sure that we get a positive shift.
We may get a negative shift if the last
occurrence of bad character in pattern
is on the right side of the current
character. */
s += max(1, j - badchar[txt[s + j]]);
}
}

/* Driver code */
int main()
{
string txt= "ABAAABCD";
string pat = "ABC";
search(txt, pat);
return 0;
}

// This code is contributed by rathbhupendra



-----------------------------------------------------------------------------------------------------

Min max using dc



#include<stdio.h>
#include<stdio.h>
int max, min;
int a[100];
void maxmin(int i, int j)
{
 int max1, min1, mid;
 if(i==j)
 {
  max = min = a[i];
 }
 else
 {
  if(i == j-1)
  {
   if(a[i] <a[j])
   {
    max = a[j];
    min = a[i];
   }
   else
   {
    max = a[i];
    min = a[j];
   }
  }
  else
  {
   mid = (i+j)/2;
   maxmin(i, mid);
   max1 = max; min1 = min;
   maxmin(mid+1, j);
   if(max <max1)
    max = max1;
   if(min > min1)
    min = min1;
  }
 }
}
int main ()
{
 int i, num;
 printf ("\nEnter the total number of numbers : ");
 scanf ("%d",&num);
 printf ("Enter the numbers : \n");
 for (i=1;i<=num;i++)
  scanf ("%d",&a[i]);

 max = a[0];
 min = a[0];
 maxmin(1, num);
 printf ("Minimum element in an array : %d\n", min);
 printf ("Maximum element in an array : %d\n", max);
 return 0;
}






--------------------------------------------------------------------------------------------


0/1  Greedy


#include <iostream>
using namespace std;


const int MAXN = 1000;

int n, m;
int w[MAXN], v[MAXN];

int knapsack() {
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        if (w[i] > m) break; // If the weight of the item exceeds the capacity of the knapsack, skip it
        ans += v[i];
        m -= w[i];
        cout<< i <<" Item included ! "<<endl;
    }
    return ans;
}

int main() {
cout<<"Enter the no. of elements : ";
    cin >> n;
    for (int i = 1; i <= n; i++) {
    cout<<"\nEnter the weight of "<<i<<" th element : ";
        cin >> w[i];
        cout<<"\nEnter the value of "<<i<<"th element : ";
        cin>>v[i];
    }
    cout<<"\nEnter the maximum capacity of the knapsack : ";
    cin>>m;
    int ans = knapsack();
    cout << "\n\nProfit is : "<< ans << endl;
    return 0;
}


/* 
#include <iostream>
using namespace std;

void knapSack(int W, int wt[], int val[], int n) {
    int i, j, maxVal = 0, curW = 0;
    for (i = 0; i < n; i++) {
        if (curW + wt[i] <= W) {
            curW += wt[i];
            maxVal += val[i];
        }
        else {
            int remain = W - curW;
            maxVal += (remain * val[i]) / wt[i];
            break;
        }
    }
    cout << "Maximum value that can be put in a knapsack of capacity " << W << " is " << maxVal << endl;
}

int main() {
    int val[] = { 60, 100, 120 };
    int wt[] = { 10, 20, 30 };
    int W = 50;
    int n = sizeof(val) / sizeof(val[0]);
    knapSack(W, wt, val, n);
    return 0;
}
*/




--------------------------------------------------------------------------------------------

0/1 dynamic


#include <iostream>
using namespace std;

int knapSack(int W, int wt[], int val[], int n) {
    int i, w;
    int K[n + 1][W + 1];
    for (i = 0; i <= n; i++) {
        for (w = 0; w <= W; w++) {
            if (i == 0 || w == 0)
                K[i][w] = 0;
            else if (wt[i - 1] <= w)
                K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
            else
                K[i][w] = K[i - 1][w];
        }
    }
    return K[n][W];
}

int main() {
    int val[] = { 60, 100, 120 };
    int wt[] = { 10, 20, 30 };
    int W = 50;
    int n = sizeof(val) / sizeof(val[0]);
    cout << "Maximum profit that can be gained in a knapsack of capacity " << W << " is " << knapSack(W, wt, val, n) << endl;
    return 0;
}






--------------------------------------------------------------------------------------------


fractional knapsack..




#include <iostream>
#include <bits/stdc++.h>

using namespace std;
typedef struct {
   int v;
   int w;
   float d;
} Item;
void input(Item items[],int sizeOfItems) {
   cout << "Enter total "<< sizeOfItems <<" item's values and weight" <<
   endl;
   for(int i = 0; i < sizeOfItems; i++) {
      cout << "Enter "<< i+1 << " V ";
      cin >> items[i].v;
      cout << "Enter "<< i+1 << " W ";
      cin >> items[i].w;
   }
}
void display(Item items[], int sizeOfItems) {
   int i;
   cout << "values: ";
   for(i = 0; i < sizeOfItems; i++) {
      cout << items[i].v << "\t";
   }
   cout << endl << "weight: ";
   for (i = 0; i < sizeOfItems; i++) {
      cout << items[i].w << "\t";
   }
   cout << endl;
}
bool compare(Item i1, Item i2) {
   return (i1.d > i2.d);
}
float knapsack(Item items[], int sizeOfItems, int W) {
   int i, j;
   float totalValue = 0, totalWeight = 0;
   for (i = 0; i < sizeOfItems; i++) {
      items[i].d = (float)items[i].v / items[i].w; //typecasting done (v is int and w is also int so we get final value of d as int)
   }
   sort(items, items+sizeOfItems, compare);
   /*
   uncomment if u need to check the data after sortingis done
   cout << "values : ";
   for(i = 0; i < sizeOfItems; i++) {
      cout << items[i].v << "\t";
   }
   cout << endl << "weights: ";
   for (i = 0; i < sizeOfItems; i++) {
      cout << items[i].w << "\t";
   }
   cout << endl << "ratio  : ";
   for (i = 0; i < sizeOfItems; i++) {
      cout << items[i].d << "\t";
   }
   cout << endl;
   */
   for(i=0; i<sizeOfItems; i++) {
      if(totalWeight + items[i].w<= W) {
         totalValue += items[i].v ;
         totalWeight += items[i].w;
      } else {
         int wt = W-totalWeight;
         totalValue += (wt * items[i].d);
         totalWeight += wt;
         break;
      }
   }
   cout << "Total weight in bag " << totalWeight<<endl;
   return totalValue;
}

int main() {
   int W;
   Item items[4];
   input(items, 4);
   cout << "Entered data \n";
   display(items,4);
   cout<< "Enter Knapsack weight \n";
   cin >> W;
   float mxVal = knapsack(items, 4, W);
   cout << "Max value for "<< W <<" weight is "<< mxVal;
}

Accessing and Parsing OneNote Notebook Content from Azure Storage Containers

Accessing and Parsing OneNote Notebook Content from Azure Storage Containers OneNote is a powerful tool for digital note-taking and collabor...