code-rag-bench/online-tutorials huggingface dataset:
ArrayDeque iterator() Method in Java - GeeksforGeeks

10 Dec, 2018
The Java.util.ArrayDeque.iterator() method is used to return an iterator of the elements of the ArrayDeque.
Syntax:
Iterator iterate_value = Array_Deque.iterator();
Parameters: The method does not take any parameter.
Return Value: The method iterates over the elements of the deque and returns the values(iterator).
Below programs illustrate the Java.util.ArrayDeque.iterator() method:Program 1:
// Java code to illustrate iterator()import java.util.*;  public class ArrayDequeDemo {    public static void main(String args[])    {        // Creating an empty ArrayDeque        Deque<String> de_que = new ArrayDeque<String>();          // Use add() method to add elements into the Queue        de_que.add("Welcome");        de_que.add("To");        de_que.add("Geeks");        de_que.add("4");        de_que.add("Geeks");          // Displaying the ArrayDeque        System.out.println("ArrayDeque: " + de_que);          // Creating an iterator        Iterator value = de_que.iterator();          // Displaying the values after iterating through the Deque        System.out.println("The iterator values are: ");        while (value.hasNext()) {            System.out.println(value.next());        }    }}
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The iterator values are: 
Welcome
To
Geeks
4
Geeks

Program 2:
// Java code to illustrate iterator()import java.util.*;  public class ArrayDequeDemo {    public static void main(String args[])    {        // Creating an empty ArrayDeque        Deque<Integer> de_que = new ArrayDeque<Integer>();          // Use add() method to add elements into the Queue        de_que.add(10);        de_que.add(15);        de_que.add(30);        de_que.add(20);        de_que.add(5);          // Displaying the ArrayDeque        System.out.println("ArrayDeque: " + de_que);          // Creating an iterator        Iterator value = de_que.iterator();          // Displaying the values after iterating through the Deque        System.out.println("The iterator values are: ");        while (value.hasNext()) {            System.out.println(value.next());        }    }}
ArrayDeque: [10, 15, 30, 20, 5]
The iterator values are: 
10
15
30
20
5

Java - util package
Java-ArrayDeque
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
C# | How to play user modified Beep sound through Console - GeeksforGeeks

29 Jan, 2019
Given a normal Console in C#, the task is to play a user modified Beep sound through the Console. User modified beep sound refers to the Beep sound played at a specific frequency for a specific duration of time.
Approach: This can be achieved with the help of Beep(Int32, Int32) method of Console Class in System package of C#.
The Beep(int, int) method of Console Class is used to play a Beep sound through the Console speaker at the specified frequency for a specified duration. These frequency and duration are specified as parameters to this method. By default, the beep plays at a frequency of 800 hertz for a duration of 200 milliseconds.
Syntax: public static void Beep (int frequency, int duration);
Parameters: This method accepts two parameters frequency and duration which are the frequency at which the Beep sound has to be played and the duration for which it is to be played, respectively.
Exceptions: This method throws following exceptions:
ArgumentOutOfRangeException if the frequency is less than 37 or more than 32767 hertz if the duration is less than or equal to zero.
HostProtectionException if this method was executed on a server, such as SQL Server, that does not permit access to a user interface.
Below programs show the use of Console.Beep(Int32, Int32) method:
Program 1:
// C# program to illustrate the use// of Console.Beep(Int32, Int32) Methodusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Set the Frequency        int frequency = 800;          // Set the Duration        int duration = 200;          // Play beep sound once        Console.Beep(frequency, duration);    }}}
Program 2:
// C# program to illustrate the use// of Console.Beep(Int32, Int32) Methodusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;  namespace GFG {  class Program {      // Main Method    static void Main(string[] args)    {          int n = 5;          // Set the Frequency        int frequency = 1000;          // Set the Duration        int duration = 400;          // Play beep sound n times        for (int i = 1; i < n; i++)            Console.Beep(frequency, duration);    }}}
Note: Please run the programs on offline Visual Studio to experience the output.
CSharp-Console-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Method Overriding
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
Introduction to .NET Framework
C# | Class and Object
Python - Stacking a multi-level column in a Pandas DataFrame

To stack a multi-level column, use the stack() method. At first, import the required library −
import pandas as pd
Create a multi-level column −
items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'),('Maths', 'Applied Mathematics')])


Now, create a DataFrame and set multi-level columns we set above −
dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],index=['John', 'Tom', 'Henry'],columns=items)
Stack the multi-level column −
dataframe.stack()
Following is the complete code −
import pandas as pd

# multi-level columns
items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'),
('Maths', 'Applied Mathematics')])

