code-rag-bench/online-tutorials huggingface dataset:
What are the inserting elements in queue in C language?

Data structure is collection of data organized in a structured way. It is divided into two types as explained below −
Linear data structure − Data is organized in a linear fashion. For example, arrays, structures, stacks, queues, linked lists.
Linear data structure − Data is organized in a linear fashion. For example, arrays, structures, stacks, queues, linked lists.
Nonlinear data structure − Data is organized in a hierarchical way. For example, Trees, graphs, sets, tables.
Nonlinear data structure − Data is organized in a hierarchical way. For example, Trees, graphs, sets, tables.
It is a linear data structure, where the insertion is done at rear end and the deletion is done at the front end.
The order of queue is FIFO – First In First Out
Insert – Inserting an element into a queue.
Delete – Deleting an element from the queue.
Queue over flow − Trying to insert an element into a full queue.
Queue over flow − Trying to insert an element into a full queue.
Queue under flow − Trying to delete an element from an empty queue.
Queue under flow − Trying to delete an element from an empty queue.
Given below is an algorithm for insertion ( ) −
Check for queue overflow.
if (r==n)
printf ("Queue overflow")
Otherwise, insert an element in to the queue.
q[r] = item
r++
Following is the C program for inserting the elements in queue −
#include <stdio.h>
#define MAX 50
void insert();
int array[MAX];
int rear = - 1;
int front = - 1;
main(){
   int add_item;
   int choice;
   while (1){
      printf("1.Insert element to queue \n");
      printf("2.Display elements of queue \n");
      printf("3.Quit \n");
      printf("Enter your choice : ");
      scanf("%d", &choice);
      switch (choice){
         case 1:
            insert();
         break;
         case 2:
            display();
         break;
         case 3:
            exit(1);
         default:
         printf("Wrong choice \n");
      }
   }
}
void insert(){
   int add_item;
   if (rear == MAX - 1)
      printf("Queue Overflow \n");
   else{
      if (front == - 1)
         /*If queue is initially empty */
         front = 0;
         printf("Inset the element in queue : ");
         scanf("%d", &add_item);
         rear = rear + 1;
         array[rear] = add_item;
      }
}
void display(){
   int i;
   if (front == - 1)
      printf("Queue is empty \n");
   else{
      printf("Queue is : \n");
      for (i = front; i <= rear; i++)
         printf("%d ", array[i]);
      printf("\n");
   }
}
When the above program is executed, it produces the following result −
1.Insert element to queue
2.Display elements of queue
3.Quit
Enter your choice: 1
Inset the element in queue: 34
1.Insert element to queue
2.Display elements of queue
3.Quit
Enter your choice: 1
Inset the element in queue: 24
1.Insert element to queue
2.Display elements of queue
3.Quit
Enter your choice: 2
Queue is:
34 24
1.Insert element to queue
2.Display elements of queue
3.Quit
Enter your choice: 3
Counting Bits in Python

Suppose we have a non-negative integer number num. For each number i in the range 0 ≤ i ≤ num we have to calculate the number of 1's in their binary counterpart and return them as a list. So if the number is 5, then the numbers are [0, 1, 2, 3, 4, 5], and number of 1s in these numbers are [0, 1, 1, 2, 1, 2]
To solve this, we will follow these steps −
res := an array which holds num + 1 number of 0s
offset := 0
for i in range 1 to num + 1if i and i – 1 = 0, then res[i] := 1 and offset := 0else increase offset by 1 and res[i] := 1 + res[offset]
if i and i – 1 = 0, then res[i] := 1 and offset := 0
else increase offset by 1 and res[i] := 1 + res[offset]
return res
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution:
   def countBits(self, num):
      result = [0] * (num+1)
      offset = 0
      for i in range(1,num+1):
         if i & i-1 == 0:
            result[i] = 1
            offset = 0
         else:
            offset+=1
            result[i] = 1 + result[offset]
      return result
ob1 = Solution()
print(ob1.countBits(6))
6
[0, 1, 1, 2, 1, 2, 2]
Get Synchronized List from ArrayList in java

In order to get a synchronized list from an ArrayList, we use the synchronizedList(List <T>) method in Java. The Collections.synchronizedList(List <T>) method accepts the ArrayList as an argument and returns a thread safe list.
Declaration −The Collections.synchronizedList(List <T>) method is declared as follows −
public static List <T> synchronizedList(List <T> list)
Let us see a program to get a synchronized List from ArrayList −
 Live Demo
