code-rag-bench/online-tutorials huggingface dataset:
addgroup command in Linux with Examples - GeeksforGeeks

22 Jun, 2020
addgroup command in Linux is used to add a new group to your current Linux machine. This command allows you to modify the configurations of the group which is to be created. It is similar to the groupadd command in Linux. The addgroup command is much interactive as compared to groupadd command.
To install addgroup tool use the following commands as per your Linux distribution.
In case of Debian/Ubuntu
$sudo apt-get install addgroup
In case of CentOS/RedHat
$sudo yum install addgroup
In case of Fedora OS
$sudo dnf install addgroup
1. To add a new group
sudo addgroup groupname
This command will create a new group for your Linux machine.
2. To add a new group with specified group id
sudo addgroup groupname --gid 12345
This command will add a new group with the specified group id.
3. To create a group with a specific shell
sudo addgroup groupname --shell /bin/sh
This command will allocate the /bin/sh shell to the newly create group.
4. To enter verbose mode
sudo addgroup groupname --debug
This command will execute the command in the verbose mode that means it will print all details of the tasks it is executing.
5. To display help related to addgroup command.
addgroup --help
This command will display the help section of the addgroup command.
6. To display version
addgroup --version
This command will display the version details of the addgroup command.
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
What e.preventDefault() method really does in jQuery?

The preventDefault() method stops the default action of a selected element from happening by a user. This method does not accept any parameter and works in two ways:
It prevents a link from following the URL so that the browser can't go another page.
It prevents a submit button from submitting a form.
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script>
      $(document).ready(function() {
         $("a").click(function(event) {
            event.preventDefault();
         });
      });
   </script>
</head>
<body>
   <a href="https://www.tutorialspoint.com/">Tutorialspoint.com</a>
   <p>Click the link and it wont work.</p>
</body>
</html>
Simple Diamond Pattern in Python - GeeksforGeeks

29 May, 2021
Given an integer n, the task is to write a python program to print diamond using loops and mathematical formulations. The minimum value of n should be greater than 4.
Examples :
For size = 5

  * * *   
* * * * * 
  * * *   
    *  
    
For size = 8

  * * * * * *   
* * * * * * * * 
  * * * * * *   
    * * * *     
      * *       
                    

For size = 11

  * * * * * * * * *   
* * * * * * * * * * * 
  * * * * * * * * *   
    * * * * * * *     
      * * * * *       
        * * *         
          *           
Approach :
The following steps are used :
Form the worksheet of (size/2+2) x size using two loops.
Apply the if-else conditions for printing stars.
Apply else condition for rest spaces.
Below is the implementation of the above approach :
Example 1:
Python3
# define the size (no. of columns)# must be odd to draw proper diamond shapesize = 8 # initialize the spacesspaces = size # loops for iterations to create worksheetfor i in range(size//2+2):    for j in range(size):               # condition to left space        # condition to right space        # condition for making diamond        # else print *        if j < i-1:            print(' ', end=" ")        elif j > spaces:            print(' ', end=" ")        elif (i == 0 and j == 0) | (i == 0 and j == size-1):            print(' ', end=" ")        else:            print('*', end=" ")                 # increase space area by decreasing spaces    spaces -= 1         # for line change    print()
Output :
  * * * * * *   
* * * * * * * * 
  * * * * * *   
    * * * *     
      * *       
Example 2:
Python3
# define the size (no. of columns)# must be odd to draw proper diamond shapesize = 11 # initialize the spacesspaces = size # loops for iterations to create worksheetfor i in range(size//2+2):    for j in range(size):               # condition to left space        # condition to right space        # condition for making diamond        # else print ^        if j < i-1:            print(' ', end=" ")        elif j > spaces:            print(' ', end=" ")        elif (i == 0 and j == 0) | (i == 0 and j == size-1):            print(' ', end=" ")        else:            print('*', end=" ")                 # increase space area by decreasing spaces    spaces -= 1         # for line change    print()
Output :
  * * * * * * * * *   
* * * * * * * * * * * 
  * * * * * * * * *   
    * * * * * * *     
      * * * * *       
        * * *         
          *          
Akanksha_Rai
Python Pattern-printing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
How to implement an interface using an anonymous inner class in Java?

An anonymous inner class is a class which doesn't have a name, we will directly define it at the instantiation line.
In the following program, we are implementing the toString() method of TutorialsPoint interface using Anonymous inner class and, print its return value.
interface TutorialsPoint{
   public String toString();
}
public class Main implements TutorialsPoint {
   public static void main(String[] args) {
      System.out.print(new TutorialsPoint() {
         public String toString() {
            return "Welcome to Tutorials Point";
         }
      });
   }
}
Welcome to Tutorials Point
GATE | GATE-CS-2015 (Set 3) | Question 23 - GeeksforGeeks

