code-rag-bench/online-tutorials huggingface dataset:
Minimum operation to make all elements equal in array in C++

Given an array with n positive integers. We need to find the minimum number of operation to make all elements equal. We can perform addition, multiplication, subtraction or division with any element on an array element.
If input array is = {1, 2, 3, 4} then we require minimum 3 operations to make all elements equal. For example, we can make elements 4 by doing 3 additions.
1. Select element with maximum frequency. Let us call it ‘x’
2. Now we have to perform n-x operations as there are x element with same value
 Live Demo
#include
using namespace std;
int getMinOperations(int *arr, int n) {
   unordered_map hash;
   for (int i = 0;i < n; ++i) {
      hash[arr[i]]++;
   }
   int maxFrequency = 0;
   for (auto elem : hash) {
      if (elem.second > maxFrequency) {
         maxFrequency = elem.second;
      }
   }
   return (n - maxFrequency);
}
int main() {
   int arr[] = {1, 2, 3, 4};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Minimum required operations = " <<
   getMinOperations(arr, n) << endl;
   return 0;
}
When you compile and execute above program. It generates following output
Minimum required operations = 3
Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python - GeeksforGeeks

23 Aug, 2021
In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this  task strptime() and strftime() function is used.
strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds
Syntax:
datetime.strptime(my_date, “%d-%b-%Y-%H:%M:%S”)
strftime() is used to convert DateTime into required timestamp format
Syntax:
datetime.strftime(“%Y-%m-%d-%H:%M:%S”)
Here,
&Y means year
%m  means month
%d means day
%H means hours
%M means minutes
%S means seconds.
First the take DateTime timestamp as a String. Then, convert it into DateTime using strptime(). Now, convert into the necessary format of DateTime using strftime
Example 1: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format
Python3
# import datetime modulefrom datetime import datetime  # consider date in string formatmy_date = "30-May-2020-15:59:02"  # convert datetime string into date,month,day and# hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")  # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S"))
Output
'2020-05-30-15:59:02'
Example 2: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format
Python3
# import datetime modulefrom datetime import datetime  # consider date in string formatmy_date = "30-May-2020-15:59:02"  # convert datetime string into date,month,day # and hours:minutes:and seconds format using# strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")  # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S"))  # consider date in string formatmy_date = "04-Jan-2021-02:45:12"  # convert datetime string into date,month,day # and hours:minutes:and seconds format using # strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")  # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S"))  # consider date in string formatmy_date = "23-May-2020-15:59:02"  # convert datetime string into date,month,day and # hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")  # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S"))
2020-05-30-15:59:02
2021-01-04-02:45:12
2020-05-23-15:59:02

Picked
Python-datetime
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
Implement Stack using Queues in C++

Suppose we want to implement one stack using a queue. We have to define these methods for the stack.
push(x) − Push x onto stack.
push(x) − Push x onto stack.
pop() − Delete and return top element from stack
pop() − Delete and return top element from stack
top() − Return the top element from stack.
top() − Return the top element from stack.
empty() − Return whether the stack is empty or not.
empty() − Return whether the stack is empty or not.
So, if we call the functions push(10), push(20), then call pop(), pop(), then the output will be 20, 10
To solve this, we will follow these steps −
Define one deque q
Define one deque q
Define a function push(), this will take x,
Define a function push(), this will take x,
insert x at the beginning of q
insert x at the beginning of q
Define a function pop()
Define a function pop()
k := first element of q
k := first element of q
delete front element from q
delete front element from q
return k
return k
Define a function top()
Define a function top()
return first element of q
return first element of q
Define a function empty()
Define a function empty()
if q is empty, then −return true
if q is empty, then −
return true
return true
Otherwisereturn false
Otherwise
return false
return false
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class MyStack {
private:
   deque<int> q;
public:
   void push(int x){
      q.push_front(x);
   }
   int pop(){
      int k = q.front();
      q.pop_front();
      return k;
   }
   int top(){
      return q.front();
   }
   bool empty(){
      if (q.empty())
         return true;
      else
         return false;
   }
};
main(){
   MyStack ob;
   ob.push(10);
   ob.push(20);
   cout << (ob.pop()) << endl;
   cout << (ob.pop()) << endl;
}
push(10),push(20),pop(),pop()
20
10
How to invert an object in JavaScript?

Inverting an object is one of the difficult tasks until underscore.js, a javascript framework, came into light. It has many functions in which _.invert() is one of them. This method actually inverts the key/value pairs. For suppose let an object has a key/value like name/Kiran. Then after inverting the object using _.invert() method the key/value pair changes into Kiran/name. Lets' discuss it, in a nutshell, using examples.
_.invert(object);
This method takes an object as an argument and inverts it. It changes the key/value pair into value/key pair.
In the following example 'name', 'salary' and 'age' of a person were inverted into their value/key pairs.
Live Demo
<html>
<body>
<script
   src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