import java.util.*;
public class Example {
   public static void main (String[] args) {
      List<String> list = new ArrayList<String>();
      list.add("Hello");
      list.add("Hi");
      list.add("World");
      list = Collections.synchronizedList(list);
      synchronized(list) {
         Iterator itr = list.iterator();
         while (itr.hasNext())
         System.out.print(itr.next()+" ");
      }
   }
}
Hello Hi World
Segregate 0’s and 1’s in an array list using Python?

List Comprehension is a popular technique in Python. Here we use this technique. We create a user input array and array element should be 0’s and 1’s in random order. Then segregate 0’s on left side and 1’s on right side. We traverse the array and separate two different list, one contains 0’s and another contains 1’s, then concatenate two list.
Input:: a=[0,1,1,0,0,1]
Output::[0,0,0,1,1,1]

seg0s1s(A)
/* A is the user input Array and the element of A should be the combination of 0’s and 1’s */
Step 1: First traverse the array.
Step 2: Then check every element of the Array. If the element is 0, then its position is left side and if 1 then it is on the right side of the array.
Step 3: Then concatenate two list.

#  Segregate 0's and 1's in an array list
def seg0s1s(A):
   n = ([i for i in A if i==0] + [i for i in A if i==1])
   print(n)

# Driver program
if __name__ == "__main__":
   A=list()
   n=int(input("Enter the size of the array ::"))
   print("Enter the number ::")
   for i in range(int(n)):
      k=int(input(""))
      A.append(int(k))
   print("The New ArrayList ::")    
   seg0s1s(A)
Enter the size of the array ::6
Enter the number ::
1
0
0
1
1
0
The New ArrayList ::
[0, 0, 0, 1, 1, 1]
FreeGames module in Python - GeeksforGeeks

26 Jul, 2021
Python provides you free games and it’s is very easy and simple to get them and you can run it on you computer. So, are you curious about how you can get them? Just follow these simple steps:
Step #1:
Go to command prompt and type the following commandpython -m pip install freegames
python -m pip install freegames
Wait until the installation process gets finished
After the process gets finished, you are ready to go.
Step #2:
Let’s check how many and which games are provided by python freely. To check type the below commandpython -m freegames list
python -m freegames list
After you click Enter, a list of available games will be shownFree Games in Python
Free Games in Python
Step #3:
Free Python Games supports a command-line interface(A command line interface (CLI) is a text-based user interface (UI) used to view and manage computer files. Command line interfaces are also called command-line user interfaces, console user interfaces and character user interfaces).
To get the help for the CLI type the below commandpython -m freegames --helpCommand-Line Interface
python -m freegames --help
Command-Line Interface
Step #4:
To run any game available in the list type, type the below command.python -m freegames.gamename"
python -m freegames.gamename"
After that just click Enter to run the game
And you can see Python Turtle Graphics will be displayed.Tic Tac Toe
Tic Tac Toe
anikaseth98
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Java Program to check whether the character is ASCII 7 bit printable

To check whether the entered value is ASCII 7-bit printable, check whether the characters ASCII value is greater than equal to 32 and less than 127 or not. These are the control characters.
Here, we have a character.
char one = '^';
Now, we have checked a condition with if-else for printable characters.
if (c >= 32 && c < 127) {
   System.out.println("Given value is printable!");
} else {
   System.out.println("Given value is not printable!");
}
 Live Demo
public class Demo {
   public static void main(String []args) {
      char c = '^';
      System.out.println("Given value = "+c);
      if (c >= 32 && c < 127) {
         System.out.println("Given value is printable!");
      } else {
         System.out.println("Given value is not printable!");
      }
   }
}
Given value = ^
Given value is printable!
Let us see another example wherein the given value is a character.
 Live Demo
public class Demo {
   public static void main(String []args) {
      char c = 'y';
      System.out.println("Given value = "+c);
      if ( c >= 32 && c < 127) {
         System.out.println("Given value is printable!");
      } else {
         System.out.println("Given value is not printable!");
      }
   }
}
Given value = y
Given value is printable!
Crystal Reports - Creating Arrays

An Array variable in Crystal Report can be defined by using a keyword "Array".
Global NumberVar Array Z := [1, 2, 3];

