code-rag-bench/online-tutorials huggingface dataset:
How to find min/max values without Math functions in JavaScript ? - GeeksforGeeks

09 Nov, 2021
In this article, we will learn how to find the minimum and maximum values in an array without using Math functions. We know that Math.max() returns the maximum number passed in an array whereas Math.min() returns the minimum number passed.
Approach: The same functionality of the Math functions can be implemented using a loop that will iterate the numbers present in the array to find maximum and minimum values inside the array.
We will keep checking all the elements in the array using a loop. If we find any element greater than the previous “max” value, we set that value as the max value. Similarly, we keep on checking for any element lesser than the “min” value. If we get any such element, we replace the value of “min” with a smaller value. Thus, using the loop function, we can get the maximum and minimum values entered in an array/list.
The below example will demonstrate the above approach.
Example:
JavaScript
<script>      // Array of numbers where the maximum    // and minimum are to be found    const array = [-1, 2, -5, 8, 16];      // Setting a number of the given array as    // value of max and min we choose 0th index    // element as atleast one element should be    // present in the given array      let max = array[0], min = array[0];    for (let i = 0; i < array.length; i++) {          // If we get any element in array greater        // than max, max takes value of that        // larger number        if (array[i] > max) { max = array[i]; }          // If we get any element in array smaller        // than min, min takes value of that        // smaller number        if (array[i] < min) { min = array[i]; }    }    console.log("max = " + max);    console.log("min = " + min);</script>
Output: The maximum and the minimum number of the array is found using the approach.
max = 16
min = -5
JavaScript-Questions
Picked
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 ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Python | Pandas Series.set_value() - GeeksforGeeks

05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.set_value() function is used to set value of the given series object using the index labels.
Syntax: Series.set_value(label, value, takeable=False)
Parameter :label : Partial indexing with MultiIndex not allowedvalue : Scalar valuetakeable : interpret the index as indexers, default False
Returns : series
Example #1: Use Series.set_value() function to set the value in the given series object using the index labels.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.set_value() function to set the value corresponding to the passed index label.
# set the valuesr.set_value('City 2', 'Dublin')
Output :
As we can see in the output, the Series.set_value() function has successfully set the value of the passed index label. Example #2: Use Series.set_value() function to set the value in the given series object using the index labels.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65])  # Print the seriesprint(sr)
Output :
Now we will use Series.set_value() function to set the value in the given series object.
# set the value to 1000 of# the passed index labelsr.set_value(3, 1000)
Output :
As we can see in the output, the Series.set_value() function has successfully set the value of the passed index label.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Convert integer to string in Python - GeeksforGeeks

12 May, 2022
In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the “%s” keyword, the .format function or using f-string function.
Below is the list of possible ways to convert an integer to string in python:
1. Using str() function 
Syntax: str(integer_value)
Example:  
Python3
num = 10  # check  and print type of num variableprint(type(num))   # convert the num into stringconverted_num = str(num)  # check  and print type converted_num variableprint(type(converted_num))
2. Using “%s” keyword
Syntax: “%s” % integer
Example: 
Python3
num = 10  # check  and print type of num variableprint(type(num))   # convert the num into string and printconverted_num = "% s" % numprint(type(converted_num))
3. Using .format() function
Syntax: ‘{}’.format(integer)
Example: 
Python3
num = 10  # check  and print type of num variableprint(type(num))   # convert the num into string and printconverted_num = "{}".format(num)print(type(converted_num))
4. Using f-string
Syntax: f'{integer}’
Example: 
Python3
num = 10  # check  and print type of num variableprint(type(num))   # convert the num into string converted_num = f'{num}'  # print type of converted_numprint(type(converted_num))
rahulas1505
python-basics
Python-Data Type
Python-datatype
python-string
Python
Write From Home
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
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java
Similarities and Difference between Java and C++
Python Program to check if given array is Monotonic - GeeksforGeeks

05 Nov, 2018
Given an array A containing n integers. The task is to check whether the array is Monotonic or not. An array is monotonic if it is either monotone increasing or monotone decreasing.An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].Return “True” if the given array A is monotonic else return “False” (without quotes).
Examples:
Input : 6 5 4 4
Output : true

Input : 5 15 20 10
Output : false