# creating a DataFrame
dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],index=['John', 'Tom', 'Henry'],columns=items)

# DataFrame
print"DataFrame...\n",dataFrame

# stack multi-level columns
print"\nStacking...\n",dataFrame.stack()
This will produce the following output −
DataFrame...
           Maths
      Mental Maths  Discrete Mathematics  Applied Mathematics
John            67                    86                   78
Tom             56                    92                   97
Henry           92                    95                   91

Stacking...
                            Maths
John   Applied Mathematics     78
       Discrete Mathematics    86
       Mental Maths            67
Tom    Applied Mathematics     97
       Discrete Mathematics    92
       Mental Maths            56
Henry  Applied Mathematics     91
       Discrete Mathematics    95
       Mental Maths            92
Tryit Editor v3.7

Tryit: link to stylesheet
Demonstrate nested loops with return statements in JavaScript?

Here’s an example with two loops, outer and inner −
let demoForLoop = ()=>{
   for(var outer=1;outer<100;outer++){
      for(var inner=1;inner<=5;inner++){
         if(outer==3){
            return 'THE OUTER VALUE IS EQUAL TO 3 INSIDE THE LOOP';
         }
      }
   }
   return 'OUT OF THE LOOP';
}
console.log(demoForLoop());
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo105.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo105.js
THE OUTER VALUE IS EQUAL TO 3 INSIDE THE LOOP
Boundary Testing

Boundary value analysis is a type of black box or specification based testing technique in which tests are performed using the boundary values.
An exam has a pass boundary at 50 percent, merit at 75 percent and distinction at 85 percent. The Valid Boundary values for this scenario will be as follows:
49, 50 - for pass
74, 75 - for merit
84, 85 - for distinction
Boundary values are validated against both the valid boundaries and invalid boundaries.
The Invalid Boundary Cases for the above example can be given as follows:
0 - for lower limit boundary value
101 - for upper limit boundary value

    80 Lectures 
     7.5 hours 

 Arnab Chakraborty

    10 Lectures 
     1 hours 

 Zach Miller

    17 Lectures 
     1.5 hours 

 Zach Miller

    60 Lectures 
     5 hours 

 John Shea

    99 Lectures 
     10 hours 

 Daniel IT

    62 Lectures 
     5 hours 

 GlobalETraining
 Print
 Add Notes
 Bookmark this page
The Simplest Way to Scrape Tabular Data with Python | by Joe T. Santhanavanich | Towards Data Science

Many of you might have already read several articles about data scraping from the websites. Most of them suggested using Node.js with Cheerio library or Python with Beautiful Soup. Although it is very effective when you master the techniques, it takes your time and effort until you finish all the coding for finding an element you need, requesting data, cleaning data to create a dataframe before you can do the actual data analysis. (And, of course, some additional time to fix all the bugs and errors 🐛)
This short article will show you a tutorial on how to the easiest way to scrape the tabular data from any website with the three lines of Python Script!
Our hero for this is the (red) PANDAS! Yes, the popular Pandas all you guys know is cute and capable of automatically extract the tabular data from the HTML file as well.
For example, you want to get the tabular data from the Worldometer website. As this dataset is dynamic, changing over time, the Data scraping is make-sense that we get the most updated result every time when running the script!
To scrape this dataset, get your machine ready with Python and Pandas. We gonna use the Pandas read_html() to extract all tables of any webpage. However, we cannot just use it to read URL directly because you might face an error 403: Forbidden. To avoid the error, we gonna request it with request module first to get the HTML body before use Pandas to read it. Overall, the script looks like this:
The dfs is a list result containing multiple dataframes from the table's class of the requested HTML body. Let’s explore the dataframe we get from the above script by print out the first dfs.
print(dfs[0])
With three lines of Python codes, you get the updated dataframe of COVID-19 data to play with, Simple and Easy!
Have fun with your data analysis/ visualization!! I hope you enjoy this short article. Feel free to leave me a message if you have questions, comments, or suggestions.
About me & Check out all my blog contents: Link
Be Safe and Healthy! 💪
Thank you for Reading. 📚
Difference between Batch Gradient Descent and Stochastic Gradient Descent | by Aerin Kim | Towards Data Science

