code-rag-bench/online-tutorials huggingface dataset:
How to open an activity after receiving a PUSH notification in Android?

This example demonstrate about How to open an activity after receiving a PUSH notification 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 src/MyFirebaseMessagingService.java
package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.app.PendingIntent ;
import android.content.Context ;
import android.content.Intent ;
import android.support.v4.app.NotificationCompat ;
import com.google.firebase.messaging.FirebaseMessagingService ;
import com.google.firebase.messaging.RemoteMessage ;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
   public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
   private final static String default_notification_channel_id = "default" ;
   @Override
   public void onNewToken (String s) {
      super .onNewToken(s) ;
   }
   @Override
   public void onMessageReceived (RemoteMessage remoteMessage) {
      super .onMessageReceived(remoteMessage) ;
      Intent notificationIntent = new Intent(getApplicationContext() , MainActivity. class ) ;
      notificationIntent.putExtra( "NotificationMessage" , "I am from Notification" ) ;
      notificationIntent.addCategory(Intent. CATEGORY_LAUNCHER ) ;
      notificationIntent.setAction(Intent. ACTION_MAIN ) ;
      notificationIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_SINGLE_TOP ) ;
      PendingIntent resultIntent = PendingIntent. getActivity (getApplicationContext() , 0 , notificationIntent , 0 ) ; 
      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext() , 
         default_notification_channel_id )
         .setSmallIcon(R.drawable. ic_launcher_foreground )
         .setContentTitle( "Test" )
         .setContentText( "Hello! This is my first push notification" )
         .setContentIntent(resultIntent) ;
      NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE ) ;
      if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
         int importance = NotificationManager. IMPORTANCE_HIGH ;
         NotificationChannel notificationChannel = new
         NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
         mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
         assert mNotificationManager != null;
         mNotificationManager.createNotificationChannel(notificationChannel) ;
      }
      assert mNotificationManager != null;
      mNotificationManager.notify(( int ) System. currentTimeMillis () ,
      mBuilder.build()) ;
   }
}
Click  here  to download the project code
html.unescape() in Python - GeeksforGeeks

22 Apr, 2020
With the help of html.unescape() method, we can convert the ascii string into html script by replacing ascii characters with special characters by using html.escape() method.
Syntax : html.unescape(String)
Return : Return a html script.
Example #1 :In this example we can see that by using html.unescape() method, we are able to convert the ascii string into html script by using this method.
# import htmlimport html  s = '<html><head></head><body><h1>This is python</h1></body></html>'temp = html.escape(s)# Using html.unescape() methodgfg = html.unescape(temp)  print(gfg)
Output :
Example #2 :
# import htmlimport html  s = '<html><head></head><body><h1>GeeksForGeeks</h1></body></html>'temp = html.escape(s)# Using html.unescape() methodgfg = html.unescape(temp)  print(gfg)
Output :
Python html-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
How to plot a smooth 2D color plot for z = f(x, y) in Matplotlib?

To plot a smooth 2D color plot for z = f(x, y) in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Get z data points using f(x, y).
Display the data as an image, i.e., on a 2D regular raster, with z data points.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

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

def f(x, y):
   return np.array([i * i + j * j for j in y for i in x]).reshape(5, 5)

x = y = np.linspace(-1, 1, 5)
z = f(x, y)

plt.imshow(z, interpolation='bilinear')

plt.show()
Pandas – Remove special characters from column names

05 Sep, 2020
Let us see how to remove special characters like #, @, &, etc. from column names in the pandas data frame.  Here we will use replace function for removing special character.
Example 1: remove a special character from column names
Python
# import pandasimport pandas as pd  # create data frameData = {'Name#': ['Mukul', 'Rohan', 'Mayank',                  'Shubham', 'Aakash'],                  'Location': ['Saharanpur', 'Meerut', 'Agra',                     'Saharanpur', 'Meerut'],                  'Pay': [25000, 30000, 35000, 40000, 45000]}  df = pd.DataFrame(Data)  # print original data frameprint(df)  # remove special characterdf.columns = df.columns.str.replace('[#,@,&]', '')  # print file after removing special characterprint("\n\n", df)
Output:
Here, we have successfully remove a special character from the column names. Now we will use a list with replace function for removing multiple special characters from our column names.
Example 2: remove multiple special characters from the pandas data frame
Python
# import pandasimport pandas as pd  # create data frameData = {'Name#': ['Mukul', 'Rohan', 'Mayank',                   'Shubham', 'Aakash'],                    'Location@' : ['Saharanpur', 'Meerut', 'Agra',                        'Saharanpur', 'Meerut'],                  'Pay&' : [25000,30000,35000,40000,45000]}    df=pd.DataFrame(Data)  # print original data frameprint(df)  # remove special characterdf.columns=df.columns.str.replace('[#,@,&]','')  # print file after removing special characterprint("\n\n" , df)
Output:
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
String concatenation in Scala