You can also assign values to the elements of Array and these values can be used for computations in formulas. For example −
StringVar Array Z := ["Hello","World"];
Z[2] :=["Bye"];
UpperCase (Z [2] )
This formula will return the string "Bye".
You can also resize Array using Redim and Redim Preserve keywords. Redim is used to remove previous entries of an Array while resizing it, and Redim Preserve is used to contain previous Array values. For example −
Local NumberVar Array Z;
Redim Z [2]; //Now Z is [0, 0]

Z [2] := 10; //Now Z is [0, 10]
Redim Z [3]; //Now Z is [0, 0, 0], Redim has erased previous Array values.

Z [3] := 20; //Now Z is [0, 0, 20]
Redim Preserve Z [4]; //Now Z is [0, 0, 20, 0], Redim Preserve has contained previous 

Array values.
"finished"
Arrays are also used with Loops: like For loop.
Local NumberVar Array Z;
Redim Z[10];

Local NumberVar x;
For x := 1 To 10 Do (
   Z[x] := 10 * x
);

Z [5] //The formula returns the Number 50

    37 Lectures 
     2 hours 

 Neha Gupta

    61 Lectures 
     4.5 hours 

 Sasha Miller

    31 Lectures 
     32 mins

 Prof Krishna N Sharma

    35 Lectures 
     2 hours 

 Prof Krishna N Sharma

    24 Lectures 
     2 hours 

 Prof Krishna N Sharma
 Print
 Add Notes
 Bookmark this page
How to add a horizontal line to the plot created by ggplot2 in R?

When we create a plot, it shows the values passed by the function for creating the plot but we might want to display some other values to provide some information through the plot and that information could be a threshold value as a horizontal line or we can also call it a cut off value. This can be done by using geom_hline function of ggplot2 package.
Consider the below data frame −
> x<-rnorm(20)
> y<-rnorm(20,1.5)
> df<-data.frame(x,y)
> df
      x       y
1 0.27810573 2.6545571
2 1.39185082 3.4845292
3 -0.19068920 1.7043852
4 1.00791317 1.4324814
5 -1.74964913 1.7996093
6 -0.13123079 2.5004350
7 0.15729145 2.6425085
8 0.42815918 -0.2970325
9 -0.84252471 0.2579510
10 0.25413824 3.0670546
11 -0.05608811 1.6974104
12 -0.85671276 0.8638574
13 -1.17183043 2.5650640
14 2.67224782 0.4832468
15 -0.01763065 3.3835275
16 1.26122484 1.1755709
17 1.91652453 1.6351443
18 0.82211772 0.9123337
19 -0.19153555 0.1831160
20 0.31878745 3.1280550
Creating a scatterplot between x and y −
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()
Adding a horizontal line in the above plot −
> ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=0.5)
Assignment Operators Overloading in C++

You can overload the assignment operator (=) just as you can other operators and it can be used to create an object just like the copy constructor.
Following example explains how an assignment operator can be overloaded.
#include <iostream>
using namespace std;
 
class Distance {
   private:
      int feet;             // 0 to infinite
      int inches;           // 0 to 12
      
   public:
      // required constructors
      Distance() {
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i) {
         feet = f;
         inches = i;
      }
      void operator = (const Distance &D ) { 
         feet = D.feet;
         inches = D.inches;
      }
      
      // method to display distance
      void displayDistance() {
         cout << "F: " << feet <<  " I:" <<  inches << endl;
      }
};

int main() {
   Distance D1(11, 10), D2(5, 11);

   cout << "First Distance : "; 
   D1.displayDistance();
   cout << "Second Distance :"; 
   D2.displayDistance();

   // use assignment operator
   D1 = D2;
   cout << "First Distance :"; 
   D1.displayDistance();

   return 0;
}
When the above code is compiled and executed, it produces the following result −
First Distance : F: 11 I:10
Second Distance :F: 5 I:11
First Distance :F: 5 I:11


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Verifying whether an element present or visible in Selenium Webdriver

We can verify whether an element is present or visible in a page with Selenium webdriver. To check the presence of an element, we can use the method – findElements.
The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list. If the size is 0, it means that this element is absent from the page.
int j = driver.findElements(By.id("txt")).size();
To check the visibility of an element in a page, the method isDisplayed is used. It returns a Boolean value( true is returned if the element is visible, and otherwise false).
boolean t = driver.findElement(By.name("txt-val")).isDisplayed();
Code Implementation for element visible.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class ElementVisible{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element with partial link text
      WebElement n =driver.findElement(By.partialLinkText("Refund"));
      //check if element visible
      boolean t = driver.findElement(By.partialLinkText("Refund")).isDisplayed();
      if (t) {
         System.out.println("Element is dispalyed");
      } else {
         System.out.println("Element is not dispalyed");
      }
      driver.quit();
   }
}
Code Implementation for element presence.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class ElementPresence{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      //check if element present
      int t = driver.findElements(By.partialLinkText("Refund")).size();
      if (t > 0) {
         System.out.println("Element is present");
      }else {
         System.out.println("Element is not present");
      }
      driver.quit();
   }
}
HTML | Marquee behavior attribute - GeeksforGeeks

