code-rag-bench/online-tutorials huggingface dataset:
wxPython - Add submenu in Menu - GeeksforGeeks

15 May, 2020
In this article we are going to learn How can we add submenu to a Menuitem inside a Menu present on MenuBar. In this we use AppendMenu() function rather than just using Append().
Steps :1. Create a MenuBar in frame using MenuBar() constructor.2. Add menu to the menu bar.3. Create wx.Menu for Menuitem.4. Add menu using ApendMenu() function.
Syntax :
wx.Menu.AppendMenu(self, id, subMenu, helpString)

Parameters of AppendMenu():
Code Example:
import wx    class Example(wx.Frame):      def __init__(self, *args, **kwargs):        super(Example, self).__init__(*args, **kwargs)          self.InitUI()      def InitUI(self):          menubar = wx.MenuBar()        fileMenu = wx.Menu()          # submenu for menuitem        imp = wx.Menu()        imp.Append(wx.ID_ANY, 'SubMenu 1')        imp.Append(wx.ID_ANY, 'SubMenu 2')        imp.Append(wx.ID_ANY, 'SubMenu 3')          # append submenu with menuitem        fileMenu.AppendMenu(wx.ID_ANY, 'MenuItem', imp)        menubar.Append(fileMenu, '&Menu')        self.SetMenuBar(menubar)          self.SetSize((350, 250))        self.SetTitle('Submenu')        self.Centre()      def OnQuit(self, e):        self.Close()    def main():      app = wx.App()    ex = Example(None)    ex.Show()    app.MainLoop()    if __name__ == '__main__':    main()
Output :
Python-gui
Python-wxPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Lambda Functions in LISP - GeeksforGeeks

09 Nov, 2021
In this article, we will discuss lambda functions in LISP. The Lambda function is used to evaluate a mathematical expression in our program. They are also known as anonymous functions.
We can create these functions using lambda expression.
Syntax:
(lambda (parameters) expression_code)
where,
The parameters are the numbers of operands in the expressionThe expression_code is the mathematical logic expression
The parameters are the numbers of operands in the expression
The expression_code is the mathematical logic expression
Example 1: LISP program to evaluate the mathematical expression through a lambda expression
Lisp
;lambda expression to get sum of product of four numbers;mathematical expression is (val1*val2) + (val3*val4)  (write ((lambda (val1 val2 val3 val4)   (+  (* val1 val2) (+ (* val3 val4))))   ;pass the values   2 4 6 8))(terpri)(write ((lambda (val1 val2 val3 val4)   (+  (* val1 val2) (+ (* val3 val4))))   ;pass the values   10 20 30 40))
Output:
56
1400
Example 2: LISP Program to evaluate an expression
Lisp
;lambda expression to get product of two numbers;mathematical expression is (val1*val2)   (write ((lambda (val1 val2 )   (* val1 val2))   ;pass the values   60 4 ))(terpri)(write ((lambda (val1 val2 )   (* val1 val2))   ;pass the values   10 20 ))
Output:
240
200
LISP-Basics
Picked
LISP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cond Construct in LISP
Data Types in LISP
Dotimes Construct in LISP
Mapping Functions in LISP
LISP - Comparison Operators on Characters & Strings
Symbols in LISP
Sets in LISP
Property Lists in LISP
Vectors in LISP
Case Construct in LISP
How to adjust the size of a Matplotlib legend box?

To adjust the size of a matplotlib legend box, we can use borderpad arguments in the legend method.
Create line1 and line2 using two lists with different line widths.
Create line1 and line2 using two lists with different line widths.
To place a legend on the figure and to adjust the size of legend box, use borderpad=2 in legend() method.
To place a legend on the figure and to adjust the size of legend box, use borderpad=2 in legend() method.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
line1, = plt.plot([1, 5, 1, 7], linewidth=0.7)
line2, = plt.plot([5, 1, 7, 1], linewidth=2.0)
plt.legend([line1, line2], ["line1", "line2"], bbox_to_anchor=(0.35, 1.0), borderpad=2)
plt.show()
How regular expression back references works in  Python?