02 Jul, 2021
A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. when a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two strings. we can also use ‘+’ operator to concatenate two strings. Syntax:  
str1.concat(str2);

Or

"str1" + "str2";
Below is the example of concatenating two strings.Using concat() method: This method appends argument to the string.Example #1:  
Scala
// Scala program to illustrate how to // concatenate stringsobject GFG{           // str1 and str2 are two strings    var str1 = "Welcome! GeeksforGeeks "    var str2 = " to Portal"           // Main function    def main(args: Array[String])    {                   // concatenate str1 and str2 strings        // using concat() function        var Newstr = str1.concat(str2);                   // Display strings         println("String 1:" +str1);        println("String 2:" +str2);        println("New String :" +Newstr);                   // Concatenate strings using '+' operator        println("This is the tutorial" +                     " of Scala language" +                     " on GFG portal");    }}
Output:  
String 1:Welcome! GeeksforGeeks 
String 2: to Portal
New String :Welcome! GeeksforGeeks  to Portal
This is the tutorial of Scala language on GFG portal
In above example, we are joining the second string to the end of the first string by using concat() function. string 1 is Welcome! GeeksforGeeks string 2 is to Portal. After concatenating two string we get new string Welcome! GeeksforGeeks to Portal.  Using + operator : we can add two string by using + operator.Example #2:  
Scala
// Scala program to illustrate how to// concatenate strings // Creating objectobject GFG{    // Main method   def main(args: Array[String])   {        var str1 = "Welcome to ";        var str2 =  "GeeksforGeeks";               // Concatenating two string        println("After concatenate two string: " + str1 + str2);   }}
Output:  
After concatenate two string: Welcome toGeeksforGeeks
In above example, string 1 is Welcome to string 2 is GeeksforGeeks. By using + operator concatenating two string we get output After concatenate two string: Welcome toGeeksforGeeks. 
surindertarika1234
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Seaborn | Regression Plots

09 Dec, 2021
The regression plots in seaborn are primarily intended to add a visual guide that helps to emphasize patterns in a dataset during exploratory data analyses. Regression plots as the name suggests creates a regression line between 2 parameters and helps to visualize their linear relationships. This article deals with those kinds of plots in seaborn and shows the ways that can be adapted to change the size, aspect, ratio etc. of such plots.
Seaborn is not only a visualization library but also a provider of built-in datasets. Here, we will be working with one of such datasets in seaborn named ‘tips’. The tips dataset contains information about the people who probably had food at the restaurant and whether or not they left a tip. It also provides information about the gender of the people, whether they smoke, day, time and so on.
Let us have a look at the dataset first before we start with the regression plots.
Load the dataset
Python3
# import the libraryimport seaborn as sns  # load the datasetdataset = sns.load_dataset('tips')  # the first five entries of the datasetdataset.head()
Python3
sns.set_style('whitegrid')sns.lmplot(x ='total_bill', y ='tip', data = dataset)
Python3
sns.set_style('whitegrid')sns.lmplot(x ='total_bill', y ='tip', data = dataset,            hue ='sex', markers =['o', 'v'])
Python3
sns.set_style('whitegrid')sns.lmplot(x ='total_bill', y ='tip', data = dataset, hue ='sex',            markers =['o', 'v'], scatter_kws ={'s':100},            palette ='plasma')
Python3
sns.lmplot(x ='total_bill', y ='tip', data = dataset,            col ='sex', row ='time', hue ='smoker')
Python3
sns.lmplot(x ='total_bill', y ='tip', data = dataset, col ='sex',            row ='time', hue ='smoker', aspect = 0.6,            size = 4, palette ='coolwarm')
sagar0719kumar
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
map::empty() in C++ STL

17 Jan, 2018
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.
empty() function is used to check if the map container is empty or not.
Syntax :
mapname.empty()
Parameters :
No parameters are passed.
Returns :
True, if map is empty
False, Otherwise

Examples:
Input  : map 
         mymap['a']=10;
         mymap['b']=20;
         mymap.empty();
Output : False

Input  : map 
         mymap.empty();
Output : True

Errors and Exceptions
1. It has a no exception throw guarantee.2. Shows error when a parameter is passed.
// Non Empty map example// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <map>using namespace std;  int main(){    map<char, int> mymap;    mymap['a'] = 1;    mymap['b'] = 2;    if (mymap.empty()) {        cout << "True";    }    else {        cout << "False";    }    return 0;}
Output:
False
// Empty map example// CPP program to illustrate// Implementation of empty() function#include <iostream>#include <map>using namespace std;  int main(){    map<char, int> mymap;    if (mymap.empty()) {        cout << "True";    }    else {        cout << "False";    }    return 0;}
Output:
True
Time Complexity : O(1)
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
Priority Queue in C++ Standard Template Library (STL)
Sorting a vector in C++
Inheritance in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
Substring in C++
Object Oriented Programming in C++
2D Vector In C++ With User Defined Size
Vim - Plug-Ins

