code-rag-bench/online-tutorials huggingface dataset:
TypeScript | Array shift() Method - GeeksforGeeks

18 Jun, 2020
The Array.shift() is an inbuilt TypeScript function which is used to remove the first element from an array and returns that element. Syntax:
array.shift(); 
Parameter: This methods does not accept any  parameter. Return Value: This method returns the removed single value of the array. Below example illustrate the  Array shift() method in TypeScriptJS:
Example 1: 
JavaScript
<script>   // Driver code    var arr = [ 11, 89, 23, 7, 98 ];       // use of shift() method     var val = arr.shift();           // printing    console.log( val );    console.log( arr );</script>
Output: 
11
[ 89, 23, 7, 98 ]


Example 2: 
JavaScript
<script>   // Driver code    var arr = [2, 5, 6, 3, 8, 9];     var val;       // use of reverse() method     val = arr.shift();    console.log( val );    val = arr.shift();    console.log( val );           // printing    console.log( arr );</script>
Output: 
2
5
[ 6, 3, 8, 9 ]

TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Colorizing text and console background in C++ - GeeksforGeeks

27 Jan, 2021
In C++ programming, the default background of the output screen is black and the text color is the white color, the task is to color both the background and text color in the output screen.
Header File:
The header file required to color the text and background can be either of the given header files:
#include <windows.h>or#include <stdlib.h>
Syntax of the color console:
HANDLE console_color;
// Color of the consoleconsole_color = GetStdHandle(STD_OUTPUT_HANDLE);
// P is color code according to your need.SetConsoleTextAttribute(console_color, P);
Below is the program for the same:
C++
// C++ program for the coloring the// background and text with// different color#include <iostream>  // Header file to change color of// text and background#include <windows.h>using namespace std;  // Driver Codeint main(){    // Color of the console    HANDLE console_color;    console_color = GetStdHandle(        STD_OUTPUT_HANDLE);      // Print different colors from 1    // to 50 on the output screen    for (int P = 1; P < 50; P++) {          // P is color code of the        // corresponding color        SetConsoleTextAttribute(            console_color, P);          // Print Statement        cout << P << " Hello Geeks, "             << "good night!!!";    }      return 0;}
Output:
Technical Scripter 2020
C++
C++ Programs
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Iterators in C++ STL
Friend class and function in C++
Polymorphism in C++
Sorting a vector in C++
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
CSV file management using C++
Program to print ASCII Value of a character
turtle.tracer() function in Python - GeeksforGeeks

06 Aug, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to turn turtle animation on or off and set a delay for update drawings.
Syntax : turtle.tracer(n=None, delay=None)
Parameters:
n: If n is given, only each n-th regular screen update is really performed.
delay: sets delay value
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packageimport turtle  # check default valueprint(turtle.tracer())
Output :
1

Example 2 :
Python3
# importing packageimport turtle  # loop for motion with# default tracer as 1for i in range(20):    turtle.forward(1+1*i)    turtle.right(45)  # set tracer values as (2,0)# 2 -> for screen update# 0 -> delayturtle.tracer(n=2, delay=0)  # loop for motion with# above tracer valuesfor i in range(20, 40):    turtle.forward(1+1*i)    turtle.right(45)  # set tracer values as (1,50)# 1 -> for screen update# 50 -> delayturtle.tracer(n=1, delay=50)  # loop for motion with# above tracer valuesfor i in range(40, 60):    turtle.forward(1+1*i)    turtle.right(45)
Output :
Python-turtle
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 program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
How to convert excel content into DataFrame in R ? - GeeksforGeeks

17 Apr, 2021
R Programming Language allows us to read and write data into various files like CSV, Excel, XML, etc. In this article, we are going to discuss how to convert excel content into DataFrame in R Programming. To read an excel file itself, read.xlsx() function from xlsx is used.
This module is not built into R but it can be installed and imported explicitly.  Open the R console and type the command given below to install xlsx package.
install.packages(“xlsx”)
read_xlsx() can be used in the following way:
Syntax: read.xlsx(“Excel File Path”, sheetName = “sheet name”, ...)
Parameters: it is necessary to give the Excel file path and sheetName as argument in read.xlsx() function but many other parameters can be used by this function such as colNames, rowNames, skipEmptyRows, skipEmptyCols, rows, cols, etc. for doing some extra modifications. Here we used colIndex as parameter for getting only column that we want. here we give 1 as a value of colIndex parameter for getting first column of Excel file. 
File in use:
First, we import xlsx package by using the library() function then give the full path of the Excel file to excel_path named variable. To create a dataframe keep extracting columns from the file and combine them into one data frame once done.
Program:
R
library(xlsx)    excel_path <- "excelContent.xlsx"  id <- read.xlsx(excel_path, sheetName = "ageData", colIndex = 1)Name <- read.xlsx(excel_path, sheetName = "ageData", colIndex = 2)Age <- read.xlsx(excel_path, sheetName = "ageData", colIndex = 3)  DataFrame <- data.frame(id, Name, Age)
Output: 
DataFrame created from excel content
Picked
R-Excel
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
How to change the order of bars in bar chart in R ?
Python Program to print strings with repetitive occurrence of an element in a list - GeeksforGeeks

