code-rag-bench/online-tutorials huggingface dataset:
Detect the RGB color from a webcam using Python - OpenCV - GeeksforGeeks

02 Sep, 2020
Prerequisites: Python NumPy, Python OpenCV
Every image is represented by 3 colors that are Red, Green and Blue. Let us see how to find the most dominant color captured by the webcam using Python.
Approach:
Import the cv2 and NumPy modulesCapture the webcam video using the cv2.VideoCapture(0) method.Display the current frame using the cv2.imshow() method.Run a while loop and take the current frame using the read() method.Take the red, blue and green elements and store them in a list.Compute the average of each list.Whichever average has the greatest value, display that color.
Import the cv2 and NumPy modules
Capture the webcam video using the cv2.VideoCapture(0) method.
Display the current frame using the cv2.imshow() method.
Run a while loop and take the current frame using the read() method.
Take the red, blue and green elements and store them in a list.
Compute the average of each list.
Whichever average has the greatest value, display that color.
Python3
# importing required librariesimport cv2import numpy as np  # taking the input from webcamvid = cv2.VideoCapture(0)  # running while loop just to make sure that# our program keep running untill we stop itwhile True:      # capturing the current frame    _, frame = vid.read()      # displaying the current frame    cv2.imshow("frame", frame)       # setting values for base colors    b = frame[:, :, :1]    g = frame[:, :, 1:2]    r = frame[:, :, 2:]      # computing the mean    b_mean = np.mean(b)    g_mean = np.mean(g)    r_mean = np.mean(r)      # displaying the most prominent color    if (b_mean > g_mean and b_mean > r_mean):        print("Blue")    if (g_mean > r_mean and g_mean > b_mean):        print("Green")    else:        print("Red")
Output:
Python-OpenCV
Python
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
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
C++ Loop Types

There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages −
C++ programming language provides the following type of loops to handle looping requirements.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Like a ‘while’ statement, except that it tests the condition at the end of the loop body.
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C++ supports the following control statements.
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Transfers control to the labeled statement. Though it is not advised to use goto statement in your program.
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the ‘for’ loop are required, you can make an endless loop by leaving the conditional expression empty.
#include <iostream>
using namespace std;
 
