code-rag-bench/online-tutorials huggingface dataset:
Abstract Base Classes in Python (abc)

A class is called an Abstract class if it contains one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and its abstract methods must be implemented by its subclasses.
Abstract base classes provide a way to define interfaces when other techniques like hasattr() would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and issubclass() functions. There are many built-in ABCs in Python. ABCs for Data structures like Iterator, Generator, Set, mapping etc. are defined in collections.abc module. The numbers module defines numeric tower which is a collection of base classes for numeric data types. The 'abc' module in Python library provides the infrastructure for defining custom abstract base classes.
'abc' works by marking methods of the base class as abstract. This is done by @absttractmethod decorator. A concrete class which is a sub class of such abstract base class then implements the abstract base by overriding its abstract methods.
The abc module defines ABCMeta class which is a metaclass for defining abstract base class. Following example defines Shape class as an abstract base class using ABCMeta. The shape class has area() method decorated by abstractmethod.
A Rectangle class now uses above Shape class as its parent and implementing the abstract area() method. Since it is a concrete class, it can be instantiated and imlemented area() method can be called.
import abc
class Shape(metaclass=abc.ABCMeta):
   @abc.abstractmethod
   def area(self):
      pass
class Rectangle(Shape):
   def __init__(self, x,y):
      self.l = x
      self.b=y
   def area(self):
      return self.l*self.b
r = Rectangle(10,20)
print ('area: ',r.area())
Note the abstract base class may have more than one abstract methods. The child class must implement all of them failing which TypeError will be raised.
the abc module also defines ABC helper class which can be used instead of ABCMeta class in definition of abstract base class.
class Shape(abc.ABC):
   @abc.abstractmethod
   def area(self):
      pass
Instead of subclassing from abstract base class, it can be registered as abstract base by register class decorator.
class Shape(abc.ABC):
   @abc.abstractmethod
   def area(self):
      pass
@Shape.register
class Rectangle():
   def __init__(self, x,y):
   self.l = x
   self.b=y
   def area(self):
      return self.l*self.b
You may also provide class methods and static methods in abstract base class by decorators @abstractclassmethod and @abstractstatic method decorators respectively.
JavaScript - Date getHours() Method

Javascript Date getHours() method returns the hour in the specified date according to local time. The value returned by getHours() is an integer between 0 and 23.
Its syntax is as follows −
Date.getHours()

Returns the hour in the specified date according to local time.
Try the following example.
<html>
   <head>
      <title>JavaScript getHours Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var dt = new Date("December 25, 1995 23:15:00");
         document.write("getHours() : " + dt.getHours() ); 
      </script>      
   </body>
</html>
getHours() : 23 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to reset the primary key of a table in mysql?

The reset the primary key of a table means to reset the auto_increment property to 1. The syntax is as follows to reset the primary key of a table.
alter table yourTableName auto_increment = 1;
To understand, let us create a table −
mysql> create table ResetPrimaryKey
−> (
   −> Id int auto_increment,
   −> PRIMARY KEY(Id)
−> );
Query OK, 0 rows affected (0.59 sec)
Insert some records into the table. The query to insert records is as follows −
mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.18 sec)

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.15 sec)

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.09 sec)

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.09 sec)
Now you can display all records with the help of select statement. The query is as follows −
mysql> select *from ResetPrimaryKey;
The following is the output that displays only the ID, which is a Primary Key:
+----+
| Id |
+----+
| 1  |
| 2  |
| 3  |
| 4  |
+----+
4 rows in set (0.00 sec)
Here is the query to reset the primary key of a table using alter −
mysql> alter table ResetPrimaryKey auto_increment = 1;
Query OK, 0 rows affected (0.21 sec)
Records: 0 Duplicates: 0 Warnings: 0
The query to check that we have added auto_increment property successfully or not:
mysql> desc ResetPrimaryKey;
The following is the output −
+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| Id    | int(11) | NO   | PRI | NULL    | auto_increment |
+-------+---------+------+-----+---------+----------------+
1 row in set (0.11 sec)
How to do groupby on a multiindex in Pandas?

Multiindex Data Frame is a data frame with more than one index. Let’s say the following is our csv stored on the Desktop −
At first, import the pandas library and read the above CSV file −
import pandas as pd

