code-rag-bench/online-tutorials huggingface dataset:
pandas.crosstab() function in Python - GeeksforGeeks

14 Aug, 2020
This method is used to compute a simple cross-tabulation of two (or more) factors. By default, computes a frequency table of the factors unless an array of values and an aggregation function are passed.
Syntax: pandas.crosstab(index, columns, values=None, rownames=None, colnames=None, aggfunc=None, margins=False, margins_name=’All’, dropna=True, normalize=False)
Arguments :
index : array-like, Series, or list of arrays/Series, Values to group by in the rows.
columns : array-like, Series, or list of arrays/Series, Values to group by in the columns.
values : array-like, optional, array of values to aggregate according to the factors. Requires `aggfunc` be specified.
rownames : sequence, default None, If passed, must match number of row arrays passed.
colnames : sequence, default None, If passed, must match number of column arrays passed.
aggfunc : function, optional, If specified, requires `values` be specified as well.
margins : bool, default False, Add row/column margins (subtotals).
margins_name : str, default ‘All’, Name of the row/column that will contain the totals when margins is True.
dropna : bool, default True, Do not include columns whose entries are all NaN.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packagesimport pandasimport numpy  # creating some dataa = numpy.array(["foo", "foo", "foo", "foo",                 "bar", "bar", "bar", "bar",                 "foo", "foo", "foo"],                dtype=object)  b = numpy.array(["one", "one", "one", "two",                 "one", "one", "one", "two",                 "two", "two", "one"],                dtype=object)  c = numpy.array(["dull", "dull", "shiny",                 "dull", "dull", "shiny",                 "shiny", "dull", "shiny",                 "shiny", "shiny"],                dtype=object)  # form the cross tabpandas.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])
Output :
Example 2 :
Python3
# importing packageimport pandas  # create some datafoo = pandas.Categorical(['a', 'b'],                          categories=['a', 'b', 'c'])  bar = pandas.Categorical(['d', 'e'],                          categories=['d', 'e', 'f'])  # form crosstab with dropna=True (default)pandas.crosstab(foo, bar)  # form crosstab with dropna=Falsepandas.crosstab(foo, bar, dropna=False)
Output :
Python pandas-categorical
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
bin() in Python

The bin() function converts a decimal to binary. You can use a positive or negative integer as the parameter to be converted.
Below is the syntax of the function.
bin(n)
Parameters : an integer to convert
Return Value : A binary string of an integer or int object.
Exceptions : Raises TypeError when a float value is sent as argument.
In the below example we convert a positive and a negative integer to binary. The results come out with a prefix of 0b to indicate that the number is a binary representation.
n = input("Enter an integer :")
dec_number = int(n)
bin_number = bin(dec_number)
print(bin_number)
Running the above code gives us the following result −
Write the code result here.
Result
Enter an integer :23
0b10111
Enter an integer :-31
-0b11111
If we do not want the 0b prefix in front of the converted number, then we need to apply string function to remove the initial 2 characters.
n = input("Enter an integer :")
dec_number = int(n)
bin_number = bin(dec_number)
print(type(bin_number))
x = bin_number[2:]
print(x)
Running the above code gives us the following result −
Enter an integer :13

1101
p5.js | noStroke() Function

