code-rag-bench/online-tutorials huggingface dataset:
Python – Find Index containing String in List

04 Jul, 2022
Given a list, the task is to write a Python Program to find the Index containing String.
Example:
Input: [‘sravan’, 98, ‘harsha’, ‘jyothika’, ‘deepika’, 78, 90, ‘ramya’]
Output: 0 2 3 4 7
Explanation: Index 0 2 3 4 7 contains only string.
By using type() operator we can get the string elements indexes from the list, string elements will come under str() type, so we iterate through the entire list with for loop and return the index which is of type string.
Python3
# create a list of names and markslist1 = ['sravan', 98, 'harsha', 'jyothika',         'deepika', 78, 90, 'ramya'] # displaylist1 # iterate through list of elementsfor i in list1:       # check for type is str    if(type(i) is str):               # display index        print(list1.index(i))
Output:
0
2
3
4
7
By using list comprehension we can get indices of string elements.
Syntax: [list.index(iterator) for iterator in list if(type(iterator) is str)]
Python3
# create a list of names and markslist1 = ['sravan', 98, 'harsha', 'jyothika',         'deepika', 78, 90, 'ramya'] # displaylist1 # list comprehensionprint([list1.index(i) for i in list1 if(type(i) is str)]) # list comprehension display stringsprint([i for i in list1 if(type(i) is str)])
Output:
[0, 2, 3, 4, 7]
['sravan', 'harsha', 'jyothika', 'deepika', 'ramya']
Python3
# create a list of names and markslist1 = ['sravan', 98, 'harsha', 'jyothika',        'deepika', 78, 90, 'ramya'] # displayprint(list1) list2=[] # iterate through list of elementsfor i in list1:    # check for type is str    if(isinstance(i,str)):        # display index        list2.append(list1.index(i))print(list2)
['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya']
[0, 2, 3, 4, 7]
sagar0719kumar
kogantibhavya
Picked
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Byte.CompareTo(Byte) Method

07 Dec, 2021
This method is used to compare this instance to a specified 8-bit unsigned integer and returns an indication of their relative values.Syntax:
public int CompareTo (byte value);
Here, the value is an 8-bit unsigned integer to compare.Return Value: This method returns a signed integer that indicates the relative order of this instance and value. 
Less than zero: This instance is less than value.
Zero: This instance is equal to value.
Greater than zero: This instance is greater than value.
Below programs illustrate the use of Byte.CompareTo(Byte) Method:Example 1:
CSHARP
// C# program to demonstrate// Byte.CompareTo(byte)// Methodusing System; class GFG {     // Main Method    public static void Main()    {         // Declaring val1 and val2        byte val1, val2;         // initializing the val1,        // val2 and val3        val1 = 12;        val2 = 13;         // getting compared constant        // using CompareTo method        int i = val2.CompareTo(val1);         // checking the condition        if (i > 0)            Console.Write("val2 is greater than val1");         else if (i < 0)            Console.Write("val2 is less than val1");         else            Console.Write("val1 is equal to val1");    }}
val2 is greater than val1
 
Example 2:
CSHARP
// C# program to demonstrate// Byte.CompareTo(byte)// Methodusing System; class GFG {     // Main Method    public static void Main()    {         // checking the condition        // calling check() method        check((byte)10, (byte)20);        check((byte)30, (byte)20);        check((byte)10, (byte)10);        check((byte)5, (byte)7);        check((byte)40, (byte)50);        check((byte)1, (byte)2);    }     // Defining the check method    public static void check(byte v1, byte v2)    {         // getting compared constant        // using CompareTo() method        int i = v1.CompareTo(v2);         // checking the condition        if (i > 0)            Console.WriteLine(v1 + " is greater than " + v2);         else if (i < 0)            Console.WriteLine(v1 + " is less than " + v2);         else            Console.WriteLine(v1 + " is equal to " + v2);    }}
10 is less than 20
30 is greater than 20
10 is equal to 10
5 is less than 7
40 is less than 50
1 is less than 2
 
Reference: 
https://docs.microsoft.com/en-us/dotnet/api/system.byte.compareto?view=netframework-4.7.2#System_Byte_CompareTo_System_Byte_
simranarora5sos
CSharp-Byte-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tryit Editor v3.7 - Show Java