df = pd.read_csv("C:/Users/amit_/Desktop/sales.csv") print(df)
We will form the ‘Car‘ and ‘Place‘ columns of the Dataframe as the index −
df = df.set_index(['Car', 'Place'])
The DataFrame is now a multi-indexed DataFrame having the ‘Car‘ and ‘Place‘ columns as an index.
Now, let us use groupby on the multiindex dataframe:
res = df.groupby(level=['Car'])['UnitsSold'].mean() print(res)
Following is the code −
import pandas as pd

df = pd.read_csv("C:/Users/amit_/Desktop/sales.csv")
print(df)

# set Car and Place columns of the DataFrame as index
df = df.set_index(['Car', 'Place'])

# sorting
df.sort_index()

# groupby on multiindex datafram
res = df.groupby(level=['Car'])['UnitsSold'].mean()
print(res)
This will produce the following output −
          Car         Place       Sold
0         BMW         Delhi         95
1    Mercedes     Hyderabad         80
2  Lamborgini    Chandigarh         80
3        Audi     Bangalore         75
4    Mercedes     Hyderabad         90
5     Porsche        Mumbai         90
6  RollsRoyce        Mumbai         95
7         BMW         Delhi         50
Car
Audi       75.8
BMW        72.5
Lamborgini 80.0
Mercedes   85.0
Porsche    90.0
RollsRoyce 95.0
Name: UnitsSold, dtype: float64
How do you set, clear, and toggle a bit in C/C++?

You can set clear and toggle bits using bitwise operators in C, C++, Python, and all other programming languages that support these operations. You also need to use the bitshift operator to get the bit to the right place.
To set a bit, we'll need to use the bitwise OR operator −
#include<iostream>
using namespace std;
int main() {
   int i = 0, n;
   
   // Enter bit to be set:
   cin >> n;
   i |= (1 << n); // Take OR of i and 1 shifted n positions
   cout << i;
   return 0;
}
If you enter 4, This will give the output −
16
because 16 is equivalent to 10000 in binary.
To clear a bit, we'll need to use the bitwise AND operator(&) and bitwise NOT operator(~) −
#include<iostream>
using namespace std;
int main() {
   // i is 110 in binary
   int i = 6, n;
   
   // Enter bit to be cleared:
   cin >> n;
   i &= ~(1 << n); // Take OR of i and 1 shifted n positions negated
   cout << i;
   return 0;
}
If you enter 1, This will give the output −
4
because 110 becomes 100 which is equivalent to 4 in decimal.
To toggle a bit, we'll need to use the bitwise XOR operator(^) −
#include<iostream>
using namespace std;
int main() {
   // i is 110 in binary
   int i = 6, n;
   
   // Enter bit to be toggled:
   cin >> n;
   i ^= (1 << n); // Take XOR of i and 1 shifted n positions
   cout << i;
   return 0;
}
If you enter 1, This will give the output −
4
because 110 becomes 100 which is equivalent to 4 in decimal.
Python program to repeat M characters of a string N times

04 Jan, 2021
In this article, the task is to write a Python program to repeat M characters of string N times.
Method 1:
Define a function that will take a word, m, n values as arguments.If M is greater than the length of the word. Set m value equal to the length of the wordNow store the characters needed to be repeated into a string named repeat_string using slicing.Initialize an empty string named as a resultConcatenate the repeat_string to result for n times.Now print the string.
Define a function that will take a word, m, n values as arguments.
If M is greater than the length of the word. Set m value equal to the length of the word
Now store the characters needed to be repeated into a string named repeat_string using slicing.
Initialize an empty string named as a result
Concatenate the repeat_string to result for n times.
Now print the string.
Below is the implementation:
Python3
def repeat(word, m, n):        # if number of characters greater than length of word.    # set number of characters = length of word    if(m > len(word)):        m = len(word)              repeat_word = word[:m]    result = ""          for i in range(n):        result = result+repeat_word    print(result)  # driver coderepeat("geeks", 2, 3)
Output:
gegege
Method 2:
Define a function which will take a word, m, n values as arguments.if M is greater than length of word. set m value equal to length of wordNow store the characters needed to be repeated into a string named repeat_string using slicing.Multiply the repeat_string with n.Now print the string.
Define a function which will take a word, m, n values as arguments.
if M is greater than length of word. set m value equal to length of word
Now store the characters needed to be repeated into a string named repeat_string using slicing.
Multiply the repeat_string with n.
Now print the string.
Python3
def repeat(word, m, n):        # if number of characters greater than length of word.    # set number of characters = length of word    if(m > len(word)):        m = len(word)              repeat_word = word[:m]    print(repeat_word*n)  # driver coderepeat("geeks", 2, 3)
Output:
gegege
Picked
Python string-programs
Python
Python Programs
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python PIL | GaussianBlur() method

