code-rag-bench/online-tutorials huggingface dataset:
How to count the number of occurrences of a particular text inside a table in a page in Selenium with python?

We can count the number of occurrences of a particular text inside a table
in Selenium. First of all we need to locate the element by xpath. In xpath, we have
a particular text() function that identifies elements based on the visible text on the
screen.
Then we have to use find_elements method to get the list of matching elements
having the text we are looking for on the page. Finally we need to get the size of
that list with the help of the len function of the list.
This will give the number of occurrences of a particular text inside a table.
driver.find_elements_by_xpath("//td[text()='Tutorialspoint']")
Coding Implementation to get the count of occurrences of a text inside a table.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm")
#to refresh the browser
driver.refresh()
# identifying the text keyword inside the table
dta = driver.find_elements_by_xpath("//td[text()='keyword']")
# len method is used to get the count of occurrences
print(len(dta))
#to close the browser
driver.close()
LISP - Dolist Construct

The dolist construct allows iteration through each element of a list.
For example, Create a new source code file named main.lisp and type the following code in it −
(dolist (n '(1 2 3 4 5 6 7 8 9))
   (format t "~% Number: ~d Square: ~d" n (* n n))
)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
Number: 1 Square: 1
Number: 2 Square: 4
Number: 3 Square: 9
Number: 4 Square: 16
Number: 5 Square: 25
Number: 6 Square: 36
Number: 7 Square: 49
Number: 8 Square: 64
Number: 9 Square: 81


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
How to install pandas using miniconda?

The popular approach of installing pandas is using Anaconda distributions. Anaconda provides pre-installed libraries and applications by default, and we no need to install any packages externally.
However, this approach means we are installing two many packages by default, Due to this anaconda costs more system storage.
If you want to have more control over package installation, or if you want to save your system storage then using Miniconda may be a better solution than using anaconda.
One can choose Miniconda if that −
Do not have any problem installing each of the packages individually, if they want to work on a particular package.
Do not have any problem installing each of the packages individually, if they want to work on a particular package.
Don't have time or disk space to install over 1,500 packages at once.
Don't have time or disk space to install over 1,500 packages at once.
Miniconda allows you to create a minimal self-contained Python installation, and then we need to use the Conda command to install additional packages. Conda is a package manager for miniconda as well as an anaconda. While using miniconda we have to use the conda command explicitly for installing any packages.
We can download the miniconda installer from this website −
https://docs.conda.io/en/latest/miniconda.html
From this above link, we can get different miniconda installers(windows, Linux, and macOS installers) for every machine’s requirements. Miniconda installers contain the conda package manager and Python.
Once we are done installing miniconda successfully, then we can use the conda command to install any other packages based on our needs.
conda install pandas
By using this above command we can install the pandas package, and This command will install pandas latest version by default. If you want to install any particular version of the pandas package, we can give the below command.
conda install pandas==1.2.3
This will install the pandas 1.2.3 version.
Get first index values in tuple of strings in Python

We have a tuple of strings. We are required to create a list of elements which are the first character of these strings in the tuple.
We design a for loop to take each element and extract the first character by applying the index condition as 0. Then the list function converts it to a list.
 Live Demo
tupA = ('Mon', 'Tue', 'Wed', 'Fri')
# Given tuple
print("Given list : \n" ,tupA)
# using index with for loop
res = list(sub[0] for sub in tupA)
# printing result
print("First index charaters:\n",res)
Running the above code gives us the following result −
Given list :
('Mon', 'Tue', 'Wed', 'Fri')
First index charaters:
['M', 'T', 'W', 'F']
We apply zip to the tuple and then apply next to get the first character of each element.
tupA = ('Mon', 'Tue', 'Wed', 'Fri')
# Given tuple
print("Given list : \n" ,tupA)
# using next and zip
res = list(next(zip(*tupA)))
# printing result
print("First index charaters:\n",res)
Running the above code gives us the following result −
Given list :
('Mon', 'Tue', 'Wed', 'Fri')
First index charaters:
['M', 'T', 'W', 'F']
Tryit Editor v3.7

CSS 2D Transforms
Tryit: The scaleX() method
Function Overriding

When the base class and derived class have member functions with exactly the same name, same return-type, and same arguments list, then it is said to be function overriding.
The following example shows how function overriding is done in C++, which is an objectoriented programming language −
#include <iostream> 
using namespace std;  

class A {  
   public: 
   void display() {   
      cout<<"Base class"; 
   } 
}; 

class B:public A {  
   public: 
   void display() {   
      cout<<"Derived Class"; 
   } 
}; 

int main() {  
   B obj; 
   obj.display(); 
   return 0;  
}
It will produce the following output
Derived Class 

The following example shows how to perform function overriding in Python, which is a functional programming language −
class A(object): 
   def disp(self): 
      print "Base Class"  
class B(A): 
   def disp(self): 
      print "Derived Class"  
x = A() 
y = B()  
x.disp() 
y.disp() 
It will produce the following output −
Base Class 
Derived Class 


    32 Lectures 
     3.5 hours 

 Pavan Lalwani

    11 Lectures 
     1 hours 

 Prof. Paul Cline, Ed.D

    72 Lectures 
     10.5 hours 

 Arun Ammasai

    51 Lectures 
     2 hours 

 Skillbakerystudios

    43 Lectures 
     4 hours 

 Mohammad Nauman

    8 Lectures 
     1 hours 

 Santharam Sivalenka
 Print
 Add Notes
 Bookmark this page
Program to evaluate one mathematical expression without built-in functions in python

Suppose we have a string that represents a mathematical expression with (+, -, *, /) Here / is representing integer division, we have to evaluate and return the result without using any built-in function.
So, if the input is like s = "2+3*5/7", then the output will be 4, as 2 + ((3 * 5) / 7) = 4
To solve this, we will follow these steps −
s := reverse the given string
Define a function get_value().
sign := 1
if s is not empty and last element of s is same as "-", thendelete last element from ssign := -1
delete last element from s
sign := -1
value := 0
while s is not empty and last element of s is a digit, dovalue := value * 10value := value + numeric value of last element from s, and delete last element of s
value := value * 10
value := value + numeric value of last element from s, and delete last element of s
return sign * value
Define a function get_term()
term := get_value()
while s is not empty and last element of s is either * or /, doop := last element of s and delete last element from svalue := get_value()if op is same as "*", thenterm := term * valueotherwise,term := the floor of (1.0 * term / value)
op := last element of s and delete last element from s
value := get_value()
if op is same as "*", thenterm := term * value
term := term * value
otherwise,term := the floor of (1.0 * term / value)
term := the floor of (1.0 * term / value)
return term
From the main method do the following:
ans := get_term()
while s is not empty, doop := last element of s, and delete it from sterm := get_term()if op is same as "+", thenans := ans + termotherwise,ans := ans - term
op := last element of s, and delete it from s
term := get_term()
if op is same as "+", thenans := ans + term
ans := ans + term
otherwise,ans := ans - term
ans := ans - term
return ans
Let us see the following implementation to get better understanding −
Live Demo
from math import floor, trunc
class Solution:
   def solve(self, s):
      s = list(s[::-1])

      def get_value():
         sign = 1
         if s and s[-1] == "-":
            s.pop()
            sign = -1
         value = 0
         while s and s[-1].isdigit():
            value *= 10
            value += int(s.pop())
         return sign * value

      def get_term():
         term = get_value()
         while s and s[-1] in "*/":
            op = s.pop()
            value = get_value()
            if op == "*":
               term *= value
            else:
               term = floor(1.0 * term / value)
         return term

      ans = get_term()
      while s:
         op, term = s.pop(), get_term()
         if op == "+":
            ans += term
         else:
            ans -= term
      return ans

ob = Solution()
s = "2+3*5/7"
print(ob.solve(s))
"2+3*5/7"
4
How to get first N characters from a MySQL column?

Use SUBSTRING() to get first N characters from a MySQL column. Let us first create a table −
mysql>create table DemoTable
(
   Information text
);
Query OK, 0 rows affected (2.63 sec)
Insert records in the table using insert command −
mysql>insert into DemoTable values('MySQL is a structured query language');
Query OK, 1 row affected (0.13 sec)
Following is the query to display all records from the table using select statement −
mysql>select *from DemoTable;
This will produce the following output −
+--------------------------------------+
| Information                          |
+--------------------------------------+
| MySQL is a structured query language |
+--------------------------------------+
1 row in set (0.00 sec)
Here is the query to get first N characters from the column. In this case, we are selecting the first 10 characters −
mysql>select substring(Information,1,10) from DemoTable;
This will produce the following output −
+-----------------------------+
| substring(Information,1,10) |
+-----------------------------+
| MySQL is a                  |
+-----------------------------+
1 row in set (0.00 sec)
Python - Tkinter tkMessageBox

The tkMessageBox module is used to display message boxes in your applications. This module provides a number of functions that you can use to display an appropriate message.
Some of these functions are showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, and askretryignore.
Here is the simple syntax to create this widget −
tkMessageBox.FunctionName(title, message [, options])

FunctionName − This is the name of the appropriate message box function.
FunctionName − This is the name of the appropriate message box function.
title − This is the text to be displayed in the title bar of a message box.
title − This is the text to be displayed in the title bar of a message box.
message − This is the text to be displayed as a message.
message − This is the text to be displayed as a message.
options − options are alternative choices that you may use to tailor a standard message box. Some of the options that you can use are default and parent. The default option is used to specify the default button, such as ABORT, RETRY, or IGNORE in the message box. The parent option is used to specify the window on top of which the message box is to be displayed.
options − options are alternative choices that you may use to tailor a standard message box. Some of the options that you can use are default and parent. The default option is used to specify the default button, such as ABORT, RETRY, or IGNORE in the message box. The parent option is used to specify the window on top of which the message box is to be displayed.
You could use one of the following functions with dialogue box −
showinfo()
showwarning()
showerror ()
askquestion()
askokcancel()
askyesno ()
askretrycancel ()
Try the following example yourself −
import Tkinter
import tkMessageBox

top = Tkinter.Tk()
def hello():
   tkMessageBox.showinfo("Say Hello", "Hello World")

B1 = Tkinter.Button(top, text = "Say Hello", command = hello)
B1.pack()

top.mainloop()
When the above code is  executed, it produces the following result −

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Shift command in Linux with examples

21 Apr, 2020
Shift is a builtin command in bash which after getting executed, shifts/move the command line arguments to one position left. The first argument is lost after using shift command. This command takes only one integer as an argument. This command is useful when you want to get rid of the command line arguments which are not needed after parsing them.
Syntax:
shift n

Here, n is the number of positions by which you want to shift command-line arguments to the left if you do not specify, the default value of n is assumed to be 1 i.e shift works the same as shift 1.
Example: Let’s create a shell script file named as sampleshift.sh as follows. The total number of command-line arguments is represented by $#. Use the following command to create the desired shell script file
vi sampleshift.sh

Now paste the following code:
#!/bin/bash

# total number of command-line arguments
echo "Total arguments passed are: $#"

# $* is used to show the command line arguments
echo "The arguments are: $*"

echo "The First Argument is: $1"
shift 2

echo "The First Argument After Shift 2 is: $1"
shift

echo "The First Argument After Shift is: $1"

Now to save the file press ESC and then type “:x” without quotes and hit Enter. Now to execute the file, use the following command on Linux terminal
sh sampleshift.sh
But here we have to pass command-line arguments so we can use the following command
sh sampleshift.sh G1 G2 G3 G4
Here, we are passing 4 command-line arguments named G1, G2, G3, and G4. Below is the screenshot of the output of using shift command:
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C library macro - va_end()

The C library macro void va_end(va_list ap) allows a function with variable arguments which used the va_start macro to return. If va_end is not called before returning from the function, the result is undefined.
Following is the declaration for va_end() macro.
void va_end(va_list ap)
ap − This is the va_list object previously initialized by va_start in the same function.
ap − This is the va_list object previously initialized by va_start in the same function.
This macro does not return any value.
The following example shows the usage of va_end() macro.
#include <stdarg.h>
#include <stdio.h>

int mul(int, ...);

int main () {
   printf("15 * 12 = %d\n",  mul(2, 15, 12) );
   
   return 0;
}

int mul(int num_args, ...) {
   int val = 1;
   va_list ap;
   int i;

   va_start(ap, num_args);
   for(i = 0; i < num_args; i++) {
      val *= va_arg(ap, int);
   }
   va_end(ap);
 
   return val;
}
Let us compile and run the above program to produce the following result −
15 * 12 =  180


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Find maximum in stack in O(1) without using additional stack in C++

Suppose we want to make a stack that can store the maximum element in the stack. And we can get it in O(1) time. The constraint is that, it should not use any additional space, so O(1) extra space.
We can make one user-defined stack, that will store the max value, when one operation is performed, like pop or peek, then the max will be returned. For peek operation, return the maximum of stack top and the max element, for pop operation, when the top element is larger, then print it and update max as 2*max – top_element. otherwise return top_element. For push operation update the max element as x(data to be inserted), 2*x – max.
 Live Demo
#include <iostream>
#include <stack>
using namespace std;
class CustomStack {
   stack<int> stk;
   int stack_max;
   public:
   void getMax() {
      if (stk.empty())
         cout << "Stack is empty"<<endl;
      else
         cout << "Maximum Element in the stack is: "<< stack_max <<endl;
   }
   void peek() {
      if (stk.empty()) {
         cout << "Stack is empty ";
         return;
      }
      int top = stk.top(); // Top element.
      cout << "Top Most Element is: "<<endl;
      (top > stack_max) ? cout << stack_max : cout << top;
   }
   void pop() {
      if (stk.empty()) {
         cout << "Stack is empty"<<endl;
         return;
      }
      cout << "Top Most Element Removed: ";
      int top = stk.top();
      stk.pop();
      if (top > stack_max) {
         cout << stack_max <<endl;
         stack_max = 2 * stack_max - top;
      } else
         cout << top <<endl;
   }
   void push(int element) {
      if (stk.empty()) {
         stack_max = element;
         stk.push(element);
         cout << "Element Inserted: " << element <<endl;
         return;
      }
      if (element > stack_max) {
         stk.push(2 * element - stack_max);
         stack_max = element;
      } else
      stk.push(element);
      cout << "Element Inserted: " << element <<endl;
   }
};
int main() {
   CustomStack stk;
   stk.push(4);
   stk.push(6);
   stk.getMax();
   stk.push(8);
   stk.push(20);
   stk.getMax();
   stk.pop();
   stk.getMax();
   stk.pop();
   stk.peek();
}
Element Inserted: 4
Element Inserted: 6
Maximum Element in the stack is: 6
Element Inserted: 8
Element Inserted: 20
Maximum Element in the stack is: 20
Top Most Element Removed: 20
Maximum Element in the stack is: 8
Top Most Element Removed: 8
Top Most Element is:
6
Using Github Pages for creating global APIs | by Gaurav Ghati | Towards Data Science

So, I accidentally figured out that we can return JSON responses instead of the standard HTML when we access any GitHub Pages site. So, I thought instead of creating a static website why not do some dev fun ;) and create a REST API for the data that I need.
For example, if you type this on terminal
curl https://gauravghati.github.io/apis/home.json
Gives the following result:
{    "name": "Gaurav Ghati",    "phone": "+91 9067365762",    "mail": "gauravghati225@gmail.com",    "bio": "MY BIO",    "fun": "FUN STATEMENT",    "github": "https://github.com/gauravghati/",    "twitter": "https://twitter.com/GauravGhati/",    "linkedin": "http://linkedin.com/in/gauravghati/",    "aboutme": {        "para1": "This is Paragraph 1",        "para2": "This is Paragraph 2"    },    "volunteer": {        "tfi": {            "heading": "Teach For India",            "description": "description of TFI"        },        "pisb": {            "heading": "PICT IEEE Student Branch",            "description": "description of PISB"        }    }}
I used this JSON API for my website, now each time when the website loads it makes a request to the Github pages link and fetch data from that URL and displays the fetched data on the website!
Now, whenever I want to edit any data on my website, I just have to change the JSON files and push them to my Github pages repo, the changes will automatically get displayed on the main website.
You can view the code of the website, here. It’s in Django.
By using Github, we can host our JSON files data there, because it is a static site, the only limitation is that it only supports GET requests.
Create a new repository on Github with the repository name “github_username.github.io.” after this your new GitHub pages repository is ready. The URL for this repository will be
https://github_username.github.io/
Clone the above repository, or if you already have JSON files saved locally, run git init in that folder and add the above remote repository and then commit and push your .json file. After you push your files there, you can access your JSON response on hitting the URL:
https://github_username.github.io/json_file.json
The data which we get after hitting the URL is in the form of JSON objects. which we can directly send to the frontend while rendering HTML pages.
When your backend is in python i.e. in Django or Flask, you can access the JSON file’s data as shown below:
import urllib.request, jsongithub_link = "https://github_username.github.io/json_file.json"with urllib.request.urlopen(github_link) as url:    json_data = json.loads(url.read().decode())print(json_data)
this piece of code will print all your JSON data as the output.
And if you want data in JavaScript using JQuery, you can access the JSON file’s data as shown below:
let github_link = ‘https://github_username.github.io/jsonfile.json';$.getJSON(github_link, function(data) {     //data is the JSON string     console.log(data);});
So, this is how you can use Github pages for creating global APIs.
Thanks for reading, You can connect with me on LinkedIn, Twitter or my portfolio
C library function - fopen()

