code-rag-bench/online-tutorials huggingface dataset:
How to add and remove names on button click with JavaScript?

To create, use add() method, whereas to delete created and appended element, you can use
remove(). Following is the code −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/
4.7.0/css/font-awesome.min.css">
<style>
</style>
</head>
<body>
<div class="">
<ul id="listOfName"></ul>
</div>
<div class="">
<h1 class="">Add A New Name</h1>
<div class="">
<input type="text" id="name" placeholder="Add Name......">
<button class="btn" id="addNameButton">AddName</button>
</div>
</div>
</div>
<script>
   var givenName = document.querySelector('#name')
   var btnClass = document.querySelector('#addNameButton')
   var listOfName = document.querySelector('#listOfName')
   btnClass.addEventListener('click', () => {
      var actualName = givenName.value
      if (actualName.length != 0) {
         var createAnHTMLList = `<li class=""><div>${actualName}</div><button
         onclick="removeNameFromTheList(this)">Remove Name</button>`
         listOfName.innerHTML += createAnHTMLList
         givenName.value = ''
         givenName.classList.remove('red')
      } else{
         givenName.classList.add('red')
      }
   })
   function removeNameFromTheList(e) {
      e.parentElement.remove()
   }
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Here, I am adding two names, which are John, David. The snapshot is as follows. Let’s first add
“John” and click “AddName” −
Click the “AddName” button. You will get following output −
Now you can do with David also. After adding both the names, you will get the following sample
output.
Now, I am going to remove the name ‘John’. This will produce the following output −
Intersection of two arrays in C#

To get intersection of two arrays, use the Intersect method. It is an extension method from the System.Linq namespace.
The method returns the common elements between the two arrays.
Set the two arrays first −
int[] arr1 = { 44, 76, 98, 34 };
int[] arr2 = { 24, 98, 44, 55, 47, 86 };
Now use the Intersect on both the arrays −
Arr1.Intersect(arr2);
The following is the complete code −
 Live Demo
using System;
using System.Linq;

class Program {
   static void Main() {
      int[] arr1 = { 44, 76, 98, 34 };
      int[] arr2 = { 24, 98, 44, 55, 47, 86 };
      var intersect = arr1.Intersect(arr2);
      foreach (int res in intersect) {
         Console.WriteLine(res);
      }
   }
}
44
98
How to create a two dimensional array in JavaScript?

A two-dimensional array has more than one dimension, such as myarray[0][0] for element one, myarray[0][1] for element two, etc. To create a two-dimensional array in JavaScript, you can try to run the following code −
Live Demo
<html>    
   <body>              
      <script>  
         var myarray=new Array(3);        
         for (i=0; i <3; i++)          
         myarray[i]=new Array(3)                
         myarray[0][0]="One"        
         myarray[0][1]="Two"        
         myarray[0][2]="Three"        
         myarray[1][0]="Four"        
         myarray[1][1]="Five"        
         myarray[1][2]="Six"        
         myarray[2][0]="Seven"        
         myarray[2][1]="Eight"        
         myarray[2][2]="Nine"  
         document.write(myarray[2][0]);      
      </script>          
   </body>
</html>
Seven
How to plot a subset of a dataframe in R ?

30 Jun, 2021
In this article, we will learn multiple approaches to plotting a subset of a Dataframe in R Programming Language. Here we will be using, R language’s inbuilt “USArrests” dataset.
In this method, first a subset of the data is created base don some condition, and then it is plotted using plot function. Let us first create the subset of the data.
Syntax: plot(subset( data, condition, select))  
Parameters:
data: dataframe
condition: indicates the logical expression on the basis of which subsetting has to be done
select: indicates columns to select
Example:
R
subset(USArrests, Assault > 100 & UrbanPop > 25,       select = c( Rape, Assault))
Output:
   Rape Assault
Alabama        21.2     236
Alaska         44.5     263
.
.
.
Washington     26.2     145
Wyoming        15.6     161
Now let’s create the plot for the subset so obtained. The above command can be directly passed to the plot() function.
Example:
R
plot(subset(USArrests,Assault > 100 & UrbanPop > 25,             select = c(Rape, Assault)))
Output:
Using the ‘[ ]’ operator, elements of vectors and observations from dataframes can be accessed and subsetted based on some condition.
Syntax: plot( df$col1[condition], df$col2[condition] )
Parameters: 
df: dataframe 
condition:  indicates the logical expression on the basis of which subsetting has to be done
Again the data will be first subsetted out and then will be provided to the plot() function.
Example:
R
plot(USArrests$Rape[USArrests$Assault > 100] ,     USArrests$Assault[USArrests$Assault > 100] )
Output:
In this we pass the row and column name to be plotted, and the condition based on which sub setting should be done to the plot function.
Syntax: plot( x ~ y, data=subset(df, condition ) )
Parameters:
x: data for x axis
y: data for y axis
data: subset of our dataframe which we want to plot.
df: dataframe object
condition: indicates the logical expression on the basis of which subsetting has to be done
Example:
R
plot(Murder ~ UrbanPop, data=subset(USArrests, Rape < 25))
Output:
Picked
R DataFrame-Programs
R-Charts
R-DataFrame
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
R - if statement
Python | Maximum Sum Sublist