09 Feb, 2022
The Marquee behavior attribute in HTML is used to set the behavior of scrolling. The default value is scroll.Syntax:  
<marquee behavior=slide >
Attribute value: 
alternate: It defines that text moving to the end and then starting in the opposite direction.
scroll: It has a default value.  specify the text scrolls to the end and starts over.
slide: It specifies the text moving to the end and then stops it.
Example:  
html
<!DOCTYPE html><html> <head>    <title>HTML Marquee behavior attribute</title>    <style>        .main {            text-align: center;        }                 .marq {            padding-top: 30px;            padding-bottom: 30px;        }    </style></head> <body>    <h1 style="color:green; text-align:center;">GeeksforGeeks</h1>    <div class="main">        <marquee class="marq"                 bgcolor="Green"                 direction="left"                 behavior=scroll                 loop="">            Scroll        </marquee>        <marquee class="marq"                 bgcolor="Green"                 behavior=alternate                 direction="left"                 loop="">            Alternate        </marquee>    </div></body> </html>
Output:  
Supported Browsers: The browsers supported by HTML Marquee behavior attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
ManasChhabra2
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Form validation using HTML and JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
Ruby | Array to_h() function - GeeksforGeeks

05 Dec, 2019
Array#to_h() : to_h() is a Array class method which returns the result of interpreting ary as an array of [key, value] pairs.
Syntax: Array.to_h()
Parameter: Array
Return: the result of interpreting ary as an array of [key, value] pairs.
Example #1 :
# Ruby code for to_h() method  # declaring arraya = [[:foo, :bar], [1, 2]]  # to_h method exampleputs "to_h() method form : #{a.to_h()}\n\n"
Output :
to_h() method form : {:foo=>:bar, 1=>2}


Example #2 :
# Ruby code for to_h() method  # declaring arraya = [[:geeks, :geeks], [1, 2]]  # to_h method exampleputs "to_h() method form : #{a.to_h{|s| [s.ord, s]}}\n\n"
Output :
to_h() method form : {:geeks=>:geeks, 1=>2}


Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array count() operation
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | String gsub! Method
Include v/s Extend in Ruby
Ruby | Case Statement
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | Data Types
How to make border around all unordered list items that are children of a specified class using jQuery ? - GeeksforGeeks

22 Apr, 2021
In this article, we will see how to set a border around all list items that are children of a specified class of an unordered list using jQuery. This task can be done by using the children selector() method.
children selector(“parent > child”) – As you notice from the name itself that it takes two arguments and then perform the task. It selects all children element specified by a child of elements specified by the “parent”. Here the parent is any selector and the child is a selector to filter the child elements.
Example: Places a border around all list items that are children of <ul class=”GFG”>.
HTML
<!doctype html><html lang="en">  <head>    <script src="https://code.jquery.com/jquery-3.5.0.js">    </script></head>  <body>      <ul class="GFG">        <h1 style="color: green;             text-align: center;">            GeeksforGeeks        </h1>          <li>DataBase            <ol>                <li>oracle</li>                <li>MySql</li>                <li>DB2</li>            </ol>        </li>        <li>Computer Networks            <ol>                <li>LAN</li>                <li>MAN</li>                <li>WAN</li>            </ol>        </li>        <li>Operating system            <ol>                <li>Linux</li>                <li>Mac</li>                <li>Windows</li>            </ol>        </li>      </ul>      <script>        $("ul.GFG > li")            .css("border", "2px dashed green");    </script>  </body>  </html>
Output – 
HTML-Tags
jQuery-Methods
jQuery-Questions
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
How to get the value in an input text box using jQuery ?
Difference Between JavaScript and jQuery
QR Code Generator using HTML, CSS and jQuery
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 ?
C++ Null Pointers

It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries, including iostream. Consider the following program −
#include <iostream>

