code-rag-bench/online-tutorials huggingface dataset:
Concatenate multiple rows and columns in a single row with MySQL

To concatenate multiple rows and columns in single row, you can use GROUP_CONCAT() along with CONCAT(). Let us first create a table −
mysql> create table DemoTable1463
   -> (
   -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ClientName varchar(20),
   -> ClientAge int
   -> );
Query OK, 0 rows affected (1.37 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1463(ClientName,ClientAge) values('Adam Smith',34);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1463(ClientName,ClientAge) values('John Doe',29);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1463(ClientName,ClientAge) values('David Miller',NULL);
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable1463(ClientName,ClientAge) values('John Smith',32);
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1463;
This will produce the following output −
+----------+--------------+-----------+
| ClientId | ClientName   | ClientAge |
+----------+--------------+-----------+
|        1 | Adam Smith   |        34 |
|        2 | John Doe     |        29 |
|        3 | David Miller |      NULL |
|        4 | John Smith   |        32 |
+----------+--------------+-----------+
4 rows in set (0.00 sec)
Following is the query to concatenate multiple rows and columns in a single row −
mysql> select group_concat(concat(ClientId,':',ClientName,':',IFNULL(ClientAge,''))) from DemoTable1463;
This will produce the following output −
+------------------------------------------------------------------------+
| group_concat(concat(ClientId,':',ClientName,':',IFNULL(ClientAge,''))) |
+------------------------------------------------------------------------+
| 1:Adam Smith:34,2:John Doe:29,3:David Miller:,4:John Smith:32          |
+------------------------------------------------------------------------+
1 row in set (0.04 sec)
Deploy Python Flask App on Heroku

19 Oct, 2021
Flask is a web application framework written in Python. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects. This article revolves around how to deploy a flask app on Heroku. To demonstrate this, we are first going to create a sample application for a better understanding of the process. 
Python
pip
Heroku CLI
Git
 
Let’s create a simple flask application first and then it can be deployed to heroku. Create a folder named “eflask” and open the command line and cd inside the “eflask” directory. Follow the following steps to create the sample application for this tutorial.STEP 1 : Create a virtual environment with pipenv and install Flask and Gunicorn . 
$ pipenv install flask gunicorn 
STEP 2 : Create a “Procfile” and write the following code.  
$ touch Procfile 
 
STEP 3 : Create “runtime.txt” and write the following code. 
$ touch runtime.txt 
 
STEP 4 : Create a folder named “app” and enter the folder.  
$ mkdir app
$ cd app
  
STEP 5 : Create a python file, “main.py” and enter the sample code. 
 touch main.py 
 
Python3
from flask import Flask app = Flask(__name__) @app.route("/")def home_view():        return "<h1>Welcome to Geeks for Geeks</h1>"
STEP 6 :Get back to the previous directory “eflask”.Create a file“wsgi.py” and insert the following code. 
$ cd ../
$ touch wsgi.py
 
Python3
from app.main import app if __name__ == "__main__":        app.run()
STEP 7 : Run the virtual environment. 
$ pipenv shell 
STEP 8 : Initialize an empty repo, add the files in the repo and commit all the changes. 
$ git init 
$ git add .
$ git commit -m "Initial Commit"
STEP 9 : Login to heroku CLI using  
heroku login
Now, Create a unique name for your Web app. 
$ heroku create eflask-app
 
STEP 10 : Push your code from local to the heroku remote.  
$ git push heroku master
 
Finally, web app will be deployed on http://eflask-app.herokuapp.com.  
 
rajeev0719singh
Articles
Git
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
SQL Interview Questions
Understanding "extern" keyword in C
Java Tutorial
SQL | Views
Working on Git for GUI
How to Set Git Username and Password in GitBash?
How to integrate Git Bash with Visual Studio Code?
Git - Difference Between Git Fetch and Git Pull
Working on Git Bash
Python PostgreSQL – Drop Table

23 Aug, 2021
In this article, we are going to see how to drop tables in PostgreSQL using pyscopg2 module Python. In PostgreSQL DROP TABLE is used to remove the existing table from the database. It removes table definition and all associated data, indexes, rules, triggers, and constraints for that table. If the particular table doesn’t exist then it shows an error. 
Syntax: DROP TABLE table_name;
Here, we are using the accounts table for demonstration.
Now let’s drops this table, for we will use will psycopg2 module to connect the PostgreSQL and execute the SQL query in cursor.execute(query) object.
Syntax: cursor.execute(sql_query);
Here we are going to drop the table using the DELETE clause.
Syntax: DROP TABLE table_name;
Code:
Python3
# importing psycopg2import psycopg2  conn=psycopg2.connect(    database="test",    user="postgres",    password="password",    host="localhost",    port="5432")    # Creating a cursor object using the cursor() # methodcursor = conn.cursor()  # drop table accountssql = '''DROP TABLE accounts '''  # Executing the querycursor.execute(sql)print("Table dropped !")  # Commit your changes in the databaseconn.commit()  # Closing the connectionconn.close()
Output:
Table dropped !
If you try to delete the same table again, since you have already deleted it, you will get an error saying “table does not exist”, so we can resolve using the IF EXIST  clause.
Syntax: DROP TABLE table_name IF EXITS table_name;
Code:
Python3
# importing psycopg2import psycopg2  conn=psycopg2.connect(    database="geeks",    user="postgres",    password="root",    host="localhost",    port="5432")    # Creating a cursor object using the cursor()# methodcursor = conn.cursor()  # drop table accountssql = '''DROP table IF EXISTS accounts '''  # Executing the querycursor.execute(sql)  print("Table dropped !")# Commit your changes in the databaseconn.commit()  # Closing the connectionconn.close()
Output:
Table dropped !
After execution of the scripts, let check the table in PostgreSQL:
Picked
Python PostgreSQL
Python Pyscopg2
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
How to merge multiple files into a new file using Python?

To merge multiple files in a new file, you can simply read files and write them to a new file using loops.
filenames = ['file1.txt', 'file2.txt', 'file3.txt']
with open('output_file', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read())
If you have very big files, instead of writing them at once, you could write them line by line.
filenames = ['file1.txt', 'file2.txt', 'file3.txt']
with open('output_file', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)
LinkedList AddAfter method in C#

Set a LinkedList.
int [] num = {1, 2, 3, 4, 5};
LinkedList<int> list = new LinkedList<int>(num);
Now add a node at the end using AddLast() method.
var newNode = list.AddLast(20);
To add a node after the above added node, use the AddAfter() method.
list.AddAfter(newNode, 30);
 Live Demo
using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      int [] num = {1, 2, 3, 4, 5};
      LinkedList<int> list = new LinkedList<int>(num);
      foreach (var n in list) {
         Console.WriteLine(n);
      }
      // adding a node at the end
      var newNode = list.AddLast(20);
      // adding a new node after the node added above
      list.AddAfter(newNode, 30);
      Console.WriteLine("LinkedList after adding new nodes...");
      foreach (var n in list) {
         Console.WriteLine(n);
      }
   }
}
1
2
3
4
5
LinkedList after adding new nodes...
1
2
3
4
5
20
30
Java - toRadians() Method