24 Oct, 2018
The noStroke() function is an inbuilt function in p5.js which is used to remove the outline which is used to draw lines and borders around shapes. By default, black color stroke is set to shapes.
Syntax:
noStroke()
Parameters: This function does not accepts any parameter.
Below program illustrates the noStroke() function in P5.js:Program:
function setup() {      // Canvas size 400*400    createCanvas(400, 400); }  function draw() {      // Shape defined just below, will not have any outline    noStroke();       // Fill light-green color to shape    fill('lightgreen');     rect(20, 20, 160, 160);}
Output:
Reference: https://p5js.org/reference/#/p5/noStroke
JavaScript-p5.js
Technical Scripter 2018
JavaScript
Technical Scripter
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Lexical Scoping vs Dynamic Scoping in R Programming

03 Sep, 2021
R is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge tool. Scoping Rules of a language are responsible for determining how value will be associated with the free variable in a function in the R language. 
In Lexical Scoping the scope of the variable is determined by the textual structure of a program. Most programming languages we use today are lexically scoped. Even, a human can determine the scope of a variable just by properly reading the code. Below is a code of lexical Scoping in R. 
Python3
# R program to depict scoping # Assign a value to aa <- 1 # Defining function b and cb <- function() ac <- function(){  a <- 2  b()} # Call to function cc()
Output: 
 1 
In this example, first, a mapping for a is created. In the next line a function b is defined which returns the value of some a. On line 3, we define a function c, which creates a new mapping for a and then calls b. Note that the assignment on line 4 does not update the definition on line 1 and in the Output value, 1 is returned. 
In Dynamic scoping, the variable takes the value of the most latest value assigned to that variable Here, Considering the same above example.  
Python3
# R program to depict scoping # Assign a value to aa <- 1 # Defining function b and cb <- function() ac <- function(){  a <- 2  b()} # Call to function cc()
Output: 
 1 
The output of this code should be 2 according to the rules of Dynamic as the latest value assigned to the variable a is 2. 
Sometimes, in R Language code can give the appearance of dynamic Scoping which happens when a function is defined in the global environment and also called from the global environment, resulting in the same environment for defining and calling the environment which can be depicted in the example given below. 
Python3
# R program to depict scoping # Assign a value to aa <- 10 # Defining function ff <- function(x) {  a <- 2  a ^ 2 + g(x)} # Defining function gg <- function(x) {  x * a} # Call to function ff(3)
Output: 
 34 
In this example, g is looked up in the environment in which it is defined and hence the value of a is 10. With dynamic scoping, the value of a variable is looked up in the environment in which it is called. In R that environment is known as the parent environment so in function f the value of a will be 2 whereas in g the value will be 10. This may create an illusion of R language being a dynamic language but in reality, it turns out to be Lexical Scope language. Below are some differences between the lexical and dynamic scoping in R programming.
 
abhishek0719kadiyan
sweetyty
Picked
R-Variables
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCS Placement Paper | Email Writing Question 6

21 May, 2019
Pre-requisite: Procedure to E-mail WritingThis is a TCS model placement email-writing question. It covers the important directions along with a sample solution to the question.
Directions:
Use all the phrases given.Minimum words should be 50 otherwise your email cannot be validated.Addressing and signing should be done as in the question given.Common grammatical rules, punctuation should be according to standard English.You can use your own phrases along with the phrases given.
Use all the phrases given.
Minimum words should be 50 otherwise your email cannot be validated.
Addressing and signing should be done as in the question given.
Common grammatical rules, punctuation should be according to standard English.
You can use your own phrases along with the phrases given.
Question:As a student representative of your college, write an email to the Principal of Professional Engineering College, Prof.Sanjib Chatterjee, inviting his institute to participate in the Technical symposium being organized in your college. Sign the email as Arun.
Phrases:
Invite - technical Symposium - previous - success - expecting - huge participation - 
latest technology - stalls - demos - interaction - topics - complete - exchange ideas - 
exciting prizes.

Solution – Sample E-mail:
Dear Prof Chatterjee,
As a student representative of our college, I would like to invite your institute into the technical Symposium that is about to be held in our college next Sunday. Many eminent personalities would be visiting the Symposium just like the previous years. We are planning for a huge success this year too and are expecting a huge participation from your esteemed institution. The symposium would introduce to the mass about the latest technologies, followed by stalls set up to show demos on Science projects. It would be a great platform for interaction on some interesting topics with some of the eminent personalities. Participants can complete their registrations before the upcoming Sunday.
It is a great opportunity to exchange ideas and win exciting prizes. Looking forward to a great participation.
Thanks and regards,Arun.
Note: You can write your own versions of e-mail keeping in mind the points needed to be taken care of while an e-mail. Refer Procedure to E-mail Writing.
interview-preparation
placement preparation
TCS
Placements
TCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 20 Puzzles Commonly Asked During SDE Interviews
Must Do Questions for Companies like TCS, CTS, HCL, IBM ...
Work and Wages
Programming Language For Placement - C++, Java or Python?
Permutation and Combination
Cognizant Placement Paper | Aptitude Set 1
Print the longest path from root to leaf in a Binary tree
Time Speed Distance
How to Prepare for HR Interviews
SimpleScriptContext setAttribute() method in Java with Examples

29 Jan, 2020
The setAttribute() method of a SimpleScriptContext class is used to set the value of an attribute in a given scope where the name of the attribute, the value of attribute and scope of the attribute is passed as parameters. If the scope is GLOBAL_SCOPE and there are no Bindings is set for GLOBAL_SCOPE, then setAttribute call is a no-op.
Syntax:
public void setAttribute(String name,
       Object value, int scope)

Parameters: This method accepts three-parameters:
name which is the Name of the attribute to set,
value which is the value of the attribute and
scope which is the scope in which to set the attribute.
Return value: This method returns nothing.
Exceptions: This method throws following Exceptions:
NullPointerException: if the name is null.
IllegalArgumentException: if the name is empty or if the scope is invalid.
Below programs illustrate the SimpleScriptContext.setAttribute() method:Program 1:
// Java program to demonstrate// SimpleScriptContext.setAttribute() method  import javax.script.ScriptContext;import javax.script.SimpleScriptContext;  public class GFG {    public static void main(String[] args)    {          // create SimpleScriptContext object        SimpleScriptContext simple            = new SimpleScriptContext();          // add some attribute using setAttribute()        simple.setAttribute(            "name1", "Value1",            ScriptContext.ENGINE_SCOPE);          // print        System.out.println("name1:"                           + simple.getAttribute("name1"));    }}
name1:Value1

Program 2:
// Java program to demonstrate// SimpleScriptContext.setAttribute() method  import javax.script.ScriptContext;import javax.script.SimpleScriptContext;  public class GFG {    public static void main(String[] args)    {          // create SimpleScriptContext object        SimpleScriptContext simple            = new SimpleScriptContext();          // add some attribute using setAttribute()        simple.setAttribute("Team1", "India",                            ScriptContext.ENGINE_SCOPE);        simple.setAttribute("Team2", "Japan",                            ScriptContext.ENGINE_SCOPE);        simple.setAttribute("Team3", "Nepal",                            ScriptContext.ENGINE_SCOPE);          // print        System.out.println("Team1:"                           + simple.getAttribute("Team1"));        System.out.println("Team2:"                           + simple.getAttribute("Team2"));        System.out.println("Team3:"                           + simple.getAttribute("Team3"));    }}
Team1:India
Team2:Japan
Team3:Nepal

References: https://docs.oracle.com/javase/10/docs/api/javax/script/SimpleScriptContext.html#setAttribute(java.lang.String, java.lang.Object, int)
Java-Functions
Java-SimpleScriptContext
javax.script package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
Initializing a List in Java
Introduction to Java
Draw Multiple Function Curves to Same Plot in R

30 May, 2021
In this article, we will discuss how to plot multiple function curves to the same plot in the R programming language.
Base R supports a function curve() which can be used to visualize a required function curve. It supports various parameters to edit the curve according to requirements.
Syntax: curve(expression, to, from, col)
Parameters:
expression: To be curved
to, from: range of curve plotting
col: color of curve
To draw multiple curves in one plot, different functions are created separately and the curve() function is called repeatedly for each curve function. The call for every other curve() function except for the first one should have added an attribute set to TRUE so that multiple curves can be added to the same plot. To differentiate among the different colors are used.
Example:
R
function1<- function(x){x ** 2}function2<-function(x){x ** 3}function3<-function(x){x / 2}function4<-function(x){2*(x ** 3)+(x ** 2)-(x / 2)}  curve(function1, col = 1)curve(function2, col = 2, add = TRUE)curve(function3, col = 3, add = TRUE)curve(function4, col = 4, add = TRUE)
Output:
GGPLOT2 is an R library used to visualize plots with its various easy-to-use functions. To draw multiple curves using gglot functions are first created normally. But to draw them in the same plot, the functions are converted to dataframe and then visualized. 
Example:
R
library("ggplot2")function1<- function(x){x ** 2}function2<-function(x){x ** 3}function3<-function(x){x / 2}function4<-function(x){2*(x ** 3)+(x ** 2)-(x / 2)}  df=data.frame(x = -2 : 2,              values = c(function1(-2 : 2),                       function2(-2 : 2),                       function3(-2 : 2),                       function4(-2 : 2)),              fun = rep(c("function1", "function2",                          "function3", "function4"))              )  ggplot(df, aes(x, values, col = fun))+geom_line()
Output:
Picked
R-Charts
R-ggplot
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.astype() to convert Data type of series

01 Oct, 2018
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 astype() is the one of the most important methods. It is used to change data type of a series. When data frame is made from a csv file, the columns are imported and data type is set automatically which many times is not what it actually should have. For example, a salary column could be imported as string but to do operations we have to convert it into float.astype() is used to do such data type conversions.
Syntax: DataFrame.astype(dtype, copy=True, errors=’raise’)
Parameters:dtype: Data type to convert the series into. (for example str, float, int)copy: Makes a copy of dataframe/series.errors: Error raising on conversion to invalid data type. For example dict to string. ‘raise’ will raise the error and ‘ignore’ will pass without raising error.
Return type: Series with changed data types
To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example:In this example, the data frame is imported and .dtypes is called on the data frame to view the data types of series. After that some columns are converted using .astype() method and the dtypes are viewed again to see the changes.
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   # dropping null value columns to avoid errorsdata.dropna(inplace = True)  # storing dtype before convertingbefore = data.dtypes  # converting dtypes using astypedata["Salary"]= data["Salary"].astype(int)data["Number"]= data["Number"].astype(str)  # storing dtype after convertingafter = data.dtypes  # printing to compareprint("BEFORE CONVERSION\n", before, "\n")print("AFTER CONVERSION\n", after, "\n")
Output:As shown in the output image, the data types of columns were converted accordingly.
golesarpavan
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.
Python | os.getppid() method

22 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.getppid() method in Python is used to get the parent process ID of the current process.
Syntax: os.getppid()
Parameter: Not required
Return Type: This method returns a integer value denoting the parent process ID of the current process. The return type of this method is of class ‘int’.
Code #1: Use of os.getppid() method
# Python program to explain os.getppid() method   # importing os module import os  # Get the Parent process ID # of the current processppid = os.getppid()  # Print the Parent process ID # of the current processprint("Parent Process ID of current process:", ppid)
Parent process ID of current process: 7653

 
Code #2: Use of os.getppid() method
# Python program to explain os.getppid() method   # importing os module import os    # Check the process ID # of the current processpid = os.getpid()print("Process ID of Current process:", pid)    # Create a child processtry:    pid = os.fork()except OSError:    exit("Could not create a child process")    # In the child process # Check its Parent process ID# os.getppid() will return # the process ID of its parent processif pid == 0:     parent = os.getppid()     print("Parent process ID of child process:", parent)
Process ID of Current process: 7653
Parent process ID of child process: 7653

python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Title Case a sentence in JavaScript?

It is nothing but converting first element of all the words in a sentence in to uppercase while the other elements remain in lowercase. The provided string(sentence) may contains a bunch of lowercase and uppercase elements. So we need an algorithm to Title Case the provided string.
Divide all the words in the sentence individually. This task can be achieved by using string.split() method.
Convert all the elements in each and every word in to lowercase using string.toLowerCase() method. 
Loop through first elements of all the words using for loop and convert them in to uppercase. After converting, concatenate them with the remaining elements of their respective word, leading to a original word with first element in upper case. 
Join all the words using String.join() with a space between them so as to convert it in to its original string but title cased.
<html>
<body>
<script>
   function titleCase(string) {
      var sentence = string.toLowerCase().split(" ");
      for(var i = 0; i< sentence.length; i++){
         sentence[i] = sentence[i][0].toUpperCase() + sentence[i].slice(1);
      }
   document.write(sentence.join(" "));
   return sentence;
   }
   titleCase("tutorix is one of best e-platforms");
</script>
</body>
</html>
Tutorix Is One Of Best E-platforms
Python Program to find transpose of a matrix

23 Jun, 2022
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]. 
For Square Matrix: The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension. 
Python3
# Python3 Program to find# transpose of a matrix N = 4 # This function stores# transpose of A[][] in B[][] def transpose(A,B):  for i in range(N):  for j in range(N):   B[i][j] = A[j][i] # driver codeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]  B = A[:][:] # To store result transpose(A, B) print("Result matrix is")for i in range(N): for j in range(N):  print(B[i][j], " ", end='') print()  # This code is contributed by Anant Agarwal.
Result matrix is
1  2  3  4  
2  2  3  4  
3  3  3  4  
4  4  4  4
Time Complexity: O(n2)Auxiliary Space: O(n2)
For Rectangular Matrix: The below program finds transpose of A[][] and stores the result in B[][]. 
Python3
# Python3 Program to find# transpose of a matrix M = 3N = 4 # This function stores# transpose of A[][] in B[][] def transpose(A, B):  for i in range(N):  for j in range(M):   B[i][j] = A[j][i] # driver codeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]  # To store resultB = [[0 for x in range(M)] for y in range(N)] transpose(A, B) print("Result matrix is")for i in range(N): for j in range(M):  print(B[i][j], " ", end='') print() 
Result matrix is
1  2  3  
1  2  3  
1  2  3  
1  2  3
Time Complexity: O(n*m)Auxiliary Space: O(n*m)
In-Place for Square Matrix:
Python3
# Python3 Program to find# transpose of a matrix N = 4 # Finds transpose of A[][] in-placedef transpose(A):  for i in range(N):  for j in range(i+1, N):   A[i][j], A[j][i] = A[j][i], A[i][j] # driver codeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] transpose(A) print("Modified matrix is")for i in range(N): for j in range(N):  print(A[i][j], " ", end='') print()  # This code is contributed by Anant Agarwal.
Modified matrix is
1  2  3  4  
1  2  3  4  
1  2  3  4  
1  2  3  4
Time Complexity: O(n2)Auxiliary Space: O(1)
Please refer complete article on Program to find transpose of a matrix for more details!
chandramauliguptach
hardikkoriintern
Python matrix-program
Matrix
Python Programs
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unique paths in a Grid with Obstacles
Find median in row wise sorted matrix
Traverse a given Matrix using Recursion
Zigzag (or diagonal) traversal of Matrix
A Boolean Matrix Question
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
numpy.triu() in Python