11 Dec, 2020
Given a strings List, write a Python program that extracts all the strings with more than one occurrence of a specific value(here described using K) in elements of a list.
Examples:
Input : test_list = [“geeksforgeeks”, “best”, “for”, “geeks”], K = ‘e’ Output : [‘geeksforgeeks’, ‘geeks’] Explanation : geeks and geeksforgeeks have 2 and 4 occurrences of K respectively.
.Input : test_list = [“geeksforgeeks”, “best”, “for”, “geeks”], K = ‘k’ Output : [‘geeksforgeeks’] Explanation : geeksforgeeks has 2 occurrences of K  
Method 1 : Using loop and count()
In this, we check for all the occurrence of K in each string using count, and check if any string has more than 1 occurrence of K and if found extract that string.
Python3
# initializing Matrixtest_list = ["geeksforgeeks", "best", "for", "geeks"]  # printing original listprint("The original list is : " + str(test_list))  # initializing KK = 'e'  res = []for ele in test_list:      # checking for count greater than 1 (repetitive)    if ele.count(K) > 1:        res.append(ele)  # printing resultprint("Repeated K strings : " + str(res))
 Output:
The original list is : [‘geeksforgeeks’, ‘best’, ‘for’, ‘geeks’]
Repeated K strings : [‘geeksforgeeks’, ‘geeks’]
Method 2 : Using list comprehension and count()
This is short hand solution for this task, similar to above method, just iteration using is done using list comprehension. 
Python3
# initializing Matrixtest_list = ["geeksforgeeks", "best", "for", "geeks"]  # printing original listprint("The original list is : " + str(test_list))  # initializing KK = 'e'  # checking for count greater than 1 (repetitive)# one-liner using list comprehensionres = [ele for ele in test_list if ele.count(K) > 1]  # printing resultprint("Repeated K strings : " + str(res))
Output:
The original list is : [‘geeksforgeeks’, ‘best’, ‘for’, ‘geeks’]
Repeated K strings : [‘geeksforgeeks’, ‘geeks’]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Split string into list of characters
Python Program for Binary Search (Recursive and Iterative)
Convert DataFrame to vector in R - GeeksforGeeks

16 Mar, 2021
In this article, we will discuss how a dataframe can be converted to a vector in R. For the Conversion of dataframe into a vector, we can simply pass the dataframe column name as [[index]].
Approach:
We are taking a column in the dataframe and passing it into another variable by the selection method. Selection method can be defined as choosing a column from a data frame using ” [[]]”.
Create a dataframe
Apply selection process on the columns in a dataframe which is created.
Verify the resultant variable.
Syntax:
convert_data = dataframe_name[[‘column_name’]]
Given below are implementations using this approach to produce this functionality.
Example 1:
R
# creating a vector for namesnames=c('sravan','bobby','ojaswi','gnanesh','rohith','satwik')  # creating vector for marks 1marks1=c(96,76,82,89,100,94)  # creating vector for marks 2marks2=c(98,79,98,78,98,89)  # display all detailsprint(names)print(marks1)print(marks2)print("----------------------")  # passing vectors to the data frameFinal_data = data.frame(names,marks1,marks2)  # display data frameprint(Final_data)print("-------------------conversion---------------------")  # converting marks1 dataframe column into vector# by passing as indexconvert_data1 = Final_data[['marks1']]print(convert_data1)  # converting marks2 dataframe column into vector # by passing as indexconvert_data2 = Final_data[['marks2']]print(convert_data2)
Output:
Example 2:
R
# creating a vector for subjectssubjects=c('java','python','c/c++')  # creating vector for teachersteachers=c('ravi','swapna','sai')  # creating vector for pass percentagepass=c(98.11,90.45,95)  # display all detailsprint(subjects)print(teachers)print(pass)print("----------------------")  # passing vectors to the data frameFinal_data = data.frame(subjects,teachers,pass)  # display data frameprint(Final_data)print("-------------------conversion---------------------")  # converting subjects dataframe column into # vector by passing as indexconvert_data1 = Final_data[['subjects']]print(convert_data1)  # converting teachers dataframe column into # vector by passing as indexconvert_data2 = Final_data[['teachers']]print(convert_data2)  # converting pass dataframe column into vector# by passing as indexconvert_data2 = Final_data[['pass']]print(convert_data2)
Output:
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
Remove rows with NA in one column of R DataFrame
Group by function in R using Dplyr
K-Means Clustering in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to copy or clone a C# list?

