code-rag-bench/online-tutorials huggingface dataset:
Encode Number in C++

Suppose we have a non-negative integer n, and we have to find the encoded form of it. The encoding strategy will be as follows −
So if the number is 23, then result will be 1000, if the number is 54, then it will be 10111
To solve this, we will follow these steps −
Create one method called bin, this will take n and k, this method will act like below
res := empty string
while n > 0res := res + the digit of n mod 2n := n /2
res := res + the digit of n mod 2
n := n /2
reverse the number res
while x > length of resres := prepend 0 with res
res := prepend 0 with res
return res
The actual method will be as follows −
if n = 0, then return empty string, if n is 1, return “0”, or when n is 2, then return “1”
x := log n base 2
if 2 ^ (x + 1) – 1 = n, thenans := empty stringincrease x by 1while x is not 0, then ans := append 0 with ans, and increase x by 1return ans
ans := empty string
increase x by 1
while x is not 0, then ans := append 0 with ans, and increase x by 1
return ans
return bin(n – 2^x + 1, x)
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string bin(int n, int x){
      string result = "";
      while(n>0){
         result += (n%2) + '0';
         n/=2;
      }
      reverse(result.begin(), result.end());
      while(x>result.size())result = '0' + result;
      return result;
   }
   string encode(int n) {
      if(n == 0)return "";
      if(n == 1)return "0";
      if(n==2) return "1";
      int x = log2(n);
      if(((1<<(x+1)) - 1) == n){
         string ans = "";
         x++;
         while(x--)ans+="0";
         return ans;
      }
      return bin(n - (1<<x) + 1, x);
   }
};
main(){
   Solution ob;
   cout << (ob.encode(23)) << endl;
   cout << (ob.encode(56)) << endl;
}
23
54
1000
11001
Histogram for discrete values with Matplotlib

To plot a histogram for discrete values with matplotlib, we can use hist() method.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make a list of discrete values.
Make a list of discrete values.
Use hist() method to plot data with bins=length of data and edgecolor=black.
Use hist() method to plot data with bins=length of data and edgecolor=black.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = [1, 4, 2, 3, 5, 9, 6, 7]
plt.hist(data, bins=len(data), edgecolor='black')
plt.show()
Program to find area of a circle - GeeksforGeeks

06 Nov, 2021
The area of a circle can simply be evaluated using the following formula. 
 
Area = pi * r2
where r is radius of circle and it maybe in float because value of pie is 3.14 
 
 
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find area// of circle#include <iostream>const double pi = 3.14159265358979323846;using namespace std; // function to calculate the area of circlefloat findArea(float r){    return (pi * r * r);}// driver codeint main(){    float r, Area;    r = 5;     // function calling    Area = findArea(r);    // displaying the area    cout << "Area of Circle is :" << Area;    return 0;}
// C program to find area// of circle#include <stdio.h>#include <math.h>#define PI 3.142 double findArea(int r){   return PI * pow(r, 2);} int main(){    printf("Area is %f", findArea(5));    return 0;}
// Java program to find area// of circle     class Test{    static final double PI = Math.PI;              static double findArea(int r)    {       return PI * Math.pow(r, 2);    }              // Driver method    public static void main(String[] args)    {        System.out.println("Area is " +  findArea(5));    }}
# Python3 program to find Area of a circle def findArea(r):    PI = 3.142    return PI * (r*r); # Driver methodprint("Area is %.6f" % findArea(5)); # This code is contributed by Chinmoy Lenka
// C# program to find area of circleusing System; class GFG{    static double PI = Math.PI;             static double findArea(int r)    {    return PI * Math.Pow(r, 2);    }             // Driver method    static void Main()    {        Console.Write("Area is " + findArea(5));    }} // This code is contributed by Sam007.
<?php// PHP program to find area// of circle      function findArea( $r){    $PI =3.142;    return $PI * pow($r, 2);}  // Driver Codeecho("Area is ");echo(findArea(5));return 0; // This code is contributed by vt_m.?>
<script> // Javascript program to find area// of circle let pi = 3.14159265358979323846;  // function to calculate the area of circlefunction findArea(r){    return (pi * r * r);} // Driver code    let r, Area;    r = 5;     // function calling    Area = findArea(r);         // displaying the area    document.write("Area of Circle is :" + Area);     // This code is contributed by Mayank Tyagi </script>
Output: 
Area is 78.550000
Time Complexity: O(1)
Auxiliary Space: O(1) 
vt_m
RamAryan
mayanktyagi1709
harisuman7082
subhammahato348
area-volume-programs
Geometric
Mathematical
School Programming
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Circle and Lattice Points
Queries on count of points lie inside a circle
Given n line segments, find if any two segments intersect
Check if a point lies inside a rectangle | Set-2
Window to Viewport Transformation in Computer Graphics with Implementation
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
C++ Program to Implement The Edmonds-Karp Algorithm

