code-rag-bench/online-tutorials huggingface dataset:
swap() in C++

06 Jul, 2022
The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables.
Syntax:
swap(a, b)

Parameters: The function accepts two mandatory parameters a and b which are to be swapped. The parameters can be of any data type.
Return Value: The function does not return anything, it swaps the values of the two variables.
Programs below illustrate the swap() function:
Program 1:
// C++ program for illustration of swap() function#include <bits/stdc++.h>using namespace std;  int main(){    int a = 10;    int b = 20;    cout << "Value of a before: " << a << endl;    cout << "Value of b before: " << b << endl;      // swap values of the variables    swap(a, b);    cout << "Value of a now: " << a << endl;    cout << "Value of b now: " << b << endl;    return 0;}
Value of a before: 10
Value of b before: 20
Value of a now: 20
Value of b now: 10

Program 2:
#include <bits/stdc++.h>using namespace std;  int main(){    string a = "Geeks";    string b = "function";    cout << "Value of a before: " << a << endl;    cout << "Value of b before: " << b << endl;    swap(a, b);    cout << "Value of a now: " << a << endl;    cout << "Value of b now: " << b << endl;    return 0;}
Value of a before: Geeks
Value of b before: function
Value of a now: function
Value of b now: Geeks

mhgeeksforgeeks
CPP-Functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python PIL | Image filter with ImageFilter module

25 Jun, 2019
The ImageFilter module contains definitions for a pre-defined set of filters, which can be be used with the Image.filter() method.
Image used:
Filters –The current version of the library provides the set of predefined image enhancement filters:
1. BLUR
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter  # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")  # applying the blur filterim2 = im1.filter(ImageFilter.BLUR)  im2.show()
Output: 2. CONTOUR
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter  # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")  # applying the contour filterim2 = im1.filter(ImageFilter.CONTOUR)  im2.show()
Output: 3. EMBOSS
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter  # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")  # applying the emboss filterim2 = im1.filter(ImageFilter.EMBOSS)  im2.show()
Output: 4. EDGE_ENHANCE
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter  # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")  # applying the EDGE_ENHANCE filterim2 = im1.filter(ImageFilter.EDGE_ENHANCE)  im2.show()
Output: 5. EDGE_ENHANCE_MORE
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter  # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")  # applying the EDGE_ENHANCE_MORE filterim2 = im1.filter(ImageFilter.EDGE_ENHANCE_MORE)  im2.show()
Output:
python-utility
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
Introduction To PYTHON
Convert integer to string in Python
How to find an element based on a data-attribute value using jQuery

To find an element based on a data-attribute value using jQuery is quite easy. Try to run the following code to find an element based on a data-attribute value −
Live Demo
<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
   $(document).ready(function() {
     $('[data-slide="0"]').addClass('demo');
   });
</script>
<style>
.demo {
    font-size: 150%;
    color: red;
}
</style>
</head>
<body>

<p data-slide="0">Rocky</p>
<p data-slide="1">Amit</p>
<p data-slide="2">John</p>

</body>
</html>
SVG <symbol> Element - GeeksforGeeks

31 Mar, 2022
SVG stands for Scalable Vector Graphic. It can be used to make graphics and animations like in HTML canvas.
The SVG <symbol> element is used to define graphical template objects which can be instantiated by the <use> element. The use of symbol elements for graphics that are used multiple times in the same document adds structure and semantics.
Syntax:
<symbol attribute="" >
    content Here
</symbol>

Attribute:
x: x-axis coordinates the positioning of the image.
y: y-axis coordinates the positioning of the image.
width: Width of the image.
height: Height of the image.
viewBox: Bound of the SVG element.
Global Attributes: Some global attributes used like core attributes and styling attributes, etc.
Example 1:
<!DOCTYPE html><html>  <body>    <svg width="400" height="400"        xmlns="http://www.w3.org/2000/svg">        <symbol id="circ"                 width="10"                 height="10"                 viewBox="0 0 2 2">            <circle cx="1" cy="1" r="1" />        </symbol>                         <use xlink:href="#circ" x="5"  y="5"/>    </svg></body>  </html>
Output: A dot symbol.
Example 2:
<!DOCTYPE html><html>  <body>    <svg viewBox="0 0 80 20"        xmlns="http://www.w3.org/2000/svg">        <symbol id="circ"                 width="10"                 height="10"                 viewBox="0 0 2 2">            <rect height="10" width="10" />        </symbol>                         <use xlink:href="#circ" x="5"              y="5" opacity="0.5" fill="green"/>    </svg></body>  </html>
Output:
Supported Browsers: The following browsers are supported by this SVG element:
Chrome
Edge
Firefox
Safari
Internet Explorer
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-SVG
SVG-Element
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Python - Group each increasing and decreasing run in list - GeeksforGeeks