09 Mar, 2022
numpy.triu(a, k = 0) : Returns copy of array with upper part of the triangle w.r.t kParameters :
a : input array
k : [int, optional, 0 by default]
          Diagonal we require; k>0 means diagonal above main diagonal or vice versa.

Returns :
Upper triangle of a, having same shape and data-type as a.
# Python Programming illustrating# numpy. triu method  import numpy as geek  # string inputa = geek.matrix([[1, 21, 30],                  [63 ,434, 3],                  [54, 54, 56]])  print("Main Diagonal elements : \n", geek. triu(a), "\n")  print("Diagonal above main Diagonal elements : \n", geek. triu(a, 1), "\n\n")  print("Main Diagonal elements : \n", geek. triu(a, -1))
Output :
Main Diagonal elements : 
 [[  1  21  30]
 [  0 434   3]
 [  0   0  56]] 

Diagonal above main Diagonal elements : 
 [[ 0 21 30]
 [ 0  0  3]
 [ 0  0  0]] 


Main Diagonal elements : 
 [[  1  21  30]
 [ 63 434   3]
 [  0  54  56]]

Reference :https://docs.scipy.org/doc/numpy/reference/generated/numpy.triu.html#numpy.triuNote :These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore them.
This article is contributed by Mohit Gupta_OMG . 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.
vinayedula
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Python | Sum values for each key in nested dictionary