To copy or clone a C# list, firstly set a list −
List < string > list1 = new List < string > ();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");
Now declare a string array and use the CopyTo() method to copy.
string[] arr = new string[20];
list1.CopyTo(arr);
Let us see the complete code to copy a list into a one-dimensional array.
using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {
   public static void Main() {
      List < string > list1 = new List < string > ();
      list1.Add("One");
      list1.Add("Two");
      list1.Add("Three");
      list1.Add("Four");

      Console.WriteLine("First list...");
      foreach(string value in list1) {
         Console.WriteLine(value);
      }

      string[] arr = new string[20];
      list1.CopyTo(arr);

      Console.WriteLine("After copy...");

      foreach(string value in arr) {
         Console.WriteLine(value);
      }
   }
}
C# | Get the number of nodes contained in LinkedList<T> - GeeksforGeeks

01 Feb, 2019
LinkedList<T>.Count property is used to get the number of nodes actually contained in the LinkedList<T>.
Syntax:
public int Count { get; }

Return Value: The number of nodes actually contained in the LinkedList.
Note: Retrieving the value of this property is an O(1) operation.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to get the number// of nodes actually contained// in the LinkedListusing System;using System.Collections;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a LinkedList of Strings        LinkedList<String> myList = new LinkedList<String>();          // Adding nodes in LinkedList        myList.AddLast("Geeks");        myList.AddLast("for");        myList.AddLast("Data Structures");        myList.AddLast("Noida");          // To get the number of nodes actually        // contained in the LinkedList        if (myList.Count > 0)            Console.WriteLine(myList.Count);        else            Console.WriteLine("LinkedList is empty");    }}
Output:
4

Example 2 :
// C# code to get the number// of nodes actually contained// in the LinkedListusing System;using System.Collections;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {        // Creating a LinkedList of Integers        LinkedList<int> myList = new LinkedList<int>();          // To get the number of nodes actually        // contained in the LinkedList        if (myList.Count > 0)            Console.WriteLine(myList.Count);        else            Console.WriteLine("LinkedList is empty");    }}
Output :
LinkedList is empty

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.count?view=netframework-4.7.2
CSharp-Generic-Namespace
CSharp-LinkedList
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Difference between Ref and Out keywords in C#
C# | Delegates
Extension Method in C#
C# | Constructors
Introduction to .NET Framework
C# | Abstract Classes
C# | Class and Object
C# | Data Types
C# | Encapsulation
Generate all permutation of a set in Python?

