code-rag-bench/online-tutorials huggingface dataset:
How to perform Case Insensitive matching with JavaScript RegExp?

To perform case-insensitive matching, use the I modifier available in JavaScript Regular Expression.
You can try to run the following code for case-insensitive matching −
<html>
   <head>
      <title>JavaScript Regular Expression</title>
   </head>
   <body>
      <script>
         var myStr = "Welcome to the website!";
         var reg = /welcome/i;
         var match = myStr.match(reg);
         
         document.write(match);
      </script>
   </body>
</html>
Tryit Editor v3.7 - Show Java

static void Main(string[] args)
    {
      string firstName = "John";
      string lastName = "Doe";
      string name = $"My full name is: {firstName} {lastName}";
Python | Print an Inverted Star Pattern - GeeksforGeeks

31 Dec, 2020
Here we are going to print inverted star pattern of desired sizes.Examples:
1) Below is the inverted star pattern of size n=5 
  (Because there are 5 horizontal lines
   or rows consist of stars). 

   *****
    ****
     ***
      **
       *

2) Below is the inverted star pattern of size n=10 
  (Because there are 5 horizontal lines
   or rows consist of stars).

   **********
    *********
     ********
      *******
       ******
        *****
         ****
          ***
           **
            *

Let’s see Python program to print inverted star pattern:
# python 3 code to print inverted star# pattern   # n is the number of rows in which# star is going to be printed.n=11  # i is going to be enabled to# range between n-i t 0 with a# decrement of 1 with each iteration.# and in print function, for each iteration,# ” ” is multiplied with n-i and ‘*’ is# multiplied with i to create correct# space before of the stars.for i in range (n, 0, -1):    print((n-i) * ' ' + i * '*')
Explanation:
The first number of rows is stored in variable n.
Then the for loop enables i to range between n-i to 0 with a decrement of 1 with each iteration.
After that, for each iteration, ” ” is multiplied with n-i and ‘*’ is multiplied with i to create correct space before of the stars.
And finally desired pattern will be printed.
Output:
***********
 **********
  *********
   ********
    *******
     ******
      *****
       ****
        ***
         **
          *

pattern-printing
Python Pattern-printing
Python Programs
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Binary Search (Recursive and Iterative)
Iterate over characters of a string in Python
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java
Python | Check if substring is part of List of Strings - GeeksforGeeks

30 Jun, 2019
Many problems of substrings have been dealt with many times. There can also be such problem in which we require to check if argument string is a part of any of the strings coming in the input list of strings. Let’s discuss various ways in which this can be performed.
Method #1 : Using join()The basic approach that can be employed to perform this particular task is computing the join of all the list strings and then searching the string in the joined string.
# Python3 code to demonstrate working of# Check if substring is part of List of Strings# Using join()  # initializing list  test_list = ['GeeksforGeeks', 'is', 'Best']  # test string check_str = "for"  # printing original string print("The original string is : " + str(test_list))  # Using join()# Check if substring is part of List of Stringstemp = '\t'.join(test_list)res = check_str in temp  # printing result print("Is check string part of any input list string : " + str(res))
The original string is : ['GeeksforGeeks', 'is', 'Best']
Is check string part of any input list string : True

 
Method #2 : Using any()The any function can be used to compute the presence of the test substring in all the strings of the list and return True if it’s found in any. This is better than above function as it doesn’t explicitly take space to create new concatenated string.
# Python3 code to demonstrate working of# Check if substring is part of List of Strings# Using any()  # initializing list  test_list = ['GeeksforGeeks', 'is', 'Best']  # test string check_str = "for"  # printing original string print("The original string is : " + str(test_list))  # Using any()# Check if substring is part of List of Stringsres = any(check_str in sub for sub in test_list)  # printing result print("Is check string part of any input list string : " + str(res))
The original string is : ['GeeksforGeeks', 'is', 'Best']
Is check string part of any input list string : True

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Python Generate successive element difference list

In this as its elements article we will see how to find the difference between the two successive elements for each pair of elements in a given list. The list has only numbers as its elements.
Using the index of the elements along with the for loop, we can find the difference between the successive pair of elements.
 Live Demo
listA = [12,14,78,24,24]
# Given list
print("Given list : \n",listA)
# Using Index positions
res = [listA[i + 1] - listA[i] for i in range(len(listA) - 1)]
# printing result
print ("List with successive difference in elements : \n" ,res)
Running the above code gives us the following result −
Given list :
[12, 14, 78, 24, 24]
List with successive difference in elements :
[2, 64, -54, 0]
Slicing is another technique where we slice the successive pairs from the list and then apply the zip function to get the result.
 Live Demo