14 May, 2020
Given a nested dictionary and we have to find sum of particular value in that nested dictionary. This is basically useful in cases where we are given a JSON object or we have scraped a particular page and we want to sum the value of a particular attribute in objects.
Code #1: Find sum of sharpness values using sum() function
# Python code to find sum values within nested dictionariesweapons = {'': None, 'sword': { 'steel': 151,                                'sharpness': 100,                                'age': 2,},                                                       'arrow': {'steel': 120,                               'sharpness': 205,                               'age': 1,}}                                 sumValue1 = sum(d['sharpness'] for d in weapons.values() if d)sumValue2 = sum(d['steel'] for d in weapons.values() if d)  print(sumValue1)print(sumValue2)
305
271

 
Code #2 : Using Iteration to convert it into key:value pair.
# Python code to find sum values within nested dictionaries  weapons = {'': None, 'sword': { 'steel': 151,                                'sharpness': 100,                                'age': 2,},                                                       'arrow': {'steel': 120,                               'sharpness': 205,                               'age': 1,}}                                 sum = 0  # iterating key value pairfor key ,value in weapons.items():      if value and 'sharpness' in value.keys():        # Adding value of sharpness to sum        sum += value['sharpness']   # printing sumprint(sum)
305

Python dictionary-programs
python-dict
Python-nested-dictionary
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python program to find uncommon words from two Strings