Approach:An array is monotonic if and only if it is monotone increasing, or monotone decreasing. Since p <= q and q <= r implies p <= r. So we only need to check adjacent elements to determine if the array is monotone increasing (or decreasing), respectively. We can check each of these properties in one pass.To check whether an array A is monotone increasing, we’ll check A[i] <= A[i+1] for all i indexing from 0 to len(A)-2. Similarly we can check for monotone decreasing where A[i] >= A[i+1] for all i indexing from 0 to len(A)-2.Note: Array with single element can be considered to be both monotonic increasing or decreasing, hence returns “True“.
Below is the implementation of above approach:
Python3
# Python3 program to find sum in Nth group  # Check if given array is Monotonicdef isMonotonic(A):      return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or            all(A[i] >= A[i + 1] for i in range(len(A) - 1)))  # Driver programA = [6, 5, 4, 4]  # Print required resultprint(isMonotonic(A))  # This code is written by# Sanjit_Prasad
True
Time Complexity: O(N), where N is the length of array.
Arrays
Greedy
Python Programs
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3
Difference between Normal Processor and AI Processor - GeeksforGeeks

17 Jul, 2020
Normal Processor :The processors mainly used in several personal computers are normal processors. Basically the central processing unit is described as a processor of the system. It uses integrated chips to organize all the components at a single place. Different brands provide different load based processors for computer systems and mobile systems. The processors are designed on the basis of versions and generations.Example:
Intel i5, AMD A8
AI processor :The processors used in artificial intelligence and machine learning-based systems are known as AI processors. These are basically the neuromorphic processing units which are designed on the basis of machine learning and artificial neural network. These processors are fast and able to read the human behavioural conditions and do computation the on basis of it.Example:
Intel Habana
Difference between Normal Processor and AI processor :
Computer Organization & Architecture
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Architecture of 8085 microprocessor
Architecture of 8086
Pin diagram of 8086 microprocessor
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
CONCAT_WS() Function in MySQL - GeeksforGeeks

03 Dec, 2020
CONCAT_WS() :This function in MySQL helps in joining two or more strings along with a separator. The separator must be specified by the user and it can also be a string. If the separator is NULL, then the result will also be NULL.
Syntax :
CONCAT_WS(separator, string1, string2, ...)
Parameters :
separator –A separator which will be added between the strings while concatenation string1, string2, etc.
[string1, string2 ...] –The input strings which needed to be concatenated.
Return :It will return a new string, after concatenating all given strings, along with a specified separator. And if all input strings are NULL, then the result will be NULL. If the separator is NULL, it will return NULL.
Example 1 :Concatenating 2 strings using CONCAT_WS Function as follows.
SELECT CONCAT_WS(": ", "Geek ", "Vansh ") AS ConcatWsStr;
Output :
Example-2 :Concatenating 3 strings using CONCAT_WS Function as follows.
SELECT CONCAT_WS("@ ", "Geek ", "Vansh ", 13 ) AS ConcatWsStr;
Output :
Example-3 :Concatenating a NULL string using NULL separator as follows.
SELECT CONCAT_WS(NULL, NULL, "Vansh ", 13 ) AS ConcatWsStr;
Output :
Example-4 :Concatenating the columns of a table using CONCAT_WS Function as follows.
Creating an Employee table :
CREATE TABLE Emp(
Employee_Id INT AUTO_INCREMENT,  
FirstName VARCHAR(100) NOT NULL,
LastName VARCHAR(100) NOT NULL,
Residence VARCHAR(50) NOT NULL,
Salary INT  NOT NULL,
PRIMARY KEY(Employee_Id )
);

Inserting data into the Table :
INSERT INTO Emp(FirstName, LastName, Residence, Salary )
VALUES
('Animesh', 'Garg', 'Delhi', 70000 ),
('Neshu', 'Sharma', 'Nepal', 73000 ),
('Aryan', 'Sharma', 'WestBengal', 72000 ),
('Abdul', 'Ali', 'Delhi', 73000 ),
('Seema', 'Sharma', 'Bihar', 70000 ) ;
To verify used the following command as follows.
Select * From Emp;
Output :
Now, concatenate FirstName and LastName of given Emp table using ‘_’ as a separator to form a new column as FullName.
SELECT CONCAT_WS('_', FirstName,  LastName) AS FullName
From Emp;  
Output :
DBMS-SQL
mysql
Technical Scripter 2020
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL | Date functions
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Insert Multiple Rows
How to create JavaFX slider with two thumbs?

In general, a slider is a component that displays a continuous range of values. This contains a track on which the numerical values are displayed. Along the track, there is a thumb pointing to the numbers. You can provide the maximum, minimum and initial values of the slider.
The slider JavaFX provides contains only one thumb if you want to create a slider with two thumbs you need to rely on an external library named org.controlsfx.control.
Following is the maven dependency for this library −
<dependency>
   <groupId>org.controlsfx</groupId>
   <artifactId>controlsfx</artifactId>
   <version>11.0.1</version>