10 Sep, 2018
While inserting the elements 71, 65, 84, 69, 67, 83 in an empty binary search tree (BST) in the sequence shown, the element in the lowest level is
(A) 65(B) 67(C) 69(D) 83Answer: (B)Explanation: Here is The Insertion Algorithm For a Binary Search Tree :
Insert(Root,key)
{
    if(Root is NULL)
        Create a Node with value as key and return
    Else if(Root.key >= key)
        Insert(Root.left,key)
    Else
        Insert(Root.right,key)
}

Creating the BST one by one using the above algorithm in the below given image :
This solution is contributed by Pranjul Ahuja.Quiz of this Question
Parmod Jangra
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
\bigstar - Tex Command

\bigstar - Used to draw big star symbol.
{ \bigstar }
\bigstar command draws big star symbol.

\bigstar 

★



\bigstar 

★


\bigstar 

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Python | Pandas Series.dt.to_pydatetime

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.to_pydatetime() function return the data as an array of native Python datetime objects. Timezone information is retained if present.
Syntax: Series.dt.to_pydatetime()
Parameter : None
Returns : numpy.ndarray
Example #1: Use Series.dt.to_pydatetime() function to return the given series object as an array of native python datetime object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30',               '2010-1-1 09:25', '2019-12-31 00:00'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.to_pydatetime() function to return the data as an array of native Python datetime objects.
# return the series data as a # native python datetime dataresult = sr.dt.to_pydatetime()   # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.to_pydatetime() function has successfully returned the underlying data of the given series object as an array of native python datetime data.
Example #2 : Use Series.dt.to_pydatetime() function to return the given series object as an array of native python datetime object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 00:00', periods = 5, freq = 'D',                            tz = 'US / Central'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.to_pydatetime() function to return the data as an array of native Python datetime objects.
# return the series data as a # native python datetime dataresult = sr.dt.to_pydatetime()   # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.to_pydatetime() function has successfully returned the underlying data of the given series object as an array of native python datetime data.
Python pandas-series-datetime
Python-pandas
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
Introduction To PYTHON
Convert integer to string in Python
How to scrape all the text from body tag using Beautifulsoup in Python?

29 Jun, 2021
strings generator is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. One drawback of the string attribute is that it only works for tags with string inside it and returns nothing for tags with further tags inside it. Thus to resolve this issue, a strings generator is used to get all the strings inside a tag, recursively.
Syntax:  
tag.strings 
Below given examples explain the concept of strings in Beautiful Soup. Example 1: In this example, we are going to get the strings.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup # Create the documentdoc = "<body><b> Hello world </b><h1> New heading </h1><body>" # Initialize the object with the documentsoup = BeautifulSoup(doc, "html.parser") # Get the whole body tagtag = soup.body # Print each string recursivelyfor string in tag.strings:    print(string)
Output: 
 Hello world 
 New heading 
Example 2:
Python3
import requestsfrom bs4 import BeautifulSoup # url of the websitedoc = "https://www.geeksforgeeks.org" # getting response objectres = requests.get(doc) # Initialize the object with the documentsoup = BeautifulSoup(res.content, "html.parser") # Get the whole body tagtag = soup.body # Print each string recursivelyfor string in tag.strings:    print(string)
 
 
Output:  
 
 
simmytarika5
Python BeautifulSoup
Python web-scraping-exercises
Web-scraping
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
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
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
How to Print Prime Numbers in MS SQL Server?

16 Nov, 2021
In this article, we are going to print Prime numbers using MS SQL. Here we will be using 2 while loops statement for printing prime numbers.
 Steps 1: First we will DECLARE a variable I with initial value 2.
Query:
DECLARE @I INT=2
Step 2: Then we will DECLARE a variable PRIME with an initial value of 0 (this will set the value of PRIME).
Query:
DECLARE @PRIME INT=0
Step 3: Table Definition 
We will create a temporary table variable that will hold prime numbers (using DECLARE and TABLE keywords).
Query:
DECLARE @OUTPUT TABLE (NUM INT)
Step 4: Now we will use nested while loop, same as we write a program for prime numbers.
Query:
DECLARE @I INT=2
DECLARE @PRIME INT=0
DECLARE @OUTPUT TABLE (NUM INT)
WHILE @I<=100
BEGIN
    DECLARE @J INT = @I-1
    SET @PRIME=1
    WHILE @J>1
    BEGIN
        IF @I % @J=0
        BEGIN
            SET @PRIME=0
        END
        SET @J=@J-1
    END
    IF @PRIME =1
    BEGIN
        INSERT @OUTPUT VALUES (@I)
    END
    SET @I=@I+1