21 Aug, 2020
Given two sentences as strings A and B. The task is to return a list of all uncommon words. A word is uncommon if it appears exactly once in any one of the sentences, and does not appear in the other sentence.
Note: A sentence is a string of space-separated words. Each word consists only of lowercase letters.
Examples:
Input : A = "Geeks for Geeks" 
        B = "Learning from Geeks for Geeks"
Output : ['Learning', 'from']

Input : A = "apple banana mango" 
        B = "banana fruits mango"
Output : ['apple', 'fruits']

Approach: Every uncommon word occurs exactly once in any one of the strings. So, we make a hash to count the number of occurrences of every word, then return a list of words that occurs exactly once.
Below is the implementation of the above approach:
# Python3 program to find a list of uncommon words  # Function to return all uncommon wordsdef UncommonWords(A, B):      # count will contain all the word counts    count = {}          # insert words of string A to hash    for word in A.split():        count[word] = count.get(word, 0) + 1          # insert words of string B to hash    for word in B.split():        count[word] = count.get(word, 0) + 1      # return required list of words    return [word for word in count if count[word] == 1]  # Driver CodeA = "Geeks for Geeks"B = "Learning from Geeks for Geeks"  # Print required answerprint(UncommonWords(A, B))
['from', 'Learning']

Another way to solve this problem:
def uncommon(a,b):    list_a = a.split()    list_b = b.split()    uc = ''    for i in list_a:        if i not in list_b:            uc = uc+" "+i    for j in list_b:        if j not in list_a:            uc = uc+" "+j      return uc  # Driver codea = "apple banana mango"b = "banana fruits mango"print(uncommon(a,b))
['apple','fruits']