11 May, 2020
We can have an application for finding the lists with the maximum value and print it. This seems quite an easy task and may also be easy to code, but having shorthands to perform the same are always helpful as this kind of problem can come in web development.
Method #1 : Using reduce() + lambdaThe above two functions can help us achieve this particular task. The lambda function does the task of logic and iteration and reduce function does the task of returning the required result. Works in Python 2 only.
# Python code to demonstrate# maximum sum sublist # using reduce() + lambda  # importing functools for reduce()import functools  # initializing matrix test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]  # printing the original matrixprint ("The original matrix is : " + str(test_matrix))  # using reduce() + lambda# maximum sum sublist res = functools.reduce(lambda i, j: i if sum(i) > sum(j)       else j, test_matrix)  # printing resultprint ("Maximum sum sublist is : " + str(res))
The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Maximum sum sublist is : [4, 5, 3]

 
Method #2 : Using max() + keyThe max function can get the maximum of all the list and key is used to specify on what the max condition has to be applied that is summation in this case.
# Python3 code to demonstrate# maximum sum sublist # using max() + key  # initializing matrix test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]  # printing the original matrixprint ("The original matrix is : " + str(test_matrix))  # using max() + key# maximum sum sublist res = max(test_matrix, key = sum)  # printing resultprint ("Maximum sum sublist is : " + str(res))
The original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Maximum sum sublist is : [4, 5, 3]

epskvv
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | How to check current state of a thread

01 Feb, 2019
A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as ThreadState to check the current state of the thread. The initial state of a thread is Unstarted state.
Syntax:
public ThreadState ThreadState{ get; }
Return Value: This property returns the value that indicates the state of the current thread.
Below programs illustrate the use of ThreadState property:
Example 1:
// C# program to illustrate the // use of ThreadState propertyusing System;using System.Threading;  public class GFG {      // Main Method    static public void Main()    {        Thread thr;          // Get the reference of main Thread        // Using CurrentThread property        thr = Thread.CurrentThread;          // Display the current state        // of the main thread        Console.WriteLine("The name of the current state of the Main "                                  + "thread is: {0}", thr.ThreadState);    }}
Output:
The name of the current state of the main thread is: Running

Example 2:
// C# program to illustrate the // use of ThreadState propertyusing System;using System.Threading;  public class GFG {      // Main method    public static void Main()    {        // Creating and initializing threads        Thread TR1 = new Thread(new ThreadStart(job));        Thread TR2 = new Thread(new ThreadStart(job));          Console.WriteLine("ThreadState of TR1 thread"+                         " is: {0}", TR1.ThreadState);          Console.WriteLine("ThreadState of TR2 thread"+                         " is: {0}", TR2.ThreadState);          // Running state        TR1.Start();        Console.WriteLine("ThreadState of TR1 thread "+                           "is: {0}", TR1.ThreadState);          TR2.Start();        Console.WriteLine("ThreadState of TR2 thread"+                         " is: {0}", TR2.ThreadState);    }      // Static method    public static void job()    {        Thread.Sleep(2000);    }}
Output:
ThreadState of TR1 thread is: Unstarted
ThreadState of TR2 thread is: Unstarted
ThreadState of TR1 thread is: Running
ThreadState of TR2 thread is: WaitSleepJoin

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.threadstate?view=netframework-4.7.2
CSharp Multithreading
CSharp Thread Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
sleep command in Linux with Examples

27 May, 2019
sleep command is used to create a dummy job. A dummy job helps in delaying the execution. It takes time in seconds by default but a small suffix(s, m, h, d) can be added at the end to convert it into any other format. This command pauses the execution for an amount of time which is defined by NUMBER.
Syntax:
sleep NUMBER[SUFFIX]...