int main () {
   for( ; ; ) {
      printf("This loop will run forever.\n");
   }

   return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C++ programmers more commonly use the ‘for (;;)’ construct to signify an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Equivalence Class Testing- Next date problem - GeeksforGeeks

28 Jan, 2020
Equivalence class testing (Equivalence class Partitioning) is a black-box testing technique used in software testing as a major step in the Software development life cycle (SDLC). This testing technique is better than many of the testing techniques like boundary value analysis, worst case testing, robust case testing and many more in terms of time consumption and terms of precision of the test cases. Since testing is done to identify possible risks, equivalence class testing performs better than the other techniques as the test cases generated using it are logically identified with partitions in between to create different input and output classes. This can be shown from the next-date problem which is stated below:
Given a day in the format of day-month-year, you need to find the next date for the given date. Perform boundary value analysis and equivalence-class testing for this.
Conditions :
D:  1<Day<31
M:  1<Month<12
Y:  1800 <Year <2048 
Boundary Value Analysis:
No. of test Cases (n = no. of variables) = 4n+1 = 4*3 +1 =13 
Test Cases:
Equivalence Class Testing:
Input classes:
Day:
D1: day between 1 to 28
D2: 29
D3: 30 
D4: 31
Month:
M1: Month has 30 days
M2: Month has 31 days
M3: Month is February
Year:
Y1: Year is a leap year
Y2: Year is a normal year 
Output Classes:
Increment Day
Reset Day and Increment Month
Increment Year
Invalid Date

Strong Normal Equivalence Class Test Cases:
Test Cases:
So from this problem it is clearly seen that equivalence class testing clearly checks for many cases that boundary value did not considered like that of February which has 28-29 days, leap year which lead to variation in number of days in February and many more.
Hence the above example proves that equivalence partitioning generates more efficient test cases that should be considered during risk assessment.
Software Testing
Technical Scripter 2019
Software Engineering
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Functional vs Non Functional Requirements
Differences between Verification and Validation
Software Engineering | Classical Waterfall Model
Software Requirement Specification (SRS) Format
Levels in Data Flow Diagrams (DFD)
Software Engineering | SDLC V-Model
Difference between Spring and Spring Boot
Difference between Unit Testing and Integration Testing
Software Engineering | Requirements Engineering Process
Software Engineering | Software Quality Assurance
fputcsv() function in PHP

The fputcsv() function formats a line as CSV and writes it to an open file. The function returns the length of the written string.
fputcsv(file_pointer, fields, delimiter, enclosure, escape)
file_pointer − A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
file_pointer − A valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
fields − Array of string.
fields − Array of string.
delimiter − Character that specifies the field separator. Default is comma ( , )
delimiter − Character that specifies the field separator. Default is comma ( , )
enclosure − Set the field enclosure character. Defaults as a double quotation mark.
enclosure − Set the field enclosure character. Defaults as a double quotation mark.
escape − Set the escape character. Defaults as a backslash (\).
escape − Set the escape character. Defaults as a backslash (\).
The fputcsv() function returns the length of the written string.
The following is an example that writes content to the “employees.csv” file.
<?php
$mylist = array (
   "Jack,Tim",
   "Henry,Tom",
);
$file_pointer = fopen("employees.csv","w");
foreach ($mylist as $line) {
   fputcsv($file_pointer,explode(',',$line));
}
fclose($file_pointer);
?>
The CSV file “employees.csv” will have the following content now.
Jack,Tim,
Henry,Tom
How to return an object from a JavaScript function?

To return an object from a JavaScript function, use the return statement, with this keyword.
You can try to run the following code to return an object from a JavaScipt function −
 Live Demo
<html>
   <head>
      <script>
         var employee = {
            empname: "David",
            department : "Finance",
            id : 002,
            details : function() {
               return this.empname + " with Department " + this.department;
            }
         };

         document.write(employee.details());
      </script>
   </head>
</html>
How to catch ZeroDivisionError Exception in Python?

When zero shows up in the denominator of a division operation, a ZeroDivisionError is raised.
We re-write the given code as follows to handle the exception and find its type.
import sys
try:
x = 11/0
print x
except Exception as e:
print sys.exc_type
print e
<type 'exceptions.ZeroDivisionError'>
integer division or modulo by zero
Max Heap in Java

Max heap is a complete binary tree, wherein the value of a root node at every step is greater than or equal to value at the child node.
Below is an implementation of Max Heap using library functions.
 Live Demo
import java.util.*;
public class Demo{
   public static void main(String args[]){
      PriorityQueue<Integer> my_p_queue = new PriorityQueue<Integer>(Collections.reverseOrder());
      my_p_queue.add(43);
      my_p_queue.add(56);
      my_p_queue.add(99);
      System.out.println("The elements in the priority queue are : ");
      Iterator my_iter = my_p_queue.iterator();
      while (my_iter.hasNext())
      System.out.println(my_iter.next());
      my_p_queue.poll();
      System.out.println("After removing an element using the poll function, the queue elements are :");
      Iterator<Integer> my_iter_2 = my_p_queue.iterator();
      while (my_iter_2.hasNext())
      System.out.println(my_iter_2.next());
      Object[] my_arr = my_p_queue.toArray();
      System.out.println("The array representation of max heap : ");
      for (int i = 0; i < my_arr.length; i++)
      System.out.println("Value: " + my_arr[i].toString());
   }
}
The elements in the priority queue are :
99
43
56
After removing an element using the poll function, the queue elements are :
56
43
The array representation of max heap :
Value: 56
Value: 43
A class named Demo contains the main function. Inside the main function, an instance of priority queue is defined and elements are added into it using the ‘add’ function. An iterator is defined and it
is used to iterate over the elements in the priority queue. The ‘poll’ function is used to remove an element from the list. Next, the elements are iterated over and displayed on the screen.
Identify last document from MongoDB find() result set?

To identify the last document from MongoDB find() result set, you can use sort() in descending order. The syntax is as follows −
db.yourCollectionName.find().sort( { _id : -1 } ).limit(1).pretty();
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.identifyLastDocuementDemo.insertOne({"UserName":"Larry","UserAge":24,"UserCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a2ff4cf1f7a64fa4df57")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Chris","UserAge":21,"UserCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a3094cf1f7a64fa4df58")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"David","UserAge":25,"UserCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a3174cf1f7a64fa4df59")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Sam","UserAge":26,"UserCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a3224cf1f7a64fa4df5a")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Mike","UserAge":27,"UserCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a32e4cf1f7a64fa4df5b")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Carol","UserAge":28,"UserCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a33c4cf1f7a64fa4df5c")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.identifyLastDocuementDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c94a2ff4cf1f7a64fa4df57"),
   "UserName" : "Larry",
   "UserAge" : 24,
   "UserCountryName" : "US"
}
{
   "_id" : ObjectId("5c94a3094cf1f7a64fa4df58"),
   "UserName" : "Chris",
   "UserAge" : 21,
   "UserCountryName" : "UK"
}
{
   "_id" : ObjectId("5c94a3174cf1f7a64fa4df59"),
   "UserName" : "David",
   "UserAge" : 25,
   "UserCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c94a3224cf1f7a64fa4df5a"),
   "UserName" : "Sam",
   "UserAge" : 26,
   "UserCountryName" : "US"
}
{
   "_id" : ObjectId("5c94a32e4cf1f7a64fa4df5b"),
   "UserName" : "Mike",
   "UserAge" : 27,
   "UserCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"),
   "UserName" : "Carol",
   "UserAge" : 28,
   "UserCountryName" : "UK"
}
Here is the query to identify the last document from MongoDB find() result set −
> db.identifyLastDocuementDemo.find().sort( { _id : -1 } ).limit(1).pretty();
The following is the output −
{
   "_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"),
   "UserName" : "Carol",
   "UserAge" : 28,
   "UserCountryName" : "UK"
}
Is it impossible to add a column in MySQL specifically before another column?