listA = [12,14,78,24,24]
# Given list
print("Given list : \n",listA)
# Using list slicing
res = [x - y for y, x in zip(listA[: -1], listA[1 :])]
# printing result
print ("List with successive difference in elements : \n" ,res)
Running the above code gives us the following result −
Given list :
[12, 14, 78, 24, 24]
List with successive difference in elements :
[2, 64, -54, 0]
The sub method from operators module can also be used through a map function. Again we apply the slicing technique two successive pairs of elements.
 Live Demo
import operator
listA = [12,14,78,24,24]
# Given list
print("Given list : \n",listA)
# Using operator.sub
res = list(map(operator.sub, listA[1:], listA[:-1]))
# printing result
print ("List with successive difference in elements : \n" ,res)
Running the above code gives us the following result −
Given list :
[12, 14, 78, 24, 24]
List with successive difference in elements :
[2, 64, -54, 0]
Python | Update each element in tuple list - GeeksforGeeks

21 Nov, 2019
Sometimes, while working with data, we can have a problem in which we need to perform update operations on tuples. This can have applications across many domains such as web development. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehensionThis is shorthand to brute function that can be applied to perform this task. In this, we iterate for each element of each tuple to perform bulk update of data.
# Python3 code to demonstrate working of# Update each element in tuple list# Using list comprehension  # initialize listtest_list = [(1, 3, 4), (2, 4, 6), (3, 8, 1)]  # printing original list print("The original list : " + str(test_list))  # initialize add elementadd_ele = 4  # Update each element in tuple list# Using list comprehensionres = [tuple(j + add_ele for j in sub ) for sub in test_list]  # printing resultprint("List after bulk update : " + str(res))
The original list : [(1, 3, 4), (2, 4, 6), (3, 8, 1)]
List after bulk update : [(5, 7, 8), (6, 8, 10), (7, 12, 5)]

 
Method #2 : Using map() + lambda + list comprehensionThe combination of above functions can be used to perform this task. In this, we just iterate for all elements using map() and extend logic of update using lambda function.
# Python3 code to demonstrate working of# Update each element in tuple list# Using list comprehension + map() + lambda  # initialize listtest_list = [(1, 3, 4), (2, 4, 6), (3, 8, 1)]  # printing original list print("The original list : " + str(test_list))  # initialize add elementadd_ele = 4  # Update each element in tuple list# Using list comprehension + map() + lambdares = [tuple(map(lambda ele : ele + add_ele, sub)) for sub in test_list]  # printing resultprint("List after bulk update : " + str(res))
The original list : [(1, 3, 4), (2, 4, 6), (3, 8, 1)]
List after bulk update : [(5, 7, 8), (6, 8, 10), (7, 12, 5)]

Python tuple-programs
Python
Python Programs
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Angular CLI - ng update Command

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

ng update command updates the application and its dependencies. 
The argument for ng update command is as follows −
Options are optional parameters.
Default: false
Create source control commits for updates and migrations.
Default: false
Aliases: -C
If false, will error out if installed packages are incompatible with the update.
Default: false
Shows a help message for this command in the console.
Default: false
Use the largest version, including beta and RCs.
Default: false
Display additional details about internal operations during execution.
Default: false
First move to an angular project updated using ng build command.The chapter is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_build.htm.
Now run the update command. Now ng will update dependencies using npm.
An example for ng update command is given below −
\>Node\>TutorialsPoint> ng update
Using package manager: 'npm'
Collecting installed dependencies...
Found 31 dependencies.
   We analyzed your package.json and everything seems to be in order. Good work!


    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Python – API.search_users() in Tweepy

05 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The search_users() method of the API class in Tweepy module is used to run a search based on a query and get users matching that query, similar to the Find People button.
Syntax : API.search_users(q, count)
Parameters :q : the text to be searchedcount : specifies the number of users to retrieve, cannot be greater than 20, the default value is 20
Returns : a list of objects of the class User
Example 1 :By default search_users() retrieves 20 users.
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the query to be searchedq = "geeks"  # search the queryusers = api.search_users(q)  # print the users retrievedfor user in users:    print(user.screen_name)
Output :
GeeksOUT
GWOBorg
GeeksOfColor
geeksaresexy
WeatherGeeks
CoachingGeeks
DealsForGeeks
TwinCitiesGeeks
RetroGameGeeks
BuddhistGeeks
KevinGeeksOut
mcrgirlgeeks
AirplaneGeeks
AirlineGeeks
geeks_3d
GeeksGamersCom
javacodegeeks
wearemoviegeeks
The_GWW
GeeksRoom

Example 2: Using the count parameter to retrieve less than 20 users.
# the query to be searchedq = "geeksforgeeks"  # number of users to be retrievedcount = 3  # search the queryusers = api.search_users(q, count)  # print the users retrievedfor user in users:    print(user.screen_name)
Output :
geeksforgeeks
gfgvideos
gfg_reader

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Python | Pandas Index.copy()