Using plug-ins, we can extends the functionality of Vim. Vim supports many plug-ins and most of them are available freely. This chapter is about Vim plug-ins and we will discuss following items −
Plug-in management
Some useful plug-ins
This section discusses plug-in management. Vim provides various plug-ins managers but we won’t be using any plug-in manager, instead we’ll be doing all these steps manually for better understanding. Once you understand these steps, you can go with plug-in manager.
To install any plug-in perform following steps −
Create .vim/bundle directory in user’s home directory
Copy plug-in inside this directory
Set runtimepath in vim
Let us install badwolf plug-in in Vim. It is a color scheme for vim.
$ mkdir -p ~/.vim/bundle 
$ cd ~/.vim/bundle/ 
$ git clone https://github.com/sjl/badwolf.git 
$ echo "set runtimepath^ = ~/.vim/bundle/badwolf" > ~/.vimrc

Now plug-in is installed, so we can use badwold color scheme as follows −
:colorscheme badwolf

If we observe carefully, plug-in is a just collection of files and if we want to update that plug-in then just update appropriate plug-in directory from ~/.vim/bundle.
Removing plug-in in Vim is really simple. To remove plug-in perform following steps −
Remove plug-in directory from ~/.vim/bundle
Modify runtimepath appropriately
Below is list of some useful Vim plug-ins
Disassemble C/C++ code
Indenting for AWK script
Vim package manager
Automatically save and load vim session based on switching of git branch
Provide liniting for python files

    46 Lectures 
     5.5 hours 

 Jason Cannon
 Print
 Add Notes
 Bookmark this page
ASP.NET - Debugging

Debugging allows the developers to see how the code works in a step-by-step manner, how the values of the variables change, how the objects are created and destroyed, etc.
When the site is executed for the first time, Visual Studio displays a prompt asking whether it should be enabled for debugging:
When debugging is enabled, the following lines of codes are shown in the web.config:
<system.web>
   <compilation debug="true">
      <assemblies>
      ..............
      </assemblies>
   </compilation>	
</system.web>
The Debug toolbar provides all the tools available for debugging:
Breakpoints specifies the runtime to run a specific line of code and then stop execution so that the code could be examined and perform various debugging jobs such as, changing the value of the variables, step through the codes, moving in and out of functions and methods etc.
To set a breakpoint, right click on the code and choose insert break point. A red dot appears on the left margin and the line of code is highlighted as shown:
Next when you execute the code, you can observe its behavior.
At this stage, you can step through the code, observe the execution flow and examine the value of the variables, properties, objects, etc.
You can modify the properties of the breakpoint from the Properties menu obtained by right clicking the breakpoint glyph:
The location dialog box shows the location of the file, line number and the character number of the selected code. The condition menu item allows you to enter a valid expression, which is evaluated when the program execution reaches the breakpoint:
The Hit Count menu item displays a dialog box that shows the number of times the break point has been executed.
Clicking on any option presented by the drop down list opens an edit field where a target hit count is entered. This is particularly helpful in analyzing loop constructs in code.
The Filter menu item allows setting a filter for specifying machines, processes, or threads or any combination, for which the breakpoint will be effective.
The When Hit menu item allows you to specify what to do when the break point is hit.
Visual Studio provides the following debug windows, each of which shows some program information. The following table lists the windows:

    51 Lectures 
     5.5 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    42 Lectures 
     18 hours 

 SHIVPRASAD KOIRALA

    57 Lectures 
     3.5 hours 

 University Code

    40 Lectures 
     2.5 hours 

 University Code

    138 Lectures 
     9 hours 

 Bhrugen Patel
 Print
 Add Notes
 Bookmark this page
Can MySQL automatically store timestamp in a row?