END
SELECT * FROM @OUTPUT
Explanation:
In the First while loop, we will DECLARE the initial value of I as 100, which means this loop will provide us the prime numbers between 2 and 100.
Now, we will declare J with the initial value as I-1. As shown in the above code.
Then, a second while loop will be inserted which will run until J is greater than 1.
if the statement is there with condition @I % @J = 0, which means when the remainder of I/J is 0 then PRIME will be set to 0, and the value of J is decremented by 1.
If at the end of loop PRIME is set to 1, then that number will be inserted in our OUTPUT TABLE using the below code.
Query:
INSERT @OUTPUT VALUES (@I)
And then another loop will start for the next number.
Step 5:  Suppose that  I have an initial value of 4, i.e I = 4.
Now in the second loop J will have an initial value of I-1 which is 3.
By 4%3 we will get 1 so Prime will be set to 1 as before and J is decremented by 1.
Now for 4%2, we will get 0, Now as per our condition, PRIME will be set to 0. Since 4 has more factors than 1 and itself, the loop will be started again with an incremented value of I, that is 5(I+1).
Output: Below output for I<=100 which means it will print prime numbers from 2 to 100.
Picked
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?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server
turtle.undo() function in Python

26 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to undo (repeatedly) the last turtle action. The number of available undo actions is determined by the size of the undobuffer. It doesn’t require any argument.
Syntax :
turtle.undo()

Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle  # set speedturtle.speed(1)  # motionturtle.forward(100)  # undo previous motionturtle.undo()
Output :
Example 2 :
Python3
# import packageimport turtle  # set turtleturtle.speed(1)turtle.up()turtle.setpos(-50,50)turtle.down()  # motionfor i in range(4):    turtle.forward(100)    turtle.right(90)      # undofor i in range(8):    turtle.undo()
Output :
Example 3 :
Python3
# import packageimport turtle  # set speedturtle.speed(1)  # loop for motionfor i in range(4):        # motion    turtle.forward(100)          # undo previous work    turtle.undo()          # turn    turtle.left(90)
Output :
Python-turtle
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
Perl | Getting the Number of Elements of an Array

18 Feb, 2019
An array in Perl is a variable used to store an ordered list of scalar values. An array variable is preceded by an “at” (@) sign. The size of an array can be determined using the scalar context on the array which returns the number of elements in the array
Example 1:
#!/usr/bin/perl  # Initializing the array@a = (1, 2, 3);  # Assigning the array to a scalar# variable which stores size of# the array$s = @a;  # Printing the sizeprint "Size of the Array is $s";
Size of the Array is 3

Above code returns the physical size of the array, not the number of valid elements. In order to obtain the maximum index of an array, ‘$#’ is used as shown in the example below:
Example 2:
#!/usr/bin/perl  # Initializing the array@a = (1, 2, 3);  # Store the value at any index# Let's take index 15 here,$a[15] = 20;  # Printing the Arrayprint "Array is @a";  # Getting the maximum index # of the array$i = $#a;  # Printing the Max. Indexprint "\nMaximum index is $i";
Array is 1 2 3             20
Maximum index is 15

Here is how the above code works:-Step1: Initializing an array with some valuesStep2: Assigning a value at any random index leaving the other indices blankStep3: Printing the array to show the blank spaces left in the arrayStep4: To get the maximum index ‘$#’ is usedStep5: Further, print the maximum index
Perl-Arrays
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filtering a row in PySpark DataFrame based on matching values from a list

28 Jul, 2021
In this article, we are going to filter the rows in the dataframe based on matching values in the list by using isin in Pyspark dataframe
isin(): This is used to find the elements contains in a given dataframe, it will take the elements and get the elements to match to the data
Syntax: isin([element1,element2,.,element n])
Create Dataframe for demonstration:
Python3
# importing moduleimport pyspark  # importing sparksessionfrom pyspark.sql import SparkSession  # creating sparksession# and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of students  data  with null values# we can define null values with nonedata = [[1, "sravan", "vignan"],        [2, "ramya", "vvit"],        [3, "rohith", "klu"],        [4, "sridevi", "vignan"],        [5, "gnanesh", "iit"]]  # specify column namescolumns = ['ID', 'NAME', 'college']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)  dataframe.show()
Output:
It is used to check the condition and give the results, Both are similar
Syntax: dataframe.filter(condition)
Where, condition is the dataframe condition.
Here we will use all the discussed methods.
Syntax: dataframe.filter((dataframe.column_name).isin([list_of_elements])).show()
where,
column_name is the column
elements are the values that are present in the column
show() is used to show the resultant dataframe
Example 1: Get the particular ID’s with filter() clause.
Python3
# get the ID : 1,2,3 from dataframedataframe.filter((dataframe.ID).isin([1,2,3])).show()
Output:
Example 2: Get ID’s not present in 1 and 3
Python3
# get the ID : not in 1 and 3 from dataframedataframe.filter(~(dataframe.ID).isin([1, 3])).show()
Output:
Example 3: Get names from dataframe.
Python3
# get name as sravandataframe.filter((  dataframe.NAME).isin(['sravan'])).show()
Output:
where() is used to check the condition and give the results
Syntax: dataframe.where(condition)
where, condition is the dataframe condition
Overall Syntax with where clause:
dataframe.where((dataframe.column_name).isin([elements])).show()
where,
column_name is the column
elements are the values that are present in the column
show() is used to show the resultant dataframe
Example: Get the particular colleges with where() clause
Python3
# get college as vignandataframe.where((  dataframe.college).isin(['vignan'])).show()
Output:
Picked
Python-Pyspark
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
Tryit Editor v3.7