12 Jan, 2022
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.copy() function make a copy of this object. The function also sets the name and dtype attribute of the new object as that of original object. If we wish to have a different datatype for the new object then we can do that by setting the dtype attribute of the function.
Syntax: Index.copy(name=None, deep=False, dtype=None, **kwargs)
Parameters :name : string, optionaldeep : boolean, default Falsedtype : numpy dtype or pandas type
Returns : copy : Index
Note : In most cases, there should be no functional difference from using deep, but if deep is passed it will attempt to deepcopy.
Example #1: Use Index.copy() function to copy the Index value to a new object and change the datatype of new object to ‘int64’
Python3
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index([17.3, 69.221, 33.1, 15.5, 19.3, 74.8, 10, 5.5])  # Print the Indexidx
Output :
Let’s create a copy of the object having ‘int64’ data type.
Python3
# Change the data type of newly # created object to 'int64'idx.copy(dtype ='int64')
Output :
As we can see in the output, the function has returned a copy of the original Index with ‘int64’ dtype. Example #2: Use Index.copy() function to make a copy of the original object. Also set the name attribute of the new object and convert the string dtype into ‘datetime’ type.
Python3
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index(['2015-10-31', '2015-12-02', '2016-01-03',                              '2016-02-08', '2017-05-05'])  # Print the Indexidx
Output :
Let’s make a copy of the original object.
Python3
# to make copy and set data type in the datetime format.idx_copy = idx.copy(dtype ='datetime64')  # Print the newly created objectidx_copy
Output :As we can see in the output, the new object has the data in datetime format and its name attribute has also been set.
surindertarika1234
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists
\implies - Tex Command

\implies - Used to draw implies symbol.
{ \implies }
\implies command draws implies symbol.

P\implies Q

P⟹Q



P\implies Q

P⟹Q


P\implies Q

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
HTML | <tr> align Attribute - GeeksforGeeks

22 Feb, 2022
The HTML <tr> align Attribute is used to set the horizontal alignment of text content inside the table row. It is not supported by HTML 5.
Syntax:
<tr align= "left | right | center | justify | char">
Attribute Values:
left: It sets the text left-align.
right: It sets the text right-align.
center: It sets the text center-align. It is a default value.
justify: It stretches the text of paragraph to set the width of all lines equal.
char: It sets the text-align to a specific character.
Example:
<!DOCTYPE html><html>  <head>    <title>HTML tr align Attribute</title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML tr align Attribute</h2>      <table width="500" border="1">        <tr align="right">            <th>Name</th>            <th>Expenses</th>        </tr>          <tr align="center">            <td>BITTU</td>            <td>2500.00</td>        </tr>          <tr align="left">            <td>RAKESH</td>            <td>1400.00</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <tr> align attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Form validation using HTML and JavaScript
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Difference between int (*p)[3] and int* p[3]? - GeeksforGeeks

24 Nov, 2020
Pointers store the address of variables or a memory location. Pointers are a symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Its general declaration in C/C++ has the format:
Syntax:
datatype *var_name; 
Example:
int *ptr;In this example “ptr” is a variable name of the pointer that holds address of an integer variable.
In this article, the focus is to differentiate between the two declarations of pointers i.e., int (*p)[3] and int *p[3].
For int (*p)[3]: Here “p” is the variable name of the pointer which can point to an array of three integers.
Below is an example to illustrate the use of int (*p)[3]:
C++
// C++ program to illustrate the use// of int (*p)[3]#include <iostream>using namespace std;  // Driver Codeint main(){    // Declaring a pointer to store address    // pointing to an array of size 3    int(*p)[3];      // Define an array of size 3    int a[3] = { 1, 2, 3 };      // Store the base address of the    // array in the pointer variable    p = &a;      // Print the results    for (int i = 0; i < 3; i++) {        cout << *(*(p) + i) << " ";    }      return 0;}
1 2 3

For int *p[3]: Here “p” is an array of the size 3 which can store integer pointers.
Below is an example to illustrate the use of int *p[3]:
C++
// C++ program to illustrate the use// of int*p[3]#include <bits/stdc++.h>using namespace std;  // Driver Codeint main(){    // Declare an array of size 3 which    // will store integer pointers    int* p[3];      // Integer variables    int a = 1, b = 2, c = 3;      // Store the address of integer    // variable at each index    p[0] = &a;    p[1] = &b;    p[2] = &c;      // Print the result    for (int i = 0; i < 3; i++) {        cout << *p[i] << " ";    }      return 0;}
1 2 3

C-Pointers
Pointers
C++
C++ Programs
Difference Between
Pointers
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Iterators in C++ STL
Sorting a vector in C++
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
CSV file management using C++
json.load() in Python - GeeksforGeeks