<script>
   var res = JSON.stringify(_.invert({name: 'Raj', age: 38, "salary": 120000}));
   document.write((res));
</script>
</body>
</html>
{"38":"age","120000":"salary","Raj":"name"}
In the following example 'name', 'Organization' and 'age' of a person were inverted into their value/key pairs.
Live Demo
<html>
<body>
<script  
   src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
   <script type="text/javascript">
      var res = JSON.stringify(_.invert({"name": 'ElonMusk',age: 47, "Organization":'Spacex' }));
      document.write((res));
   </script>
</body>
</html>
{"47":"age","ElonMusk":"name","Spacex":"Organization"}
Perl | sort() Function - GeeksforGeeks

07 May, 2019
sort() function in Perl is used to sort a list with or without the use of method of sorting. This method can be specified by the user in the form of subroutines or blocks. If a subroutine or block is not specified then it will follow the default method of sorting.
Syntax:sort Listsort block, Listsort Subroutine, List
Returns: sorted list as per user’s requirement
Example 1:
#!/usr/bin/perl  @array1 = ("a", "d", "h", "e", "b");  print "Original Array: @array1\n";print ("Sorted Array: ", sort(@array1));
Original Array: a d h e b
Sorted Array: abdeh

 Example 2: Use of Block to sort
#!/usr/bin/perl -wuse warnings;use strict;  # Use of Block to sort my @numeric = sort { $a <=> $b } (2, 11, 54, 6, 35, 87);  print "@numeric\n";
2 6 11 35 54 87

In the above code, block is used to sort because sort() function uses characters to sort the strings, but in numerical context, it is not possible to follow the same. Hence, block is used to ease the sort. Example 3: Use of Subroutine to sort
#!/usr/bin/perl -wuse warnings;use strict;  # Calling subroutine to sort numerical arraymy @numerical = sort compare_sort (2, 11, 54, 6, 35, 87);print "@numerical\n";   # function to compare two numberssub compare_sort{   if($a < $b)   {      return -1;   }   elsif($a == $b)   {      return 0;   }   else   {      return 1;                          }}
2 6 11 35 54 87

Perl-function
Perl-List-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl Tutorial - Learn Perl With Examples
Perl | Writing to a File
Perl | Multidimensional Hashes
Perl | Operators | Set - 1
Perl | File Handling Introduction
Perl | index() Function
Perl | Reading Excel Files
Perl | Special Character Classes in Regular Expressions
Perl | Data Types
Perl | Appending to a File
Dot Product of Vectors in R Programming - GeeksforGeeks

25 Aug, 2020
In mathematics, the dot product or also known as the scalar product is an algebraic operation that takes two equal-length sequences of numbers and returns a single number. Let us given two vectors A and B, and we have to find the dot product of two vectors.
Given that, 
and,
where,
i: the unit vector along the x directions
j: the unit vector along the y directions
k: the unit vector along the z directions
Then the dot product is calculated as:
Example:
Given two vectors A and B as,
A = 3i + 5j + 4k,
and
B = 2i + 7j + 5k
Dot Product = 3 * 2 + 5 * 7 + 4 * 5 = 6 + 35 + 20 + 61 
R language provides a very efficient method to calculate the dot product of two vectors. By using dot() method which is available in the geometry library one can do so.
Syntax: dot(x, y, d = NULL)
Parameters:
x: Matrix of vectors
y: Matrix of vectors
d: Dimension along which to calculate the dot product
Return: Vector with length of dth dimension
Example 1:
R
# R Program illustrating# dot product of two vectors  # Import the required librarylibrary(geometry)  # Taking two scalar valuesa = 5b = 7  # Calculating dot product using dot()print(dot(a, b, d = TRUE))
Output:
[1] 35

Example 2:
R
# R Program illustrating# dot product of two vectors  # Import the required librarylibrary(geometry)  # Taking two complex valuesa = 3 + 1ib = 7 + 6i  # Calculating dot product using dot()print(dot(a, b, d = TRUE))
Output:
[1] 15+25i

Example 3:
R
# R Program illustrating# dot product of two vectors  # Import the required librarylibrary(geometry)  # Taking two simple vectorsa = c(1, 4)b = c(7, 4)  # Calculating dot product using dot()print(dot(a, b, d = TRUE))
Output:
[1] 23