Tryit: HTML semantics
All permutations of a string using iteration?

In this section we will see how to get all permutations of a string. The recursive approach is very simple. It uses the back-tracking procedure. But here we will use the iterative approach.
All permutations of a string ABC are like {ABC, ACB, BAC, BCA, CAB, CBA}. Let us see the algorithm to get the better idea.
begin
   sort the characters of the string
   while true, do
      print the string str
      i := length of str – 1
      while str[i - 1] >= str[i], do
         i := i – 1
         if i is 0, then
            return
         end if
      done
      j := length of str – 1
      while j > i AND str[j] <= str[i – 1], do
         j := j – 1
      done
      exchange the characters from position str[i - 1], str[j]
      reverse the string.
   done
end
 Live Demo
#include <iostream>
#include <algorithm>
using namespace std;
void getAllPerm(string str){
   sort(str.begin(), str.end());
   while (true){
      cout << str << endl;
      int i = str.length() - 1;
      while (str[i-1] >= str[i]){
         if (--i == 0)
         return;
      }
      int j = str.length() - 1;
      while (j > i && str[j] <= str[i - 1])
      j--;
      swap(str[i - 1], str[j]);
      reverse (str.begin() + i, str.end());
   }
}
int main(){
   string str = "WXYZ";
   getAllPerm(str);
}
WXYZ
WXZY
WYXZ
WYZX
WZXY
WZYX
XWYZ
XWZY
XYWZ
XYZW
XZWY
XZYW
YWXZ
YWZX
YXWZ
YXZW
YZWX
YZXW
ZWXY
ZWYX
ZXWY
ZXYW
ZYWX
ZYXW
How to remove a member from the local group using PowerShell?

To remove a member from the local group using PowerShell, we can use the RemoveLocalGroupMember command. This command is available in the module Microsoft.PowerShell.LocalAccounts in and above PowerShell version 5.1.
To use this command, we need to provide two parameter values. One is the -Group (Local Group Name) and the second is -Member (Name of the Member to remove). For example,
Remove-LocalGroupMember -Group Administrators -Member TestUser
The above command will remove TestUser from the local group Administrators.
To use the above command on the remote computer, we need to use Invoke-Command. For example,
Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{
   Remove-LocalGroupMember -Group "Administrators" -Member "LabDomain\Alpha"
}
The above command will remove LabDomain\Alpha user from the local Administrators group on remote computers.
If you don’t have the LocalAccounts module available or the PowerShell version is below 5.1 then you can use the cmd command as shown below.
net localgroup Administrators labdomain\alpha /delete
In the above example, labdomain\alpha will be removed from the local group Administrators using cmd command. You can execute this command remotely using Invoke-Command method,
Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{
   net localgroup Administrators labdomain\alpha /delete
}
C program for a number to be expressed as a sum of two prime numbers.

Find out if a given number can be expressed as sum of two prime numbers or not.
Given a positive integer N, we need to check if the number N can be represented as a sum of two prime numbers.
Consider an example given below −
20 can be expressed as sum of two prime numbers 3 and 17, 13 and 7.
20= 3+7
20= 13+7
Refer an algorithm given below for expressing a given number as a sum of two prime numbers.
Step 1 − Input the number to be checked at run time.
Step 2 − Repeat from i = 2 to (num/2).
Step 3 − Check i is a prime number.
Step 4 − If i is prime, check if (n - i) is a prime number.
Step 5 − If both (i)and (n - i) are primes, then, the given number can be represented as the sum of primes i and (n - i).
Following is the C program for expressing a given number as a sum of two prime numbers −
 Live Demo
#include <stdio.h>
int Sum(int n);
int main(){
   int num, i;
   printf("Enter number: ");
   scanf("%d", &num);
   int flag = 0;
   for(i = 2; i <= num/2; ++i){
      if (sum(i) == 1){
         if (sum(num-i) == 1){
            printf("\nThe given %d can be expressed as the sum of %d and %d\n\n", num, i, num - i);
            flag = 1;
         }
      }
   }
   if (flag == 0)
   printf("The given %d cannot be expressed as the sum of two prime numbers\n", num);
   return 0;
}
//check if a number is prime or not
int sum(int n){
   int i, isPrime = 1;
   for(i = 2; i <= n/2; ++i){
      if(n % i == 0){
         isPrime = 0;
         break;
      }
   }
   return isPrime;
}
When the above program is executed, it produces the following output −
Run 1:
Enter number: 34
The given 34 can be expressed as the sum of 3 and 31
The given 34 can be expressed as the sum of 5 and 29
The given 34 can be expressed as the sum of 11 and 23
The given 34 can be expressed as the sum of 17 and 17
Run 2:
Enter number: 11
The given 11 cannot be expressed as the sum of two prime numbers
How to find the unique values in a column of an R data frame?