We group part of a regular expression by enclosing it in a pair of parentheses. This way we apply operators to the group instead of a single character.
Parentheses not only group sub-expressions but they also create backreferences. The part of the string matched by the grouped part of the regular expression, is stored in a backreference. With the use of backreferences we reuse parts of regular expressions. 
If sub-expression is placed in parentheses, it can be accessed with \1 or $1 and so on.
For example, the regex \b(\w+)\b\s+\1\b matches repeated words, such as tahiti tahiti, because the parentheses in (\w+) capture a word to Group 1 then the back-reference \1 matches the characters that were captured by Group 1.
import re s = 'Tahiti Tahiti Atoll' result = re.findall(r'\b(\w+)\b\s+\1\b', s) print result
This gives the output
['Tahiti']
Tokenize a string in C++?

First way is using a stringstream to read words seperated by spaces. This is a little limited but does the task fairly well if you provide the proper checks. 
#include <vector>
#include <string>
#include <sstream>

using namespace std;

int main() {
   string str("Hello from the dark side");
   string tmp; // A string to store the word on each iteration.
   stringstream str_strm(str);

   vector<string> words; // Create vector to hold our words

   while (str_strm >> tmp) {
      // Provide proper checks here for tmp like if empty
      // Also strip down symbols like !, ., ?, etc.
      // Finally push it.
      words.push_back(tmp);
   }
}
Another way is to provide a custom delimiter to split the string by using the getline function −
#include <vector>
#include <string>
#include <sstream>

using namespace std;

int main() {
   std::stringstream str_strm("Hello from the dark side");
   std::string tmp;
   vector<string> words;
   char delim = ' '; // Ddefine the delimiter to split by

   while (std::getline(str_strm, tmp, delim)) {
      // Provide proper checks here for tmp like if empty
      // Also strip down symbols like !, ., ?, etc.
      // Finally push it.
      words.push_back(tmp);
   }
}
HTML <table> align Attribute - GeeksforGeeks

22 Feb, 2022
The HTML <table> align Attribute is used to specify the alignment of the table and its content.
Note : This attribute is not supported by HTML5.
Syntax:
<table align="left | right | center">
Attribute Values:
left: It sets the left align to the table. It is a default value.
right: It sets the right align to the table.
center: It sets the center align to the table.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML table align Attribute    </title></head>  <body>    <h1 style="green">GeeksforGeeks</h1>      <h2>HTML table align Attribute</h2>      <table border="1"            align="right">        <caption>Author Details</caption>          <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>        <tr>            <td>BITTU</td>            <td>22</td>            <td>CSE</td>        </tr>        <tr>            <td>RAM</td>            <td>21</td>            <td>ECE</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <table> align attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
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.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Form validation using HTML and JavaScript
How to create an HTML button that acts like a link?
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
Top 10 Angular Libraries For Web Developers
Python Tweepy – Getting the URL of a user - GeeksforGeeks

18 Jun, 2020
In this article we will see how we can get the URL of a user. The url attribute is a URL provided by the user in association with their profile. The URL attribute is optional and is Nullable.
Identifying the URL in the GUI :
In the above mentioned profile the url is : geeksforgeeks.org
In order to get the URL we have to do the following :
Identify the user ID or the screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the url attribute present in it.
Identify the user ID or the screen name of the profile.
Get the User object of the profile using the get_user() method with the user ID or the screen name.
From this object, fetch the url attribute present in it.
Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058.
# 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 ID of the userid = 57741058  # fetching the useruser = api.get_user(id)  # fetching the urlurl = user.url  print("The URL of the user is : " + url)
Output :
The URL of the user is : http://t.co/k2iUfxLRBj

Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG.
# the screen name of the userscreen_name = "PracticeGfG"  # fetching the useruser = api.get_user(screen_name)  # fetching the urlurl = user.url  print("The URL of the user is : " + url)
Output :
The URL of the user is : https://t.co/C5SOw0qMo4

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
How to check whether a string contains a substring in jQuery?

The jQuery :contains() Selector is used to check whether a string contains a substring in jQuery.
Set the substring you are searching for in the contains() method as shown below:
$(document).ready(function(){
   $("p:contains(Video)").css("background-color", "blue");
});
Now, let us see the complete code to check whether a string contains a substring or not:
 Live Demo
<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
      $(document).ready(function(){
         $("p:contains(Video)").css("background-color", "blue");
      });
   </script>
</head>
<body>

<h1>Tutorialspoint</h1>

<p>This is demo text.</p>
<p>Free Tutorials</p>
<p>Free Video Tutorials</p>

</body>
</html>
How to use input type field with date field in HTML?