Example 4:
In this following example let’s take two 2D arrays and calculate the dot product of these two. To create a 2D array in R please refer Multidimensional Array in R.
R
# R Program illustrating# dot product of two vectors  # Import the required librarylibrary(geometry)  # Taking two 2D arrayvector1 = c(2, 1)vector2 = c(0, 3)a = array(c(vector1, vector2), dim = c(2, 2))vector1 = c(4, 2)vector2 = c(9, 3)b = array(c(vector1, vector2), dim = c(2, 2))  # Calculating dot product using dot()print(dot(a, b, d = TRUE))
Output:
[1] 10  9

R Vector-Function
R-Vectors
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Replace Specific Characters in String in R
What are the differences between a JTextField and a JFormattedTextField in Java?

A JTextField can be used for plain text whereas a JFormattedTextField is a class that can extend JTextField and it can be used to set any format to the text that it contains phone numbers, e-mails, dates and etc.
A JTextFeld is one of the most important components that allow the user to type an input text value in a single line format.
A JTextField can generate an ActionListener interface when we try to enter some input inside the text field and it can generate a CaretListener interface each time the caret (i.e. the cursor) changes position.
A JTextField can also generate a MouseListener and KeyListener interfaces.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextFieldTest extends JFrame {
   JTextField jtf;
   public JTextFieldTest() {
      setTitle("JTextField Test");
      setLayout(new FlowLayout());
      jtf = new JTextField(15);
      add(jtf);
      jtf.addActionListener(new ActionListener() {
         public void actionPerformed (ActionEvent ae) {
            System.out.println("Event generated: " + jtf.getText());
         }
      });
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JTextFieldTest();
   }
}
A formatted text field is an instance of the class JFormattedTextField which is a direct subclass of JTextField.
A JFormattedTextField is like a normal text field except that is controls the validity of the characters the user type and it can be associated with a formatter that specifies the characters the user can enter.
A JFormattedTextField is a subclass of Format class to build a formatted text field. We can create a formatter, customize it if necessary. We can call the JFormattedTextField(Format format) constructor which takes an argument of type Format.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JFormattedTextFieldTest extends JFrame {
   JFormattedTextField jftf;
   MaskFormatter mf;
   public JFormattedTextFieldTest() {
      setTitle("JFormattedTextField Test");
      setLayout(new FlowLayout());
      // A phone number formatter - (country code)-(area code)-(number)
      try {
         mf = new MaskFormatter("##-###-#######");
         mf.setPlaceholderCharacter('#');
         jftf = new JFormattedTextField(mf);
         jftf.setColumns(12);
      } catch(Exception e) {
         e.printStackTrace();
      }
      add(jftf);
      setSize(375, 250);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JFormattedTextFieldTest();
   }
}
Swing Examples - Creating Toggle Button

A Toggle Button is a two state button. It is either pressed or not pressed. Following example showcase how to modify the default appearance of a Button in a Java Swing application.
We are using the following APIs.
JToggleButton() − To create a toggle button.
JToggleButton() − To create a toggle button.
JToggleButton.isSelected() − To check if toggle button is currently in pressed state or not.
JToggleButton.isSelected() − To check if toggle button is currently in pressed state or not.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class SwingTester {
   public static void main(String[] args)  {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       
      final JToggleButton toggleButton = new JToggleButton("Click Me!");     
      toggleButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(frame, ((JToggleButton)e.getSource()).isSelected());
         }
      });
      panel.add(toggleButton);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}
 Print
 Add Notes
 Bookmark this page
Write a C program to reduce any fraction to least terms using while loop

Reducing the fraction to the lowest terms means that there is no number, except 1, that can be divided evenly into both the numerator and the denominator.
For example, 24/4 is a fraction, the lowest term for this fraction is 6, or 12/16 is a fraction the lowest term is 3/4.
Now let’s write a c program to reduce the fraction into their lowest terms.
 Live Demo
#include<stdio.h>
int main(){
   int x,y,mod,numerat,denomi,lessnumert,lessdenomi;
   printf("enter the fraction by using / operator:");
   scanf("%d/%d", &x,&y);
   numerat=x;
   denomi=y;
   switch(y){
      case 0:printf("no zero's in denominator\n");
      break;
   }
   while(mod!=0){
      mod= x % y;
      x=y;
      y=mod;
   }
   lessnumert= numerat/x;
   lessdenomi=denomi/x;
   printf("lowest representation of fraction:%d/%d\n",lessnumert,lessdenomi);
   return 0;
}
enter the fraction by using / operator:12/24
lowest representation of fraction:1/2
//reduce the Fraction
#include <stdio.h>
int main() {
   int num1, num2, GCD;
   printf("Enter the value for num1 /num2:");
   scanf("%d/%d", &num1, &num2);
   if (num1 < num2){
      GCD = num1;
   } else {
      GCD = num2;
   }
   if (num1 == 0 || num2 == 0){
      printf("simplified fraction is %s\n", num1?"Infinity":"0");
   }
   while (GCD > 1) {
      if (num1 % GCD == 0 && num2 % GCD == 0)
         break;
      GCD--;
   }
   printf("Final fraction %d/%d\n", num1 / GCD, num2 / GCD);
   return 0;
}
Enter the value for num1 /num2:28/32
Final fraction 7/8
Bitwise AND and OR in Arduino