This is a C++ Program to Implement the Edmonds-Karp algorithm to calculate maximum flow between source and sink vertex.
Begin
   function edmondsKarp() :
      initiate flow as 0.
      If there is an augmenting path from source to sink, add the path to flow.
      Return flow.
End
#include<cstdio>
#include<queue>
#include<cstring>
#include<vector>
#include<iostream>
using namespace std;
int c[10][10];
int flowPassed[10][10];
vector<int> g[10];
int parList[10];
int currentPathC[10];
int bfs(int sNode, int eNode)//breadth first search
{
   memset(parList, -1, sizeof(parList));
   memset(currentPathC, 0, sizeof(currentPathC));
   queue<int> q;//declare queue vector
   q.push(sNode);
   parList[sNode] = -1;//initialize parlist’s source node
   currentPathC[sNode] = 999;//initialize currentpath’s source node
   while(!q.empty())// if q is not empty
   {
      int currNode = q.front();
      q.pop();
      for(int i=0; i<g[currNode].size(); i++)
      {
         int to = g[currNode][i];
         if(parList[to] == -1)
         {
            if(c[currNode][to] - flowPassed[currNode][to] > 0)
            {
               parList[to] = currNode;
               currentPathC[to] = min(currentPathC[currNode],
               c[currNode][to] - flowPassed[currNode][to]);
               if(to == eNode)
               {
                  return currentPathC[eNode];
               }
               q.push(to);
            }
         }
      }
   }
   return 0;
}
int edmondsKarp(int sNode, int eNode)
{
   int maxFlow = 0;
   while(true)
   {
      int flow = bfs(sNode, eNode);
      if (flow == 0)
      {
         break;
      }
      maxFlow += flow;
      int currNode = eNode;
      while(currNode != sNode)
      {
         int prevNode = parList[currNode];
         flowPassed[prevNode][currNode] += flow;
         flowPassed[currNode][prevNode] -= flow;
         currNode = prevNode;
      }
   }
return maxFlow;
}
int main()
{
   int nodCount, edCount;
   cout<<"enter the number of nodes and edges\n";
   cin>>nodCount>>edCount;
   int source, sink;
   cout<<"enter the source and sink\n";
   cin>>source>>sink;
   for(int ed = 0; ed < edCount; ed++)
   {
      cout<<"enter the start and end vertex along with capacity\n";
      int from, to, cap;
      cin>>from>>to>>cap;
      c[from][to] = cap;
      g[from].push_back(to);
      g[to].push_back(from);
   }
   int maxFlow = edmondsKarp(source, sink);
   cout<<endl<<endl<<"Max Flow is:"<<maxFlow<<endl;
}
enter the number of nodes and edges
6
7
enter the source and sink
0
4
enter the start and end vertex along with capacity
0
1
14
enter the start and end vertex along with capacity
2
4
10
enter the start and end vertex along with capacity
6
7
9
enter the start and end vertex along with capacity
5
2
10
enter the start and end vertex along with capacity
1
4
12
enter the start and end vertex along with capacity
2
0
15
enter the start and end vertex along with capacity
5
3
15
Max Flow is:12
PyQt5 - How to get visible column in the model of combo box - GeeksforGeeks

22 Apr, 2020
In this article we will see how we can get the visible column of combo box. Column model is used to set the column which will be visible to the user, model column property holds the column in the model that is visible. In order to set this we use setModelColumn method. In order to get the model column we use modelColumn method.
Syntax : combo_box.modelColumn()
Argument : It takes no argument
Return : It returns integer
Below is the implementation –
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 150, 30)          # setting visible model column        self.combo_box.setModelColumn(0)          # geek list        geek_list = ["Sayian", "Super Saiyan", "Super Sayian 2", "Super Sayian B"]          # making it editable        self.combo_box.setEditable(True)          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # getting model column        model_column = self.combo_box.modelColumn()          # creating label to show model        label = QLabel("Model Column = " + str(model_column), self)          # setting geometry to the label        label.setGeometry(200, 100, 300, 30)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
Power Function in C/C++

Power function is used to calculate the power of the given number.
The pow function find the value of a raised to the power b i.e. ab.
double pow(double a , double b)
It accepts a double integers as input and output a double integer as output. It pow() function is defined in math.h package.
If you pass an integer to the power function, the function converts it into double data type. But there's an issue with this, sometimes this conversion might store this as a lower double. For example, if we pass 3 and is converted as 2.99 then the square is 8.99940001 which converts into 8. But this is an error although it comes rarely but to remove this error 0.25 is added to it.
#include <stdio.h>
#include <math.h>
int main() {
   double x = 6.1, y = 2;
   double result = pow(x, y);
   printf("%f raised to the power of %f is %f \n" ,x,y, result );
   // Taking integers
   int a = 5 , b = 2;
   int square = pow(a,b);
   printf("%d raised to the power of %d is %d \n", a,b, square );
   return 0;
}
6.100000 raised to the power of 2.000000 is 37.210000
5 raised to the power of 2 is 25
Gradle - Build a Groovy Project

