code-rag-bench/online-tutorials huggingface dataset:
Maximum consecutive repeating character in string in C++

We are given a string of alphabets. The task is to find the character which has the longest consecutive repetitions occurring in string. Let’s understand with examples.
Input− String[] = “abbbabbbbcdd”
Output − b
Explanation − In the above string, the longest consecutive sequence is of character ‘b’. Count of consecutive b’s is 4.
Input− String[] = “aabbcdeeeeed”
Output − b
Explanation − In the above string, the longest consecutive sequence is of character ‘e’. Count of consecutive e’s is 5.
The character array string1[] is used to store the string of alphabets.
The character array string1[] is used to store the string of alphabets.
Function maxRepeating(char str[], int n) takes two input parameters. The string itself, its size. Returns the character with the longest consecutive repetitions sequence.
Function maxRepeating(char str[], int n) takes two input parameters. The string itself, its size. Returns the character with the longest consecutive repetitions sequence.
Traverse the string in str[] from 1st position till last.
Traverse the string in str[] from 1st position till last.
If str[i] and next one str[i+1] are the same, increment count .
If str[i] and next one str[i+1] are the same, increment count .
If that count is maximum, store the value in maxC and character in repchar.
If that count is maximum, store the value in maxC and character in repchar.
Return the repchar as a final result.
Return the repchar as a final result.
 Live Demo
#include <iostream>
#include <iostream>
char maxRepeating(char str[], int n){
   int count = 0;
   char repchar = str[0];
   int maxC = 1;
   for (int i=0; i<n; i++){
      if (str[i] == str[i+1] && i < n-1 )
         maxC++;
      else{
         if (maxC > count){
            count = maxC;
            repchar = str[i];
         }
         maxC = 1;
      }
   }
   return repchar;
}
int main(){
   char string1[] = "aaabbaacccddef";
   int N=14;
   printf("Maximum Consecutive repeating character in string: %c",maxRepeating(string1,N));
   return 0;
}
If we run the above code it will generate the following output −
Maximum Consecutive repeating character in string: a
Python math function | sqrt() - GeeksforGeeks

11 Jan, 2018
sqrt() function is an inbuilt function in Python programming language that returns the square root of any number.
Syntax:
math.sqrt(x)

Parameter: 
x is any number such that x>=0 

Returns:
It returns the square root of the number 
passed in the parameter. 
# Python3 program to demonstrate the # sqrt() method   # import the math module import math   # print the square root of  0 print(math.sqrt(0))   # print the square root of 4print(math.sqrt(4))   # print the square root of 3.5print(math.sqrt(3.5)) 
Output:
0.0
2.0
1.8708286933869707

Error: When x<0 it does not executes due to a runtime error.
# Python3 program to demonstrate the error in # sqrt() method   # import the math module import math   # print the error when x<0 print(math.sqrt(-1)) 
Output:
Traceback (most recent call last):
  File "/home/67438f8df14f0e41df1b55c6c21499ef.py", line 8, in 
    print(math.sqrt(-1)) 
ValueError: math domain error

Practical Application : Given a number, check if its prime or not.Approach: Run a loop from 2 to sqrt(n) and check if any number in range (2-sqrt(n)) divides n.
# Python program for practical application of sqrt() function  # import math moduleimport math  # function to check if prime or not def check(n):    if n == 1:        return False                  # from 1 to sqrt(n)     for x in range(2, (int)(math.sqrt(n))+1):        if n % x == 0:            return False     return True  # driver coden = 23if check(n):    print("prime") else:    print("not prime")
Output:
prime

Python-Built-in-functions
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
Iterate over a list in Python
Read a file line by line in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Stack in Python
Bar Plot in Matplotlib
SWING - Event Classes

Event classes represent the event. Java provides various Event classes, however, only those which are more frequently used will be discussed.
It is the root class from which all event state objects shall be derived. All Events are constructed with a reference to the object, the source, that is logically deemed to be the object upon which the Event in question initially occurred upon. This class is defined in java.util package.
Following is the declaration for java.util.EventObject class −
public class EventObject
   extends Object
      implements Serializable