static void Main()
    {
      // Full name
      string name = "John Doe";

      // Location of the letter D
      int charPos = name.IndexOf("D");

      // Get last name
      string lastName = name.Substring(charPos);

      // Print the result
IsNullOrEmpty() Method in C#

The IsNullOrEmpty() method in C# is used to indicate whether the specified string is null or an empty string ("").
The syntax is as follows−
public static bool IsNullOrEmpty (string val);
Above, the value val is the string to test.
Let us now see an example −
 Live Demo
using System;
public class Demo {
   public static void Main(){
      string str1 = "Amit";
      string str2 = " ";
      Console.WriteLine("Is string1 null or empty? = "+string.IsNullOrEmpty(str1));
      Console.WriteLine("Is string2 null or empty? = "+string.IsNullOrEmpty(str2));
   }
}
This will produce the following output −
Is string1 null or empty? = False
Is string2 null or empty? = False
Let us now see another example −
 Live Demo
using System;
public class Demo {
   public static void Main(){
      string str1 = null;
      string str2 = String.Empty;
      Console.WriteLine("Is string1 null or empty? = "+string.IsNullOrEmpty(str1));
      Console.WriteLine("Is string2 null or empty? = "+string.IsNullOrEmpty(str2));
   }
}
This will produce the following output −
Is string1 null or empty? = True
Is string2 null or empty? = True
Transpose a matrix in C#

Transpose of a matrix flips the matrix over its diagonal and this brings the row elements on the column and column elements on the row.
For example −
Matrix before Transpose:

123
456
789

Matrix after Transpose:
147
258
369
Let us see an example in C# to achieve transpose of a matrix −
using System;
public class Demo {
   public static void Main() {
      int i, j, m, n;
      int[, ] arr1 = new int[30, 30];
      int[, ] arr2 = new int[30, 30];

      Console.Write("\nEnter the number of rows and columns of the matrix :\n");
      Console.Write("Rows entered = ");
      m = Convert.ToInt32(Console.ReadLine());

      Console.Write("Columns entered = ");
      n = Convert.ToInt32(Console.ReadLine());

      Console.Write("Set elements in the matrix...\n");
      for (i = 0; i < m; i++) {
         for (j = 0; j < n; j++) {
            Console.Write("\n [{0}],[{1}] : ", i, j);
            arr1[i, j] = Convert.ToInt32(Console.ReadLine());
         }
      }

      Console.Write("\n\nMatrix before Transpose:\n");
      for (i = 0; i < m; i++) {
         Console.Write("\n");
         for (j = 0; j < n; j++)
         Console.Write("{0}\t", arr1[i, j]);
      }

      for (i = 0; i < m; i++) {
         for (j = 0; j < n; j++) {

            arr2[j, i] = arr1[i, j];
         }
      }

      Console.Write("\n\nMatrix after Transpose: ");
      for (i = 0; i < m; i++) {
         Console.Write("\n");
         for (j = 0; j < n; j++) {
            Console.Write("{0}\t", arr2[i, j]);
         }
      }
      Console.Write("\n\n");
   }
}
The following result will be produced on running the above program. Here, values from the user are to be entered for number of rows and columns, and the elements of the matrix −
Enter the number of rows and columns of the matrix :3 3
Rows entered = 3
Columns entered 3
Set elements in the matrix...

[0],[0] : 1
[0],[1] : 2
[0],[2] : 3
[1],[0] : 4
[1],[1] : 5
[1],[2] : 6
[2],[0] : 7
[2],[1] : 8
[2],[2] : 9

Matrix before Transpose:

123
456
789

Matrix after Transpose:
147
258
369
C++ Numeric Library - accumulate

It returns the result of accumulating all the values in the range [first,last) to init.
Following is the declaration for std::accumulate.
	
template <class InputIterator, class T>
   T accumulate (InputIterator first, InputIterator last, T init);
template <class InputIterator, class T, class BinaryOperation>
   T accumulate (InputIterator first, InputIterator last, T init,
                 BinaryOperation binary_op);
template <class InputIterator, class T>
   T accumulate (InputIterator first, InputIterator last, T init);
template <class InputIterator, class T, class BinaryOperation>
   T accumulate (InputIterator first, InputIterator last, T init,
                 BinaryOperation binary_op);
first, last − It iterators to the initial and final positions in a sequence.
first, last − It iterators to the initial and final positions in a sequence.
init − It is an initial value for the accumulator.
init − It is an initial value for the accumulator.
binary_op − It is binary operation.
binary_op − It is binary operation.
It returns the result of accumulating all the values in the range [first,last) to init.
It throws if any of binary_op, the assignments or an operation on an iterator throws.
The locale object is modified.
In below example for std::accumulate.
#include <iostream>    
#include <functional>   
#include <numeric>     

int myfunction (int x, int y) {return x+2*y;}
struct myclass {
   int operator()(int x, int y) {return x+3*y;}
} myobject;

int main () {
int init = 100;
   int numbers[] = {5,10,20};

   std::cout << "using default accumulate: ";
   std::cout << std::accumulate(numbers,numbers+3,init);
   std::cout << '\n';

   std::cout << "using functional's minus: ";
   std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());
   std::cout << '\n';

   std::cout << "using custom function: ";
   std::cout << std::accumulate (numbers, numbers+3, init, myfunction);
   std::cout << '\n';

   std::cout << "using custom object: ";
   std::cout << std::accumulate (numbers, numbers+3, init, myobject);
   std::cout << '\n';

   return 0;
}
The output should be like this −
using default accumulate: 135
using functional's minus: 65
using custom function: 170
using custom object: 205

 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2003 | Question 20 - GeeksforGeeks