The <input type="date"> is for input fields with date. It allows to easily entering the date with day, month and year. You can get user input for birthday date, registration date, etc.
A datepicker will be visible when you will try to add a date in the input type.
Note − The input type date is not supported by Firefox and Internet Explorer. It works on Google Chrome.
You can try to run the following code to use input type field with date field in HTML. Here, we’re entering the date of birth.
<!DOCTYPE html>
<html>
   <head>
      <title>HTML input date</title>
   </head>

   <body>
      <form action = "" method = "get">
         Enter Registration Date:<br>
         <input type="date" name="birthday"><br>
         <input type="submit" value="Submit">
      </form>
   </body>
</html>
Elements greater than the previous and next element in an Array in C++

In this problem, we are given an array arr[] of n positive integers. Our task is to create a program to find the elements greater than the previous and next element in an Array. 
Code Description: We need to find the elements of the array that satisfy the condition, the element is greater that the element at index 1 less than it and also is greater than the element at index 1 greater than it.
Input: arr[] = {3, 2, 5, 7, 3, 4, 5}
Output: 7
Explanation −
Element with index one less than the current element, 5.Element with index one more than the current element, 3.
The current element is greater than both.
A simple solution to the problem is by checking the condition for each element of the array and then print the element that satisfies the condition.
For this we need to follow these steps−
Step 1: Loop through the elements of the array from index 1 to n-2.
Step 1.1: for each element, arr[i]. We will check if arr[i] > arr[i-1]  and arr[i] > arr[i+1]. 
Step 1.2: If it is true, print arr[i].
Live Demo
#include <iostream>
using namespace std;

void findElemenetsInArray(int arr[], int n) {
   
   for (int i = 1; i < n-1; i++)
      if ( (arr[i] > arr[i+1] && arr[i] > arr[i-1]) ) {
         cout<<arr[i]<<"\t";
      }
}

int main()
{
   int n = 8;
   int arr[n] = { 5, 4, 7, 1, 17, 8, 3 };
   cout<<"The elements that satisfy the given condition are ";
   findElemenetsInArray(arr, n);
   return 0;
}
The elements that satisfy the given condition are 7 17
Combine SUM and FORMAT in MySQL to format the result