06 Jun, 2021
Given a list, the task is to write a Python program to group each increasing and decreasing run.  This is known as a monotonous grouping. A list is monotonic if it is either monotone increasing or monotone decreasing. A list A is monotone decreasing if for all i <= j, A[i] >= A[j].
Example:
Input : test_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2]
Output : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1], [11, 12], [2]]
Explanation : 6 > 5 and then 2 is smaller than 6, hence becomes decreasing and new group is started. 2 and 9 being peak or transit elements, belong to individual groups.
Input : test_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1]
Output : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1]]
Explanation : 6 > 5 and then 2 is smaller than 6, hence becomes decreasing and new group is started. 2 and 9 being peak or transit elements, belong to individual groups.
Example : Using loop  + zip()
In this, every two lists each starting from 0th and 1st index are zipped, and then each element from both are compared to check run and change flag accordingly. Initial flag value is evaluated on basis of which of the first 2 elements is greater, post that flag is toggled to have appropriate run grouping.
Python3
# Python3 code to demonstrate working of# Monotonous grouping in List# Using loop + zip()  # initializing listtest_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2]               # printing original listprint("The original list is : " + str(test_list))  res = []temp = []is_up = True if test_list[0] > test_list[1]:    is_up = Falsefor curr, nex in zip(test_list, test_list[1:]):    temp.append(curr)          # checking for increasing or decreasing to change list    if (nex > curr and not is_up) or (nex < curr and is_up):        res.append(temp)        temp = []                  # toggling         is_up = not is_up  temp.append(nex)res.append(temp)  # printing resultprint("Monotonous grouping : " + str(res))
Output:
The original list is : [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2]
Monotonous grouping : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1], [11, 12], [2]]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
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 | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to test if a parameter is provided to a function in JavaScript?

To test if a parameter is provided by a function, use the if condition and check with “undefined”.
Following is the code −
function checkingParameter(parameter) {
   if (parameter !== undefined) {
      console.log("Parameter is provided.");
   } else {
      console.log("Parameter is not provided.")
   }
}
checkingParameter();
checkingParameter("JavaScript");
To run the above program, you need to use the below command −
node fileName.js.
Here, my file name is demo327.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo327.js
Parameter is not provided.
Parameter is provided.
Python 3 - List len() Method

The len() method returns the number of elements in the list.
Following is the syntax for len() method −
len(list)

list − This is a list for which number of elements to be counted.
This method returns the number of elements in the list.
The following example shows the usage of len() method.
#!/usr/bin/python3

list1 = ['physics', 'chemistry', 'maths']
print (len(list1))

list2 = list(range(5)) #creates list of numbers between 0-4
print (len(list2))
When we run above program, it produces the following result −
Program to find the Area of a Parallelogram

20 Jun, 2022
Given the sides of a Parallelogram, task is calculate the area of a Parallelogram. 
Examples:  
Input: base = 30, height = 40
Output: 1200.000000
    As Area of parallelogram = base * height,
    Therefore, Area = 30 * 40 = 1200.00