14 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method.
PIL.ImageFilter.GaussianBlur() method create Gaussian blur filter.
Syntax: PIL.ImageFilter.GaussianBlur(radius=5)
Parameters:radius – blur radius. Changing value of radius the different intensity of GaussianBlur image were obtain.
Returns type: An image.
Image Used:
     # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter   # creating a image object im1 = Image.open(r"C:\Users\System-Pc\Desktop\leave.JPG")   # applying the Gaussian Blur filter im2 = im1.filter(ImageFilter.GaussianBlur(radius = 5))  im2.show() 
Output:
radius:radius value used here is 2.
Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter   # creating a image object im1 = Image.open(r"C:\Users\System-Pc\Desktop\leave.JPG")   # applying the Gaussian Blur filter im2 = im1.filter(ImageFilter.GaussianBlur(radius = 2))  im2.show() 
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to deal with “could not find function” error in R?

The error “could not find function” occurs due to the following reasons −
Function name is incorrect. Always remember that function names are case sensitive in
R.
Function name is incorrect. Always remember that function names are case sensitive in
R.
The package that contains the function was not installed. We have to install packages
in R once before using any function contained by them. It can be done as
install.packages("package_name")
The package that contains the function was not installed. We have to install packages
in R once before using any function contained by them. It can be done as
install.packages("package_name")
The package was not loaded before using the function. To use the function that is
contained in a package we need to load the package and it can be done as
library("package_name").
The package was not loaded before using the function. To use the function that is
contained in a package we need to load the package and it can be done as
library("package_name").
Version of R is older where the function you are using does not exist.
Version of R is older where the function you are using does not exist.
If you have installed and loaded many packages but forgot which package contains the
function you are using then you can do it by using getAnywhere
> library(ggplot2)
> library(BSDA)
Loading required package: lattice
Attaching package: ‘BSDA’
The following object is masked from ‘package:datasets’ −
Orange
> library(purrr)
> getAnywhere(ggplot)
A single object matching ‘ggplot’ was found
It was found in the following places
package:ggplot2
namespace:ggplot2
with value
function (data = NULL, mapping = aes(), ..., environment = parent.frame()){
   UseMethod("ggplot")
}
<bytecode: 0x0000000011201848>
<environment: namespace:ggplot2>
Here we have loaded three packages, named ggplot2, BSDA, and purr. Suppose we
wanted to know which package contains ggplot function. So, we used getAnywhere and
it returns the package name as ggplot2.
You should make sure that you do not make the mistakes mentioned above. If you use an
older version of R but want to perform calculations using a function that is created for a
newer version then it would not be possible. But it can become possible if you use
package backports to make newly added functions available to older version of R. Also,
you need to find the list of function that need to be backported on the git repo of
backports. Just remember that R versions older than R3.0.0 are not compatible with
packages built for R3.0.0 and later versions.
Object.assign() in JavaScript?

This method is used to copy one or more source objects to a target object. It invokes getters and setters since it uses both 'get' on the source and 'Set' on the target. It returns the target object which has properties and values copied from the target object. This method does not throw on null or undefined source values.
Object.assign(target, ...source objects);
It takes source objects and a target object as parameters and push the source objects into the target object and display the target object.
In the following example, the properties from the source objects  "obj1", "obj2", and "obj3" were pushed into a target object "obj" and the target object is returned as the output.
<html>
<body>
<script>
   var obj1 = { a: 10, b:20 };
   var obj2 = { c: 30, d:40 };
   var obj3 = { e: 50 };
   var obj = Object.assign({}, obj1, obj2, obj3);
   document.write(JSON.stringify(obj));
</script>
</body>
</html>
{"a":10,"b":20,"c":30,"d":40,"e":50}
In the following example, there are multiple instances of some of the properties of the objects. In this case the method Object.assign() takes the lastly assigned value of a property. For instance, in all the 3 objects "obj1", "obj2", and "obj3 property 'c' is common and assigned values such as 1,3 and 0 respectively. The value of property 'c' in obj3 overrides the other previously assigned values 1 and 3. So if we look at the output, property 'c' is assigned with a value 0.
<html>
<body>
<script>
   var obj1 = { a: 10, b:20, c:1 };
   var obj2 = { b: 30, d:10, c:3 };
   var obj3 = { e: 60, d:70, c:0 };
   var obj = Object.assign({}, obj1, obj2, obj3);
   document.write(JSON.stringify(obj));