The method converts the argument value to radians.
double toRadians(double d)

Here is the detail of parameters −
d − A double data type.
d − A double data type.
This method returns a double value.
public class Test { 

   public static void main(String args[]) {
      double x = 45.0;
      double y = 30.0;

      System.out.println( Math.toRadians(x) );
      System.out.println( Math.toRadians(y) );
   }
}
This will produce the following result −
0.7853981633974483
0.5235987755982988


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Hadoop - HDFS Operations

Initially you have to format the configured HDFS file system, open namenode (HDFS server), and execute the following command.
$ hadoop namenode -format 

After formatting the HDFS, start the distributed file system. The following command will start the namenode as well as the data nodes as cluster.
$ start-dfs.sh 

After loading the information in the server, we can find the list of files in a directory, status of a file, using ‘ls’. Given below is the syntax of ls that you can pass to a directory or a filename as an argument.
$ $HADOOP_HOME/bin/hadoop fs -ls <args>

Assume we have data in the file called file.txt in the local system which is ought to be saved in the hdfs file system. Follow the steps given below to insert the required file in the Hadoop file system.
You have to create an input directory.
$ $HADOOP_HOME/bin/hadoop fs -mkdir /user/input 

Transfer and store a data file from local systems to the Hadoop file system using the put command.
$ $HADOOP_HOME/bin/hadoop fs -put /home/file.txt /user/input 

You can verify the file using ls command.
$ $HADOOP_HOME/bin/hadoop fs -ls /user/input 

Assume we have a file in HDFS called outfile. Given below is a simple demonstration for retrieving the required file from the Hadoop file system.
Initially, view the data from HDFS using cat command.
$ $HADOOP_HOME/bin/hadoop fs -cat /user/output/outfile 

Get the file from HDFS to the local file system using get command.
$ $HADOOP_HOME/bin/hadoop fs -get /user/output/ /home/hadoop_tp/ 

You can shut down the HDFS by using the following command.
$ stop-dfs.sh 


    39 Lectures 
     2.5 hours 

 Arnab Chakraborty

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    12 Lectures 
     1 hours 

 Pranjal Srivastava

    24 Lectures 
     6.5 hours 

 Pari Margu

    89 Lectures 
     11.5 hours 

 TELCOMA Global

    43 Lectures 
     1.5 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