</dependency>
The RangeSlider class of this package is the JavaFXSlider but with two thumbs. Therefore to use it instantiate this class, add the required attributes, add it to the Node object.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.controlsfx.control.RangeSlider;
public class SliderTwoThumbs extends Application {
   public void start(Stage stage) {
      //Instantiating the RangeSlider class
      RangeSlider slider = new RangeSlider(0, 100, 10, 90);
      //Setting the slider properties
      slider.setShowTickLabels(true);
      slider.setShowTickMarks(true);
      slider.setMajorTickUnit(25);
      slider.setBlockIncrement(10);
      //VBox to arrange circle and the slider
      VBox vbox = new VBox();
      vbox.setPadding(new Insets(75));
      vbox.setSpacing(150);
      vbox.getChildren().addAll(slider);
      //Preparing the scene
      Scene scene = new Scene(vbox, 600, 200);
      stage.setTitle("Slider Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Output:
Contingency Table in Python - GeeksforGeeks

21 Jan, 2019
Estimations like mean, median, standard deviation, and variance are very much useful in case of the univariate data analysis. But in the case of bivariate analysis(comparing two variables) correlation comes into play.
Contingency Table is one of the techniques for exploring two or even more variables. It is basically a tally of counts between two or more categorical variables.
To get the Loan Data click here.
Loading Libraries
import numpy as npimport pandas as pdimport matplotlib as plt
Loading Data
data = pd.read_csv("loan_status.csv")  print (data.head(10))
Output:
Describe Data
data.describe()
Output:
Data Info
data.info()
Output:
Data Types
# data types of feature/attributes # in the datadata.dtypes
Output:
Code #1: Contingency Table showing correlation between Grades and loan status.
data_crosstab = pd.crosstab(data['grade'],                            data['loan_status'],                                margins = False)print(data_crosstab)
Output:
Code #2: Contingency Table showing correlation between Purpose and loan status.
data_crosstab = pd.crosstab(data['purpose'],                             data['loan_status'],                                margins = False)print(data_crosstab)
Output:
Code #3: Contingency Table showing correlation between Grades+Purpose and loan status.
data_crosstab = pd.crosstab([data.grade, data.purpose],                              data.loan_status, margins = False)print(data_crosstab)
Output:
So as in the code, Contingency Tables are giving clear correlation values between two and more variables. Thus making it much more useful to understand the data for further information extraction..
data-science
Python-pandas
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Python | Decision tree implementation
Search Algorithms in AI
Decision Tree Introduction with example
Reinforcement learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
How to load html content in android webview?

This example demonstrate about How to load html content in android webview.
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"
   android:orientation = "vertical">
   <WebView
      android:id = "@+id/web_view"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken web view to show html content.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
   @RequiresApi(api = Build.VERSION_CODES.P)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      final ProgressDialog progressDialog = new ProgressDialog(this);
      progressDialog.setMessage("Loading Data...");
      progressDialog.setCancelable(false);
      WebView web_view = findViewById(R.id.web_view);
      web_view.requestFocus();
      web_view.getSettings().setLightTouchEnabled(true);
      web_view.getSettings().setJavaScriptEnabled(true);
      web_view.getSettings().setGeolocationEnabled(true);
      web_view.setSoundEffectsEnabled(true);
      web_view.loadData("<html><body>Hello, world!</body></html>",
      "text/html", "UTF-8");
      web_view.setWebChromeClient(new WebChromeClient() {
         public void onProgressChanged(WebView view, int progress) {
            if (progress < 100) {
               progressDialog.show();
            }
            if (progress = = 100) {
               progressDialog.dismiss();
            }
         }
      });
   }
}
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
What are different types of constants in C language?

Constant is a value that cannot be changed during program execution; it is fixed.
In C language, a number or character or string of characters is called a constant. And it can be any data type. Constants are also called as literals.
There are two types of constants −
Primary constants − Integer, float, and character are called as Primary constants.
Secondary constants − Array, structures, pointers, Enum, etc., called as secondary constants.
const datatype variable;
 Live Demo
#include<stdio.h>
int main(){
   const int height=20;
   const int base=40;
   float area;
   area=0.5 * height*base;
   printf("The area of triangle :%f", area);
   return 0;
}
The area of triangle :400.000000
 Live Demo
include<stdio.h>
void main(){
   int a;
   int *p;
   a=10;
   p=&a;
   printf("a=%d\n",a);//10//
   printf("p=%d\n",p);//address value of p//
   *p=12;
   printf("a=%d\n",a);//12//
   printf("p=%d\n",p);//address value of p//
}
a=10
p=6422036
a=12
p=6422036
Dart Programming - Map.forEach() Function

Applies the specified function on every Map entry. In other words, forEach enables iterating through the Map’s entries.
Map.forEach(void f(K key, V value));

f(K key, V value) − Applies f to each key-value pair of the map.
Calling f must not add or remove keys from the map

f(K key, V value) − Applies f to each key-value pair of the map.
Calling f must not add or remove keys from the map
Return Type − void.
void main() { 
   var usrMap = {"name": "Tom", 'Email': 'tom@xyz.com'}; 
   usrMap.forEach((k,v) => print('${k}: ${v}')); 
} 
It will produce the following output −
Python program to find the string weight

05 Jul, 2021
Given a String, each character mapped with a weight( number), compute the total weight of the string.
Input : test_str = ‘GeeksforGeeks’, {“G” : 1, “e” : 2, “k” : 5, “f” : 3, “s” : 15, “o” : 4, “r” : 6} Output : 63 Explanation : 2 (G*2) + 8(e*4) + 30(s*2) + 10(k*2) + 4(o) + 6(r) +3(f) = 63.
Input : test_str = ‘Geeks’, {“G” : 1, “e” : 2, “k” : 5, “s” : 15} Output : 25  
Method#1 : Using loop
This is one of the ways in which this task can be performed. In this, we iterate for all the characters and sum all the weights mapped from dictionary.
Python3
# Python3 code to demonstrate working of# String Weight# Using loop # initializing stringtest_str = 'GeeksforGeeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing sum dictionarysum_dict = {"G" : 5, "e" : 2, "k" : 10,            "f" : 3, "s" : 15, "o" : 4, "r" : 6} # referring dict for sum# iteration using loopres = 0for ele in test_str:    res += sum_dict[ele] # printing resultprint("The weighted sum : " + str(res))
The original string is : GeeksforGeeks
The weighted sum : 81
Method #2 : Using sum()
This is one more way in which this task can be performed. In this, we use generator expression, and sum() is used to compute the summation of individual weights.
Python3
# Python3 code to demonstrate working of# String Weight# Using sum() # initializing stringtest_str = 'GeeksforGeeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing sum dictionarysum_dict = {"G" : 5, "e" : 2, "k" : 10, "f" : 3,            "s" : 15, "o" : 4, "r" : 6} # sum() used to get summationres = sum(sum_dict[ele] for ele in test_str) # printing resultprint("The weighted sum : " + str(res))
The original string is : GeeksforGeeks
The weighted sum : 81
saurabh1990aror
Python string-programs
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
Python 3 - Tkinter Button

The Button widget is used to add buttons in a Python application. These buttons can display text or images that convey the purpose of the buttons. You can attach a function or a method to a button which is called automatically when you click the button.
Here is the simple syntax to create this widget −
w = Button ( master, option = value, ... )

master − This represents the parent window.
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
activebackground
Background color when the button is under the cursor.
activeforeground
Foreground color when the button is under the cursor.
bd
Border width in pixels. Default is 2.
bg
Normal background color.
command
Function or method to be called when the button is clicked.
fg
Normal foreground (text) color.
font
Text font to be used for the button's label.
height
Height of the button in text lines (for textual buttons) or pixels (for images).
highlightcolor

The color of the focus highlight when the widget has focus.
image
Image to be displayed on the button (instead of text).
justify
How to show multiple text lines: LEFT to left-justify each line; CENTER to center them; or RIGHT to right-justify.
padx
Additional padding left and right of the text.
pady
Additional padding above and below the text.
relief
Relief specifies the type of the border. Some of the values are SUNKEN, RAISED, GROOVE, and RIDGE.
state
Set this option to DISABLED to gray out the button and make it unresponsive. Has the value ACTIVE when the mouse is over it. Default is NORMAL.
underline
Default is -1, meaning that no character of the text on the button will be underlined. If nonnegative, the corresponding text character will be underlined.
width
Width of the button in letters (if displaying text) or pixels (if displaying an image).
wraplength
If this value is set to a positive number, the text lines will be wrapped to fit within this length.
Following are commonly used methods for this widget −
flash()
Causes the button to flash several times between active and normal colors. Leaves the button in the state it was in originally. Ignored if the button is disabled.
invoke()
Calls the button's callback, and returns what that function returns. Has no effect if the button is disabled or there is no callback.
Try the following example yourself −
# !/usr/bin/python3
from tkinter import *

from tkinter import messagebox

top = Tk()
top.geometry("100x100")
def helloCallBack():
   msg = messagebox.showinfo( "Hello Python", "Hello World")

B = Button(top, text = "Hello", command = helloCallBack)
B.place(x = 50,y = 50)
top.mainloop()
When the above code is  executed, it produces the following result −
PostgreSQL – CASE

28 Aug, 2020
PostgreSQL has a conditional expression called CASE to form conditional queries. The PostgreSQL CASE expression is the same as IF/ELSE statement in other programming languages. PostgreSQL provides two forms of the CASE expressions.
Syntax:
CASE 
      WHEN condition_1  THEN result_1
      WHEN condition_2  THEN result_2
      [WHEN ...]
      [ELSE result_n]
END
For examples we will be using the sample database (ie, dvdrental).
Example 1:Here we will work on the film table of the sample database. Suppose you want to assign a price segment to a film with the following logic:
Mass if the rental rate is 0.99
Economic if the rental rate is 1.99
Luxury if the rental rate is 4.99
We will query for number of films in each segment using the below statement:
SELECT
    SUM (
        CASE
        WHEN rental_rate = 0.99 THEN
            1
        ELSE
            0
        END
    ) AS "Mass",
    SUM (
        CASE
        WHEN rental_rate = 2.99 THEN
            1
        ELSE
            0
        END
    ) AS "Economic",
    SUM (
        CASE
        WHEN rental_rate = 4.99 THEN
            1
        ELSE
            0
        END
    ) AS "Luxury"
FROM
    film;
Output:
Example 2:PostgreSQL provides another form of the CASE expression called simple form as follows:
CASE expression
WHEN value_1 THEN
    result_1
WHEN value_2 THEN
    result_2 
[WHEN ...]
ELSE
    result_n
END;
We can rewrite the general CASE expression using the simple CASE as follows:
SELECT
    SUM (
        CASE rental_rate
        WHEN 0.99 THEN
            1
        ELSE
            0
        END
    ) AS "Mass",
    SUM (
        CASE rental_rate
        WHEN 2.99 THEN
            1
        ELSE
            0
        END
    ) AS "Economic",
    SUM (
        CASE rental_rate
        WHEN 4.99 THEN
            1
        ELSE
            0
        END
    ) AS "Luxury"
FROM
    film;
Output:The query returns the same result as the first CASE example.
postgreSQL-basics
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
PostgreSQL - ROW_NUMBER Function
How to Get the Input From Tkinter Text Box?

11 Dec, 2020
Tkinter Text box widget is used to insert multi-line text. This widget can be used for messaging, displaying information, and many other tasks. The important task is to get the inserted text for further processing. For this, we have to use the get() method for the textbox widget.
Syntax: get(start, [end])
where,
start is starting index of required text in TextBox
end is ending index of required text in TextBox
If end is not provided, only character at provided start index will be retrieved.
Create Tkinter window
Create a TextBox widget
Create a Button widget
Create a function that will return text from textbox using get() method after hitting a button
Below is the implementation:
Python3
import tkinter as tk  # Top level windowframe = tk.Tk()frame.title("TextBox Input")frame.geometry('400x200')# Function for getting Input# from textbox and printing it # at label widget  def printInput():    inp = inputtxt.get(1.0, "end-1c")    lbl.config(text = "Provided Input: "+inp)  # TextBox Creationinputtxt = tk.Text(frame,                   height = 5,                   width = 20)  inputtxt.pack()  # Button CreationprintButton = tk.Button(frame,                        text = "Print",                         command = printInput)printButton.pack()  # Label Creationlbl = tk.Label(frame, text = "")lbl.pack()frame.mainloop()
Output:
Snapshot after pressing Print button for above code
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Percentages in Stacked Column Chart in Excel?

17 Dec, 2021
In this article, you will learn how to create a stacked column chart in excel.  Show percentages instead of actual data values on chart data labels.
By default, the data labels are shown in the form of chart data Value (Image 1).  But very often user needs to plot charts with actual data and show percentages/custom values on the chart instead of default data. For that we have an option “Value From Cells” in chart “Format Data Label” (Image 2) to select a custom range.
Image 1
Image 2
Follow the below steps to show percentages in stacked column chart In Excel:
Step 1: Open excel and create a data table as below
Step 2: Select the entire data table.
Step 3: To create a column chart in excel for your data table.  Go to “Insert” >> “Column or Bar Chart”  >> Select Stacked Column Chart 
Step 4: Add Data labels to the chart.  Goto “Chart Design” >> “Add Chart Element” >> “Data Labels” >> “Center”.  You can see all your chart data are in Columns stacked bar.
Step 5: Steps to add percentages/custom values in Chart.  
Create a percentage table for your chart data.  Copy header text in cells “b1 to E1” to cells “G1 to J1”.  
Insert below formula in cell “G2”.
=B2/SUM($B2:$E2)– make sure the “$” symbol are placed in-front of the characters (B and E) in formula
Step 6: Drag down/across the formula to fill cells G2:J6. Click Percent style (1) to convert your new table to show number with Percentage Symbol
Step 7: Select chart data labels and right-click, then choose “Format Data Labels”. 
Step 8: Check “Values From Cells”.
Step 9: Above step popup an input box for the user to select a range of cells to display on the chart instead of default values.  
In our example, Qtr_04 series default values are in E2:E6.  But we select range J2:J6 to show respective percentages. Press “OK”
Step 10: Un-check “Value” to hide the actual value from the chart.
Step 11: Repeat steps 7 to 10 for each series of our data.
Output:
Excel-Charts
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How can we add multiple columns, with single command, to an existing MySQL table?

We can also add multiple columns to an existing table with the help of ALTER command. The syntax for it would be as follows −
Alter table table-name ADD (column-name1 datatype, column-name2 datatype,... column-nameN datatype);
In the example below, with the help of ALTER Command, columns ‘Address’, ‘Phone’ and ‘Email’ are added to the table ‘Student’.
mysql> Alter Table Student ADD(Address Varchar(25), Phone INT, Email Varchar(20));
Query OK, 5 rows affected (0.38 sec)
Records: 5 Duplicates: 0 Warnings: 0
Python program to count upper and lower case characters without using inbuilt functions

In this article, we will learn about the solution and approach to solve the given problem statement.
Given a string input, we need to find the number of uppercase & lowercase characters in the given strings.
Here we will we checking ASCII value of each character by the help of built-in ord() function.
Here we have assigned two counters to 0 and we are traversing the input string and checking their ASCII values and incrementing their counter respectively.
Now let’s see the implementation below −
 Live Demo
def upperlower(string):
   upper = 0
   lower = 0
   for i in range(len(string)):
      # For lowercase
      if (ord(string[i]) >= 97 and
         ord(string[i]) <= 122):
         lower += 1
      # For uppercase
      elif (ord(string[i]) >= 65 and
         ord(string[i]) <= 90):
         upper += 1
   print('Lower case characters = %s' %lower,
      'Upper case characters = %s' %upper)
# Driver Code
string = 'Tutorialspoint'
upperlower(string)
Lower case characters = 13 Upper case characters = 1
All variables and functions are declared in global scope as shown in the figure below.
In this article, we learned about the approach to count upper and lower case characters without using inbuilt functions.
Number of Segments in a String in C++

Suppose we have a string s. We have to count the number of segments in a string, where a segment is defined to be a contiguous sequence of characters (no whitespace).
So, if the input is like "Hello, I love programming", then the output will be 4, as there are 4 segments.
To solve this, we will follow these steps −
n := 0
n := 0
for initialize i := 0, when i < size of s, update (increase i by 1), do −if s[i] is not equal to white space, then −(increase n by 1)while (i < size of s and s[i] is not equal to white space), do −(increase i by 1)
for initialize i := 0, when i < size of s, update (increase i by 1), do −
if s[i] is not equal to white space, then −(increase n by 1)
if s[i] is not equal to white space, then −
(increase n by 1)
(increase n by 1)
while (i < size of s and s[i] is not equal to white space), do −(increase i by 1)
while (i < size of s and s[i] is not equal to white space), do −
(increase i by 1)
(increase i by 1)
return n
return n
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int countSegments(string s) {
      int n = 0;
      for(int i = 0; i < s.size(); i++){
         if(s[i] != ' ')
            n++;
         while( i < s.size() && s[i] != ' ')
            i++;
      }
      return n;
   }
};
main(){
   Solution ob;
   cout << (ob.countSegments("Hello, I love programming"));
}
"Hello, I love programming"
4
Can we define an interface inside a Java class?