Also another way-using in-built function “symmetric_difference()”
def uncommon(a,b):  a=a.split()  b=b.split()  k=set(a).symmetric_difference(set(b))  return k  #Driver codeif __name__=="__main__":  a="apple banana mango"   b="banana fruits mango"  print(list(uncommon(a,b)))
['apple', 'fruits']

Another way to solve this problem
def uncommon(A, B):    un_comm = [i for i in "".join(B).split() if i not in "".join(A).split()]    return un_comm  #Driver codeA = "Geeks for Geeks" B = "Learning from Geeks for Geeks"print(uncommon(A, B))
['Learning', 'from']

kunchamaparna509
chauhansumit
harshithakotturi
datapirate98
Pattern Searching
Python Programs
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search a Word in a 2D Grid of characters
Count of number of given string in 2D character array
Wildcard Pattern Matching
Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1
Applications of String Matching Algorithms
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Iterate over characters of a string in Python
Python | Convert set into a list
What is Zed Attack Proxy?

14 Jun, 2022
Zed Attack Proxy is an open-source security software written in Java programming language and released in 2010. It is used to scan web applications and find vulnerabilities in it. It was started as a small project by the Open Web Application Security Project (OWASP) and now it is the most active project maintained by thousands of individuals around the globe. It is available for Linux, Windows, and mac in 29 languages. It can also be used as a proxy server like a burp suite to manipulate the request including the HTTPS request. Daemon mode is also present in it which can later be controlled by REST API. 
Features:
Passive Scanner
Automated Scanner
Proxy Server
Port Identification
Directory Searching
Brute Force Attack
Web Crawler
Fuzzer
Why do we use Zed Attack Proxy? Zed Attack Proxy is used to detect vulnerabilities present on any web server and try to remove them. Here is some big vulnerability that could be present in the web server:
SQL injection
Cross-site scripting (XSS)
Broken access control
Security miss-configuration
Broken authentication
Sensitive data exposure
Cross-site request forgery (CSRF)
Using components with known vulnerabilities.
Some Important Terminologies:
Proxy Server: It is a server that acts as a mediator for clients who want to go through the request and want to alter them.
Spider: It is a type of information gathering process in which the application in this case ZAP will go through the whole web page and try to find out all the links and other important details.
Passive Scan: In this type of scanning the vulnerability is detected without getting in direct contact with the target machine.
Active Scan: In this, the vulnerability is detected by getting in direct contact with the target machine which makes it very easy to be detected by the administrator.
Working Process: First we set up the proxy server with any browser. The browser sends website data to the proxy server and then the browser inside the ZAP process the request and perform attacks and generates the report.  
Configuration Steps:
Step 1: Download ZAP from https://www.zaproxy.org/download/ by selecting the proper operating system.
Step 2: Run the file and follow the instruction until the installation is complete.
Steps to Run:
Step 1: Open the application through the terminal or by clicking on the icon.
Step 2: In the next step, select the first option and click start. 
Step 3: Now choose a target to scan and enter its web address in the green highlighted box and click attack. 
Step 4: Now you will have to wait for a few minutes to get the result.
harshmaster07705
Cyber-security
Network-security
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of URL

27 Nov, 2020
URL stands for Uniform Resource Locator. Any internet location available on server is called a web URL, web address or website. Each website or webpage has a unique address called URL. e.g., the website of geeksforgeeks website has an address or URL called https://www.geeksforgeeks.org/
type: It specifies the type of the server in which the file is located.
address: It specifies the address or location of the internet server.
path: It specifies the location of the file on the internet server.
Types of URL: URL gives the address of files created for webpages or other documents like an image, pdf for a doc file, etc.
There are two types of URL:
Absolute URL
Relative URL
Absolute URL: This type of URL contains both the domain name and directory/page path. An absolute URL gives complete location information. It begins with a protocol like “http://” and continues, including every detail. An absolute URL typically comes with the following syntax.
protocol://domain/path
For web browsing, absolute URL’s are types in the address bar of a web browser. For example, if it is related to our project page link of geeksforgeeks website, the URL should be mentioned as https://www.geeksforgeeks.org/computer-science-projects/ this gives the complete information about the file location path.
Note: The protocol may be of following types.
http://, https://, ftp://, gopher://, etc.
Relative URL: This type of URL contains the path excluding the domain name. Relative means “in relation to”, and a relative URL tells a URL location on terms of the current location. Relative path is used for reference to a given link of a file that exist within the same domain.
Let us assume a web developer setting up a webpage and want to link an image called “geeksforgeeks.jpg”.
<img src="geeksforgeeks.jpg">
It would internally be interpreted like the following.
<img src="./geeksforgeeks.jpg">
The dot(.) before the “/” in the src attribute is a “special character”. It means the location should be started from the current directory to find the file location.
HTML-Misc
Technical Scripter 2020
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2000 | Question 47