Following are the fields for java.util.EventObject class −
protected Object source − The object on which the Event initially occurred.
EventObject(Object source)
Constructs a prototypical Event.
Object getSource()
The object on which the Event initially occurred.
String toString()
Returns a String representation of this EventObject.
This class inherits methods from the following class −
java.lang.Object
Following is the list of commonly used Event classes.
It is the root event class for all SWING events. This class and its subclasses supercede the original java.awt.Event class.
The ActionEvent is generated when the button is clicked or the item of a list is double-clicked.
The InputEvent class is the root event class for all component-level input events.
On entering the character the Key event is generated.
This event indicates a mouse action occurred in a component.
The object of this class represents the change in the state of a window.
The object of this class represents the adjustment event emitted by Adjustable objects.
The object of this class represents the change in the state of a window.
The object of this class represents the change in the state of a window.
The object of this class represents the change in the state of a window.
The object of this class represents the change in the state of a window.

    30 Lectures 
     3.5 hours 

 Pranjal Srivastava

    13 Lectures 
     1 hours 

 Pranjal Srivastava

    25 Lectures 
     4.5 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    14 Lectures 
     1.5 hours 

 Travis Rose

    14 Lectures 
     1 hours 

 Travis Rose
 Print
 Add Notes
 Bookmark this page
Inplace operator in Python

Definition - In-place operation is an operation that changes directly the content of a given linear algebra, vector, matrices(Tensor) without making a copy. The operators which helps to do the operation is called in-place operator.
Eg:   a+= b is equivalent to a= operator.iadd(a, b)
There are some operators are used for In-place operation.
This function is used to assign the current value and add  them. This operator does x+=y operation. In case of strings, numbers assigning is not performed.
a =operator.iadd(1, 3);
print ("The result after adding : ", end="")
print(a)
The result after adding: 5

This function is used to assign the current value and subtract them. This operator does x-=y operation. In case of strings, numbers assigning is not performed.
a =operator.isub(8, 6);
print ("The result after subtracting : ", end="")
print(a)
The result after subtracting: 2

This function is used to assign the current value and multiply them. This operator does x*=y operation. In case of strings, numbers assigning is not performed.
a =operator.imul(8, 6);
print ("The result after multiplying : ", end="")
print(a)
The result after multiplying: 48

This function is used to assign the current value and divide  them. This operator does x/=y operation. In case of strings, numbers assigning is not performed.
a =operator.itruediv(54, 6);
print ("The result after dividing : ", end="")
print(a)
The result after dividing: 9

This function is used to assign the current value and divide  them. This operator does x%=y operation. In case of strings, numbers assigning is not performed.
a =operator.imod(10, 5);
print ("The result after modulus : ", end="")
print(a)
The result after modulus: 2.0

This function is used to concatenate two strings.
a= "jupyter”
b = "notebook"
t =operator.iconcat(a, b)
print (" After concatenation : ", end="") 
print (t) 
After concatenation : jupyter notebook
Default Assignment Operator and References in C++ - GeeksforGeeks

27 Dec, 2021
We have discussed assignment operator overloading for dynamically allocated resources here. In this article, we discussed that when we don’t write our own assignment operator, the compiler creates an assignment operator itself that does shallow copy and thus causes problems. The difference between shallow copy and deep copy becomes visible when the class has pointers as member fields. However, there is no difference when pointers are not used. What happens when we have references in our class and there is no user-defined assignment operator. 
For example, predict the output of the following program,
CPP
// CPP program to demonstrate  references in a class and// there is no user defined assignment operator#include <iostream>using namespace std;  class Test {    int x;    int& ref;  public:    Test(int i)        : x(i)        , ref(x)    {    }    void print() { cout << ref; }    void setX(int i) { x = i; }};  // Driver Codeint main(){    Test t1(10);    Test t2(20);    t2 = t1;    t1.setX(40);    t2.print();    return 0;}
Output:
Compiler Error: non-static reference member 'int& Test::ref', 
             can't use default assignment operator
The compiler doesn’t create default assignment operator in the following cases:
1. Class has a non-static data member of a const type or a reference type. 2. Class has a non-static data member of a type that has an inaccessible copy assignment operator. 3. Class is derived from a base class with an inaccessible copy assignment operator.
When any of the above conditions is true, the user must define the assignment operator. For example, if we add an assignment operator to the above code, the code works fine without any error.
CPP
// CPP Program to demonstrate assignment operator#include <iostream>using namespace std;  class Test {    int x;    int& ref;  public:    Test(int i)        : x(i)        , ref(x)    {    }    void print() { cout << ref; }    void setX(int i) { x = i; }    Test& operator=(const Test& t)    {        x = t.x;        return *this;    }};  int main(){    Test t1(10);    Test t2(20);    t2 = t1;    t1.setX(40);    t2.print();    return 0;}
10
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
Constructors in C++
Angular CLI - ng serve Command

This chapter explains the syntax, argument and options of ng serve command along with an example.
The syntax for ng serve command is as follows −
ng serve <project> [options]
ng s <project> [options]

ng serve command builds and serve the application. It rebuilds the application if changes occur. Here project is the name of the application as defined in angular.json. 
The argument for ng serve command is as follows −
Options are optional parameters.
A named build target, as specified in the "configurations" section of angular.json. Each named target is accompanied by a configuration of option defaults for that target. Setting this explicitly overrides the "--prod" flag.
Aliases: -c
Don't verify connected clients are part of allowed hosts.
Default: false
Shows a help message for this command in the console.
Default: false
Enable hot module replacement.
Default: false
Show a warning when the --hmr option is enabled.
Default: true
Host to listen on.
Default: localhost
Whether to reload the page on change, using live-reload.
Default: true
Opens the url in default browser.
Default: false
Aliases: -o
Port to listen on.
Default: 4200
Show a warning when deploy-url/base-href use unsupported serve path values.
Default: true
Serve using HTTPS.
Default: false
Rebuild on change.
Default: true
First move to an angular project updated using ng build command and then run the command.The chapter is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm.
An example for ng serve command is given below −
\>Node\>TutorialsPoint> ng serve
chunk {main} main.js, main.js.map (main) 14.3 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 141 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 12.4 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 3 MB [initial] [rendered]
Date: 2020-06-04T04:01:47.562Z - Hash: a90c5fc750c475cdc4d1 - Time: 10164ms
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
: Compiled successfully.

Here ng serve command has built and serve our project TutorialsPoint successfully.Now open http://localhost:4200 in a browser window and verify the output.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Help function in Python

Many times we need to look into the python documentation for some help on functions, modules etc. Python provides a help function that gives us this needed results.
Help(‘term’)
Where term is the word on which we want the help.
In the below example we seek to find help on the word time. The output comes from python documentation and it is quite exhaustive.
 Live Demo
print(help('time'))
Running the above code gives us the following result −
Help on built-in module time:
NAME
time - This module provides various functions to manipulate time values.

DESCRIPTION
There are two standard representations of time. One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer
or a floating point number (to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
The actual value can be retrieved by calling gmtime(0).
............................
Date.getDate() function in JavaScript

The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
The getDate() function of the date object returns the day of the month of its current date.
Its syntax is as follows
dateObj.getDate();
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('September 26, 1989 00:4:00');
      document.write(dateObj.getDate());
   </script>
</body>
</html>
26
If you do not mention the date of the month by default 1 will be returned.
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('September, 1989 00:4:00');
      document.write(dateObj.getDate());
   </script>
</body>
</html>
1
If you do not pass any value to the constructor while creating the date object then this function returns the day of the month of the current date (current days date).
 Live Demo
<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date();
      document.write(dateObj.getDate());
   </script>
</body>
</html>
24
How can we create a MySQL view with a subquery?

To illustrate the making of MySQL view with subquery we are using the following data from the table ‘Cars’ −
mysql> select * from cars;
+------+--------------+---------+
| ID   | Name         | Price   |
+------+--------------+---------+
|    1 | Nexa         | 750000  |
|    2 | Maruti Swift | 450000  |
|    3 | BMW          | 4450000 |
|    4 | VOLVO        | 2250000 |
|    5 | Alto         | 250000  |
|    6 | Skoda        | 1250000 |
|    7 | Toyota       | 2400000 |
|    8 | Ford         | 1100000 |
+------+--------------+---------+
8 rows in set (0.08 sec)
Now, the following query will create a view named ‘cars_avgprice’ by using a subquery that will supply the values to the view. The subquery must be enclosed within parentheses.
mysql> Create view cars_avgprice AS SELECT NAME, Price FROM Cars WHERE price > (SELECT AVG(Price) from cars);
Query OK, 0 rows affected (0.12 sec)

mysql> Select * from cars_avgprice;
+--------+---------+
| NAME   | Price   |
+--------+---------+
| BMW    | 4450000 |
| VOLVO  | 2250000 |
| Toyota | 2400000 |
+--------+---------+
3 rows in set (0.03 sec)
If we will run the above subquery individually we can understand how view got its values −
mysql> Select AVG(Price) from cars;
+--------------+
| AVG(Price)   |
+--------------+
| 1612500.0000 |
+--------------+
1 row in set (0.00 sec)
That is why the view ‘cars_avgprice’ has the list of cars having price more than the average of price i.e. 1612500.
Puppeteer - Getting Element Text

We can get element text in Puppeteer. This is done with the help of the textContent property. This property of the element is passed as a parameter to the getProperty method.
The syntax of getting element text is as follows −
const n = await page.$("#txt")
const t = await (await n.getProperty('textContent')).jsonValue()

In the below image, let us obtain the text - About Tutorialspoint for the highlighted element −
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as follows −
Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).
The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.
Right-click on the folder where the node_modules folder is created, then click on the New file button.
Step 2 − Enter a filename, say testcase1.js.
Step 3 − Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function getText(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/about/about_careers.htm')
   //identify element
   const f = await page.$("[class='heading']")
   //obtain text
   const text = await (await f.getProperty('textContent')).jsonValue()
   console.log("Text is: " + text)
}
getText()
Step 4 − Execute the code with the command given below −
node <filename>

So in our example, we shall run the following command −
node testcase1.js

After the command has been successfully executed, the text of the element - About Tutorialspoint gets printed in the console.
 Print
 Add Notes
 Bookmark this page
Python Numbers

There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them:
To verify the type of any object in Python, use the type() function:
Int, or integer, is a whole number, 
positive or negative, without decimals, of unlimited length.
Integers:
Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Floats:
Float can also be scientific numbers with an "e" to indicate the power of 10.
Floats:
Complex numbers are written with a "j" as the imaginary part:
Complex:
You can convert from one type to another with the int(), 
float(), and complex() methods:
Convert from one type to another:
Note: You cannot convert complex numbers into another number type.
Python does not have a random() function to 
make a random number, but Python has a built-in module called
random that can be used to make random numbers:
Import the random module, and display a random number between 1 and 9:
In our Random Module Reference you will learn more about the Random module.
Insert the correct syntax to convert x into a floating point number.
x = 5
x = (x)

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
JavaFX example to set action listeners to a CheckBox

A checkbox is a type of selection control, which is square in shape with a tick mark int it, It has three states checked or, unchecked and, tristate/indeterminate (optional).
In JavaFX a checkbox is represented by the javafx.scene.control.CheckBox class. This class has three boolean properties namely allowIndeterminate, indeterminate, and, selected.
The selected property of the CheckBox class specifies whether the current checkbox is selected. Its value will be true if checked and false if unchecked.
The selectedProperty() method returns a boolean property indicating whether the current checkbox is checked. If you want to perform certain actions in case a checkbox is selected. You can add a listener to this property as −
checkBox2.selectedProperty().addListener(
   //. . . . .
);
Following JavaFX example creates three checkboxes and performs some action when each checkbox is checked.
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class CheckBoxAction extends Application {
   public void start(Stage stage) {
      //Creating the check boxes
      CheckBox checkBox1 = new CheckBox("English");
      CheckBox checkBox2 = new CheckBox("Hindi");
      CheckBox checkBox3 = new CheckBox("Telugu");
      Label label = new Label("Select a language:");
      Font font = Font.font("verdana", 12);
      label.setFont(font);
      Text text1 = new Text(250.0, 45.0, "");
      text1.setFont(font);
      Text text2 = new Text(250.0, 75.0, "");
      text1.setFont(font);
      Text text3 = new Text(250.0, 105.0, "");
      text1.setFont(font);
      //Setting action to check boxes
      checkBox1.selectedProperty().addListener(
      (ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) -> {
         text1.setText("Welcome to Tutorilaspoint");
      });
      checkBox2.selectedProperty().addListener(
      ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) -> {
         text2.setText("टुटोरियल्स पॉइन्ट को आप का स्वागत है");
      });
      checkBox3.selectedProperty().addListener(
      (ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) -> {
         text3.setText("ట్యూ టోరియల్స్ పాయింట్ కి స్వా గతిం");
      });
      //Adding the toggle button to the pane
      VBox vBox = new VBox(5);
      vBox.setPadding(new Insets(5, 5, 5, 50));
      vBox.getChildren().addAll(label, checkBox1, checkBox2, checkBox3 );
      Group root = new Group();
      root.getChildren().addAll(vBox, text1, text2, text3);
      //Setting the stage
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Check Box Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Matplotlib - Setting Ticks and Tick Labels - GeeksforGeeks

26 Dec, 2020
In this article, we are going to discuss how set Ticks and Tick labels in a graph.
Ticks are the markers denoting data points on the axes and tick labels are the name given to ticks. By default matplotlib itself marks the data points on the axes but it has also provided us with setting their own axes having ticks and tick labels of their choice.
Methods used:
plt.axes(*args, emit=True, **kwargs): For setting the axes for our plot with parameter rect as [left,bottom,width,height] for  setting axes position.
plt.axes().set_xticks() and plt.axes().set_yticks() : For setting ticks on x-axis and y-axis respectively. having data in form of a list set as parameter.
plt.axes().set_xlabels() and plt.axes().set_ylabels() : To set labels of our ticks with parameters in form of list.
Below are some examples which depict how to add ticks and ticklabels in a plot:
Example 1: 
Python3
# import required moduleimport matplotlib.pyplot as plt  # assign coordinatesx = y = [i for i in range(0, 10)]ax = plt.axes()  # depict illustrationplt.plot(x, y, color="lime")  # setting ticks for x-axisax.set_xticks([2, 4, 6, 8, 10])  # setting ticks for y-axisax.set_yticks([1, 3, 5, 7, 9])  plt.show()
Output:
Example 2:
Python3
# import required moduleimport matplotlib.pyplot as plt  # assign coordinatesx = y = [i for i in range(0, 10)]ax = plt.axes()  # depict illustrationplt.plot(x, y, color="lime")  # setting ticks for x-axisax.set_xticks([2, 4, 6, 8, 10])  # setting label for x tickax.set_xticklabels(['Geeks', 'for', 'geeks', '!'])  # setting ticks for y-axisax.set_yticks([1, 3, 5, 7, 9])  # setting label for y tickax.set_yticklabels(['A', 'B', 'C', 'D'])  plt.show()
Output:
Example 3:
Python3
# import required modulesimport matplotlib.pyplot as pltimport numpy as npimport math  # assign coordinatesx = np.arange(0, math.pi*2, 0.05)y = np.sin(x)ax = plt.axes()  # depict illustrationplt.plot(x, y, color="lime")  # setting ticks for x-axisax.set_xticks([0, 2, 4, 6])  # setting ticks for y-axisax.set_yticks([-1, 0, 1])  plt.show()
Output:
Example 4:
Python3
# import required modulesimport matplotlib.pyplot as pltimport numpy as npimport math  # assign coordinatesx = np.arange(0, math.pi*2, 0.05)y = np.sin(x)ax = plt.axes()plt.xlabel("x-axis")plt.ylabel("y-axis")  # depict illustrationplt.plot(x, y, color="lime")  # setting ticks for x-axisax.set_xticks([0, 2, 4, 6])  # setting ticks for y-axisax.set_yticks([-1, 0, 1])  # setting label for y tickax.set_yticklabels(["sin(-90deg)", "sin(0deg)", "sin(90deg)"])  plt.show()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
numpy.equal() in Python - GeeksforGeeks

04 Jan, 2022
numpy.equal(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None, ufunc ‘not_equal’) : This logical function checks for arr1 == arr2 element-wise.
Parameters :
arr1 : [array_like]Input arrayarr2 : [array_like]Input array
out : [ndarray, optional]Output array with same dimensions as Input array, placed with result.
**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.
where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
Return :
Returns arr1 == arr2 element-wise

 Code 1 :
# Python Program illustrating# numpy.equal() methodimport numpy as geek    a  = geek.equal([1., 2.], [1., 3.])print("Check to be Equal : \n", a, "\n")   b = geek.equal([1, 2], [[1, 3],[1, 4]])print("Check to be Equal : \n", b, "\n")
Output :
Check to be Equal : 
 [ True False] 

Check to be Equal : 
 [[ True False]
 [ True False]] 

 Code 2 : Comparing data-type using .equal() function
# Python Program illustrating# numpy.equal() methodimport numpy as geek    # Here we will compare Complex values with inta = geek.array([0 + 1j, 2])b = geek.array([1,2])   d  = geek.equal(a, b)print("Comparing complex with int using .equal() : ", d)
Output :
Comparing complex with int using .equal() :  [False  True]
 Code 3 :
# Python Program illustrating# numpy.not_equal() methodimport numpy as geek    # Here we will compare Float with int valuesa = geek.array([1.1, 1])b = geek.array([1, 2])    d  = geek.not_equal(a, b)print("\nComparing float with int using .not_equal() : ", d)
Output :
Comparing float with int using .not_equal() :  [ True  True]
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.equal.html.
sagar0719kumar
Python numpy-Logic Functions
Python-numpy
Python
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
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
DateTime.SpecifyKind() Method in C#

The DateTime.SpecifyKind() method in C# is used to create a new DateTime object that has the same number of ticks as the specified DateTime but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.
Following is the syntax −
public static DateTime SpecifyKind (DateTime d, DateTimeKind kind);
Above, the parameter d is the DateTime, whereas kind is One of the enumeration values that indicates whether the new object represents local time, UTC, or neither.
Let us now see an example to implement the DateTime.SpecifyKind() method −
using System;
using System.Globalization;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 10, 11, 11, 10, 42);
      DateTime res = DateTime.SpecifyKind(d, DateTimeKind.Local);
      Console.WriteLine("Kind = " + res.Kind);
   }
}
This will produce the following output −
Kind = Local
Let us now see another example to implement the DateTime.SpecifyKind() method −
using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 11, 25, 10, 20, 35);
      DateTime res = DateTime.SpecifyKind(d, DateTimeKind.Utc);
      Console.WriteLine("Kind = " + res.Kind);
   }
}
This will produce the following output −
Kind = Utc
SAS - Cross Tabulations

Cross tabulation involves producing cross tables also called contingent tables using all possible combinations of two or more variables. In SAS it is created using PROC FREQ along with the TABLES option. For example - if we need the frequency of each model for each make in each car type category, then we need to use the TABLES option of PROC FREQ.
The basic syntax for applying cross tabulation in SAS is −
PROC FREQ DATA = dataset;
TABLES variable_1*Variable_2;

Following is the description of the parameters used −
Dataset is the name of the dataset.
Dataset is the name of the dataset.
Variable_1 and Variable_2 are the variable names of the dataset whose frequency distribution needs to be calculated.
Variable_1 and Variable_2 are the variable names of the dataset whose frequency distribution needs to be calculated.
Consider the case of finding how many car types are available under each car brand from the dataset cars1 which is created form SASHELP.CARS as shown below. In this case we need the individual frequency values as well as the sum of the frequency values across the makes and across the types. We can observer that the result shows values across the rows and the columns.
PROC SQL;
create table CARS1 as
SELECT make, type, invoice, horsepower, length, weight
   FROM 
   SASHELP.CARS
   WHERE make in ('Audi','BMW')
;
RUN;

proc FREQ data = CARS1;
tables make*type; 
run;

When the above code is executed, we get the following result −
When we have three variables we can group 2 of them and cross tabulate each of these two with the third varaible. So in the result we have two cross tables.
In the below example we find the frequency of each type of car and each model of car with respect to the make of the car. Also we use the nocol and norow option to avoid the sum and percentage values.
proc FREQ data = CARS2 ;
tables make * (type model)  / nocol norow nopercent;   
run;

When the above code is executed, we get the following result −
With 4 variables, the number of paired combinations increases to 4. Each variable from group 1 is paired with each variable of group 2.
In the below example we find the frequency of length of the car for each make and each model. Similarly the frequency of horsepower for each make and each model.
proc FREQ data = CARS2 ;
tables (make model) * (length  horsepower)  / nocol norow nopercent;   
run;

When the above code is executed, we get the following result −

    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    35 Lectures 
     2.5 hours 

 Ermin Dedic

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
Jackson Annotations - @JsonIdentityInfo

@JsonIdentityInfo is used when objects have parent child relationship. @JsonIdentityInfo is used to indicate that object identity will be used during serialization/de-serialization.
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException, ParseException{
      ObjectMapper mapper = new ObjectMapper();     
      Student student = new Student(1,13, "Mark");
      Book book1 = new Book(1,"Learn HTML", student);
      Book book2 = new Book(2,"Learn JAVA", student);

      student.addBook(book1);
      student.addBook(book2);

      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(book1);
      System.out.println(jsonString);
   }
}
@JsonIdentityInfo(
   generator = ObjectIdGenerators.PropertyGenerator.class,
   property = "id")
class Student { 
   public int id;
   public int rollNo;
   public String name;
   public List<Book> books;
   
   Student(int id, int rollNo, String name){
      this.id = id;
      this.rollNo = rollNo;
      this.name = name;
      this.books = new ArrayList<Book>();
   }
   public void addBook(Book book){
      books.add(book);
   }
}
@JsonIdentityInfo(
   generator = ObjectIdGenerators.PropertyGenerator.class,
   property = "id")
class Book{
   public int id;
   public String name;

   Book(int id, String name, Student owner){
      this.id = id;
      this.name = name;
      this.owner = owner;
   }
   public Student owner;
}
{
   "id" : 1,
   "name" : "Learn HTML",
   "owner" : {
      "id" : 1,
      "rollNo" : 13,
      "name" : "Mark",
      "books" : [ 
         1, {
            "id" : 2,
            "name" : "Learn JAVA",
            "owner" : 1
         }  
      ]
   }
}

 Print
 Add Notes
 Bookmark this page
log4j - Sample Program

We have seen how to create a configuration file. This chapter describe how to generate debug messages and log them in a simple text file.
Following is a simple configuration file created for our example. Let us revise it once again:
The level of the root logger is defined as DEBUG and attaches appender named FILE to it.
The level of the root logger is defined as DEBUG and attaches appender named FILE to it.
The appender FILE is defined as org.apache.log4j.FileAppender and writes to a file named log.out located in the log directory.
The appender FILE is defined as org.apache.log4j.FileAppender and writes to a file named log.out located in the log directory.
The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.
The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.
The contents of log4j.properties file are as follows −
# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

The following Java class is a very simple example that initializes, and then uses, the log4j logging library for Java applications.
import org.apache.log4j.Logger;

import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class log4jExample{

   /* Get actual class name to be printed on */
   static Logger log = Logger.getLogger(log4jExample.class.getName());
   
   public static void main(String[] args)throws IOException,SQLException{
      log.debug("Hello this is a debug message");
      log.info("Hello this is an info message");
   }
}
Here are the steps to compile and run the above-mentioned program. Make sure you have set  PATH  and CLASSPATH appropriately before proceeding for the compilation and execution.
All the libraries should be available in CLASSPATH and your log4j.properties file should be available in PATH. Follow the steps give below −
Create log4j.properties as shown above.
Create log4j.properties as shown above.
Create log4jExample.java as shown above and compile it.
Create log4jExample.java as shown above and compile it.
Execute log4jExample binary to run the program.
Execute log4jExample binary to run the program.
You would get the following result inside /usr/home/log4j/log.out file −
Hello this is a debug message
Hello this is an info message

 Print
 Add Notes
 Bookmark this page
What is the use of cin.ignore() in C++?

The cin.ignore() function is used which is used to ignore or clear one or more characters from the input buffer.
To get the idea about ignore() is working, we have to see one problem, and its solution is found using the ignore() function. The problem is like below.
Sometimes we need to clear the unwanted buffer, so when next input is taken, it stores into the desired container, but not in the buffer of previous variable. For example, after entering into the cin statement, we need to input a character array or string. So we need to clear the input buffer, otherwise it will occupy the buffer of previous variable. By pressing the “Enter” key after the first input, as the buffer of previous variable has space to hold new data, the program skips the following input of container.
#include<iostream>
#include<vector>
using namespace std;
main() {
   int x;
   char str[80];
   cout << "Enter a number and a string:\n";
   cin >> x;
   cin.getline(str,80); //take a string
   cout << "You have entered:\n";
   cout << x << endl;
   cout << str << endl;
}
Enter a number and a string:
8
You have entered:
8
There are two cin statements for integer and string, but only number is taken. When we press enter key, it skips the getLine() function without taking any input. Sometimes it can take input but inside the buffer of integer variable, so we cannot see the string as output.
Now to resolve this issue, we will use the cin.ignore() function. This function is used to ignore inputs upto given range. If we write the statement like this −
cin.ignore(numeric_limits::max(), ‘\n’)
Then it ignores input including the new line character also.
#include<iostream>
#include<ios> //used to get stream size
#include<limits> //used to get numeric limits
using namespace std;
main() {
   int x;
   char str[80];
   cout << "Enter a number and a string:\n";
   cin >> x;
   cin.ignore(numeric_limits<streamsize>::max(), '\n'); //clear buffer before taking new
   line
   cin.getline(str,80); //take a string
   cout << "You have entered:\n";
   cout << x << endl;
   cout << str << endl;
}
Enter a number and a string:
4
Hello World
You have entered:
4
Hello World
How to redirect to another webpage with JavaScript?

To redirect to another webpage using JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<h1>Redirect to a Webpage Example</h1>
<button class="redirectBtn">Redirect</button>
<h2>Click the above button to Redirect to another Webpage</h2>
<script>
   document .querySelector(".redirectBtn") .addEventListener("click", redirectFunction);
   function redirectFunction() {
      location.href("https://tutorialspoint.com/");
   }
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “Redirect” button we will be redirected to a new site −
Java - rint() Method

The method rint returns the integer that is closest in value to the argument.
double rint(double d)

Here is the detail of parameters −
d − it accepts a double value as parameter.
d − it accepts a double value as parameter.
This method returns the integer that is closest in value to the argument. Returned as a double.
This method returns the integer that is closest in value to the argument. Returned as a double.
public class Test {

   public static void main(String args[]) {
      double d = 100.675;
      double e = 100.500;
      double f = 100.200;

      System.out.println(Math.rint(d));
      System.out.println(Math.rint(e)); 
      System.out.println(Math.rint(f)); 
   }
}
This will produce the following result −
101.0
100.0
100.0


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Node.js zlib.gunzipSync() Method

12 Oct, 2021
The zlib.gunzipSync() method is an inbuilt application programming interface of the Zlib module which is used to decompress a chunk of data with Gunzip.
Syntax:
zlib.gunzipSync( buffer, options )
Parameters: This method accepts two parameters as mentioned above and described below:
buffer: This parameter holds the buffer of type Buffer, TypedArray, DataView, ArrayBuffer, string.
options: This parameter holds the zlib options value.
Return Value: It returns the chunk of data with Gunzip.
Below examples illustrate the use of zlib.gunzipSync() method in Node.js:
Example 1:
// Node.js program to demonstrate the     // zlib.gunzipSync() method    // Including zlib modulevar zlib = require('zlib');  // Declaring input and assigning// it a value stringvar input = "Nidhi";  // Calling gzipSync methodvar gzi = zlib.gzipSync(input);  // Calling gunzipSync methodvar decom = zlib.gunzipSync(    new Buffer.from(gzi)).toString();  console.log(decom);
Output:
Nidhi
Example 2:
// Node.js program to demonstrate the     // zlib.gunzipSync() method    // Including zlib modulevar zlib = require('zlib');  // Declaring input and assigning// it a value stringvar input = "Nidhi";  // Calling gzipSync methodvar gzi = zlib.gzipSync(input).toString('hex');  // Calling gunzipSync methodvar decom = zlib.gunzipSync(new Buffer.from(        gzi, 'hex')).toString('base64');  console.log(decom);
Output:
TmlkaGk=

Reference: https://nodejs.org/api/zlib.html#zlib_zlib_gunzipsync_buffer_options
Node.js-Zlib-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Remove unwanted spaces from string

25 Jun, 2019
Sometimes, while working with strings, we may have situations in which we might have more than 1 spaces between intermediate words in strings that are mostly unwanted. This type of situations can occur in web development and often needs rectification. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using re.sub()This problem can be performed using the regex in which we can restrict the separation between the words to be just a single space using the appropriate regex string.
# Python3 code to demonstrate working of# remove additional space from string# Using re.sub()import re  # initializing string test_str = "GfG  is   good           website"  # printing original string print("The original string is : " + test_str)  # using re.sub()# remove additional space from string res = re.sub(' +', ' ', test_str)  # printing result print("The strings after extra space removal : " + str(res))
The original string is : GfG  is   good           website
The strings after extra space removal : GfG is good website

 
Method #2 : Using split() and join()This task can also be performed using the split and join function. This is performed in two steps. In first step, we convert the string into list of words and then join with a single space using the join function.
# Python3 code to demonstrate working of# remove additional space from string# Using split() + join()  # initializing string test_str = "GfG  is   good           website"  # printing original string print("The original string is : " + test_str)  # using split() + join()# remove additional space from string res = " ".join(test_str.split())  # printing result print("The strings after extra space removal : " + str(res))
The original string is : GfG  is   good           website
The strings after extra space removal : GfG is good website

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add Timer in Next.js ?

15 Nov, 2021
In this article, we are going to learn how we can add Timer in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.
Approach: To add our Timer we are going to use the react-countdown-circle-timer package. The react-countdown-circle-timer package helps us to integrate different types of timers. So first, we will install the react-countdown-circle-timer package, and then we will add timer on our homepage.
Create NextJS Application: You can create a new NextJs project using the below command:
npx create-next-app gfg
Install the required package: Now we will install the react-countdown-circle-timer package using the below command:
npm i react-countdown-circle-timer
Project Structure: It will look like this.
Adding the Timer: After installing the react-countdown-circle-timer package we can easily add Timer in our app . For this example, we are going to add timer to our homepage.
Add the below content in the index.js file:
Javascript
import { CountdownCircleTimer } from     'react-countdown-circle-timer'  export default function Timer(){  return (    <div>      <h3>GeeksforGeeks - Timer</h3>      <CountdownCircleTimer        isPlaying        duration={10}        colors={[          ['#004777', 0.33],          ['#F7B801', 0.33],          ['#A30000', 0.33],        ]}      >        {({ remainingTime }) => remainingTime}      </CountdownCircleTimer>    </div>      )}
Explanation: In the above example first, we are importing our CountdownCircleTimer component from the installed package. After that, we are using the component and set the initial properties like isPlaying, duration, and color. Then we are displaying the remainingTime.
Steps to run the application: Run the below command in the terminal to run the app.
npm run dev
Next.js
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.