The C library function FILE *fopen(const char *filename, const char *mode) opens the filename pointed to, by filename using the given mode.
Following is the declaration for fopen() function.
FILE *fopen(const char *filename, const char *mode)
filename − This is the C string containing the name of the file to be opened.
filename − This is the C string containing the name of the file to be opened.
mode − This is the C string containing a file access mode. It includes −
mode − This is the C string containing a file access mode. It includes −
"r"
Opens a file for reading. The file must exist.
"w"
Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.
"a"
Appends to a file. Writing operations, append data at the end of the file. The file is created if it does not exist.
"r+"
Opens a file to update both reading and writing. The file must exist.
"w+"
Creates an empty file for both reading and writing.
"a+"
Opens a file for reading and appending.
This function returns a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error.
The following example shows the usage of fopen() function.
#include <stdio.h>
#include <stdlib.h>

int main () {
   FILE * fp;

   fp = fopen ("file.txt", "w+");
   fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012);
   
   fclose(fp);
   
   return(0);
}
Let us compile and run the above program that will create a file file.txt with the following content −
We are in 2012

Now let us see the content of the above file using the following program −
#include <stdio.h>

int main () {
   FILE *fp;
   int c;
  
   fp = fopen("file.txt","r");
   while(1) {
      c = fgetc(fp);
      if( feof(fp) ) { 
         break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   
   return(0);
}
Let us compile and run the above program to produce the following result −
We are in 2012


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How can we encode a JSON object in Java?

A JSONObject is a subclass of java.util.HashMap where no order is provided. We can also use the strict ordering of elements as well with the help of the JSONValue.toJSONString(map) method i.e. by the implementation of java.util.LinkedHashMap.
We can encode a JSON object in the below two examples.
import java.util.*;
import org.json.simple.JSONObject;
public class JSONEncodingTest {
   public static void main(String[] args) {
      Map<Object, Object> dataMap = new HashMap<Object, Object>();
      dataMap.put("Name", "Adithya");
      dataMap.put("Age", new Integer(25));
      dataMap.put("Salary", new Double(25000.00));
      dataMap.put("Employee Id", new Integer(115));
      dataMap.put("Company", "TutorialsPoint");
      JSONObject jsonObj = new JSONObject(dataMap);
      System.out.print("Encoding a JSON object: ");
      System.out.print(jsonObj);
   }
}
Encoding a JSON object: {"Salary":25000.0,"Employee id":115,"Company":"TutorialsPoint","Age":25,"Name":"Adithya"}
import java.io.*;
import org.json.simple.*;
public class JSONEncodingTest1 {
   public static void main(String[] args) throws IOException {
      JSONObject obj = new JSONObject();
      obj.put("Name", "Jai");
      obj.put("Mobile_Number", new Integer(995998480));
      obj.put("Bank_Balance", new Double(50000.00));
      obj.put("Is_A_SelfEmployee", new Boolean(false));
      StringWriter out = new StringWriter();
      obj.writeJSONString(out);
      String jsonText = out.toString();
      System.out.print(jsonText);
   }
}
{"Is_A_SelfEmployee":false,"Bank_Balance":50000.0,"Mobile_Number":995998480,"Name":"Jai"}
Perl chdir Function

This function changes the current working directory to EXPR, or to the user's home directory if none is specified. This function call is equivalent to Unix command cd EXPR.
Following is the simple syntax for this function −
chdir EXPR

chdir

This function returns 0 on failure and 1 on success.
Following is the example code showing its basic usage, assume you are working in /user/home/tutorialspoint directory −
#!/usr/bin/perl

chdir "/usr/home";

# Now you are in /usr/home dir.
chdir;

# Now you are in home directory /user/home/tutorialspoint

    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Matplotlib - Multiplots

In this chapter, we will learn how to create multiple subplots on same canvas.
The subplot() function returns the axes object at a given grid position. The Call signature of this function is −
plt.subplot(subplot(nrows, ncols, index)
In the current figure, the function creates and returns an Axes object, at position index of a grid of nrows by ncolsaxes. Indexes go from 1 to nrows * ncols, incrementing in row-major order.Ifnrows, ncols and index are all less than 10. The indexes can also be given as single, concatenated, threedigitnumber.
For example, subplot(2, 3, 3) and subplot(233) both create an Axes at the top right corner of the current figure, occupying half of the figure height and a third of the figure width.
Creating a subplot will delete any pre-existing subplot that overlaps with it beyond sharing a boundary.
import matplotlib.pyplot as plt
# plot a line, implicitly creating a subplot(111)
plt.plot([1,2,3])
# now create a subplot which represents the top plot of a grid with 2 rows and 1 column.
#Since this subplot will overlap the first, the plot (and its axes) previously 
created, will be removed
plt.subplot(211)
plt.plot(range(12))
plt.subplot(212, facecolor='y') # creates 2nd subplot with yellow background
plt.plot(range(12))
The above line of code generates the following output −
The add_subplot() function of the figure class will not overwrite the existing plot −
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot([1,2,3])
ax2 = fig.add_subplot(221, facecolor='y')
ax2.plot([1,2,3])
When the above line of code is executed, it generates the following output −
You can add an insert plot in the same figure by adding another axes object in the same figure canvas.
import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig=plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3]) # inset axes
y = np.sin(x)
axes1.plot(x, y, 'b')
axes2.plot(x,np.cos(x),'r')
axes1.set_title('sine')
axes2.set_title("cosine")
plt.show()
Upon execution of the above line of code, the following output is generated −

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to draw a circle with arc() in HTML5?

The arc() method is used to create a circle in HTML5 with the canvas element. For a circle with arc() method, use the start angle as 0 and end angle to 2*Math.PI.
Here are the parameter values of the arc() method −
You can try to run the following code to draw a circle with arc() method in HTML5 −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Canvas</title>
   <head>
   <body>
      <canvas id="newCanvas" width="300" height="150" style="border:1px solid #000000;"></canvas>
      <script>
         var c = document.getElementById("newCanvas");
         var ctxt = c.getContext("2d");
         ctxt.beginPath();
         ctxt.arc(100,75,50,0,2*Math.PI);
         ctxt.stroke();
      </script>
   </body>
</html>
How can I define duplicate items in a Python tuple?

You can directly enter duplicate items in a Python tuple as it doesn't behave like a set(which takes only unique items). 
myTpl = (1, 2, 2, 2, 3, 5, 5, 4)
You can also use operators on tuples to compose large tuples.For Example
myTpl = (1,) * 5
print(myTpl)
This will give the output
(1,1,1,1,1)
You can also join tuples using + operator. 
myTpl = (1,) * 3 + (2,) * 2
print(myTpl)
This will give the output
(1,1,1,2,2)
Search an element in the given singly Linked List using C++

Given a singly linked list, the task is to search a particular element in the linked list. If the element is found, then print “present” otherwise “Not present”. For example,
Input-1 −
1→ 2→ 3→ 4→ 5→ 6
Searching for ‘7’
Output −
Not Present
Explanation − In the given singly linked list the element ‘7’ is not present, hence we will return the output as “Not Present”.
Input-2 −
1→ 2→ 3→ 4→ 5
Searching for ‘2’
Output −
Present
Explanation − Since in the given Singly linked list the element ‘2’ is present thus we will return the output as “Present”.
There are two approaches to search a particular element in the given singly linked list; we have to check recursively whether one element is present in the linked list or not.
If the linked list is empty, we will return false otherwise if the current node having the data value is equal to the input element then we will return true. In the other approach, we check the element iteratively if it equals the current head pointer or not and return true or false accordingly.
Take Input and Initialize a singly linked list by inserting nodes in it.
Take Input and Initialize a singly linked list by inserting nodes in it.
A Boolean recursive function searhRecursive(node*head, int element) takes the head pointer of the linked list and the key element as a parameter.
A Boolean recursive function searhRecursive(node*head, int element) takes the head pointer of the linked list and the key element as a parameter.
Initially if the head is NULL or if the linked list is empty then return false.
Initially if the head is NULL or if the linked list is empty then return false.
If the element to be searched is equal to the current head of the linked list then return true.
If the element to be searched is equal to the current head of the linked list then return true.
 Live Demo
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
class node{
public:
   int data;
   node*next;
   node(int d){
      data=d;
      node*next= NULL;
   }
};
void insertAt(node*&head, int data){
   node*n= new node(data);
   n->next= head;
   head= n;
}
bool searchRecursive(node*head,int key){
   if(head==NULL){
      return false;
   }
   if(head->data==key){
      return true;
   }
   else{
      return searchRecursive(head->next, key);
   }
}
void printNode(node*head){
   while(head!=NULL){
      cout<<head->data<<"->";
      head=head->next;
   }
   cout<<endl;
}
int main(){
   node*head= NULL;
   insertAt(head,5);
   insertAt(head,4);
   insertAt(head,3);
   insertAt(head,2);
   insertAt(head,1);
   printNode(head);
   if(searchRecursive(head,7)){
      cout<<"present"<<endl;
   }
   else{
      cout<<"Not Present"<<endl;
   }
}
Running the above code will generate the output as,
Not Present
Since in the given linked list 1→2→3→4→5 the element ‘7’ is not present thus we return “Not Present”.
BitConverter Class in C#

The BitConverter class converts base data types to an array of bytes, and an array of bytes to base data types.
Following are the methods −
Let us see some examples −
The BitConverter.ToBoolean() method in C# returns a Boolean value converted from the byte at a specified position in a byte array.
Following is the syntax −
public static bool ToBoolean (byte[] arr, int startIndex);
Above, arr is a byte array, whereas startIndex is the index of the byte within a value.
Let us now see an example to implement the BitConverter.ToBoolean() method −
 Live Demo
using System;
public class Demo {
   public static void Main(){
      byte[] arr = { 50, 100 };
      Console.WriteLine("Array values...");
      for (int i = 0; i < arr.Length; i++) {
         Console.WriteLine("{0} ", arr[i]);
      }
      Console.WriteLine("\nConverted values...");
      for (int index = 0; index < arr.Length; index++) {
         bool res = BitConverter.ToBoolean(arr, index);
         Console.WriteLine(""+res);
      }
   }
}
This will produce the following output −
Array values...
50
100
Converted values...
True
True
The BitConverter.DoubleToInt64Bits() method in C# is used to convert the specified double-precision floating-point number to a 64-bit signed integer.
Following is the syntax −
public static long DoubleToInt64Bits (double val);
Above, val is the number to convert.
Let us now see an example to implement the BitConverter.DoubleToInt64Bits() method −
 Live Demo
using System;
public class Demo {
   public static void Main(){
      double d = 5.646587687;
      Console.Write("Value = "+d);
      long res = BitConverter.DoubleToInt64Bits(d);
      Console.Write("\n64-bit signed integer = "+res);
   }
}
This will produce the following output −
Value = 5.646587687 
64-bit signed integer = 4618043510978159912
What is the session Object in JSP?

The session object is used to track a client session between client requests.
JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across.
a one-page request or
visit to a website or
store information about that user
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows −
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the implicit session object. Since the session object is already provided to the JSP programmer, the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession().
How to detect a route change in AngularJS ? - GeeksforGeeks

30 Nov, 2019
Approach: To detect route change at any moment in AngularJS this can be achieved by using $on() method. The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/view change is done.
Syntax:
$rootScope.$on('$routeChangeSuccess', function () {
    Content...
});

Example: Here, we are displaying “route changed” in the console window whenever there is any route change. Inside the $on() method, we console route changed. Hence, In this way whenever route change occurs, it triggers $routeChangeSuccess handled by $on() event handler and then “route changed” is displayed in the console window.
Below is the implementation of the above approach:
<!DOCTYPE html><html>   <head>      <title>Angular JS Route Change</title>        <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>        <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js">      </script>   </head>        <body style = "text-align:center;">              <h1 style = "color:green;" >          GeeksForGeeks      </h1>       <div>        <p><a href = "#viewLink1">Link 1</a></p>        <p><a href = "#viewLink2">Link 2</a></p>        <div ng-app = "mainApp" ng-controller = "GFGController">        <div ng-view></div>    </div>            <script>        var mainApp = angular.module("mainApp", ['ngRoute']);        mainApp.config(['$routeProvider', function($routeProvider) {            $routeProvider                          .when('/viewLink1', {                template: "<p> This is Link 1 </p>"            })                          .when('/viewLink2', {                template: "<p> This is Link 2 </p>"            })                          .otherwise({                redirectTo: '/viewLink1'            });         }]);            mainApp.controller(                   'GFGController', function($scope, $location, $rootScope) {            $rootScope.$on('$routeChangeSuccess', function () {            console.log("route changed");            });         });      </script>   </body></html>
Output:As we change the link, the $routeChangeSuccess event gets triggered and thus display route changed in the console window.
AngularJS-Misc
Picked
AngularJS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to bundle an Angular app for production?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to Install Ulauncher in Ubuntu? - GeeksforGeeks

06 Oct, 2021
Ulauncher is a fast app launcher which allows searching app and files by pressing hotkeys. Ulauncher is written in Python with GTK+. Below are some Ulauncher app launcher features:
Fuzzy search (type in app name without worrying about spelling)
built-in themes
customizable shortcuts
Search Google, Wikiepdia, and Stack Overflow
wide range of plugins
1. add PPA for Ulauncher: Open terminal from the application menu and type this command to add the PPA:
$ sudo add-apt-repository ppa:agornostal/ulauncher
and press Enter.
2. Check for Updates: Update PPAs on your system, using the below command
$ sudo apt update
3. Install Ulauncher: Use the below command to install Ulauncher and press Y.
$ sudo apt install ulauncher
Step 1: To remove the PPA repository from system
$ sudo add-apt-repository --remove ppa:agornostal/ulauncher
Step 2: To remove the app launcher, run this command:
$ sudo apt remove ulauncher
how-to-install
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Check the OS Version in Linux?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to remove rows that contains all zeros in an R data frame?

Often, we get missing data and sometimes missing data is filled with zeros if zero is not the actual range for a variable. In this type of situations, we can remove the rows where all the values are zero. For this purpose, we can use rowSums function and if the sum is greater than zero then keep the row otherwise neglect it.
 Live Demo
Consider the below data frame −
set.seed(251)
x1<−sample(0:1,20,replace=TRUE)
x2<−sample(0:1,20,replace=TRUE)
df1<−data.frame(x1,x2)
df1
x1 x2
1 0 0
2 0 1
3 0 1
4 1 1
5 1 0
6 0 1
7 1 0
8 1 1
9 1 1
10 0 0
11 0 1
12 1 0
13 1 0
14 1 1
15 0 1
16 1 1
17 1 1
18 1 1
19 1 1
20 0 0
Removing rows having all zeros −
df1[rowSums(df1[])>0,]
x1 x2
2 0 1
3 0 1
4 1 1
5 1 0
6 0 1
7 1 0
8 1 1
9 1 1
11 0 1
12 1 0
13 1 0
14 1 1
15 0 1
16 1 1
17 1 1
18 1 1
19 1 1
 Live Demo
y1<−sample(c(0,5),20,replace=TRUE)
y2<−sample(c(0,2),20,replace=TRUE)
df2<−data.frame(y1,y2)
df2
y1 y2
1 5 0
2 0 2
3 0 2
4 0 0
5 5 2
6 5 0
7 5 0
8 0 2
9 0 2
10 5 0
11 0 0
12 0 0
13 5 0
14 0 0
15 5 2
16 5 0
17 0 0
18 0 2
19 5 2
20 0 0
Removing rows having all zeros −
df2[rowSums(df2[])>0,]
y1 y2
1 5 0
2 0 2
3 0 2
5 5 2
6 5 0
7 5 0
8 0 2
9 0 2
10 5 0
13 5 0
15 5 2
16 5 0
18 0 2
19 5 2
 Live Demo
z1<−rep(0,20)
z2<−sample(c(0,1),20,replace=TRUE)
df3<−data.frame(z1,z2)
df3
z1 z2
1 0 0
2 0 0
3 0 0
4 0 0
5 0 0
6 0 1
7 0 1
8 0 1
9 0 1
10 0 1
11 0 1
12 0 0
13 0 0
14 0 1
15 0 1
16 0 0
17 0 1
18 0 1
19 0 1
20 0 1
Removing rows having all zeros −
df3[rowSums(df3[])>0,]
z1 z2
6 0 1
7 0 1
8 0 1
9 0 1
10 0 1
11 0 1
14 0 1
15 0 1
17 0 1
18 0 1
19 0 1
20 0 1
C++ program to generate random number - GeeksforGeeks

03 Jan, 2018
The below implementation is to generate random number from 1 to given limit. The below function produces behavior similar to srand() function.
Prerequisite : random header in C++ | Set 1(Generators)
// C++ program to generate random number#include <bits/stdc++.h>using namespace std;  // Function with return random number from 1 to// given limitint randomNoGenerator(int limit){    // uniformly-distributed integer random number    // generator that produces non-deterministic    // random numbers.    random_device rd;      // A Mersenne Twister pseudo-random generator    // of 32-bit numbers with a state size of    // 19937 bits.    mt19937 gen(rd());      // Uniform distribution    uniform_int_distribution<> dis(1, limit);    return dis(gen);}  // Driver Codeint main(){    int limit = 100;    cout << randomNoGenerator(limit) << endl;    return 0;}
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
Sorting a Map by value in C++ STL
LinkedList addFirst() Method in Java - GeeksforGeeks

10 Dec, 2018
The java.util.LinkedList.addFirst() method in Java is used to insert a specific element at the beginning of a LinkedList.
Syntax:
void addFirst(Object element)

Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended at beginning of the list.
Return Value: This method does not returns any value.
Below program illustrate the java.util.LinkedList.addFirst() method:
// Java code to illustrate addFirst() method of class LinkedList  import java.io.*;import java.util.LinkedList;  public class LinkedListDemo {    public static void main(String args[])    {          // creating an empty LinkedList        LinkedList<String> list = new LinkedList<String>();          // use add() method to add elements in the list        list.add("Geeks");        list.add("for");        list.add("Geeks");        list.add("10");        list.add("20");          // Output the present list        System.out.println("The list is:" + list);          // Adding new elements at the beginning        list.addFirst("First");        list.addFirst("At");          // Displaying the new list        System.out.println("The new List is:" + list);    }}
The list is:[Geeks, for, Geeks, 10, 20]
The new List is:[At, First, Geeks, for, Geeks, 10, 20]

Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
Compute cartesian product of elements in an array in JavaScript

The Cartesian product of two sets (arrays) A and B, denoted A × B, is the set (array) of all ordered pairs (a, b) where a is in A and b is in B.
In simpler terms, a cartesian product of two arrays is a permutation of all possible arrays of two elements whose first element belongs to the first array and the second element belongs to the second array.
For example − If the two arrays are −
const arr1 = [1, 2, 3];
const arr2 = [4, 5];
Then their cartesian product will be −
const product = [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]];
The code for this will be −
const arr1 = [1, 2, 3];
const arr2 = [4, 5];
const cartesianProduct = (arr1, arr2) => {
   const res = [];
   for(let i = 0; i < arr1.length; i++){
      for(let j = 0; j < arr2.length; j++){
         res.push(
            [arr1[i]].concat(arr2[j])
         );
      };
   };
   return res;
};
console.log(cartesianProduct(arr1, arr2));
And the output in the console will be −
[ [ 1, 4 ], [ 1, 5 ], [ 2, 4 ], [ 2, 5 ], [ 3, 4 ], [ 3, 5 ] ]
Substring Matching of Test Names