Categorical variables have multiple categories but if the data set is large and the categories are also large in numbers then it becomes a little difficult to recognize them. Therefore, we can extract unique values for categorical variables that will help us to easily recognize the categories of a categorical variable. We can do this by using unique for every column of an R data frame.
Consider the below data frame −
> x1<-rep(c("A","B","C","D"),each=5)
> x2<-rep(c(5,10,15,20),times=c(2,8,6,4))
> x3<-rep(c("India","Russia","China","Indonesia","Iceland"),times=c(4,3,5,2,6))
> x4<-rep(c(letters[1:10]),times=2)
> df<-data.frame(x1,x2,x3,x4)
> df
   x1 x2  x3     x4
1  A  5 India     a
2  A  5 India     b
3  A 10 India     c
4  A 10 India     d
5  A 10 Russia    e
6  B 10 Russia    f
7  B 10 Russia    g
8  B 10 China     h
9  B 10 China     i
10 B 10 China     j
11 C 15 China     a
12 C 15 China     b
13 C 15 Indonesia c
14 C 15 Indonesia d
15 C 15 Iceland   e
16 D 15 Iceland   f
17 D 20 Iceland   g
18 D 20 Iceland   h
19 D 20 Iceland   i
20 D 20 Iceland   j
Finding the unique values in column x1 −
> unique(df[c("x1")])
x1
1 A
6 B
11 C
16 D
Finding the unique values in column x2 −
> unique(df[c("x2")])
x2
1 5
3 10
11 15
17 20
Finding the unique values in column x3 −
> unique(df[c("x3")])
x3
1 India
5 Russia
8 China
13 Indonesia
15 Iceland
Finding the unique values in column x4 −
> unique(df[c("x4")])
x4
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
10 j
How to update field to add value to existing value in MySQL?

You can update field to add value to an existing value with the help of UPDATE and SET command. The syntax is as follows −
UPDATE yourTableName SET yourColumnName = yourColumnName+integerValueToAdd WHERE yourCondition;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table addingValueToExisting
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(30),
   -> GameScore int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.58 sec)
Insert records in the table using insert command. The query is as follows −
mysql> insert into addingValueToExisting(Name,GameScore) values('John',89);
Query OK, 1 row affected (0.11 sec)

mysql> insert into addingValueToExisting(Name,GameScore) values('Mike',56);
Query OK, 1 row affected (0.28 sec)

mysql> insert into addingValueToExisting(Name,GameScore) values('Sam',99);
Query OK, 1 row affected (0.18 sec)

mysql> insert into addingValueToExisting(Name,GameScore) values('Carol',100);
Query OK, 1 row affected (0.17 sec)

mysql> insert into addingValueToExisting(Name,GameScore) values('David',67);
Query OK, 1 row affected (0.25 sec)

mysql> insert into addingValueToExisting(Name,GameScore) values('Bob',78);
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from addingValueToExisting;
The following is the output −
+----+-------+-----------+
| Id | Name  | GameScore |
+----+-------+-----------+
| 1  | John  |        89 |
| 2  | Mike  |        56 |
| 3  | Sam   |        99 |
| 4  | Carol |       100 |
| 5  | David |        67 |
| 6  | Bob   |        78 |
+----+-------+-----------+
6 rows in set (0.00 sec)
Update field to add a value to existing value. For our example, let us update 100 with the value 110 by adding 10. The query is as follows −
mysql> update addingValueToExisting set GameScore = GameScore+10 where Id = 4;
Query OK, 1 row affected (0.23 sec)
Rows matched − 1 Changed − 1 Warnings − 0
Check the specific record has been updated or not. The query is as follows −
mysql> select *from addingValueToExisting where Id = 4;
The following is the output −
+----+-------+-----------+
| Id | Name  | GameScore |
+----+-------+-----------+
| 4  | Carol | 110       |
+----+-------+-----------+
1 row in set (0.00 sec)
Look at the above output, the value 100 is incremented by 10, which is now 110.
Difference between DELETE and DROP in SQL - GeeksforGeeks

19 Aug, 2019
Prerequisite – SQL CommandsDELETE is a Data Manipulation Language (DML) command and used when you want to remove some or all the tuples from a relation. If WHERE clause is used along with the DELETE command it removes only those tuples which satisfy the WHERE clause condition but if WHERE clause is missing from the DELETE statement then by default all the tuples present in relation are removed.
The syntax of DELETE command:
DELETE FROM relation_name 
WHERE condition;
DROP is a Data Definition Language (DDL) command which removes the named elements of the schema like relations, domains or constraints and you can also remove an entire schema using DROP command.
The syntax of DROP command:
DROP SCHEMA schema_name RESTRICT;
DROP Table table_name CASCADE;
Comparison Chart:
NikhilKoyikkamannil
DBMS-SQL
DBMS
SQL
Technical Scripter
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of Functional dependencies in DBMS
Introduction of Relational Algebra in DBMS
KDD Process in Data Mining
Structure of Database Management System
Difference between File System and DBMS
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
How to get connected remote desktop users on computers using PowerShell?