using namespace std;
int main () {
   int  *ptr = NULL;
   cout << "The value of ptr is " << ptr ;
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
The value of ptr is 0

On most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing.
To check for a null pointer you can use an if statement as follows −
if(ptr)     // succeeds if p is not null
if(!ptr)    // succeeds if p is null

Thus, if all unused pointers are given the null value and you avoid the use of a null pointer, you can avoid the accidental misuse of an uninitialized pointer. Many times, uninitialized variables hold some junk values and it becomes difficult to debug the program.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Angular CLI - ng xi18n Command

This chapter explains the syntax, arguments and options of ng xi18n command along with an example.
The syntax for ng xi18n command is as follows −
ng xi18n <project> [options]
ng i18n-extract <project> [options]

ng xi18n command extracts i18n messages from source code. 
The argument for ng xi18n command is as follows −
Options are optional parameters.
A named build target, as specified in the "configurations" section of angular.json. Each named target is accompanied by a configuration of option defaults for that target. Setting this explicitly overrides the "--prod" flag.
Aliases: -c
Create source control commits for updates and migrations.
Default: false
Aliases: -C
Output format for the generated file.
Default: xlf
Shows a help message for this command in the console.
Default: false
Log progress to the console.
Default: true
First move to an angular project updated using ng build command. The chapter is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm.
Update the app.component.html as follows −
app.component.spec.ts
<div class="content" role="main">
   <span i18n>app is running!</span>
</div>
<app-goals></app-goals>
<router-outlet></router-outlet>
Now run the xi18n command.
An example for ng xi18n command is given below −
\>Node\>TutorialsPoint> ng xi18n

Add localization support.
\>Node\>TutorialsPoint> ng add @angular/localize
Installing packages for tooling via npm.
Installed packages for tooling via npm.
UPDATE src/polyfills.ts (3064 bytes)

Now ng will create a messages.xlf file in root folder which is a industry standard translation file.
messages.xlf
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
   <file source-language="en-US" datatype="plaintext" original="ng2.template">
      <body>
         <trans-unit id="6226cbeebaffaec0342459915ef7d9b0e9e92977" datatype="html">
            <source>app is running!</source>
            <context-group purpose="location">
               <context context-type="sourcefile">src/app/app.component.html</context>
               <context context-type="linenumber">2</context>
            </context-group>
         </trans-unit>
      </body>
   </file>
</xliff>

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Find and display duplicate values only once from a column in MySQL

Let us first create a table −
mysql> create table DemoTable
-> (
-> value int
-> );
Query OK, 0 rows affected (0.82 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.28 sec)

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.34 sec)

mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.24 sec)

mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.07 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| value |
+-------+
| 10    |
| 100   |
| 20    |
| 10    |
| 30    | 
| 40    |
| 20    |
+-------+
7 rows in set (0.00 sec)
Following is the query to find the duplicate values and display them once −
mysql> select *from DemoTable group by value having count(*) > 1;
This will produce the following output −
+-------+
| value |
+-------+
| 10    |
| 20    |
+-------+
2 rows in set (0.00 sec)
Wand arc() function in Python - GeeksforGeeks

16 Oct, 2021
arc() is a function present in wand.drawing module. arc() function draws an arc in the image. You’ll need to define three pairs of (x, y) coordinates. First & second pair of coordinates will be the minimum bounding rectangle, and the last pair define the starting & ending degree. 
Syntax :  
wand.drawing.arc(start, end, degree)
Parameters : 
 
Example #1:  
Python3
# Import required objects from wand modulesfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color # generate object for wand.drawingwith Drawing() as draw:    # set stroke color    draw.stroke_color = Color('black')    # set width for stroke    draw.stroke_width = 1    # fill white color in arc    draw.fill_color = Color('white')    draw.arc(( 50, 50),  # Stating point             ( 150, 150),  # Ending point             (135, -45))  # From bottom left around to top right    with Image(width = 100,               height = 100,               background = Color('green')) as img:        # draw shape on image using draw() function        draw.draw(img)        img.save(filename ='arc.png')
Output:  
Example #2:Source Image:  
 
Python3
# Import required objects from wand modulesfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color # generate object for wand.drawingwith Drawing() as draw:'    # set stroke color    draw.stroke_color = Color('black')    # set width for stroke    draw.stroke_width = 1    # fill white color in arc    draw.fill_color = Color('white')    draw.arc(( 50, 50),  # Starting point             ( 150, 150),  # Ending point             (135, -45))  # From bottom left around to top right    with Image(filename ="gog.png") as img:        # draw shape on image using draw() function        draw.draw(img)        img.save(filename ='arc.png')
Output:  
 