Let us create a table −
mysql> create table DemoTable1950
   (
   Amount float
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1950 values(45.60);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1950 values(101.78);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1950 values(75.90);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1950 values(89.45);
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1950;
This will produce the following output −
+--------+
| Amount |
+--------+
|   45.6 |
| 101.78 |
|   75.9 |
|  89.45 |
+--------+
4 rows in set (0.00 sec)
Following is the query to combine SUM and FORMAT in MySQL:
mysql> select format(sum(Amount),2) as TotalSum from DemoTable1950;
This will produce the following output −
+----------+
| TotalSum |
+----------+
| 312.73   |
+----------+
1 row in set (0.00 sec)
numpy.divide() in Python

29 Nov, 2018
numpy.divide(arr1, arr2, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) :Array element from first array is divided by elements from second element (all happens element-wise). Both arr1 and arr2 must have same shape and element in arr2 must not be zero; otherwise it will raise an error.
Parameters :
arr1 : [array_like]Input array or object which works as dividend.arr2 : [array_like]Input array or object which works as divisor.out : [ndarray, optional]Output array with same dimensions as Input array,placed with result.**kwargs : allows you to pass keyword variable length of argument to a function.It is used when we want to handle named argument in a function.where : [array_like, optional]True value means to calculate the universalfunctions(ufunc) at that position, False value means to leave thevalue in the output alone.
Return :
An array with arr1/arr2(element-wise) as elements of output array.

 Code 1 : arr1 divide by arr2 elements
# Python program explaining# divide() functionimport numpy as np  # input_arrayarr1 = [2, 27, 2, 21, 23]arr2 = [2, 3, 4, 5, 6]print ("arr1         : ", arr1)print ("arr2         : ", arr2)  # output_arrayout = np.divide(arr1, arr2)print ("\nOutput array : \n", out)
Output :
arr1         :  [2, 27, 2, 21, 23]
arr2         :  [2, 3, 4, 5, 6]

Output array : 
 [ 1.          9.          0.5         4.2         3.83333333]

 Code 2 : elements of arr1 divided by divisor
# Python program explaining# divide() functionimport numpy as np  # input_arrayarr1 = [2, 27, 2, 21, 23]divisor = 3print ("arr1         : ", arr1)  # output_arrayout = np.divide(arr1, divisor)print ("\nOutput array : \n", out)
Output :
arr1         :  [2, 27, 2, 21, 23]

Output array : 
 [ 0.66666667  9.          0.66666667  7.          7.66666667]
 Code 3 : warning if arr2 has element = 0
# Python program explaining# divide() functionimport numpy as np  # input_arrayarr1 = [2, 27, 2, 21, 23]arr2 = [2, 3, 0, 5, 6]print ("arr1         : ", arr1)print ("arr2         : ", arr2)  # output_arrayout = np.divide(arr1, arr2)print ("\nOutput array : ", out)
Output :
arr1         :  [2, 27, 2, 21, 23]
arr2         :  [2, 3, 0, 5, 6]

Output array :  [ 1.          9.                 inf  4.2         3.83333333]
RuntimeWarning: divide by zero encountered in true_divide
  out = np.power(arr1, arr2)

References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.divide.html.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Python Dictionary
Deque in Python
Stack in Python
Queue in Python
Read a file line by line in Python
Different ways to create Pandas Dataframe
HTML5 | Mathematical operators

03 Dec, 2018
Mathematical Operators are used for representation of mathematical and technical operators. In HTML5 some special codes are used. For the representation of these operators we can use the name or hexadecimal(Hex) reference.
Examples:
Input : &minus or &#8722 
Output : -
Input : &times or &#215
Output : x
Input : &frac34 or &#190
Output : 3/4

<!DOCTYPE html><html><body>     <p>∑</p>  <p>&#8721</p>  <p>°</p>  <p>&#176</p>  <p>≈</p>   <p>&#8776</p></body></html>
Output:


In writing the hex reference in html code, a semicolon is required at the end.Some Common mathematical Characters are-Some Complex mathematical symbols are-
HTML5
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter

26 Jun, 2021
Here, we are going to see how to find the name of a person whose name starts with a specified letter in SQL. In this article, we will be making use of the Microsoft SQL Server as our database.
 For example, finding the name of the person whose name starts with the letter “H”. We will use the % symbol after the specified letter in the SQL query. Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table.
Creating Database:
CREATE DATABASE geeks;
To use this database:
USE geeks;
This is our table in the geeks database
CREATE TABLE department(
    ID int,
    SALARY int,
    NAME Varchar(20),
    DEPT_ID Varchar(255));
To see the table:
EXEC sp_column department;
Add value into the table:
INSERT INTO department VALUES (1, 34000, 'ANURAG', 'UI DEVELOPERS');
INSERT INTO department VALUES (2, 33000, 'harsh', 'BACKEND DEVELOPERS');
INSERT INTO department VALUES (3, 36000, 'SUMIT', 'BACKEND DEVELOPERS');
INSERT INTO department VALUES (4, 36000, 'RUHI', 'UI DEVELOPERS');
INSERT INTO department VALUES (5, 37000, 'KAE', 'UI DEVELOPERS');
This is our data inside the table:
SELECT * FROM department;
Now let’s find the name of a person whose name starts with a specified letter:
Syntax:
SELECT “column_name”
FROM “table_name”
WHERE “column_name” LIKE {PATTERN};
Example 1: In this example, we will find the name starting with H.
 SELECT * FROM department WHERE NAME LIKE 'H%';
Output:
Example 2: In this example, we will find the name starting with R.
 SELECT * FROM department WHERE NAME LIKE 'R%';
Output:
RajuKumar19
sweetyty
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Window functions in SQL
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
SQL Correlated Subqueries
What is Temporary Table in SQL?
C Program for Bubble Sort

13 Jun, 2022
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
C
// C program for implementation of Bubble sort#include <stdio.h>void swap(int *xp, int *yp){int temp = *xp;*xp = *yp;*yp = temp;}// A function to implement bubble sortvoid bubbleSort(int arr[], int n){int i, j;for (i = 0; i < n-1; i++)// Last i elements are already in placefor (j = 0; j < n-i-1; j++)if (arr[j] > arr[j+1])swap(&arr[j], &arr[j+1]);}/* Function to print an array */void printArray(int arr[], int size){int i;for (i=0; i < size; i++)printf("%d ", arr[i]);printf("n");}// Driver program to test above functionsint main(){int arr[] = {64, 34, 25, 12, 22, 11, 90};int n = sizeof(arr)/sizeof(arr[0]);bubbleSort(arr, n);printf("Sorted array: \n");printArray(arr, n);return 0;}
Time Complexity: O(n2)Auxiliary Space: O(1)
Please refer complete article on Bubble Sort for more details!
amankr0211
BubbleSort
C Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
C++ Program to check Prime Number
Producer Consumer Problem in C
C Program to Swap two Numbers
How to Append a Character to a String in C
Merge Sort
QuickSort
Insertion Sort
Selection Sort Algorithm
Ways to sort list of dictionaries by values in Python – Using itemgetter

05 Jul, 2022
In this article, we will cover how to sort a dictionary by value in Python. To sort a list of dictionaries by the value of the specific key in Python we will use the following method in this article.
In everyday programming, sorting has always been a helpful tool. Python’s dictionary is frequently utilized in a variety of applications, from those involving competition to those involving developers (e.g. handling JSON data). In these circumstances, being able to filter dictionaries according to their values can be helpful.There are two methods for doing this sorting:
 
The Itemgetter can be used instead of the lambda function to achieve similar functionality. Outputs in the same way as sorted() and lambda, but has different internal implementation. It takes the keys of dictionaries and converts them into tuples. It reduces overhead and is faster and more efficient. The “operator” module has to be imported for its work. The code is explained below 
Performance: itemgetter performs better than lambda functions in the context of time.
Concise: : itemgetter looks more concise when accessing multiple values than lambda functions.
Example:
Python3
# Python code demonstrate the working of sorted()# and itemgetter # importing "operator" for implementing itemgetterfrom operator import itemgetter # Initializing list of dictionarieslis = [{"name": "Nandini", "age": 20},       {"name": "Manjeet", "age": 20},       {"name": "Nikhil", "age": 19}] # using sorted and itemgetter to print list sorted by ageprint "The list printed sorting by age: "print sorted(lis, key=itemgetter('age')) print("\r") # using sorted and itemgetter to print# list sorted by both age and name# notice that "Manjeet" now comes before "Nandini"print "The list printed sorting by age and name: "print sorted(lis, key=itemgetter('age', 'name')) print("\r") # using sorted and itemgetter to print list# sorted by age in descending orderprint "The list printed sorting by age in descending order: "print sorted(lis, key=itemgetter('age'), reverse=True)
Output:
The list printed sorting by age: 
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}]