In mathematics, arranging all the members of a set into some order or sequence and if the set is already ordered, rearranging (reordering) its elements is called permutation.
We can generate permutation using different technique. Below are some of them,
Python comes with dedicated module for permutations and combinations called itertools.
>>> import itertools
>>>
The permutation function allows us to get permutation of N values within a list, where order matters. For example, selection N = 2 values with [1,2,3,4] is done as follows −
Permutation (order matters):
>>> print(list(itertools.permutations([1,2,3,4],2)))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
>>> print(list(itertools.combinations('1234', 2)))
[('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]
Below is the implementation on a list without creating new intermediate lists.
def permute(xs, low=0):
if low + 1 >= len(xs):
yield xs
else:
for p in permute(xs, low + 1):
yield p
for i in range(low + 1, len(xs)):
xs[low], xs[i] = xs[i], xs[low]
for p in permute(xs, low + 1):
yield p
xs[low], xs[i] = xs[i], xs[low]
for p in permute([1, 2, 3]):
print (p)
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
import copy
def perm(prefix,rest):
for e in rest:
new_rest=copy.copy(rest)
new_prefix=copy.copy(prefix)
new_prefix.append(e)
new_rest.remove(e)
if len(new_rest) == 0:
print (new_prefix + new_rest)
continue
perm(new_prefix,new_rest)
perm([],[1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
C library function - strstr()

The C library function char *strstr(const char *haystack, const char *needle) function finds the first occurrence of the substring needle in the string haystack. The terminating '\0' characters are not compared.
Following is the declaration for strstr() function.
char *strstr(const char *haystack, const char *needle)
haystack − This is the main C string to be scanned.
haystack − This is the main C string to be scanned.
needle − This is the small string to be searched with-in haystack string.
needle − This is the small string to be searched with-in haystack string.
This function returns a pointer to the first occurrence in haystack of any of the entire sequence of characters specified in needle, or a null pointer if the sequence is not present in haystack.
The following example shows the usage of strstr() function.
#include <stdio.h>
#include <string.h>


int main () {
   const char haystack[20] = "TutorialsPoint";
   const char needle[10] = "Point";
   char *ret;

   ret = strstr(haystack, needle);

   printf("The substring is: %s\n", ret);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
The substring is: Point


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Output of C programs | Set 65 (If-Else) - GeeksforGeeks

07 Sep, 2021
Prerequisite : Decision making in CQuestion 1  
C
#include"stdio.h"#include"stdlib.h"void reverse(int i){    if (i > 5)         exit(0);     printf("%d\n", i);     return reverse(i++);}int main(){    reverse(1);}
OPTIONS: a)Segmenation fault b)Compilation error c)Print 1 Infinite time d)Both a & c 
OUTPUT:  (d)Both a & c
Explanation: We call the main method again and again by 1 because we use post-increment. At certain time stack frame will full means segmentation fault occurs.Question 2  
C
#include"stdio.h"int main(){    if(-1L>1UL)        printf("paul is crazy");    else        printf("mannu is Crazy");}
OPTIONS: a)mannu is Crazy b)paul is crazy  
OUTPUT:  (b)paul is crazy 
Explanation: Here ,comparison between long int and unsigned long int generally which is not possible. Now,long int is promoted to unsigned long int whose value will be (2^size_of_unsigned_long_int)-1.Question 3  
C
#include"stdio.h"int main(){    int i;    if(i=0,2,3)        printf("Geeksforgeeks ");    else        printf("Hello ");    printf("%d\n",i);}
OPTIONS: a)Hello 3 b)Hello 0 c)Geeksforgeeks 0 d)Geeksforgeeks 3 
OUTPUT:  (c) Geeksforgeeks 0
Explanation: At first zero will assign in ‘i’ then comma operator returns the last value which is 3 and condition becomes true.Question 4  
CPP
#include"stdio.h"int main(){    int i;    if(i=(2,1,0))        printf("Geeksforgeeks ");    else        printf("Hello ");    printf("%d\n",i);}
OPTIONS: a)Hello 3 b)Geeksforgeeks 0 c)Hello 0 d)Geeksforgeeks 3 
OUTPUT:  (c) Hello 0
Explanation: Priority of parenthesis bracket is greater than equal to(=) operator , So atfirst comma operator return the last value which is zero(0) and then equal to(=) operator assign 0 to ‘i’ and condition becomes false.Question 5  
C
#include"stdio.h"int main(){    float a=0.7d;    if(a<0.7)         printf("C");        else         printf("C++");    return 0;}
OPTIONS: a)Compilation error b)C++ c)C 
OUTPUT:  (C)C 
Explanation: a = 0.7 is rounded to 0.699999988 and the constant 0.7 is as 0.69999999999 so a<0.7 is true so it print “c” but in case of 0.8 a = 0.800000011 and constant 0.8 is 0.8000000000000000 This article is contributed by Abhishek kurmi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
Avesh_Agrawal
Akanksha_Rai
sumitgumber28
C Basics
Program Output
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways to copy a string in C/C++
Output of Python Program | Set 1
Runtime Errors
Output of python program | Set 2
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Python Dictionary
Inheritance in C++
Overriding in Java
Arrays in C/C++
Copy Constructor in C++
Python | Multiply Integer in Mixed List of string and numbers - GeeksforGeeks