28 Jun, 2021
Consider the following three claims
1. (n + k)m = Θ(nm), where k and m are constants
2. 2n + 1 = O(2n)
3. 22n + 1 = O(2n) 
Which of these claims are correct ?
(A) 1 and 2(B) 1 and 3(C) 2 and 3(D) 1, 2, and 3Answer: (A)Explanation: (n + k)m and Θ(nm) are asymptotically same as theta notation can always be written by taking the leading order term in a polynomial expression.
2n + 1 and O(2n) are also asymptotically same as 2n + 1 can be written as 2 * 2n and constant multiplication/addition doesn’t matter in theta notation.
22n + 1 and O(2n) are not same as constant is in power.
See Asymptotic Notations for more details.
Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
MySQL trigger to insert row into another table?

Let us first create a table. The CREATE command is used to create a table.
mysql> create table Table1
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.62 sec)
Let us now create another table.
mysql> create table Table2
   -> (
   -> id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.49 sec)
Now, the following is how you can create a trigger.
mysql> delimiter #
mysql> create trigger Table1Trigger after insert on Table1
   -> for each row
   -> begin
   ->  insert into Table2(id, name) values (new.id, new.name);
   -> end#
Query OK, 0 rows affected (0.29 sec)

mysql> delimiter ;
To create a trigger, we need to change the delimiter.
Inserting the row into Table1 activates the trigger and inserts the records into Table2. To insert record in Table1.
mysql> insert into Table1 values(1,'John'),(2,'Smith'),(3,'Carol');
Query OK, 3 rows affected (0.28 sec)
Records: 3  Duplicates: 0  Warnings: 0
To check if the records are inserted in both tables or not.
mysql> select *from Table1;
Here is the output that shows record inserted successfully in Table1.
+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|    2 | Smith |
|    3 | Carol |
+------+-------+
3 rows in set (0.00 sec)

To check for second table.
mysql>  select *from Table2;
The following is the output that shows record inserted successfully in Table2.
+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|    2 | Smith |
|    3 | Carol |
+------+-------+
3 rows in set (0.00 sec)
NPDA for accepting the language L = {anbm | n,m ≥ 1 and n ≠ m}

05 Jul, 2022
Prerequisite – Pushdown automata, Pushdown automata acceptance by final state
Problem – Design a non deterministic PDA for accepting the language , i.e.,
L = {aab, abb, aaab, abbb, aaaab, aaabb, aabbb, abbbb ......} 
In each of the string, the number of a’s are followed by unequal number of b’s.
Explanation –Here, we need to maintain the order of a’s and b’s. That is, all the a’s are coming first and then all the b’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack. We will take 2 stack alphabets:
 = { a, z }
Where,
 = set of all the stack alphabetz = stack start symbol
Approach used in the construction of PDA –As we want to design a NPDA, thus every time ‘a’ comes before ‘b’. When ‘a’ comes then push it in stack and if again ‘a’ comes then also push it. After that, when ‘b’ comes then pop one ‘a’ from the stack each time. So, at the end if the stack becomes empty and b is coming or string is end and stack is not empty then we can say that the string is accepted by the PDA.
Stack transition functions –
(q0, a, z)  (q0, az)
(q0, a, a)  (q0, aa)
(q0, b, a)  (q1,  )
(q1, b, a)  (q1,  )
(q1, , a)  (qf, a)   
(q1, b, z)  (qf, z)   

Where, q0 = Initial stateqf = Final state = indicates pop operation
State Transition Diagram –
So, this is our required non deterministic PDA for accepting the language .
mitalibhola94
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
Introduction of Operating System - Set 1
Differences between TCP and UDP
Difference between DFA and NFA
Turing Machine in TOC
Chomsky Hierarchy in Theory of Computation
Boyer-Moore Majority Voting Algorithm
Regular Expressions, Regular Grammar and Regular Languages
Find the k most frequent words from data set in Python