23 Mar, 2020
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python.
Note: For more information, refer to Working With JSON Data in Python
json.load() takes a file object and returns the json object. A JSON object contains data in the form of key/value pair. The keys are strings and the values are the JSON types. Keys and values are separated by a colon. Each entry (key/value pair) is separated by a comma.
Syntax :
json.load(file_object)
Argument : It takes file object as a parameter.
Return : It return json object.
Example: Let’s suppose the JSON looks like this.
We want to read the content of this file. Below is the implementation.
# Python program to read# json file      import json   # Opening JSON filef = open('data.json',)   # returns JSON object as # a dictionarydata = json.load(f)   # Iterating through the json# listfor i in data['emp_details']:    print(i)   # Closing filef.close()
Output:
Here, we have used the open() function to read the JSON file. Then, the file is parsed using json.load() method which gives us a dictionary named data.
Python-json
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
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
How to return only a single property “_id” in MongoDB?

Following is the syntax to return only a single property _id in MongoDB
db.yourCollectionName.find({}, {"_id": 1}).pretty();
Let us first create a collection with documents
> db.singlePropertyIdDemo.insertOne({"_id":101,"UserName":"Larry","UserAge":21});
{ "acknowledged" : true, "insertedId" : 101 }
> db.singlePropertyIdDemo.insertOne({"_id":102,"UserName":"Mike","UserAge":26});
{ "acknowledged" : true, "insertedId" : 102 }
> db.singlePropertyIdDemo.insertOne({"_id":103,"UserName":"Chris","UserAge":24});
{ "acknowledged" : true, "insertedId" : 103 }
> db.singlePropertyIdDemo.insertOne({"_id":104,"UserName":"Robert","UserAge":23});
{ "acknowledged" : true, "insertedId" : 104 }
> db.singlePropertyIdDemo.insertOne({"_id":105,"UserName":"John","UserAge":27});
{ "acknowledged" : true, "insertedId" : 105 }
Following is the query to display all documents from a collection with the help of find() method
> db.singlePropertyIdDemo.find().pretty();
This will produce the following output
{ "_id" : 101, "UserName" : "Larry", "UserAge" : 21 }
{ "_id" : 102, "UserName" : "Mike", "UserAge" : 26 }
{ "_id" : 103, "UserName" : "Chris", "UserAge" : 24 }
{ "_id" : 104, "UserName" : "Robert", "UserAge" : 23 }
{ "_id" : 105, "UserName" : "John", "UserAge" : 27 }
Following is the query to return only a single property _id
> db.singlePropertyIdDemo.find({}, {"_id": 1}).pretty();
This will produce the following output
{ "_id" : 101 }
{ "_id" : 102 }
{ "_id" : 103 }
{ "_id" : 104 }
{ "_id" : 105 }
What is the importance of _isEqual() method in JavaScript?

_isEqual() is from the underscore and lodash library of javascript. It is used to compare javascript objects. The importance of this method is that it doesn't care about the order of properties while comparing the objects. It only checks whether the properties in the two objects are equal or not. Whereas JSON.stringify(), which is used in comparing the objects, checks even the order of properties of the objects, making _isEqual() the better option. 
_.isEqual(object1, object2);
It accepts two objects as parameters and scrutinizes whether they are equal or not.
Live Demo
<html>
<head>
<script src =
   "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>
</head>
<body>
<script>
   var obj1 = {name: "Sikha", designation: "Content developer"};
   var obj2 = {name: "Sikha", designation: "Content developer"};
   document.write(_.isEqual(obj1, obj2));
</script>
</body>
</html>
true
In the following example, Both JSON.stringify() and _isEqual() methods are used. Since the order of properties is not a problem for the _isEqual() method it gives out true as output whereas JSON.stringify() gives out false as output.
Live Demo
<html>
<head>
<script src =
   "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</script>
</head>
<body>
<script>
   var obj1 = {name: "Sikha", designation: "Content developer"};
   var obj2 = {designation: "Content developer", name: "Sikha"};
   document.write(_.isEqual(obj1, obj2));
   document.write("</br>");
   document.write(JSON.stringify(obj1) === JSON.stringify(obj2));
</script>
</body>
</html>
true
false
Matplotlib legends in subplot