\mathscr - Tex Command

\mathscr - Used to turn on script typestyle for uppercase letters. If lowercase script letters are not available, then they are typeset in a roman typestyle.
{ \mathscr #1 }
\mathscr command is used to turn on script typestyle for uppercase letters. If lowercase script letters are not available, then they are typeset in a roman typestyle.

\mathscr{ABCDEFGHIJKLMNOPQRSTUVWXYZ}

ABCDEFGHIJKLMNOPQRSTUVWXYZ


\mathscr{0123456789}

0123456789


\mathscr{abcdefghijklmnopqrstuvwxyz}

abcdefghijklmnopqrstuvwxyz


abcdefghijklmnopqrstuvwxyz

abcdefghijklmnopqrstuvwxyz


\mathscr{AB}AB

ABAB



\mathscr{ABCDEFGHIJKLMNOPQRSTUVWXYZ}

ABCDEFGHIJKLMNOPQRSTUVWXYZ


\mathscr{ABCDEFGHIJKLMNOPQRSTUVWXYZ}
\mathscr{0123456789}

0123456789


\mathscr{0123456789}
\mathscr{abcdefghijklmnopqrstuvwxyz}

abcdefghijklmnopqrstuvwxyz


\mathscr{abcdefghijklmnopqrstuvwxyz}
abcdefghijklmnopqrstuvwxyz

abcdefghijklmnopqrstuvwxyz


abcdefghijklmnopqrstuvwxyz
\mathscr{AB}AB

ABAB


\mathscr{AB}AB

    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
C++ Program to Generate Randomized Sequence of Given Range of Numbers

At first let us discuss about the rand() function. rand() function is a predefined method of C++. It is declared in <stdlib.h> header file. rand() is used to generate random number within a range. Here min_n is the minimum range of the random numbers and max_n is the maximum range of the numbers. So rand() will return the random numbers between min_n to (max_n – 1) inclusive of the limit values. Here if we mention lower and upper limits as 1 and 100 respectively, then rand() will return values from 1 to (100 – 1). i.e. from 1 to 99.
Begin
   Declare max_n to the integer datatype.
      Initialize max_n = 100.
   Declare min_n to the integer datatype.
      Initialize min_n = 1.
   Declare new_n to the integer datatype.
   Declare i of integer datatype.
   Print “The random number is:”.
   for (i = 0; i < 10; i++)
      new_n = ((rand() % (max_n + 1 - min_n)) + min_n)
   Print the value of new_n.
End.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
   int max_n = 100;
   int min_n = 1;
   int new_n;
   int i;
   cout<<"The random number is: \n";
   for (i = 0; i < 10; i++) {
      new_n = ((rand() % (max_n + 1 - min_n)) + min_n);
      //rand() returns random decimal number.
      cout<<new_n<<endl;
   }
   return 0;
}
The random number is:
42
68
35
1
70
25
79
59
63
65
ACPI command in Linux with examples - GeeksforGeeks

04 Apr, 2019
acpi command is used to display the battery status and other ACPI information. It displays the information from the /proc or the /sys filesystem, such as battery status or thermal information.
Syntax:
acpi [options]  
-b | –battery : It displays the battery information.
Example:
-a | –ac-adapter : It displays the ac adapter information.
Example:
-t | –thermal : It shows the thermal information.
Example:
-c | –cooling : It displays the cooling device information.
Example:
-V | –everything : It is used to show every device, overrides above options.
Example:
-s | –show-empty : It displays the non-operational devices.
Example:
-i | –details : It displays the additional details if available.
Example:
-f | –fahrenheit : It uses fahrenheit as the temperature unit instead of default celsius.
Example:
-k | –kelvin : It uses kelvin as the temperature unit instead of default celsius.
Example:
-p | –proc : It uses the old /proc interface, default is the new /sys one.
-d | –directory : It uses the path to ACPI info (either /proc/acpi or /sys/class)/
-h | –help : It display help and exit.
Example:
-v | –version : It shows the output version information and exit.
Example:
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
UDP Server-Client implementation in C
curl command in Linux with Examples
Conditional Statements | Shell Script
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Mutex lock for Linux Thread Synchronization
Python program to Find the size of a Tuple

When it is required to find the size of a tuple, the ‘sizeof’ method can be used.
Below is the demonstration of the same −
 Live Demo
import sys
tuple_1 = ("A", 1, "B", 2, "C", 3)
tuple_2 = ("Java", "Lee", "Code", "Mark", "John")
tuple_3 = ((1, "Bill"), ( 2, "Ant"), (3, "Fox"), (4, "Cheetah"))