10 Dec, 2017
Given the data set, we can find k number of most frequent words.
The solution of this problem already present as Find the k most frequent words from a file. But we can solve this problem very efficiently in Python with the help of some high performance modules.
In order to do this, we’ll use a high performance data type module, which is collections. This module got some specialized container datatypes and we will use counter class from this module.Examples :
Input : "John is the son of John second. 
         Second son of John second is William second."
Output : [('second', 4), ('John', 3), ('son', 2), ('is', 2)]

Explanation :
1. The string will converted into list like this :
    ['John', 'is', 'the', 'son', 'of', 'John', 
     'second', 'Second', 'son', 'of', 'John', 
     'second', 'is', 'William', 'second']
2. Now 'most_common(4)' will return four most 
   frequent words and its count in tuple. 


Input : "geeks for geeks is for geeks. By geeks
         and for the geeks."
Output : [('geeks', 5), ('for', 3)]

Explanation :
most_common(2) will return two most frequent words and their count.

Approach :
Import Counter class from collections module.Split the string into list using split(), it will
return the lists of words. Now pass the list to the instance of Counter classThe function 'most-common()' inside Counter will return
the list of most frequent words from list and its count.
Import Counter class from collections module.Split the string into list using split(), it will
return the lists of words. Now pass the list to the instance of Counter classThe function 'most-common()' inside Counter will return
the list of most frequent words from list and its count.
Import Counter class from collections module.
Split the string into list using split(), it will
return the lists of words. 
Now pass the list to the instance of Counter class
The function 'most-common()' inside Counter will return
the list of most frequent words from list and its count.
Below is Python implementation of above approach :
# Python program to find the k most frequent words# from data setfrom collections import Counter  data_set = "Welcome to the world of Geeks " \"This portal has been created to provide well written well" \"thought and well explained solutions for selected questions " \"If you like Geeks for Geeks and would like to contribute " \"here is your chance You can write article and mail your article " \" to contribute at geeksforgeeks org See your article appearing on " \"the Geeks for Geeks main page and help thousands of other Geeks. " \  # split() returns list of all the words in the stringsplit_it = data_set.split()  # Pass the split_it list to instance of Counter class.Counter = Counter(split_it)  # most_common() produces k frequently encountered# input values and their respective counts.most_occur = Counter.most_common(4)  print(most_occur)
Output :
[('Geeks', 5), ('to', 4), ('and', 4), ('article', 3)]

Order-Statistics
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.sort() in Python

29 Nov, 2018
numpy.sort() : This function returns a sorted copy of an array.
Parameters :
arr : Array to be sorted.axis : Axis along which we need array to be started.order : This argument specifies which fields to compare first.kind : [‘quicksort’{default}, ‘mergesort’, ‘heapsort’]Sorting algorithm.
Return :
Sorted Array
# importing librariesimport numpy as np  # sort along the first axisa = np.array([[12, 15], [10, 1]])arr1 = np.sort(a, axis = 0)        print ("Along first axis : \n", arr1)            # sort along the last axisa = np.array([[10, 15], [12, 1]])arr2 = np.sort(a, axis = -1)        print ("\nAlong first axis : \n", arr2)    a = np.array([[12, 15], [10, 1]])arr1 = np.sort(a, axis = None)        print ("\nAlong none axis : \n", arr1)
Output :
Along first axis : 
 [[10  1]
 [12 15]]

Along first axis : 
 [[10 15]
 [ 1 12]]

Along none axis : 
 [ 1 10 12 15]
Python numpy-Sorting Searching
Python-numpy
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON
How to create a transparent histogram using ggplot2 in R?

When we create a histogram using ggplot2 package, the area covered by the histogram is filled with grey color but we can remove that color to make the histogram look transparent. This can be done by using fill="transparent" and color="black" arguments in geom_histogram, we need to use color argument because if we don’t use then the borders of the histogram bars will also be removed and this color is not restricted to black color only.
Consider the below data frame −
set.seed(987)
x<-rnorm(10000,2,1.5)
df<-data.frame(x)
Loading ggplot2 package and creating histogram of x −
library(ggplot2) ggplot(df,aes(x))+geom_histogram(bins=30)
Creating the transparent histogram −
ggplot(df,aes(x))+geom_histogram(bins=30,fill="transparent",color="black")
Autocmplete ComboBox in Python-Tkinter - GeeksforGeeks