To add legends in a subplot, we can take the following Steps −
Using numpy, create points for x, y1, y2 and y3.
Using numpy, create points for x, y1, y2 and y3.
Create a figure and a set of subplots, using the subplots() method, considering 3 subplots.
Create a figure and a set of subplots, using the subplots() method, considering 3 subplots.
Plot the curve on all the subplots(3), with different labels, colors. To place the legend for each curve or subplot adding label.
Plot the curve on all the subplots(3), with different labels, colors. To place the legend for each curve or subplot adding label.
To activate label for each curve, use the legend() method.
To activate label for each curve, use the legend() method.
To display the figure, use the show() method.
To display the figure, use the 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
x = np.linspace(-2, 2, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
f, axes = plt.subplots(3)
axes[0].plot(x, y1, c='r', label="sine")
axes[0].legend(loc='upper left')
axes[1].plot(x, y2, c='g', label="cosine")
axes[1].legend(loc='upper left')
axes[2].plot(x, y3, c='b', label="tan")
axes[2].legend(loc='upper left')
plt.show()
EOF, getc() and feof() in C

EOF stands for End of File. The function getc() returns EOF, on success..
Here is an example of EOF in C language,
Let’s say we have “new.txt” file with the following content.
This is demo!
This is demo!
Now, let us see the example.
#include <stdio.h>
int main() {
   FILE *f = fopen("new.txt", "r");
   int c = getc(f);
   while (c != EOF) {
      putchar(c);
      c = getc(f);
   }
   fclose(f);
   getchar();
   return 0;
}
This is demo!
This is demo!
In the above program, file is opened by using fopen(). When integer variable c is not equal to EOF, it will read the file.
FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}
It reads a single character from the input and return an integer value. If it fails, it returns EOF.
Here is the syntax of getc() in C language,
int getc(FILE *stream);
Here is an example of getc() in C language,
Let’s say we have “new.txt” file with the following content −
This is demo!
This is demo!
Now, let us see the example.
#include <stdio.h>
int main() {
   FILE *f = fopen("new.txt", "r");
   int c = getc(f);
   while (c != EOF) {
      putchar(c);
      c = getc(f);
   }
   fclose(f);
   getchar();
   return 0;
}
This is demo!
This is demo!
In the above program, file is opened by using fopen(). When integer variable c is not equal to EOF, it will read the file. The function getc() is reading the characters from the file.
FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}
The function feof() is used to check the end of file after EOF. It tests the end of file indicator. It returns non-zero value if successful otherwise, zero.
Here is the syntax of feof() in C language,
int feof(FILE *stream)
Here is an example of feof() in C language,
Let’s say we have “new.txt” file with the following content −
This is demo!
This is demo!
Now, let us see the example.
#include <stdio.h>
int main() {
   FILE *f = fopen("new.txt", "r");
   int c = getc(f);
   while (c != EOF) {
      putchar(c);
      c = getc(f);
   }
   if (feof(f))
   printf("\n Reached to the end of file.");
   else
   printf("\n Failure.");
   fclose(f);
   getchar();
   return 0;
}
This is demo!
This is demo!
Reached to the end of file.
In the above program, In the above program, file is opened by using fopen(). When integer variable c is not equal to EOF, it will read the file. The function feof() is checking again that pointer has reached to the end of file or not.
FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}
if (feof(f))
printf("\n Reached to the end of file.");
else
printf("\n Failure.");
How to extract unique combinations of two or more variables in an R data frame?

An R data frame can have a large number of categorical variables and these categorical form different combinations. For example, one value of a variable could be linked with two or more values of the other variable. Also, one categorical variable can have all unique categories. We can find this unique combination for as many variables as we want and it can be done with the help of unique function.
Consider the below data frame −
> x1<-rep(c(1,2,3,4,5),times=4)
> x2<-rep(c("A","B","C","D"),each=5)
> x3<-letters[1:20]
> x4<-rep(c(5,10,15,20),times=c(2,8,6,4))
> df<-data.frame(x1,x2,x3,x4)
> df
x1 x2 x3 x4
1 1 A a 5
2 2 A b 5
3 3 A c 10
4 4 A d 10
5 5 A e 10
6 1 B f 10
7 2 B g 10
8 3 B h 10
9 4 B i 10
10 5 B j 10
11 1 C k 15
12 2 C l 15
13 3 C m 15
14 4 C n 15
15 5 C o 15
16 1 D p 15
17 2 D q 20
18 3 D r 20
19 4 D s 20
20 5 D t 20
Finding the unique combinations of x2, and x4 −
> unique(df[c("x2","x4")])
x2 x4
1 A 5
3 A 10
6 B 10
11 C 15
16 D 15
17 D 20
Finding the unique combinations of x1, x3, and x4 −
> unique(df[c("x1","x3","x4")])
x1 x3 x4
1 1 a 5
2 2 b 5
3 3 c 10
4 4 d 10
5 5 e 10
6 1 f 10
7 2 g 10
8 3 h 10
9 4 i 10
10 5 j 10
11 1 k 15
12 2 l 15
13 3 m 15
14 4 n 15
15 5 o 15
16 1 p 15
17 2 q 20
18 3 r 20
19 4 s 20
20 5 t 20
Finding the unique combinations of x1, x2, and x4 −
> unique(df[c("x1","x2","x4")])
x1 x2 x4
1 1 A 5
2 2 A 5
3 3 A 10
4 4 A 10
5 5 A 10
6 1 B 10
7 2 B 10
8 3 B 10
9 4 B 10
10 5 B 10
11 1 C 15
12 2 C 15
13 3 C 15
14 4 C 15
15 5 C 15
16 1 D 15
17 2 D 20
18 3 D 20
19 4 D 20
20 5 D 20
How to print duplicate rows in a table? - GeeksforGeeks

