code-rag-bench/online-tutorials huggingface dataset:
Python Pandas - How to Sort MultiIndex at a specific level

To create a MultiIndex, use the from_arrays() method. However, to sort MultiIndex at a specific level, use the multiIndex.sortlevel() method in Pandas. Set the level as an argument.
At first, import the required libraries −
import pandas as pd
MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays:
arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob']]

The "names" parameter sets the names for each of the index levels. The from_arrays() is used to create a MultiIndex −
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
Sort MultiIndex. The specific level to sort is set as a parameter i.e. level 1 here −
print("\nSort MultiIndex at the requested level...\n",multiIndex.sortlevel(1))

Following is the code −
import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob']]

# The "names" parameter sets the names for each of the index levels
# The from_arrays() is used to create a MultiIndex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))

# display the MultiIndex
print("The Multi-index...\n",multiIndex)

# get the levels in MultiIndex
print("\nThe levels in Multi-index...\n",multiIndex.levels)

# Sort MultiIndex
# The specific level to sort is set as a parameter i.e. level 1 here
print("\nSort MultiIndex at the requested level...\n",multiIndex.sortlevel(1))
This will produce the following output −
The Multi-index...
MultiIndex([(2, 'Peter'),
            (4, 'Chris'),
            (3,  'Andy'),
            (1, 'Jacob')],
            names=['ranks', 'student'])

The levels in Multi-index...
   [[1, 2, 3, 4], ['Andy', 'Chris', 'Jacob', 'Peter']]

Sort MultiIndex at the requested level...
(MultiIndex([(3, 'Andy'),
             (4, 'Chris'),
             (1, 'Jacob'),
             (2, 'Peter')],
             names=['ranks', 'student']), array([2, 1, 3, 0], dtype=int64))
How to access a DOM element in React ? - GeeksforGeeks

19 Feb, 2021
In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method.
Creating Refs: Refs are created using React.createRef() and attached to React elements via the ref attribute. 
class App extends React.Component {
constructor(props) {
  super(props);
  //creating ref
  this.myRef= React.createRef();
}
render() {
//assigning ref
  return (
  <div >
  <input ref= {this.myRef } />
  </div>
  )
}
}
Accessing Refs: When we assign a ref to an element in the render, then we can access the element using the current attribute of the ref.
const element = this.myRef.current;
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.
Filename- App.js: Open App.js file situated inside an src folder edit it as:
Javascript
import React from 'react'  class App extends React.Component {      constructor(props) {        super(props);                 this.myRef = React.createRef();      }           handleClick = () => {                    this.myRef.current.value = "you clicked on button";    }        render() {      return (        <div>        <input ref = {this.myRef}/>          <button             onClick = {this.handleClick}          > click me </button>        </div>      );    }  }    export default App;
Output:
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to redirect to another page in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS setState()
Re-rendering Components in ReactJS
ReactJS defaultProps
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
Space format specifiers in Java

For format specifier, import the following package −
import java.util.Formatter;
Create a formatter object and set space format specifier −
Formatter f = new Formatter();
f.format("% d", -50);
System.out.println(f);
f = new Formatter();
f.format("% d", 90);
System.out.println(f);
f = new Formatter();
f.format("%10d", -50);
System.out.println(f);
f = new Formatter();
f.format("% 10d", 90);
System.out.println(f);
The following is an example displaying different forms of space format specifiers −
 Live Demo
import java.util.Formatter;
public class Demo {
   public static void main(String args[]) {
      Formatter f = new Formatter();
      f.format("% d", -50);
      System.out.println(f);
      f = new Formatter();
      f.format("% d", 90);
      System.out.println(f);
      f = new Formatter();
      f.format("%10d", -50);
      System.out.println(f);
      f = new Formatter();
      f.format("% 10d", 90);
      System.out.println(f);
      f = new Formatter();
      f.format("%12.2f", -7.598);
      System.out.println(f);
      f = new Formatter();
      f.format("% 12.3f", 90.87787);
      System.out.println(f); 
   }
}
-50
90
   -50
   90 
   -7.60
   90.878
C Program to count vowels, digits, spaces, consonants using the string concepts