Yes, you can define an interface inside a class and it is known as a nested interface. You can’t access a nested interface directly; you need to access (implement) the nested interface using the inner class or by using the name of the class holding this nested interface.
Live Demo
public class Sample {
   interface myInterface {
      void demo();
   }
   class Inner implements myInterface {
      public void demo() {
         System.out.println("Welcome to Tutorialspoint");
      }
   }
   public static void main(String args[]) {
      Inner obj = new Sample().new Inner();
      obj.demo();
   }
}
Welcome to Tutorialspoint
You can also access the nested interface using the class name as −
class Test {
   interface myInterface {
      void demo();
   }
}
public class Sample implements Test.myInterface {
   public void demo() {
      System.out.println("Hello welcome to tutorialspoint");
   }
   public static void main(String args[]) {
      Sample obj = new Sample();
      obj.demo();
   }
}
What is the difference between 'isset()' and '!empty()' in PHP?

ISSET checks the variable to see if it has been set. In other words, it checks to see if the variable is any value except NULL or not assigned a value. ISSET returns TRUE if the variable exists and has a value other than NULL. That means variables assigned a "", 0, "0", or FALSE are set, and therefore are TRUE for ISSET.
 Live Demo
<?php
   $val = '0';
   if( isset($val)) {
      print_r(" $val is set with isset function <br>");
   }
   $my_array = array();
   echo isset($my_array['New_value']) ?
   'array is set.' :  'array is not set.';