akshaysingh98088
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Matplotlib.pyplot.axis() in Python - GeeksforGeeks

12 Apr, 2020
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Pyplot is a Matplotlib module which provides a MATLAB-like interface. Matplotlib is designed to be as usable as MATLAB, with the ability to use Python and the advantage of being free and open-source.
This function is used to set some axis properties to the graph.
Syntax: matplotlib.pyplot.axis(*args, emit=True, **kwargs)
Parameters:xmin, xmax, ymin, ymax:These parameters can be used toset the axis limits on the graphemit:Its a bool value used to notify observers of the axis limit change
Example #1:
import matplotlib.pyplot as plt    x =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10]  # Plotting the graphplt.plot(x, y)  # Setting the x-axis to 1-10# and y-axis to 1-15plt.axis([0, 10, 1, 15])  # Showing the graph with updated axisplt.show()
Output:
Example #2:
import matplotlib.pyplot as plt  x =[1, 2, 3, 4, 5]y =[2, 4, 6, 8, 10]  plt.plot(x, y)  # we can turn off the axis and display# only the line by passing the # optional parameter 'off' to itplt.axis('off')  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
sum() function in Python
Stack in Python
Reading and Writing to text files in Python
Difference between C-SCAN and SSTF Disk Scheduling Algorithm - GeeksforGeeks

12 Jun, 2020
1. C-SCAN Disk Scheduling Algorithm :C-SCAN algorithm, also known as Circular Elevator algorithm is the modified version of SCAN algorithm. In this algorithm, the head pointer starts from one end of disk and moves towards the other end, serving all requests in between. After reaching the other end, the head reverse its direction and go to the starting point. It then satisfies the remaining requests, in same direction as before. Unlike SSTF, it can handle requests only in one direction.
Example –Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows:
98, 183, 40, 122, 10, 124, 65 
Current head position of the Read/Write head is 53 and will move in Right direction . Calculate the total number of track movements of Read/Write head using C-SCAN algorithm.
Total head movements,
= (65-53)+(98-65)+(122-98)+(124-122)+(183-124)
               +(199-183)+(199-0)+(10-0)+(40-10)
= 395 
2. SSTF Disk Scheduling Algorithm :SSTF stands for Shortest Seek Time First, as the the name suggests it serves the request which is closest to the current position of head or pointer. In this algorithm, direction of the the head pointer matters a lot. If there occurs a tie between requests, then the head will serve the request in its ongoing direction. Unlike C-SCAN, SSTF algorithm is very efficient in total seek time.
Example –Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows:
98, 183, 40, 122, 10, 124, 65 
Current head position of the Read/Write head is 53 and will move in Right direction. Calculate the total number of track movements of Read/Write head using SSTF algorithm.
Total head movements,
= (65-53)+(65-40)+(40-10)
           +(98-10)+(122-98)+(124-122)+(183-124)
= 240 
Difference between C-SCAN and SSTF Disk Scheduling Algorithm :
File & Disk Management
Difference Between
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Informed and Uninformed Search in AI
Difference between Internal and External fragmentation
Difference between HashMap and HashSet
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
How to create a stacked bar plot with vertical bars in R using ggplot2?

Traditionally, the stacked bar plot has multiple bars for each level of categories lying upon each other. But this visual can be changed by creating vertical bars for each level of categories, this will help us to read the stacked bar easily as compared to traditional stacked bar plot because people have a habit to read vertical bars.
Consider the below data frame −
 Live Demo
set.seed(999)
Class<-sample(c("I","II","III","IV"),20,replace=TRUE)
Category<-sample(LETTERS[1:4],20,replace=TRUE)
Score<-sample(41:100,20)
df<-data.frame(Class,Category,Score)
df
   Class Category Score
1  II     D        47
2  III    C        88
3  I      C        83
4  IV     B        67
5  IV     D        61
6  I      D        56
7  III    C        74
8  I      C        54
9  II     D       100
10 III    B        43
11 II     A        77
12 III    A        72
13 I      C        92
14 IV     C        81
15 I      C        49
16 IV     D        97
17 I      D        91
18 IV     D        73
19 I     A         59
20 I     B         75
Loading ggplot2 and creating a stacked bar chart with bars on top of each other −
library(ggplot2) ggplot(df,aes(Class,Score,fill=Category))+geom_bar(stat="identity")
Creating a stacked bar chart with vertical bars −
ggplot(df,aes(Class,Score,fill=Category))+geom_bar(stat="identity",position="dodge")
Read List of Dictionaries from File in Python - GeeksforGeeks