</script>
</body>
</html>
{"a":10,"b":30,"c":0,"d":70,"e":60}
SQL | Distinct Clause

11 Sep, 2020
The distinct keyword is used in conjunction with select keyword. It is helpful when there is a need of avoiding duplicate values present in any specific columns/table. When we use distinct keyword only the unique values are fetched. 
Syntax : 
SELECT DISTINCT column1, column2 
FROM table_name 

column1, column2 : Names of the fields of the table.
table_name : Table from where we want to fetch the records.
This query will return all the unique combinations of rows in the table with fields column1, column2. 
NOTE: If distinct keyword is used with multiple columns, the distinct combination is displayed in the result set. 
Table – Student
Queries
To fetch unique names from the NAME field – 
SELECT DISTINCT NAME 
FROM Student;

Output : 
To fetch a unique combination of rows from the whole table – 
SELECT DISTINCT * 
FROM Student;

Output :  
Note : Without the keyword distinct in both the above examples 6 records would have been fetched instead of 4, since in the original table there are 6 records with the duplicate values.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Anshika Goyal
SQL-Clauses-Operators
Articles
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCS Placement Paper | Email Writing Question 10

21 May, 2019
Pre-requisite: Procedure to E-mail WritingThis is a TCS model placement email-writing question. It covers the important directions along with a sample solution to the question.
Directions:
Use all the phrases given.Minimum words should be 70 otherwise your email cannot be validated.Addressing and signing should be done as in the question given.Common grammatical rules, punctuation should be according to standard English.You can use your own phrases along with the phrases given.
Use all the phrases given.
Minimum words should be 70 otherwise your email cannot be validated.
Addressing and signing should be done as in the question given.
Common grammatical rules, punctuation should be according to standard English.
You can use your own phrases along with the phrases given.
Question:As your company is doing good business and expanding, your company is relocating its office to a new address. Using the following phrases, write an email with a minimum of 70 words and a maximum of 100 words to your customer informing the change in address.
Phrases:
near outer ring road - shifting to - bigger office space - November 10 -
change in telephone number - new address is provided below - fourth floor - 
Cessna Business Park.

Solution – Sample E-mail:
Dear All,It gives a pleasure in announcing the expansion of this company, a sign of growing business and increasing clientele. For a better productivity result, we are relocating the company and shifting to a bigger office space from November 10th onwards. New facilities and amenities shall be installed along with modern state of art amenities. There has been a change in telephone number along with the new address is provided below:Fourth Floor, Cessna Business Park(Near Outer Ring Road), Noida.Phone: 1234567890Please make a note of this to serve our clients better.Thanks and Regards
Note: You can write your own versions of e-mail keeping in mind the points needed to be taken care of while an e-mail. Refer Procedure to E-mail Writing.
interview-preparation
placement preparation
TCS
Placements
TCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
list front() function in C++ STL

24 Jun, 2022
The list::front() is a built-in function in C++ STL which is used to return a reference to the first element in a list container. Unlike the list::begin() function, this function returns a direct reference to the first element in the list container. Syntax: 
list_name.front() 
Parameters: This function does not accept any parameter, it simply returns a reference to the first element in the list container. Return Value: This function returns a direct reference to the first element in the list container. Exception: This function creates an undefined behavior when used with an empty list container. Below program illustrates the list::front() function. 
CPP
// CPP program to illustrate the// list::front() function#include <bits/stdc++.h>using namespace std; int main(){    // Creating a list    list<int> demoList;     // Add elements to the List    demoList.push_back(10);    demoList.push_back(20);    demoList.push_back(30);    demoList.push_back(40);     // get the first element using front()    int ele = demoList.front();     // Print the first element    cout << ele;     return 0;}
10
Note: This function works in constant time complexity.
Time complexity: O(1)
Auxiliary Space: O(n) where n is size of the list
kumargaurav97520
CPP-Functions
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
Python | Farthest point on horizontal lines in 2D plane