?>
This will produce the following output −
0 is set with isset function
array is not set.
EMPTY checks to see if a variable is empty. Empty is interpreted as: "" (an empty string), 0 (integer), 0.0 (float)`, "0" (string), NULL, FALSE, array() (an empty array), and "$var;" (a variable declared, but without a value in a class.
 Live Demo
<?php
   $temp_val = 0;
   if (empty($temp_val)) {
      echo $temp_val . ' is considered empty';
   }
   echo "nn";
   $new_val = 1;
   if (!empty($new_val)) {
      echo $new_val . ' is considered set';
   }
?>
This will produce the following output −
0 is considered empty 1 is considered set
Creating a Graph in Javascript

We'll be creating a graph class that supports weights and both directed and undirected types. This will be implemented using an adjacency list. As we move to more advanced concepts, both weights and directed nature of the graphs will come in handy.
An adjacency list is an array A of separate lists. Each element of the array Ai is a list, which contains all the vertices that are adjacent to vertex i. We're defining it using 2 members, nodes and edges.
Let's set up the graph class by defining our class and some methods that we'll use to add nodes and edges to our graph.
We'll initially define the following methods −
addNode: Adds a node to the graph
addEdge: Adds an undirected edge to the graph
addDirectedEdge: Adds a directed edge
class Graph {
   constructor() {
      this.edges = {};
      this.nodes = [];
   }
   addNode(node) {
      this.nodes.push(node);
      this.edges[node] = [];
   }
   addEdge(node1, node2) {
      this.edges[node1].push(node2);
      this.edges[node2].push(node1);
   }
   addDirectedEdge(node1, node2) {
      this.edges[node1].push(node2);
   }
   display() {
      let graph = ""; this.nodes.forEach(node => {
         graph += node + "->" + this.edges[node].join(", ") + "\n";
      });
      console.log(graph);
   }
}
You can test these methods and our class using − 
let g = new Graph();
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addNode("E");
 
g.addEdge("A", "C");
g.addEdge("A", "B");
g.addDirectedEdge("A", "D");
g.addEdge("D", "E");

g.display();
This will give the output −
A->C, B, D
B->A
C->A
D->E
E->D
Python Program for nth Catalan Number

In this article, we will learn about calculating the nth Catalan number.
Catalan numbers are a sequence of natural numbers that are defined by the recursive formula −
C0=1andCn+1=∑i=0nCiCn−iforn≥0;
The first few Catalan numbers for n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132,429,...................
Catalan numbers can be obtained both by recursion and dynamic programming.
So let’s see their implementation.
 Live Demo
# A recursive solution
def catalan(n):
   #negative value
   if n <=1 :
      return 1
   # Catalan(n) = catalan(i)*catalan(n-i-1)
   res = 0
   for i in range(n):
      res += catalan(i) * catalan(n-i-1)
   return res
# main
for i in range(6):
   print (catalan(i))
1
1
2
5
14
42
The scope of all the variables and recursive calls are shown below.
 Live Demo
# using dynamic programming
def catalan(n):
   if (n == 0 or n == 1):
      return 1
   # divide table
   catalan = [0 for i in range(n + 1)]
   # Initialization
   catalan[0] = 1
   catalan[1] = 1
   # recursion
   for i in range(2, n + 1):
      catalan[i] = 0
      for j in range(i):
         catalan[i] = catalan[i] + catalan[j] * catalan[i-j-1]
   return catalan[n]
# main
for i in range (6):
   print (catalan(i),end=" ")
1
1
2
5
14
42
The scope of all the variables and recursive calls are shown below.
In this article, we learned about the method of generating the nth Catalan number.
Makefile - Example

This is an example of the Makefile for compiling the hello program. This program consists of three files main.cpp, factorial.cpp and  hello.cpp.
# Define required macros here
SHELL = /bin/sh

OBJS =  main.o factorial.o hello.o
CFLAG = -Wall -g
CC = gcc
INCLUDE =
LIBS = -lm

hello:${OBJ}
   ${CC} ${CFLAGS} ${INCLUDES} -o $@ ${OBJS} ${LIBS}

clean:
   -rm -f *.o core *.core

.cpp.o:
   ${CC} ${CFLAGS} ${INCLUDES} -c $<
Now you can build your program hello using the make. If you will issue a command make clean then it removes all the object files and core files available in the current directory.
 Print
 Add Notes
 Bookmark this page
How to write "Hello World" Program in C++?

To run the hello world program, you'll have to follow the following steps −
Now that you have a compiler installed, its time to write a C++ program. Let's start with the epitome of programming example's, it, the Hello world program. We'll print hello world to the screen using C++ in this example. Create a new file called hello.cpp and write the following code to it −
#include<iostream>
int main() {
   std::cout << "Hello World\n";
}
Let's dissect this program.
Line 1 − We start with the #include<iostream> line which essentially tells the compiler to copy the code from the iostream file(used for managing input and output streams) and paste it in our source file.  Header iostream, that allows to perform standard input and output operations, such as writing the output of this program (Hello World) to the screen. Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor.
Line 2 − A blank line: Blank lines have no effect on a program.
Line 3 − We then declare a function called main with the return type of int. main() is the entry point of our program. Whenever we run a C++ program, we start with the main function and begin execution from the first line within this function and keep executing each line till we reach the end. We start a block using the curly brace({) here. This marks the beginning of main's function definition, and the closing brace (}) at line 5, marks its end. All statements between these braces are the function's body that defines what happens when main is called.
Line 4 −
std::cout << "Hello World\n";
This line is a C++ statement. This statement has three parts: First, std::cout, which identifies the standard console output device. Second the insertion operator << which indicates that what follows is inserted into std::cout. Last, we have a sentence within quotes that we'd like printed on the screen. This will become more clear to you as we proceed in learning C++.
In short, we provide cout object with a string "Hello world\n" to be printed to the standard output device.
Note that the statement ends with a semicolon (;). This character marks the end of the statement
Now that we've written the program, we need to translate it to a language that the processor understands, ie, in binary machine code. We do this using a compiler we installed in the first step. You need to open your terminal/cmd and navigate to the location of the hello.cpp file using the cd command. Assuming you installed the GCC, you can use the following command to compile the program −
$ g++ -o hello hello.cpp
This command means that you want the g++ compiler to create an output file, hello using the source file hello.cpp.
Now that we've written our program and compiled it, time to run it! You can run the program using −
$ ./hello
You will get the output −
Hello world
Ext.js - Ext.tab.Panel Container

Ext.tab.Panel − Tab panel is like a normal panel but has support for card tab panel layout.
Following is a simple syntax to create Ext.tab.Panel container.
Ext.create('Ext.tab.Panel', {
   items: [child1, child2]  
   // this way we can add different child elements to the container as container items.
});

Following is a simple example showing Ext.tab.Panel container.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css" 
         rel = "stylesheet" />
      <script type = "text/javascript" 
         src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
      
      <script type = "text/javascript">
         Ext.onReady(function () {
            Ext.create('Ext.tab.Panel', {
               renderTo: Ext.getBody(),
               height: 100,
               width: 200,
               
               items: [{
                  xtype: 'panel',
                  title: 'Tab One',
                  html: 'The first tab',
                  listeners: {
                     render: function() {
                        Ext.MessageBox.alert('Tab one', 'Tab One was clicked.');
                     }
                  }
               },{
                  // xtype for all Component configurations in a Container
                  title: 'Tab Two',
                  html: 'The second tab',
                  listeners: {
                     render: function() {
                        Ext.MessageBox.alert('Tab two', 'Tab Two was clicked.');
                     }
                  }
               }]
            });
         });
      </script>
   </head>
   
   <body>
   </body>
</html>
The above program will produce the following result −
 Print
 Add Notes
 Bookmark this page