Let’s take the simplest example, which is Linear Regression.
As always, we start with the cost function.
Linear Regression Recap done.
Now, what was the Gradient Descent algorithm?
In the above algorithm says, to perform the GD, we need to calculate the gradient of the cost function J. And to calculate the gradient of the cost function, we need to sum (yellow circle!) the cost of each sample. If we have 3 million samples, we have to loop through 3 million times or use the dot product.
Here is the Python code:
def gradientDescent(X, y, theta, alpha, num_iters):    """       Performs gradient descent to learn theta    """    m = y.size  # number of training examples    for i in range(num_iters):        y_hat = np.dot(X, theta)        theta = theta - alpha * (1.0/m) * np.dot(X.T, y_hat-y)    return theta
Do you see np.dot(X.T, y_hat-y) above? That’s the vectorized version of “looping through (summing) 3 million samples”.
Wait... just to move a single step towards the minimum, do we really have to calculate each cost 3 million times?
Yes. If you insist to use GD.
But if you use Stochastic GD, you don’t have to!
Basically, in SGD, we are using the cost gradient of 1 example at each iteration, instead of using the sum of the cost gradient of ALL examples.
def SGD(f, theta0, alpha, num_iters):    """        Arguments:       f -- the function to optimize, it takes a single argument            and yield two outputs, a cost and the gradient            with respect to the arguments       theta0 -- the initial point to start SGD from       num_iters -- total iterations to run SGD for       Return:       theta -- the parameter value after SGD finishes    """    start_iter = 0    theta= theta0    for iter in xrange(start_iter + 1, num_iters + 1):        _, grad = f(theta)        theta = theta - (alpha * grad) # there is NO dot product!    return theta
Well, Stochastic Gradient Descent has a fancy name, but I guess it’s a pretty simple algorithm!
A few things to note:
a) In SGD, before for-looping, you need to randomly shuffle the training examples.
b) In SGD, because it’s using only one example at a time, its path to the minima is noisier (more random) than that of the batch gradient. But it’s ok as we are indifferent to the path, as long as it gives us the minimum AND the shorter training time.
c) Mini-batch gradient descent uses n data points (instead of 1 sample in SGD) at each iteration.
If you like my post, could you please clap? It gives me motivation to write more. :)
Find the unique pair combinations of an R data frame column values.

To find the unique pair combinations of an R data frame column values, we can use combn function along with unique function.
For Example, if we have a data frame called df that contains a column say x then we can find the unique pair combinations of all column values by using the command given below −
combn(unique(df$x),2,FUN=paste,collapse=' ')
Following snippet creates a sample data frame −
Grp<-sample(c("I","II","III"),20,replace=TRUE)
df1<-data.frame(Grp)
df1
The following dataframe is created
Grp
1 II
2 III
3 I
4 I
5 II
6 I
7 II
8 III
9 III
10 I
11 I
12 I
13 I
14 II
15 III
16 II
17 I
18 II
19 II
20 III
To find unique pair combinations for values in column Grp of df1 on the above created data frame, add the following code to the above snippet −
Grp<-sample(c("I","II","III"),20,replace=TRUE)
df1<-data.frame(Grp)
combn(unique(df1$Grp),2,FUN=paste,collapse=' ')
If you execute all the above given snippets as a single program, it generates the following Output −
[1] "II III" "II I" "III I"
Following snippet creates a sample data frame −
Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE)
df2<-data.frame(Class)
df2
The following dataframe is created
Class
1 Second
2 Fourth
3 Fourth
4 Second
5 Fourth
6 Third
7 Fourth
8 Third
9 First
10 Fifth
11 Second
12 Second
13 Third
14 Second
15 First
16 Second
17 Fourth
18 First
19 Fifth
20 First
To find unique pair combinations for values in column Class of df2 on the above created data frame, add the following code to the above snippet −
Class<-sample(c("First","Second","Third","Fourth","Fifth"),20,replace=TRUE)
df2<-data.frame(Class)
combn(unique(df2$Class),2,FUN=paste,collapse=' ')
If you execute all the above given snippets as a single program, it generates the following Output −
[1] "Second Fourth" "Second Third" "Second First" "Second Fifth"
[5] "Fourth Third" "Fourth First" "Fourth Fifth" "Third First"
[9] "Third Fifth" "First Fifth"
Following snippet creates a sample data frame −
Category<-sample(c("Extra Small","Small","Medium","Large","Extra Large"),20,replace=TRUE)
df3<-data.frame(Category)
df3
The following dataframe is created
Category
1 Large
2 Extra Small
3 Extra Small
4 Small
5 Large
6 Extra Small
7 Medium
8 Large
9 Large
10 Extra Large
11 Extra Small
12 Extra Small
13 Extra Small
14 Extra Large
15 Large
16 Extra Small
17 Large
18 Medium
19 Extra Large
20 Extra Large
To find unique pair combinations for values in column Category of df3 on the above created data frame, add the following code to the above snippet −
Category<-sample(c("Extra Small","Small","Medium","Large","Extra Large"),20,replace=TRUE)
df3<-data.frame(Category)
combn(unique(df3$Category),2,FUN=paste,collapse=' ')
If you execute all the above given snippets as a single program, it generates the following Output −
[1] "Large Extra Small" "Large Small"
[3] "Large Medium" "Large Extra Large"
[5] "Extra Small Small" "Extra Small Medium"
[7] "Extra Small Extra Large" "Small Medium"
[9] "Small Extra Large" "Medium Extra Large"
Java Program to display date with day name in short format