This chapter explains how to compile and execute a Groovy project using build.gradle file.
The Groovy plug-in for Gradle extends the Java plug-in and provides tasks for Groovy programs. You can use the following line for applying groovy plugin.
apply plugin: 'groovy'

Copy the following code into build.gradle file. The complete build script file is as follows −
apply plugin: 'groovy'

repositories {
   mavenCentral()
}

dependencies {
   compile 'org.codehaus.groovy:groovy-all:2.4.5'
   testCompile 'junit:junit:4.12'
}
You can use the following command to execute the build script −
gradle build

The Groovy plugin assumes a certain setup of your Groovy project.
src/main/groovy contains the Groovy source code
src/test/groovy contains the Groovy tests
src/main/java contains the Java source code
src/test/java contains the Java tests
Check the respective directory where build.gradle file places for build folder.
 Print
 Add Notes
 Bookmark this page
Connecting Apache Hive To Microsoft Power BI | by Rahul Pathak | Towards Data Science

In this story of our blog post, we are mentioning the steps we took to perform the required connection. The Hive database was based on Cloudera & the Power BI Desktop was installed on Windows. The connection can also occur with other BI tools such as Tableau & etc. As Hive can be integrated with many BI tools but the process can be challenging. Let's look forward to taking the required steps for the connection.
Initially, we need to download the ODBC drivers from the Cloudera community. There are two versions one is the 64 bit and the other is 32 bit version. It depends on the version of your PC/Laptop you are using. You may check the version of your PC by clicking the Windows button and the Pause/Break button. A Panel opens up showing the technical characteristics of your system. Then you may go ahead and install the Hive ODBC driver depending on your system. Also, the links for Power BI desktop download are given below!
Power BI Desktop Download link
HIVE ODBC DRIVER DOWNLOAD LINK
Here, we started the Hive Thrift server by using the command
hive --service hiveserver2
Type ifconfig to get the inet address that would be your host for your connection.
ifconfig
First Press Windows + R simultaneously and type in odbcad32. A window would show up.
In the User DSN tab click on the Add button
Click on Cloudera ODBC Driver for Apache Hive and click Finish
A New Window would open up
Type in your Desired Data Source Name (DSN). In this case its Hive_Connection.Description is optionalChoose Hive Server 2 as your Server TypeType in your Host Address which you obtained from the terminal in Cloudera using ifconfigPort is 10000The Database section is optionalChoose the mechanism as usernameThe username for this connection is ClouderaChoose SASL in Thrift TransportClick on TestCheck whether the test is successful. After successful completion click OK
Type in your Desired Data Source Name (DSN). In this case its Hive_Connection.
Description is optional
Choose Hive Server 2 as your Server Type
Type in your Host Address which you obtained from the terminal in Cloudera using ifconfig
Port is 10000
The Database section is optional
Choose the mechanism as username
The username for this connection is Cloudera
Choose SASL in Thrift Transport
Click on Test
Check whether the test is successful. After successful completion click OK
Click on Get Data =>more
In the search bar type ODBC and click connect
Choose Cloudera Hive DSN and click OK
The tables from your Hive Database will be visible in your Navigator column of Power BI
Once connected we may visualize the data imported from the hive table to the Power BI.
Thank you for reading this throughout. I hope we are able to help you connect these tools. Happy Learning 🤗.
React Memo

Using memo will cause React to skip rendering a component if its props have not changed.
This can improve performance.
This section uses React Hooks. See the React Hooks section for more information on Hooks.
In this example, the Todos component re-renders even when the todos have not changed.
index.js:
import { useState } from "react";
import ReactDOM from "react-dom/client";
import Todos from "./Todos";