26 Jul, 2020
A dictionary in Python is a collection where every value is mapped to a key. Since they are unordered and there is no constraint on the data type of values and keys stored in the dictionary, it is tricky to read dictionaries from files in Python.
The problem statement mentions a list of dictionaries that have to be read from a file. There can be two ways of doing this:
1. Reading from Text File
We can read data from a text file as a string and convert that data into a dictionary in Python. Assuming our data is stored in a text file in the following format – 
{'geek': 10, 'geeky': True}
{'GeeksforGeeks': 'Education', 'geekgod': 101.0, 3: 'gfg'}
{'supergeek': 5}

The approach would include the following steps:
Open the text file in read mode and read the content
Parse every line in the content into a dictionary.
2. Reading using Pickle Module
The pickle module in Python is mostly used in fields like Data Science where data persistence is critical. The pickle module stores the given data as a serialized byte sequence into files which can be easily retrieved at a later time. Pickle module supports various Python objects and dictionaries are one among them. This method would include the following steps:
Importing the pickle module
Opening the file in read binary mode
Loading the data into a variable using pickle module’s dump method
list_dictionary = pickle.load(filehandler)

Below are the examples of the above-discussed approaches.
1. Reading from Text File:
Input File:
Python3
def parse(d):    dictionary = dict()    # Removes curly braces and splits the pairs into a list    pairs = d.strip('{}').split(', ')    for i in pairs:        pair = i.split(': ')        # Other symbols from the key-value pair should be stripped.        dictionary[pair[0].strip('\'\'\"\"')] = pair[1].strip('\'\'\"\"')    return dictionarytry:    geeky_file = open('geeky_file.txt', 'rt')    lines = geeky_file.read().split('\n')    for l in lines:        if l != '':            dictionary = parse(l)            print(dictionary)    geeky_file.close()except:    print("Something unexpected occurred!")
Output:
{'geek': '10', 'geeky': 'True'}
{'GeeksforGeeks': 'Education', 'geekgod': '101.0', '3': 'gfg'}
{'supergeek': '5'}
2. Reading using Pickle
Python3
import pickle    try:    geeky_file = open('GFG.txt', 'r')    dictionary_list = pickle.load(geeky_file)          for d in dictionary_list:        print(d)    geeky_file.close()  except:    print("Something unexpected occurred!")
Output:
Python dictionary-programs
python-dict
python-file-handling
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python OOPs Concepts
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
C# program to convert string to long

To convert a string to a long, use the Long.parse method in C# −
Firstly, set a string −
string str = "6987646475767";
Now, convert it to long −
long.Parse(str);
Here is the complete code −
 Live Demo
using System;
using System.Linq;
class Demo {
   static void Main() {
      string str = "6987646475767";
      long res = long.Parse(str);
      Console.WriteLine(res);
   }
}
6987646475767
Python | Excel File Comparison

09 Sep, 2019
Input : 
Two Excel files

Output :
Column name : 'location' and Row Number : 0
Column name : 'location' and Row Number : 3
Column name : 'date' and Row Number     : 1


Code : Python code for comparing two excel files
# Write Python3 code here# importing Pandas  import pandas as pd  #Reading two Excel Sheets  sheet1 = pd.read_excel(r'Book1.xlsx')sheet2 = pd.read_excel(r'Book2.xlsx')  # Iterating the Columns Names of both Sheetsfor i,j in zip(sheet1,sheet2):         # Creating empty lists to append the columns values        a,b =[],[]      # Iterating the columns values    for m, n in zip(sheet1[i],sheet2[j]):          # Appending values in lists        a.append(m)        b.append(n)      # Sorting the lists    a.sort()    b.sort()      # Iterating the list's values and comparing them    for m, n in zip(range(len(a)), range(len(b))):        if a[m] != b[n]:            print('Column name : \'{}\' and Row Number : {}'.format(i,m))
Articles
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Remove empty List from List