print("The first tuple is :")
print(tuple_1)
print("The second tuple is :")
print(tuple_2)
print("The third tuple is :")
print(tuple_3)
print("Size of first tuple is : " + str(sys.getsizeof(tuple_1)) + " bytes")
print("Size of second tuple is : " + str(sys.getsizeof(tuple_2)) + " bytes")
print("Size of third tuple is: " + str(sys.getsizeof(tuple_3)) + " bytes")
The first tuple is :
('A', 1, 'B', 2, 'C', 3)
The second tuple is :
('Java', 'Lee', 'Code', 'Mark', 'John')
The third tuple is :
((1, 'Bill'), (2, 'Ant'), (3, 'Fox'), (4, 'Cheetah'))
Size of first tuple is : 96 bytes
Size of second tuple is : 88 bytes
Size of third tuple is : 80 bytes
The required packages are imported.
The required packages are imported.
The tuples are defined, and are displayed on the console.
The tuples are defined, and are displayed on the console.
The ‘sizeof’ method is called on every tuple and the length is displayed as output on the console.
The ‘sizeof’ method is called on every tuple and the length is displayed as output on the console.
Is assignment operator inherited? - GeeksforGeeks

29 Mar, 2022
In C++, like other functions, assignment operator function is inherited in derived class.
For example, in the following program, base class assignment operator function can be accessed using the derived class object.
#include<iostream>  using namespace std;  class A { public:   A & operator= (A &a) {     cout<<" base class assignment operator called ";     return *this;   }};  class B: public A { };  int main(){  B a, b;  a.A::operator=(b); //calling base class assignment operator function                     // using derived class  getchar();  return 0;}
Output: base class assignment operator called
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
naggarwal1
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Bitwise Operators in C/C++
Socket Programming in C/C++
Constructors in C++
Virtual Function in C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
Copy Constructor in C++
What are unchecked exceptions in Java?