To execute the tests containing a string in its name we can use the following syntax −
pytest -k <substring> -v

-k <substring> represents the substring to search for in the test names.
Now, run the following command −
pytest -k great -v

This will execute all the test names having the word ‘great’ in its name. In this case, they are test_greater() and test_greater_equal(). See the result below.
test_compare.py::test_greater FAILED
test_compare.py::test_greater_equal PASSED
============================================== FAILURES 
==============================================
____________________________________________ test_greater 
____________________________________________
def test_greater():
num = 100
>  assert num > 100
E  assert 100 > 100
test_compare.py:3: AssertionError
========================== 1 failed, 1 passed, 3 deselected in 0.07 seconds 
==========================

Here in the result, we can see 3 tests deselected. This is because those test names do not contain the word great in them.
Note − The name of the test function should still start with ‘test’.

    21 Lectures 
     4 hours 

 Lucian Musat

    22 Lectures 
     1.5 hours 

 Fanuel Mapuwei

    44 Lectures 
     3.5 hours 

 Rohit Dharaviya
 Print
 Add Notes
 Bookmark this page
Find and return array positions of multiple values JavaScript

We have to write a function, say findPositions() that takes in two arrays as argument.
And it should return an array of the indices of all the elements of the second array present in the
first array.
For example −
If the first array is [‘john’, ‘doe’, ‘chris’, ‘snow’, ‘john’, ‘chris’],
And the second array is [‘john’, chris]
Then the output should be −
[0, 2, 4, 5]
Therefore, let’s write the code for this function. We will use a forEach() loop here;
const values = ['michael', 'jordan', 'jackson', 'michael', 'usain',
'jackson', 'bolt', 'jackson'];
const queries = ['michael', 'jackson', 'bolt'];
const findPositions = (first, second) => {
   const indicies = [];
   first.forEach((element, index) => {
      if(second.includes(element)){
         indicies.push(index);
      };
   });
   return indicies;
};
console.log(findPositions(values, queries));
The output in the console will be −
[ 0, 2, 3, 5, 6, 7 ]