11 Dec, 2019
Sometimes, while working with Python, we can come across a problem in which we require to find the product of list. This problem is easier to solve. But this can get complex in case we have mixture of data types to go along with it. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using Type casting + Exception HandlingWe can employ a brute force method to type caste each element and catch the exception if any occurs. This can ensure that only integers are multiplied to product and hence can solve the problem.
# Python3 code to demonstrate working of# Mixed List Integer Multiplication# using type caste and exception handling  # initializing listtest_list = [5, 8, "gfg", 8, (5, 7), 'is', 2]  # printing original listprint("The original list is : " + str(test_list))  # Mixed List Integer Multiplication# using type caste and exception handlingres = 1for ele in test_list:    try:        res *= int(ele)    except :        pass  # printing result print("Product of integers in list : " + str(res))
The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]
Product of integers in list : 640

 
Method #2 : Using loop + isinstance()This is brute force way in which this task can be performed. In this, we run a loop over all the elements and perform multiplication only when we find an integer using isinstance().
# Python3 code to demonstrate working of# Mixed List Integer Multiplication# using loop + isinstance()  # initializing listtest_list = [5, 8, "gfg", 8, (5, 7), 'is', 2]  # printing original listprint("The original list is : " + str(test_list))  # Mixed List Integer Multiplication# using loop + isinstance()res = 1for ele in test_list:    if(isinstance(ele, int)):        res *= ele  # printing result print("Product of integers in list : " + str(res))
The original list is : [5, 8, 'gfg', 8, (5, 7), 'is', 2]
Product of integers in list : 640

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
Kotlin Inheritance

In Kotlin, it is possible to inherit class properties and functions from one class to another. We group the "inheritance concept" into two categories:
subclass (child) - the class that inherits from another class
superclass (parent) - the class being inherited from
In the example below, MyChildClass (subclass) inherits the 
properties from the 
MyParentClass class 
(superclass):
// Superclassopen class MyParentClass {
  val x = 5
}

// Subclass
class MyChildClass: MyParentClass() {
  fun myFunction() {
    println(x) // x is now inherited from the superclass
  }
}

// Create an object of MyChildClass and call myFunction
fun main() {
  val myObj = MyChildClass()
  myObj.myFunction()
} 
Use the open keyword in front of the superclass/parent, 
to make this the class other classes should inherit properties and functions from.
To inherit from a class, specify the name of the subclass, followed by a colon :, 
and then the name of the superclass.
- It is useful for code reusability: reuse properties and functions of an existing class when you create a new class.
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.
Python | Sum list of dictionaries with same key

03 Mar, 2019
You have given a list of dictionaries, the task is to return a single dictionary with sum values with the same key.
Let’s discuss different methods to do the task.
Method #1: Using reduce() + operator
# Python code to demonstrate# return the sum of values of dictionary# with same keys in list of dictionary  import collections, functools, operator  # Initialising list of dictionaryini_dict = [{'a':5, 'b':10, 'c':90},            {'a':45, 'b':78},             {'a':90, 'c':10}]    # printing initial dictionaryprint ("initial dictionary", str(ini_dict))  # sum the values with same keysresult = dict(functools.reduce(operator.add,         map(collections.Counter, ini_dict)))  print("resultant dictionary : ", str(result))
initial dictionary [{‘b’: 10, ‘a’: 5, ‘c’: 90}, {‘b’: 78, ‘a’: 45}, {‘a’: 90, ‘c’: 10}]resultant dictionary : {‘b’: 88, ‘a’: 140, ‘c’: 100}
 Method #2: Using counter
# Python code to demonstrate# return the sum of values of dictionary# with same keys in list of dictionary  import collections  # Initialising list of dictionaryini_dict = [{'a':5, 'b':10, 'c':90},             {'a':45, 'b':78},            {'a':90, 'c':10}]  # printing initial dictionaryprint ("initial dictionary", str(ini_dict))  # sum the values with same keyscounter = collections.Counter()for d in ini_dict:     counter.update(d)      result = dict(counter)    print("resultant dictionary : ", str(counter))
initial dictionary [{‘c’: 90, ‘a’: 5, ‘b’: 10}, {‘a’: 45, ‘b’: 78}, {‘a’: 90, ‘c’: 10}]resultant dictionary : Counter({‘a’: 140, ‘c’: 100, ‘b’: 88})
 Method #3: Naive Method
# Python code to demonstrate# return the sum of values of dictionary# with same keys in list of dictionary  from operator import itemgetter  # Initialising list of dictionaryini_dict = [{'a':5, 'b':10, 'c':90},            {'a':45, 'b':78},             {'a':90, 'c':10}]  # printing initial dictionaryprint ("initial dictionary", str(ini_dict))  # sum the values with same keysresult = {}for d in ini_dict:    for k in d.keys():        result[k] = result.get(k, 0) + d[k]    print("resultant dictionary : ", str(result))
initial dictionary [{‘b’: 10, ‘c’: 90, ‘a’: 5}, {‘b’: 78, ‘a’: 45}, {‘c’: 10, ‘a’: 90}]resultant dictionary : {‘b’: 88, ‘c’: 100, ‘a’: 140}
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.str.get_dummies()