An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. 
If you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Live Demo
public class Unchecked_Demo {
   public static void main(String args[]) {
      int num[] = {1, 2, 3, 4};
      System.out.println(num[5]);
   }
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
   at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
How to read data from JSON array using JavaScript?

Following is the code to read data from JSON array using JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample,.result {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>Read data from JSON array using JavaScript</h1>
<div class="sample">
[{"name":"Rohan","age":22}, {"name":"Shawn","age":12} ,{"name":"Michael","age":21}]
</div>
<div class="result" style="color: green;"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to read data from above JSON array</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let resultEle = document.querySelector(".result");
   let parsedJson = JSON.parse(sampleEle.innerHTML);
   document.querySelector(".Btn").addEventListener("click", () => {
      parsedJson.forEach((item) => {
         resultEle.innerHTML += "Name = " + item.name + "";
         resultEle.innerHTML += "Age = " + item.age + "";
      });
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
Java program to find a cube of a given number

Cube of a value is simply three times multiplication of the value with self.
For example, cube of 2 is (2*2*2) = 8.
Take integer variable A.
Multiply A three times.
Display result as Cube.
import java.util.Scanner;

public class FindingCube {
   public static void main(String args[]){
      int n = 5;
      System.out.println("Enter a number ::");
      Scanner sc = new Scanner(System.in);
      int num = sc.nextInt();
      System.out.println("Cube of the given number is "+(num*num*num));
   }
}
Enter a number ::
5
Cube of the given number is 125
What is the difference between “screen” and “only screen” in media queries? - GeeksforGeeks

07 Mar, 2019
Media query is used to create responsive web design. It means that the view of web page differ from system to system based on screen or media types.screen: It is used to set the screen size of media query. The screen size can be set by using max-width and min-width. The screen size is differ from screen to screen.
Syntax:
@media screen and (max-width: width)
Example: This example use media query which works when the maximum width of display area is 400px. It is specifying screen as opposed to the other available media types the most common other one being print.
<!DOCTYPE html><html>      <head>    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">          <!-- CSS property to set style -->        <style>        body {            background-color: lightgreen;        }                  /* Media query */        @media screen and (max-width: 400px) {            body {                background-color: green;                color:white;            }        }    </style></head>  <body>    <h1>The @media Rule</h1>          <p>        Resize the browser window. When the width of        this document is 400 pixels or less, the         background-color is "green", otherwise it        is "lightblue".    </p></body>  </html>                    
Output:Screen size greater then 400px:Screen size less then 400px:
only screen: The only keyword is used to prevent older browsers that do not support media queries with media features from applying the specified styles.
Syntax:
@media only screen and (max-width: width) 
Example 2
<!DOCTYPE html><html>      <head>    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">          <!-- CSS property to set style -->        <style>        body {            background-color: lightgreen;        }                  /* Media query */        @media only screen and (max-width: 400px) {            body {                background-color: green;            }        }    </style></head>  <body>    <h1>The @media Rule</h1>          <p>        Resize the browser window. When the width of        this document is 400 pixels or less, the         background-color is "green", otherwise it        is "lightblue".    </p></body>  </html>                    
Output:Screen size greater then 400px:Screen size less then 400px:
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Responsive Navbar using ReactJS
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to Upload Image into Database and Display it using PHP ?
How to set div width to fit content using CSS ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
What does DELIMITER // do in a Trigger in MySQL?

The DELIMITER // can be used to change the statement from semicolon (;) to //. Now you can write multiple statements with semi-colon in a trigger.
Here is the demo of triggers. In this example whenever you enter the EmployeeSalary less than 1000 then it will by default set to 10000.
Firstly, let us create a table. The query to create a table is as follows -
mysql> create table EmployeeTable
-> (
-> EmployeeId int,
-> EmployeeName varchar(100),
-> EmployeeSalary float
-> );
Query OK, 0 rows affected (0.76 sec)
After creating a table, you need to create a trigger on insert command. The query to create a trigger is as follows.
mysql> delimiter //
mysql> create trigger CheckSalary before insert on EmployeeTable
-> for each row if new.EmployeeSalary < 1000 then set
-> new.EmployeeSalary=10000;
-> end if;
-> //
Query OK, 0 rows affected (0.40 sec)
mysql> delimiter ;
Now you can check the trigger using insert command. If you insert EmployeeSalary less than 1000, then it does not give any error but it will store a default value which I have given 10000.
The query to insert record is as follows -
mysql> insert into EmployeeTable values(1,'Carol',500);
Query OK, 1 row affected (0.25 sec)
Now check all the records from the table using select statement. The query is as follows.
mysql> select *from EmployeeTable;
The following is the output.
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
| 1          | Carol        | 10000          |
+------------+--------------+----------------+
1 row in set (0.00 sec)
If you insert 1000 or greater than 1000 then it will show your number only. I have deleted the previous record from the table using truncate command.
mysql> truncate table EmployeeTable;
Query OK, 0 rows affected (1.44 sec)
The query to insert records in the table.
mysql> insert into EmployeeTable values(2,'Bob',1000);
Query OK, 1 row affected (0.14 sec)

mysql> insert into EmployeeTable values(3,'Carol',2500);
Query OK, 1 row affected (0.19 sec)
Here is the query to check all records from the table using select statement.
mysql> select *from EmployeeTable;
The following is the output.
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeSalary |
+------------+--------------+----------------+
| 2          | Bob          | 1000           |
| 3          | Carol        | 2500           |
+------------+--------------+----------------+
2 rows in set (0.00 sec)
Look at the above sample output, EmployeeSalary is greater than or equal to 1000. This will give your salary. Remember, if it is less than 1000 then the default value is set to 10000.
Can we have a return statement in a JavaScript switch statement?

The JavaScript switch statement can contain return statements if it is present inside a function. The function will return the value in the switch statement and the code after the switch statement will not be executed.
Following is the code to have return statements in JavaScript switch statement −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Return statement in JavaScript switch</h1>
Enter day 1-7<input type="text" class="day" /><button class="Btn">
CHECK
</button>
<div style="color: green;" class="result"></div>
<h3>
Click on the above button to check which day it is
</h3>
<script>
   let dayVal = document.querySelector(".day");
   let resEle = document.querySelector(".result");
   function returnDay(val) {
      switch (val) {
         case 1:
            return "It's monday";
         case 2:
            return "It's tuesday";
         case 3:
            return "It's wednesday";
         case 4:
            return "It's thursday";
         case 5:
            return "It's friday";
         case 6:
            return "It's saturday";
         case 7:
            return "It's sunday";
         default:
            return "Enter a value between 1 - 7";
      }
   }
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = returnDay(parseInt(dayVal.value));
   });
</script>
</body>
</html>
The above code will produce the following output −
On entering a number between 1-7 and clicking on CHECK −
How to bind all the number keys in Tkinter?

While developing a Tkinter application, we often encounter cases where we have to perform some specific operation or event with the keystrokes (on keyboard). Tkinter provides a mechanism to deal with such events.
You can use bind(<Key>, callback) function for each widget that you want to bind in order to perform a certain type of event. Whenever we bind a key with an event, the callback event occurs whenever a corresponding key is pressed.
Let's consider an example. Using the bind("", callback) function, we can also bind all the number keys to display a message on the screen such that whenever a user presses a key (1-9), a message will appear on the screen.
# Import required libraries
from tkinter import *

# Create an instance of tkinter window
win = Tk()
win.geometry("700x300")

# Function to display a message whenever a key is pressed
def add_label(e):
   Label(win, text="You have pressed: " + e.char, font='Arial 16 bold').pack()

# Create a label widget
label=Label(win, text="Press any key in the range 0-9")
label.pack(pady=20)
label.config(font='Courier 18 bold')

# Bind all the number keys with the callback function
for i in range(10):
   win.bind(str(i), add_label)

win.mainloop()
Running the above code snippet will display a window with a Label widget.
Whenever you press a key in the range (0-9), it will display a message on the screen.
Fetch datetime row from exactly past 7 days records in MySQL

For this, you can use the INTERVAL 7 day concept. Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   AdmissionDate datetime
);
Query OK, 0 rows affected (0.83 sec)
Note − Let’s say the current date is 2019-08-23.
Insert some records in the table using insert command −
mysql> insert into DemoTable(AdmissionDate) values('2019-01-23');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(AdmissionDate) values('2019-08-15');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(AdmissionDate) values('2019-08-16');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(AdmissionDate) values('2019-08-24');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+---------------------+
| Id | AdmissionDate       |
+----+---------------------+
|  1 | 2019-01-23 00:00:00 |
|  2 | 2019-08-15 00:00:00 |
|  3 | 2019-08-16 00:00:00 |
|  4 | 2019-08-24 00:00:00 |
+----+---------------------+
4 rows in set (0.00 sec)
Here is the query to fetch DateTime row from exactly past 7 days records −
mysql> select *from DemoTable where date(AdmissionDate)=CURDATE() - interval 7 day;
This will produce the following output −
+----+---------------------+
| Id | AdmissionDate       |
+----+---------------------+
|  3 | 2019-08-16 00:00:00 |
+----+---------------------+
1 row in set (0.04 sec)
Update multiple rows in a single MongoDB query?

Use the concept of initializeUnorderedBulkOp(). Let us first create a collection with documents −
>db.upDateMultipleRowsDemo.insertOne({"CustomerName":"John","CustomerPurchaseAmount":500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6ceb06d78f205348bc626")
}
>db.upDateMultipleRowsDemo.insertOne({"CustomerName":"Chris","CustomerPurchaseAmount":700});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6ceb26d78f205348bc627")
}
>db.upDateMultipleRowsDemo.insertOne({"CustomerName":"David","CustomerPurchaseAmount":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6ceb36d78f205348bc628")
}
>db.upDateMultipleRowsDemo.insertOne({"CustomerName":"Larry","CustomerPurchaseAmount":1900});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6ceb46d78f205348bc629")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.upDateMultipleRowsDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd6ceb06d78f205348bc626"),
   "CustomerName" : "John",
   "CustomerPurchaseAmount" : 500
}
{
   "_id" : ObjectId("5cd6ceb26d78f205348bc627"),
   "CustomerName" : "Chris",
   "CustomerPurchaseAmount" : 700
}
{
   "_id" : ObjectId("5cd6ceb36d78f205348bc628"),
   "CustomerName" : "David",
   "CustomerPurchaseAmount" : 50
}
{
   "_id" : ObjectId("5cd6ceb46d78f205348bc629"),
   "CustomerName" : "Larry",
   "CustomerPurchaseAmount" : 1900
}
Following is the query to update multiple rows in a single query −
> var manyUpdateValue = db.upDateMultipleRowsDemo.initializeUnorderedBulkOp();