04 Jul, 2022
Sometimes, while working with python, we can have a problem in which we need to filter out certain empty data. These can be none, empty string, etc. This can have applications in many domains. Let us discuss certain ways in which the removal of empty lists can be performed. 
Method 1: Using list comprehension: This is one of the ways in which this problem can be solved. In this, we iterate through the list and don’t include the list which is empty. 
Example
Python3
# Python3 code to Demonstrate Remove empty List# from List using list comprehension # Initializing listtest_list = [5, 6, [], 3, [], [], 9] # printing original listprint("The original list is : " + str(test_list)) # Remove empty List from List# using list comprehensionres = [ele for ele in test_list if ele != []] # printing resultprint("List after empty list removal : " + str(res))
The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]
Method 2: Using filter() method
This is yet another way in which this task can be performed. In this, we filter None values. The none values include empty lists as well and hence these get removed.
Example
Python3
# Python3 Code to Demonstrate Remove empty List# from List using filter() Method # Initializing list by custom valuestest_list = [5, 6, [], 3, [], [], 9] # Printing original listprint("The original list is : " + str(test_list)) # Removing empty List from List# using filter() methodres = list(filter(None, test_list)) # Printing the resultant listprint("List after empty list removal : " + str(res))
The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]
Method 3: Using function defination 
Python3
# Python Code to Remove empty List from List def empty_list_remove(input_list):    new_list = []    for ele in input_list:        if ele:            new_list.append(ele)    return new_list  # input list valuesinput_list = [5, 6, [], 3, [], [], 9] # print initial list valuesprint(f"The original list is : {input_list}")# function-call & print valuesprint(f"List after empty list removal : {empty_list_remove(input_list)}")
The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]
Above defined method(Method 3) is best optimized method among all three.
Method 4: Using len() and type() methods.If the length is zero then the list is empty.
Python3
# Python3 code to Demonstrate Remove empty List # Initializing listtest_list = [5, 6, [], 3, [], [], 9] # printing original listprint("The original list is : " + str(test_list))new_list=[]# Remove empty List from Listfor i in test_list:    x=str(type(i))    if(x.find('list')!=-1):        if(len(i)!=0):            new_list.append(i)    else:        new_list.append(i)# printing resultprint("List after empty list removal : " + str(new_list))
The original list is : [5, 6, [], 3, [], [], 9]
List after empty list removal : [5, 6, 3, 9]
saikot
varshagumber28
kogantibhavya
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js process.exit() Method

24 Dec, 2021
The process.exit() method is used to end the process which is running at the same time with an exit code in NodeJS.
Syntax:
process.exit( code )
Parameter:  This function accepts single parameter as mentioned above and described below:
Code: It can be either 0 or 1. 0 means end the process without any kind of failure and 1 means end the process with some failure.
Return value: It does not return any value.
As it is the predefined module, so we don’t have to install it in our directory.
How to implement in code?
Create a file with name index.jsCreate a variable with the name process and require the ‘process’ module in it.Create an infinite loop to check the functionality of .exit().
Create a file with name index.js
Create a variable with the name process and require the ‘process’ module in it.
Create an infinite loop to check the functionality of .exit().
Case 1: Without using process.exit() method:
index.js
// Importing process modulevar process = require('process');  var a = 0;  // Infinite loopwhile (a == 0) {      // Printing statement    console.log('GeeksforGeeks');  }
Run index.js file using below command:
node index.js
Output: In the above code, we have created an infinite loop that prints GeeksForGeeks until we have stopped the program manually.
Case-II: Using process.exit() method:
index.js
// Importing process modulevar process = require('process');var a = 0;  // Infinite loopwhile (a == 0) {      // Printing statement    console.log('GeeksForGeeks');          // Terminate the entire process    process.exit(0);}
Run index.js file using below command:
node index.js
Output: In the above code, we have used the same code as CASE-I but the only difference is we have used process.exit() function that automatically stops the NodeJS program when there is some problem with the code. In this case, the code prints GeeksForGeeks only for a single time.
Reference: https://nodejs.org/api/process.html#process_process_exit_code
surinderdawra388
Node.js-Methods
Node.js-process-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
get_cookie driver method – Selenium Python

03 Dec, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. 
This article revolves around get_cookie driver method in Selenium. get_cookie method is used to get a cookie with a specified name. It returns the cookie if found, None if not.
Syntax – 
driver.get_cookie(name)
Example – Now one can use get_cookie method as a driver method as below – 
driver.get("https://www.geeksforgeeks.org/")
driver.get_cookie("foo")
To demonstrate, get_cookie method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s first add a cookie and then get it.
Program – 
Python3
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # add_cookie method driverdriver.add_cookie({"name" : "foo", "value" : "bar"}) # get browser cookiedriver.get_cookie("foo")
Output – Screenshot after cookie added –  
 
Akanksha_Rai
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON