code-rag-bench/online-tutorials huggingface dataset:
Python | Standard deviation of list - GeeksforGeeks

03 Oct, 2019
Sometimes, while working with Mathematics, we can have a problem in which we intend to compute the standard deviation of a sample. This has many applications in competitive programming as well as school level projects. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using sum() + list comprehensionThis is a brute force shorthand to perform this particular task. We can approach this problem in sections, computing mean, variance and standard deviation as square root of variance. The sum() is key to compute mean and variance. List comprehension is used to extend the common functionality to each of element of list.
# Python3 code to demonstrate working of# Standard deviation of list# Using sum() + list comprehension  # initializing listtest_list = [4, 5, 8, 9, 10]  # printing listprint("The original list : " + str(test_list))  # Standard deviation of list# Using sum() + list comprehensionmean = sum(test_list) / len(test_list)variance = sum([((x - mean) ** 2) for x in test_list]) / len(test_list)res = variance ** 0.5  # Printing resultprint("Standard deviation of sample is : " + str(res))
 
The original list : [4, 5, 8, 9, 10]
Standard deviation of sample is : 2.3151673805580453

Method #2 : Using pstdev()This task can also be performed using inbuilt functionality of pstdev(). This function computes standard deviation of sample internally.
# Python3 code to demonstrate working of# Standard deviation of list# Using pstdev()import statistics  # initializing listtest_list = [4, 5, 8, 9, 10]  # printing listprint("The original list : " + str(test_list))  # Standard deviation of list# Using pstdev()res = statistics.pstdev(test_list)  # Printing resultprint("Standard deviation of sample is : " + str(res))
 
The original list : [4, 5, 8, 9, 10]
Standard deviation of sample is : 2.3151673805580453

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Can we declare an abstract method final or static in java?

A method which does not have body is known as abstract method. It contains only method signature with a semi colon and, an abstract keyword before it.
public abstract myMethod();
To use an abstract method, you need to inherit it by extending its class and provide implementation to it.
If you declare a method in a class abstract to use it, you must override this method in the subclass. But, overriding is not possible with static methods. Therefore, an abstract method cannot be static.
If you still, try to declare an abstract method static a compile time error is generated saying “illegal combination of modifiers − abstract and static”.
In the following Java program, we are trying to declare an abstract method static.
 Live Demo
abstract class MyClass {
   public static abstract void display();
}
public class AbstractClassExample extends MyClass{
   public void display() {
      System.out.println("This is the subclass implementation of the display method ");
   }
   public static void main(String args[]) {
      new AbstractClassExample().display();
   }
}
On compiling, the above program generates the following error.
AbstractClassExample.java:2: error: illegal combination of modifiers: abstract and static
   public static abstract void display();
^
1 error
Similarly, you cannot override final methods in Java.But, in-case of abstract, you must override an abstract method to use it.Therefore, you cannot use abstract and final together before a method.
If, you still try to declare an abstract method final a compile time error is generated saying “illegal combination of modifiers: abstract and final”.
In the following Java program, we are trying to declare an abstract method final.
public abstract class AbstractClassExample {
   public final abstract void display();
}
On compiling, the above program generates the following error.
AbstractClassExample.java:2: error: illegal combination of modifiers: abstract and final
public final abstract void display();
^
1 error
Python | sympy.div() method

26 Aug, 2019
Syntax:sympy.div(f, g, domain='QQ')
Return: division of polynomials with remainder

Example #1:
# import sympy from sympy import *   f = 5 * x**2 + 10 * x + 3g = 2 * x + 2  # Using sympy.div() method q, r = div(f, g, domain ='QQ')  print(q)print(r)
Output:
5*x/2 + 5/2
-2

Example #2:
# import sympy from sympy import *   f = 5 * x**2 + 10 * x + 3g = 2 * x**2 + 2  # Using sympy.div() method q, r = div(f, g, domain ='QQ')  print(q)print(r)
Output:
5/2
10*x - 2

SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
ReactJS getSnapshotBeforeUpdate() Method

23 Dec, 2020
The getSnapshotBeforeUpdate() method is invoked just before the DOM is being rendered. It is used to store the previous values of the state after the DOM is updated.
Any value returned by getSnapshotBeforeUpdate() method will be used as a parameter for componentDidUpdate() method. This function is always used along with the componentDidUpdate() method but vice-versa isn’t true.
Syntax:
getSnapshotBeforeUpdate(prevProps, prevState)
Parameters: It accepts two parameters, they are prevProps and prevState which are just the props or state before the component in question is re-rendered.
Creating React Application:
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
Example: Program to demonstrate the use of getSnapshotBeforeUpdate() method. Here, we are going to use the previous and current values of the state to display some text.
Filename: App.js:  
Javascript
import React from 'react';class App extends React.Component {    // Initializing the state  state = {    name: 'GFG',  };    componentDidMount() {      // Changing the state after 1 sec    setTimeout(() => {      this.setState({ name: 'GeeksForGeeks' });    }, 1000);  }    getSnapshotBeforeUpdate(prevProps, prevState) {      // Displaying the previous value of the state    document.getElementById('prev').innerHTML =      'Previous Name: ' + prevState.name;  }    componentDidUpdate() {      // Displaying the current value of the state    document.getElementById('new').innerHTML =      'Current Name: ' + this.state.name;  }    render() {    return (      <div>        <div id="prev"></div>        <div id="new"></div>      </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:
Reference: https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set background image as fixed with CSS

Use the background-attachment property to display the background image as fixed.
You can try to run the following code to implement the background-attachment property −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         body {
            background-image: url("https://www.tutorialspoint.com/videotutorials/images/tutor_connect_home.jpg");
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-position: right top;
         }
      </style>
   </head>
   <body>
      <h1>Background Image</h1>
   </body>
</html>
Print a long int in C using putchar() only

21 Jun, 2022
Write a C function print(n) that takes a long int number n as argument, and prints it on console. The only allowed library function is putchar(), no other function like itoa() or printf() is allowed. Use of loops is also not allowed.
We strongly recommend to minimize the browser and try this yourself first.
This is a simple trick question. Since putchar() prints a character, we need to call putchar() for all digits. Recursion can always be used to replace iteration, so using recursion we can print all digits one by one. Now the question is putchar() prints a character, how to print digits using putchar(). We need to convert every digit to its corresponding ASCII value, this can be done by using ASCII value of ‘0’. Following is complete C program.
C
/* C program to print a long int number using putchar() only*/#include <stdio.h> void print(long n){    // If number is smaller than 0, put a - sign    // and change number to positive    if (n < 0) {        putchar('-');        n = -n;    }     // Remove the last digit and recur    if (n/10)        print(n/10);     // Print the last digit    putchar(n%10 + '0');} // Driver program to test above functionint main(){    long int n = 12045;    print(n);    return 0;}
Output: 
12045
Time Complexity: O(logn)
Auxiliary Space: O(logn)
One important thing to note is the sequence of putchar() and recursive call print(n/10). Since the digits should be printed left to right, the recursive call must appear before putchar() (The rightmost digit should be printed at the end, all other digits must be printed before it).
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
Prashant__Singh
sweetyty
tarakki100
C-Library
C-String
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
C Language Introduction
How to make a NumPy array read-only?

17 Jun, 2022
Let’s discuss how to make NumPy array immutable i.e that can not be rewritten or can’t be changed. This can be done by setting a writable flag of the NumPy array to false.
Syntax:
array.flags.writable=False
 This set the writable flag to false and hence array becomes immutable i.e read-only. See the example below
Example:
Python
import numpy as np  a = np.zeros(11)print("Before any change ")print(a) a[1] = 2print("Before after first change ")print(a) a.setflags(write=False)print("After making array immutable on attempting  second change ")a[1] = 7
Output:
Before any change
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
Before after first change
[0. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
After making array immutable on attempting  second change
Traceback (most recent call last):
  File "gfg9.py", line 11, in <module>
    a[1]=7
ValueError: assignment destination is read-only
sagar0719kumar
abhisheksinghbhadauriya
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
What is the difference between the widgets of tkinter and tkinter.ttk in Python?

tkinter.ttk is a module that is used to style the tkinter widgets. Just like CSS is used to style an HTML element, we use tkinter.ttk to style tkinter widgets.
Here are the major differences between tkinter widget and tkinter.ttk −
Tkinter widgets are used to add Buttons, Labels, Text, ScrollBar, etc., however, tkinter.ttk supports a variety of widgets as compared to tkinter widgets.
Tkinter widgets are used to add Buttons, Labels, Text, ScrollBar, etc., however, tkinter.ttk supports a variety of widgets as compared to tkinter widgets.
Tkinter.ttk doesn't support Place, Pack() and Grid(), thus it is recommended to use tkinter widget with ttk.
Tkinter.ttk doesn't support Place, Pack() and Grid(), thus it is recommended to use tkinter widget with ttk.
Ttk has many features and configurations that extend the functionality of a native application and make it look more modern.
Ttk has many features and configurations that extend the functionality of a native application and make it look more modern.
Tkinter widget is a native widget in the tkinter library, however ttk is a themed module.
Tkinter widget is a native widget in the tkinter library, however ttk is a themed module.
To override the basic Tk widget in tkinter, use "from tkinter.ttk import *"
To override the basic Tk widget in tkinter, use "from tkinter.ttk import *"
In the following example, we have styled a tkinter native widget using tkinter.ttk module. We will create a button that will change the background color of the text widget.
#Import the tkinter library
from tkinter import *
from tkinter.ttk import *

#Create an instance of tkinter frame
win = Tk()

#Set the geometry
win.geometry("620x400")

#Add a class to style the tkinter widgets
style = ttk.Style()
style.configure('TEntry', foreground = 'red')

#Define a function to change the text color
def change_color():
   text.configure(background="red")

#Create a text widget
text=Label(win,text="This is a New Text",foreground="white",
background="blue",font=('Aerial bold',20))
text.pack(pady=20)

#Create a Button widget
Button(win, text= "Click Here", command= change_color).pack(pady=10)
win.mainloop()
Running the above code will produce the following output −
Now, click the "Click Here" button. It will change the background color of the text widget to Red.
How do we use multi-line comments in JavaScript?

The following is a multi line comment in JavaScript.
/*
   * This is a multiline comment in JavaScript
   * It is very similar to comments in C Programming
*/
The following example shows how to use multi-line comments in JavaScript.
<script>
   <!--
      /*
         * This is a multiline comment in JavaScript
         * It is very similar to comments in C Programming
      */
   //-->
</script>
Python Text To Speech | pyttsx module

14 Jan, 2019
pyttsx is a cross-platform text to speech library which is platform independent. The major advantage of using this library for text-to-speech conversion is that it works offline. However, pyttsx supports only Python 2.x. Hence, we will see pyttsx3 which is modified to work on both Python 2.x and Python 3.x with the same code.
Use this command for Installation:
pip install pyttsx3
 Usage –First we need to import the library and then initialise it using init() function. This function may take 2 arguments.init(driverName string, debug bool)
drivername : [Name of available driver] sapi5 on Windows | nsss on MacOS
debug: to enable or disable debug output
After initialisation, we will make the program speak the text using say() function. This method may also take 2 arguments.say(text unicode, name string)
text : Any text you wish to hear.
name : To set a name for this speech. (optional)
Finally, to run the speech we use runAndWait() All the say() texts won’t be said unless the interpreter encounters runAndWait().
Code #1: Speaking Text
# importing the pyttsx libraryimport pyttsx3  # initialisationengine = pyttsx3.init()  # testingengine.say("My first code on text-to-speech")engine.say("Thank you, Geeksforgeeks")engine.runAndWait()
 Code #2: Listening for events
import pyttsx3  def onStart():   print('starting')  def onWord(name, location, length):   print('word', name, location, length)  def onEnd(name, completed):   print('finishing', name, completed)  engine = pyttsx3.init()  engine.connect('started-utterance', onStart)engine.connect('started-word', onWord)engine.connect('finished-utterance', onEnd)  sen = 'Geeks for geeks is a computer portal for Geeks'    engine.say(sen)engine.runAndWait()
Why pyttsx?It works offline, unlike other text-to-speech libraries. Rather than saving the text as audio file, pyttsx actually speaks it there. This makes it more reliable to use for voice-based projects.
Python-Library
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Python Program for Largest K digit number divisible by X

03 Dec, 2018
Integers X and K are given. The task is to find highest K-digit number divisible by X.
Examples:
Input : X = 30, K = 3
Output : 990
990 is the largest three digit 
number divisible by 30.

Input : X = 7, K = 2
Output : 98

An efficient solution is to use below formula.
ans = MAX - (MAX % X)
where MAX is the largest K digit 
number which is  999...K-times
The formula works on simple school method division. We remove remainder to get the largest divisible number.
# Python code to find highest # K-digit number divisible by X  def answer(X, K):          # Computing MAX    MAX = pow(10, K) - 1          #returning ans    return (MAX - (MAX % X))  X = 30; K = 3;   print(answer(X, K));   # Code contributes by Mohit Gupta_OMG <(0_o)>
Output :
990

Please refer complete article on Largest K digit number divisible by X for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to interchange first and last elements in a list
Appending to list in Python dictionary
Appending a dictionary to a list in Python
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python | Difference between two dates (in minutes) using datetime.timedelta() method
Python Program to check Armstrong Number
Python | Remove spaces from a string
Python - Convert JSON to string
Python Program for Merge Sort
Python | Get the first key in dictionary
Change Data Type for one or more columns in Pandas Dataframe

08 Jul, 2022
Let’s see How To Change Column Type in Pandas DataFrames, There are different ways of changing DataType for one or more columns in Pandas Dataframe.
DataFrame.astype() method is used to cast pandas object to a specified dtype. This function also provides the capability to convert any suitable existing column to a categorical type.
Python3
# importing pandas as pdimport pandas as pd # sample dataframedf = pd.DataFrame({    'A': [1, 2, 3, 4, 5],    'B': ['a', 'b', 'c', 'd', 'e'],    'C': [1.1, '1.0', '1.3', 2, 5]}) # using dictionary to convert specific columnsconvert_dict = {'A': int,                'C': float                } df = df.astype(convert_dict)print(df.dtypes)
Output: 
 
We can pass any Python, Numpy, or Pandas datatype to change all columns of a Dataframe to that type, or we can pass a dictionary having column names as keys and datatype as values to change the type of selected columns. 
Python3
# importing pandas as pdimport pandas as pd # sample dataframedf = pd.DataFrame({    'A': [1, 2, 3, 4, 5],    'B': ['a', 'b', 'c', 'd', 'e'],    'C': [1.1, '1.0', '1.3', 2, 5]}) # converting all columns to string typedf = df.astype(str)print(df.dtypes)
Output: 
 
We can pass pandas.to_numeric, pandas.to_datetime, and pandas.to_timedelta as arguments to apply the apply() function to change the data type of one or more columns to numeric, DateTime, and time delta respectively. 
Python3
# importing pandas as pdimport pandas as pd # sample dataframedf = pd.DataFrame({    'A': [1, 2, 3, '4', '5'],    'B': ['a', 'b', 'c', 'd', 'e'],    'C': [1.1, '2.1', 3.0, '4.1', '5.1']}) # using apply methoddf[['A', 'C']] = df[['A', 'C']].apply(pd.to_numeric)print(df.dtypes)
Output: 
 
This method attempts soft-conversion by inferring the data type of ‘object’-type columns. Non-object and unconvertible columns are left unchanged. 
Python3
# importing pandas as pdimport pandas as pd # sample dataframedf = pd.DataFrame({    'A': [1, 2, 3, 4, 5],    'B': ['a', 'b', 'c', 'd', 'e'],    'C': [1.1, 2.1, 3.0, 4.1, 5.1]}, dtype='object') # converting datatypesdf = df.infer_objects()print(df.dtypes)
Output: 
 
A new DataFrame with each column’s data type changed to the best one is returned by the convert dtypes() method. 
Python3
import pandas as pd data = {  "name": ["Aman", "Hardik", pd.NA],  "qualified": [True, False, pd.NA]} df = pd.DataFrame(data) print("Original_dtypes:")print(df.dtypes) newdf = df.convert_dtypes() print("New_dtypes:")print(newdf.dtypes)
Output:
Original_dtypes:
name         object
qualified    object
dtype: object
New_dtypes:
name          string
qualified    boolean
dtype: object
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON
Python OOPs Concepts
pandas.eval() function in Python

14 Aug, 2020
This method is used to evaluate a Python expression as a string using various back ends. It returns ndarray, numeric scalar, DataFrame, Series.
Syntax : pandas.eval(expr, parser=’pandas’, engine=None, truediv=True, local_dict=None, global_dict=None, resolvers=(), level=0, target=None, inplace=False)
Arguments :
expr : str or unicode. The expression to evaluate. This string cannot contain any Python
parser : string, default ‘pandas’, {‘pandas’, ‘python’}.
engine : string or None, default ‘numexpr’, {‘python’, ‘numexpr’}
truediv : bool, optional, Whether to use true division, like in Python >= 3
level : int, optional, The number of prior stack frames to traverse and add to the current scope. Most users will **not** need to change this parameter.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packageimport pandas  # evaluate the expressions given# in form of stringprint(pandas.eval("2+3"))print(pandas.eval("2+3*(5-2)"))
Output :
5
11

Example 2 :
Python3
# importing packageimport pandas  # creating datadata = pandas.DataFrame({      "Student": ["A", "B", "C", "D"],     "Physics": [89,34,23,56],     "Chemistry": [34,56,98,56],     "Math": [34,94,50,59]    })  # view datadisplay(data)  # adding new column by existing # columns evaluationdata['Total']=pandas.eval("data.Physics+data.Chemistry+data.Math")  # view datadisplay(data)  # adding new column by existing # columns evaluationpandas.eval("Avg=data.Total/3",target=data,inplace=True)  # view datadisplay(data)
Output :
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
How to declare object with computed property name in JavaScript ? - GeeksforGeeks

22 Nov, 2021
In this article, we learn how to declare an object with a computed property name. Before beginning this article, we have to know about the javascript objects.
Javascript Object: Javascript objects contain key-value pairs in which the key represents a property from which we can get and set the value of the object. Now we will see how to declare an object with a computed property name. 
Method 1: We will use the expression within the [ ] (square bracket) to create the name of an object property. In ES6, it is possible to use an expression within brackets ‘[ ]’. Depending on the result of the expression, a property name will be assigned to an object. 
 
JavaScript
<script>    let LAST_NAME = "lastname";    let fullname = {        firstname: "somya",        [LAST_NAME]: "jain"    };    console.log(        "My fullname is: " + fullname.firstname            + " " + fullname.lastname    );</script>
Output:
My fullname is: somya jain
Method 2: In this method, We will create the property name of an object dynamically. As part of this method, we will dynamically create an object and add a property name and assign a value to that specific property in order to create a customized key-value pair.  
Syntax:
objectname["name of the property name"]=value

Javascript
<script>    let LAST_NAME = "lastname";    let fullname = {        firstname: "somya"    };    fullname[LAST_NAME] = "jain";    console.log(        "My fullname is: " + fullname.firstname            + " " + fullname.lastname    );</script>
Output:
My fullname is: somya jain
ES6
javascript-object
JavaScript-Questions
Picked
JavaScript
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?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
std::basic_istream::ignore in C++ with Examples - GeeksforGeeks

10 Jan, 2022
The std::basic_istream::ignore is used to extracts characters from the input string and discards them including delimiting character, i.e., if the end of the file is reached this function stops extracting characters. The delimiting character is the new line character i.e ‘\n’. This function will also stop extracting characters if the end-of-file is reached if the input is taken using a file. This function accesses the input sequence by first constructing a sentry object. It extracts characters from its associated stream buffer object and destroys the sentry object before returning.Header File: 
#include <iostream>
Syntax: 
istream& ignore(size N,
            int delim = EOF);
Parameters: It accepts the following parameters: 
N: It represent maximum number of characters to extract.
delim: It is used for where stop the extraction.
Return Values: It returns the basic_istream object.Below are the programs to demonstrate basic_istream::ignore():Program 1: 
CPP
// C++ program to demonstrate// basic_istream::ignore #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){     // Input String    istringstream input(        "12\n"        "It is a string\n"        "14\n");     for (;;) {         int n;         // Taking input streamed string        input >> n;         // Check for end of file or if        // any bad  bit occurs        if (input.eof() || input.bad()) {            break;        }         // If any failbit occurs        else if (input.fail()) {             // Clear the input            input.clear();             // Use ignore to stream the given            // input as per delimiter '\n'            input.ignore(                numeric_limits<streamsize>::max(),                '\n');        }         // Else print the integer in        // the string        else {            cout << n << '\n';        }    }    return 0;}
12
14
 
Program 2: 
CPP
// C++ program to demonstrate// basic_istream::ignore #include <bits/stdc++.h>using namespace std; // Driver Codeint main(){     char first, last;     cout << "Enter a String: ";     // Get one character    first = cin.get();     // Ignore string until space occurs    cin.ignore(256, ' ');     // Get one character    last = std::cin.get();     cout << "Your initials are "         << first << ' '         << last << '\n';     return 0;}
Output: 
Reference: http://www.cplusplus.com/reference/istream/basic_istream/ignore/
gabaa406
akshaysingh98088
prachisoda1234
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Secondary Indexes on MAP Collection in Cassandra - GeeksforGeeks

17 Mar, 2021
In this article, we will discuss the overview of Secondary Indexes on MAP Collection in Cassandra and then will implement the exercise and will see how it actually works, and then finally will conclude the importance of Secondary Indexes on MAP Collection. Let’s discuss it one by one.
Pre-requisite –
Concept of indexing in Apache Cassandra
Collection Data Type in Apache Cassandra
Overview :Creating secondary Indexes on MAP Collection in Cassandra is very useful. So, here you will see the real use case of creating an index on a collection because it makes searching and querying data very efficient and fast. So if, you want to search based on a keyword then while searching and querying data, you can use the CONTAINS KEY keywords for a specific keyword in the MAP collection data type. In MAP collection data key-value pairs will be stored, and we will use KEY to search the data. Let’s understand the whole concept with the help of examples.
Syntax :In this, you will see the syntax part of how to create an index on collection. You can use the given below command as follows.
CREATE INDEX ON <table_name>(KEYS<map_column>)
Here, you will see the syntax of the WHERE clause part where you will use the CONTAINS keyword to search the specific value in the MAP collection. 
WHERE <map_column> CONTAINS KEY <key>
Example :Let’s consider you have existing keyspace namely cluster1 and then first we will create a user_data table by using CQL command as follows.
Step-1 : Creating table -user_data –
use cluster1;
create table user_data
           (
           user_id varchar,
           user_first_name varchar,
           user_last_name varchar,
           company varchar,
           user_tags map<varchar,varchar>,
           primary key(user_id)
           );
Step-2 : Creating Index on user_tags –
CREATE INDEX ON user_data (KEYS(user_tags))
Step-3 : Inserting data –
insert into user_data(user_id, user_first_name, user_last_name, company, user_tags)
values('Ashish01','Ashish','Rana','abc',{'GFG':'Geeks for Geeks','HTML':'HyperText Markup Language'});

insert into user_data(user_id, user_first_name, user_last_name, company, user_tags)
values('Ashish02','Ayush','NA','abc',{'GFG':'Geeks for Geeks','IDK':'I Do not Know'});

insert into user_data(user_id, user_first_name, user_last_name, company, user_tags)  
values('Ashish03','Ayushi','NA','abc',{'FYI':'For Your Information','IDK':'I Do not Know'});
Step-4 : Verifying and Reading data – 
select * from user_data;
Step-5 : Output – 
Step-6: Searching on the basis of specific keyword – 
select * from user_data where user_tags CONTAINS KEY 'GFG';
Step-7 : Output –
Apache
NoSQL
Articles
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
Difference between Class and Object
SQL | Date functions
SQL | WITH clause
ACID Properties in DBMS
SQL query to find second highest salary?
Normal Forms in DBMS
Introduction of B-Tree
calloc() versus malloc() in C

The function calloc() stands for contiguous location. It works similar to the malloc() but it allocate the multiple blocks of memory each of same size.
Here is the syntax of calloc() in C language,
void *calloc(size_t number, size_t size);
Here,
number − The number of elements of array to be allocated.
size − Size of allocated memory in bytes.
Here is an example of calloc() in C language,
 Live Demo
#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) calloc(n, sizeof(int));
   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");
   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   return 0;
}
Enter elements of array : 2 24 35 12
Sum : 73
In the above program, The memory block is allocated by calloc(). If the pointer variable is null, there is no memory allocation. If pointer variable is not null, user has to enter four elements of array and then sum of elements is calculated.
p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
   printf("\nError! memory not allocated.");
   exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
   scanf("%d", p + i);
   s += *(p + i);
}
The function malloc() is used to allocate the requested size of bytes and it returns a pointer to the first byte of allocated memory. It returns null pointer, if fails.
Here is the syntax of malloc() in C language,
pointer_name = (cast-type*) malloc(size);
Here,
pointer_name − Any name given to the pointer.
cast-type − The datatype in which you want to cast the allocated memory by malloc().
size − Size of allocated memory in bytes.
Here is an example of malloc() in C language,
 Live Demo
#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) malloc(n * sizeof(int));
   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");
   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   return 0;
}
Here is the output,
Enter elements of array : 32 23 21 8
Sum : 84
In the above program, four variables are declared and one of them is a pointer variable *p which is storing the memory allocated by malloc. Elements of array are printed by user and sum of elements is printed.
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
   printf("\nError! memory not allocated.");
   exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
   scanf("%d", p + i);
   s += *(p + i);
}
printf("\nSum : %d", s);
Check if two List objects are equal in C#

To check if two List objects are equal, the code is as follows −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<string> list1 = new List<string>();
      list1.Add("One");
      list1.Add("Two");
      list1.Add("Three");
      list1.Add("Four");
      list1.Add("Five");
      Console.WriteLine("Elements in List1...");
      foreach (string res in list1){
         Console.WriteLine(res);
      }
      List<string> list2 = new List<string>();
      list2.Add("India");
      list2.Add("US");
      list2.Add("UK");
      list2.Add("Canada");
      list2.Add("Poland");
      list2.Add("Netherlands");
      Console.WriteLine("Elements in List2...");
      foreach (string res in list2){
         Console.WriteLine(res);
      }
      Console.WriteLine("Is List2 equal to List1? = "+list2.Equals(list1));
   }
}
This will produce the following output −
Elements in List1...
One
Two
Three
Four
Five
Elements in List2...
India
US
UK
Canada
Poland
Netherlands
Is List2 equal to List1? = False
Let us see another example −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<string> list1 = new List<string>();
      list1.Add("One");
      list1.Add("Two");
      list1.Add("Three");
      list1.Add("Four");
      list1.Add("Five");
      Console.WriteLine("Elements in List1...");
      foreach (string res in list1){
         Console.WriteLine(res);
      }
      List<string> list2 = new List<string>();
      list2.Add("India");
      list2.Add("US");
      list2.Add("UK");
      list2.Add("Canada");
      list2.Add("Poland");
      list2.Add("Netherlands");
      Console.WriteLine("Elements in List2...");
      foreach (string res in list2){
         Console.WriteLine(res);
      }
      List<string> list3 = new List<string>();
      list3 = list2;
      Console.WriteLine("Is List3 equals to List2? = "+list3.Equals(list2));
   }
}
This will produce the following output −
Elements in List1...
One
Two
Three
Four
Five
Elements in List2...
India
US
UK
Canada
Poland Netherlands
Is List3 equals to List2? = True
Ints join() function in Java