> manyUpdateValue.find({ _id: ObjectId("5cd6ceb06d78f205348bc626")}).updateOne({$set:{"CustomerName":"Bob" }});

> manyUpdateValue.find({ _id: ObjectId("5cd6ceb36d78f205348bc628")}).updateOne({$set:{"CustomerPurchaseAmount":56544444}});

> manyUpdateValue.execute();
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 0,
   "nUpserted" : 0,
   "nMatched" : 2,
   "nModified" : 2,
   "nRemoved" : 0,
   "upserted" : [ ]
})
Let us check all the documents once again −
> db.upDateMultipleRowsDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd6ceb06d78f205348bc626"),
   "CustomerName" : "Bob",
   "CustomerPurchaseAmount" : 500
}
{
   "_id" : ObjectId("5cd6ceb26d78f205348bc627"),
   "CustomerName" : "Chris",
   "CustomerPurchaseAmount" : 700
}
{
   "_id" : ObjectId("5cd6ceb36d78f205348bc628"),
   "CustomerName" : "David",
   "CustomerPurchaseAmount" : 56544444
}
{
   "_id" : ObjectId("5cd6ceb46d78f205348bc629"),
   "CustomerName" : "Larry",
   "CustomerPurchaseAmount" : 1900
}
How to sum a variable by factor levels in R?