27 Aug, 2019
Sometimes, while in competitive programming, we might be facing a problem which is of geometry domain and works with x-y coordinate system. The list of tuple can be used to store the same. And along with this, there might be a problem in which we need point with max value of x axis with similar y axis i.e farthest point on horizontal lines. Let’s discuss certain ways to discuss this problem.
Method : Using list comprehension + max()This is a generic brute force method applied to get the max x axis point for common y axis, made as 1 liner using list comprehension. The max() is used to find the max of x axis element.
# Python3 code to demonstrate working of# Farthest point on horizontal lines in 2D plane# Using list comprehension + max()from collections import defaultdict  # initializing listtest_list = [(1, 6), (4, 6), (2, 6), (6, 8), (1, 8), (2, 9)]  # printing original listprint("The original list is : " +  str(test_list))  # Using list comprehension + max()# Farthest point on horizontal lines in 2D planetemp = defaultdict(list)for key, val in test_list:   temp[val].append(key)res = [(key, val) for key, val in test_list if max(temp[val]) == key]  # Printing resultprint("The list after filtering just maximum points on lines : " +  str(res))
The original list is : [(1, 6), (4, 6), (2, 6), (6, 8), (1, 8), (2, 9)]
The list after filtering just maximum points on lines : [(4, 6), (6, 8), (2, 9)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Draw smiling face emoji using Turtle in Python

07 Oct, 2020
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle. To move turtle, there are some functions i.e forward(), backward(), etc.
In this article, we will see how to draw a smiling face emoji using the Turtle module.
Following steps are used :
Import turtle.
Make objects.
Draw a circle and fill yellow color.
Draw eyes with two circles and fill white and black color respectively.
Draw circle for nose and fill black color.
Draw semi circle for mouth.
Draw semi circle for tongue and fill red color.
Below is the implementation  :
Python3
# Python program to draw smile# face emoji using turtleimport turtle # turtle objectpen = turtle.Turtle() # function for creation of eyedef eye(col, rad):    pen.down()    pen.fillcolor(col)    pen.begin_fill()    pen.circle(rad)    pen.end_fill()    pen.up()  # draw facepen.fillcolor('yellow')pen.begin_fill()pen.circle(100)pen.end_fill()pen.up() # draw eyespen.goto(-40, 120)eye('white', 15)pen.goto(-37, 125)eye('black', 5)pen.goto(40, 120)eye('white', 15)pen.goto(40, 125)eye('black', 5) # draw nosepen.goto(0, 75)eye('black', 8) # draw mouthpen.goto(-40, 85)pen.down()pen.right(90)pen.circle(40, 180)pen.up() # draw tonguepen.goto(-10, 45)pen.down()pen.right(180)pen.fillcolor('red')pen.begin_fill()pen.circle(10, 180)pen.end_fill()pen.hideturtle()
smiling face
2. Let’s draw a different smiling emoji which is drawn above just to understand it better.
Following steps are used :
Import turtle.
Define pen size and pen width.
Draw a circle .
Draw eyes with two circles and fill red color respectively.
Draw triangle for nose ..
Draw semi circle for mouth.
Below is the implementation for the same:-
Python3
#import moduleimport turtle #define pen sizeturtle.pensize (5) #define pen colorturtle.pencolor ("Blue") #for outer bigger circleturtle.fillcolor ("red")turtle.penup ()turtle.goto (0, -200)turtle.pendown ()turtle.circle (200) #for eyesturtle.penup ()turtle.goto (-100,50)turtle.pendown ()turtle.begin_fill ()turtle.circle (17.5)turtle.end_fill ()turtle.penup ()turtle.goto (100,50)turtle.pendown ()turtle.begin_fill ()turtle.circle (17.5)turtle.end_fill () #for noseturtle.penup ()turtle.goto (0,50)turtle.pendown ()turtle.circle (-70, steps=3) # for smileturtle.penup ()turtle.goto (-100, -70)turtle.pendown ()turtle.right (90)turtle.circle (100,180)turtle.mainloop ()
Output:
pulkitagarwal03pulkit
Python-projects
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to print Emojis

11 Feb, 2022
There are multiple ways we can print the Emojis in Python. Let’s see how to print Emojis with Unicodes, CLDR names and emoji module. Using Unicodes: Every emoji has a Unicode associated with it. Emojis also have a CLDR short name, which can also be used. From the list of unicodes, replace “+” with “000”. For example – “U+1F600” will become “U0001F600” and prefix the unicode with “\” and print it. 
Python3
# grinning faceprint("\U0001f600") # grinning squinting faceprint("\U0001F606") # rolling on the floor laughingprint("\U0001F923")
Output:  
  Using CLDR short name:  
Python3
# grinning faceprint("\N{grinning face}") # slightly smiling faceprint("\N{slightly smiling face}") # winking faceprint("\N{winking face}")
Output:  
  Using emoji module: Emojis can also be implemented by using the emoji module provided in Python. To install it run the following in the terminal. 
pip install emoji
emojize() function requires the CLDR short name to be passed in it as the parameter. It then returns the corresponding emoji. Replace the spaces with underscore in the CLDR short name. 
Python3
# import emoji moduleimport emoji  print(emoji.emojize(":grinning_face_with_big_eyes:"))print(emoji.emojize(":winking_face_with_tongue:"))print(emoji.emojize(":zipper-mouth_face:"))
Output:  
  demojize() function converts the emoji passed into its corresponding CLDR short name.  
  Below is a list of some common emoji Unicodes with their CLDR short names:
 
 
varshagumber28
sumitgumber28
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Why “0” is not equal to false in if condition in JavaScript ?

28 Jun, 2019
The reason behind this behavior is that JavaScript treats non-empty string as true. First, “0” is converted into its boolean value, by automatic type conversion which is true. Therefore, if statement executes.
Example: This example illustrates why “0” is not equal to false in if() condition.
<script>          // JavaScript script to demonstrate     // why “0” is not equal to false in    // ‘if’ condition          function GFG() {              // Print type of "0"        document.write(typeof "0" + "</br>");              // Print boolean value of "0"        document.write(Boolean("0") + "</br>");                  // Boolean value of "0" is true so        // 'if' part will execute        if("0") {            document.write("if part executed");        }        else {            document.write("else part executed");        }    }          // Driver code    GFG();  </script>                    
Output:
string
true
if part executed

JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Roadmap to Learn JavaScript For Beginners
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to remove the digits after the decimal point in axis ticks in Matplotlib?

To remove the digits after the decimal point in axis ticks in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create x and y data points using numpy.
Create a figure and a set of subplots.
Create a figure and a set of subplots.
To set the xtick labels only in digits, we can use x.astype(int) method.
To set the xtick labels only in digits, we can use x.astype(int) method.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.array([1.110, 2.110, 4.110, 5.901, 6.00, 7.90, 8.90])
y = np.array([2.110, 1.110, 3.110, 9.00, 4.001, 2.095, 5.890])

fig, ax = plt.subplots()

ax.plot(x, y)

ax.set_xticklabels(x.astype(int))

plt.show()
Batch Script - String Concatenation

You can use the set operator to concatenate two strings or a string and a character, or two characters. Following is a simple example which shows how to use string concatenation.
@echo off 
SET a = Hello 
SET b = World 
SET c=%a% and %b% 
echo %c%
The above command produces the following output.
Hello and World

 Print
 Add Notes
 Bookmark this page
Set Axis Limits of Plot in R

23 Aug, 2021
In this article, we will be looking at the approach to set the axis limits of the plot in R programming language. 
Axis limit of the plot basically refers to the scaling of the x-axis and the y-axis of the given plot.
In this approach to set the axis limits of the given plot, the user here just simply use the xlim argument with the required parameters to set the limits of the x-axis limits and use the ylim argument with the required parameters to set the limits of the y-axis limits in the plot function of the R programming language to set the axis limits of the plot given.
Plot function: This is a Generic function for plotting R objects.
Syntax: plot(x, y,xlim,ylim ...)
Arguments:
x: the x coordinates of points in the plot.
y: the y coordinates of points in the plot.
xlim: Set or query x-axis limits
ylim: Set or query y-axis limits
In this example, we will be setting up the limits of the x-axis from -20 to 20 of the given plot of 10 data points in it using the xlim argument of the plot function in the R programming language.
R
x = c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1)y = c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6)  plot(x, y, xlim = c(-20, 20))
Output:
In this example, we will be setting up the limits of the y-axis from -20 to 20 of the given plot of 10 data points in it using the ylim argument of the plot function in the R programming language.
R
x = c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1)y = c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6)  plot(x, y, ylim = c(-20, 20))
Output:
In this example, we will be setting up the limits of the x-axis and y-axis from -20 to 20 of the given plot of 10 data points in it using the xlim and ylim argument of the plot function in the R programming language.
R
x = c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1)y = c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6)  plot(x, y, xlim = c(-20, 20),     ylim = c(-20, 20))
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use Grid Component in ReactJS?