Example:
Note: If you will define more than one NUMBER with sleep command then this command will delay for the sum of the values.
Options provided by sleep command:
–help : It displays help information.
–version : It displays version information.
linux-command
Linux-Shell-Commands
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
'crontab' in Linux with Examples
Tail command in Linux with examples
TCP Server-Client implementation in C
Docker - COPY Instruction
UDP Server-Client implementation in C
diff command in Linux with examples
echo command in Linux with Examples
Cat command in Linux with examples
How to Create a Histogram from Pandas DataFrame?

19 Dec, 2021
A histogram is a graph that displays the frequency of values in a metric variable’s intervals. These intervals are referred to as “bins,” and they are all the same width.
We can create a histogram from the panda’s data frame using the df.hist() function.
Syntax:
DataFrame.hist(column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, bins=10, backend=None, legend=False, **kwargs)
We use df.hist() and plot.show() to display the Histogram.
CSV file used: gene_expression.csv
Python3
# import libraries and packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns  # reading the CSV filedf = pd.read_csv('gene_expression.csv')  # displaying the DataFrameprint(df)  # creating a basic histogramdf.hist()plt.show()
Output:
In this example, we add extra parameters to the hist method. We have changed the fig size, no of bins is specified as 15, and by parameter is given which ensures histograms for each cancer group are created.
Python3
# import libraries and packagesimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns  # reading the CSV filedf = pd.read_csv('gene_expression.csv')  # displaying the DataFrameprint(df)  # creating a basic histogramdf.hist(by='Cancer Present', figsize=[12, 8], bins=15)plt.show()
Output:
Picked
Python pandas-plotting
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Count keys with particular value in dictionary

22 Jun, 2022
Sometimes, while working with Python dictionaries, we can come across a problem in which we have a particular value, and we need to find frequency if it’s occurrence. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using loop This problem can be solved using naive method of loop. In this we just iterate through each key in dictionary and when a match is found, the counter is increased. 
Python3
# Python3 code to demonstrate working of# Count keys with particular value in dictionary# Using loop # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2} # printing original dictionaryprint("The original dictionary : " +  str(test_dict)) # Initialize valueK = 2 # Using loop# Selective key values in dictionaryres = 0for key in test_dict:    if test_dict[key] == K:        res = res + 1     # printing resultprint("Frequency of K is : " + str(res))
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3
  Method #2 : Using sum() + values() This can also be solved using the combination of sum() and value(). In this, sum is used to perform the summation of values filtered and values of dictionary are extracted using values() 
Python3
# Python3 code to demonstrate working of# Count keys with particular value in dictionary# Using sum() + values() # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2} # printing original dictionaryprint("The original dictionary : " +  str(test_dict)) # Initialize valueK = 2 # Using sum() + values()# Selective key values in dictionaryres = sum(x == K for x in test_dict.values())     # printing resultprint("Frequency of K is : " + str(res))
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3
Method #3 : Using count() and values().These methods can be used together to find number of keys with particular value.
Python3
# Python3 code to demonstrate working of# Count keys with particular value in dictionary# Using count() + values() # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 2, 'CS' : 2} # printing original dictionaryprint("The original dictionary : " +  str(test_dict)) # Initialize valueK = 2 # Using count() + values()list1=list(test_dict.values()) # Selective key values in dictionaryres = list1.count(K)    # printing resultprint("Frequency of K is : " + str(res))
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 2, 'CS': 2}
Frequency of K is : 3
In all the solutions time and space complexity are the same:
Time Complexity: O(n)
Space Complexity: O(n)
kogantibhavya
harshmaster07705
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Key Value list pairings in Dictionary

22 Apr, 2020
Sometimes, while working with Python dictionaries, we can have problems in which we need to pair all the keys with all values to form a dictionary with all possible pairings. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using list comprehensionThis task can be performed using this method. In this we manually extract each key and then iterate with all the values of them to form new dictionary list. This has drawbacks of only available for certain keys.
# Python3 code to demonstrate working of # Key Value list pairings in Dictionary# Using list comprehension  # initializing dictionarytest_dict = {'gfg' : [7, 8],             'best' : [10, 11, 7]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Key Value list pairings in Dictionary# Using list comprehensionres = [{'gfg': i, 'best': j} for i in test_dict['gfg']                           for j in test_dict['best']]  # printing result print("All key value paired List : " + str(res)) 
The original dictionary is : {‘gfg’: [7, 8], ‘best’: [10, 11, 7]}All key value paired List : [{‘gfg’: 7, ‘best’: 10}, {‘gfg’: 7, ‘best’: 11}, {‘gfg’: 7, ‘best’: 7}, {‘gfg’: 8, ‘best’: 10}, {‘gfg’: 8, ‘best’: 11}, {‘gfg’: 8, ‘best’: 7}]
 