We can do this by using aggregate function or with the help tapply
> x <- data.frame(Category=factor(c("Graduation", "Graduation", "Post-Graduation",
"Graduation","PhD", "Post-Graduation", "PhD")),
Frequency=c(12,19,15,20,25,13,14))
> x
Category Frequency
1 Graduation 12
2 Graduation 19
3 Post-Graduation 15
4 Graduation 20
5 PhD 25
6 Post-Graduation 13
7 PhD 14
Using aggregate
> aggregate(x$Frequency, by=list(Group=x$Category), FUN=sum)
    Group x
1 Graduation 51
2 PhD 39
3 Post-Graduation 28
Using tapply
> tapply(x$Frequency, x$Category, FUN=sum)
Graduation PhD Post-Graduation
51         39      28
uniform() method in Python Random module - GeeksforGeeks

15 Oct, 2020
uniform() is a method specified in the random library in Python 3.
Nowadays, in general, day-day tasks, there’s always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there’s an inbuilt method, “uniform()” which performs this task with ease and using just the one word. This method is defined in “random” module
Syntax : uniform(int x, int y)
Parameters :x Specifies the lower limit of the random number required to generate.y Specifies the upper limit of the random number required to generate.
Returns : Returns the generated floating point random number between lower limit and upper limit
 Code #1 : Code to generate float random number.
# Python3 code to demonstrate# the working of uniform()  # for using uniform()import random  # initializing bounds a = 4b = 9  # printing the random numberprint("The random number generated between 4 and 9 is : ", end ="")print(random.uniform(a, b))
Output:
The random number generated between 4 and 9 is : 7.494931618830411

Application :There are many possible applications that can be thought of this function, some of the notable being generating random numbers in casino games, for lottery or custom games.Below is the game that decided the winner on the basis of closeness to a certain value.
 Code #2 : Application of uniform() – A Game
# Python3 code to demonstrate# the application of uniform()  # for using uniform()import random, math  # initializing player numbersplayer1 = 4.50player2 = 3.78player3 = 6.54  # generating winner random numberwinner = random.uniform(2, 9)  # finding closest diffa = math.fabs(winner - player1)diffb = math.fabs(winner - player2)diffc = math.fabs(winner - player3)  # printing winnerif(diffa < diffb and diffa < diffc):    print("The winner of game is : ", end ="")    print("Player1")  if(diffb < diffc and diffb < diffa):    print("The winner of game is : ", end ="")    print("Player2")      if(diffc < diffb and diffc < diffa):    print("The winner of game is : ", end ="")    print("Player3")
Output:
The winner of game is : Player2

Python-Built-in-functions
Python-Functions
Python-Library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
p5.js | torus() Function - GeeksforGeeks