Firstly, set the format with SimpleDateFormat class
Format dateFormat = new SimpleDateFormat("EEE, dd/MM/yyyy");
Above, the “EEE” is set to display the name of the day i.e. Monday, Tuesday, Wednesday, etc.
Now, to display the date −
String res = dateFormat.format(new Date());
The following is an example −
 Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
   public static void main(String[] argv) throws Exception {
      Format dateFormat = new SimpleDateFormat("EEE, dd/MM/yyyy");
      String res = dateFormat.format(new Date());
      System.out.println("Date = " + res);
   }
}
Date = Thu, 22/11/2018
Mid-Square hashing in C++.

The mid-square method is a method of generating pseudorandom numbers. This method was invented by John von Neumann and was described at a conference in 1949
In this technique, an initial seed value is taken and it is squared.
In this technique, an initial seed value is taken and it is squared.
Some digits from the middle are extracted and these extracted digits form a number which is taken as the new seed.Let us take 3456 as seed. Its square is 11943936Take the middle 4 digits as new seed i.e. 9439. Its square is 89094721Take middle 4 digits as new seed i.e. 0947Repeat this process
Some digits from the middle are extracted and these extracted digits form a number which is taken as the new seed.
Let us take 3456 as seed. Its square is 11943936
Let us take 3456 as seed. Its square is 11943936
Take the middle 4 digits as new seed i.e. 9439. Its square is 89094721
Take the middle 4 digits as new seed i.e. 9439. Its square is 89094721
Take middle 4 digits as new seed i.e. 0947
Take middle 4 digits as new seed i.e. 0947
Repeat this process
Repeat this process
1. Choose initial seed value
2. Take the square of the seed value
3. Update seed by taking n digits from previous result
#include <iostream>
#include <ctime>
using namespace std;
long long getTime(){
   time_t t = time(NULL);
   struct tm *tm = localtime(&t);
   long long x = (tm->tm_hour) * 50000000 + (tm->tm_min) * 100000 + (tm->tm_sec) * 5000 +
(tm->tm_mday) * 50 + (tm->tm_year);
   return x;
}
long getHash(){
   long long key = getTime();
   key = key * key;
   key = key / 10000;
   key = key % 100000000;
   return key;
}
int main(){
   cout << "Random number: " << getHash() << endl;
   return 0;
}
When you compile and execute the above program. It generates the following output−
Random number: 10088419
Python Program to Create a class performing Calculator Operations

When it is required to create a class that performs calculator operations, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to perform calculator operations.
Below is a demonstration for the same −
 Live Demo
class calculator_implementation():
   def __init__(self,in_1,in_2):
      self.a=in_1
      self.b=in_2
   def add_vals(self):
      return self.a+self.b
   def multiply_vals(self):
      return self.a*self.b
   def divide_vals(self):
      return self.a/self.b
   def subtract_vals(self):
      return self.a-self.b
input_1 = int(input("Enter the first number: "))
input_2 = int(input("Enter the second number: "))
print("The entered first and second numbers are : ")
print(input_1, input_2)
my_instance = calculator_implementation(input_1,input_2)
choice=1
while choice!=0:
   print("0. Exit")
   print("1. Addition")
   print("2. Subtraction")
   print("3. Multiplication")
   print("4. Division")
   choice=int(input("Enter your choice... "))
   if choice==1:
      print("The computed addition result is : ",my_instance.add_vals())
   elif choice==2:
      print("The computed subtraction result is : ",my_instance.subtract_vals())
   elif choice==3:
      print("The computed product result is : ",my_instance.multiply_vals())
   elif choice==4:
      print("The computed division result is : ",round(my_instance.divide_vals(),2))
   elif choice==0:
      print("Exit")
   else:
      print("Sorry, invalid choice!")