Yes, you can achieve this in the following two ways.
First Approach At the time of creation of a table.
First Approach At the time of creation of a table.
Second Approach At the time of writing query.
Second Approach At the time of writing query.
The syntax is as follows.
CREATE TABLE yourTableName
(
yourDateTimeColumnName datetime default current_timestamp
);
You can use alter command.
The syntax is as follows.
ALTER TABLE yourTableName ADD yourColumnName datetime DEFAULT CURRENT_TIMESTAMP;
Implement both the syntaxes now.
The first approach is as follows.
mysql> create table CurrentTimeStampDemo
-> (
-> CreationDate datetime default current_timestamp
-> );
Query OK, 0 rows affected (0.61 sec)
If you do not pass any parameter for the column ‘CreationDate’, MySQL by default stores the current timestamp.
Insert record in the table using insert command. The query is as follows.
mysql> insert into CurrentTimeStampDemo values();
Query OK, 1 row affected (0.12 sec)
Let us now display all records from the table
using select command. The query is as follows.
mysql> select *from CurrentTimeStampDemo;
The following is the output.
+---------------------+
| CreationDate        |
+---------------------+
| 2019-01-02 15:53:03 |
+---------------------+
1 row in set (0.00 sec)
This is using ALTER command. The query to create a table is as follows.
mysql> create table Current_TimestampDemo
-> (
-> Id int
-> );
Query OK, 0 rows affected (0.43 sec)
Here is the query to automatically store creation time. The query is as follows.
mysql> ALTER TABLE Current_TimestampDemo
-> ADD CreationDate datetime DEFAULT CURRENT_TIMESTAMP;
Query OK, 0 rows affected (0.53 sec)
Records: 0 Duplicates: 0 Warnings: 0
If you do not pass the value for column ‘CreationDate’. MySQL stores the current datetime value for this column. The query is as follows.
mysql> insert into Current_TimestampDemo(Id) values(1);
Query OK, 1 row affected (0.19 sec)
Display records of the table using select statement. The query is as follows.
mysql> select CreationDate from Current_TimestampDemo;
The following is the output.
+---------------------+
| CreationDate        |
+---------------------+
| 2019-01-02 16:25:12 |
+---------------------+
1 row in set (0.00 sec)
Dining Philosophers Problem (DPP)

The dining philosophers problem states that there are 5 philosophers sharing a circular table and they eat and think alternatively. There is a bowl of rice for each of the philosophers and 5 chopsticks. A philosopher needs both their right and left chopstick to eat. A hungry philosopher may only eat if there are both chopsticks available.Otherwise a philosopher puts down their chopstick and begin thinking again.
The dining philosopher is a classic synchronization problem as it demonstrates a large class of concurrency control problems.
A solution of the Dining Philosophers Problem is to use a semaphore to represent a chopstick. A chopstick can be picked up by executing a wait operation on the semaphore and released by executing a signal semaphore.
The structure of the chopstick is shown below −
semaphore chopstick [5];
Initially the elements of the chopstick are initialized to 1 as the chopsticks are on the table and not picked up by a philosopher.
The structure of a random philosopher i is given as follows −
do {
   wait( chopstick[i] );
   wait( chopstick[ (i+1) % 5] );
   . .
   . EATING THE RICE
   .
   signal( chopstick[i] );
   signal( chopstick[ (i+1) % 5] );
   .
   . THINKING
   .
} while(1);
In the above structure, first wait operation is performed on chopstick[i] and chopstick[ (i+1) % 5]. This means that the philosopher i has picked up the chopsticks on his sides. Then the eating function is performed.
After that, signal operation is performed on chopstick[i] and chopstick[ (i+1) % 5]. This means that the philosopher i has eaten and put down the chopsticks on his sides. Then the philosopher goes back to thinking.
The above solution makes sure that no two neighboring philosophers can eat at the same time. But this solution can lead to a deadlock. This may happen if all the philosophers pick their left chopstick simultaneously. Then none of them can eat and deadlock occurs.
Some of the ways to avoid deadlock are as follows −
There should be at most four philosophers on the table.
An even philosopher should pick the right chopstick and then the left chopstick while an odd philosopher should pick the left chopstick and then the right chopstick.
A philosopher should only be allowed to pick their chopstick if both are available at the same time.
Decimal constants in C#

Decimal type has constants to get the minimum and maximum values.
Set a decimal value −
decimal d = 5.8M;
To get the minimum and maximum values of the decimal type, use the following properties −
decimal.MaxValue
decimal.MinValue
Here is the complete code −
 Live Demo
using System;
using System.Linq;
class Demo {
   static void Main() {
      decimal d = 5.8M;
      Console.WriteLine(d);
      Console.WriteLine("Maximum Value: "+decimal.MaxValue);
      Console.WriteLine("Maximum Value: "+decimal.MinValue);
   }
}
5.8
Maximum Value: 79228162514264337593543950335
Maximum Value: -79228162514264337593543950335
Number of Dice Rolls With Target Sum in Python