25 Oct, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas str.get_dummies() is used to separate each string in the caller series at the passed separator. A data frame is returned with all the possible values after splitting every string. If the text value in original data frame at same index contains the string (Column name/ Splitted values) then the value at that position is 1 otherwise, 0.
Since this is a string operation, .str has to be prefixed every time before calling this function. Otherwise, it will throw an error.
Syntax: Series.str.get_dummies(sep=’|’)
Parameters:sep: String value, separator to split strings at
Return type: Data frame with binary values only
To download the data set used in following examples, click here.
In the following examples, the data frame used contains data of some employees. The image of data frame before any operations is attached below. Example #1: Separating different strings on whitespace.
In this example, string in the Team column have been split at ” ” (White-space) and the data frame is returned with all possible values after splitting. The value in returned data frame is 1 if the string(Column name) exists in the text value at same index in old data frame.
Python3
# importing pandasimport pandas as pd  # making data frame from csv at urldata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/employees.csv")  # making dataframe using get_dummies()dummies = data["Team"].str.get_dummies(" ")  # displaydummies.head(10)
Output:As shown in the output image, it can be compared with the original image of data frame. If the string exists at that same index, then value is 1 otherwise 0. Important points:
If string is not null, then at least one column will have value 1 at the same index.
If the value is null, then all columns will have 0 value at that index (Can be seen at 2nd element in above example)
 Example #2: Splitting at multiple points/Static value column
In this example, a static value is taken for the new column (“Hello gfg family”). Then the get_dummies() method is applied and the string is separated at “g”. Since “g” is occurring more than once, there will be more than one column and also the values in all column must be same as the string is also same for all rows.
Python3
# importing pandasimport pandas as pd  # making data frame from csv at urldata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/employees.csv")  # string for new columnstring ="Hello gfg family"  # creating new columndata["New_column"]= string  # creating dummiesdf = data["New_column"].str.get_dummies("g")  # displaydf.head(10)
Output:As shown in output image, the new data frame has 3 columns and every row has same values.
Akanksha_Rai
gabaa406
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JSX Full Form - GeeksforGeeks

03 Jun, 2021
JSX stands for JavaScript XML. It is simply a syntax extension of JavaScript. It allows us to directly write HTML in React (within JavaScript code). It is easy to create a template using JSX in React, but it is not a simple template language instead it comes with the full power of JavaScript.It is faster than normal JavaScript as it performs optimizations while translating to regular JavaScript. Instead of separating the markup and logic in separated files, React uses components for this purpose. We will learn about components in detail in further articles. 
Syntax:
const element = <h1>Welcome to GeeksforGeeks.</h1>;
Characteristics of JSX:
JSX is not mandatory to use there are other ways to achieve the same thing but using JSX makes it easier to develop react application.
JSX allows writing expression in { }. The expression can be any JS expression or React variable.
To insert a large block of HTML we have to write it in a parenthesis i.e, ().
JSX produces react elements.
JSX follows XML rule.
After compilation, JSX expressions become regular JavaScript function calls.
JSX uses camelcase notation for naming HTML attributes. For example, tabindex in HTML is used as tabIndex in JSX.
Advantages of JSX:
JSX makes it easier to write or add HTML in React.
JSX can easily convert HTML tags to react elements.
It is faster than regular JavaScript.
JSX allows us to put HTML elements in DOM without using appendChild() or createElement() method.
As JSX is an expression, we can use it inside of if statements and for loops, assign it to variables, accept it as arguments, or return it from functions.
JSX prevents XSS (cross-site-scripting) attacks popularly known as injection attacks.
It is type-safe, and most of the errors can be found at compilation time.
 
Disadvantages of JSX:
JSX throws an error if the HTML is not correct.
In JSX HTML code must be wrapped in one top-level element otherwise it will give an error.
If HTML elements are not properly closed JSX will give an error.
Example :
index.js
import React from 'react';import ReactDOM from 'react-dom';  const name = "Learner";  const element = <h1>Hello,{ name }.Welcome to GeeksforGeeks.< /h1>;  ReactDOM.render(    element,    document.getElementById("root"));
Output:
ReactJS-Basics
Full Form
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SSTF Full Form
JPEG Full Form
DML Full Form
BLOB Full Form
CIDR Full Form
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
Create a Responsive Navbar using ReactJS
How to pass data from one component to other component in ReactJS ?
MYSQL - CREATE ROLE Statement