To get the user sessions on the remote computers using PowerShell, we need to use the cmd query command. First of all, we will get the user sessions on the local computer using the below command.
query session
Let’s see what are other supported parameters for the query session command.
PS C:\> query session /?
Display information about Remote Desktop Services sessions.

QUERY SESSION [sessionname | username | sessionid]
              [/SERVER:servername] [/MODE] [/FLOW] [/CONNECT] [/COUNTER] [/VM]

sessionname         Identifies the session named sessionname.
username            Identifies the session with user username.
sessionid           Identifies the session with ID sessionid.
/SERVER:servername  The server to be queried (default is current).
/MODE               Display current line settings.
/FLOW               Display current flow control settings.
/CONNECT            Display current connect settings.
/COUNTER            Display current Remote Desktop Services counters information.
/VM                 Display information about sessions within virtual machines.
To get the sessions on the remote computers, we can use /Server:ServerName switch.
query session /server:Test1-win2k12
How to remove pagefile on the specific drive using PowerShell?

In this article, we have a pagefile set on E: (System managed) and we need to remove the pagefile from E: So in the below image once we remove it, the pagefile should be “No Paging File”.
To do so using PowerShell, we need to filter the pagefile on a specific drive and need to run the below code.
$pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'}
$pagefileset.Delete()
You may want to reboot the server after removing pagefile.
To change the above settings on the remote computer, use -ComputerName parameter in the GetWMIObject class.
Explain how L1 Normalization can be implemented using scikit-learn library in Python?

The process of converting a range of values into standardized range of values is known as normalization. These values could be between -1 to +1 or 0 to 1. Data can be normalized with the help of subtraction and division as well.
Data fed to the learning algorithm as input should remain consistent and structured. All features of the input data should be on a single scale to effectively predict the values. But in real-world, data is unstructured, and most of the times, not on the same scale.
This is when normalization comes into picture. It is one of the most important data-preparation process.
It helps in changing values of the columns of the input dataset to fall on a same scale.
During the process of normalization, the range of values are ensured to be non-distorted.
Note − Not all input dataset fed to machine learning algorithms have to be normalized. Normalization is required only when features in a dataset have completely different scale of values.
There are different kinds of normalization −
Min-Max normalization
Z Normalization
Unit Vector Normalization
Let us understand how L1 normalization works.
Also known as Least Absolute Deviations, it changes the data such that the sum of the absolute values remains as 1 in every row.
Let us see how L1 Normalization can be implemented using scikit learn in Python −
import numpy as np
from sklearn import preprocessing
input_data = np.array(
   [[34.78, 31.9, -65.5],[-16.5, 2.45, -83.5],[0.5, -87.98, 45.62],[5.9, 2.38, -55.82]]
)
data_normalized_l1 = preprocessing.normalize(input_data, norm='l1')
print("\nL1 normalized data is \n", data_normalized_l1)
L1 normalized data is
[[ 0.26312604 0.24133757 -0.49553639]
[-0.16105417 0.0239141 -0.81503172]
[ 0.00372856 -0.65607755 0.34019389]
[ 0.09204368 0.03712949 -0.87082683]]
The required packages are imported.
The required packages are imported.
The input data is generated using the Numpy library.
The input data is generated using the Numpy library.
The ‘normalize’ function present in the class ‘preprocessing‘ is used to normalize the data.
The ‘normalize’ function present in the class ‘preprocessing‘ is used to normalize the data.
The type of normalization is specified as ‘l1’.
The type of normalization is specified as ‘l1’.
This way, any data in the array gets normalized and the sum of every row would be 1 only.
This way, any data in the array gets normalized and the sum of every row would be 1 only.
This normalized data is displayed on the console.
This normalized data is displayed on the console.
Find largest document size in MongoDB?