The list printed sorting by age and name: 
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Manjeet'}, {'age': 20, 'name': 'Nandini'}]

The list printed sorting by age in descending order: 
[{'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}, {'age': 19, 'name': 'Nikhil'}]
Next Article -> Ways to sort list of dictionaries by values in Python – Using lambda function
surajkumarguptaintern
Python dictionary-programs
python-dict
Python
Sorting
python-dict
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2016 (Set 1) | Question 60

22 Sep, 2021
Consider the following proposed solution for the critical section problem. There are n processes: P0 ...Pn−1. In the code, function pmax returns an integer not smaller than any of its arguments. For all i, t[i] is initialized to zero.
Which one of the following is TRUE about the above solution?(A) At most one process can be in the critical section at any time(B) The bounded wait condition is satisfied(C) The progress condition is satisfied(D) It cannot cause a deadlockAnswer: (A)Explanation:
Mutual exclusion  is satisfied:
All other processes j started before i must have value (i.e. t[j]) 
less than the value of process i (i.e. t[i])  as function pMax() 
return a integer not smaller  than any of its arguments. So if anyone 
out of the processes j have positive value will be executing in its 
critical section as long as the condition t[j] > 0 && t[j] <= t[i] within 
while will persist. And when  this j process comes out of its critical 
section, it sets t[j] = 0;  and next process will be selected in for loop.
So when i process reaches to its critical section none of the  processes j 
which started earlier before process i  is in its critical section. This 
ensure that only one process is executing its critical section at a time. 

Deadlock and progress are  not satisfied:  
while (t[j] != 0 && t[j] <=t[i]); because of this condition deadlock is 
possible when value of j process becomes equals to the value of process i 
(i.e t[j] == t[i]).  because of the deadlock progress is also not possible 
(i.e. Progress == no deadlock) as no one process is able to make progress  
by stopping other process. 

Bounded waiting is also not satisfied: 
In this case both deadlock and bounded waiting to be arising from the same 
reason as if t[j] == t[i] is possible then starvation is possible means 
infinite waiting.
This explanation has been contributed by Dheerendra Singh.Quiz of this Question
kk9826225
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
Python | Reverse All Strings in String List

27 Feb, 2020
Given a list, we always come across situations in which we require to apply certain function to each element in a list. This can be easily done by applying a loop and performing an operation to each element. But having shorthands to solve this problem is always beneficial and helps to focus more on important aspects of problem. Let’s discuss certain ways in which reverse operation on each string in string list can be performed.
Method #1 : Using list comprehensionThis method performs the same task in the background as done by the looping constructs. The advantage this particular method provides is that this is a one liner and also improves code readability.
# Python3 code to demonstrate # Reverse All Strings in String List# using list comprehension  # initializing list test_list = ["geeks", "for", "geeks", "is", "best"]  # printing original listprint ("The original list is : " + str(test_list))  # using list comprehension# Reverse All Strings in String Listres = [i[::-1] for i in test_list]  # printing resultprint ("The reversed string list is : " + str(res))
The original list is : ['geeks', 'for', 'geeks', 'is', 'best']
The reversed string list is : ['skeeg', 'rof', 'skeeg', 'si', 'tseb']

 
Method #2 : Using map()Using map function, one can easily associate an element with the operation one wishes to perform. This is the most elegant way to perform or solve this kind of problems.
# Python3 code to demonstrate # Reverse All Strings in String List# using map()  # initializing list test_list = ["geeks", "for", "geeks", "is", "best"]  # printing original listprint ("The original list is : " + str(test_list))  # Reverse All Strings in String List# using map()reverse = lambda i : i[::-1]res = list(map(reverse, test_list))  # printing resultprint ("The reversed string list is : " + str(res))
The original list is : ['geeks', 'for', 'geeks', 'is', 'best']
The reversed string list is : ['skeeg', 'rof', 'skeeg', 'si', 'tseb']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Timestamp.nanosecond

08 Jan, 2019
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 Timestamp.nanosecond attribute return the nanosecond value of the given Timestamp object.
Syntax : Timestamp.nanosecond
Parameters : None
Return : nanosecond
Example #1: Use Timestamp.nanosecond attribute to find the nanosecond value in the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(2016, 1, 1, 12, 25, 16, 28, 32)  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.nanosecond attribute to print the value of nanosecond in ts object.
# find the value of nanosecondts.nanosecond
Output :
As we can see in the output, the Timestamp.nanosecond attribute has returned 32 indicating that the value of nanosecond in the ts object is set to 32. Example #2: Use Timestamp.nanosecond attribute to find the nanosecond value in the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009,  month = 5, day = 31, hour = 4,                        nanosecond = 15, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.nanosecond attribute to print the value of nanosecond in ts object.
# find the value of nanosecondts.nanosecond
Output :
As we can see in the output, the Timestamp.nanosecond attribute has returned 15 indicating that the value of nanosecond in the ts object is set to 15.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Writing Tests using Selenium Python

29 Dec, 2021
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way. This article illustrates about how to use Selenium Python to write automated tests using Python Selenium.If you have not installed Selenium and its components yet, install them from here – Selenium Python Introduction and Installation. The selenium package itself doesn’t provide a testing tool/framework. One can write test cases using Python’s unittest module. The other options for a tool/framework are py.test and nose. 
We have used unittest framework of Python to write tests. Let’s test search functionality at Python.org using Python selenium tests. To know more about unittest, visit – unittest Documentation. Explanation for each line is give in code itself.Code –  
Python3
# import all required frameworksimport unittestfrom selenium import webdriverfrom selenium.webdriver.common.keys import Keys # inherit TestCase Class and create a new test classclass PythonOrgSearch(unittest.TestCase):     # initialization of webdriver    def setUp(self):        self.driver = webdriver.Firefox()     # Test case method. It should always start with test_    def test_search_in_python_org(self):                 # get driver        driver = self.driver        # get python.org using selenium        driver.get("http://www.python.org")         # assertion to confirm if title has python keyword in it        self.assertIn("Python", driver.title)         # locate element using name        elem = driver.find_element_by_name("q")         # send data        elem.send_keys("pycon")         # receive data        elem.send_keys(Keys.RETURN)        assert "No results found." not in driver.page_source     # cleanup method called after every test performed    def tearDown(self):        self.driver.close() # execute the scriptif __name__ == "__main__":    unittest.main()
Output –  
 
sagartomar9927
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sum 2D array in Python using map() function

22 Nov, 2020
Given a 2-D matrix, we need to find sum of all elements present in matrix ?
Examples:
Input  : arr = [[1, 2, 3], 
                [4, 5, 6], 
                [2, 1, 2]]
Output : Sum = 26


This problem can be solved easily using two for loops by iterating whole matrix but we can solve this problem quickly in python using map() function.
# Function to calculate sum of all elements in matrix# sum(arr) is a python inbuilt function which calculates# sum of each element in a iterable ( array, list etc ).# map(sum,arr) applies a given function to each item of # an iterable and returns a list of the results.def findSum(arr):      # inner map function applies inbuilt function      # sum on each row of matrix arr and returns     # list of sum of elements of each row    return sum(map(sum,arr))    # Driver functionif __name__ == "__main__":    arr = [[1, 2, 3], [4, 5, 6], [2, 1, 2]]    print ("Sum = ",findSum(arr))
Output:
26

What does map() do?The map() function applies a given function to each item of an iterable(list, tuple etc.) and returns a list of the results. For example see given below example :
# Python code to demonstrate working of map()  # Function to calculate square of any numberdef calculateSquare(n):    return n*n  # numbers is a list of elementsnumbers = [1, 2, 3, 4]  # Here map function is mapping calculateSquare # function to each element of numbers list.# It is similar to pass each element of numbers # list one by one into calculateSquare function # and store result in another listresult = map(calculateSquare, numbers)  # resultant output will be [1,4,9,16]print (result)
Output :
[1, 4, 9, 16]
This article is contributed by Shashank Mishra (Gullu). 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.
Matrix
Misc
Python
Misc
Misc
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sudoku | Backtracking-7
Rotate a matrix by 90 degree in clockwise direction without using any extra space
The Celebrity Problem
Unique paths in a Grid with Obstacles
Inplace rotate square matrix by 90 degrees | Set 1
Overview of Data Structures | Set 1 (Linear Data Structures)
vector::push_back() and vector::pop_back() in C++ STL
Top 10 algorithms in Interview Questions
How to write Regular Expressions?
Program for nth Catalan Number
Control Point Border Thickness of ggplot2 Scatterplot in R - GeeksforGeeks

23 May, 2021
In this article, we will see how to control Point Border Thickness of ggplot ScatterPlot in R Programming Language. For this, we will be using geom_point() function. Following is brief information about ggplot function, geom_point().
Syntax : geom_point(size, color, fill, shape, stroke)
Parameter :
size : Size of Points
color : Color of Points/Border
fill : Color of Points
shape : Shape of Points in in range from 0 to 25
stroke : Thickness of point border
Return : It creates scatterplots. 
Let us first create a scatterplot with no modification so that the difference is apparent.
Example: 
R
# Load packagelibrary("ggplot2")  # Create data for plottingdata <- data.frame(x = rnorm(10), y = rnorm(10))  # Create Scatterplot with size 10 and green color ggplot(data, aes(x, y)) +            geom_point(size = 10, color = "green")
Output:
Scatterplot using ggplot2
To change the shape of the points in scatterplot i.e to make borders around points in Scatterplot, we use shape parameter of geom_point() function to set the value as 21 which specify the shape of points in range from 0 to 25. The following image represents the shape of points with range. Other than that we use fill parameter to fill the color of points and color parameter of border color. 
Shapes of Points of Scatterplot with Range
Example:
R
# Load packagelibrary("ggplot2")  # Create data for plottingdata <- data.frame(x = rnorm(10), y = rnorm(10))  # Create a border around points # in Scatterplotggplot(data, aes(x, y)) +            geom_point(size = 10, color = "black",              fill = "green", shape = 21)
Output:
Scatterplot with borders around points
Now to change the thickness of border, we simply use a parameter inside geom_point() function called stroke, which specify the thickness of the border of points in Scatterplot. 
Example:
R
# Load packagelibrary("ggplot2")  # Create data for plottingdata <- data.frame(x = rnorm(10), y = rnorm(10))  # Change thickness of the borderggplot(data, aes(x, y)) +            geom_point(size = 10, color = "black",              fill = "green", shape = 21,              stroke = 4)
Output:
Scatteplot with changed border thickness of points
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement
How to assign values to an array with null/empty objects in JavaScript?

Following is the code to assign values to an array with null/empty objects using JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Assign values to an array with null/empty objects</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to assign values to empty object inside arrObj</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let obj = {
      firstName: "Rohan",
      lastName: "Sharma",
      address: "Delhi",
   };
   let arrObj = [{}, {}, {}];
   BtnEle.addEventListener("click", () => {
      arrObj.forEach((item, index) => {
         item[Object.keys(obj)[index]] = obj[Object.keys(obj)[index]];
      });
      console.log(arrObj);
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button and inspecting the output in console −
Android image scale animation relative to center point?

This example demonstrate about Android image scale animation relative to center point.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout
   xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent">
   <Button
      android:id = "@+id/button"
      android:layout_centerHorizontal = "true"
      android:layout_marginTop = "100dp"
      android:layout_width = "150dp"
      android:text = "Click"
      android:layout_height = "wrap_content"/>
   <ImageView
      android:id = "@+id/imageView"
      android:src = "@mipmap/ic_launcher_round"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</RelativeLayout>
In the above code, we have taken button to show image scaling animation(Zoom animation).
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
   ImageView view;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      view = findViewById(R.id.imageView);
      view.setVisibility(View.INVISIBLE);
      findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            ScaleAnimation fade_in = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            fade_in.setDuration(1000);
            fade_in.setFillAfter(true);
            view.startAnimation(fade_in);
         }
      });
   }
}
when user click on button, it will show image scaling animation using the below code -
ScaleAnimation fade_in = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
fade_in.setDuration(1000);
fade_in.setFillAfter(true);
view.startAnimation(fade_in);
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
in the above screen we have used button, when user click on button, it will show an image with zooming effect as shown below -
Click here to download the project code
VBScript Replace Function