Bitwise AND/ OR means AND/ OR performed at a bit-level, individually. Each number has its binary representation. When you perform the bitwise AND of one number with another, the AND operation is performed on the corresponding bits of the two numbers. Thus, LSB of number 1 is ANDed with the LSB of number 2, and so on.
The bitwise AND operation in Arduino is & and the bitwise OR operator is |.
a & b
for AND.
a | b
for OR.
The truth table for AND is
The truth table for OR is −
Since these are bitwise operators, we need to perform this for each bit.
For example, if I have to perform 10 & 3, this is how the operation will look like
As you can see, the AND operator is performed for each of the corresponding bits individually.
Similarly, the operation for 10 | 3 will look like the following −
Please note that this actually applies to all the bits of the number (even the leading 0s). Thus, if your board uses 16-bits to represent an integer, the actual operation (for 10 & 3) will look like −
Same applies for the | operation.
Let’s verify this through Arduino. The code is given below −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   int a = 10;
   int b = 3;
   Serial.println(a & b);
   Serial.println(a | 3);
}
void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, the output is exactly what we expected.
How to Extract Time from Datetime in R ?

30 Jun, 2021
In this article, we are going to extract time from Datetime in R programming language using lubridate() function and format() function.
Note: datetime is in the format of time and date (YYYY/MM/DD HH:MM:SS) i.e. Year:month:day Hours:Minute:Seconds
Where,
Year:month:day comes under date
Hours:Minute:Seconds comes under time
We are going to extract only time and for that create a variable and assign a timestamp to it. Then, extract time from the timestamp. We can do this by using as.POSIXct() function. To get a particular time hour format we can use format() function
Syntax:
format(as.POSIXct(data), format = “%H:%M”)
Parameter:
as.POSIXct() is used to extract time from the time stamp
format is used to get the time format. Ex : hours:Minutes and secondsformat = “%H:%M:%S” (To get hours: minutes :seconds)format = “%H:%M” (To get hours: minutes )format = “%H” (To get hours)
format = “%H:%M:%S” (To get hours: minutes :seconds)
format = “%H:%M” (To get hours: minutes )
format = “%H” (To get hours)
data is the time stamp
Example 1:
R
# create variable with one time stamp data ="2021/05/25 12:34:25"                             # get time from date using format in the # form of hoursprint(paste(  "Hours : ", format(as.POSIXct(data), format = "%H")))  # get time from date using format in the # form of minutesprint(paste(  "Minutes : ", format(as.POSIXct(data), format = "%M")))  # get time from date using format in the # form of secondsprint(paste(  "Seconds : ", format(as.POSIXct(data), format = "%S")))  # get time from date using format in the # form of minutesprint(paste(  "Hours and Minutes : ", format(as.POSIXct(data), format = "%H:%M")))  # get time from date using format in the # form of secondsprint(paste(  "Time : ", format(as.POSIXct(data), format = "%H:%M:%S")))
Output:
Example 2:
R
# create vector that stores five time stampsdata =c("2021/05/25 12:34:25","2022/05/25 11:39:25",        "2011/05/25 08:31:25","2013/04/13 1:34:25",        "2018/05/25 12:34:25")                             # get time from date using format in the# form of secondsprint(paste("Time : ", format(  as.POSIXct(data), format = "%H:%M:%S")))
Output:
lubridate() package is used to return the time from the datetime individually. It will return hour, minute, and second separately.
To get hour from the datetime we will use hour command
Syntax:
hour(datetime)
Returns the time in hours
To get minutes from the datetime we will use minute command
Syntax:
minute(datetime)
Returns the time in minutes
To get seconds from the datetime we will use second command
Syntax:
second(datetime)
Returns the time in seconds
Example 1:
R
# load the packagelibrary('lubridate')  # datetime variabledata ="2021/05/25 12:34:25"  # extract hourhour(data)  # extract minuteminute(data)  # extract the secondsecond(data)
Output:
Picked
R-DateTime
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Run Length Encoding in Python

31 Mar, 2020
Given an input string, write a function that returns the Run Length Encoded string for the input string.
For example, if the input string is ‘wwwwaaadexxxxxx’, then the function should return ‘w4a3d1e1x6’.
Examples:
Input  :  str = 'wwwwaaadexxxxxx'
Output : 'w4a3d1e1x6'