28 Jun, 2021
Given the following relation instance.
x  y  z
1  4  2
1  5  3
1  6  3
3  2  2  
Which of the following functional dependencies are satisfied by the instance? (GATE CS 2000)(A) XY -> Z and Z -> Y(B) YZ -> X and Y -> Z(C) YZ -> X and X -> Z(D) XZ -> Y and Y -> XAnswer: (B)Explanation: See question 2 of https://www.geeksforgeeks.org/database-management-system-set-1/Quiz of this Question
GATE-CS-2000
GATE-GATE-CS-2000
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
GATE | GATE-CS-2016 (Set 1) | Question 45
GATE | GATE CS 1996 | Question 63
What is an event loop in JavaScript ?

06 Oct, 2021
JavaScript is a single-threaded synchronous programming language. But what does it actually mean? What is this event loop in JavaScript that we all keep talking about? 
What does it actually mean when we say JavaScript is single threaded?
It means that the main thread where JavaScript code is run, runs in one line at a time manner and there is no possibility of running code in parallel.
Example:
Javascript
console.log("Before delay");  function delayBySeconds(sec) {   let start = now = Date.now()   while(now-start < (sec*1000)) {     now = Date.now();   }}  delayBySeconds(5);  // Executes after delay of 5 secondsconsole.log("After delay");
Output:
Before delay
(... waits for 5 seconds)
After delay
Memory allocation in JavaScript:
1) Heap memory: Data stored randomly and memory allocated.
2) Stack memory: Memory allocated in the form of stacks. Mainly used for functions.
Function call stack: The function stack is a function which keeps track of all other functions executed in run time. Ever seen a stack trace being printed when you ran into an error in JavaScript. That is nothing but a snapshot of the function stack at that point when the error occurred.
Example:
Javascript
function LevelTwo() {   console.log("Inside Level Two!")}  function LevelOne() {   LevelTwo()}  function main() {   LevelOne()}  main()
Order at which functions get executed i.e get popped out of the stack after a function’s purpose gets over as shown below:
Event loop: An event loop is something that pulls stuff out of the queue and places it onto the function execution stack whenever the function stack becomes empty.
The event loop is the secret by which JavaScript gives us an illusion of being multithreaded even though it is single-threaded. The below illusion demonstrates the functioning of event loop well:
Here the callback function in the event queue has not yet run and is waiting for its time into the stack when the SetTimeOut() is being executed and the Web API is making the mentioned wait. When the function stack becomes empty, the function gets loaded onto the stack as shown below:
That is where the event loop comes into picture, it takes the first event from the Event Queue and places it onto the stack i.e in this case the callback function. From here, this function executes calling other functions inside it, if any.
This cycle is called the event loop and this how JavaScript manages its events.
uppala0863
javascript-basics
JavaScript-Misc
Picked
Technical Scripter 2020
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the difference between echo, print, and print_r in PHP?

12 Dec, 2018
echo: echo is not a function rather it is described as a language construct. It accepts an list of argument (multiple arguments can be passed) and returns no value or returns void. It cannot be used as a variable function in PHP. It is used to display the output of parameters that is passed to it. It display the outputs one or more strings separated by commas.
Example:
<?php  // PHP program to illustrate echo  // Declare variable and initialize it.$x = "GeeksforGeeks ";$y = "Computer science portal";  // Display the value of $xecho $x, $y;?>
GeeksforGeeks Computer science portal

print: It is not a real function. it is a language construct but always returns the value 1. So it can be used as an expression. Unlike echo, print accepts only one argument at a time. It cannot be used as a variable function in PHP. The print outputs only the strings. It is slow compared to that of echo.Example:
<?php  // PHP program to illustrate echo  // Declare variable and initialize it.$x = "GeeksforGeeks";  // Display the value of $xprint $x;?>
GeeksforGeeks