18 Jan, 2021
The Material Design responsive layout grid adapts to screen size and orientation, ensuring consistency across layouts. Material UI for React has this component available for us and it is very easy to integrate. We can the Grid component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';import { makeStyles, createStyles, Theme } from '@material-ui/core/styles';import Paper from '@material-ui/core/Paper';import Grid from '@material-ui/core/Grid';  const useStyles = makeStyles((theme: Theme) =>  createStyles({    paper: {      padding: theme.spacing(2),      textAlign: 'center',      color: theme.palette.text.secondary,    },    root: {      flexGrow: 1,    },  }),);  export default function FullWidthGrid() {  const classes = useStyles();    return (    <div style={{ width: '90%', backgroundColor: 'green',                   padding: '10px' }}>      <Grid container spacing={3}>        <Grid item xs={12}>          <Paper className={classes.paper}>              GEEKSFORGEEKS ---> GRID COMPONENT DEMO          </Paper>        </Grid>        <Grid item xs={6} sm={3}>          <Paper className={classes.paper}>1/4 Size</Paper>        </Grid>        <Grid item xs={6} sm={3}>          <Paper className={classes.paper}>1/4 Size</Paper>        </Grid>        <Grid item xs={6} sm={3}>          <Paper className={classes.paper}>1/4 Size</Paper>        </Grid>        <Grid item xs={6} sm={3}>          <Paper className={classes.paper}>1/4 Size</Paper>        </Grid>        <Grid item xs={12} sm={6}>          <Paper className={classes.paper}>1/2 Size</Paper>        </Grid>        <Grid item xs={12} sm={6}>          <Paper className={classes.paper}>1/2 Size</Paper>        </Grid>        <Grid item xs={12}>          <Paper className={classes.paper}>Full Size</Paper>        </Grid>      </Grid>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
JavaScript
ReactJS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Decimal normalize() method