The join() method of Ints class returns a string containing the supplied int values separated by separator. The syntax is as follows −
public static String
   join(String separator, int[] arr)
Here, separator parameter is something that should appear between consecutive values, whereas arr is an array of int values.
Let us first see an example −
import com.google.common.primitives.Ints;
class Demo {
   public static void main(String[] args) {
      int[] myArr = { 10, 20, 30, 40, 50, 60,70, 80, 90, 100 };
      System.out.println(Ints.join("-", myArr));
      int index = Ints.indexOf(myArr, 40);
      if (index != -1) {
         System.out.println("Element 40 is in the array at position " + (index+1));
      } else {
         System.out.println("Element 40 is not in the array");
      }
   }
}
10-20-30-40-50-60-70-80-90-100
Element 40 is in the array at position 4
Python - Working with .docx module

Word documents contain formatted text wrapped within three object levels. Lowest level- Run objects, Middle level- Paragraph objects and Highest level- Document object.
So, we cannot work with these documents using normal text editors. But we can manipulate these word documents in python using the python-docx module.
The first step is to install this third-party module python-docx. You can use pip “pip install python-docx”
After installation import “docx” NOT “python-docx”.
Use “docx.Document” class to start working with the word document.
# import docx NOT python-docx
import docx
# create an instance of a word document
doc = docx.Document()
# add a heading of level 0 (largest heading)
doc.add_heading('Heading for the document', 0)
# add a paragraph and store
# the object in a variable
doc_para = doc.add_paragraph('Your paragraph goes here, ')
# add a run i.e, style like
# bold, italic, underline, etc.
doc_para.add_run('hey there, bold here').bold = True
doc_para.add_run(', and ')
doc_para.add_run('these words are italic').italic = True
# add a page break to start a new page
doc.add_page_break()
# add a heading of level 2
doc.add_heading('Heading level 2', 2)
# pictures can also be added to our word document
# width is optional
doc.add_picture('path_to_picture')
# now save the document to a location
doc.save('path_to_document')
JavaScript Function Call