print()
Enter the first number: 70
Enter the second number: 2
The entered first and second numbers are :
70 2
0. Exit
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice... 1
The computed addition result is : 72
0. Exit
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice... 2
The computed subtraction result is : 68
0. Exit
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice... 3
The computed product result is : 140
0. Exit
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice... 4
The computed division result is : 35.0
0. Exit
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice... 0
Exit
A class named ‘calculator_implementation’ class is defined, that has functions like ‘add_vals’, ‘subtract_vals’, ‘multiply_vals’, and ‘divide_vals’.
These are used to perform calculator operations such as addition, subtraction, multiplication, and division respectively.
An instance of this class is created.
The value for the two numbers are entered and operations are performed on it.
Relevant messages and output is displayed on the console.
Uri.GetLeftPart() Method in C# with Examples - GeeksforGeeks

28 May, 2020
Uri.GetLeftPart() Method is an instance method that is used to get a specified part from the given URI based on passed UriPartial enum.
Syntax: string Uri.GetLeftPart (UriPartial Part);
Parameters:
Part: It represents UriPartial to get specified part from Uri.
Return Value: This method returns string value to represent specified part of Uri.
Exception: There are two type of exception are:
System.ArgumentException: If the specified part is not valid.
System.InvalidOperationException: If the current Uri instance is not an absolute instance.
Below programs illustrate the use of Uri.GetLeftPart() Method:
Example 1:
C#
// C# program to demonstrate the // Uri.GetLeftPart() Method using System; using System.Globalization;     class GFG {          // Main Method     public static void Main()     {         // Declaring and initializing Uri         Uri  val;                  val = new Uri("https://www.geeksforgeeks.org/data-structure");                  // Use of Uri.GetLeftPart() Method        // Getting the Authority        string str = val.GetLeftPart(UriPartial.Authority);                  Console.WriteLine(str);     } }
Output:
https://www.geeksforgeeks.org

Example 2:
C#
// C# program to demonstrate the // Uri.GetLeftPart() Method using System; using System.Globalization;     class GFG {          // Main Method     public static void Main()     {         // Declaring and initializing Uri         Uri  val;                  val = new Uri("https://www.geeksforgeeks.org/");                  // Use of Uri.GetLeftPart() Method        // Getting the Path        string str1 = val.GetLeftPart(UriPartial.Path);        Console.WriteLine(str1);                   // Getting the Query        string str2 = val.GetLeftPart(UriPartial.Query);        Console.WriteLine(str2);                  // Getting the Scheme        string str3 = val.GetLeftPart(UriPartial.Scheme);        Console.WriteLine(str3);    } }
Output:
https://www.geeksforgeeks.org/
https://www.geeksforgeeks.org/
https://

CSharp-Uri-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Linked List Implementation in C#
Python String | zfill() - GeeksforGeeks

08 Jan, 2018
zfill() method returns a copy of the string with ‘0’ characters padded to the leftside of the given string.
Syntax :
str.zfill(length)

Parameters :
length : length is the length of the returned string from zfill() with ‘0’ digits filled to the leftside.
Return :
Returns a copy of the string with '0' characters   
padded to the leftside of the given string.

CODE 1
text = "geeks for geeks"  print(text.zfill(25))  print(text.zfill(20))  # Given length is less than# the length od original stringprint(text.zfill(10))
Output :
0000000000geeks for geeks
00000geeks for geeks
geeks for geeks