const App = () => {
  const [count, setCount] = useState(0);
  const [todos, setTodos] = useState(["todo 1", "todo 2"]);

  const increment = () => {
    setCount((c) => c + 1);
  };

  return (
    <>
      <Todos todos={todos} />
      <hr />
      <div>
        Count: {count}
        <button onClick={increment}>+</button>
      </div>
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Todos.js:
const Todos = ({ todos }) => {
  console.log("child render");
  return (
    <>
      <h2>My Todos</h2>
      {todos.map((todo, index) => {
        return <p key={index}>{todo}</p>;
      })}
    </>
  );
};

export default Todos;


Run 
Example »

When you click the increment button, the Todos component re-renders.
If this component was complex, it could cause performance issues.
To fix this, we can use memo.
Use memoto keep the Todos component from needlessly re-rendering.
Wrap the Todos component export in memo:
index.js:
import { useState } from "react";
import ReactDOM from "react-dom/client";
import Todos from "./Todos";

const App = () => {
  const [count, setCount] = useState(0);
  const [todos, setTodos] = useState(["todo 1", "todo 2"]);

  const increment = () => {
    setCount((c) => c + 1);
  };

  return (
    <>
      <Todos todos={todos} />
      <hr />
      <div>
        Count: {count}
        <button onClick={increment}>+</button>
      </div>
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Todos.js:
import { memo } from "react";

const Todos = ({ todos }) => {
  console.log("child render");
  return (
    <>
      <h2>My Todos</h2>
      {todos.map((todo, index) => {
        return <p key={index}>{todo}</p>;
      })}
    </>
  );
};

export default memo(Todos);


Run 
Example »

Now the Todos component only re-renders when the todos that are passed to it through props are updated.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Solidity - Pure Functions

Pure functions ensure that they not read or modify the state. A function can be declared as pure. The following statements if present in the function are considered reading the state and compiler will throw warning in such cases. 
Reading state variables.
Reading state variables.
Accessing address(this).balance or <address>.balance.
Accessing address(this).balance or <address>.balance.
Accessing any of the special variable of block, tx, msg (msg.sig and msg.data can be read).
Accessing any of the special variable of block, tx, msg (msg.sig and msg.data can be read).
Calling any function not marked pure.
Calling any function not marked pure.
Using inline assembly that contains certain opcodes.
Using inline assembly that contains certain opcodes.
Pure functions can use the revert() and require() functions to revert potential state changes if an error occurs.
See the example below using a view function.
pragma solidity ^0.5.0;

contract Test {
   function getResult() public pure returns(uint product, uint sum){
      uint a = 1; 
      uint b = 2;
      product = a * b;
      sum = a + b; 
   }
}
Run the above program using steps provided in Solidity First Application chapter.
0: uint256: product 2
1: uint256: sum 3


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
Time Series of Price Anomaly Detection with LSTM | by Susan Li | Towards Data Science

Autoencoders are an unsupervised learning technique, although they are trained using supervised learning methods. The goal is to minimize reconstruction error based on a loss function, such as the mean squared error.
In this post, we will try to detect anomalies in the Johnson & Johnson’s historical stock price time series data with an LSTM autoencoder.
The data can be downloaded from Yahoo Finance. The time period I selected was from 1985–09–04 to 2020–09–03.
The steps we will follow to detect anomalies in Johnson & Johnson stock price data using an LSTM autoencoder:
Train an LSTM autoencoder on the Johnson & Johnson’s stock price data from 1985–09–04 to 2013–09–03. We assume that there were no anomalies and they were normal.Using the LSTM autoencoder to reconstruct the error on the test data from 2013–09–04 to 2020–09–03.If the reconstruction error for the test data is above the threshold, we label the data point as an anomaly.
Train an LSTM autoencoder on the Johnson & Johnson’s stock price data from 1985–09–04 to 2013–09–03. We assume that there were no anomalies and they were normal.
Using the LSTM autoencoder to reconstruct the error on the test data from 2013–09–04 to 2020–09–03.
If the reconstruction error for the test data is above the threshold, we label the data point as an anomaly.
We will break down an LSTM autoencoder network to understand them layer-by-layer.
Train test split
Standardize the data
Create sequences
Convert input data into 3-D array combining TIME_STEPS. The shape of the array should be [samples, TIME_STEPS, features], as required for LSTM network.
We want our network to have memory of 30 days, so we set TIME_STEPS=30.
We define the reconstruction LSTM Autoencoder architecture that expects input sequences with 30 time steps and one feature and outputs a sequence with 30 time steps and one feature.
RepeatVector() repeats the inputs 30 times.
Set return_sequences=True, so the output will still be a sequence.
TimeDistributed(Dense(X_train.shape[2])) is added at the end to get the output, where X_train.shape[2] is the number of features in the input data.
plt.plot(history.history['loss'], label='Training loss')plt.plot(history.history['val_loss'], label='Validation loss')plt.legend();
model.evaluate(X_test, y_test)
Find MAE loss on the training data.
Make the max MAE loss value in the training data as the reconstruction error threshold.
If the reconstruction loss for a data point in the test set is greater than this reconstruction error threshold value then we will label this data point as an anomaly.
anomalies = test_score_df.loc[test_score_df['anomaly'] == True]anomalies.shape
As you can see, there are 22 data points in the test set that exceeded the reconstruction error threshold.
The model found that some low price anomalies in March and high price anomalies in April. As it was well documented that JNJ stock hit a 2020 low in March, but quickly reaccelerated to a high point less than a month later on bullish expectations for its coronavirus vaccine.
Jupyter notebook can be found on Github. Have a great week!
time.perf_counter() function in Python

23 Mar, 2022
The time module provides various time-related functions. We must import the time module before using perf_counter() so we can access the function without throwing any errors.The perf_counter() function always returns the float value of time in seconds. Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid. In between this we can use time.sleep() and likewise functions.Code #1: Understand the usage of the perf_counter .  
Python3
# Python program to show time by perf_counter()from time import perf_counter # integer input from user, 2 input in single linen, m = map(int, input().split()) # Start the stopwatch / countert1_start = perf_counter() for i in range(n):    t = int(input()) # user gave input n times    if t % m == 0:        print(t) # Stop the stopwatch / countert1_stop = perf_counter() print("Elapsed time:", t1_stop, t1_start)  print("Elapsed time during the whole program in seconds:",                                        t1_stop-t1_start)
Output:  
pref_counter_ns(): It always gives the integer value of time in nanoseconds. Similar to perf_counter(), but return time as nanoseconds.Code #2: Usage of the perf_counter_ns and how to implement it.  
Python3
# Python program to show time by# perf_counter_ns()from time import perf_counter_ns # integer input from user, 2 input in single linen, m = map(int, input().split()) # Start the stopwatch / countert1_start = perf_counter_ns() for i in range(n):    t = int(input()) # user gave input n times    if t % m == 0:        print(t) # Stop the stopwatch / countert1_stop = perf_counter_ns() print("Elapsed time:", t1_stop, 'ns', t1_start, 'ns') print("Elapsed time during the whole program in ns after n, m inputs:",       t1_stop-t1_start, 'ns')
Output:  
Compare both the outputs of the program as perf_counter() returns in seconds and pers_counter_ns() returns in nanoseconds.Advantages of perf_counter() : 1. perf_counter() will give you more precise value than time.clock() function . 2. From Python3.8 time.clock() function will be deleted and perf_counter will be used. 3. We can calculate float and integer both values of time in seconds and nanoseconds.  
bunnyram19
ign2ncwzil34u2ovu4yn62qdubl0y33ro9mqjcee
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2001 | Question 47

28 Jun, 2021
Consider Peterson’s algorithm for mutual exclusion between two concurrent processes i and j. The program executed by process is shown below.
   repeat   
      flag [i] = true; 
      turn = j; 
      while ( P ) do no-op; 
      Enter critical section, perform actions, then exit critical 
      section 
      flag [ i ] = false; 
      Perform other non-critical section actions. 
   until false; 
For the program to guarantee mutual exclusion, the predicate P in the while loop should be.(A) flag[j] = true and turn = i(B) flag[j] = true and turn = j(C) flag[i] = true and turn = j(D) flag[i] = true and turn = iAnswer: (B)Explanation: See question 2 of https://www.geeksforgeeks.org/operating-systems-set-2/Quiz of this Question
GATE-CS-2001
GATE-GATE-CS-2001
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Replace tuple according to Nth tuple element

15 Oct, 2019
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it’s application in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + enumerate()This task can be performed using the combination of loops and enumerate function which can help to access to the Nth element and then check and replace when the condition is satisfied.
# Python3 code to demonstrate working of# Replace tuple according to Nth tuple element# Using loops + enumerate()  # Initializing listtest_list = [('gfg', 1), ('was', 2), ('best', 3)]  # printing original listprint("The original list is : " + str(test_list))  # Initializing change recordrepl_rec = ('is', 2)  # Initializing N N = 1  # Replace tuple according to Nth tuple element# Using loops + enumerate()for key, val in enumerate(test_list):    if val[N] == repl_rec[N]:        test_list[key] = repl_rec        break  # printing resultprint("The tuple after replacement is : " + str(test_list))
The original list is : [('gfg', 1), ('was', 2), ('best', 3)]
The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]

 
Method #2 : Using list comprehensionThis is the one-liner approach to solve this particular problem. In this, we just iterate the list element and keep matching the matching Nth element of tuple and perform replacement.
# Python3 code to demonstrate working of# Replace tuple according to Nth tuple element# Using list comprehension  # Initializing listtest_list = [('gfg', 1), ('was', 2), ('best', 3)]  # printing original listprint("The original list is : " + str(test_list))  # Initializing change recordrepl_rec = ('is', 2)  # Initializing N N = 1  # Replace tuple according to Nth tuple element# Using list comprehensionres = [repl_rec if sub[N] == repl_rec[N] else sub for sub in test_list]  # printing resultprint("The tuple after replacement is : " + str(res))
The original list is : [('gfg', 1), ('was', 2), ('best', 3)]
The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between <div> and <span> Tag in HTML

16 May, 2022
Both the tags (<div> and <span>) are used to represent the part of the webpage, <div> tag is used a as block part of the webpage and <span> tag is used as a inline part of the webpage like below:  
 <div>A Computer Science Portal for Geeks <span>GeeksforGeeks</span></div>
HTML <div> tag: The div tag is known as Division tag. The div tag is used in HTML to make divisions of content on the web page like (text, images, header, footer, navigation bar, etc). Div tag has both opening(<div>) and closing (</div>) tags and it is mandatory to close the tag. As we know Div tag is a block-level tag. In this example, the div tag contains the entire width. It will be displayed div tag each time on a new line, not on the same line. 
Example:  
html
<!DOCTYPE html><html> <head>    <title>Div tag</title>         <style>        div {            color: white;            background-color: #009900;            margin: 2px;            font-size: 25px;        }    </style></head> <body>    <div> div tag </div>    <div> div tag </div>    <div> div tag </div>    <div> div tag </div></body> </html>
Output:  
HTML <span> tag: The HTML span element is a generic inline container for inline elements and content. It used to group elements for styling purposes (by using the class or id attributes). A better way to use it when no other semantic element is available. The span tag is very similar to the div tag, but div is a block-level tag and span is an inline tag.  
Example:  
html
<!DOCTYPE html><html> <head>    <title>span tag</title></head> <body>    <h2>Welcome To GFG</h2>     <!-- Inside paragraph applying span tag    with different style -->    <p><span style="background-color:lightgreen">        GeeksforGeeks</span> is A Computer Science Portal        where you can<span style="color:blue;">        Publish</span> your own <span        style="background-color:lightblue;">articles</span>         and share your knowledge with the world!!    </p></body> </html>
Output:  
Differences between <div> and <span> tag:  
 
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
 
adnanirshad158
robertschv
tejendrasrajawat
HTML-Misc
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Lightweight Transactions in Cassandra

20 Nov, 2019
In this article we will discuss Lightweight Transactions(LWT) in Cassandra which is also help to improve performance.
Sometimes insert or update operations must be unique which require a read-before-write. The read-before-write has performance implications – Use wisely! This type of problem solved by CQL Lightweight Transactions (LWT) by using an IF clause on inserts and updates.
For Example:Creating a keyspace:
CREATE KEYSPACE IF NOT EXIST keyspace1 
WITH replication = {'class': 'SimpleStrategy', 
                    'replication_factor' : 2}; 
Creating a table:
CREATE TABLE User (
U_email text,
U_password int,      
U_id UUID,
PRIMARY KEY (email)
); 
To read used the following CQL query.
Select * 
from keyspace1.User 
where U_email = ‘ashish@gmail.com’; 
Output:
[0 rows]
To insert the data into table used the following CQL Query.
Insert into keyspace1.User (U_email, U_password, U_id) 
values (‘ashish@gmail.com’, ‘password_A’, uuid()) 
if not exists; 
Let’s have a look.
Now, LWT created the row.
Select * 
from keyspace1.User 
where U_email = ‘ashish@gmail.com’; 
Output:
LWT on Existing Row:
Insert into keyspace1.User (U_email, U_password, U_id) 
values (‘ashish@gmail.com’, ‘password_XYZ’, uuid()) 
if not exists;  
Let’s have a look,
Here is the output of the above CQL query.
Select * 
from keyspace1.User 
where U_email = ‘ashish@gmail.com’; 
Output:
Lightweight Transactions(LWT) on Updating Row:CQL query for updating an existing row and now we are applying LWT on this. CQL query for updating an existing row.
UPDATE keyspace1.User SET U_password = 'password_XYZ' 
WHERE U_email = 'ashish@gmail.com'
IF U_password = 'password_A' ; 
Operators can be used for UPDATE command:
=, <,, >=, != and IN 
Let’s have a look,
Apache
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
Difference between OLAP and OLTP in DBMS
What is Temporary Table in SQL?
SQL | DDL, DML, TCL and DCL
Difference between Where and Having Clause in SQL
Introduction of Relational Algebra in DBMS
Relational Model in DBMS
Difference between Star Schema and Snowflake Schema
What is Cursor in SQL ?
HTML | alt attribute

05 Jan, 2022
The HTML alt attribute is used to provide an alternate tag that is used to show or display something if the primary attribute i.e., the <img> tag, fails to display the value assigned to it.Supported tags: 
area
image
input
<applet>
Attribute Values: It contains single value text which is used to specify the alternative text for supported element, if image is not displaying.
Example: Img alt attribute.  
html
<!DOCTYPE html> <html>   <head>     <title>         HTML img alt Attribute     </title> </head>   <body>     <h1>GeeksforGeeks</h1>       <h2>HTML img alt Attribute</h2>       <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png"        alt="GeeksforGeeks logo">   </body>   </html> 
Output: Before:  
After:  
Example: Area alt attribute.  
html
<!DOCTYPE html> <html>   <head>     <title>         HTML area alt Attribute     </title> </head>   <body style="text-align:center;">     <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20190227165729/area11.png"        alt="alt_attribute" width="300" height="119" class="aligncenter"        usemap="#shapemap" />       <map name="shapemap">                   <!-- area tag contained image. -->        <area shape="poly" coords="59, 31, 28, 83, 91, 83" href= "https://media.geeksforgeeks.org/wp-content/uploads/20190227165802/area2.png"        alt="Triangle">                   <area shape="circle" coords="155, 56, 26" href= "https://media.geeksforgeeks.org/wp-content/uploads/20190227165934/area3.png"        alt="Circle">                   <area shape="rect" coords="224, 30, 276, 82" href= "https://media.geeksforgeeks.org/wp-content/uploads/20190227170021/area4.png"        alt="Square">     </map> </body>   </html>
Output:  
Example: Input alt attribute.  
html
<!DOCTYPE html> <html>   <head>     <title>         HTML Input alt Attribute     </title> </head>   <body style="text-align:center;">       <h1 style="color:green;">             GeeksForGeeks         </h1>       <h2>HTML Input alt Attribute</h2>     <input id="myImage"        type="image"        src= "https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png"        alt="Submit"        width="48"        height="48"> </body>   </html>
Output:  
Supported Browsers: The browsers supported by HTML | alt attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
 
ManasChhabra2
hritikbhatnagar2182
vshylaja
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Output of C Program | Set 20

10 Jul, 2018
Predict the outputs of following C programs.
Question 1
int main(){  int x = 10;  static int y = x;    if(x == y)     printf("Equal");  else if(x > y)     printf("Greater");  else     printf("Less");    getchar();  return 0;}
Output: Compiler ErrorIn C, static variables can only be initialized using constant literals. See this GFact for details.
Question 2
#include <stdio.h>  int main(){  int i;    for (i = 1; i != 10; i += 2)  {    printf(" GeeksforGeeks ");  }    getchar();  return 0;}
Output: Infinite times GeeksforGeeks
The loop termination condition never becomes true and the loop prints GeeksforGeeks infinite times. In general, if a for or while statement uses a loop counter, then it is safer to use a relational operator (such as <) to terminate the loop than using an inequality operator (operator !=). See this for details.
Question 3
#include<stdio.h>struct st{    int x;    struct st next;};  int main(){    struct st temp;    temp.x = 10;    temp.next = temp;    printf("%d", temp.next.x);      getchar();    return 0;}
Output: Compiler ErrorA C structure cannot contain a member of its own type because if this is allowed then it becomes impossible for compiler to know size of such struct. Although a pointer of same type can be a member because pointers of all types are of same size and compiler can calculate size of struct.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Runtime Errors
Different ways to copy a string in C/C++
Output of C++ Program | Set 1
Output of Java Program | Set 3
Output of C++ programs | Set 47 (Pointers)
Output of Java Programs | Set 12
Output of Java Program | Set 7
Output of C programs | Set 59 (Loops and Control Statements)
unsigned specifier (%u) in C with Examples
Output of Java program | Set 5
GATE | GATE CS 2012 | Question 17

28 Jun, 2021
Let G be a simple undirected planar graph on 10 vertices with 15 edges. If G is a connected graph, then the number of bounded faces in any embedding of G on the plane is equal to(A) 3(B) 4(C) 5(D) 6Answer: (D)Explanation: If the graph is planar, then it must follow below Euler’s Formula for planar graphs
v - e + f = 2
v is number of vertices
e is number of edges
f is number of faces including bounded and unbounded

10 - 15 + f = 2
f = 7
There is always one unbounded face, so the number of bounded faces =  6
Quiz of this Question
GATE-CS-2012
GATE-GATE CS 2012
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
Python | Numpy matrix.diagonal()

12 Apr, 2019
With the help of Numpy matrix.diagonal() method, we are able to find a diagonal element from a given matrix and gives output as one dimensional matrix.
Syntax : matrix.diagonal()
Return : Return diagonal element of a matrix
Example #1 :In this example we can see that with the help of matrix.diagonal() method we are able to find the elements in a diagonal of a matrix.
# import the important module in pythonimport numpy as np         # make matrix with numpygfg = np.matrix('[6, 2; 3, 4]')         # applying matrix.diagonal() methodgeeks = gfg.diagonal()   print(geeks)
[[6 4]]

Example #2 :
# import the important module in pythonimport numpy as np         # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]')         # applying matrix.diagonal() methodgeeks = gfg.diagonal()   print(geeks)
[[1 5 9]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstraction and Encapsulation in C++

06 Oct, 2021
Abstraction: In OOPs, Abstraction is the method of getting information where the information needed will be taken in such a simplest way that solely the required components are extracted, and also the ones that are considered less significant are unnoticed. The concept of abstraction only shows necessary information to the users. It reduces the complexity of the program by hiding the implementation complexities of programs. Example of Abstraction: 
CPP
#include <iostream>using namespace std; class Summation {private:    // private variables    int a, b, c;public:    void sum(int x, int y)    {        a = x;        b = y;        c = a + b;        cout<<"Sum of the two number is : "<<c<<endl;    }};int main(){    Summation s;    s.sum(5, 4);    return 0;}
Output:  
Sum of the two number is: 9 
In the this example, we can see that abstraction has achieved by using class. The class ‘Summation’ holds the private members a, b and c, which are only accessible by the member functions of that class.Encapsulation: Encapsulation is the process or method to contain the information. Encapsulation is a method to hide the data in a single entity or unit along with a method to protect information from outside world. This method encapsulates the data and function together inside a class which also results in data abstraction. Example of Encapsulation: 
CPP
#include <iostream>using namespace std; class EncapsulationExample {private:    // we declare a as private to hide it from outside    int a; public:    // set() function to set the value of  a    void set(int x)    {        a = x;    }     // get() function to return the value of a    int get()    {        return a;    }}; // main functionint main(){    EncapsulationExample e1;     e1.set(10);     cout<<e1.get();    return 0;}
Output:  
10
In the this program, the variable a is made private so that this variable can be accessed and manipulated only by using the methods get() and set() that are present within the class. Therefore we can say that, the variable a and the methods set() as well as get() have binded together that is nothing but encapsulation.Difference between Abstraction and Encapsulation: 
 
tanya_dixit17
cpp-class
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Groovy - getTime()

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
public long getTime()

None.
The number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      Date olddate = new Date("05/11/2015");
      Date newdate = new Date("05/11/2015"); 
      Date latestdate = new Date(); 
		
      System.out.println(olddate.getTime()); 
      System.out.println(newdate.getTime()); 
      System.out.println(latestdate.getTime()); 
   } 
}	  
When we run the above program, we will get the following result −
1431288000000 
1431288000000 
1449769878348


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
How to set background color in jQuery?

To set the background color using jQuery, use the jQuery css() property. We will set background color on mouse hover with the jQuery on() method.
You can try to run the following color to set background color in jQuery.
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("body").on({
        mouseenter: function(){
            $(this).css("background-color", "gray");
        },  
    });    
});
</script>
</head>
<body>
<p>Move the mouse pointer on the page to change the background color.</p>
</body>
</html>
col-lg-* Bootstrap class

The input-lg is used to set the width of forms in Bootstrap.
You can try to run the following code to implement col-lg Bootstrap class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <form role = "form">
         <div class = "row">
            <div class = "col-lg-2">
               <input type = "text" class = "form-control" placeholder = ".col-lg-2">
            </div>
            <div class = "col-lg-3">
               <input type = "text" class = "form-control" placeholder = ".col-lg-3">
            </div>
            <div class = "col-lg-4">
               <input type = "text" class = "form-control" placeholder = ".col-lg-4">
            </div>
         </div>
      </form>
   </body>
</html>
Retrieving Elements from Collection in C#

Let us see an example of a list collection.
We have set the elements −
List<int> list = new List<int>();
list.Add(20);
list.Add(40);
list.Add(60);
list.Add(80);
Now let’s say we need to retrieve the first element from the list. For that, set the index like this −
int a = list[0];
The following is an example showing how to retrieve elements from a list collection −
using System;
using System.Collections.Generic;

class Demo {

   static void Main(String[] args) {
      List<int> list = new List<int>();
      list.Add(20);
      list.Add(40);
      list.Add(60);
      list.Add(80);

      foreach (int val in list) {
         Console.WriteLine(val);
      }

      int a = list[0];
      Console.WriteLine("First element: "+a);
   }
}
Adding unique constraint to ALTER TABLE in MySQL

Let us first create a table −
mysql> create table DemoTable1811
     (
     FirstName varchar(20),
     LastName varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)
Here is the query to add index
mysql> alter table DemoTable1811 ADD UNIQUE unique_index_first_last_name(FirstName, LastName);
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0
Insert some records in the table using insert command −
mysql> insert into DemoTable1811 values('John','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1811 values('John','Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1811 values('Adam','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1811 values('John','Doe');
ERROR 1062 (23000): Duplicate entry 'John-Doe' for key 'unique_index_first_last_name'
Display all records from the table using select statement −
mysql> select * from DemoTable1811;
This will produce the following output −
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Adam      |    Smith |
| John      |      Doe |
| John      |    Smith |
+-----------+----------+
3 rows in set (0.00 sec)