A role in MySQL is a set of privileges with name. You can create one or more roles in MySQL using the CREATE ROLE statement. To create a role, you need to have CREATE ROLE or CREATE USER privilege.
Following is the syntax of the CREATE ROLE Statement −
CREATE ROLE [IF NOT EXISTS] desiredname

Where, desiredname is the name of the role you need to create.
Following query creates a role named TestRole_ReadOnly.
mysql> CREATE ROLE 'TestRole_ReadOnly';
Query OK, 0 rows affected (0.13 sec)
Now, let’s grant read only privilege to the created role using the GRANT statement as −
mysql> GRANT SELECT ON * . * TO 'TestRole_ReadOnly';
Query OK, 0 rows affected (0.14 sec)
Then, you can GRANT the created role to a user as follows −
mysql> CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.14 sec)

mysql> GRANT 'TestRole_ReadOnly' TO 'newuser'@'localhost';
Query OK, 0 rows affected (0.13 sec)
You can create a role by specifying the host −
mysql> CREATE ROLE samplerole@localhost;
Query OK, 0 rows affected (0.14 sec)
You can also create multiple roles at once as shown below −
mysql> CREATE ROLE 'MyAdmin', 'MyDeveloper';
Query OK, 0 rows affected (0.21 sec)
If you try to create a role with an existing name an error will be generated −
mysql> CREATE ROLE 'testrole@localhost';
Query OK, 0 rows affected (0.16 sec)
mysql> CREATE ROLE 'testrole@localhost';
ERROR 1396 (HY000): Operation CREATE ROLE failed for 'testrole@localhost'@'%'
If you use the IF NOT EXISTS clause along with the CREATE ROLE statement as shown below a new role will be created and if a role with the given name, already exists the query will be ignored.
mysql> CREATE ROLE IF NOT EXISTS 'testrole@localhost';
Query OK, 0 rows affected, 1 warning (0.12 sec)

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
HTML | <th> align Attribute - GeeksforGeeks

31 Dec, 2021
The HTML <th> align Attribute is used to set the horizontal alignment of text content inside the table header cell.
Syntax:
<th align= "left | right | center | justify | char">
Attribute Values:
left: It sets the text left-align.
right: It sets the text right-align.
center: It sets the text center-align.
justify: It stretches the text of paragraph to set the width of all lines equal.
char: It sets the text-align to a specific character.
Note: The
Example:
<!DOCTYPE html><html>  <head>    <title>      HTML th align Attribute  </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML th align Attribute</h2>      <table width="300" border="1">        <tr>            <th align="left">NAME</th>            <th align="center">AGE</th>            <th align="right">BRANCH</th>        </tr>          <tr>            <td>BITTU</td>            <td>22</td>            <td>CSE</td>        </tr>          <tr>            <td>RAKESH</td>            <td>25</td>            <td>EC</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <th> align attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
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 update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
How to conditionally add attributes to React components? - GeeksforGeeks

05 Jan, 2021
We can conditionally add attributes to React components with the following approaches:
Approach 1: 
Evidently, with some attributes, React is smart enough to omit the attribute if the value you pass to it is not truthy. For example:
state= {
  disabled: false,
  required: true
}

return (
   <input type="text" disabled={disabled} required={required}  />
);
Above Syntax will result in the following output:
<input type="text" required>
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Approach 2: We can use the below syntax:
state {
   condition: true
}

return (
 <Button {...(condition ? {className: 'btn btn-primary'} : {})} />
);
Depending on the value of condition either the {className: ‘btn btn-primary’} or {} will be returned. The Spread Operator will then spread the returned object properties to the Button component. In the falsy case, because the returned object has no properties, nothing will be passed to the component.
Approach 1:
Javascript
import React, { Component } from "react";class App extends Component {    state = {    disabled: true,    text: "Make it Unable"  }      updateState = () => {    let text = !this.state.disabled ? "Make it Unable" : "Make it Disable";    this.setState({ disabled: !this.state.disabled, text: text })  }    render() {    return (      <div>        <input type="text" disabled={this.state.disabled} />        <button          onClick={this.updateState}>          {this.state.text}        </button>      </div>    );  }}  export default App;
Output:
Approach 2:
Javascript
import React, { Component } from "react";class App extends Component {    state = {    condition: true    }      updateState = () => {    this.setState({ condition: !this.state.condition })  }  render() {    return (      <div>        <button          {...(this.state.condition ? { className: 'btn btn-primary' } : {})}          onClick={this.updateState}>          click            </button>      </div>    );  }}  export default App;
Output: 
Picked
react-js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Lodash _.debounce() Method
Angular File Upload
How to remove duplicate elements from JavaScript Array ?
How to change selected value of a drop-down list using jQuery?
C# | Math.Atan() Method - GeeksforGeeks