26 Mar, 2020
Prerequisites: Python GUI – tkinter
The Listbox widget is used to display a list of items from which a user can select a number of items. But have you ever wondered, how to return the list of possible results when a key is pressed? Let’s see the following approach towards the same.
Working of Program
List consisting of words is initialized.
Entry box and Listbox are created and are added to the root window.
Bind function is used for event handling. Key release event is handled for an Entry field.
When any key is pressed in the Entry, checkkey() function is called.
checkkey() function then compares the entered string with existing list keywords and populates Listbox with matching keywords.
Then this data is sent to update function which then updates the Listbox.
Below is the approach.
from tkinter import *         # Function for checking the# key pressed and updating# the listboxdef checkkey(event):           value = event.widget.get()    print(value)          # get data from l    if value == '':        data = l    else:        data = []        for item in l:            if value.lower() in item.lower():                data.append(item)                       # update data in listbox    update(data)      def update(data):          # clear previous data    lb.delete(0, 'end')       # put new data    for item in data:        lb.insert('end', item)    # Driver codel = ('C','C++','Java',     'Python','Perl',     'PHP','ASP','JS' )  root = Tk()  #creating text box e = Entry(root)e.pack()e.bind('<KeyRelease>', checkkey)  #creating list boxlb = Listbox(root)lb.pack()update(l)   root.mainloop()
Output:
Python-tkinter
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
Getting equal or greater than number from the list of numbers in JavaScript

We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument. The function should return an array of all the elements from the input array that are greater than or equal to the number taken as the second argument.
Following is the code −
const arr = [56, 34, 2, 7, 76, 4, 45, 3, 3, 34, 23, 2, 56, 5];
const threshold = 40;
const findGreater = (arr, num) => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      if(arr[i] < num){
         continue;
      };
      res.push(arr[i]);
   };
   return res;
};
console.log(findGreater(arr, threshold));
This will produce the following output in console −
[ 56, 76, 45, 56 ]
Python Tweepy – Getting the number of times a tweet has been retweeted - GeeksforGeeks

18 Jun, 2020
In this article we will see how we can get the number of times a tweet/status has been retweeted. The retweet_count attribute of the Status object provides us with the number of times a tweet has been retweeted .
Identifying the number of times a tweet has been retweeted in the GUI :
The above mentioned status has been retweeted 4 times.
In order to get the number of times a status has been retweeted, we have to do the following :
Identify the status ID of the status from the GUI.Get the Status object of the status using the get_status() method with the status ID.From this object, fetch the retweet_count attribute present in it.
Identify the status ID of the status from the GUI.
Get the Status object of the status using the get_status() method with the status ID.
From this object, fetch the retweet_count attribute present in it.
Example 1 : Consider the following status :
We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272771459249844224.
# 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 statusid = 1272771459249844224  # fetching the statusstatus = api.get_status(id)  # fetching the retweet_count attributeretweet_count = status.retweet_count   print("The number of time the status has been retweeted is : " + str(retweet_count))
Output :
The number of time the status has been retweeted is : 0

Example 2 : Consider the following status :
We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272479136133627905.
# the ID of the statusid = 1272479136133627905  # fetching the status with extended tweet_modestatus = api.get_status(id, tweet_mode = "extended")  # fetching the retweet_count attributeretweet_count = status.retweet_count   print("The number of time the status has been retweeted is : " + str(retweet_count))
Output :
The number of time the status has been retweeted is : 22

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 ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Set style to current link in a Navigation Bar with CSS

To set a style to current link in a navigation bar, add style to .active. You can try to run the following code to style current link:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         ul {
            list-style-type: none;
            margin: 5;
            padding: 5;
         }
         li a {
            display: block;
            width: 70px;
            background-color: #F0E7E7;
         }
         .active {
            background-color: #4CAF50;
            color: white;
         }
      </style>
   </head>
   <body>
      <ul>
         <li><a href="#home">Home</a></li>
         <li><a href="#company" class="active">Company</a></li>
         <li><a href="#product">Product</a></li>
         <li><a href="#services">Services</a></li>
         <li><a href="#contact">Contact</a></li>
      </ul>
   </body>
</html>
Delete items from dictionary while iterating in Python

A python dictionary is a collection which is unordered, changeable and indexed. They have keys and values and each item is referred using the key. In this article we will explore the ways to delete the items form a dictionary.
In this approach we capture the key values that are needed to be deleted. Once we apply the del function, the key value pairs for those keys get deleted.
 Live Demo
# Given dictionary
ADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'}

# Get keys with value in 2,3.
to_del = [key for key in ADict if key in(2,3)]

# Delete keys
for key in to_del: del ADict[key]