This problem has existing solution please refer Run Length Encoding link. Here we will solve this problem quickly in python using OrderedDict. Approach is very simple, first we create a ordered dictionary which contains characters of input string as key and 0 as their default value, now we run a loop to count frequency of each character and will map it to it’s corresponding key.
# Python code for run length encodingfrom collections import OrderedDictdef runLengthEncoding(input):      # Generate ordered dictionary of all lower    # case alphabets, its output will be     # dict = {'w':0, 'a':0, 'd':0, 'e':0, 'x':0}    dict=OrderedDict.fromkeys(input, 0)      # Now iterate through input string to calculate     # frequency of each character, its output will be     # dict = {'w':4,'a':3,'d':1,'e':1,'x':6}    for ch in input:        dict[ch] += 1      # now iterate through dictionary to make     # output string from (key,value) pairs    output = ''    for key,value in dict.items():         output = output + key + str(value)    return output   # Driver functionif __name__ == "__main__":    input="wwwwaaadexxxxxx"    print (runLengthEncoding(input))
Output:
'w4a3d1e1x6'

Another code:
def encode(message):    encoded_message = ""    i = 0       while (i <= len(message)-1):        count = 1        ch = message[i]        j = i        while (j < len(message)-1):            if (message[j] == message[j+1]):                count = count+1                j = j+1            else:                break        encoded_message=encoded_message+str(count)+ch        i = j+1    return encoded_message  #Provide different values for message and test your programencoded_message=encode("ABBBBCCCCCCCCAB")print(encoded_message)
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
gayatrivgk
String-Run Length Encoding
Python
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python String – removeprefix() function

12 Nov, 2020
In this article we will use str.removeprefix(prefix, /) function which removes the prefix and returns the rest of the string. If the prefix string is not found then it returns the original string. It is introduced in Python 3.9.0 version.
Syntax:
str.removeprefix(prefix, /)

Parameters:
suffix- prefix string that we are checking for.

Return value:
Returns string[len(prefix):] otherwise the copy of the original string.
Code:
Example 1:
Python3
# Python 3.9 code explaining # str.removeprefix()  s = 'GeeksforGeeks'  # prefix existsprint(s.removeprefix('Geeks'))print(s.removeprefix('G'))    # whole string is a prefix# it would print an empty stringprint(s.removeprefix('GeeksforGeeks'))  # prefix doesn't exist# whole string is returnedprint(s.removeprefix('for'))print(s.removeprefix('IT'))print(s.removeprefix('forGeeks'))
Output:
forGeeks
eeksforGeeks

GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

Example 2:
Python3
# Python 3.9 code explaining # str.removeprefix()  # String for removeprefix() # If prefix exists then # remove prefix from the string # otherwise return original string     string1 = "Welcome to python 3.9"print("Original String 1 : ", string1)     # prefix exists result = string1.removeprefix("Welcome") print("New string : ", result)     string2 = "Welcome Geek"print("Original String 2 : ", string2)     # prefix doesn't exist result = string2.removeprefix("Geek") print("New string : ", result)
Output:
Original String 1 :  Welcome to python 3.9
New string :   to python 3.9
Original String 2 :  Welcome Geek
New string :  Welcome Geek

Python-string-functions
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Grouping dropdown options using ReactJS - GeeksforGeeks

18 Jan, 2021
Grouping options means putting options in groups based on conditions for a better user experience. For example on our mobile, all contacts are grouped by their first letter so that it becomes easier for users to search for contacts. Material UI for React has this component available for us and it is very easy to integrate.
Creating React Application and Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
npm install @material-ui/lab
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react'import TextField from '@material-ui/core/TextField';import Autocomplete from '@material-ui/lab/Autocomplete';  const App = () => {    const myOptions = [    { title: 'Gourav', age: 20 },    { title: 'Dinesh', age: 25 },    { title: 'Madhuri', age: 18 },    { title: 'Kartik', age: 21 },    { title: 'Gaurank', age: 5 },  ];    // Our sample dropdown options  const options = myOptions.map((option) => {    const initialLetter = option.title[0].toUpperCase();    return {      initialLetter: /[0-9]/.test(initialLetter) ?       '0-9' : initialLetter,      ...option,    };  });    return (    <div style={{ marginLeft: '40%', marginTop: '60px' }}>      <h3>Greetings from GeeksforGeeks!</h3>      <Autocomplete        style={{ width: 600 }}        options={options.sort((a, b) =>          -b.initialLetter.localeCompare(a.initialLetter))}        groupBy={(option) => option.initialLetter}        getOptionLabel={(option) => option.title}        renderInput={(params) => <TextField {...params}          label="Grouping Demo"          variant="outlined" />}      />    </div>  );}  export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
JavaScript
ReactJS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
Why "&" is not used for strings in scanf() function? - GeeksforGeeks