Method #2 : Using dict() + zip() + product()The combination of above methods can also be used to perform this task. In this, the formation of combinations is done using product(), and linking of values is done using zip().
# Python3 code to demonstrate working of # Key Value list pairings in Dictionary# Using dict() + zip() + product()from itertools import product  # initializing dictionarytest_dict = {'gfg' : [7, 8],             'best' : [10, 11, 7]}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Key Value list pairings in Dictionary# Using dict() + zip() + product()res = [dict(zip(test_dict, sub)) for sub in product(*test_dict.values())]  # printing result print("All key value paired List : " + str(res)) 
The original dictionary is : {‘gfg’: [7, 8], ‘best’: [10, 11, 7]}All key value paired List : [{‘gfg’: 7, ‘best’: 10}, {‘gfg’: 7, ‘best’: 11}, {‘gfg’: 7, ‘best’: 7}, {‘gfg’: 8, ‘best’: 10}, {‘gfg’: 8, ‘best’: 11}, {‘gfg’: 8, ‘best’: 7}]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Check If a Name Begins and Ends With a Vowel

08 Oct, 2021
In this article, we will see an SQL query to check if a name begins and ends with a vowel and we will implement it with the help of an example for better understanding, first of all, we will create a database Name of the Database will GeeksforGeeks. and inside the database, we will create a table name As “Student”. 
Here we use two different methods for this.
Syntax:
FOR LEFT():
LEFT ( expression, no_of_chars needed to the left)

FOR RIGHT():
RIGHT ( expression, no_of_chars needed to the right)
In this article let us see how to Check If a Name Begins and Ends With a Vowel and display them using MSSQL as a server.
Creating a database GeeksforGeeks by using the following SQL query as follows.
Query:
CREATE DATABASE GeeksforGeeks;
Using the database GeeksforGeeks using the following SQL query as follows.
Query:
USE GeeksforGeeks;
Creating a table student with 3 columns using the following SQL query as follows.
Query:
CREATE TABLE student(
stu_id VARCHAR(8),
stu_name VARCHAR(30),
stu_branch VARCHAR(30)
)
To view the description of the table using the following SQL query as follows.
Query:
EXEC sp_columns student 
Inserting rows into student tables using the following SQL query as follows.
Query:
INSERT INTO student VALUES
('191401', 'ABHI','E.C.E'),
('191402', 'OLIVIA','E.C.E'),
('191403', 'SAMARTH','E.C.E'),
('191404', 'ANNABELLE','E.C.E'),
('191405', 'ARIA','E.C.E'),
('191406', 'RAMESH','E.C.E')
Viewing the table student after inserting rows by using the following SQL query as follows.
Query:
SELECT * FROM student 
Step 7: Query  to Check If a Name Begins and Ends With a Vowel using string functions and IN operator
To check if a name begins ends with a vowel we use the string functions to pick the first and last characters and check if they were matching with vowels using in where the condition of the query. We use the LEFT() and RIGHT() functions of the string in SQL to check the first and last characters.
Query:
SELECT stu_name
FROM student 
WHERE LEFT(stu_name , 1) IN ('a','e','i','o','u')
AND RIGHT(stu_name,1) IN  ('a','e','i','o','u')
Output:
Method 2: 
Using Regular Expressions and LIKE operator to check if first and last characters are vowels. Query  to Check If a Name Begins and Ends With a Vowel using REGEX
Query:
SELECT stu_name 
FROM student 
WHERE stu_name LIKE '[aeiouAEIOU]%[aeiouAEIOU]'
Here % is used for multiple occurrences of any character and [] is used for anyone occurrence of a given set of characters in the brackets.
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Software Engineering | The Make-Buy Decision or Decision Table