No, you can easily add a column before another column using ALTER.
Note − To add a column at a specific position within a table row, use FIRST or AFTER col_name Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20),
   -> CountryName varchar(100)
   -> );
Query OK, 0 rows affected (0.67 sec)
Let us check all the column names from the table −
mysql> show columns from DemoTable;
This will produce the following output −
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id          | int(11)      | YES  |     | NULL    |       |
| Name        | varchar(20)  | YES  |     | NULL    |       |
| CountryName | varchar(100) | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
Following is the query to add a column before another column in MySQL.
mysql> alter table DemoTable add Age int AFTER Name;
Query OK, 0 rows affected (1.50 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check all the column names from the above table once again −
mysql> show columns from DemoTable;
This will produce the following output. We have successfully added a column name −
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id          | int(11)      | YES  |     | NULL    |       |
| Name        | varchar(20)  | YES  |     | NULL    |       |
| Age         | int(11)      | YES  |     | NULL    |       |
| CountryName | varchar(100) | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
How to parse json string  in android?

This example demonstrates How to parse JSON string in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
   <TextView
      android:id = "@+id/text"
      android:textSize = "30sp"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken a text view to show the json element name.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.KeyguardManager;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   String json = "{"
      + " \"geodata\": ["
      + " {"
      + " \"id\": \"1\","
      + " \"name\": \"Julie Sherman\","
      + " \"gender\" : \"female\","
      + " \"latitude\" : \"37.33774833333334\","
      + " \"longitude\" : \"-121.88670166666667\""
      + " },"
      + " ]"
      + "}";
   @RequiresApi(api = Build.VERSION_CODES.N)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      try {
         final JSONObject obj = new JSONObject(json);
         final JSONArray geodata = obj.getJSONArray("geodata");
         final JSONObject person = geodata.getJSONObject(0);
         textView.setText(person.getString("name"));
      } catch (JSONException e) {
         e.printStackTrace();
      }
   }
   @Override
   protected void onStop() {
      super.onStop();
   }
   @Override
   protected void onResume() {
      super.onResume();
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
TypeScript - Ifâ¦else Statement

An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if statement evaluates to false.
if(boolean_expression) {  
   // statement(s) will execute if the boolean expression is true
} else {
   // statement(s) will execute if the boolean expression is false  
}

The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true.
The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false.
var num:number = 12; 
if (num % 2==0) { 
   console.log("Even"); 
} else {
   console.log("Odd"); 
}

On compiling, it will generate the following JavaScript code −
//Generated by typescript 1.8.10
var num = 12;
if (num % 2 == 0) {
   console.log("Even");
} else {
   console.log("Odd");
}

The above example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same. Here is the output of the above code −
Even 


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
How do I use PIL with Tkinter?

The PIL or Pillow package in Python provides a way to process images in a program. We can open an image, manipulate the image for different use, and can use it to visualize the data as well. In order to use the PIL package in Tkinter, you've to install the Python Pillow library in your environment.
To install Pillow, just type pip install pillow. Once the installation has been successful, you can import the module in your project and use it for further implementation.
In this example, we've displayed an image in the canvas widget using Python Pillow package.
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

# Create a canvas widget
canvas=Canvas(win, width=700, height=350)
canvas.pack()

# Load the image
img=ImageTk.PhotoImage(file="opera.jpg")

# Add the image in the canvas
canvas.create_image(350, 200, image=img, anchor="center")

win.mainloop()
If we run the above code, it will display an image in the window.
Java program to find the percentage of uppercase, lowercase, digits and special characters in a String

Convert the given string into an array of characters for each character of the array verify whether it is upper case, lower case, digit or, any other character using isUpperCase(), isLowerCase(), isDigit() method of the Character class.
Live Demo
public class Sample2 {
   public static void main(String args[]) {
      String data = "Hello HOW are you MR 51";
      char [] charArray = data.toCharArray();
      int upper = 0;
      int lower = 0;
      int digit = 0;
      int others = 0;

      int totalChars = data.length();
      for(int i=0; i<data.length(); i++) {
         if (Character.isUpperCase(charArray[i])) {
            upper++;
         } else if(Character.isLowerCase(charArray[i])) {
            lower++;
         } else if(Character.isDigit(charArray[i])){
            digit++;
         } else {
            others++;
         }
      }
      System.out.println("Total length of the string :"+totalChars);
      System.out.println("Upper case :"+upper);
      System.out.println("Percentage of upper case letters: "+(upper*100)/totalChars);
      System.out.println("Lower case :"+lower);
      System.out.println("Percentage of lower case letters:"+(lower*100)/totalChars);
      System.out.println("Digit :"+digit);
      System.out.println("Percentage of digits :"+(digit*100)/totalChars);
      System.out.println("Others :"+others);
      System.out.println("Percentage of other characters :"+(others*100)/totalChars);
   }
}
Total length of the string :23
Upper case :6
Percentage of upper case letters: 26
Lower case :10
Percentage of lower case letters:43
Digit :2
Percentage of digits :8
Others :5
Percentage of other characters :21
How to remove all Global Modules in Node.js ?

01 Jul, 2020
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside of a browser. You need to remember that Node.js is not a framework and it’s not a programming language. Most of the people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services like APIs like Web App or Mobile App. It is used in production by large companies such as Paypal, Uber, Netflix, Wallmart, and so on.
We can remove all the module globally in Node.js by the following ways:
For Linux (Ubuntu) users: In order to uninstall the globally installed package_name package, the following command can be used (using sudo if necessary, depending on your setup and permissions).
sudo npm rm --global package_name

To check whether the package is installed globally or not, use below command:
npm ls --global packae_name

Below images display the use of above command to uninstall express package globally:
For Window users: The Windows user can remove all the Node.js modules globally by just deleting the content of the following directory:
C:\Users\username\AppData\Roaming\npm
Steps to remove Global Modules:
Press win + r (win = Windows button) from keyboard and a dialog box will appear as shown below:Now type %appdata%/npm in the text field and press enter button as shown below:The directory will have files and folders as shown below:Now delete the content of this directory.
Press win + r (win = Windows button) from keyboard and a dialog box will appear as shown below:
Now type %appdata%/npm in the text field and press enter button as shown below:The directory will have files and folders as shown below:
The directory will have files and folders as shown below:
Now delete the content of this directory.
All the global node modules are removed properly.
Node.js-Misc
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Working of Keyword long in C programming

13 Oct, 2018
long is a keyword in Java that symbolises the Long datatype. The long data type is a 64-bit two’s complement integer with:
Size: 64 bit
Value: -263 to 263-1.
Output of 64 bit GCC compiler would give the size of long as 8 whereas on 32 bit GCC compiler the size would be 4. So it varies from compiler to compiler. Now the question is what exactly is happening here? Let’s discuss it in the way of how compiler allocates memory internally.
CPU calls data from RAM by giving the address of the location to MAR (Memory Address Register). The location is found and the data is transferred to MDR (Memory Data Register). This data is recorded in one of the Registers in the Processor for further processing. That’s why size of Data Bus determines the size of Registers in Processor. Now, a 32 bit register can call data of 4 bytes size only, at a time. And if the data size exceeds 32 bits, then it would required two cycles of fetching to have the data in it. This slows down the speed of 32 bit Machine compared to 64 bit, which would complete the operation in ONE fetch cycle only. So, obviously for the smaller data, it makes no difference if my processors are clocked at the same speed. Compilers are designed to generate the most efficient code for the target machine architecture.
Note: Interestingly we don’t have any need of “long” data type as their replacement(int, long long) is already available from C99 standard.
In the below program, all the possible variables with long datatype are defined and their sizes are calculated and print using sizeof() operator.
Below is the C program to find the demonstrate working of long keyword:
// C program to demonstrate the working// of long keyword  #include <stdio.h>  int main(){      long longType;    int integerType;    long int longIntegerType;    long long int longLongIntegerType;    float floatType;    double doubleType;    long double longDoubleType;      // Calculate and Print the size of all variables    printf("Size of longType is: %ld\n",           sizeof(longType));    printf("Size of integerType is: %ld\n",           sizeof(integerType));    printf("Size of longIntegerType is: %ld\n",           sizeof(longIntegerType));    printf("Size of longLongIntegerType is: %ld\n",           sizeof(longLongIntegerType));    printf("Size of floatType is: %ld\n",           sizeof(floatType));    printf("Size of doubleType is: %ld\n",           sizeof(doubleType));    printf("Size of longDoubleType is: %ld\n",           sizeof(longDoubleType));    return 0;}
Output:
Size of longType is: 8
Size of integerType is: 4
Size of longIntegerType is: 8
Size of longLongIntegerType is: 8
Size of floatType is: 4
Size of doubleType is: 8
Size of longDoubleType is: 16

C-Data Types
cpp-data-types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Sort list of tuples by specific ordering

26 Feb, 2019
The normal sorting of tuples has been dealt previously. This article aims at sorting the given list of tuples by the second element, based on the order provided in some list.
Method #1 : Using list comprehension + filter() + lambdaAbove three functions can be combined to perform the particular task in which list comprehension performs the iteration, lambda function is used as helper function for filtering to sort according to second element of tuple.
# Python3 code to demonstrate# sort list of tuples according to second# using list comprehension + filter() + lambda  # initializing list of tuplestest_list = [('a', 2), ('c', 3), ('d', 4)]  # initializing sort order sort_order = [4, 2, 3]  # printing the original listprint ("The original list is : " + str(test_list))  # printing sort order list print ("The sort order list is : " + str(sort_order))  # using list comprehension + filter() + lambda# sort list of tuples according to secondres = [i for j in sort_order       for i in filter(lambda k: k[1] == j, test_list)]  # printing resultprint ("The list after appropriate sorting : " + str(res))
The original list is : [('a', 2), ('c', 3), ('d', 4)]
The sort order list is : [4, 2, 3]
The list after appropriate sorting : [('d', 4), ('a', 2), ('c', 3)]

 Method #2 : Using sorted() + index() + lambdaThe sorted function can be used to sort according to order specified. The index function specifies that second element of tuple has to be taken into considerations and all are joined with help of lambda.
# Python3 code to demonstrate# sort list of tuples according to second# using sorted() + index() + lambda  # initializing list of tuplestest_list = [('a', 2), ('c', 3), ('d', 4)]  # initializing sort order sort_order = [4, 2, 3]  # printing the original listprint ("The original list is : " + str(test_list))  # printing sort order list print ("The sort order list is : " + str(sort_order))  # using sorted() + index() + lambda# sort list of tuples according to secondres = list(sorted(test_list,       key = lambda i: sort_order.index(i[1])))  # printing resultprint ("The list after appropriate sorting : " + str(res))
The original list is : [('a', 2), ('c', 3), ('d', 4)]
The sort order list is : [4, 2, 3]
The list after appropriate sorting : [('d', 4), ('a', 2), ('c', 3)]

Python list-programs
Python tuple-programs
python-list
python-tuple
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Map clear() method in Java with Example

31 Dec, 2018
The java.util.Map.clear() method in Java is used to clear and remove all of the elements or mappings from a specified Map collection.
Syntax:
void clear()
Parameters: The method does not accept any parameters.
Return Value: The method does not return any value.
Below programs are used to illustrate the working of java.util.Map.clear() Method:
Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the clear() methodimport java.util.*;  public class Map_Demo {    public static void main(String[] args)    {        // Creating an empty Map        Map<Integer, String> map = new HashMap<Integer, String>();          // Mapping string values to int keys        map.put(10, "Geeks");        map.put(15, "4");        map.put(20, "Geeks");        map.put(25, "Welcomes");        map.put(30, "You");          // Displaying the Map        System.out.println("Initial Mappings are: " + map);          // Clearing the map using clear()        map.clear();          // Displaying the final HashMap        System.out.println("Finally the maps look like this: " + map);    }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Finally the maps look like this: {}

Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the clear() methodimport java.util.*;  public class Map_Demo {    public static void main(String[] args)    {          // Creating an empty Map        Map<String, Integer> map = new HashMap<String, Integer>();          // Mapping int values to string keys        map.put("Geeks", 10);        map.put("4", 15);        map.put("Geeks", 20);        map.put("Welcomes", 25);        map.put("You", 30);          // Displaying the Map        System.out.println("Initial Mappings are: " + map);          // Clearing the map using clear()        map.clear();          // Displaying the final Map        System.out.println("Finally the maps look like this: " + map);    }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
Finally the maps look like this: {}

Note: The same operation can be performed with any type of Mapping with variation and combination of different data types.
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#clear()
Java-Collections
Java-Functions
java-map
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Create Constant Variable in Python using Pconst Library

03 Mar, 2021
Constant variable the name itself says that it is constant. We have to define a constant variable at the time of declaration. After that, we will not able to change the value of a constant variable. In some cases, constant variables are very useful.
Creating constant variables, functions, objects is allowed in languages like c++, Java. But in python creating constant variable, it is not allowed. There is no predefined type for a constant variable in Python. But we can use pconst library for that.
Installation:
pip install pconst
Below are some examples which depict how to use constants in python
Example 1:
You can set constants to const module’s attribute.
Python3
# import modulefrom pconst import const  # declare constantsconst.LANGUAGE = "PYTHON"const.COMPANY_NAME = 'GFG'  # displayprint(const.LANGUAGE)print(const.COMPANY_NAME)
Output:
Example 2:
If try to update the constant value, ConstantError will be raised.
Python3
# import modulefrom pconst import const  # declare constantsconst.LANGUAGE = "PYTHON"const.COMPANY_NAME = 'GFG'  # updateconst.LANGUAGE="C++"
Output:
Example 3:
The del operator is disallowed.
Python3
# import modulefrom pconst import const  # declare constantsconst.LANGUAGE = "PYTHON"const.COMPANY_NAME = 'GFG'  # deletedel const.LANGUAGE
Output: 
Example 4: 
You can also set dict and list value to const module, and they will be not editable (if dict or list values contains dict or list, then will be applied recursively.).
Python3
# import modulefrom pconst import const  # define dictionaryconst.COMPANY_DATA = {    'Name': "GFG",    'Language': ["C", "C++",                  "Python"]}  # displayprint('Name:', const.COMPANY_DATA['Name'])print('Language:', const.COMPANY_DATA['Language'])
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
EmBomber – Email Bomber Tool in Kali Linux

29 Jun, 2021
EmBomber tool is used to perform call and SMS bombing on the target Email address.  You must ensure that you always install the latest version of EmBomber from GitHub in order to not get stuck with the working of the tool. This tool works with open-source intelligence APIs that’s why this tool requires an internet connection to perform bombing. EmBomber is a free and an open-source tool available on GitHub. This tool takes your email address. You only have to enter the target email address and the tool will do the rest of the work.
Note: This tool is written in Python. You must have python installed in your kali linux operating system.
Step 1: Open your kali Linux operating system and use the following command to install the tool from GitHub and then move to the tool directory using the second command.
git clone https://github.com/MazenElzanaty/EmBomber.git
cd EmBomber
Step 2: The tool has been downloaded now, so use the following command to run the tool.
python EmBomber.py
The tool has been downloaded and installed successfully. Now we see an example to use the command.
Example 1: Use the EmBomber tool to perform email bombing on an email address.
1
Now Provide the email by which you want to sent and then provide email at  which you wantbombing to send email.
You can see that Bombing has started on the target email address. The tool has started sending the emails, some of them get success some of them failed but you can try again and again for best results. The email failed due to poor internet connection if your internet is good then no emails of yours will fail.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas MultiIndex.droplevel()

24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas MultiIndex.droplevel() function return Index with requested level removed. If MultiIndex has only 2 levels, the result will be of Index type not MultiIndex..
Syntax: MultiIndex.droplevel(level=0)
Parameters :level : int/level name or list thereof
Returns : index : Index or MultiIndex
Example #1: Use MultiIndex.droplevel() function to drop the 0th level of the MultiIndex.
# importing pandas as pdimport pandas as pd  # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography',                                      'Anthropology', 'Science'],                                              [88, 84, 98, 95]])  # Print the MultiIndexprint(midx)
Output :
Now let’s drop the 0th level of the MultiIndex.
# drop the 0th level.midx.droplevel(level = 0)
Output :As we can see in the output, the function has dropped the 0th level and returned an Index object. Example #2: Use MultiIndex.droplevel() function to drop the 1st level of the MultiIndex.
# importing pandas as pdimport pandas as pd  # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography',                                     'Anthropology', 'Science'],                                              [88, 84, 98, 95]])  # Print the MultiIndexprint(midx)
Output :
Now let’s drop the 1st level of the MultiIndex.
# drop the 1st level.midx.droplevel(level = 1)
Output :As we can see in the output, the function has dropped the 1st level and returned an Index object.
Python pandas-multiIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get table column names in alphabetical order in MySQL?

To get the table column names in alphabetical order, you need to use ORDER BY. The syntax
is as follows −
SELECT anyReferenceName.COLUMN_NAME FROM
INFORMATION_SCHEMA.COLUMNS anyReferenceName
WHERE anyReferenceName.TABLE_NAME = ’yourTableName’
ORDER BY anyReferenceName.COLUMN_NAME
First, we need to get all the columns and then we need to use ORDER BY. In the above query,
we are getting all columns using INFORMATION_SCHEMA.COLUMNS.
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table ColumnsOrder
   -> (
   -> StudentFirstName varchar(20),
   -> Id int,
   -> StudentAge int,
   -> StudentLastName varchar(20)
   -> );
Query OK, 0 rows affected (0.90 sec)
Implement the above syntax to get table columns in alphabetical order.
Case 1 − By default, ORDER BY gives ascending order.
The query is as follows −
mysql> select ref.column_name from information_schema.columns ref
   -> where ref.table_name = 'ColumnsOrder'
   -> order by ref.column_name;
The following is the output −
+------------------+
| COLUMN_NAME      |
+------------------+
| Id               |
| StudentAge       |
| StudentFirstName |
| StudentLastName  |
+------------------+
4 rows in set (0.13 sec)
Case 2 − If you want in descending order, then use DESC command in the end. 
The query is as follows −
mysql> select ref.column_name from information_schema.columns ref
   -> where ref.table_name = 'ColumnsOrder'
   -> order by ref.column_name desc;
The following is the output −
+------------------+
| COLUMN_NAME      |
+------------------+
| StudentLastName  |
| StudentFirstName |
| StudentAge       |
| Id               |
+------------------+
4 rows in set (0.00 sec)
Get unique values from a column in Pandas DataFrame - GeeksforGeeks

10 Dec, 2018
Let’s discuss how to get unique values from a column in Pandas DataFrame.
Create a simple dataframe with dictionary of lists, say columns name are A, B, C, D, E with duplicate elements.
Now, let’s get the unique values of a column in this dataframe.
Example #1: Get the unique values of ‘B’ column
# Import pandas package import pandas as pd  # create a dictionary with five fields eachdata = {    'A':['A1', 'A2', 'A3', 'A4', 'A5'],     'B':['B1', 'B2', 'B3', 'B4', 'B4'],     'C':['C1', 'C2', 'C3', 'C3', 'C3'],     'D':['D1', 'D2', 'D2', 'D2', 'D2'],     'E':['E1', 'E1', 'E1', 'E1', 'E1'] }  # Convert the dictionary into DataFrame df = pd.DataFrame(data)  # Get the unique values of 'B' columndf.B.unique()
Output:
 Example #2: Get the unique values of ‘E’ column
# Import pandas package import pandas as pd  # create a dictionary with five fields eachdata = {    'A':['A1', 'A2', 'A3', 'A4', 'A5'],     'B':['B1', 'B2', 'B3', 'B4', 'B4'],     'C':['C1', 'C2', 'C3', 'C3', 'C3'],     'D':['D1', 'D2', 'D2', 'D2', 'D2'],     'E':['E1', 'E1', 'E1', 'E1', 'E1'] }  # Convert the dictionary into DataFrame df = pd.DataFrame(data)  # Get the unique values of 'E' columndf.E.unique()
Output:
Example #3: Get number of unique values in a column
# Import pandas package import pandas as pd  # create a dictionary with five fields eachdata = {    'A':['A1', 'A2', 'A3', 'A4', 'A5'],     'B':['B1', 'B2', 'B3', 'B4', 'B4'],     'C':['C1', 'C2', 'C3', 'C3', 'C3'],     'D':['D1', 'D2', 'D2', 'D2', 'D2'],     'E':['E1', 'E1', 'E1', 'E1', 'E1'] }  # Convert the dictionary into DataFrame df = pd.DataFrame(data)  # Get number of unique values in column 'C'df.C.nunique(dropna = True)
Output:
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Update a column of text with MySQL REPLACE()

Let us first create a table −
mysql> create table DemoTable
(
   Code varchar(100)
);
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('8565-9848-7474');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('9994-6464-8737');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('6574-9090-7643');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------------+
| Code           |
+----------------+
| 8565-9848-7474 |
| 9994-6464-8737 |
| 6574-9090-7643 |
+----------------+
3 rows in set (0.00 sec)
Following is the query to replace column value −
mysql> update DemoTable
set Code=replace(Code,'9994-6464-8737','9994-9999-88888');
Query OK, 1 row affected (0.10 sec)
Rows matched : 3 Changed : 1 Warnings : 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-----------------+
| Code            |
+-----------------+
| 8565-9848-7474  |
| 9994-9999-88888 |
| 6574-9090-7643  |
+-----------------+
3 rows in set (0.00 sec)
numpy.geomspace() in Python - GeeksforGeeks

31 May, 2021
numpy.geomspace() is used to return numbers spaced evenly on a log scale (a geometric progression). This is similar to numpy.logspace() but with endpoints specified directly. Each output sample is a constant multiple of the previous.  
Syntax : numpy.geomspace(start, stop, num=50, endpoint=True, dtype=None)Parameters : start : [scalar] The starting value of the sequence. stop : [scalar] The final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned. num : [integer, optional] Number of samples to generate. Default is 50. endpoint : [boolean, optional] If true, stop is the last sample. Otherwise, it is not included. Default is True. dtype : [dtype] The type of the output array. If dtype is not given, infer the data type from the other input arguments.Return : samples : [ndarray] num samples, equally spaced on a log scale.  
Code #1 : Working  
Python
# Python3 Program demonstrate# numpy.geomspace() function import numpy as geek  print("B\n", geek.geomspace(2.0, 3.0, num = 5), "\n") # To evaluate sin() in long rangepoint = geek.geomspace(1, 2, 10)print("A\n", geek.sin(point))
Output :  
B
 [ 2.          2.21336384  2.44948974  2.71080601  3.        ] 

A
 [ 0.84147098  0.88198596  0.91939085  0.95206619  0.9780296   0.9948976
  0.99986214  0.98969411  0.96079161  0.90929743]
  Code #2 : Graphical Representation of numpy.geomspace()  
Python
# Graphical Representation of numpy.geomspace()import numpy as geekimport pylab as p% matplotlib inline  # Start = 1# End = 3 # Samples to generate = 10x1 = geek.geomspace(1, 3, 10, endpoint = False)y1 = geek.ones(10)   p.plot(x1, y1, '+')
Output :  
 
anikaseth98
Pyhton numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python
DUAL table in SQL - GeeksforGeeks

25 Aug, 2020
There may be a situation where we want to query something that is not from a table. For example, getting the current date or querying a simple arithmetic expression like 2+2.
In Oracle, clause FROM is not exceptional. If we don’t write the FROM clause in Oracle, we’ll get an error.
Example-1: Oracle Query
SELECT SYSDATE;
Output –
ORA-00923: FROM keyword not found where expected
Example-2: Oracle Query
SELECT 'GeeksforGeeks';
Output –
ORA-00923: FROM keyword not found where expected
DUAL :It is a table that is automatically created by Oracle Database along with the data dictionary. DUAL is in the schema of the user SYS but is accessible by the name DUAL to all users. It has one column, DUMMY, defined to be VARCHAR2(1), and contains one row with a value X.
Example: Oracle Query
SELECT * 
FROM DUAL ;
Output –
X 
Selecting from the DUAL table is useful for computing a constant expression with the SELECT statement. Because DUAL has only one row, the constant is returned only once.
Oracle Query :
SELECT 'GeeksforGeeks' 
AS NAME FROM DUAL;
Output –
GeeksforGeeks 
Oracle Query :
SELECT 2+2 
FROM DUAL;
Output :
2+2 = 4 
Several other databases, including MS SQL Server, MySQL, PostgreSQL and SQLite, allows the omitting of FROM clause. This exception is the reason there is no dummy table like DUAL in other databases.
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of B-Tree
Difference between Clustered and Non-clustered index
CTE in SQL
SQL | Views
SQL Interview Questions
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?