21 Jun, 2018
In the above table, we can find duplicate row using below query.
SELECT name, section FROM tbl
GROUP BY name, section
HAVING COUNT(*) > 1

Another Example:Given a table named PERSON task is to write an SQL query to find all duplicate name in the table.Example :
+----+---------+
| Id | NAME    |
+----+---------+
| 1  | Geeks   |
| 2  | for     |
| 3  | Geeks   |
+----+---------+

Output :
+---------+
| NAME    |
+---------+
| Geeks   |
+---------+

The simple approach is to make a temporary table which have count of all the names in a table.
Duplicated NAME existed more than one time, so to count the times each NAME exists, we can use the following code:
select NAME, count(NAME) as num
from Person
group by NAME;

| NAME    | num |
|---------|-----|
| Geeks   | 2   |
| for     | 1   |

This is a temporary table, on which we can run the below code to get duplicate NAME.
select NAME from
(
  select NAME, count(NAME) as num
  from Person
  group by NAME
) as statistic
where num > 1;

The Best approach is to use GROUP BY and HAVING condition. It is more effective and faster then previous.
MySql :
select NAME
from Person
group by NAME
having count(NAME) > 1;

This article is contributed by Sahil Rajput. 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.
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
Introduction of B-Tree
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of ER Model
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
SQL Trigger | Student Database
SQL | Views
How to sort the objects in a list in Python?

To sort a list of ints, floats, strings, chars or any other class that has implemented the __cmp__ method can be sorted just by calling sort on the list. If you want to sort the list in reverse order(descending), just pass in the reverse parameter as well. 
my_list = [1, 5, 2, 6, 0]
my_list.sort()
print(my_list)
my_list.sort(reverse=True)
print(my_list)
This will give the output −
[0, 1, 2, 5, 6]
[6, 5, 2, 1, 0]
Since tuples are immutable, they don't have an in-place sort function that can be called directly on them. You have to use the sorted function, which returns a sorted list. If you dont want to sort the list in place, use sorted in place of the list class method sort. 
my_list = [1, 5, 2, 6, 0]
print(sorted(my_list))
print(sorted(my_list, reverse=True))
This will give the output −
[0, 1, 2, 5, 6]
[6, 5, 2, 1, 0]
If you have a list of objects without __cmp__ method implemented in the class, you can use the key argument to specify how to compare 2 elements. For example, if you have dictionaries in a list and want to sort them based on a key size, you could do the following:
def get_my_key(obj):
  return obj['size']
my_list = [{'name': "foo", 'size': 5}, {'name': "bar", 'size': 3}, {'name': "baz", 'size': 7}]
my_list.sort(key=get_my_key)
print(my_list)
This will give the output −
[{'name': 'bar', 'size': 3}, {'name': 'foo', 'size': 5}, {'name': 'baz', 'size': 7}]
It would call the function specified for each entry and sort based on this value for each entry. You could also specify the same function for an object as well, by returning an attribute of the object.
Rotate div to -20 degrees angle with CSS

You can try to run the following code to rotate div to -20 degrees angle with CSS −
 Live Demo
<html>
   <head>
      <style>
         div {
            width: 300px;
            height: 100px;
            background-color: pink;
            border: 1px solid black;
         }
         div#myDiv {
            /* IE 9 */
            -ms-transform: rotate(-20deg);
            /* Safari */
            -webkit-transform: rotate(-20deg);
            /* Standard syntax */
            transform: rotate(-20deg);
         }
      </style>
   </head>
   
   <body>
      <div>
         Tutorials point.com.
      </div>
      
      <div id = "myDiv">
         Tutorials point.com
      </div>
   </body>
   
</html>
C++ Program to Implement Nearest Neighbour Algorithm

This is a C++ program to implement Nearest Neighbour Algorithm which is used to implement traveling salesman problem to compute the minimum cost required to visit all the nodes by traversing across the edges only once.
Begin
   Initialize c = 0, cost = 1000;
   Initialize g[][].
   function swap() is used to swap two values x and y.
   function cal_sum() to calculate the cost which take array a[] and size of array as input.
   Initialize sum =0.
   for i = 0 to n
      compute s+= g[a[i %3]][a[(i+ 1) %3]];
   if (cost >s)
      cost = s
   function permute() is used to perform permutation:
   If there is one lement in array
      call cal_sum().
   else
      for j = i to n
         swap (a+i) with (a + j)
         cal_sum(a+1,n)
         swap (a+i) with (a + j)