# New Dictionary
print(ADict)
Running the above code gives us the following result −
{1: 'Mon', 4: 'Thu', 5: 'Fri'}
We can create a list containing the keys from the dictionary and also use a conditional expression to select the keys to be used for deletion. In the below example we have only considered the keys with even values by comparing the remainder from division with two equal to zero.
 Live Demo
# Given dictionary
ADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'}

# Get keys with even value
for key in list(ADict):
if (key%2) == 0:
del ADict[key]

# New Dictionary
print(ADict)
Running the above code gives us the following result −
{1: 'Mon', 3: 'Wed', 5: 'Fri'}
Instead of keys we can also use the items of the dictionary to delete the values. But after choosing the item we have to indirectly use the keys to select the items to be deleted.
 Live Demo
# Given dictionary
ADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'}

NewDict = []
# Get keys with even value
for key,val in ADict.items():
if val in('Tue','Fri'):
NewDict.append(key)

for i in NewDict:
del ADict[i]

# New Dictionary
print(ADict)
Running the above code gives us the following result −
{1: 'Mon', 3: 'Wed', 4: 'Thu'}
Python - Remove Top level from Dictionary - GeeksforGeeks

22 Apr, 2020
Sometimes, while working with Python Dictionaries, we can have nesting of dictionaries, with each key being single values dictionary. In this we need to remove the top level of dictionary. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed.
Method #1 : Using values() + dictionary comprehensionThe combination of above functions can be used to solve this problem. In this, we perform the task of dictionary reconstruction using dictionary comprehension and nested lists are extracted using values().
# Python3 code to demonstrate working of # Remove Top level from Dictionary# Using dictionary comprehension + values()  # initializing dictionarytest_dict = {'gfg' : {'data1' : [4, 5, 6, 7]},             'is' : {'data2' : [1, 3, 8]},             'best' : {'data3' : [9, 10, 13]}}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Remove Top level from Dictionary# Using dictionary comprehension + values()res = dict(ele for sub in test_dict.values() for ele in sub.items())      # printing result print("The top level removed dictionary is : " + str(res)) 
The original dictionary is : {‘is’: {‘data2’: [1, 3, 8]}, ‘gfg’: {‘data1’: [4, 5, 6, 7]}, ‘best’: {‘data3’: [9, 10, 13]}}The top level removed dictionary is : {‘data1’: [4, 5, 6, 7], ‘data2’: [1, 3, 8], ‘data3’: [9, 10, 13]}
 
Method #2 : Using ChainMap() + dict()The combination of above functionalities can also be used to solve this problem. In this, we employ ChainMap() to perform mapping of nested values.
# Python3 code to demonstrate working of # Remove Top level from Dictionary# Using ChainMap() + dict()from collections import ChainMap  # initializing dictionarytest_dict = {'gfg' : {'data1' : [4, 5, 6, 7]},             'is' : {'data2' : [1, 3, 8]},             'best' : {'data3' : [9, 10, 13]}}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Remove Top level from Dictionary# Using ChainMap() + dict()res = dict(ChainMap(*test_dict.values()))      # printing result print("The top level removed dictionary is : " + str(res)) 
The original dictionary is : {‘is’: {‘data2’: [1, 3, 8]}, ‘gfg’: {‘data1’: [4, 5, 6, 7]}, ‘best’: {‘data3’: [9, 10, 13]}}The top level removed dictionary is : {‘data1’: [4, 5, 6, 7], ‘data2’: [1, 3, 8], ‘data3’: [9, 10, 13]}
Python dictionary-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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
PHP | SimpleXMLElement addChild() Function - GeeksforGeeks

29 May, 2019
Pre-requisite: Read XML Basics
The SimpleXMLElement::addChild() function is an inbuilt function in PHP which is used to add a child in a SimpleXML object.
Syntax:
SimpleXMLElement SimpleXMLElement::addChild($name, $value, $namespace);
Parameter: This function accepts three parameters as mentioned above and described below:
$name: It is required parameter. It specifies the name of the child element to be added.
$value: It is optional parameter. It specifies the value of the child element to be added.
$namespace: It is optional parameter. It specifies namespace for the child element.
Return Value: It returns SimpleXMLElement object on successful child addition.
Note: This function is available for PHP 5.1.3 and newer version.
Example:
<?php// Loading XML document to $user  $user = <<<XML<user><username>user123</username><name>firstname lastname</name><phone>+91-9876543210</phone><detail>I am John Doe. Live in Kolkata, India.</detail></user>XML;  // creating new SimpleXMLElement// object from $user$xml = new SimpleXMLElement($user);  // Adding child named "institution"// and valued "geeksforgeeks"$xml -> addChild("institution", "geeksforgeeks");  // Printing as XMLecho $xml->asXML();  echo $xml->asXML('savexmltofile.xml');  ?>
Output:
user123 firstname lastname +91-9876543210 I am John Doe.
Live in Kolkata, India. geeksforgeeks 1