Suppose we have d dice, and each die has f number of faces numbered 1, 2, ..., f. We have to find the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equal to the target. So if the input is like d = 2, f = 6, target = 7, then the output will be 6. So if we throw each dice with 6 faces, then there are 6 ways to get sum 6, as 1 + 6, 2 + 5, 3 + 3, 4 + 3, 5 + 2, 6 + 1.
To solve this, we will follow these steps −
m := 1e9 + 7
make a table dp of order d x (t + 1), and fill this with 0
for i in range 0 to d – 1for j in range 0 to tif i = 0, then dp[i, j] := 1 when j in range 1 to f, otherwise 0otherwisefor l in range 1 to fif j – l > 0, then dp[i, j] := dp[i, j] + dp[i – 1, j - l], and dp[i,j] := dp[i, j] mod m
for j in range 0 to tif i = 0, then dp[i, j] := 1 when j in range 1 to f, otherwise 0otherwisefor l in range 1 to fif j – l > 0, then dp[i, j] := dp[i, j] + dp[i – 1, j - l], and dp[i,j] := dp[i, j] mod m
if i = 0, then dp[i, j] := 1 when j in range 1 to f, otherwise 0
otherwisefor l in range 1 to fif j – l > 0, then dp[i, j] := dp[i, j] + dp[i – 1, j - l], and dp[i,j] := dp[i, j] mod m
for l in range 1 to fif j – l > 0, then dp[i, j] := dp[i, j] + dp[i – 1, j - l], and dp[i,j] := dp[i, j] mod m
if j – l > 0, then dp[i, j] := dp[i, j] + dp[i – 1, j - l], and dp[i,j] := dp[i, j] mod m
return dp[d – 1, t] mod m
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def numRollsToTarget(self, d, f, t):
      mod = 1000000000+7
      dp =[[0 for i in range(t+1)] for j in range(d)]
      for i in range(d):
         for j in range(t+1):
            if i == 0:
               dp[i][j] = 1 if j>=1 and j<=f else 0
            else:
               for l in range(1,f+1):
                  if j-l>0:
                     dp[i][j]+=dp[i-1][j-l]
                     dp[i][j]%=mod
      return dp [d-1][t] % mod
ob = Solution()
print(ob.numRollsToTarget(2,6,7))
2
6
7
6
Tryit Editor v3.7

Tryit: HTML table - width: 100%
Why we use lambda expressions in Java?

A lambda expression can implement a functional interface by defining an anonymous function that can be passed as an argument to some method.
Enables functional programming: All new JVM based languages take advantage of the functional paradigm in their applications, but programmers forced to work with Object-Oriented Programming (OOPS) till lambda expressions came. Hence lambda expressions enable us to write functional code.
Readable and concise code: People have started using lambda expressions and reported that it can help to remove a huge number of lines from their code.
Easy-to-Use APIs and Libraries: An API designed using lambda expressions can be easier to use and support other API.
Enables support for parallel processing: A lambda expression can also enable us to write parallel processing because every processor is a multi-core processor nowadays.
(arg1, arg2...) -> { body }
 or
(type1 arg1, type2 arg2...) -> { body }
import javax.swing.*;

@FunctionalInterface
interface Action {
   void run(String s);
}
public class LambdaExpressionTest {
   public void action(Action action) {
      action.run("Welcome to TutorialsPoint");
   }
   public static void main(String[] args) {
      new LambdaExpressionTest().action((String s) -> System.out.print("*" + s + "*")); // lambda expression
   }
}
*Welcome to TutorialsPoint*
CSS 3D Transforms

CSS also supports 3D transformations.
Mouse over the elements below to see the difference between a 2D 
and a 3D transformation:
In this chapter you will learn about the following CSS property:
transform
The numbers in the table specify the first browser version that fully supports the property.
With the CSS transform property you can use 
the following 3D transformation methods:
rotateX()
rotateY()
rotateZ()
The rotateX() method rotates an element around its X-axis at a given degree:
The rotateY() method rotates an element around its Y-axis at a given degree:
The rotateZ() method rotates an element around its Z-axis at a given degree:
With the transform property, rotate the <div> element 150deg around its X-axis..
<style>
div {
  width: 100px;
  height: 100px;
  background-color: lightblue;
  border: 1px solid black;
  : ;
}
</style>

<body>
  <div>This is a div</div>
</body>

Start the Exercise
The following table lists all the 3D transform properties:
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Why isn't sizeof for a struct equal to the sum of sizeof of each member in C/C++?

The size of a struct type element taken by sizeof() is not always equal to the size of each individual member. Sometimes the compilers add some padding to avoid alignment issues. So the size may change. The padding is added when a structure member is followed by a member with a larger size or at the end of the structure. Different compiler has different types of alignment constraints. In C standard, the total alignment structure depends on the implementation.
In this case the double z is 8-byte long, which is larger than x (4-byte). So another 4-byte padding is added. Also short type data y has 2-byte space in memory so extra 6-bytes are added as padding.
#include <stdio.h>
struct myStruct {
   int x; //Integer takes 4 bytes, and padding 4 bytes
   double z; //Size of double is 8-byte, no padding
   short int y; //Size of short is 2-byte, padding 6-bytes
};
main() {
   printf("Size of struct: %d", sizeof(struct myStruct));
}
Size of struct: 24
In this case the double is inserted at first, and it takes 8-bytes of space. Now the integer x (4-byte) is added. So there is another 4-byte space. When the short y is added, it can be placed into that extra 4-byte space and occupies total 16-bytes of space.
#include <stdio.h>
struct myStruct {
   double z; //Size of double is 8-byte, no padding
   int x; //Integer takes 4 bytes, and padding 4 bytes
   short int y; //Size of short is 2-byte, padding 6-bytes
};
main() {
   printf("Size of struct: %d", sizeof(struct myStruct));
}
Size of struct: 16
In the third case it also takes 16-byte of memory space, but the arrangements are different. As the first member is double then it is placed at first, then the short type data is added. Now when the integer is trying to insert, it can be placed into the remaining 6-byte area. So one padding is present after short but no padding is required after the integer data.
#include <stdio.h>
struct myStruct {
   double z; //Size of double is 8-byte, no padding
   short int y; //Size of short is 2-byte, padding 6-bytes
   int x; //Integer takes 4 bytes, and padding 4 bytes
};
main() {
   printf("Size of struct: %d", sizeof(struct myStruct));
}
Size of struct: 16
How to format string using PowerShell?