29 Dec, 2021
Below is syntax of Scanf. It requires two arguments: 
scanf("Format Specifier", Variable Address);

Format Specifier: Type of value to expect while input
Variable Address: &variable returns the variable's memory address.
In case of a string (character array), the variable itself points to the first element of the array in question. Thus, there is no need to use the ‘&’ operator to pass the address.  
C
// C program to illustrate  not using "&"// in scanf statement#include<stdio.h>int main(){    char name[25];     // Syntax to scan a String    scanf("%s", name);     // Comparing base address of String with address    // of first element of array which must return    // true as both must be same    printf("(Is Base address = address of first element)? \n %d",           (name == &name[0])); }
Output:  
(Is Base address = address of first element)?
1
Important Points
‘&’ is used to get the address of the variable. C does not have a string type, String is just an array of characters and an array variable stores the address of the first index location.By default the variable itself points to the base address and therefore to access base address of string, there is no need of adding an extra ‘&’
‘&’ is used to get the address of the variable. C does not have a string type, String is just an array of characters and an array variable stores the address of the first index location.
By default the variable itself points to the base address and therefore to access base address of string, there is no need of adding an extra ‘&’
This article is contributed by Ajeet. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
surinderdawra388
C-String
cpp-input-output
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Smart Pointers in C++ and How to Use Them
Ways to copy a vector in C++
Multiple Inheritance in C++
Understanding "extern" keyword in C
How to split a string in C/C++, Python and Java?
Modular Addition - GeeksforGeeks

12 Aug, 2020
Below are some interesting properties of Modular Addition:  
(a + b) mod m = ((a mod m) + (b mod m)) mod m (a + b + c) mod m = ((a mod m) + (b mod m) + (c mod m)) mod m  
Example 1: Find the remainder of 22 + 26 + 29 when divided by 5. Solution: On dividing 22 by 5 we get 2 as remainder. On dividing 26 by 5 we get 1 as remainder. On dividing 29 by 5 we get 4 as remainder. Remainder of the expression (22 + 26 + 29)/5 will be equal to (2 + 1 + 4)/5. Combined remainder will be equal to remainder of 7/5 i.e. 2. 
Example 2: Find the remainder of 1234 + 5678 + 1478 when divided by 11. Solution: On dividing 1234 by 11 we get 2 as remainder. On dividing 5678 by 11 we get 2 as remainder. On dividing 1478 by 11 we get 4 as remainder. Rem [(1234 + 5678 + 1478)/11] = Rem [(2 + 2 + 4)/11] Rem [8/11] = 8. 
How is it useful? If we need to find remainder of addition of two large numbers, we can avoid doing the addition of large numbers, especially helpful in programming where addition of large numbers can cause overflow. Like in C, C++ programming languages if addition of two large numbers exceed 10^18 then overflow happens and we start getting unexpected results. 
Proof: Here we will prove for two numbers and thus it can be generalized for more than two numbers.  
Let a % m = r1
and b % m = r2 

Then a and b can be written as (using quotient theorem).  
Here q1 is quotient when we divide a by m and r1 is remainder. 
Similar meanings are there for q2 and r2
a = m x q1 + r1
b = m x q2 + r2

LHS = (a + b) % m

    = ((m x q1 + r1 ) + (m x q2 + r2) ) % m

    = (m x (q1 + q2) + r1 + r2 ) % m

We can eliminate the multiples of m when we take the mod m.
Then,
LHS = (r1 + r2) % m

RHS = (a % m + b % m) % m

    = (r1 + r2) % m

Hence, LHS = RHS


 
dark_hunter
Modular Arithmetic
Engineering Mathematics
GATE CS
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Difference between Propositional Logic and Predicate Logic
Logic Notations in LaTeX
Univariate, Bivariate and Multivariate data and its analysis
Z-test
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
FakeDataGen - Full Valid Fake Data Generator - GeeksforGeeks