Saved XML file:
Reference: https://www.php.net/manual/en/simplexmlelement.addchild.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
C# User Input

You have already learned that Console.WriteLine() is used to output (print) values. Now we will use 
Console.ReadLine() to get user input.
In the following example, the user can input his or hers username, which is stored in the 
variable userName. Then we print the value of 

userName:
// Type your username and press enter
Console.WriteLine("Enter username:");

// Create a string variable and get user input from the keyboard and store it in the variable
string userName = Console.ReadLine();

// Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);

Run example »

The Console.ReadLine() method returns a string. Therefore, you cannot get information from another data type, such as int. The following program will cause an error:
Console.WriteLine("Enter your age:");
int age = Console.ReadLine();
Console.WriteLine("Your age is: " + age);
The error message will be something like this:
Like the error message says, you cannot implicitly convert type 'string' to 
'int'. 
Luckily, for you, you just learned from the previous chapter (Type Casting), that you can convert 
any type explicitly, by using one of the 
Convert.To methods:
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);

Run example »

Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like System.FormatException: 'Input string was not in a correct format.').
You will learn more about Exceptions and how to handle errors in a later chapter.
Fill in the missing parts to get user input, stored in the variable userName:
Console.WriteLine("Enter username:");
 userName = Console.;
Console.WriteLine("Username is: " + userName);
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
list::swap() in C++ STL - GeeksforGeeks

12 Jan, 2018
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists.
This function is used to swap the contents of one list with another list of same type and size.
Syntax :
listname1.swap(listname2)
Parameters :
The name of the lists with which
the contents have to be swapped.
Result :
All the elements of the 2 list are swapped.

Examples:
Input  : mylist1 = {1, 2, 3, 4}
         mylist2 = {3, 5, 7, 9}
         mylist1.swap(mylist2);
Output : mylist1 = {3, 5, 7, 9}
         mylist2 = {1, 2, 3, 4}

Input  : mylist1 = {1, 3, 5, 7}
         mylist2 = {2, 4, 6, 8}
         mylist1.swap(mylist2);
Output : mylist1 = {2, 4, 6, 8}
         mylist2 = {1, 3, 5, 7}

Errors and Exceptions
1. It throws an error if the lists are not of the same type.2. It throws an error if the lists are not of the same size.2. It has a basic no exception throw guarantee otherwise.
// CPP program to illustrate// Implementation of swap() function#include <iostream>#include <list>using namespace std;  int main(){    // list container declaration    list<int> mylist1{ 1, 2, 3, 4 };    list<int> mylist2{ 3, 5, 7, 9 };      // using swap() function to     //swap elements of lists    mylist1.swap(mylist2);      // printing the first list    cout << "mylist1 = ";    for (auto it = mylist1.begin();              it != mylist1.end(); ++it)        cout << ' ' << *it;      // printing the second list    cout << endl        << "mylist2 = ";    for (auto it = mylist2.begin();              it != mylist2.end(); ++it)        cout << ' ' << *it;    return 0;}
Output:
mylist1 = 3 5 7 9 
mylist2 = 1 2 3 4 

cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Virtual Function in C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
vector erase() and clear() in C++
Object Oriented Programming in C++
Logger getName() Method in Java with Examples - GeeksforGeeks

26 Mar, 2019
getName() method of a Logger class used to get the name of logger. Many times you have to check the logger name so we can use this method to get the logger name.
Syntax:
public String getName()

Parameters: This method accepts nothing.
Return value: This method return logger name and it will be null for anonymous Loggers.
Below programs illustrate the getName() method:Program 1:
// Java program to demonstrate// Logger.getName() method  import java.util.logging.*;  public class GFG {      // Create a logger using getGLobal()    static Logger logger1        = Logger.getGlobal();      // Create a logger using getLogger()    static Logger logger2        = Logger.getLogger("com.gfg");      public static void main(String[] args)    {        System.out.println("logger1 name = "                           + logger1.getName());          System.out.println("logger2 name = "                           + logger2.getName());    }}
logger1 name = global
logger2 name = com.gfg

Program 2:
// Java program to demonstrate// Logger.getName() method  import java.util.logging.*;  public class GFG {      // Create a logger using getLogger()    static Logger logger        = Logger.getLogger("com.gfg.logger.");      public static void main(String[] args)    {          System.out.println("logger name = "                           + logger.getName());    }}
logger name = com.gfg.logger.

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#getName()
Java - util package
Java-Functions
Java-Logger
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
PostgreSQL - GROUP BY clause - GeeksforGeeks