End
#include<iostream>
using namespace std;

int c = 0, cost = 1000;
int g[3][3 ] = { {1,2,3},{4,5,8},{6,7,10}};

void swap(int *x, int *y) {
   int t;
   t = *x;
   *x = *y;
   *y = t;
}

void cal_sum(int *a, int n) {
   int i, s= 0;
   for (i = 0; i <= n; i++) {
      s+= g[a[i %3]][a[(i+ 1) %3]];
   }
   if (cost >s) {
      cost = s;
   }
}

void permute(int *a,int i,int n) {
   int j, k;
   if (i == n) {
      cal_sum (a,n);
   } else {
      for (j = i; j <= n; j++) {
         swap((a + i), (a + j));
         cal_sum(a+1,n);
         swap((a + i), (a + j));
      }
   }
}

int main() {
   int i, j;
   int a[] = {1,2,3};//take array elements
   permute(a, 0,2);
   cout << "minimum cost:" << cost << endl;
}
minimum cost:3
How to Create a Sequence of Linearly Increasing Values with Numpy Arrange? - GeeksforGeeks

05 Aug, 2021
In this article, we are going to create a sequence of linearly increasing values with Numpy arrange() function. 
By using arrange() function, we can create a sequence of linearly increasing values. This method returns an array with evenly spaced elements as per the interval. The interval mentioned is half opened i.e. [Start, Stop)
Syntax: numpy.arrange(start, stop, step)
Parameters:
start is the starting value
stop is the ending value
step is a linear increment value with in the given range. It is optional. By default, it is 1.
Return Type:
Return an array of elements
For example:
numpy.arrange(1,10,3)  # array([1,4,7])
Here, we have given a range from 1 to 10(start = 1 and stop = 10) but we specified step=3. That means it skips every 3 elements in a range. So In this way, we can increase linearity in data.
Example 1: 
Create elements within range with 3-step linearly.
Python3
# importing numpy moduleimport numpy as np # create an elements from 1# to 10 with 3 step linearityprint(np.arrange(1, 10, 3)) # create an elements from 1# to 20 with 3 step linearityprint(np.arrange(1, 20, 3)) # create an elements from 1# to 30 with 3 step linearityprint(np.arrange(1, 30, 3)) # create an elements from 1# to 40 with 3 step linearityprint(np.arrange(1, 40, 3)) # create an elements from 1# to 50 with 3 step linearityprint(np.arrange(1, 50, 3))
Output:
Example 2:
Create elements within range with 5-step linearly.
Python3
#importing numpy moduleimport numpy as np #create an elements from 1 to# 10 with 5 step linearityprint(np.arrange(1,10,5)) #create an elements from 1 to# 20 with 5 step linearityprint(np.arrange(1,20,5)) #create an elements from 1 to# 30 with 5 step linearityprint(np.arrange(1,30,5)) #create an elements from 1 to# 40 with 5 step linearityprint(np.arrange(1,40,5)) #create an elements from 1 to# 50 with 5 step linearityprint(np.arrange(1,50,5))
 
 
Output:
 
 
Example 3:
 
Create elements within the range of 34 to 50 with 5-step linearly.
 
Python3
#importing numpy moduleimport numpy as np #create an elements from 34 to 50 with 4 step linearityprint(np.arrange(34,50,5))
Output:
[34 39 44 49]
saurabh1990aror
Picked
Pyhton numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python | Column Average in Record List - GeeksforGeeks

19 Feb, 2020
Sometimes the data that we receive, is in the form of tuples having data from various sources and we can usually have a use case in which we require to process the finding average of each index of tuple for cumulation. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehensionThis is the most naive method to perform this particular task, in this method we compute the average of each index of all the possible indices of the tuple.
# Python3 code to demonstrate # Column Average in Record List# using list comprehension  # initializing list test_list = [(1, 6), (3, 4), (5, 8)]  # printing original list print ("The original list is : " + str(test_list))  # Column Average in Record List# using list comprehensiontemp = sum(i[0] for i in test_list), sum(i[1] for i in test_list)res = []for ele in temp:    res.append(ele / len(test_list))  # printing summationprint ("The position Average of tuples : " + str(res))
The original list is : [(1, 6), (3, 4), (5, 8)]
The position Average of tuples : [3.0, 6.0]

 
Method #2 : Using zip() + sum()This is the most elegant and pythonic way to perform this particular task. In this we combine all the indices of the element using zip() and the performance of summation using sum function. And then divide the list by list length to compute average.
# Python3 code to demonstrate # Column Average in Record List# using zip() + sum()  # initializing list test_list = [(1, 6), (3, 4), (5, 8)]  # printing original list print ("The original list is : " + str(test_list))  # Column Average in Record List# using zip() + sum()temp = [sum(i) for i in zip(*test_list)]res = []for ele in temp:    res.append(ele / len(test_list))  # printing summationprint ("The position Average of tuples : " + str(res))
The original list is : [(1, 6), (3, 4), (5, 8)]
The position Average of tuples : [3.0, 6.0]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
C++ Program to Add Complex Numbers by Passing Structure to a Function