04 Jan, 2022
FakeDataGen is a free and open-source tool available on GitHub. This tool can be used to create a Full Valid Data Generator. This tool can be used to create fake accounts, emails, name data set which can be used in many attacks such as the men in the middle attack. Using this tool you can find the most common Spanish names with accounts.  You can create data as many as you want. This data can be used to perform various types of attacks such as phishing attacks. This tool is written in python languages, You must have python language installed in your kali Linux operating system in order to use this tool.
Step 1: Use the following commands to install the from GitHub. Use the second command to move in the directory of the tool.
git clone https://github.com/JoelGMSec/FakeDataGen
cd 
ls
Step 2: Now use the following command to install the requirements of the tool.
pip3 install -r requirements.txt
Step 3: Now use the following command to run the tool.
python3 FakeDataGen.py -h
The tool is running successfully. Now we will see examples to use the tool.
Example 1: Use the FakeDataGen tool to generate fake data.
python3 FakeDataGen.py -n 10
You can see that the data has been created successfully.
Example 2: Use the FakeDataGen tool to generate fake data.
python3 FakeDataGen.py -n 100
You can see that the data has been created successfully. You can use this tool for education purposing.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks

28 Jun, 2021
Let an represent the number of bit strings of length n containing two consecutive 1s. What is the recurrence relation for an?(A) an–2 + an–1 + 2n–2(B) an–2 + 2an–1 + 2n–2(C) 2an–2 + an–1 + 2n–2(D) 2an–2 + 2an–1 + 2n–2Answer: (A)Explanation: Simple SolutionOne way to solve this is to try for small values and rule out options.
a0 = 0  
a1 = 0  
a2 = 1  ["11"]
a3 = 3  ["011", "110", "111"] 
a4 = 8  ["0011", "0110", "0111", "1101",
                    "1011", "1100", "1110", "1111"]

If we check for a3, we can see that only A and C satisfy the value. Among (A) and (C), only (A) satisfies for a4.
Another Solution (With Proof)
A string of length n (n >= 2) can be formed by 
following 4 prefixes

1) 11 followed by a string of length n-2
2) 00 followed by a string of length n-2
3) 01 followed by a string of length n-2
4) 10 followed by a string of length n-2

Number 1 has already two consecutive 1's so number 
of binary strings beginning with number 3 is 2n-2
as remaining n-2 bits can have any value.

Number 2 has two 0's so remaining n-2 bits must have
two consecutive 1's. Therefore number of binary strings
that can be formed by number 2 is an-2.

Number 3 and Number 4 together form all strings of length
n-1 and two consecutive 1's.
Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
autoheader command in Linux with Examples - GeeksforGeeks

15 May, 2019
autoheader command in Linux is used to create a template file of C “#define” or any other template header for configure to use. If the user will give autoheader an argument, it reads the standard input instead of reading configure.ac and also writes the header file to the standard output. This command scans the configure.ac file and figures out which C preprocessor symbols it might have defined.
Syntax:
autoheader [OPTION]... [TEMPLATE-FILE]
Options:
-h, –help: Display the help message and then exits.autoheader -h or autoheader --help
autoheader -h or autoheader --help
-V, –version: Shows the version number and then exits.autoheader -V or autoheader --version
autoheader -V or autoheader --version
-v, –verbose: Gives the verbosely report processing.autoheader -v filename or autoheader --verbose filename
autoheader -v filename or autoheader --verbose filename
-d, –debug: Makes sure to not remove any files which are temporary.autoheader -d filename or autoheader --debug filename
autoheader -d filename or autoheader --debug filename
-f, –force: Consider all the files as obsolete.autoheader -f or autoheader --force
autoheader -f or autoheader --force
-w, –warnings: Reports the warnings falling in the categories.autoheader -w category or autoheader --warnings categoryThe other warning categories are:
autoheader -w category or autoheader --warnings category
The other warning categories are:
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
Linux | Nmon - GeeksforGeeks

27 Oct, 2018
Nmon is a fully interactive performance monitoring command-line utility tool for Linux. It is a benchmark tool that displays performance about the CPU, MEMORY, NETWORK, DISKS, FILE SYSTEM, NFS, TOP PROCESSES, RESOURCES, AND POWER MICRO-PARTITION.
INSTALLATIONOn Ubuntu/Debian :
$ sudo apt-get install nmon
On Fedora:
# yum install nmon
CentOS/RHEL:
# yum install epel-release
# yum install nmon
Once the installation of Nmon has been finished and you launch it from the terminal by typing the ‘nmon‘ command you will be presented with the following output.
$ nmon