The JavaScript call() function allows us to use the same method from different objects. The parameters are passed separately here.
Following is the code for the JavaScript function call() −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript call()</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above buttons to check if adult or not
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let obj1 = { name: "Rohan", age: 22 };
   function checkAdult(vehicle, country) {
      if (this.age > 18) {
         sampleEle.innerHTML =this.name + " you are an adult and can drive " + vehicle +
         " in " + country;
      } else
      sampleEle.innerHTML = this.name + " you are an adult and cannot drive " + vehicle +
         " in " + country;
   }
   document.querySelector(".Btn").addEventListener("click", () => {
      checkAdult.call(obj1, 'car','INDIA');
   });
</script>
</body>
</html>
On clicking the “CLICK HERE” button −
Tryit Editor v3.6 - Show React

import React from 'react';
import ReactDOM from 'react-dom/client';

const myFirstElement = <h1>Hello React!</h1>

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myFirstElement);

/*
You are now watching
the React file 'index.js'
through our 'Show React' tool.
*/




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport"
      content="width=device-width, initial-scale=1" />
How to display long X-axis labels in a bar chart using plotly in R?

Plotly in R is a package specifically designed to create highly-interactive and publication-quality charts. The chart can be created by using plot_ly function of the package and there are three main arguments of plot_ly defined as x, y, and type, where x refers to the X-axis, y refers to the Y-axis and type refers to the chart type but the axes values are stored in a data frame or itself a shared.
Loading plotly package:
> library(plotly)
Consider the below data frame:
Live Demo
> x<-c("United States of America","United Kingdom","Republic of China")
> y<-c(501,510,505)
> df<-data.frame(x,y)
> df
x y
1 United States of America 501
2 United Kingdom 510
3 Republic of China 505
Creating the bar plot for x:
> plot_ly(x=x,y=y,type="bar")%>%layout(xaxis=list(tickangle=45))
Warning message:
`arrange_()` is deprecated as of dplyr 0.7.0.
Please use `arrange()` instead.
See vignette('programming') for more help
This warning is displayed once every 8 hours.
Call `lifecycle::last_warnings()` to see where this warning was generated.
Here it is showing a warning but it is not related to our chart hence there is no problem in ignoring it.
How to show alert dialog in Android?