22 Apr, 2019
The torus() function in p5.js is used to draw a torus with given torus radius and tube radius.
Syntax:
torus( radius, tubeRadius, detailX, detailY )
Parameters: This function accepts four parameters as mentioned above and described below:
radius: This parameter stores the radius of the torus.
tubeRadius: This parameter stores the radius of the tube.
detailX: This parameter stores the number of segments in x-dimension.
detailY: This parameter stores the number of segments in y-dimension.Below programs illustrate the torus() function in p5.js:Example 1: This example uses torus() function to draw a torus with given torus radius and tube radius.function setup() {          // Create Canvas of size 600*600    createCanvas(600, 600, WEBGL);}   function draw() {          // Set background color    background(200);         // Set fill color of torus    fill('green');         // Call to torus function    torus(90, 35, 12, 12);}Output:Example 2: This example uses torus() function to draw a torus with given torus radius and tube radius.function setup() {          // Create Canvas of size 600*600    createCanvas(600, 600, WEBGL);}   function draw() {          // Set background color    background(200);         // Set fill color of torus    fill('yellow');         // Rotate     rotateX(frameCount * 0.01);    rotate(frameCount*0.05);         // Call to torus function    torus(90, 35);}Output:Reference: https://p5js.org/reference/#/p5/torusMy Personal Notes
arrow_drop_upSave
Below programs illustrate the torus() function in p5.js:
Example 1: This example uses torus() function to draw a torus with given torus radius and tube radius.
function setup() {          // Create Canvas of size 600*600    createCanvas(600, 600, WEBGL);}   function draw() {          // Set background color    background(200);         // Set fill color of torus    fill('green');         // Call to torus function    torus(90, 35, 12, 12);}
Output:
Example 2: This example uses torus() function to draw a torus with given torus radius and tube radius.
function setup() {          // Create Canvas of size 600*600    createCanvas(600, 600, WEBGL);}   function draw() {          // Set background color    background(200);         // Set fill color of torus    fill('yellow');         // Rotate     rotateX(frameCount * 0.01);    rotate(frameCount*0.05);         // Call to torus function    torus(90, 35);}
Output:Reference: https://p5js.org/reference/#/p5/torus
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Python | Convert dictionary to list of tuples - GeeksforGeeks

08 Jul, 2021
Given a dictionary, write a Python program to convert the given dictionary into list of tuples.Examples:  
Input: { 'Geeks': 10, 'for': 12, 'Geek': 31 }
Output : [ ('Geeks', 10), ('for', 12), ('Geek', 31) ]

Input: { 'dict': 11, 'to': 22, 'list_of_tup': 33}
Output : [ ('dict', 11), ('to', 22), ('list_of_tup', 33) ]
Below are various methods to convert dictionary to list of tuples.Method #1 : Using list comprehension  
Python3
# Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Converting into list of tuplelist = [(k, v) for k, v in dict.items()] # Printing list of tupleprint(list)
[('Geek', 31), ('for', 12), ('Geeks', 10)]
 
  Method #2 : Using items()  
Python3
# Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Converting into list of tuplelist = list(dict.items()) # Printing list of tupleprint(list)
[('for', 12), ('Geeks', 10), ('Geek', 31)]
 
  Method #3 : Using zip  
Python3
# Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Using ziplist = zip(dict.keys(), dict.values()) # Converting from zip object to list objectlist = list(list) # Printing listprint(list)
[('Geek', 31), ('Geeks', 10), ('for', 12)]
 
  Method #4 : Using iteration  
Python3
# Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Initialization of empty listlist = [] # Iterationfor i in dict:   k = (i, dict[i])   list.append(k) # Printing listprint(list)
[('Geeks', 10), ('for', 12), ('Geek', 31)]
 
  Method #5 : Using collection  
Python3
# Python code to convert dictionary into list of tuples # Initialization of dictionarydict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } # Importingimport collections # Convertinglist_of_tuple = collections.namedtuple('List', 'name value') lists = list(list_of_tuple(*item) for item in dict.items()) # Printing listprint(lists)
[List(name=’for’, value=12), List(name=’Geek’, value=31), List(name=’Geeks’, value=10)] 
 
akshaysingh98088
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
What is the use of serve favicon from Node.js server ? - GeeksforGeeks

13 Jul, 2021
When the browser loads a website for the first time, it will automatically request /favicon.ico (GET) to load favicon. A favicon is a small size file as known as website icon, tab icon, URL icon or bookmark icon. The serve-favicon module is used to serve favicon from the NodeJS server.
Why to use this module?
User agents request frequently and indiscriminately for favicon. Use this middleware before your logger middleware to exclude these request from logs.
favicon.ico is small size file, this module caches the favicon in memory to give better performance by skipping dick access.
This module provides an ETag for the icon.
This module provides compatible Content-Type for the icon.
Project Setup and Module Installation:
Step 1: Create a NodeJS application and name it Project using the following command.mkdir Project && cd Project
npm init -y 
Step 1: Create a NodeJS application and name it Project using the following command.
mkdir Project && cd Project
npm init -y
 
Step 2: Install the dependency modules using the following command.npm install express serve-favicon
Step 2: Install the dependency modules using the following command.
npm install express serve-favicon
Step 3: Generate a favicon from here or download the GFG favicon and place it in your root directory. Then create index.html and server.js in your Project directory. 
Step 3: Generate a favicon from here or download the GFG favicon and place it in your root directory. Then create index.html and server.js in your Project directory. 
Project Directory: It will look like this.
Project directory
Example:
index.html
<!DOCTYPE html><html>  <head>    <title>GeeksForGeeks</title></head>  <body>    <h1 style="color: green;">        GeeksForGeeks    </h1></body>  </html>
server.js
// Import modulesconst favicon = require('serve-favicon');const express = require('express')const app = express()  // Returns a middleware to serve faviconapp.use(favicon(__dirname + '/favicon.ico'));  // API endpoint to serve index app.get('/', (_, res)=> res.sendFile(__dirname + '/index.html'))  // Start the serverapp.listen(8080);
Step to run the application: Run the server.js using the following command
node server.js
Output: Open the browser and go to http://localhost:8080/, we will see the following output on screen.
Note: Remember, serve-favicon is only serving default, implicit favicon, which is GET /favicon.ico. Use serve-static for vendor-specific icons that require HTML markup. 
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js Export Module
How to connect Node.js with React.js ?
Difference between dependencies, devDependencies and peerDependencies
Mongoose find() Function
Mongoose Populate() Method
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Python 3 - String ljust() Method

The method ljust() returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
Following is the syntax for ljust() method −
str.ljust(width[, fillchar])

width − This is string length in total after padding.
width − This is string length in total after padding.
fillchar − This is filler character, default is a space.
fillchar − This is filler character, default is a space.
This method returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s).
The following example shows the usage of ljust() method.
#!/usr/bin/python3

str = "this is string example....wow!!!"
print str.ljust(50, '*')
When we run above program, it produces the following result −
this is string example....wow!!!******************


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page