CODE 2
number = "6041"print(number.zfill(8))  number = "+6041"print(number.zfill(8))  text = "--anything%(&%(%)*^"print(text.zfill(20))
Output :
00006041
+0006041
-0-anything%(&%(%)*^

python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Lex program to copy the content of one file to another file - GeeksforGeeks

07 Apr, 2021
Problem: Given a text file as input, the task is to copy the content of the given file to another file. Explanation: Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Approach: As we know, yytext holds the text matched by the current token. Append the value of yytext to a temporary string. If a newline character (‘\n’) is encountered, write the content of temporary string to destination file. Input File: input.txt  
GeeksForGeeks: A Computer Science portal for geeks.
Below is the implementation of above approach: 
C
/* LEX code to replace a word with another   taking input from file */   /* Definition section *//* character array line can be    accessed inside rule section and main() */ %{#include<stdio.h>#include<string.h>char line[100]; %} /* Rule Section *//* Rule 1 writes the string stored in line   character array to file output.txt *//* Rule 2 copies the matched token   i.e every character except newline character    to line character array  */ %%['\n']    { fprintf(yyout,"%s\n",line);}(.*)      { strcpy(line,yytext); line[0] = '\0'; }<<EOF>> { fprintf(yyout,"%s",line); return 0;}%%  int yywrap(){    return 1;} /* code section */int main(){        extern FILE *yyin, *yyout;        /* open the source file           in read mode */    yyin=fopen("input.txt","r");                  /* open the output file           in write mode */    yyout=fopen("output.txt","w");    yylex();}
Output: 
Output file: output.txt  
GeeksForGeeks: A Computer Science portal for geeks.
 
y_27
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
S - attributed and L - attributed SDTs in Syntax directed translation
Issues in the design of a code generator
Error Handling in Compiler Design
Error detection and Recovery in Compiler
Difference between Top down parsing and Bottom up parsing
Runtime Environments in Compiler Design
Loop Optimization in Compiler Design
Why FIRST and FOLLOW in Compiler Design?
Bottom Up or Shift Reduce Parsers | Set 2
Extracting MAC address using Python - GeeksforGeeks

31 Mar, 2020
MAC address also known as physical address is the unique identifier that is assigned to the NIC (Network Interface Card) of the computer. NIC helps in connection of a computer with other computers in the network. MAC address is unique for all the NIC’s.
Uses of MAC address :
Useful in places where IP address change frequently. Helps network admin. to get information regarding network traffic.
Helps us to configure which computers can be connected to our computers. By this way we can filter potential spam/virus attacks.
Helps in uniquely identifying computers from other computers around the world.
This article aims at extracting MAC address of computer using Python.
Method 1 : using mac moduleTo get the physical address of the device we use getmac module of Python.
>>>from getmac import get_mac_address as gma
>>>print(gma())
'3c:7e:94:8f:d0:34'
Method 2 : Using uuid.getnode()
getnode() can be used to extract the MAC address of the computer. This function is defined in uuid module.The illustrated code given below shows how to generate a UUID for a given host, identified by its MAC address, using the uuid1() function.
# Python Program to compute# MAC address of host# using UUID module  import uuid  # printing the value of unique MAC# address using uuid and getnode() function print (hex(uuid.getnode()))
Output :
0x163e990bdb

Drawback :
The visible drawback is that the output is not in the formatted form.
Method 3 : Using getnode() + format() [ for better formatting ]
# Python 3 code to print MAC# in formatted way.  import uuid  # joins elements of getnode() after each 2 digits.  print ("The MAC address in formatted way is : ", end="")print (':'.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff)for ele in range(0,8*6,8)][::-1]))
Output :
The MAC address in formatted way is : 00:16:3e:99:0b:db

Drawback :
This code appears to be complex.
Method 4 : Using getnode() + findall() + re() [ for reducing complexity ]
# Python 3 code to print MAC# in formatted way and easier# to understand  import re, uuid  # joins elements of getnode() after each 2 digits.# using regex expressionprint ("The MAC address in formatted and less complex way is : ", end="")print (':'.join(re.findall('..', '%012x' % uuid.getnode())))
Output :
The MAC address in formatted and less complex way is : 00:16:3e:99:0b:db

DivyaVishwakarma1
Computer Networks
Python
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
RSA Algorithm in Cryptography
Differences between TCP and UDP
TCP Server-Client implementation in C
Data encryption standard (DES) | Set 1
Differences between IPv4 and IPv6
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python - Add Phrase in middle of String - GeeksforGeeks

25 Oct, 2020
Given a String, add a phrase in the middle of it.
Input : test_str = ‘geekforgeeks is for geeks’, mid_str = “good” Output : geekforgeeks is good for geeks Explanation : Added just in middle, after 2 words.
Input : test_str = ‘geekforgeeks best’, mid_str = “is” Output : geekforgeeks is best Explanation : Added just in middle, after 1 word. 
Method #1 : Using split() + slicing + join()
In this, Strings are converted to a list of words, then the middle position is extracted to append a new phrase. After addition, the string is back converted using join().
Python3
# Python3 code to demonstrate working of# Add Phrase in middle of String# Using split() + slicing + join()  # initializing stringtest_str = 'geekforgeeks is for geeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing mid stringmid_str = "best"  # splitting string to listtemp = test_str.split()mid_pos = len(temp) // 2  # appending in midres = temp[:mid_pos] + [mid_str] + temp[mid_pos:]  # conversion backres = ' '.join(res)  # printing resultprint("Formulated String : " + str(res))
The original string is : geekforgeeks is for geeks
Formulated String : geekforgeeks is best for geeks

Method #2 : Using split() + slicing + join() [ more compact]
Similar to the above method, just one-liner way to solve this problem, for more compact.
Python3
# Python3 code to demonstrate working of# Add Phrase in middle of String# Using split() + slicing + join()  # initializing stringtest_str = 'geekforgeeks is for geeks'  # printing original stringprint("The original string is : " + str(test_str))  # initializing mid stringmid_str = "best"  # splitting string to listtemp = test_str.split()mid_pos = len(temp) // 2  # joining and construction using single lineres = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:])  # printing resultprint("Formulated String : " + str(res))
The original string is : geekforgeeks is for geeks
Formulated String : geekforgeeks is best for geeks

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
context_click - Action Chains in Selenium Python - GeeksforGeeks

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around context_click method on Action Chains in Python Selenium. context_click method is used to perform a context-click (right click) on an element.
Syntax –
context_click(on_element=None)
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd")
Now one can use context_click method as an Action chain as below –
context_click(on_element=element)

To demonstrate, context_click method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver  # import Action chains from selenium.webdriver.common.action_chains import ActionChains  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # create action chain objectaction = ActionChains(driver)  # context click the itemaction.context_click(on_element = element)  # perform the operationaction.perform()
Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Python | Split URL from Query Parameters - GeeksforGeeks

07 Feb, 2022
Sometimes, while web development, we can come across a task in which we may require to perform a split of query parameters from URLs which is done by ‘?’ character. This has application over web development as well as other domains which involve URLs. Lets discuss certain ways in which this task can be performed.Method #1 : Using split() This is one of the way in which we can solve this problem. We split by ‘?’ and return the first part of split for result. 
Python3
# Python3 code to demonstrate working of# Split URL from Query Parameters# Using split() # initializing stringtest_str = 'www.geeksforgeeks.org?is = best' # printing original stringprint("The original string is : " + str(test_str)) # Split URL from Query Parameters# Using split()res = test_str.split('?')[0] # printing resultprint("The base URL is : " + res)
The original string is : www.geeksforgeeks.org?is=best
The base URL is : www.geeksforgeeks.org
 
 Method #2 : Using rfind() This is another way in which we need to perform this task. In this, we find the first occurrence of ‘?’ from right and slice the string. 
Python3
# Python3 code to demonstrate working of# Split URL from Query Parameters# Using rfind() # initializing stringtest_str = 'www.geeksforgeeks.org?is = best' # printing original stringprint("The original string is : " + str(test_str)) # Split URL from Query Parameters# Using rfind()res = test_str[:test_str.rfind('?')] # printing resultprint("The base URL is : " + res)
The original string is : www.geeksforgeeks.org?is=best
The base URL is : www.geeksforgeeks.org
 
saurabh1990aror
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Matplotlib.pyplot.clim() in Python - GeeksforGeeks

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.
The clim() function in pyplot module of matplotlib library is used to set the color limits of the current image.
Syntax: matplotlib.pyplot.clim(vmin=None, vmax=None)
Parameters: This method accepts only two parameters.
vmin, vmax : These parameters are used for color scaling.
Below examples illustrate the matplotlib.pyplot.clim() function in matplotlib.pyplot:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm    dx, dy = 0.015, 0.05y, x = np.mgrid[slice(-4, 4 + dy, dy),                slice(-4, 4 + dx, dx)]  z = (1 - x / 3. + x ** 5 + y ** 5) * np.exp(-x ** 2 - y ** 2)z = z[:-1, :-1]z_min, z_max = -np.abs(z).max(), np.abs(z).max()          im = plt.imshow(z, cmap ='Greens',                 vmin = z_min,                 vmax = z_max,                extent = [x.min(),                          x.max(),                           y.min(),                           y.max()],                interpolation ='nearest',                origin ='lower')  plt.clim(vmin = 0, vmax = 2)plt.title('matplotlib.pyplot.clim Example')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm    dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y)   extent = np.min(x), np.max(x), np.min(y), np.max(y)   Z1 = np.add.outer(range(8), range(8)) % 2plt.imshow(Z1,            cmap ="binary_r",           interpolation ='nearest',           extent = extent, alpha = 1)   def geeks(x, y):    return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2))   Z2 = geeks(X, Y)   plt.imshow(Z2, cmap ="Greens",            alpha = 0.7,           interpolation ='bilinear',           extent = extent)  plt.clim(0, 2)plt.title('matplotlib.pyplot.clim Example')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
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Haskell - Input & Output