To format a string in a PowerShell we can use various methods. First using the simple expanding string method.
PS C:\> $str = 'PowerShell'
PS C:\> Write-Output "Hello $str !!!!"
Hello PowerShell !!!!
Second, using the format method. In this method, we will use the Format function of the String .NET class.
PS C:\> $str = "PowerShell"
PS C:\> [String]::Format("Hello $str...!!!")
Hello PowerShell...!!!
The third method using the Format operator. We can use the number format here as shown below.
PS C:\> $str = 'PowerShell'
PS C:\> "Hello {0}" -f $str
Hello PowerShell
If we have multiple variables then we need to increase the numbers inside the curly brackets. For example,
PS C:\> $str = "PowerShell"
PS C:\> $str1 = "Azure"
PS C:\> "Hello {0} and {1}" -f $str,$str1
Hello PowerShell and Azure
You can also use the same format operator inside the format method.
PS C:\> [String]::Format("Hello {0} and {1}", $str,$str1)
Hello PowerShell and Azure
React Sass Styling

Sass is a CSS pre-processor.
Sass files are executed on the server and sends CSS to the 
browser.
You can learn more about Sass in our
Sass Tutorial.
If you use the create-react-app in your project, you can easily 
install and use Sass in your React projects.
Install Sass by running this command in your terminal:
Now you are ready to include Sass files in your project!
Create a Sass file the same way as you create CSS files, but Sass files have the 
file extension .scss
In Sass files you can use variables and other Sass functions:
Create a variable to define the color of the text:
$myColor: red;

h1 {
  color: $myColor;
}
Import the Sass file the same way as you imported a CSS file:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './my-sass.scss';