02 Sep, 2021
A decision table is a brief visual representation for specifying which actions to perform depending on given conditions. The information represented in decision tables can also be represented as decision trees or in a programming language using if-then-else and switch-case statements. 
A decision table is a good way to settle with different combination inputs with their corresponding outputs and is also called a cause-effect table. The reason to call cause-effect table is a related logical diagramming technique called cause-effect graphing that is basically used to obtain the decision table. 
Importance of Decision Table:
Decision tables are very much helpful in test design techniques.
It helps testers to search the effects of combinations of different inputs and other software states that must correctly implement business rules.
It provides a regular way of starting complex business rules, that is helpful for developers as well as for testers.
It assists in the development process with the developer to do a better job. Testing with all combinations might be impractical.
A decision table is basically an outstanding technique used in both testing and requirements management.
It is a structured exercise to prepare requirements when dealing with complex business rules.
It is also used in model complicated logic.
CONDITIONS    STEP 1    STEP 2    STEP 3    STEP 4
Condition 1                
Condition 2                
Condition 3                
Condition 4                
Decision Table: Combinations 
CONDITIONS    STEP 1    STEP 2    STEP 3    STEP 4
Condition 1      Y         Y         N         N
Condition 2      Y         N         Y         N
Condition 3      Y         N         N         Y
Condition 4      N         Y         Y         N
Advantage of Decision Table:  
Any complex business flow can be easily converted into test scenarios & test cases using this technique.
Decision tables work iteratively which means the table created at the first iteration is used as input tables for the next tables. The iteration is done only if the initial table is not satisfactory.
Simple to understand and everyone can use this method to design the test scenarios & test cases.
It provides complete coverage of test cases which helps to reduce the rework on writing test scenarios & test cases.
These tables guarantee that we consider every possible combination of condition values. This is known as its completeness property.
 
varshachoudhary
rajeev0719singh
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays in Python using heapq?

In this section we will see how two sorted lists can be merged using the heapq module in Python. As an example, if list1 = [10, 20, 30, 40] and list2 = [100, 200, 300, 400, 500], then after merging it will return list3 = [10, 20, 30, 40, 100, 200, 300, 400, 500]
To perform this task, we will use the heapq module. This module comes with Python as Standard Library Module. So we need to import it before using it.
import heapq
The heapq module has some properties. These are like below −
Method heapq.heapify(iterable)
It is used to convert an iterable dataset to heap data structure.
Method heapq.heappush(heap, element)
This method is used to insert the element into the heap. After that re-heap the entire heap structure.
Method heapq.heappop(heap)
This method is used to return and delete the element from the top of the heap and perform heapify on the rest of the elements.
Method heapq.heappushpop(heap, element)
This method is used to insert and pop element in one statement.
Method heapq.heapreplace(heap, element)
This method is used to insert and pop element in one statement. It removes the element from root of the heap, then insert element into the heap.
Method heapq.nlargest(n, iterable, key=None)
This method is used to return n largest element from the heap.
Method heapq.nsmallest(n, iterable, key=None)
This method is used to return n smallest element from the heap.
 Live Demo
import heapq
first_list = [45, 12, 63, 95, 74, 21, 20, 15, 36]
second_list = [42, 13, 69, 54, 15]

first_list = sorted(first_list)
second_list = sorted(second_list)

print('First sorted list: ' + str(first_list))
print('Second sorted list: ' + str(second_list))

final_list = list(heapq.merge(first_list, second_list))
print('The final list: ' + str(final_list))
First sorted list: [12, 15, 20, 21, 36, 45, 63, 74, 95]
Second sorted list: [13, 15, 42, 54, 69]
The final list: [12, 13, 15, 15, 20, 21, 36, 42, 45, 54, 63, 69, 74, 95]
TRIM() Function in SQL Server

18 Jan, 2021
TRIM() function :
This function in SQL Server is used to omit the space character or additional stated characters from the beginning or the ending of a specified string.
Features :
This function is used to omit the space character or some additional given characters from the beginning or the ending of a string stated.
This function accepts specific characters and string.
This function can by default omit the front and endmost spaces from a string given.
Syntax :
TRIM([characters FROM ]string)
Parameter :
This method accepts two parameters
characters FROM – Specific characters which are to be omitted.
string – Specified string from which the stated characters or spaces are omitted.
Returns :
It returns the specified string after omitting the space character or some additional stated characters from the front or the endmost part of it.
Example-1 :
Getting the specified string after omitting the beginning and ending space of it.
SELECT TRIM('     GFG     ');
Output :
GFG
Example-2 :
Using TRIM() function with a variable and getting the specified string after modification as output.
DECLARE @str VARCHAR(10);
SET @str = '   Geeks   ';
SELECT TRIM(@str);
Output :
Geeks
Example-3 :
Getting the specified string after omitting the specific characters and the beginning and ending space of it.
SELECT TRIM('@$ ' FROM '    @geeksforgeeks$    ');
Output :
geeksforgeeks
Here, the specified character is also omitted.
Example-4 :
Using TRIM() function with two variables and getting the specified string after modification as output.
DECLARE @str VARCHAR(10);
DEclare @char VARCHAR(10);
SET @str = '   &Geeks*  ';
SET @char = '&* ';
SELECT TRIM(@char FROM @str);
Output :
Geeks
Application :
This function is used to return the modified string after omitting the space character or additional stated characters from the beginning or the ending of a given string.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
How to Import JSON Data into SQL Server?
SQL Query to Compare Two Dates
Introduction of Database Normalization