17 Sep, 2019
Decimal#normalize() : normalize() is a Decimal class method which returns the simplest form of the Decimal value.
Syntax:  Decimal.normalize()

Parameter:  Decimal values

Return:  the simplest form of the Decimal value. 

Code #1 : Example for normalize() method
# Python Program explaining # normalize() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal(-1)  b = Decimal('0.142857')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.normalize() methodprint ("\n\nDecimal a with normalize() method : ", a.normalize())  print ("Decimal b with normalize() method : ", b.normalize())
Output :
Decimal value a :  -1
Decimal value b :  0.142857


Decimal a with normalize() method :  -1
Decimal b with normalize() method :  0.142857


Code #2 : Example for normalize() method
# Python Program explaining # normalize() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal('-3.14')  b = Decimal('321e + 5')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.normalize() methodprint ("\n\nDecimal a with normalize() method : ", a.normalize())  print ("Decimal b with normalize() method : ", b.normalize())
Output :
Decimal value a :  -3.14
Decimal value b :  3.21E+7


Decimal a with normalize() method :  -3.14
Decimal b with normalize() method :  3.21E+7


Python-Functions
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
GATE | GATE CS 2013 | Question 17

28 Jun, 2021
Which of the following statements is/are FALSE?
1. For every non-deterministic Turing machine, 
   there exists an equivalent deterministic Turing machine.
2. Turing recognizable languages are closed under union 
   and complementation.
3. Turing decidable languages are closed under intersection 
   and complementation.
4. Turing recognizable languages are closed under union 
   and intersection. 
(A) 1 and 4 only(B) 1 and 3 only(C) 2 only(D) 3 onlyAnswer: (C)Explanation: A recognizer of a language is a machine that recognizes that language.A decider of a language is a machine that decides that language.
Both types of machine halt in the Accept state on strings that are in the languageA Decider also halts if the string is not in the languageA Recogizer MAY or MAY NOT halt on strings that are not in the language
On all input:A Decider MUST halt (in Accept or Reject state)A Recogizer MAY or MAY NOT halt on some strings (Q: Which ones?)
A language is Turing-decidable (or decidable) if some Turing machine decides it. Aka Recursive Language.
A language is Turing-recognizable if some Turing machine recognizes it. Aka Recursively Enumerable Language.
Source: http://www.radford.edu/~nokie/classes/420/Chap3-Langs.html
Recursive (Turing Decidable) languages are closed under followingKleene star, concatenation, union, intersection, complement and set difference.
Recursively enumerable language are closed under Kleene star, concatenation, union, intersection. They are NOT closed under complement or set difference.Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
StringBuilder length() in Java with Examples