All the examples that we have discussed so far are static in nature. In this chapter, we will learn to communicate dynamically with the users. We will learn different input and output techniques used in Haskell.
We have so far hard-coded all the inputs in the program itself. We have been taking inputs from static variables. Now, let us learn how to read and write from an external file.
Let us create a file and name it "abc.txt". Next, enter the following lines in this text file: "Welcome to Tutorialspoint. Here, you will get the best resource to learn Haskell."
Next, we will write the following code which will display the contents of this file on the console. Here, we are using the function readFile() which reads a file until it finds an EOF character.
main = do  
   let file = "abc.txt" 
   contents <- readFile file 
   putStrLn contents   
The above piece of code will read the file "abc.txt" as a String until it encounters any End of File character.  This piece of code will generate the following output.
Welcome to Tutorialspoint
Here, you will get the best resource to learn Haskell.

Observe that whatever it is printing on the terminal is written in that file.
Haskell also provides the facility to operate a file through the command prompt. Let us get back to our terminal and type "ghci". Then, type the following set of commands −
let file = "abc.txt" 
writeFile file "I am just experimenting here." 
readFile file 

Here, we have created a text file called "abc.txt". Next, we have inserted a statement in the file using the command writeFile. Finally, we have used the command readFile to print the contents of the file on the console. Our code will produce the following output −
I am just experimenting here.