Interactive Mode
Check CPU by processorIn order to get the CPU performance, you should hit the ‘c‘ key on the keyboard of the system you are using.
CPU by processor
Top Process DetailsIn order to get the top processes that are running currently, you should hit the ‘t‘ key on the keyboard of the system you are using.
Top Processes
Check Network StatisticsIn order to check network statistics, you should hit the ‘n‘ key on the keyboard of the system you are using.
Network Statistics
Disk I/O GraphsIn order to get informations of disks, you should hit the ‘d‘ key on the keyboard of the system you are using.
Monitor Disk I/O
Check Kernel InformationIn order to check kernel information, you should hit the ‘k‘ key on the keyboard of the system you are using.
Check Linux Kernel Information
Get System InformationIn order to get system information on different resources such as operating system version, Linux Version, Machine architecture, you should hit the ‘r‘ key on the keyboard of the system you are using.
System Information
Check File System StatisticsIn order to check File System Statistics, you should hit the ‘j‘ key on the keyboard of the system you are using. You can get information on the size of the file system, used space, free space, type of the file system and the mount point.
File System Statistics
Virtual Memory StatisticsIn order to check Virtual Memory Statistics, you should hit the ‘V‘ key on the keyboard of the system you are using.
Virtual Memory Statistics
CPU Long TermIn order to check CPU Long Term Statistics, you should hit the ‘l‘ key on the keyboard of the system you are using.
CPU Long-term
linux-command
Technical Scripter 2018
Linux-Unix
Technical Scripter
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
How to Run a Python Script using Docker?
Top Programming Languages for Android App Development
Setting up the environment in Java
How to use gotoxy() in codeblocks? - GeeksforGeeks

18 May, 2021
The gotoxy() function places the cursor at the desired location on the screen. This means it is possible to change the cursor location on the screen using the gotoxy() function. It is basically used to print text wherever the cursor is moved. Below is the C program to print the “hello” message on the screen without using the gotoxy() function:
C
// C program for the above approach#include <stdio.h>  // Driver Codevoid main(){    printf("hello");}
Output:
Explanation: The message “hello” is print on the top left side of the screen by default. So to print text at a particular coordinate use the gotoxy() function.
gotoxy() In Code::Blocks:
Code blocks don’t have a gotoxy() predefined function. Therefore, “SetConsoleCursorPosition()” can be used to carry out the same procedure. To use this function add a header file called #include<windows.h>. The arguments for SetConsoleCursorPosition() are:
Handle: To get the value of handle, call a predefined function “GetStdHandle(STD_OUTPUT_HANDLE)”.
Coord: The predefined function used to get X and Y coordinates.
Note: A screen has 25 lines and 80 columns.
Below is the implementation of the above-discussed function to print the “hello” message in the center of the screen:
C
// C program for the above approach  #include <stdio.h>#include <windows.h>  // Driver Codevoid main(){    // Input    COORD c;    c.X = 40;    c.Y = 16;      SetConsoleCursorPosition(        GetStdHandle(STD_OUTPUT_HANDLE), c);      printf("hello");    getch();}
Output:
Note: Any value for X and Y can be used to print the desired text at any location on the screen. Here, X is used for the vertical axis and Y is used for the horizontal axis.
Articles
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GTest Framework
Asymptotic Notations and how to calculate them
File globbing in Linux
Data Link Layer in OSI Model
Construct an array from its pair-sum array
Arrays in C/C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
Python Main Function

27 Dec, 2019
Main function is like the entry point of a program. However, Python interpreter runs the code right from the first line. The execution of the code starts from the starting line and goes line by line. It does not matter where the main function is present or it is present or not.
Since there is no main() function in Python, when the command to run a Python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, it will define a few special variables. __name__ is one such special variable. If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value __main__. If this file is being imported from another module, __name__ will be set to the module’s name.__name__ is a built-in variable which evaluates to the name of the current module.
Example:
# Python program to demonstrate# main() function    print("Hello")  # Defining main functiondef main():    print("hey there")    # Using the special variable # __name__if __name__=="__main__":    main()
Output:
Hello
hey there

When above program is executed, the interpreter declares the initial value of name as “main”. When the interpreter reaches the if statement it checks for the value of name and when the value of if is true it runs the main function else the main function is not executed.
Now when we import a Python script as module the __name__ variable gets the value same as the name of the python script imported.
Example: Let’s consider there are two Files(File1.py and File2.py). File1 is as follow.
# File1.py     print("File1 __name__ = %s" %__name__)    if __name__ == "__main__":     print("File1 is being run directly")else:     print("File1 is being imported")
Output:
File1 __name__ = __main__
File1 is being run directly

Now, when the File1.py is imported into File2.py, the value of __name__ changes.
# File2.py     import File1     print("File2 __name__ = %s" %__name__)    if __name__ == "__main__":    print("File2 is being run directly")else:     print("File2 is being imported")
Output:
File1 __name__ = File1
File1 is being imported
File2 __name__ = __main__
File2 is being run directly

As seen above, when File1.py is run directly, the interpreter sets the __name__ variable as __main__ and when it is run through File2.py by importing, the __name__ variable is set as the name of the python script, i.e. File1. Thus, it can be said that if __name__ == “__main__” is the part of the program that runs when the script is run from the command line using a command like Python File1.py.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.