To find the largest document size in MongoDB, you need to write a script in the shell.
To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.largestDocumentDemo.insertOne({"StudentName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ed2e32f684a30fbdfd57d")
}
> db.largestDocumentDemo.insertOne({"StudentName":"Carol","StudentAge":22,"StudentCountryName":"US","TechnicalSubject":["C","C++","Java","MySQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ed3282f684a30fbdfd57e")
}
> db.largestDocumentDemo.insertOne({"StudentName":"Mike","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ed3382f684a30fbdfd57f")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.largestDocumentDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8ed2e32f684a30fbdfd57d"), "StudentName" : "John" }
{
   "_id" : ObjectId("5c8ed3282f684a30fbdfd57e"),
   "StudentName" : "Carol",
   "StudentAge" : 22,
   "StudentCountryName" : "US",
   "TechnicalSubject" : [
      "C",
      "C++",
      "Java",
      "MySQL"
   ]
}
{
   "_id" : ObjectId("5c8ed3382f684a30fbdfd57f"),
   "StudentName" : "Mike",
   "StudentAge" : 22
}
Here is the query to find the largest document size in MongoDB −
> var largestDocumentSize = 0;
> db.largestDocumentDemo.find().forEach(function(myObject) {
   ... var currentDocumentSize = Object.bsonsize(myObject);
   ... if(largestDocumentSize < currentDocumentSize ) {
      ... largestDocumentSize = currentDocumentSize ;
   ... }
... });
> print('The Largest Document Size =' + ' ' +largestDocumentSize);
The following is the output displaying the largest document size −
The Largest Document Size = 160
How to setup MongoDB Java environment?

Visit the MongoDB home page, in the Software (dropdown), select Community Server.
Visit the MongoDB home page, in the Software (dropdown), select Community Server.
In the MongoDB Community Server page, specify the platform details and download the MongoDB server compatible to your platform.
In the MongoDB Community Server page, specify the platform details and download the MongoDB server compatible to your platform.
Install the downloaded software and create a folder/directory named data in the C drive to store the database files.
Install the downloaded software and create a folder/directory named data in the C drive to store the database files.
Set the path (environmental variable) for the bin directory of MongoDB i.e. C:\Program Files\MongoDB\Server\4.2\bin>
Set the path (environmental variable) for the bin directory of MongoDB i.e. C:\Program Files\MongoDB\Server\4.2\bin>
Open a command prompt and run the MongoDB server by executing the mongod command as shown below −
Open a command prompt and run the MongoDB server by executing the mongod command as shown below −
C:\Users\Tutorialspoint>mongod --dbpath "C:\data"
Open another command prompt connect to the server by running the mongo command this will give you MongoDB shell and from this, you can
Open another command prompt connect to the server by running the mongo command this will give you MongoDB shell and from this, you can
From MongoDB shell, you can manipulate data in the database.
From MongoDB shell, you can manipulate data in the database.
For testing the setup, try connecting to a database named my database using the use command. If your setup is successful you will get the following result.
> use myDatabase;
switched to db myDatabase
To set up a MongoDB java environment in eclipse you need to create a Java – Maven project and, add the following dependency to its pom.xml file.
<dependency>
   <groupId>org.mongodb</groupId>
   <artifactId>mongo-java-driver</artifactId>
   <version>3.12.2</version>
</dependency>
Following JDBC program connects with a database on MongoDB, try executing it −
import com.mongodb.MongoClient;
public class ConnectToDB {
   public static void main( String args[] ) {
      //Creating a MongoDB client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Accessing the database
      mongo.getDatabase("myDatabase");
      System.out.println("Connected to the database successfully");
   }
}
If everything goes fine the above program generates the following output −
Connected to the database successfully
MFC - Standard I/O

The MFC library provides its own version of file processing. This is done through a class named CStdioFile. The CStdioFile class is derived from CFile. It can handle the reading and writing of Unicode text files as well as ordinary multi-byte text files.
Here is the list of constructors, which can initialize a CStdioFile object −
CStdioFile();
CStdioFile(CAtlTransactionManager* pTM);
CStdioFile(FILE* pOpenStream);
CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags);
CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags, CAtlTransactionManager* pTM);
Here is the list of methods in CStdioFile −
Open
Overloaded. Open is designed for use with the default CStdioFile constructor (Overrides CFile::Open).
ReadString
Reads a single line of text.
Seek
Positions the current file pointer.
WriteString
Writes a single line of text.
Let us look into a simple example again by creating a new MFC dialog based application.
Step 1 − Drag one edit control and two buttons as shown in the following snapshot.
Step 2 − Add value variable m_strEditCtrl for edit control.
Step 3 − Add click event handler for Open and Save buttons.
Step 4 − Here is the implementation of event handlers.
void CMFCStandardIODlg::OnBnClickedButtonOpen() {
   
   // TODO: Add your control notification handler code here
   UpdateData(TRUE);

   CStdioFile file;
   file.Open(L"D:\\MFCDirectoryDEMO\\test.txt", CFile::modeRead | CFile::typeText);
   
   file.ReadString(m_strEditCtrl);
   file.Close();
   UpdateData(FALSE);
}