An exception can be considered as a bug in the code. It is a situation where the compiler does not get the expected output at runtime. Like any other good programming language, Haskell provides a way to implement exception handling.
If you are familiar with Java, then you might know the Try-Catch block where we usually throw an error and catch the same in the catch block. In Haskell, we also have the same function to catch runtime errors.
The function definition of try looks like "try :: Exception e => IO a -> IO (Either e a)". Take a look at the following example code. It shows how you can catch the "Divide by Zero" exception.
import Control.Exception 

main = do 
   result <- try (evaluate (5 `div` 0)) :: IO (Either SomeException Int) 
   case result of 
      Left ex   -> putStrLn $ "Caught exception: " ++ show ex 
      Right val -> putStrLn $ "The answer was: " ++ show val 
In the above example, we have used the inbuilt try function of the Control.Exception module, hence we are catching the exception beforehand. Above piece of code will yield below output in the screen.
Caught exception: divide by zero 

 Print
 Add Notes
 Bookmark this page
How can I change the font family and font size with jQuery?

To change the font family and font size with jQuery, use the jQuery css() method. The css property font-family and font-size is used. You can try to run the following code to learn how to change font family and font size with jQuery −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
   $("p").on({
     mouseenter: function() {
        $(this).css({"font-family": "Arial, Helvetica, sans-serif", "font-size": "200%"});
     }
   });    
});
</script>
</head>
<body>
<p>Move the mouse pointer on the text to change the font family and size.</p>
</body>
</html>
How to calculate an average value across database rows in MySQL?

For this, you can use AVG(). Following is the syntax −
select avg(yourColumnName1) as anyAliasName1,
avg(yourColumnName2) as anyAliasName2,
avg(yourColumnName3) as anyAliasName3,
.
.
N
from yourTableName;
Let us create a table −
mysql> create table demo31
−> (
−> value1 int,
−> value2 int,
−> value3 int
−> );
Query OK, 0 rows affected (2.27 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo31 values(34,55,67);
Query OK, 1 row affected (0.27 sec)

mysql> insert into demo31 values(50,60,70);
Query OK, 1 row affected (0.16 sec)

mysql> insert into demo31 values(100,200,300);
Query OK, 1 row affected (0.14 sec)

mysql> insert into demo31 values(10,300,200);
Query OK, 1 row affected (0.15 sec)
Display records from the table using select statement −
mysql> select *from demo31;
This will produce the following output −
+--------+--------+--------+
| value1 | value2 | value3 |
+--------+--------+--------+
|     34 |     55 |     67 |
|     50 |     60 |     70 |
|    100 |    200 |    300 |
|     10 |    300 |    200 |
+--------+--------+--------+
4 rows in set (0.00 sec)
Following is the query to calculate an average value across database rows −
mysql> select avg(value1) as Value1_AVG,
−> avg(value2) as Value2_AVG,
−> avg(value3) as Value3_AVG
−> from demo31;
This will produce the following output −
+------------+------------+------------+
| Value1_AVG | Value2_AVG | Value3_AVG |
+------------+------------+------------+
| 48.5000    | 153.7500   | 159.2500   |
+------------+------------+------------+
1 row in set (0.00 sec)
Batch Script - Create String

A string can be created in DOS in the following way.
@echo off 
:: This program just displays Hello World 
set message = Hello World 
echo %message%
The above command produces the following output.
Hello World

 Print
 Add Notes
 Bookmark this page
TypeScript - Array sort()

sort() method sorts the elements of an array.
array.sort( compareFunction );

compareFunction − Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically.
Returns a sorted array.
var arr = new Array("orange", "mango", "banana", "sugar"); 
var sorted = arr.sort(); 
console.log("Returned string is : " + sorted );

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Returned string is : banana,mango,orange,sugar


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page