This example demonstrates how do I show alert dialog in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Press The Back Button."
      android:textStyle="bold"
      android:textSize="24sp"
      android:layout_centerInParent="true" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   @Override
   public void onBackPressed() {
      AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
      builder.setMessage("Do you want to exit?");
      builder.setTitle("Alert!");
      builder.setCancelable(false);
      builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int which) {
            finish();
         }
      });
      builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
         }
      });
      AlertDialog alertDialog = builder.create();
      alertDialog.show();
   }
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
Get the sum of a column in all MySQL rows?

Use aggregate function SUM() to get the sum of a column in al rows. Let us first create a table −
mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Amount int
   );
Query OK, 0 rows affected (0.20 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Amount) values(50);
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(Amount) values(60);
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(Amount) values(70);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+
| Id | Amount |
+----+--------+
|  1 |     50 |
|  2 |     60 |
|  3 |     70 |
+----+--------+
3 rows in set (0.00 sec)
Following is the query to get the sum of all rows in MySQL.
mysql> select sum(Amount) from DemoTable;
This will produce the following output −
+-------------+
| sum(Amount) |
+-------------+
|         180 |
+-------------+
1 row in set (0.00 sec)
Bootstrap Inline Form

To create a form where all of the elements are inline, left aligned and labels are alongside, add the class .form-inline to the <form> tag.
You can try to run the following code to create an inline form in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <form class = "form-inline" role = "form">
         <div class = "form-group">
            <label class = "sr-only" for = "name">Full Name</label>
            <input type = "text" class = "form-control" id = "name" placeholder = "Enter Full Name">
         </div>
         <div class = "form-group">
            <label class = "sr-only" for = "inputfile">File input</label>
            <input type = "file" id = "inputfile">
         </div>
         <div class = "checkbox">
            <label><input type = "checkbox"> Check me out</label>
         </div>
         <button type = "submit" class = "btn btn-default">Submit</button>
      </form>
   </body>
</html>