15 Oct, 2018
The length() method of StringBuilder class returns the number of character the StringBuilder object contains. The length of the sequence of characters currently represented by this StringBuilder object is returned by this method.
Syntax:
public int length()
Return Value: This method returns length of sequence of characters contained by StringBuilder object.
Below programs demonstrate the length() method of StringBuilder Class:
Example 1:
// Java program to demonstrate// the length() Method.  class GFG {    public static void main(String[] args)    {          // create a StringBuilder object        // with a String pass as parameter        StringBuilder            str            = new StringBuilder("WelcomeGeeks");          // print string        System.out.println("String = "                           + str.toString());          // get length of StringBuilder object        int length = str.length();          // print length        System.out.println("length of String = "                           + length);    }}
String = WelcomeGeeks
length of String = 12

Example 2:
// Java program to demonstrate// the length() Method.  class GFG {    public static void main(String[] args)    {          // create a StringBuilder object        // with a String pass as parameter        StringBuilder            str            = new StringBuilder("India is Great");          // print string        System.out.println("String = "                           + str.toString());          // get length of StringBuilder object        int length = str.length();          // print length        System.out.println("length of String = "                           + length);    }}
String = India is Great
length of String = 14

Reference:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#length()
java-basics
Java-Functions
Java-StringBuilder
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Multidimensional Arrays in Java
Collections in Java
Stream In Java
Set in Java
Initializing a List in Java
Python | Pandas Index.value_counts()

23 Nov, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas Index.value_counts() function returns object containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default. 
Syntax: Index.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)Parameters : normalize : If True then the object returned will contain the relative frequencies of the unique values. sort : Sort by values ascending : Sort in ascending order bins : Rather than count values, group them into half-open bins, a convenience for pd.cut, only works with numeric data dropna : Don’t include counts of NaN.Returns : counts : Series  
Example #1: Use Index.value_counts() function to count the number of unique values in the given Index. 
Python3
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick',                'Harry', 'Arther'], name ='Student') # Print the Indexprint(idx)
Output : 
Index(['Harry', 'Mike', 'Arther', 'Nick', 'Harry', 'Arther'], dtype='object', name='Student')
Let’s find the count of all unique values in the index. 
Python3
# find the count of unique values in the indexidx.value_counts()
Output : 
Harry     2
Arther    2
Nick      1
Mike      1
Name: Student, dtype: int64
The function has returned the count of all unique values in the given index. Notice the object returned by the function contains the occurrence of the values in descending order.   Example #2: Use Index.value_counts() function to find the count of all unique values in the given index.
Python3
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([21, 10, 30, 40, 50, 10, 50]) # Print the Indexprint(idx)
Output : 
Int64Index([21, 10, 30, 40, 50, 10, 50], dtype='int64')
Let’s count the occurrence of all the unique values in the Index.
Python3
# for finding the count of all# unique values in the index.idx.value_counts()
Output : 
10    2
50    2
30    1
21    1
40    1
dtype: int64
The function has returned the count of all unique values in the index.
gopalsakhwala18
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java String concat() with examples

27 Oct, 2021
The Java String concat() method concatenates one string to the end of another string. This method returns a string with the value of the string passed into the method, appended to the end of the string. Consider the below illustration:
Illustration:
Input:  String 1   : abc
        String 2   : def
        String n-1 : ...
        String n   : xyz
Output: abcdef...xyz        
Syntax:
public String concat(String anostr)   
Parameter: A string to be concatenated at the end of the other string
Return: Concatenated(combined) string  
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Example:
java
// Java program to Illustrate Working of concat() method// with Strings// By explicitly assigning result  // Main classclass GFG {      // Main driver method    public static void main(String args[])    {        // Custom input string 1        String s = "Hello ";          // Custom input string 2        s = s.concat("World");          // Explicitly assigning result by        // Combining(adding, concatenating strings)        // using concat() method          // Print and display combined string        System.out.println(s);    }}
Hello World
Example 2:
java
// Java program to Illustrate Working of concat() method// in strings where we are sequentially// adding multiple strings as we need  // Main classpublic class GFG {      // Main driver method    public static void main(String args[])    {        // Custom string 1        String str1 = "Computer-";          // Custom string 2        String str2 = "-Science";          // Combining above strings by        // passing one string as an argument        String str3 = str1.concat(str2);          // Print and display temporary combined string        System.out.println(str3);          String str4 = "-Portal";        String str5 = str3.concat(str4);        System.out.println(str5);    }}
Computer--Science
Computer--Science-Portal
As perceived from the code we can do as many times as we want to concatenate strings bypassing older strings with new strings to be contaminated as a parameter and storing the resultant string in String datatype.
Akanksha_Rai
solankimayank
adnanirshad158
Java-Functions
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.