Complex numbers are numbers that are expressed as a+bi where i is an imaginary number and a and b are real numbers. Some examples on complex numbers are −
2+5i
3-9i
8+2i
A program to add complex numbers by passing structure to a function is given as follows −
 Live Demo
#include <iostream>

using namespace std;
typedef struct complexNumber {
   float real;
   float imag;
};
complexNumber addCN(complexNumber num1,complexNumber num2) {
   complexNumber temp;
   temp.real = num1.real + num2.real;
   temp.imag = num1.imag + num2.imag;
   return(temp);
}
int main() {
   complexNumber num1, num2, sum;
   cout << "Enter real part of Complex Number 1: " << endl;

   cin >> num1.real;
   cout << "Enter imaginary part of Complex Number 1: " << endl;

   cin >> num1.imag;
   cout << "Enter real part of Complex Number 2: " << endl;

   cin >> num2.real;
   cout << "Enter imaginary part of Complex Number 2: " << endl;

   cin >> num2.imag;
   sum = addCN(num1, num2);

   if(sum.imag >= 0)
   cout << "Sum of the two complex numbers is "<< sum.real <<" + "<< sum.imag <<"i";
   else
   cout << "Sum of the two complex numbers is "<< sum.real <<" + ("<< sum.imag <<")i";
   return 0;
}
The output of the above program is as follows −
Enter real part of Complex Number 1: 5
Enter imaginary part of Complex Number 1: -9
Enter real part of Complex Number 2: 3
Enter imaginary part of Complex Number 2: 6
Sum of the two complex numbers is 8 + (-3)i
In the above program, the structure complexNumber contains the real and imaginary parts of the complex number. This is given below −
struct complexNumber {
   float real;
   float imag;
};
The function addCN() takes two arguments of type complexNumber type and adds the real and imaginary parts of the two numbers. Then the added value is returned to the main() function. This is given below −
complexNumber addCN(complexNumber num1,complexNumber num2) {
   complexNumber temp;
   temp.real = num1.real + num2.real;
   temp.imag = num1.imag + num2.imag;
   return(temp);
}
In the main() function, the values of the numbers are obtained from the user. This is given below −
cout << "Enter real part of Complex Number 1: " << endl;
cin >> num1.real;
cout << "Enter imaginary part of Complex Number 1: " << endl;
cin >> num1.imag;

cout << "Enter real part of Complex Number 2: " << endl;
cin >> num2.real;
cout << "Enter imaginary part of Complex Number 2: " << endl;
cin >> num2.imag;
The sum of the two numbers is obtained by the calling the addCN() function. Then the sum is printed. This is given below −
sum = addCN(num1, num2);
if(sum.imag >= 0)
cout << "Sum of the two complex numbers is "<< sum.real <<" + "<< sum.imag <<"i";

else
cout << "Sum of the two complex numbers is "<< sum.real <<" + ("<< sum.imag <<")i";
Python - Extract URL from Text

URL extraction is achieved from a text file by using regular expression. The expression fetches the text wherever it matches the pattern. Only the re module is used for this purpose. 
We can take a input file containig some URLs and process it thorugh the following program to extract the URLs. The findall()function is used to find all instances matching with the regular expression. 
Shown is the input file below. Which contains teo URLs.
Now a days you can learn almost anything by just visiting http://www.google.com. But if you are completely new to computers or internet then first you need to leanr those fundamentals. Next
you can visit a good e-learning site like - https://www.tutorialspoint.com to learn further on a variety of subjects.

Now, when we take the above input file and process it through the following program we get the required output whihc gives only the URLs extracted from the file. 
import re
 
with open("path\url_example.txt") as file:
        for line in file:
            urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', line)
            print(urls)

When we run the above program we get the following output −
['http://www.google.com.']
['https://www.tutorialspoint.com']


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
C++ Vector Library - back() Function

The C++ function std::vector::back() returns a reference to the last element of the vector.
Calling back on empty vector causes undefined behavior.
Following is the declaration for std::vector::back() function form std::vector header.
reference back();
const_reference back() const;

None
Reference to last element of the vector.
If vector object is constant qualified then method returns a constant reference otherwise non-constant reference.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::vector::back() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   auto il = {1, 2, 3, 4, 5};
   vector<int> v(il);

   cout << "Last element of vector = " << v.back() << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Last element of vector = 5

 Print
 Add Notes
 Bookmark this page