const Header = () => {
  return (
    <>
      <h1>Hello Style!</h1>
      <p>Add a little style!.</p>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);
 


Run 
Example »

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to plot a dashed line on a Seaborn lineplot in Matplotlib?

To plot a dashed line on a Seaborn lineplot, we can use linestyle="dashed" in the argument of lineplot().
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.
Use lineplot() method with x and y data points in the argument and linestyle="dashed".
Use lineplot() method with x and y data points in the argument and linestyle="dashed".
To display the figure, use show() method.
To display the figure, use show() method.
import seaborn as sns
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.random.rand(10)
y = np.random.rand(10)
ax = sns.lineplot(x=x, y=y, linestyle="dashed")
plt.show()
Binary Tree ADT in Data Structure

A binary tree is defined as a tree in which no node can have more than two children. The highest degree of any node is two. This indicates that the degree of a binary tree is either zero or one or two.
In the above fig., the binary tree consists of a root and two sub trees TreeLeft & TreeRight. All nodes to the left of the binary tree are denoted as left subtrees and all nodes to the right of a binary tree are referred to as right subtrees.
A binary tree has maximum two children; we can assign direct pointers to them. The declaration of tree nodes is same as in structure to that for doubly linked lists, in that a node is a structure including the key information plus two pointers (left and right) to other nodes.
typedef struct tree_node *tree_ptr;
struct tree_node
{
   element_type element1;
   tree_ptr left1; tree_ptr right1;
};
typedef tree_ptr TREE;
Strictly binary tree
Strictly binary tree is defined as a binary tree where all the nodes will have either zero or two children. It does not include one child in any node.
Skew tree
A skew tree is defined as a binary tree in which every node except the leaf has only one child node. There are two types of skew tree, i.e. left skewed binary tree and right skewed binary tree.
Left skewed binary tree
A left skew tree has node associated with only the left child. It is a binary tree contains only left subtrees.
Right skewed binary tree
A right skew tree has node associated with only the right child. It is a binary tree contains only right subtrees.
Full binary tree or proper binary tree
A binary tree is defined as a full binary tree if all leaves are at the same level and every non leaf node has exactly two children and it should consist of highest possible number of nodes in all levels. A full binary tree of height h has maximum 2h+1 – 1 nodes.
 Complete binary tree
Every non leaf node has exactly two children but all leaves are not necessary to belong at the same level. A complete binary tree is defined as one where all levels have the highest number of nodes except the last level. The last level elements should be filled from left to right direction.
 Almost complete binary tree
An almost complete binary tree is defined as a tree in which each node that has a right child also has a left child. Having a left child does not need a node to have a right child
Differences between General Tree and Binary Tree
General tree has no limit of number of children.
Evaluating any expression is hard in general trees.
Binary Tree
A binary tree has maximum two children
Evaluation of expression is simple in binary tree.
Application of trees
Manipulation of arithmetic expression
Construction of symbol table
Analysis of Syntax
Writing Grammar
Creation of Expression Tree
Convert Object to String in Python - GeeksforGeeks

28 Jul, 2020
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting an object to a string.
Everything is an object in Python. So all the built-in objects can be converted to strings using the str() and repr() methods.
Example 1: Using str() method
Python3
# object of intInt = 6  # object of floatFloat = 6.0  # Converting to strings1 = str(Int)print(s1)print(type(s1))  s2= str(Float)print(s2)print(type(s2))
Output:
6
<class 'str'>
6.0
<class 'str'>
Example 2: Use repr() to convert an object to a string
Python3
print(repr({"a": 1, "b": 2}))print(repr([1, 2, 3]))  # Custom classclass C():    def __repr__(self):        return "This is class C"  # Converting custom object to # stringprint(repr(C()))
Output:
{'a': 1, 'b': 2}
[1, 2, 3]
This is class C
Note: To know more about str() and repr() and the difference between to refer, str() vs repr() in Python
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Time Complexity of Loop with Powers - GeeksforGeeks

30 Dec, 2021
What is the time complexity of the below function?
C++
C
Java
Python3
C#
Javascript
void fun(int n, int k){    for (int i = 1; i <= n; i++)    {        int p = pow(i, k);        for (int j = 1; j <= p; j++)        {            // Some O(1) work        }    }} // This code is contributed by Shubham Singh
void fun(int n, int k){    for (int i = 1; i <= n; i++)    {        int p = pow(i, k);        for (int j = 1; j <= p; j++)        {            // Some O(1) work        }    }}
static void fun(int n, int k){    for (int i = 1; i <= n; i++)    {        int p = Math.pow(i, k);        for (int j = 1; j <= p; j++)        {            // Some O(1) work        }    }} // This code is contributed by umadevi9616
def fun(n, k):         for i in range(1, n + 1):        p = pow(i, k)        for j in range(1, p + 1):            # Some O(1) work          # This code is contributed by Shubham Singh
static void fun(int n, int k){    for (int i = 1; i <= n; i++)    {        int p = Math.Pow(i, k);        for (int j = 1; j <= p; j++)        {            // Some O(1) work        }    }} // This code is contributed by umadevi9616
<script> // JavaScript program for the above approachfunction fun(n, k){    for(let i = 1; i <= n; i++)    {        int p = Math.pow(i, k);        for (let j = 1; j <= p; j++)        {            // Some O(1) work        }    }} // This code is contributed by Shubham Singh </script>
Time complexity of above function can be written as 1k + 2k + 3k + ... n1k.
Let us try few examples: 
k=1
Sum = 1 + 2 + 3 ... n 
    = n(n+1)/2 
    = n2/2 + n/2

k=2
Sum = 12 + 22 + 32 + ... n12.
    = n(n+1)(2n+1)/6
    = n3/3 + n2/2 + n/6

k=3
Sum = 13 + 23 + 33 + ... n13.
    = n2(n+1)2/4
    = n4/4 + n3/2 + n2/4     
In general, asymptotic value can be written as (nk+1)/(k+1) + Θ(nk)If  n>=k then the time complexity will be considered in O((nk+1)/(k+1)) and if n<k, then the time complexity will be considered as  in the O(nk)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
biplab_prasad
rohitnandi01234
umadevi9616
SHUBHAMSINGH10
time complexity
Analysis
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Analysis of Algorithms | Big-O analysis
Analysis of different sorting techniques
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
SQL Interview Questions
How to write a Pseudo Code?
Matplotlib.pyplot.thetagrids() in Python - GeeksforGeeks

29 Jul, 2021
Matplotlib is a plotting library of Python programming language and its numerical mathematics module is NumPy. matplotlib.pyplot is a collection of command style functions that make matplotlib work like the MATLAB Tool. Each of the pyplot functions makes certain changes to a figure: e.g., creating a figure, creating a plot area in a figure, plots some lines in a plotting area or decorate the plot with labels, etc.Note: For more information, refer to Pyplot in Matplotlib 
 
Set the theta locations of the gridlines in the polar plot. If no arguments are passed, it returns a tuple (lines, labels) where lines are an array of radial gridlines (Line2D instances) and labels is an array of tick labels (Text instances):
 
Syntax: lines, labels = thetagrids(angles, labels=None, fmt=’%d’, frac = 1.5)Parameters:
Angles:
set the angles to the place of theta grids (these gridlines are equal along the theta dimension)
labels:
if not None, then it is len(angles) or list of strings of the labels to use at each angle. If labels are None, the labels will be fmt%angle. 
frac: It is the fraction of the polar axes radius at the place of label (1 is the edge). e.g., 1.25 is outside the axes and 0.75 is inside the axes.  Return Type: Return value is a list of tuples (lines, labels)Note: lines are Line2D instances, labels are Text instances.
Return Type: Return value is a list of tuples (lines, labels)Note: lines are Line2D instances, labels are Text instances.
Example: 
Python3
import matplotlib.pyplot as pltimport numpy as np    employee = ["Rahul", "Joy", "Abhishek",            "Tina", "Sneha"]  actual = [41, 57, 59, 63, 52, 41]expected = [40, 59, 58, 64, 55, 40]    # Initialing the spiderplot by # setting figure size and polar# projectionplt.figure(figsize =(10, 6))plt.subplot(polar = True)    theta = np.linspace(0, 2 * np.pi, len(actual))    # Arranging the grid into number # of sales into equal parts in# degreeslines, labels = plt.thetagrids(range(0, 360, int(360/len(employee))),                                                         (employee))    # Plot actual sales graphplt.plot(theta, actual)plt.fill(theta, actual, 'b', alpha = 0.1)    # Plot expected sales graphplt.plot(theta, expected)    # Add legend and title for the plotplt.legend(labels =('Actual', 'Expected'),           loc = 1)plt.title("Actual vs Expected sales by Employee")    # Display the plot on the screenplt.show()
Output: 
 
singghakshay
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
AngularJS | number Filter - GeeksforGeeks

07 May, 2019
AngularJS number filter is used to convert a number into string or text. We can also define a limit to display a number of decimal digits. Number filter rounds off the number to specified decimal digits.
Syntax:
{{ string| number : fractionSize}}

Parameter Values: It contains single parameter value fractionsize which is of type number and used to specify the number of decimals.
Example 1: This example format the number and set it into the fraction with two decimal place.
<!DOCTYPE html><html>    <head>        <title>Number Filter</title>                  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">        </script>    </head>          <body>           <div ng-app="gfgApp" ng-controller="numberCntrl">            <h3>Number filter with fraction size.</h3>            <p>Number : {{ value| number  : 2}}</p>        </div>           <script>            var app = angular.module('gfgApp', []);            app.controller('numberCntrl', function($scope) {                $scope.value = 75598.548;            });        </script>       </body></html>
Output:
Example 2: This example format the number and set it into the fraction with three decimal place.
<!DOCTYPE html><html>    <head>        <title>Number Filter</title>                  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">        </script>    </head>          <body>           <div ng-app="gfgApp" ng-controller="numberCntrl">            <h3>Number filter without fraction size.</h3>            <p>Number : {{ value| number}}</p>        </div>           <script>            var app = angular.module('gfgApp', []);            app.controller('numberCntrl', function($scope) {                $scope.value = 524598.54812;            });        </script>       </body></html>
Output:
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular PrimeNG Dropdown Component
Angular | keyup event
Auth Guards in Angular 9/10/11
How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference Between ArrayList and Vector in Java

In this post, we will understand the difference between ArrayList and Vector in Java.
It is not synchronized.
It is not synchronized.
If the number of elements exceeds the capacity of the ArrayList, it increments the current array size by 50 percent.
If the number of elements exceeds the capacity of the ArrayList, it increments the current array size by 50 percent.
It is not thread-safe.
It is not thread-safe.
It was introduced in JDK 1.2.
It was introduced in JDK 1.2.
it can only use iterator to traverse.
it can only use iterator to traverse.
Since it is non-synchronized, it is quick.
Since it is non-synchronized, it is quick.
It uses the Iterator interface to traverse through the elements.
It uses the Iterator interface to traverse through the elements.
ArrayList<T> al = new ArrayList<T>();
It is synchronized.
It is synchronized.
It is thread safe.
It is thread safe.
It is a legacy class.
It is a legacy class.
It is slow, since it is synchronized.
It is slow, since it is synchronized.
If the number of elements exceeds the capacity of the Vector, it increments the current array size by 100 percent.
If the number of elements exceeds the capacity of the Vector, it increments the current array size by 100 percent.
It can use enumerator and iterator to traverse.
It can use enumerator and iterator to traverse.
It is preferred over ArrayList.
It is preferred over ArrayList.
It provides a multi-threading environment.
It provides a multi-threading environment.
It holds other threads in the runnable or non-runnable state, until the current thread releases the lock on the specific object.
It holds other threads in the runnable or non-runnable state, until the current thread releases the lock on the specific object.
It can use either the ‘Iterator’ interface or the Enumeration interface to traverse through the elements.
It can use either the ‘Iterator’ interface or the Enumeration interface to traverse through the elements.
Vector<T> v = new Vector<T>();