28 Jun, 2021
Database normalization is the process of organizing the attributes of the database to reduce or eliminate data redundancy (having the same data but at different places) . 
Problems because of data redundancy Data redundancy unnecessarily increases the size of the database as the same data is repeated in many places. Inconsistency problems also arise during insert, delete and update operations. 
Functional Dependency Functional Dependency is a constraint between two sets of attributes in relation to a database. A functional dependency is denoted by an arrow (→). If an attribute A functionally determines B, then it is written as A → B. 
For example, employee_id → name means employee_id functionally determines the name of the employee. As another example in a timetable database, {student_id, time} → {lecture_room}, student ID and time determine the lecture room where the student should be. 
What does functionally dependent mean? A function dependency A → B means for all instances of a particular value of A, there is the same value of B. 
For example in the below table A → B is true, but B → A is not true as there are different values of A for B = 3. 
A   B
------
1   3
2   3
4   0
1   3
4   0
Trivial Functional Dependency X → Y is trivial only when Y is subset of X. Examples  
ABC → AB
ABC → A
ABC → ABC
Non Trivial Functional Dependencies X → Y is a non trivial functional dependency when Y is not a subset of X. 
X → Y is called completely non-trivial when X intersect Y is NULL.  
Example: 
Id → Name, 
Name → DOB
Semi Non Trivial Functional Dependencies X → Y is called semi non-trivial when X intersect Y is not NULL. Examples:  
AB → BC, 
AD → DC
Normal Forms
Quiz on Normalization
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
AmanSrivastava1
krishna_97
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
Matplotlib.axes.Axes.clear() 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.clear() function in axes module of matplotlib library is used to clear the axes.
Syntax: Axes.clear(self)
Parameters: This method does not accept any parameters.
Returns:This method does not returns any values.
Below examples illustrate the matplotlib.axes.Axes.clear() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt     fig, ax = plt.subplots()ax.set_xlabel('x-axis')ax.set_ylabel('y-axis')ax.plot([1, 2, 3])ax.grid(True)ax.clear()ax.set_title('matplotlib.axes.Axes.clear() \Example\n', fontsize = 12, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt     t = np.linspace(0.0, 2.0, 201)s = np.sin(2 * np.pi * t)  fig, [ax, ax1] = plt.subplots(2, 1, sharex = True)  ax.set_ylabel('y-axis')ax.plot(t, s)ax.grid(True)ax.set_title('matplotlib.axes.Axes.clear() Example\n\n Sample Example',             fontsize = 12, fontweight ='bold')  ax1.set_ylabel('y-axis')ax1.plot(t, s)ax1.grid(True)ax1.clear()ax1.set_title('Above example with clear() \function', fontsize = 12, 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 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
pandas.array() function in Python

14 Aug, 2020
This method is used to create an array from a sequence in desired data type.
Syntax : pandas.array(data: Sequence[object], dtype: Union[str, numpy.dtype, pandas.core.dtypes.base.ExtensionDtype, NoneType] = None, copy: bool = True)
Parameters :
data : Sequence of objects. The scalars inside `data` should be instances of the scalar type for `dtype`. It’s expected that `data` represents a 1-dimensional array of data. When `data` is an Index or Series, the underlying array will be extracted from `data`.
dtype : tr, np.dtype, or ExtensionDtype, optional. The dtype to use for the array. This may be a NumPy dtype or an extension type registered with pandas.
copy : bool, default True. Whether to copy the data, even if not necessary. Depending on the type of `data`, creating the new array may require copying data, even if “copy=False“.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packagesimport pandas  # create Pandas array with dtype stringpd_arr = pandas.array(data=[1,2,3,4,5],dtype=str)  # print the formed arrayprint(pd_arr)
Output :
<PandasArray>
['1', '2', '3', '4', '5']
Length: 5, dtype: str32

Example 2 :
Python3
# importing packagesimport pandasimport numpy  # create Pandas array with dtype from numpypd_arr = pandas.array(data=['1', '2', '3', '4', '5'],                      dtype=numpy.int8)  # print the formed arrayprint(pd_arr)
Output :
<PandasArray>
[1, 2, 3, 4, 5]
Length: 5, dtype: int8

Python pandas-datatypes
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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
Python | datetime.timedelta() function
Program to swap numbers using XOR operator in C#

08 Jun, 2020
C# Program to swap the two numbers using Bitwise XOR Operation. Given two variables, x and y, swap two variables with using a XOR statements. 
Example: 
Input: 300 400 

Output: 400 300 

Explanation: 
x = 300 y = 400 
x = 400 y = 300
C#
// C# Program to Swap the two Numbers// using Bitwise XOR Operationusing System;using System.Text;  namespace Test {class GFG {      static void Main(string[] args) {    int x, y;    Console.WriteLine("Enter two numbers \n");    x = int.Parse(Console.ReadLine());    y = int.Parse(Console.ReadLine());      // printing the numbers before swapping    Console.WriteLine("Numbers before swapping");    Console.WriteLine("x = {0} \t b = {1}", x, y);      // swapping    x = x ^ y;    y = x ^ y;    x = x ^ y;      // printing the numbers after swapping    Console.WriteLine("Numbers after swapping");    Console.WriteLine("x = {0} \t b = {1}", x, y);      Console.ReadLine();  }}}
Output: 
Enter two numbers 

Numbers before swapping
x = 300      b = 400
Numbers after swapping
x = 400      b = 300

C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Convert String to Character Array in C#
Program to Print a New Line in C#
Socket Programming in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number
Searching Books with Python

19 Aug, 2021
In this article, we are going to write python scripts for searching books using isbntools modules. isbntools module able to search for books by there name or ISBN( International Standard Book Number) and return all the information about the book.
Installation: Run the following pip command:
pip install isbntools
Importing the module:
Python3
from isbntools.app import *
  
1. Use isbn_from_words() function to get the ISBN for a book.
 
Syntax: isbn_from_words(str) 
Parameter: book name
Returns: ISBN of the book.
 
Python3
get_isbn = isbn_from_words("Half Girlfriend")print(get_isbn)
  
Output:
 
9788129135728
 
2. Get the information of a book by its ISBN.
 
Syntax: registry.bibformatters[identifiers](meta(isbn))
Parameter: ISB Number of the book
Returns: the meta information of the book
 
Notes: Identifiers can be used to print different types of format (bibtex, csl, opf, msword, endnote, refworks, json).
 
Python3
print(registry.bibformatters['labels'](meta("9788129135728")))
  
Output:
 
 
3. If you want to print the object without identifiers then you will all object in a specific location.
 
Python3
print(registry.bibformatters)
  
Output:
 
 
4. Get information in JSON format:
 
Python3
print(registry.bibformatters['json'](meta("9788129135728")))
  
Output:
 
 
5. Get information in MS Word format:
 
Python3
print(registry.bibformatters['msword'](meta("9788129135728")))
  
Output:
 
 
rajeev0719singh
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Treemap in Pygal

28 Jul, 2020
Pygal is a Python module that is mainly used to build SVG (Scalar Vector Graphics) graphs and charts. SVG is a vector-based graphics in the XML format that can be edited in any editor. Pygal can create graphs with minimal lines of code that can be easy to understand and write.
Treemap is a chart that is used for displaying echelons data using planted figures mainly rectangles. Each branch of the tree is in rectangular form and then which is macadamize with smaller rectangles to represent sub-branches. The color and the pattern are fixed in such a way in a treemap structure, that it won’t be difficult to understand the material. The second advantage of making treemap is they take less space in layout and can display thousands of items on a screen simultaneously. It can be created using Treemap() method.
Syntax:
treemap = pygal.Treemap()
Example 1:
# importing pygalimport pygalimport numpy    # creating the chart objecttreemap = pygal.Treemap()  # naming the titletreemap.title = 'Treemap'    # Random datatreemap.add('A', numpy.random.rand(5))treemap.add('B', numpy.random.rand(5))treemap.add('C', numpy.random.rand(5))treemap.add('D', numpy.random.rand(5))  treemap
Output:
Example 2:
# importing pygalimport pygalimport numpy    # creating the chart objecttreemap = pygal.Treemap()  # naming the titletreemap.title = 'Treemap'          # Random datatreemap.add('A', [26, 22, 39, 39, 32, 30, 33, 24, 24, 30])treemap.add('B', [31, 40, None, None, None, None, 40, 32, 25, 31])treemap.add('C', [37, 27, 31, 20, None, 32, 24, 39, 29, 22])treemap.add('D', [38, None, 20, 29, 33, 23, 32, 33, 32, 23])  treemap
Output:
Data Visualization
Python pygal-chart
Python-pygal
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python – Row with Minimum difference in extreme values

11 Oct, 2020
Given a Matrix, extract the rows with a minimum difference in extreme values.
Examples:
Input : test_list = [[4, 10, 18], [5, 0], [1, 4, 6], [19, 2]] Output : [[1, 4, 6], [5, 0]] Explanation : 6 – 1 = 5, 5 – 0 = 5, is minimum difference between extreme values. 
Input : test_list = [[4, 10, 18], [5, 0], [2, 4, 6], [19, 2]] Output : [[2, 4, 6]] Explanation : 6 – 2 = 4, is min diff. 
Method #1 : Using list comprehension + min()
In this, we compute minimum difference between extreme values, and then use list comprehension to get particular row with that value difference between extreme values.
Python3
# Python3 code to demonstrate working of # Matrix Minimum difference in extreme values row# Using min() + list comprehension  # initializing listtest_list = [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]  # printing original listprint("The original list is : " + str(test_list))  # getting min value min_val = min([max(sub) - min(sub) for sub in test_list])  # using list comprehension to filter res = [sub for sub in test_list if max(sub) - min(sub) == min_val]  # printing result print("Rows with Minimum difference in extreme values : " + str(res))
Output:
The original list is : [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]Rows with Minimum difference in extreme values : [[1, 4, 6]]
Method #2 : Using min() + list comprehension + filter() + lambda
In this, we perform task of filtering comparing with minimum value using filter() + lambda.
Python3
# Python3 code to demonstrate working of # Matrix Minimum difference in extreme values row# Using min() + list comprehension + filter() + lambda  # initializing listtest_list = [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]  # printing original listprint("The original list is : " + str(test_list))  # getting min value min_val = min([max(sub) - min(sub) for sub in test_list])  # using filter() + lambda to filter res = list(filter(lambda sub : max(sub) - min(sub) == min_val, test_list))  # printing result print("Rows with Minimum difference in extreme values : " + str(res))
Output:
The original list is : [[4, 10, 18], [5, 3, 10], [1, 4, 6], [19, 2]]Rows with Minimum difference in extreme values : [[1, 4, 6]]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Return true or false in a MySQL select if another field contains a string?

To return TRUE or FALSE if another field contains a string, use IF(). Let us first create a table
mysql> create table DemoTable
(
   FirstName varchar(100),
   LastName varchar(100)
);
Query OK, 0 rows affected (1.28 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris','Brown');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('David','Miller');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Adam','Smith');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Chris     | Brown    |
| David     | Miller   |
| Adam      | Smith    |
+-----------+----------+
3 rows in set (0.00 sec)
Following is the query to return true or false in a MySQL select if another field contains a string. Here, we are checking for string “Miller” −
Mysql> select if(LastName=’Miller’,’Yes','No') AS LastName,FirstName from DemoTable;
This will produce the following output −
+----------+-----------+
| LastName | FirstName |
+----------+-----------+
| No       | Chris     |
| Yes      | David     |
| No       | Adam      |   
+----------+-----------+
3 rows in set (0.00 sec)
Python | Pandas DataFrame.transform

21 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.transform() function call func on self producing a DataFrame with transformed values and that has the same axis length as self.
Syntax: DataFrame.transform(func, axis=0, *args, **kwargs)
Parameter :func : Function to use for transforming the dataaxis : {0 or ‘index’, 1 or ‘columns’}, default 0*args : Positional arguments to pass to func.**kwargs : Keyword arguments to pass to func.
Returns : DataFrame
Example #1 : Use DataFrame.transform() function to add 10 to each element in the dataframe.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1],                    "B":[7, 2, 54, 3, None],                    "C":[20, 16, 11, 3, 8],                    "D":[14, 3, None, 2, 6]})   # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']  # Set the indexdf.index = index_  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.transform() function to add 10 to each element of the dataframe.
# add 10 to each element of the dataframeresult = df.transform(func = lambda x : x + 10)  # Print the resultprint(result)
Output :
As we can see in the output, the DataFrame.transform() function has successfully added 10 to each element of the given Dataframe. Example #2 : Use DataFrame.transform() function to find the square root and the result of euler’s number raised to each element of the dataframe.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1],                    "B":[7, 2, 54, 3, None],                    "C":[20, 16, 11, 3, 8],                    "D":[14, 3, None, 2, 6]})   # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']  # Set the indexdf.index = index_  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.transform() function to find the square root and the result of euler’s number raised to each element of the dataframe.
# pass a list of functionsresult = df.transform(func = ['sqrt', 'exp'])  # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.transform() function has successfully performed the desired operation on the given dataframe.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.