print_r(): print_r() is a regular function. It outputs the detailed information about the parameter in a format with its type (of an array or an object), which can be easily understandable by humans. In this function the output get stored on the internal buffer when the return parameter is passed. If pass the return parameter to TRUE, print_r() would return the complete information rather than just print it. During walk-through this function helps in identifying any of the glitches while executing the program. It is more similar to the var_dump() function.Example:
<?php  // PHP program to illustrate echo  // Declare an array$arr = array('0' => "GeeksforGeeks",             '1' => "Computer",              '2' => "Science",             '3' => "Portal");  // Display the value of $xprint_r($arr);?>
Array
(
    [0] => GeeksforGeeks
    [1] => Computer
    [2] => Science
    [3] => Portal
)

Example:
<?php  $a = "GeeksforGeeks";$b = array('0' => "Geeks", '1' => "for", '2' => "Geeks");$c = 3.14;$d = 7;  // Single argumentprint "\n$a\n";  // Multiple argumentecho $c + $d . "\n";  // Return with internal output bufferingprint_r($b);?>
GeeksforGeeks
10.14
Array
(
    [0] => Geeks
    [1] => for
    [2] => Geeks
)

Picked
Technical Scripter 2018
PHP
PHP Programs
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Comparing two dates in PHP
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
How do I center the text in a Tkinter Text widget?

Tkinter text widget is a multiline text input widget. It is used to insert, delete, and add textual data in the input field. It provides many built-in functions and attributes in its widget class.
To configure and align the text at the CENTER of a Tkinter Text widget, we can use justify=CENTER property.
# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

text=Text(win)

# Configure the alignment of the text
text.tag_configure("tag_name", justify='center')

# Insert a Demo Text
text.insert("1.0", "How do I center align the text " "in a Tkinter Text widget?")

# Add the tag in the given text
text.tag_add("tag_name", "1.0", "end")
text.pack()

win.mainloop()
Run the above code to display a window with a sample text placed at the center of the Text widget.
How to control the border of a bar patch in matplotlib?

To control the border of a bar patch in matplotlib, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a list of heights and a tuple for labels.
Create a list of heights and a tuple for labels.
Use the bar() method with edgecolor in the argument to control the color of the bar patch. Here we have used edgecolor='green'.
Use the bar() method with edgecolor in the argument to control the color of the bar patch. Here we have used edgecolor='green'.
Set the ticks and labels of the X-axis.
Set the ticks and labels of the X-axis.
To display the figure, use Show() method.
To display the figure, use Show() method.
import numpy as np
import matplotlib.pyplot as plt

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

height = [3, 12, 5, 18, 45]
labels = ('P1', 'P2', 'P3', 'P4', 'P5')

x_pos = np.arange(len(labels))

plt.bar(x_pos, height, color=(0.9, 0.7, 0.1, 0.5), edgecolor='green')
plt.xticks(x_pos, labels)

plt.show()

It will produce the following output −
You can change the width of the borders by introducing the linewidth parameter in the bar() method. Suppose we take linewidth=5, then It will produce the following output −
What is the importance of a Cursor class in Java?

A Cursor is a subclass of Object class and it can be defined as point or indicator on the screen. A Cursor is used to select the input from the system that the user operates with the mouse. Different types of cursors available in the Cursor class are DEFAULT_CURSOR, CROSSHAIR_CURSOR, HAND_CURSOR, TEXT_CURSOR, WAIT_CURSOR and etc. The important methods of Cursor class are getDefaultCursor(), getName(), getPredefinedCursor(), getSystemCustomCursor() and getType().
import java.awt.*;
import javax.swing.*;
public class CursorTest extends JFrame {
   public CursorTest() {
      setTitle("Cursor Test");
      Cursor cursor = new Cursor(Cursor.HAND_CURSOR); // HAND CURSOR
      setCursor(cursor);
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new CursorTest();
   }
}
Tryit Editor v3.7

Tryit: HTML empty canvas
How to create a thread by using anonymous class in Java?

A Thread is a functionality which can be executed simultaneously with the other part of the program. All Java programs have at least one thread, known as the main thread, which is created by the Java Virtual Machine (JVM) at the program start when the main() method is invoked with the main thread.
In Java, we can create a thread by extending a Thread
class or by implementing the Runnable interface. We can also create a thread by using the anonymous class without extending a Thread class in the below program.
public class AnonymousThreadTest {
   public static void main(String[] args) {
      new Thread() {
         public void run() {
            for (int i=1; i <= 5; i++) {
               System.out.println("run() method: " + i);
            }
         }
      }.start();
      for (int j=1; j <= 5; j++) {
         System.out.println("main() method: " + j);
      }
   }
}
main() method: 1
run() method: 1
main() method: 2
run() method: 2
main() method: 3
run() method: 3
main() method: 4
run() method: 4
main() method: 5
run() method: 5