An array of characters (or) collection of characters is called a string.
Refer the declaration given below −
char stringname [size];
For example − char a[50]; string of length 50 characters.
The initialization is as follows −
Using single character constant −
char a[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants −
char a[10] = "Hello":;
There is a control string “%s” used for accessing the string, till it encounters ‘\0’.
The logic used to count number of vowels is as follows −
if(string[i]=='a'||string[i]=='e'||string[i]=='i'||
   string[i]=='o'||string[i]=='u')//checking the char is vowel vowel=vowel+1;
The logic used to count number of digits is as follows −
if(string[i]=='0'||string[i]=='1'||string[i]=='2'||
string[i]=='3'||string[i]=='4'||string[i]=='5'||
string[i]=='6'||string[i]=='7'||string[i]=='8'||string[i]=='9')
digit=digit+1;
The logic used to count number of spaces is as follows −
if(string[i]==' ')
space=space+1;
Else, remaining all consonants.
Following is the C Program to count vowels, digits, spaces, consonants by using the string concepts −
 Live Demo
#include<stdio.h>
int main(){
   char string[50];
   int i,vowel=0,digit=0,space=0,consonant=0;
   printf("enter any string includes all types of characters:\n");
   gets(string);
   for(i=0;string[i]!='\0';i++){
      if(string[i]=='a'||string[i]=='e'||string[i]=='i'||
         string[i]=='o'||string[i]=='u')//checking the char is vowel vowel=vowel+1;
      else if(string[i]=='0'||string[i]=='1'||string[i]=='2'||
         string[i]=='3'||string[i]=='4'||string[i]=='5'||
         string[i]=='6'||string[i]=='7'||string[i]=='8'||string[i]=='9')
         digit=digit+1;
      else if(string[i]==' ')
         space=space+1;
      else
         consonant=consonant+1;
   }
   printf("vowel=%d\ndigit=%d\nspace=%d\nconsonant=%d\n",vowel,digit,space,consonant);
   return 0;
}
The output is given below −
enter any string includes all types of characters:
Tutorials Point 1234 C programming 2020
vowel=9
digit=8
space=5
consonant=17
Python 3 - String max() Method

The max() method returns the max alphabetical character from the string str.
Following is the syntax for max() method −
max(str)

str − This is the string from which max alphabetical character needs to be returned.
This method returns the max alphabetical character from the string str.
The following example shows the usage of max() method.
#!/usr/bin/python3

str = "this is a string example....really!!!"
print ("Max character: " + max(str))

str = "this is a string example....wow!!!"
print ("Max character: " + max(str))
When we run above program, it produces the following result −
Max character: y
Max character: x


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
MongoDB to fetch documents with $or Operator

The $or operator performs a logical OR operation on an array of two or more expressions. Let us create a collection with documents −
> db.demo674.insertOne({Name:"Chris",Age:21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f33604263e90dac943eb")
}
> db.demo674.insertOne({Name:"David",Age:23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f33c04263e90dac943ec")
}
> db.demo674.insertOne({Name:"Bob",Age:21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f34204263e90dac943ed")
}
> db.demo674.insertOne({Name:"John",Age:24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f34804263e90dac943ee")
}
Display all documents from a collection with the help of find() method −
> db.demo674.find();
This will produce the following output −
{ "_id" : ObjectId("5ea3f33604263e90dac943eb"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5ea3f33c04263e90dac943ec"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5ea3f34204263e90dac943ed"), "Name" : "Bob", "Age" : 21 }
{ "_id" : ObjectId("5ea3f34804263e90dac943ee"), "Name" : "John", "Age" : 24 }
Following is the query to fetch documents with $or operator −
> db.demo674.find({$or:[{Name:"David"},{Age:21}]});
This will produce the following output −
{ "_id" : ObjectId("5ea3f33604263e90dac943eb"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5ea3f33c04263e90dac943ec"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5ea3f34204263e90dac943ed"), "Name" : "Bob", "Age" : 21 }
Program for Decimal to Binary Conversion in C++

Given with a decimal number as an input, the task is to convert the given decimal number into a binary number.
Decimal number in computers is represented with base 10 and binary number is represented with base 2 as it has only two binary digits 0 and 1 whereas decimal numbers can be any numeric digit starting from 0 – 9.
To convert a decimal number into a binary number follow the given steps −
Firstly divide the given number with the base value of conversion number e.g. dividing 42 by 2 because we need to convert 42 into a binary numbers which have base 2 and then obtain a quotient and store it. If the remainder is 0 store the bit as 0 else 1.
Divide the obtained quotient with the base value of binary number which is 2 and keep storing the bits.
Keep doing right shift to the stored bits
Repeat the step until the remainder left indivisible
Given below is the pictorial representation of converting a decimal number into a binary number.
Input-: 42
   Divide the 42 with base 2 : 42 / 2 = 0 (remainder) 21(quotient)
   Divide quotient with base: 21 / 2 = 1(remainder) 10(quotient)
   Divide quotient with base: 10 / 2 = 0(remainder) 5(quotient)
   Divide quotient with base: 5 / 2 = 1(remainder) 2(quotient)
   Divide quotient with base: 2 / 2 = 0(remainder) 1(quotient)
   Now reverse the bits to obtain final value.
Output-: 101010
Start
Step 1-> declare function to convert decimal to binary
   int convert(int num)
   Loop For int i = 31 i >= 0 i—
      Set int k = num >> i
      If (k & 1)
         Print "1"
      End
      Else
         Print "0"
      End
   End
Step 2-> In main()
   Declare and set int num = 42
   Call convert(num)
Stop
 Live Demo
#include <iostream>
using namespace std;
//convert decimal to binary
int convert(int num) {
   for (int i = 31; i >= 0; i--) {
      int k = num >> i;
      if (k & 1)
         cout << "1";
      else
         cout << "0";
   }
}
int main() {
   int num = 42;
   convert(num);
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
00000000000000000000000000101010
Checking all tables and schema in SAP HANA

When you add a HANA system in HANA Studio, you can see different tabs under system pane. Each pane has different object types of HANA system.
To see the list of all schema and tables, you need to navigate to Catalog tab.
Other available tabs in HANA Studio includes:
Backup
Catalog
Provisioning
Content
Security
You can check under table type- if a table is row store or column store. On right top corner, it is mentioned.New tables can be created using the two methods given below −
Using SQL editor
Using GUI option
The new table can be created using SQL Create Table statement −
Create column Table Test1 (
   ID INTEGER,
   NAME VARCHAR(10),
   PRIMARY KEY (ID)
);
To know more about schema and tables in SAP HANA, you can refer our link below: https://www.tutorialspoint.com/sap_hana/sap_hana_tables.htm
java.time.LocalTime.parse() Method Example

The java.time.LocalTime.parse(CharSequence text, DateTimeFormatter formatter) method obtains an instance of LocalTime from a text string using a specific formatter.
Following is the declaration for java.time.LocalTime.parse(CharSequence text, DateTimeFormatter formatter) method.
public static LocalTime parse(CharSequence text, DateTimeFormatter formatter)

text − the text to parse such as "10:15:30", not null.
text − the text to parse such as "10:15:30", not null.
formatter − the formatter to use, not null.
formatter − the formatter to use, not null.
the local date, not null.
DateTimeParseException − if the text cannot be parsed.
The following example shows the usage of java.time.LocalTime.parse(CharSequence text, DateTimeFormatter formatter) method.
package com.tutorialspoint;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class LocalTimeDemo {
   public static void main(String[] args) {
  
      DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_TIME;
      String time = "10:15:30";
      LocalTime time1 = LocalTime.parse(time, dateTimeFormatter);
      System.out.println(time1);
   }
}
Let us compile and run the above program, this will produce the following result −
10:15:30

 Print
 Add Notes
 Bookmark this page
Python - PoS Tagging and Lemmatization using spaCy

spaCy is one of the best text analysis library. spaCy excels at large-scale information extraction tasks and is one of the fastest in the world. It is also the best way to prepare text for deep learning. spaCy is much faster and accurate than NLTKTagger and TextBlob.
pip install spacy
python -m spacy download en_core_web_sm
#importing loading the library
import spacy
# python -m spacy download en_core_web_sm
nlp = spacy.load("en_core_web_sm")
#POS-TAGGING
# Process whole documents
text = ("""My name is Vishesh. I love to work on data science problems. Please check out my github profile!""")
doc = nlp(text)
# Token and Tag
for token in doc:
print(token, token.pos_)
# You want list of Verb tokens
print("Verbs:", [token.text for token in doc if token.pos_ == "VERB"])
#Lemmatization : It is a process of grouping together the inflected #forms of a word so they can be analyzed as a single item, #identified by the word’s lemma, or dictionary form.
import spacy
# Load English tokenizer, tagger,
# parser, NER and word vectors
nlp = spacy.load("en_core_web_sm")
# Process whole documents
text = ("""My name is Vishesh. I love to work on data science problems. Please check out my github profile!""")
doc = nlp(text)
for token in doc:
print(token, token.lemma_)
How to convert array of comma separated strings to array of objects?

Following is the code to convert array of comma separated strings to array of objects −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>Convert array of comma separated strings to array of object</h1>
<div class="sample"></div>
<br />
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to convert the above array of strings to objects</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   let arr = [
      '{ "name":"Rohan", "age":12}',
      '{ "name":"Mohit", "age":22}',
      '{ "name":"Shawn", "age":18}',
      '{ "name":"Michael", "age":19}',
   ];
   sampleEle.innerHTML = arr;
   BtnEle.addEventListener("click", () => {
      arr.forEach((item, index) => {
         arr[index] = JSON.parse(item);
      });
      arr.forEach((item) => {
         resEle.innerHTML += "Name = " + item.name + " : Age = " + item.age + "<br>";
      });
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
numpy.ndarray.ndim() method | Python

26 Mar, 2020
numpy.ndarray.ndim() function return the number of dimensions of an array.
Syntax : numpy.ndarray.ndim(arr)
Parameters :arr : [array_like] Input array. If it is not already an ndarray, a conversion is attempted.
Return : [int] Return the number of dimensions in arr.
Code #1 :
# Python program explaining# numpy.ndarray.ndim() function  # importing numpy as geek import numpy as geek  arr = geek.array([1, 2, 3, 4])  gfg = arr.ndim  print (gfg)
Output :
1

 Code #2 :
# Python program explaining# numpy.ndarray.ndim() function  # importing numpy as geek import numpy as geek  arr = [[1, 2, 3], [4, 5, 6]]  gfg = geek.ndim(arr)  print (gfg)
Output :
2

Python numpy-ndarray
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Get the first and last item in an array using JavaScript

24 Nov, 2021
In this article, we will learn to get the first & last element in an array in Javascript, along with understanding their implementation through the examples.
Javascript array is a variable that holds multiple values at a time. The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index. The array length property in JavaScript is used to set or return the number of elements in an array.
Example 1: This example illustrates to access the first and last number in the array.
Javascript
<script>  // Array   let s=[3, 2, 3, 4, 5];   function Gfg() {        // Storing the first item in a variable     let f=s[0];          // Storing the last item     let l=s[s.length-1];          // Printing output to screen   document.write("First element is "+ f);    document.write("<br> Last element is "+ l);   }   Gfg(); // Calling the function</script>
Output:
First element is 3 
Last element is 5
Example 2: This example illustrates to access the first and last word in the array.
Javascript
<script>  // Simple array  let s= ["Geeks", "for", "geeks", "computer", "science"];   function Gfg() {       // First item of the array   let f=s[0];        // Last item of the array   let l=s[s.length-1];        // Printing the output to screen   document.write("First element is "+ f);    document.write("<br> Last element is "+ l);    }   Gfg(); // Calling the function </script>
Output:
First element is Geeks
Last element is science 
bhaskargeeksforgeeks
javascript-array
JavaScript-Questions
Picked
JavaScript
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
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
Node.js | fs.writeFileSync() Method
JavaScript | Promises
How to filter object array based on attributes?
How to Use the JavaScript Fetch API to Get Data?
Lossless Decomposition in DBMS

15 Nov, 2021
 Lossless join decomposition is a decomposition of a relation R into relations R1, R2 such that if we perform a natural join of relation R1 and R2, it will return the original relation R. This is effective in removing redundancy from databases while preserving the original data...
In other words by lossless decomposition, it becomes feasible to reconstruct the relation R from decomposed tables R1 and R2  by using Joins.
In Lossless Decomposition, we select the common attribute and the criteria for selecting a common attribute is that the common attribute must be a candidate key or super key in either relation R1, R2, or both.
Decomposition of a relation R into R1 and R2 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies)  
    
R1 ∩ R2 → R1
   OR
R1 ∩ R2 → R2
Question 1: Let R (A, B, C, D) be a relational schema with the following functional dependencies:  
A → B, B → C,
C → D and D → B. 

The decomposition of R into 
(A, B), (B, C), (B, D)
(A) gives a lossless join, and is dependency preserving (B) gives a lossless join, but is not dependency preserving (C) does not give a lossless join, but is dependency preserving (D) does not give a lossless join and is not dependency preserving 
Refer to this for a solution. 
Question 2 R(A,B,C,D) is a relation. Which of the following does not have a lossless join, dependency preserving BCNF decomposition? (A) A->B, B->CD (B) A->B, B->C, C->D (C) AB->C, C->AD (D) A ->BCD 
Refer to this for a solution. 
Below is the Quiz of previous year GATE Questions 
https://www.geeksforgeeks.org/dbms-gq/database-design-normal-forms-gq/ 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
srivastavaharshit848
satyajitmahunta98
niharikatanwar61
DBMS-Normalization
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
CTE in SQL
Difference between Clustered and Non-clustered index
SQL Trigger | Student Database
SQL Interview Questions
Data Preprocessing in Data Mining
SQL | Views
Difference between DELETE, DROP and TRUNCATE
shuf Command in Linux with Examples

02 Dec, 2020
The shuf command in Linux writes a random permutation of the input lines to standard output. It pseudo randomizes an input in the same way as the cards are shuffled. It is a part of GNU Coreutils and is not a part of POSIX. This command reads either from a file or standard input in bash and randomizes those input lines and displays the output. Like other Linux commands, shuf command comes with –help option.
Syntax:
shuf [OPTION] [FILE] //file shuf
shuf -i LO-HI [OPTION] // range shuf
shuf -e [OPTION]... [ARG] //list shuf
shuf
When shuf command is used without any argument in the command line, it takes input from the user until CTRL- D is entered to terminate the set of inputs. It displays the input lines in a shuffled form. If 1, 2, and 3 are entered as input lines, then it generates 1.2 and 3 in random order in the output as seen in the image below:
1. File shuf
shuf [option] [file]
When shuf command is used in the above form i.e, without -e or -i option, then it operates as a file shuf i.e, it shuffles the contents of the file. The file_name is the last parameter of the shuf command and if it is not given, then input has to be provided from the shell or pipe. 
Consider an example where input is taken from a file:
shuf file.txt
Suppose file.txt contains 6 lines, then the shuf command displays the input lines in random order as output.
Any number of lines can be randomized by using -n option.
shuf -n 2 file.txt
This will display any two random lines from the file.
Consider an example where Input is taken  from the pipe:
{
seq 5 | shuf
}
seq 5 returns the integers sequentially from 1 to 5 while the shuf command takes it as input and shuffles the content i.e, the integers from 1 to 5. Hence, 1 to 5 is displayed as output in random order.
2. List shuf
shuf -e [OPTION]... [ARG]
When -e option is used with shuf command, it works as a list shuf. The arguments of the command are taken as the input line for the shuf.
Consider an example:
shuf -e A B C D E
It will take A, B, C, D, E as input lines, and will shuffle them to display the output
Any number of input lines can be displayed using the -n option along with -e option.
shuf -e -n 1 A B C D E
This will display any one of the inputs.
3. Range shuf
shuf -i LO-HI [OPTION]
When -i option is used along with shuf command, it acts as a range shuf. It requires a range of input as input where L0 is the lower bound while HI is the upper bound. It displays integers from L0-HI in shuffled form.
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | How to get function name ?

22 May, 2019
One of the most prominent styles of coding is following OOP paradigm. For this, nowadays, stress has been to write code with modularity, to increase debugging and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to know certain hacks of functions. This article discusses how to print the name of a function. Let’s discuss certain ways in which this can be done.
Method #1 : Using function.func_name
By using a simple function property function, func_name, one can get the name of the function and hence can be quite handy in the Testing purpose and also for documentation at times. The drawback is that this works just for Python2.
# Python code to demonstrate# way to get function name# using function.func_name  # initializing functiondef GFG():    return "You just called for success !!"  # printing function name # using function.func_nameprint("The name of function is : " + GFG.func_name)
The name of function is : GFG

 
Method #2 : Using function.__name__
This function can be used as an alternative to the above function and has been introduced in Python3 as the function mentioned in above method had been depreciated in Python3.
# Python code to demonstrate# way to get function name# using function.__name__  # initializing functiondef GFG():    return "You just called for success !!"  # printing function name # using function.__name__print("The name of function is : " + GFG.__name__)
The name of function is : GFG

Python function-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python math.gamma() Method

03 Dec, 2020
Python in its language allows various mathematical operations, which has manifolds application in scientific domain. One such offering of Python is the inbuilt gamma() function, which numerically computes the gamma value of the number that is passed in the function.
Syntax : math.gamma(x)Parameters :x : The number whose gamma value needs to be computed.
Returns : The gamma value, which is numerically equal to “factorial(x-1)”.
Code #1 : Demonstrating the working of gamma()
# Python code to demonstrate# working of gamma()import math  # initializing argumentgamma_var = 6  # Printing the gamma value.print ("The gamma value of the given argument is : "                       + str(math.gamma(gamma_var)))
Output:
The gamma value of the given argument is : 120.0
 
The gamma value can also be found using factorial(x-1), but the use case of gamma() is because, if we compare both the function to achieve the similar task, gamma() offers better performance.
Code #2 : Comparing factorial() and gamma()
# Python code to demonstrate# factorial() vs gamma()import mathimport time   # initializing argumentgamma_var = 6  # checking performance # gamma() vs factorial()start_fact = time.time()res_fact = math.factorial(gamma_var-1)  print ("The gamma value using factorial is : "                               + str(res_fact))  print ("The time taken to compute is : "        + str(time.time() - start_fact))  print ('\n')  start_gamma = time.time()res_gamma = math.gamma(gamma_var)  print ("The gamma value using gamma() is : "                           + str(res_gamma))  print ("The time taken to compute is : "        + str(time.time() - start_gamma))
Output:
The gamma value using factorial is : 120
The time taken to compute is : 9.059906005859375e-06

The gamma value using gamma() is : 120.0
The time taken to compute is : 5.245208740234375e-06

Python math-library
Python math-library-functions
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Python program to sort a string

06 Jun, 2022
Sorting has always been quite a popular utility with lots of applications everywhere, where Python language opts. Python in its language offers a sort function to perform this task. But due to fact that not all the containers in Python are mutable, such as string, the sort function doesn’t work as it is in place tries to sort and immutability stops this. Let’s discuss certain ways in which a string can be sorted. 
 The combination of the above functions can potentially solve this particular problem. This task is performed in 2 steps in which first step we get the sorted list of characters and then we join the result to get the resultant sorted string. 
Example
Python3
# Python3 code to demonstrate# Sorting a string# using join() + sorted() # initializing stringtest_string = "geekforgeeks" # printing original stringprint("The original string : " + str(test_string)) # using join() + sorted()# Sorting a stringres = ''.join(sorted(test_string))     # print resultprint("String after sorting : " + str(res))
The original string : geekforgeeks
String after sorting : eeeefggkkors
To sort a given string with user input using the inbuilt python sort method.
Example
Python3
string = input("Enter String: ")lst = [string[i] for i in range(0,len(string))]lst.sort()for i in lst:    print(i, end = "")
Output:
Enter String: geeksforgeeks
eeeefggkkors
This particular task can also be performed using the combination of the above 3 functions. Here we join the resultant sorted list of characters using the lambda function joined by the reduce function. Works only for Python2 
Example
Python
# Python code to demonstrate# Sorting a string# using sorted() + reduce() + lambda # initializing stringtest_string = "geekforgeeks" # printing original stringprint("The original string : " + str(test_string)) # using sorted() + reduce() + lambda# Sorting a stringres = reduce(lambda x, y: x + y, sorted(test_string))     # print resultprint("String after sorting : " + str(res))
The original string : geekforgeeks
String after sorting : eeeefggkkors
dey0btpch57lmvgz5mqhpaiqn337p09fd8yq1lw4
Python string-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
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
How to display HTML tags as plain text in HTML ?

20 Sep, 2021
Basically, there are two methods for displaying HTML tags as plain text.
1. Using <plaintext> element: Plaintext element is deprecated which means this feature is no longer supported. Though some browsers might still support it, it is not recommended to use.
2. HTML entities: The second and only option available is using html entities. < ,> are reserved characters in HTML, In order to display this reserved characters  you have to replace them with html entities. You can learn more about entities here. You can either use entity name or entity number initializing them with  & and ending them with ;
 
Refer to below table for required html entities:
Sign
Example 1: In the first example, we are using html entity names to display body element and paragraph element on web page.
HTML
<!DOCTYPE html><html>  <head>    <title>Plain text </title></head>  <body>    <pre>        Paragraph element: <p> </p>        Body element : < body > < /body >    </pre></body>  </html>
Output:
Output
Explanation: In above code, “<” and “>” is simply replaced by their respective html entities.<pre></pre> is html element which defines preformatted text.
Example 2: In below example, we are trying to display html entity name for “<” using entity name for “&” sign.
HTML
<!DOCTYPE html><html lang="en">  <head>    <title>Plain text demo</title></head>  <body>    <pre>        < is entity name for <    </pre></body>  </html>
Output:
Output
Explanation: In above example, “&” is replaced with “&amp;” and “<“ is replaced with “&lt;”
Blogathon-2021
HTML-Questions
HTML-Tags
Picked
Blogathon
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Groovy - Nested If Statement

Sometimes there is a requirement to have multiple if statement embedded inside of each other.
The general form of this statement is −
if(condition) { 
   statement #1 
   statement #2 
   ... 
} else if(condition) { 
   statement #3 
   statement #4 
} else { 
   statement #5 
   statement #6 
}

Following is an example of a nested if/else statement −
class Example { 
   static void main(String[] args) { 
      // Initializing a local variable 
      int a = 12 
		
      //Check for the boolean condition 
      if (a>100) {
         //If the condition is true print the following statement 
         println("The value is less than 100"); 
      } else 
         // Check if the value of a is greater than 5 
			
      if (a>5) { 
         //If the condition is true print the following statement 
         println("The value is greater than 5 and greater than 100"); 
      } else { 
         //If the condition is false print the following statement 
         println("The value of a is less than 5"); 
      }  
   } 
}	     
In the above example, we are first initializing a variable to a value of 12. In the first if statement, we are seeing if the value of a is greater than 100. If not, then we enter our second for loop to see if the value of a is greater than 5 or less than 5. The output of the above code would be −
The value is greater than 5 and greater than 100
PHP | json_encode() Function

17 Jun, 2019
The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation.Syntax :
string json_encode( $value, $option, $depth )
Parameters:
$value: It is a mandatory parameter which defines the value to be encoded.
$option: It is optional parameter which defines the Bitmask consisting of JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR.
$depth: It is optional parameter which sets the maximum depth. Its value must be greater than zero.
Return Value: This function returns a JSON representation on success or false on failure.
Example 1: This example encodes PHP array into JSON representation.
<?php   // Declare an array $value = array(    "name"=>"GFG",    "email"=>"abc@gfg.com");   // Use json_encode() function$json = json_encode($value);   // Display the outputecho($json);   ?>
{"name":"GFG","email":"abc@gfg.com"}

Example 2: This example encodes PHP multidimensional array into JSON representation.
<?php  // Declare multi-dimensional array $value = array(    "name"=>"GFG",    array(        "email"=>"abc@gfg.com",        "mobile"=>"XXXXXXXXXX"    ));   // Use json_encode() function$json = json_encode($value);   // Display the outputecho($json);   ?>
{"name":"GFG","0":{"email":"abc@gfg.com","mobile":"XXXXXXXXXX"}}

Example 3: This example encodes PHP objects into JSON representation.
<?php  // Declare classclass GFG {       }   // Declare an object$value = new GFG();   // Set the object elements$value->organisation = "GeeksforGeeks";$value->email = "feedback@geeksforgeeks.org";  // Use json_encode() function$json = json_encode($value);   // Display the outputecho($json);  ?>
{"organisation":"GeeksforGeeks","email":"feedback@geeksforgeeks.org"}

Reference: https://www.php.net/manual/en/function.json-encode.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Matplotlib.axes.Axes.set_xscale() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_xscale() function in axes module of matplotlib library is used to set the x-axis scale.
Syntax: Axes.set_xscale(self, value, **kwargs)
Parameters: This method accepts the following parameters.
value : This parameter is the axis scale type to apply.
**kwargs: There are different keyword arguments which are accepted and its depend on the scale.
Below examples illustrate the matplotlib.axes.Axes.set_xscale() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.ticker import EngFormatter  val = np.random.RandomState(19680801)xs = np.logspace(1, 9, 100)ys = (0.8 + 4 * val.uniform(size = 100)) * np.log10(xs)**2  fig, ax0 = plt.subplots()ax0.set_xscale('log')formatter0 = EngFormatter(unit ='Hz')ax0.xaxis.set_major_formatter(formatter0)ax0.plot(xs, ys)ax0.set_xlabel('Frequency')  fig.suptitle('matplotlib.axes.Axes.set_xscale() \function Example\n', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt    fig, ax4 = plt.subplots()  x = 10.0**np.linspace(0.0, 2.0, 15)y = x**2.0ax4.set_xscale("log", nonposx ='clip')ax4.set_yscale("log", nonposy ='clip')  ax4.errorbar(x, y, xerr = 0.1 * x,             yerr = 2.0 + 1.75 * y,              color ="green")  ax4.set_ylim(bottom = 0.1)  fig.suptitle('matplotlib.axes.Axes.set_xscale()\ function Example\n', fontweight ="bold")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Find missing numbers in a sorted list range

11 May, 2020
Given a range of sorted list of integers with some integers missing in between, write a Python program to find all the missing integers.
Examples:
Input : [1, 2, 4, 6, 7, 9, 10]
Output : [3, 5, 8]

Input : [5, 6, 10, 11, 13]
Output : [7, 8, 9, 12]

 Method #1 : List comprehension
# Python3 program to Find missing # integers in list          def find_missing(lst):    return [x for x in range(lst[0], lst[-1]+1)                                if x not in lst]  # Driver codelst = [1, 2, 4, 6, 7, 9, 10]print(find_missing(lst))
[3, 5, 8]

 Method #2 : List comprehension using zip()
# Python3 program to Find missing # integers in list          def find_missing(lst):    return [i for x, y in zip(lst, lst[1:])         for i in range(x + 1, y) if y - x > 1]  # Driver codelst = [1, 2, 4, 6, 7, 9, 10]print(find_missing(lst))
[3, 5, 8]

 Method #3 : Using set
The use of Python set is an efficient and tricky way to find the missing numbers in the list. We convert the list to set and simply output the difference between this set and a set that contains integers ranging from min(lst) and max(lst).
# Python3 program to Find missing # integers in list          def find_missing(lst):    return sorted(set(range(lst[0], lst[-1])) - set(lst))  # Driver codelst = [1, 2, 4, 6, 7, 9, 10]print(find_missing(lst))
[3, 5, 8]

 Method #4 : Using difference()
This is a similar approach to the previous one with a slight difference that instead of using ‘-‘ operator to find the difference between both the sets, we can use Python difference() method.
# Python3 program to Find missing # integers in list          def find_missing(lst):    start = lst[0]    end = lst[-1]    return sorted(set(range(start, end + 1)).difference(lst))  # Driver codelst = [1, 2, 4, 6, 7, 9, 10]print(find_missing(lst))
[3, 5, 8]

Python list-programs
Python-Sorted
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python Program that Sends And Receives Message from Client

17 Jun, 2021
Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server.Socket programming is started by importing the socket library and making a simple socket.  
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Here we made a socket instance and passed it two parameters. The first parameter is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address family ipv4. The SOCK_STREAM means connection-oriented TCP protocol.Note: For more information, refer to Socket Programming in PythonNow we can connect to a server using Server:A Server is a program that provides service to other computers on the network or Internet. Similarly, a client is a program that receives services from the server. When a server wants to communicate with a client, there is a need for a socket. A socket is a point of connection between the server and the client.TCP/IP server program that sends message to the client.  
Python3
import socket  # take the server name and port namehost = 'local host'port = 5000  # create a socket at server side# using TCP / IP protocols = socket.socket(socket.AF_INET,                  socket.SOCK_STREAM)  # bind the socket with server# and port numbers.bind(('', port))  # allow maximum 1 connection to# the sockets.listen(1)  # wait till a client accept# connectionc, addr = s.accept()  # display client addressprint("CONNECTION FROM:", str(addr))  # send message to the client after# encoding into binary stringc.send(b"HELLO, How are you ? \       Welcome to Akash hacking World") msg = "Bye.............."c.send(msg.encode())  # disconnect the serverc.close()
TCP/IP server program that receive message from server.  
Python3
import socket  # take the server name and port name  host = 'local host'port = 5000  # create a socket at client side# using TCP / IP protocols = socket.socket(socket.AF_INET,                  socket.SOCK_STREAM)  # connect it to server and port# number on local computer.s.connect(('127.0.0.1', port))  # receive message string from# server, at a time 1024 Bmsg = s.recv(1024)  # repeat as long as message# string are not emptywhile msg:    print('Received:' + msg.decode())    msg = s.recv(1024) # disconnect the clients.close()
Note: Open In Two Separate DOS Windows And First Execute server, then Execute client.Output of Server: 
Output of Client:  
 
saurabh1990aror
surinderdawra388
Python-socket
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
OpenCV Static Saliency Detection in a Nutshell | by Bethea Davida | Towards Data Science

Saliency is the standout part of an image that enables our brain to focus on that part. It’s what we put attention on when we see an image, the conspicuous region. For example, have you ever seen something interesting in an ad that makes you stop for a while to see it? That’s the saliency of the ad, the part that pulls your interest even when you just saw it in a glance.
First thing first, you need to install OpenCV library. If you already have pip installed, you can do it by running these commands.
> pip install opencv-python> pip install opencv-contrib-python
To verify the installation, you can run these commands.
> pythonPython 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49)Type "help", "copyright", "credits" or "license" for more information.>> import cv2>> cv2.saliency  <module 'cv2.saliency'>
There are many ways to detect saliency. In OpenCV, algorithms provided for saliency detection are divided into three categories:
We will talk about static saliency. Static saliency detection algorithms use different image features that allow detecting salient object of a non-dynamic image. There are two algorithms that already implemented in OpenCV, spectral residual and fine grained.
This algorithm analyzes the log-spectrum of an input image, extracts the spectral residual of an image in the spectral domain, and proposes a fast method to construct saliency map which suggests the positions of proto-objects.
Similarities imply redundancies. For a system aiming at minimizing the redundant visual information, it must be aware of the statistical similarities of the input stimuli. Therefore, in different log spectra where considerable shape similarities can be observed, what deserves our attention is the information that jumps out of the smooth curves. We believe that the statistical singularities in the spectrum may be responsible for anomalous regions in the image, where proto-objects are popped up.
And if you plot the saliency map, you will get the output image below.
Reference: Hou, Xiaodi, and Liqing Zhang. “Saliency detection: A spectral residual approach.” Computer Vision and Pattern Recognition, 2007. CVPR‘07. IEEE Conference on. IEEE, 2007.
The retina of the human eyes consists of ganglion cells. There are two types of ganglion cells, on-center and off-center. The on-center responds to bright areas surrounded by a dark background. The off-center responds to dark areas surrounded by a bright background.
This algorithm calculates the saliency based on the on-center and off-center differences.
In our case, by using an efficient implementation ofcenter-sorround differences through the so-called integral image, we demonstrate a method to generate fine grained feature maps of visual saliency operating in real time at the original image resolution.
And if you plot the saliency map, you will get the output image below.
Reference: B. Wang and P. Dudek “A Fast Self-tuning Background Subtraction Algorithm”, in proc of IEEE Workshop on Change Detection, 2014