28 Aug, 2020
The PostgreSQL GROUP BY clause is used to divide rows returned by SELECT statement into different groups. The speciality of GROUP BY clause is that one can use Functions like SUM() to calculate the sum of items or COUNT() to get the total number of items in the groups.
Syntax:
SELECT 
   column_1, 
   column_2,
   computing_function(column_3)
FROM 
   table_name
GROUP BY 
   column_1,
   column_2;
It is important to note that The GROUP BY clause must exactly appear after the FROM or WHERE clause.
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Example 1:Here we will query for data from the payment table and group the result by customer id from the “payment” table of our sample database.
SELECT
   customer_id
FROM
   payment
GROUP BY
   customer_id;
Output:
Example 2:Here we will query to get the amount that each customer has paid till date and use an aggregate function (ie SUM()), to do so and group them by customer_id from the “payment” table of the sample database.
SELECT
    customer_id,
    SUM (amount)
FROM
    payment
GROUP BY
    customer_id;
Output:
Example 3:here we will make a query to count the number of payment transactions that each staff has been processing, you group the rows in the payment table based on staff_id and use the COUNT() function to get the number of transactions.
SELECT
    staff_id,
    COUNT (payment_id)
FROM
    payment
GROUP BY
    staff_id;
Output:
postgreSQL-clauses
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - CREATE PROCEDURE
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Identity Column
HTML - <table> Tag

The HTML <table> tag is used for defining a table. The table tag contains other tags that define the structure of the table.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML table Tag</title>
   </head>

   <body>
      <table border = "1">
         <tr>
            <th>Team</th>
            <th>Ranking</th>
         </tr>
         
         <tr>
            <td>India</td>
            <td>1</td>
         </tr>
         
         <tr>
            <td>South Africa</td>
            <td>2</td>
         </tr>
         
         <tr>
            <td>Australia</td>
            <td>3</td>
         </tr>
      </table>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <table> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Overload unary minus operator in C++?

The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.
The unary operators operate on a single operand and following are the examples of Unary operators −
The increment (++) and decrement (--) operators.
The unary minus (-) operator.
The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometimes they can be used as postfix as well like obj++ or obj--.
Following example explain how minus(-) operator can be overloaded for prefix usage −
#include <iostream>
using namespace std;
class Distance {
   private:
   int feet;
   int inches;
   public:
   // Constructor
   Distance(int f, int i) {
      feet = f;
      inches = i;
   }
   // method to display distance
   void display() {
      cout << "F: " << feet << " I:" << inches <<endl;
   }
   // overloaded minus(-) operator
   Distance operator-() {
      feet = -feet;
      inches = -inches;
      return Distance(feet, inches);
   }
};
int main() {
   Distance D1(3, 4), D2(-1, 10);
   !D1;
   D1.display();
   !D2;
   D2.display();
   return 0;
}
This will give the output −
F: -3 I:-4
F: 1 I:-10
D3.js selection.node() Function - GeeksforGeeks

21 Dec, 2021
The selection.node() function in D3.js is used to return the first element in the selection. If the selection does not contain any elements then it returns null. 
Syntax:
selection.node()
Parameters: This function does not accept any parameters.
Return Values: This function returns the first element in the selection.
Example 1:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" path1tent=        "width=device-width,initial-scale=1.0">    <script src="https://d3js.org/d3.v4.min.js">    </script>    <script src=    "https://d3js.org/d3-selection.v1.min.js">    </script></head>  <body>    <h2>Some text</h2>    <div>Geeks for Geeks </div>      <script>        let selection = d3.selectAll("div")        let div = selection.node();        console.log(div)          // Printing innerHTML of the tag        console.log(div.innerHTML)        selection = d3.selectAll("h1")                  // Null is returned        console.log(selection.node())    </script></body>  </html>
Example 2:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" path1tent=        "width=device-width,initial-scale=1.0">    <script src="https://d3js.org/d3.v4.min.js">    </script>    <script src=    "https://d3js.org/d3-selection.v1.min.js">    </script></head>  <body>    <div>Some text</div>    <div>Geeks for <div>geeks</div>    </div>    <div>Geeks <div></div> for geeks</div>    <div>Some text</div>      <script>        let selection = d3.selectAll("div")        console.log(selection.node())        selection = d3.selectAll("h2")          // Null is returned        console.log(selection.node())    </script></body>  </html>
Output:
kapoorsagar226
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Remove elements from a JavaScript Array
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?