Approach: 
Area of parallelogram = base * height
Below is the implementation of the above approach: 
C++
C
Java
Python
C#
PHP
Javascript
#include <iostream>using namespace std; // function to calculate the areafloat CalArea(float base, float height){    return (base * height);}// driver codeint main(){    float base, height, Area;    base = 30;    height = 40;     // function calling    Area = CalArea(base, height);    // displaying the area    cout << "Area of Parallelogram is :" << Area;    return 0;}
#include <stdio.h> // function to calculate the areafloat CalArea(float base, float height){    return (base * height);} // driver codeint main(){    float base, height, Area;    base = 30;    height = 40;     // function calling    Area = CalArea(base, height);     // displaying the area    printf("Area of Parallelogram is : %f\n", Area);    return 0;}
public class parallelogram {    public static void main(String args[])    {        int base = 30;        int height = 40;         // formula for calculating the area        int area_parallelogram = base * height;         // displayin g the area        System.out.println("Area of the parallelogram = " + area_parallelogram);    }}
base = 30height = 40  # formula for finding the areaarea_parallelogram = base * height # displaying the outputprint("Area of the parallelogram = "+str(area_parallelogram))
using System;class parallelogram{public static void Main(){    int b_ase = 30;    int height = 40;     // formula for calculating the area    int area_parallelogram = b_ase * height;     // displayin g the area    Console.WriteLine("Area of the parallelogram = " +                                  area_parallelogram);}} // This code is contributed by vt_m
<?php      $base = 30;    $height = 40;    $area_parallelogram=$base*$height;     echo "Area of the parallelogram = ";     echo $area_parallelogram; ?>
<script> let base = 30;let height = 40;let area_parallelogram=base*height;document.write( "Area of the parallelogram = ");document.write(area_parallelogram.toFixed(6));     // This code is contributed by Bobby </script>
Area of Parallelogram is : 1200.000000
 
Time Complexity: O(1)
Auxiliary Space: O(1)
vt_m
gottumukkalabobby
ajaymakvana
area-volume-programs
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Minimum number of jumps to reach end
Find minimum number of coins that make a given value
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
PostgreSQL – POSITION Function

01 Feb, 2021
The PostgreSQL POSITION() function returns the location of a substring in a string.
Syntax: POSITION(substring in string)
Let’s analyze the above syntax:
The substring argument is the string that is to be located.
The string argument represents the string for which the substring is to be searched.
The POSITION() function returns the location of the searched substring in integer form that represents the location of the substring within the string. It returns zero (0) if no matching substring found.
Example 1:
The following statement returns the position of the ‘Tutorial’ in the string ‘GeeksForGeeks Tutorial’:
SELECT POSITION('Tutorial' IN 'GeeksForGeeks Tutorial');
Output:
Example 2:
The POSITION() function returns the location of the first instance of the substring in the strings shown in the below example:
SELECT POSITION('am' IN 'I am a geek');
Output:
PostgreSQL-function
PostgreSQL-String-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - IF Statement
PostgreSQL - DROP TABLE
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Rename Table
PostgreSQL - Joins
PostgreSQL - Variables
PostgreSQL - REPLACE Function
PostgreSQL - Introduction to Stored Procedures
PostgreSQL - CREATE SEQUENCE
Delete Duplicates in MS SQL Server

08 Sep, 2020
Duplicate values in any table might be due to the poor table design or unwanted data from other sources. To delete the duplicate data from the table in SQL Server, follow the below steps –
Find duplicate rows.Use DELETE statement to remove the duplicate rows.
Find duplicate rows.
Use DELETE statement to remove the duplicate rows.
Let us create a table named Geek –
CREATE TABLE Geek(
Name NVARCHAR(100) NOT NULL,
Email NVARCHAR(255) NOT NULL,
City NVARCHAR(100) NOT NULL);
Let us insert some values into the table Geek –
INSERT INTO Geek (Name, Email, City) VALUES
('Nisha', 'nisha@gfg.com', 'Delhi'),
('Megha', 'megha@gfg.com', 'Noida'),
('Khushi', 'khushi@gfg.com', 'Jaipur'),
('Khushi', 'khushi@gfg.com', 'Jaipur'),
('Khushi', 'khushi@gfg.com', 'Jaipur'),
('Hina', 'hina@gfg.com', 'Kanpur'),
('Hina', 'hina@gfg.com', 'Kanpur'),
('Misha', 'misha@gfg.com', 'Gurugram'),
('Misha', 'misha@gfg.com', 'Gurugram'),
('Neha', 'neha@gfg.com', 'Pilani');
Let us display the contents of table Geek –
SELECT * 
FROM Geek;
Table – Geek
SQL Server query to delete duplicate records from the table Geek :
WITH CTE AS (
SELECT Name, Email, City
ROW_NUMBER() OVER (
PARTITION BY Name, Email. City
ORDER BY Name, Email. City
) row_num
FROM Geek
)
DELETE FROM CTE
WHERE row_num > 1;
Output –(5 rows affected)
SELECT * 
FROM Geek;
Table – Geek
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Window functions in SQL
SQL | GROUP BY
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
Spark SQL - JSON Datasets

Spark SQL can automatically capture the schema of a JSON dataset and load it as a DataFrame. This conversion can be done using SQLContext.read.json() on either an RDD of String or a JSON file.
Spark SQL provides an option for querying JSON data along with auto-capturing of JSON schemas for both reading and writing data. Spark SQL understands the nested fields in JSON data and allows users to directly access these fields without any explicit transformations.
Let us consider an example of employee records in a text file named employee.json. Use the following commands to create a DataFrame (df).
Read a JSON document named employee.json with the following content and generate a table based on the schema in the JSON document.
employee.json − Place this file into the directory where the current scala> pointer is located.
{
   {"id" : "1201", "name" : "satish", "age" : "25"}
   {"id" : "1202", "name" : "krishna", "age" : "28"}
   {"id" : "1203", "name" : "amith", "age" : "39"}
   {"id" : "1204", "name" : "javed", "age" : "23"}
   {"id" : "1205", "name" : "prudvi", "age" : "23"}
}
Let us perform some Data Frame operations on given data.
DataFrame provides a domain-specific language for structured data manipulation. Here we include some basic examples of structured data processing using DataFrames.
Follow the steps given below to perform DataFrame operations −
First of all, we have to read the JSON document. Based on that, generate a DataFrame named dfs.
Use the following command to read the JSON document named employee.json containing the fields − id, name, and age. It creates a DataFrame named dfs.
scala> val dfs = sqlContext.read.json("employee.json")

Output − The field names are automatically taken from employee.json.
dfs: org.apache.spark.sql.DataFrame = [age: string, id: string, name: string]

If you want to see the Structure (Schema) of the DataFrame, then use the following command.
scala> dfs.printSchema()

Output
root
   |-- age: string (nullable = true)
   |-- id: string (nullable = true)
   |-- name: string (nullable = true)

If you want to show the data in the DataFrame, then use the following command.
scala> dfs.show()

Output − You can see the employee data in a tabular format.
<console>:22, took 0.052610 s
+----+------+--------+
|age |  id  |  name  |
+----+------+--------+
| 25 | 1201 | satish |
| 28 | 1202 | krishna|
| 39 | 1203 | amith  |
| 23 | 1204 | javed  |
| 23 | 1205 | prudvi |
+----+------+--------+

Then we can run different SQL statements in it. Users can migrate data into JSON format with minimal effort, regardless of the origin of the data source.

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    31 Lectures 
     1 hours 

 Frahaan Hussain

    12 Lectures 
     1 hours 

 Pranjal Srivastava

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
How to get the javascript function parameter names/values dynamically? - GeeksforGeeks

27 Sep, 2021
Given any arbitrary JavaScript function and the task is to return the parameter names of the function. 
Approach: JavaScript contains a method called Function.toString() which is used to represent a function code into its string representation. This method is used to get the parameter names/values. 
First, get the function’s code to its string equivalent using toString() method.
Then remove all the unnecessary codes like comments, function body, white spaces, and ES6 arrow (if any).
Identify the first occurrence of ‘(‘, it will be just before the starting of parameters.
The last character of the string will be ‘)’ which removes all comments, function body, white spaces, and ES6 arrow.
Also, the last character will be just after the end of the parameters.
Example: 
Javascript
<script> // JavaScript program to get the function// name/values dynamicallyfunction getParams(func) {             // String representaation of the function code    var str = func.toString();     // Remove comments of the form /* ... */    // Removing comments of the form //    // Remove body of the function { ... }    // removing '=>' if func is arrow function    str = str.replace(/\/\*[\s\S]*?\*\//g, '')            .replace(/\/\/(.)*/g, '')                    .replace(/{[\s\S]*}/, '')            .replace(/=>/g, '')            .trim();     // Start parameter names after first '('    var start = str.indexOf("(") + 1;     // End parameter names is just before last ')'    var end = str.length - 1;     var result = str.substring(start, end).split(", ");     var params = [];     result.forEach(element => {                 // Removing any default value        element = element.replace(/=[\s\S]*/g, '').trim();         if(element.length > 0)            params.push(element);    });         return params;} // Test sample functionsvar fun1 = function(a){ }; function fun2(a = 5*6/3, // Comment    b){ }; var fun3 = (a, /*    */    b, //comment    c) => /** */{ }; console.log(`List of parameters of ${fun1.name}:`, getParams(fun1));console.log(`List of parameters of ${fun2.name}:`, getParams(fun2));console.log(`List of parameters of ${fun3.name}:`, getParams(fun3));</script>
Output: 
List of parameters:
List of parameters of fun1: [ 'a' ]
List of parameters of fun2: [ 'a', 'b' ]
List of parameters of fun3: [ 'a', 'b', 'c' ]
 
sweetyty
javascript-functions
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Select column names containing a string in MySQL?

For this, you can use SHOW COLUMNS command. Following is the syntax. Here, we have set the string using LIKE −
SHOW COLUMNS FROM yourTableName LIKE ‘yourStringValue’;
Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstName varchar(20),
   -> LastName varchar(20)
   -> );
Query OK, 0 rows affected (0.69 sec)
Here is the query to select column names containing a specific string −
mysql> SHOW COLUMNS FROM DemoTable LIKE 'FirstName';
+-----------+-------------+------+-----+----------+-------+
| Field     | Type        | Null | Key  | Default | Extra |
+-----------+-------------+------+-----+----------+-------+
| FirstName | varchar(20) | YES  |     | NULL     |       |
+-----------+-------------+------+-----+---------+-------+
1 row in set (0.05 sec)
How to create a thread in Java

A thread can be created by implementing the Runnable interface and overriding the run() method. Then a Thread object can be created and the start() method called.
The Main thread in Java is the one that begins executing when the program starts. All the child threads are spawned from the Main thread and it is the last thread to finish execution.
A program that demonstrates this is given as follows:
 Live Demo
class ThreadDemo implements Runnable {
   Thread t;
   ThreadDemo() {
      t = new Thread(this, "Thread");
      System.out.println("Child thread: " + t);
      t.start();
   }
   public void run() {
      try {
         System.out.println("Child Thread");
         Thread.sleep(50);
      } catch (InterruptedException e) {
         System.out.println("The child thread is interrupted.");
      }
      System.out.println("Exiting the child thread");
   }
}
public class Demo {
   public static void main(String args[]) {
      new ThreadDemo();
      try {
         System.out.println("Main Thread");
         Thread.sleep(100);
      } catch (InterruptedException e) {
         System.out.println("The Main thread is interrupted");
      }
      System.out.println("Exiting the Main thread");
   }
}
Child thread: Thread[Thread,5,main]
Main Thread
Child Thread
Exiting the child thread
Exiting the Main thread
How to generate 6-digit random number in MySQL?

You can use LPAD() along with rand() and floor() to generate 6-digit random number. Let us first create a table −
mysql> create table DemoTable
   (
   Value int
   );
Query OK, 0 rows affected (0.64 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(2);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(3);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(4);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(5);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(6);
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
| 1     |
| 2     |
| 3     |
| 4     |
| 5     |
| 6     |
+-------+
6 rows in set (0.00 sec)
Following is the query to generate 6-digit random number in MySQL −
mysql> update DemoTable
set Value=LPAD(FLOOR(RAND() * 999999.99), 6, '0');
Query OK, 6 rows affected (0.15 sec)
Rows matched: 6 Changed: 6 Warnings: 0
Let us display the updated records from the table −
mysql> select * from DemoTable;
This will produce the following output −
+--------+
| Value  |
+--------+
| 499540 |
| 550607 |
| 254419 |
| 620272 |
| 338104 |
| 829705 |
+--------+
6 rows in set (0.00 sec)
JavaScript Bubble sort for objects in an array

Suppose, we have a constructor class that creates Shoe objects like this −
class Shoe {
   constructor(name, price, type) {
      this.name = name;
      this.price = price;
      this.type = type;
   }
};
We are using this class to fill an array with objects like this −
const arr = [
   new Shoe('Nike AirMax 90', '120', 'Casual'),
   new Shoe('Jordan Retro 1', '110', 'Casual'),
   new Shoe('Jadon Doc Martens', '250', 'Seasonal boots'),
   new Shoe('Adidas X Ghosted', '110', 'Athletic'),
   new Shoe('Nike Vapourmax Flyknit', '250', 'Casual'),
   new Shoe('Aldo Loafers', '130', 'Formal'),
   new Shoe('Timberlands', '199', 'Seasonal boots'),
   new Shoe('Converse High Tops', '70', 'Casual'),
   new Shoe('Converse Low Tops', '80', 'Casual'),
   new Shoe('Adidas NMDs', '110', 'Athletic'),
   new Shoe('Heels', '130', 'Formal'),
   new Shoe('Nike AirForce', '150', 'Casual')
];
We are required to write a JavaScript function makes use of precisely the Bubble Sort algorithm to sort this array of objects based on the price property of the objects.
The code for this will be −
class Shoe {
   constructor(name, price, type) {
      this.name = name;
      this.price = price;
      this.type = type;
   }
};
const arr = [
   new Shoe('Nike AirMax 90', '120', 'Casual'),
   new Shoe('Jordan Retro 1', '110', 'Casual'),
   new Shoe('Jadon Doc Martens', '250', 'Seasonal boots'),
   new Shoe('Adidas X Ghosted', '110', 'Athletic'),
   new Shoe('Nike Vapourmax Flyknit', '250', 'Casual'),
   new Shoe('Aldo Loafers', '130', 'Formal'),
   new Shoe('Timberlands', '199', 'Seasonal boots'),
   new Shoe('Converse High Tops', '70', 'Casual'),
   new Shoe('Converse Low Tops', '80', 'Casual'),
   new Shoe('Adidas NMDs', '110', 'Athletic'),
   new Shoe('Heels', '130', 'Formal'),
   new Shoe('Nike AirForce', '150', 'Casual')
];
const bubbleSort = (arr = []) => {
   let swapped;
   do {
      swapped = false;
      for (let i = 0; i < arr.length − 1; i++) {
         if (+arr[i].price > +arr[i + 1].price) {
            let temp = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = temp;
            swapped = true;
         };
      };
   }while (swapped);
}
bubbleSort(arr);
console.log(arr);
And the output in the console will be −
[
   Shoe { name: 'Converse High Tops', price: '70', type: 'Casual' },
   Shoe { name: 'Converse Low Tops', price: '80', type: 'Casual' },
   Shoe { name: 'Jordan Retro 1', price: '110', type: 'Casual' },
   Shoe { name: 'Adidas X Ghosted', price: '110', type: 'Athletic' },
   Shoe { name: 'Adidas NMDs', price: '110', type: 'Athletic' },
   Shoe { name: 'Nike AirMax 90', price: '120', type: 'Casual' },
   Shoe { name: 'Aldo Loafers', price: '130', type: 'Formal' },
   Shoe { name: 'Heels', price: '130', type: 'Formal' },
   Shoe { name: 'Nike AirForce', price: '150', type: 'Casual' },
   Shoe { name: 'Timberlands', price: '199', type: 'Seasonal boots' },
   Shoe { name: 'Jadon Doc Martens', price: '250', type: 'Seasonal boots'},
   Shoe { name: 'Nike Vapourmax Flyknit', price: '250', type: 'Casual' }
]
Suppress Warnings Globally in R - GeeksforGeeks

31 Aug, 2021
In this article, we are going to discuss how to suppress warnings globally in R programming language.
A warning is a message that does not disturb the program flow but displays the warning along with the output. In order to suppress the warnings globally, we have to set warn=-1 in the options function
Syntax:
options(warn = – 1)   
If you want to see the warnings then set warn=0
Example: R program to see the warning when using pmax and pmin
R
# pmax function and display the warnings# pmax function will return the parallel# maximum of two vectorspmax(c(1, 2, 3), c(1, 2, 3, 4, 5))  # pmin function and display the warnings# pmin function will return the parallel# minimum of two vectorspmin(c(1, 2, 3), c(1, 2, 3, 4, 5))
Output:
Example: R program to suppress the warning messages when using pmax and pmin
R
# suppress the warnings by setting warn=-1options(warn=-1)  # pmax function and display the warnings# pmax function will return the parallel# maximum of two vectorspmax(c(1, 2, 3), c(1, 2, 3, 4, 5))  # pmin function and display the warnings# pmin function will return the parallel# minimum of two vectorspmin(c(1, 2, 3), c(1, 2, 3, 4, 5))
Output:
12345
12312
If we want to see the warnings again, set warn=0
Example: R program to again see the warnings
R
# display the warnings by setting warn=0options(warn=0)  # pmax function and display the warnings# pmax function will return the parallel# maximum of two vectorspmax(c(1, 2, 3), c(1, 2, 3, 4, 5))  # pmin function and display the warnings# pmin function will return the parallel# minimum of two vectorspmin(c(1, 2, 3), c(1, 2, 3, 4, 5))
Output:
Picked
R-basics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
Tryit Editor v3.7 - Show Java

public class Main {
  public static void main(String[] args) {
    int myNum = 5;               // integer (whole number)
    float myFloatNum = 5.99f;    // floating point number
    char myLetter = 'D';         // character
    boolean myBool = true;       // boolean
    String myText = "Hello";     // String
Convert CSV to JSON using the Jackson library in Java?


A Jackson is a Java JSON API that provides several different ways to work with JSON. We can convert CSV data to JSON data using the CsvMapper class, it is specialized ObjectMapper, with extended functionality to produce CsvSchema instances out of POJOs. We can use the reader() method for constructing ObjectReader with default settings. In order to convert this, we need to import the com.fasterxml.jackson.dataformat.csv package.
In the below example, convert a CSV to JSON.
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.dataformat.csv.*;
public class CsvToJsonTest {
   public static void main(String args[]) throws Exception {
      File input = new File("input.csv");
      try {
         CsvSchema csv = CsvSchema.emptySchema().withHeader();
         CsvMapper csvMapper = new CsvMapper();
         MappingIterator<Map<?, ?>> mappingIterator =  csvMapper.reader().forType(Map.class).with(csv).readValues(input);
         List<Map<?, ?>> list = mappingIterator.readAll();
        System.out.println(list);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
[{last name=Chandra, first name=Ravi, location=Bangalore}]
How to store the contents of arrays in a file using Java?

You can use write data into a file using the Writer classes. In the example given below, we are writing the contents of the array using the BufferedWriter.
Live Demo
import java.io.BufferedWriter;
import java.io.FileWriter;

public class WritingStringArrayToFile {
   public static void main(String args[]) throws Exception {
      String[] myArray = {"JavaFX", "HBase", "OpenCV", "Java", "Hadoop", "Neo4j"};
      BufferedWriter writer = new BufferedWriter(new FileWriter("myFile.txt", false));
      for(int i = 0; i < myArray.length; i++) {
         writer.write(myArray[i].toString());
         writer.newLine();
      }
      writer.flush();
      System.out.println("Data Entered in to the file successfully");
   }
}
Data Entered in to the file successfully
If you verify the file you can observe that the file with the contents of an array −
Live Demo
import java.io.BufferedWriter;
import java.io.FileWriter;

public class WritingIntArrayToFile {
   public static void main(String args[]) throws Exception {
      Integer[] myArray = {23, 93, 56, 92, 39};
      BufferedWriter writer = new BufferedWriter(new FileWriter("myFile.txt", false));
      for(int i = 0; i < myArray.length; i++) {
         writer.write(myArray[i].toString());
         writer.newLine();
      }
      writer.flush();
      System.out.println("Data Entered in to the file successfully");
   }
}
Data Entered in to the file successfully
If you verify the file you can observe that the file with the contents of an array −
GATE | GATE-CS-2003 | Question 80 - GeeksforGeeks

27 Oct, 2021
Suppose we want to synchronize two concurrent processes P and Q using binary semaphores S and T. The code for the processes P and Q is shown below.
Process P:
while (1) {
W:
   print '0';
   print '0';
X:
}
	
Process Q:
while (1) {
Y:
   print '1';
   print '1';
Z:
}
Synchronization statements can be inserted only at points W, X, Y and Z.Which of the following will always lead to an output starting with ‘001100110011’ ?(A) P(S) at W, V(S) at X, P(T) at Y, V(T) at Z, S and T initially 1(B) P(S) at W, V(T) at X, P(T) at Y, V(S) at Z, S initially 1, and T initially 0(C) P(S) at W, V(T) at X, P(T) at Y, V(S) at Z, S and T initially 1(D) P(S) at W, V(S) at X, P(T) at Y, V(T) at Z, S initially 1, and T initially 0Answer: (B)Explanation: P(S) means wait on semaphore ‘S’ and V(S) means signal on semaphore ‘S’.
Wait(S){    while (i <= 0)     --S;}    Signal(S){    S++;}
Initially, we assume S = 1 and T = 0 to support mutual exclusion in process P and Q.Since S = 1, only process P will be executed and wait(S) will decrement the value of S. Therefore, S = 0.At the same instant, in process Q, value of T = 0. Therefore, in process Q, control will be stuck in while loop till the time process P prints 00 and increments the value of T by calling the function V(T).While the control is in process Q, semaphore S = 0 and process P would be stuck in while loop and would not execute till the time process Q prints 11 and makes the value of S = 1 by calling the function V(S).This whole process will repeat to give the output 00 11 00 11 ... . Thus, B is the correct choice.
Watch GeeksforGeeks Video Explanation :
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersExamples of Semaphore with Viomesh Singh | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:009:36 / 24:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=yFyCUSn7jkY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 Please comment below if you find anything wrong in the above post.Quiz of this Question
anikaseth98
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2012 | Question 54
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2006 | Question 49
How to check if PSCustomObject is empty in PowerShell?

To check if the PSCustomObject is empty or not in PowerShell, we need to check the fields of the PSCustomObject. Consider the below example,
$output = [PSCustomObject]@{
   Name = 'John'
   City = 'New York'
   Country = 'US'
   Company = 'Alpha'  
}
$output1 = [PSCustomObject]@{
   Name = ''
   City = ''
   Country = ''
   Company = ''
}
PS C:\WINDOWS\system32> $output
Name    City     Country    Company
----    ----     -------    -------
John    New York  US        Alpha
PS C:\WINDOWS\system32> $output1
Name    City     Country    Company
----    ----     -------    -------
In this example, we have Output and Output1 PSCustomObjects and the output1 is the empty one. First of all, we can’t determine by the Count property because no such direct method exists for the Custom Objects. For example,
PS C:\WINDOWS\system32> $output.count
PS C:\WINDOWS\system32> $output1.count
There will be no output because Count is not supported in the PSCustomObject but if we convert it to the string using the ToString() method then we can use the count method. For example,
PS C:\WINDOWS\system32> $output.ToString().Count
1
PS C:\WINDOWS\system32> $output1.ToString().Count
1
But it entirely considers PSCustomObject as one so always gives the count 1. But we can determine if the PSCustoObject is empty or not by checking its field. So we will check here any property of the column of the object and if it is null then the PSCustomObject is null.
PS C:\WINDOWS\system32> $output.Country -eq ""
False
PS C:\WINDOWS\system32> $output1.Country -eq ""
True
So the Output1 Object is empty. In some cases, you can check multiple properties to confirm if the PSCustomObject is empty.
Output of C Program | Set 28 - GeeksforGeeks

27 Dec, 2016
Predict the output of following C program.
Question 1
#include <stdio.h>  int main(){    char a = 30;    char b = 40;    char c = 10;    char d = (a * b) / c;    printf ("%d ", d);      return 0;}
At first look, the expression (a*b)/c seems to cause arithmetic overflow because signed characters can have values only from -128 to 127 (in most of the C compilers), and the value of subexpression ‘(a*b)’ is 1200. For example, the following code snippet prints -80 on a 32 bit little endian machine.
    char d = 1200;
    printf ("%d ", d);
Arithmetic overflow doesn’t happen in the original program and the output of the program is 120. In C, char and short are converted to int for arithmetic calculations. So in the expression ‘(a*b)/c’, a, b and c are promoted to int and no overflow happens.
Question 2
#include<stdio.h>int main(){    int a, b = 10;    a = -b--;    printf("a = %d, b = %d", a, b);    return 0;}
Output:
a = -10, b = 9

The statement ‘a = -b–;’ compiles fine. Unary minus and unary decrement have save precedence and right to left associativity. Therefore ‘-b–‘ is treated as -(b–) which is valid. So -10 will be assigned to ‘a’, and ‘b’ will become 9.Try the following program as an exercise.
#include<stdio.h>int main(){    int a, b = 10;    a = b---;    printf("a = %d, b = %d", a, b);    return 0;}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways to copy a string in C/C++
Output of Java Program | Set 3
Runtime Errors
Output of Java Programs | Set 14 (Constructors)
Output of Java program | Set 5
Output of Java Program | Set 7
Output of C programs | Set 57 (for loop)
unsigned specifier (%u) in C with Examples
Output of Java Program | Set 4
Output of Java program | Set 26
Common Words in Two Strings in Python

Suppose we have two strings s0 and s1, they are representing a sentence, we have to find the
number of unique words that are shared between these two sentences. We have to keep in
mind that, the words are case-insensitive so "tom" and "ToM" are the same word.
So, if the input is like s0 = "i love python coding", s1 = "coding in python is easy", then the
output will be 2 as there are 2 common words, ['python', 'coding']
To solve this, we will follow these steps −
convert s0 and s1 into lowercase
s0List := a list of words in s0
s1List := a list of words in s1
convert set from words in s0List and s1List, then intersect them to get common words,
and return the count of the intersection result.
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, s0, s1):
      s0 = s0.lower()
      s1 = s1.lower()
      s0List = s0.split(" ")
      s1List = s1.split(" ")
   return len(list(set(s0List)&set(s1List)))
ob = Solution()
S = "i love python coding"
T = "coding in python is easy"
print(ob.solve(S,T))
"i love python coding", "coding in python is easy"
2
How to add a primary key constraint to a column of a table in a database using JDBC API?

You can add a primary key constraint to a column of a table using the ALTER TABLE command.
ALTER TABLE table_name
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
Assume we have a table named Dispatches in the database with 7 columns namely id, CustomerName, DispatchDate, DeliveryTime, Price and, Location with description as shown below:
+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductName  | varchar(255) | YES  |     | NULL    |       |
| CustomerName | varchar(255) | YES  |     | NULL    |       |
| DispatchDate | date         | YES  |     | NULL    |       |
| DeliveryTime | time         | YES  |     | NULL    |       |
| Price        | int(11)      | YES  |     | NULL    |       |
| Location     | text         | YES  |     | NULL    |       |
| ID           | int(11)      | NO   |     | NULL    |       |
+--------------+--------------+------+-----+---------+-------+
Following JDBC program establishes connection with MySQL database, and adds a primary-key constraint to the column named id.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Adding_PrimaryKey_Constraint {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to alter the table
      String query = "ALTER TABLE Sales ADD CONSTRAINT MyPrimaryKey PRIMARY KEY(ID)";
      //Executing the query
      stmt.executeUpdate(query);
      System.out.println("Constraint added......");
   }
}
Connection established......
Constraint added......
Since we added primary constraint on the column named id column, if you get the description of the Sales table using the describe command you can observe that the Key value PRI added opposite to Id.
mysql> describe sales;
+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductName  | varchar(255) | YES  |     | NULL    |       |
| CustomerName | varchar(255) | YES  |     | NULL    |       |
| DispatchDate | date         | YES  |     | NULL    |       |
| DeliveryTime | time         | YES  |     | NULL    |       |
| Price        | int(11)      | YES  |     | NULL    |       |
| Location     | text         | YES  |     | NULL    |       |
| ID           | int(11)      | NO   | PRI | NULL    |       |
+--------------+--------------+------+-----+---------+-------+
7 rows in set (0.00 sec)