void CMFCStandardIODlg::OnBnClickedButtonSave() {
   
   // TODO: Add your control notification handler code here
   UpdateData(TRUE);
   CStdioFile file;
   if (m_strEditCtrl.GetLength() == 0) {

      AfxMessageBox(L"You must specify the text.");
      return;
   }
   file.Open(L"D:\\MFCDirectoryDEMO\\test.txt", CFile::modeCreate |
      CFile::modeWrite | CFile::typeText);
   file.WriteString(m_strEditCtrl);
   file.Close();
}
Step 5 − When the above code is compiled and executed, you will see the following output.
Step 6 − Write something and click Save. It will save the data in *.txt file.
Step 7 − If you look at the location of the file, you will see that it contains the test.txt file.
Step 8 − Now, close the application. Run the same application. When you click Open, the same text loads again.
Step 9 − It starts by opening the file, reading the file, followed by updating the Edit Control.
 Print
 Add Notes
 Bookmark this page
How to create boxplot for multiple categories with long names in base R?

In base R, we use boxplot function to create the boxplots but if we have categorical vector and the corresponding numerical vector then the boxplot can be easily created. For this purpose, we should save those vectors in a data frame and use the $ operator and las = 2 argument to create the boxplot as shown in the below example.
Consider the below vectors:
Countries<−sample(c("China","India","Canada","USA","Russia","Indonesia","Nepal"),5000,replace=TRUE)
> Rate<−rnorm(5000,10,1)
Create the data frame using above vectors −
df<−data.frame(Countries,Rate)
> head(df,20)
Countries    Rate
1 Russia    9.885246
2 Nepal     9.895285
3 USA      11.524113
4 Nepal    10.133226
5 Indonesia 9.711389
6 Russia    10.017597
7 Nepal      9.204832
8 Russia     8.436829
9 Russia    10.579013
10 Canada    7.984238
11 Canada    9.407908
12 Indonesia 9.047598
13 China     9.193126
14 India     8.524555
15 China    10.398155
16 India     6.926581
17 China    10.104521
18 Canada   10.178826
19 India    12.006973
20 Canada   10.371956
Creating boxplot for countries −
boxplot(df$Rate~df$Countries)
Creating boxplot for countries by changing the printing direction of country’s name −
boxplot(df$Rate~df$Countries,las=2,xlab="")
What does the Double Star operator mean in Python?

For numeric data types double asterisk (**) is defined as exponentiation operator
>>> a=10; b=2
>>> a**b
100
>>> a=1.5; b=2.5
>>> a**b
2.7556759606310752
>>> a=3+2j
>>> b=3+5j
>>> a**b
(-0.7851059645317211+2.350232331971346j)
In a function definition, argument with double asterisks as prefix helps in sending multiple keyword arguments to it from calling environment
>>> def function(**arg):
    for i in arg:
      print (i,arg[i])

>>> function(a=1, b=2, c=3, d=4)
a 1
b 2
c 3
d 4
How do I create an automatically updating GUI using Tkinter?

Using Tkinter, we can create GUI which can be configured for auto-updation. For
this purpose, we will create GUI-based clocks that will automatically get refreshed
when the time changes. We will display the clock along with the day and TimeZone.
First, we will import the tkinter library in the notebook, then we will create a function which creates instances of current time and day using the “strftime” function.
#Import the tkinter library
from tkinter import *
import time
#Create an instance of the canvas
win = Tk()

#Select the title of the window
win.title("tutorialspoint.com")

#Define the geometry of the window
win.geometry("600x400")
#Define the clock which
def clock():
   hh= time.strftime("%I")
   mm= time.strftime("%M")
   ss= time.strftime("%S")
   day=time.strftime("%A")
   ap=time.strftime("%p")
   time_zone= time.strftime("%Z")
   my_lab.config(text= hh + ":" + mm +":" + ss)
   my_lab.after(1000,clock)

   my_lab1.config(text=time_zone+" "+ day)
#Update the Time
def updateTime():
   my_lab.config(text= "New Text")

#Creating the label with text property of the clock
my_lab= Label(win,text= "",font=("sans-serif", 56), fg= "red")
my_lab.pack(pady=20)
my_lab1= Label(win, text= "", font=("Helvetica",20), fg= "blue")
my_lab1.pack(pady= 10)

#Calling the clock function
clock()
#Keep Running the window

win.mainloop()
Running the above code will create an automatically updated GUI Application in the window.
How can I delete an element in Selenium using Python?

We can delete an element in Selenium webdriver using Python with the help of JavaScript Executor. Selenium is not capable of modifying the structure of DOM directly.
It has the feature of injecting JavaScript into the webpage and changing the DOM with the help execute_script method. The JavaScript command to be used is passed as a parameter to this method.
JavaScript command to delete an element is −
var l = document.getElementsByClassName("tp-logo")[0];
l.parentNode.removeChild(l);
The above script is to be passed as a parameter to the execute_script method.
Let us try to remove the highlighted logo from the below page −
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
#implicit wait
driver.implicitly_wait(0.5)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#delete element with JavaScript Executor
driver.execute_script("""
   var l = document.getElementsByClassName("tp-logo")[0];
   l.parentNode.removeChild(l);
""")