The Replace Function replaces a specified part of a string with a specific string a specified number of times.
Replace(string,find,replacewith[,start[,count[,compare]]]) 

string, a Required Parameter. The Input String from to be searched for replacing.
string, a Required Parameter. The Input String from to be searched for replacing.
find, a Required Parameter. The Part of the String that will be be replaced.
find, a Required Parameter. The Part of the String that will be be replaced.
replace with, a Required Parameter. The replacement string, which would be replaced against the find parameter.
replace with, a Required Parameter. The replacement string, which would be replaced against the find parameter.
start, an Optional Parameter. Specifies the start position from where the string has to be searched and replaced. Default value is 1.
start, an Optional Parameter. Specifies the start position from where the string has to be searched and replaced. Default value is 1.
count, an Optional Parameter. Specifies the number of times the replacement has to be performed.
count, an Optional Parameter. Specifies the number of times the replacement has to be performed.
compare, an Optional Parameter. Specifies the comparison method to be used. Default value is 0.
compare, an Optional Parameter. Specifies the comparison method to be used. Default value is 0.
0 = vbBinaryCompare - Performs a binary comparison
0 = vbBinaryCompare - Performs a binary comparison
1 = vbTextCompare - Performs a Textual comparison
1 = vbTextCompare - Performs a Textual comparison
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         var = "This is VBScript Programming"

         'VBScript to be replaced by MS VBScript
         document.write("Line 1: " & Replace(var,"VBScript","MS VBScript") & "<br />")

         'VB to be replaced by vb
         document.write("Line 2: " & Replace(var,"VB","vb") & "<br />")

         ''is' replaced by ##
         document.write("Line 3: " & Replace(var,"is","##") & "<br />")

         ''is' replaced by ## ignores the characters before the first occurence
         document.write("Line 4: " & Replace(var,"is","##",5) & "<br />")

         ''s' is replaced by ## for the next 2 occurences.
         document.write("Line 5: " & Replace(var,"s","##",1,2) & "<br />")

         ''r' is replaced by ## for all occurences textual comparison.
         document.write("Line 6: " & Replace(var,"r","##",1,-1,1) & "<br />")

         ''t' is replaced by ## for all occurences Binary comparison
         document.write("Line 7: " & Replace(var,"t","##",1,-1,0) & "<br />")

      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1: This is MS VBScript Programming
Line 2: This is vbScript Programming
Line 3: Th## ## VBScript Programming
Line 4: ## VBScript Programming
Line 5: Thi## i## VBScript Programming
Line 6: This is VBSc##ipt P##og##amming
Line 7: This is VBScrip## Programming


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page