31 Jan, 2019
Math.Atan() is an inbuilt Math class method which returns the angle whose tangent is given as a double value argument. If the argument is NaN, then the result will be NaN.
Syntax:
public static double Atan(double num)

Parameter:
num: It is the number that represents a tangent and type of this parameter is System.Double.
Return Type: Returns an angle Θ, measured in radians and its type is System.Double. Here the angle is always measured in radians, such that -π/2 ≤ Θ ≤ π/2.
Examples:
Input  : Math.Atan(1)
Output : 0.785398163397448
     
Input  : Math.Atan(0.0)
Output : 0

Input  : Math.Atan(-0.0)
Output : 0

Input  : Math.Atan(Double.PositiveInfinity)
Output : 1.5707963267949

Input  : Math.Atan(Double.NegativeInfinity)
Output : -1.5707963267949

Program: To illustrate the Math.Atan() method
// C# program to demonstrate working// of Math.Atan() methodusing System;  class Geeks {      // Main Method    public static void Main(String []args)    {        double a = Math.PI;                  // using Math.Atan() method         Console.WriteLine(Math.Atan(a));          double d = 0.0;        double e = -0.0;        double posi = Double.PositiveInfinity;        double nega = Double.NegativeInfinity;        double nan = Double.NaN;          Console.WriteLine(Math.Atan(1));          // Input positive zero        // Output positive zero        Console.WriteLine(Math.Atan(d));          // Input negative zero        // Output positive zero        Console.WriteLine(Math.Atan(e));                  // input PositiveInfinity        // Output 1.5707963267949        Console.WriteLine(Math.Atan(posi));                  // input NegativeInfinity        // Output -1.5707963267949        Console.WriteLine(Math.Atan(nega));                  // input NaN        // Output NaN        Console.WriteLine(Math.Atan(nan));    }}
1.26262725567891
0.785398163397448
0
0
1.5707963267949
-1.5707963267949
NaN

Reference: https://msdn.microsoft.com/en-us/library/system.math.atan
CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Lambda Expressions in C#
CakePHP - Views

The letter “V” in the MVC is for Views. Views are responsible for sending output to user based on request. View Classes is a powerful way to speed up the development process.
The View Templates file of CakePHP gets data from controller and then render the output so that it can be displayed properly to the user. We can use variables, various control structures in template.
Template files are stored in src/Template/, in a directory named after the controller that uses the files, and named after the action it corresponds to. For example, the Viewfile for the Products controller’s “view()” action, would normally be found in src/Template/Products/view.php.
In short, the name of the controller (ProductsController) is same as the name of the folder (Products) but without the word Controller and name of action/method (view()) of the controller (ProductsController) is same as the name of the View file(view.php).
View variables are variables which get the value from controller. We can use as many variables in view templates as we want. We can use the set() method to pass values to variables in views. These set variables will be available in both the view and the layout your action renders. The following is the syntax of the set() method.
Cake\View\View::set(string $var, mixed $value)
This method takes two arguments − the name of the variable and its value.
Make Changes in the config/routes.php file as shown in the following program.
config/routes.php
<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   // Register scoped middleware for in scopes.
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   $builder->connect('template',['controller'=>'Products','action'=>'view']);
   $builder->fallbacks();
});
Create a ProductsController.php file at src/Controller/ProductsController.php. Copy the following code in the controller file.
src/Controller/ProductsController.php
<?php
declare(strict_types=1);
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Http\Exception\ForbiddenException;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response;
use Cake\View\Exception\MissingTemplateException;
class ProductsController extends AppController {
public function view(){
      $this->set('Product_Name','XYZ');
   }
}
Create a directory Products at src/Template and under that folder create a View file called view.php. Copy the following code in that file.
Value of variable is: <?php echo $Product_Name; ? >

Execute the above example by visiting the following URL.
http://localhost/cakephp4/template
The above URL will produce the following output.
 Print
 Add Notes
 Bookmark this page