code-rag-bench/online-tutorials huggingface dataset:
MySQL Error - #1046 - No database selected

The error-#1046 can occur when we are creating a table, but forget to select the database. Let
us say we have started MySQL as shown below −
After giving the correct password, the above window will open. Now create a table without
choosing any database. This will show an error −
mysql> CREATE table TblUni
-> (
-> id int,
-> Name varchar(100)
-> );
ERROR 1046 (3D000): No database selected
The following screenshot is showing the same error −
Now, choose any database to get rid of the above error. Firstly, let us check how many
databases are present in MySQL with the help of SHOW command −
mysql> SHOW databases;

The following is the output −
+--------------------+
| Database           |
+--------------------+
| business           |
| hello              |
| information_schema |
| mybusiness         |
| mysql              |
| performance_schema |
| sample             |
| sys                | 
| test               |
+--------------------+
9 rows in set (0.00 sec)
Now, we can choose any database. Suppose I am using the database ‘business’, therefore we
can choose with the help of ‘use’ command.
mysql> use business;
Database changed
After using database ‘business’, we can create the above table and we will not get any error.
mysql> CREATE table TblUni
-> (
-> id int,
-> Name varchar(100)
-> );
Query OK, 0 rows affected (0.50 sec)
Python - Negative Binomial Discrete Distribution in Statistics - GeeksforGeeks

10 Jan, 2020
scipy.stats.nbinom() is a Negative binomial discrete random variable. It is inherited from the of generic methods as an instance of the rv_discrete class. It completes the methods with details specific for this particular distribution.
Parameters :
x : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : Negative binomial discrete random variable
Code #1 : Creating Negative binomial discrete random variable
# importing library  from scipy.stats import nbinom     numargs = nbinom .numargs a, b = 0.2, 0.8rv = nbinom (a, b)     print ("RV : \n", rv)  
Output :
RV : 
 scipy.stats._distn_infrastructure.rv_frozen object at 0x0000016A4C016208

Code #2 : Negative binomial discrete variates and probability distribution
import numpy as np quantile = np.arange (0.01, 1, 0.1)   # Random Variates R = nbinom .rvs(a, b, size = 10) print ("Random Variates : \n", R)   # PDF x = np.linspace(nbinom.ppf(0.01, a, b),                nbinom.ppf(0.99, a, b), 10)R = nbinom.ppf(x, 1, 3)print ("\nProbability Distribution : \n", R) 
Output :
Random Variates : 
 [0 0 0 0 0 0 0 0 0 0]

Probability Distribution : 
 [-1. nan nan nan nan nan nan nan nan nan]


Code #3 : Graphical Representation.
import numpy as np import matplotlib.pyplot as plt      distribution = np.linspace(0, np.minimum(rv.dist.b, 2)) print("Distribution : \n", distribution)      plot = plt.plot(distribution, rv.ppf(distribution)) 
Output :
Distribution : 
 [0.         0.04081633 0.08163265 0.12244898 0.16326531 0.20408163
 0.24489796 0.28571429 0.32653061 0.36734694 0.40816327 0.44897959
 0.48979592 0.53061224 0.57142857 0.6122449  0.65306122 0.69387755
 0.73469388 0.7755102  0.81632653 0.85714286 0.89795918 0.93877551
 0.97959184 1.02040816 1.06122449 1.10204082 1.14285714 1.18367347
 1.2244898  1.26530612 1.30612245 1.34693878 1.3877551  1.42857143
 1.46938776 1.51020408 1.55102041 1.59183673 1.63265306 1.67346939
 1.71428571 1.75510204 1.79591837 1.83673469 1.87755102 1.91836735
 1.95918367 2.        ]
  
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as plt import numpy as np   x = np.linspace(0, 5, 100)      # Varying positional arguments y1 = nbinom.ppf(x, a, b) y2 = nbinom.pmf(x, a, b) plt.plot(x, y1, "*", x, y2, "r--") 
Output :
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to repeat a string in JavaScript?

There are two ways to repeat a string in javascript. One way is to use string.repeat() method and the other way is to use the fill() method. Let's discuss them in detail.
string.repeat(number);
This method takes a number as a parameter and repeats the string those many numbers of times.
Array(number).fill(string).join('');
This method initially takes a number and allocates those many numbers of spaces. It inserts the provided string in all those places and joins them to get a repeated string.
In the following example, number 3 is sent into the repeat method as an argument. So the string is repeated for 3 times as shown in the output.
Live Demo
<html>
<body>
   <script>
      const str = 'Tutorix, '
      var res = str.repeat(3);
      document.write(res);
   </script>
</body>
</html>
Tutorix, Tutorix, Tutorix,
In the following example, Initially, an array is created with 3 slots and the provided string is kept in all those slots and later on, using join() method the elements in the array were joined and the output is displayed as shown.
Live Demo
<html>
<body>
   <script>
      const str = 'Tutorialspoint '
      var d = Array(3).fill(str).join('')
      document.write(d);
   </script>
</body>
</html>
Tutorialspoint Tutorialspoint Tutorialspoint
Grouping Operators in LINQ

The operators put data into some groups based on a common shared attribute.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Operators {
   class Program {
      static void Main(string[] args) {
      
         List<int> numbers = new List<int>() { 35, 44, 200, 84, 3987, 4, 199, 329, 446, 208 };

         IEnumerable<IGrouping<int, int>> query = from number in numbers 
		                              group number by number % 2;    

         foreach (var group in query) {
            Console.WriteLine(group.Key == 0 ? "\nEven numbers:" : "\nOdd numbers:");
           
            foreach (int i in group)
               Console.WriteLine(i);
         }
			
         Console.ReadLine();                
      }
   }
}
Module Module1
   Sub Main()
      Dim numbers As New System.Collections.Generic.List(Of Integer)(
      New Integer() {35, 44, 200, 84, 3987, 4, 199, 329, 446, 208})

      Dim query = From number In numbers 
                  Group By Remainder = (number Mod 2) Into Group
     
      For Each group In query
         Console.WriteLine(If(group.Remainder = 0, vbCrLf &"Even numbers:", vbCrLf &"Odd numbers:"))
		 
         For Each num In group.Group           
            Console.WriteLine(num)
         Next 
		 
      Next
	  
      Console.ReadLine()
	  
   End Sub
   
End Module
When the above code in C# or VB is compiled and executed, it produces the following result −
Odd numbers: 
35 
3987 
199 
329 

Even numbers: 
44 
200 
84 
4 
446 
208


    23 Lectures 
     1.5 hours 

 Anadi Sharma

    37 Lectures 
     13 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
How to catch SyntaxError Exception in Python?

A SyntaxError occurs any time the parser finds source code it does not understand. This can be while importing a module, invoking exec, or calling eval(). Attributes of the exception can be used to find exactly what part of the input text caused the exception.
We rewrite the given code to handle the exception and find its type
try:
print eval('six times seven')
except SyntaxError, err:
print 'Syntax error %s (%s-%s): %s' % \
(err.filename, err.lineno, err.offset, err.text)
print err
C:/Users/TutorialsPoint1/~.py
Syntax error <string> (1-9): six times seven
invalid syntax (<string>, line 1)
How do I find the location of my Python site-packages directory?

You can find the location of Python site-packages directory by using the site module in the following way −
>>> import site
>>> site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']
If you want the per user site packages directory, then run the following code in your shell −
$ python -m site --user-site
Python program to find difference between two timestamps

Suppose we have two times in this format "Day dd Mon yyyy hh:mm:ss +/-xxxx", where Day is three letter day whose first letter is in uppercase. Mon is the name of month in three letters and finally + or - xxxx represents the timezone for example +0530 indicates it is 5 hours 30 minutes more than GMT (other formats like dd, hh, mm, ss are self-explanatory). We have to find absolute difference between two timestamps in seconds.
To solve this using python we will use the datetime library. There is a function called strptime() this will convert string formatted date to datetime object. There are few format specifiers like below −
%a indicates the day in three letter format
%d indicates day in numeric format
%b indicates month in three letter format
%Y indicates year in yyyy format
%H indicates hour in hh format
%M indicates minutes in mm format
%S indicates seconds in ss format
%z indicates the timezone in +/- xxxx format
So, if the input is like t1 = "Thu 15 Jul 2021 15:10:17 +0530" t2 = "Thu 15 Jul 2021 20:25:29 +0720", then the output will be 12312
To solve this, we will follow these steps −
t1 := change first time format from given string to above mentioned format
t2 := change second time format from given string to above mentioned format
return difference between t1 and t2 in seconds
Let us see the following implementation to get better understanding −
from datetime import datetime

def solve(t1, t2):
   t1 = datetime.strptime(t1, "%a %d %b %Y %H:%M:%S %z")
   t2 = datetime.strptime(t2, "%a %d %b %Y %H:%M:%S %z")
   return abs(int((t1-t2).total_seconds()))

t1 = "Thu 15 Jul 2021 15:10:17 +0530"
t2 = "Thu 15 Jul 2021 20:25:29 +0720"
print(solve(t1, t2))
"Thu 15 Jul 2021 15:10:17 +0530", "Thu 15 Jul 2021 20:25:29 +0720"
12312
Program to find correlation coefficient in C++

In this tutorial, we will be discussing a program to find correlation coefficient.
For this we will be provided with two arrays. Our task is to find the correlation coefficient denoting the strength of the relation between the given values.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
//function returning correlation coefficient
float find_coefficient(int X[], int Y[], int n){
   int sum_X = 0, sum_Y = 0, sum_XY = 0;
   int squareSum_X = 0, squareSum_Y = 0;
   for (int i = 0; i < n; i++){
      sum_X = sum_X + X[i];
      sum_Y = sum_Y + Y[i];
      sum_XY = sum_XY + X[i] * Y[i];
      squareSum_X = squareSum_X + X[i] * X[i];
      squareSum_Y = squareSum_Y + Y[i] * Y[i];
   }
   float corr = (float)(n * sum_XY - sum_X * sum_Y) / sqrt((n * squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y));
   return corr;
}
int main(){
   int X[] = {15, 18, 21, 24, 27};
   int Y[] = {25, 25, 27, 31, 32};
   int n = sizeof(X)/sizeof(X[0]);
   cout<<find_coefficient(X, Y, n);
   return 0;
}
0.953463
How to change autopct text color to be white in a pie chart in Matplotlib?

To change the autopct text color to be white in a pie chart in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Make a list of hours,
activities, and colors to plot pie chart.
Make a list of '.Text' instances for the numeric labels, while making the pie chart.
Iterate autotexts and set the color of autotext as white.
To display the figure, use show() method.
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

plt.figure()

hours = [8, 1, 11, 4]
activities = ['sleeping', 'exercise', 'studying', 'working']
colors = ["grey", "green", "orange", "blue"]
_, _, autotexts = plt.pie(hours, labels=activities, colors=colors, autopct="%.2f")

for ins in autotexts:
    ins.set_color('white')

plt.show()
How to convert String to StringBuilder and vice versa Java?

The String type is a class in Java, it is used to represent a set of characters. Strings in Java are immutable, you cannot change the value of a String once created.
Since a String is immutable, if you try to reassign the value of a String. The reference of it will be pointed to the new String object leaving an unused String in the memory.
Java provides StringBuffer class as a replacement of Strings in places where there is a necessity to make a lot of modifications to Strings of characters.
You can modify/manipulate the contents of a StringBuffer over and over again without leaving behind a lot of new unused objects.
The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilder’s methods are not thread safe (not synchronized).
It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However, if the thread safety is necessary, the best option is StringBuffer objects.
The append() method of the StringBuilder class accepts a String value and adds it to the current object.
To convert a String value to StringBuilder object just append it using the append() method.
In the following Java program we are converting an array of Strings to a single StringBuilder object.
public class StringToStringBuilder {
   public static void main(String args[]) {
      String strs[] = {"Arshad", "Althamas", "Johar", "Javed", "Raju", "Krishna" };
      StringBuilder sb = new StringBuilder();
      sb.append(strs[0]);
      sb.append(" "+strs[1]);
      sb.append(" "+strs[2]);
      sb.append(" "+strs[3]);
      sb.append(" "+strs[4]);
      sb.append(" "+strs[5]);
      System.out.println(sb.toString());
   }
}
Arshad Althamas Johar Javed Raju Krishna
The toString() method of the StringBuilder class reruns String value of the current object. To convert a StringBuilder to String value simple invoke the toString() method on it.
In the following Java program we are converting an array of Strings to a singleStringusing the toString() method of the StringBuilder.
public class StringToStringBuilder {
   public static void main(String args[]) {
      String strs[] = {"Arshad", "Althamas", "Johar", "Javed", "Raju", "Krishna" };
      StringBuilder sb = new StringBuilder();
      sb.append(strs[0]);
      sb.append(" "+strs[1]);
      sb.append(" "+strs[2]);
      sb.append(" "+strs[3]);
      sb.append(" "+strs[4]);
      sb.append(" "+strs[5]);
      String singleString = sb.toString();
      System.out.println(singleString);
   }
}
Arshad Althamas Johar Javed Raju Krishna
MySQL Sum Query with IF Condition?

The Sum() is an aggregate function in MySQL. You can use sum query with if condition. To understand the sum query with if condition, let us create a table.
The query to create a table −
mysql> create table SumWithIfCondition
   −> (
   −> ModeOfPayment varchar(100)
   −> ,
   −> Amount int
   −> );
Query OK, 0 rows affected (1.60 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into SumWithIfCondition values('Offline',10);
Query OK, 1 row affected (0.21 sec)

mysql> insert into SumWithIfCondition values('Online',100);
Query OK, 1 row affected (0.16 sec)

mysql> insert into SumWithIfCondition values('Offline',20);
Query OK, 1 row affected (0.13 sec)

mysql> insert into SumWithIfCondition values('Online',200);
Query OK, 1 row affected (0.16 sec)

mysql> insert into SumWithIfCondition values('Offline',30);
Query OK, 1 row affected (0.11 sec)

mysql> insert into SumWithIfCondition values('Online',300);
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from SumWithIfCondition;
The following is the output −
+---------------+--------+
| ModeOfPayment | Amount |
+---------------+--------+
| Offline       |     10 |
| Online        |    100 |
| Offline       |     20 |
| Online        |    200 |
| Offline       |     30 |
| Online        |    300 |
+---------------+--------+
6 rows in set (0.00 sec)
Here is the sum query with if condition.
Case 1 - if for Online Mode of Payment
The query is as follows −
mysql> select sum(if(ModeOfPayment = 'Online',Amount,0)) as TotalAmount from SumWithIfCondition;
The following is the output −
+-------------+
| TotalAmount |
+-------------+
|         600 |
+-------------+
1 row in set (0.00 sec)
Case 2 - if for Offline Mode of Payment
The query is as follows −
mysql> select sum(if(ModeOfPayment = 'Offline',Amount,0)) as TotalAmount from SumWithIfCondition;
The following is the output −
+-------------+
| TotalAmount |
+-------------+
|          60 |
+-------------+
1 row in set (0.00 sec)
Selenium - Drop Down Interaction

In this section, we will understand how to interact with Drop down Boxes. We can select an option using 'selectByVisibleText' or 'selectByIndex' or 'selectByValue' methods.
Let us understand how to interact with a dropdown box using https://www.calculator.net/interest-calculator.html. We can also check if a dropdown box is selected/enabled/visible.
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class webdriverdemo {
   public static void main(String[] args) throws InterruptedException {
   
      WebDriver driver = new FirefoxDriver();
      
      //Puts a Implicit wait, Will wait for 10 seconds before throwing exception
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      
      //Launch website
      driver.navigate().to("http://www.calculator.net/interest-calculator.html");
      driver.manage().window().maximize();
      
      //Selecting an item from Drop Down list Box
      Select dropdown = new Select(driver.findElement(By.id("ccompound")));
      dropdown.selectByVisibleText("continuously");
      
      //you can also use dropdown.selectByIndex(1) to select second element as
      //index starts with 0.
      //You can also use dropdown.selectByValue("annually");
      
      System.out.println("The Output of the IsSelected " +
         driver.findElement(By.id("ccompound")).isSelected());
      System.out.println("The Output of the IsEnabled " +
         driver.findElement(By.id("ccompound")).isEnabled());
      System.out.println("The Output of the IsDisplayed " +
         driver.findElement(By.id("ccompound")).isDisplayed());
      
      driver.close();
   }
}
Upon execution, the dropdown is set with the specified value and the output of the commands are displayed in the console.

    46 Lectures 
     5.5 hours 

 Aditya Dua

    296 Lectures 
     146 hours 

 Arun Motoori

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    22 Lectures 
     7 hours 

 Arun Motoori

    118 Lectures 
     17 hours 

 Arun Motoori

    278 Lectures 
     38.5 hours 

 Lets Kode It
 Print
 Add Notes
 Bookmark this page
C++ Program to Implement Radix Sort

Radix sort is non-comparative sorting algorithm. This sorting algorithm works on the integer keys by grouping digits which share the same position and value. The radix is the base of a number system. As we know that in decimal system the radix or base is 10. So for sorting some decimal numbers, we need 10 positional box to store numbers.
Time Complexity: O(nk)
Time Complexity: O(nk)
Space Complexity: O(n+k)
Space Complexity: O(n+k)
Input − The unsorted list: 802 630 20 745 52 300 612 932 78 187
Output − Data after Sorting: 20 52 78 187 300 612 630 745 802 932
Input: An array of data, and the total number in the array, digit count of max number.
Output: Sorted array.
Begin
   define 10 lists as pocket
   for i := 0 to max -1 do
      m = 10i+1
      p := 10i
      for j := 0 to n-1 do
      temp := array[j] mod m
      index := temp / p
      pocket[index].append(array[j])
   done
   count := 0
   for j := 0 to radix do
      while pocket[j] is not empty
         array[count] := get first node of pocket[j] and delete it
         count := count +1
      done
   done
End
#include<iostream>
#include<list>
#include<cmath>
using namespace std;
void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}
void radixSort(int *arr, int n, int max) {
   int i, j, m, p = 1, index, temp, count = 0;
   list<int> pocket[10];      //radix of decimal number is 10
   for(i = 0; i< max; i++) {
      m = pow(10, i+1);
      p = pow(10, i);
      for(j = 0; j<n; j++) {
         temp = arr[j]%m;
         index = temp/p;      //find index for pocket array
         pocket[index].push_back(arr[j]);
      }
      count = 0;
      for(j = 0; j<10; j++) {
         //delete from linked lists and store to array
         while(!pocket[j].empty()) {
            arr[count] = *(pocket[j].begin());
            pocket[j].erase(pocket[j].begin());
            count++;
         }
      }
   }
}
int main() {
   int n, max;
   cout << "Enter the number of elements: ";
   cin >> n;
   cout << "Enter the maximum digit of elements: ";
   cin >> max;
   int arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;
   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }
   cout << "Data before Sorting: ";
   display(arr, n);
   radixSort(arr, n, max);
   cout << "Data after Sorting: ";
   display(arr, n);
}
Enter the number of elements: 10
Enter the maximum digit of elements: 3
Enter elements:
802 630 20 745 52 300 612 932 78 187
Data before Sorting: 802 630 20 745 52 300 612 932 78 187
Data after Sorting: 20 52 78 187 300 612 630 745 802 932
How to detect when an OptionMenu or Checkbutton changes in Tkinter?

Let us suppose that in a particular application, we have some fixed set of options or choices for the user in a drop-down list. The Options or Choices can be created using the OptionMenu Widget Constructor.
OptionMenu(window, variable, choice1, choice2, choice3......)
Once the option is created, it can be detected by a click event which generally prints whether a particular option is selected or not. For this example, we will simply create an application where a check button will be present with some choices from the range (1 to 9). By default, the button is set to “1” using the set method. Selecting other options will print the button on the screen.
#Import the tkinter library
from tkinter import *

#Create an instance of tkinter frame
tk = Tk()
tk.geometry("700x300")

#Create the option and Check Button Event
def OptionMenu_CheckButton(event):
   print(var.get())
   pass

#Create the variables
var = StringVar();var.set("1")
options = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
OptionMenu(tk, var, *(options), command =
OptionMenu_CheckButton).pack()
tk.mainloop()
Running the above code will trace the options selected by the user and print it on
the screen.
MongoDB – Insert Single Document Using MongoShell

27 Feb, 2020
In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations add new documents in the existing collection. You are allowed to add a single document in the collection using db.collection.insertOne() method.
insertOne() is a mongo shell method, which can insert one document at a time. This method can be used in the multi-document transactions. In this method, you can add a document in the collection with or without _id field. If you add a document without _id field, then mongodb will automatically add a _id field and assign it with a unique ObjectId.
Syntax:
db.collection.deleteOne(
    <document>,
   {
      writeConcern: <document>,
     
   }
)
Parameters:
document: First parameter of this method. It represents a document that will insert in the collection.
writeConcern: It is an optional parameter. It is only used when you do not want to use the default write concern. The type of this parameter is document.
Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and insertedId represents the _id field of the inserted document.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: student
In this example, we are inserting a document in the student collection without _id field using db.collection.insertOne() method.
In this example, we are inserting a document in the student collection with _id field using db.collection.deleteOne() method.
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Docker - COPY Instruction
Decision Tree Introduction with example
Getting started with Machine Learning
How to Run a Python Script using Docker?
ML | Underfitting and Overfitting
Clustering in Machine Learning
Python | Decision tree implementation
ML | Monte Carlo Tree Search (MCTS)
TreeMap get() Method in Java

28 Jun, 2018
The java.util.TreeMap.get() method of TreeMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Syntax:
Tree_Map.get(Object key_element)
Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched.
Return Value: The method returns the value associated with the key_element in the parameter.
Below programs illustrates the working of java.util.TreeMap.get() method:Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the get() methodimport java.util.*;  public class Tree_Map_Demo {    public static void main(String[] args)    {          // Creating an empty TreeMap        TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>();          // Mapping string values to int keys        tree_map.put(10, "Geeks");        tree_map.put(15, "4");        tree_map.put(20, "Geeks");        tree_map.put(25, "Welcomes");        tree_map.put(30, "You");          // Displaying the TreeMap        System.out.println("Initial Mappings are: " + tree_map);          // Getting the value of 25        System.out.println("The Value is: " + tree_map.get(25));          // Getting the value of 10        System.out.println("The Value is: " + tree_map.get(10));    }}
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
The Value is: Welcomes
The Value is: Geeks

Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the get() methodimport java.util.*;  public class Tree_Map_Demo {    public static void main(String[] args)    {          // Creating an empty TreeMap        TreeMap<String, Integer> tree_map = new TreeMap<String, Integer>();          // Mapping int values to string keys        tree_map.put("Geeks", 10);        tree_map.put("4", 15);        tree_map.put("Geeks", 20);        tree_map.put("Welcomes", 25);        tree_map.put("You", 30);          // Displaying the TreeMap        System.out.println("Initial Mappings are: " + tree_map);          // Getting the value of "Geeks"        System.out.println("The Value is: " + tree_map.get("Geeks"));          // Getting the value of "You"        System.out.println("The Value is: " + tree_map.get("You"));    }}
Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}
The Value is: 20
The Value is: 30

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Java - util package
Java-Collections
java-TreeMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Queue Interface In Java
How to add an element to an Array in Java?
Multidimensional Arrays in Java
Math pow() method in Java with Example
PriorityQueue in Java
Stack Class in Java
List Interface in Java with Examples
ArrayList in Java
Different ways of Reading a text file in Java
GATE | GATE-CS-2015 (Set 2) | Question 27

28 Jun, 2021
Consider a complete binary tree where the left and the right subtrees of the root are max-heaps. The lower bound for the number of operations to convert the tree to a heap is(A) Ω(logn)(B) Ω(n)(C) Ω(nlogn)(D) Ω(n2)Answer: (A)Explanation: The answer to this question is simply max-heapify function. Time complexity of max-heapify is O(Log n) as it recurses at most through height of heap.
// A recursive method to heapify a subtree with root at given index
// This method assumes that the subtrees are already heapified
void MinHeap::MaxHeapify(int i)
{
    int l = left(i);
    int r = right(i);
    int largest = i;
    if (l < heap_size && harr[l] < harr[i])
        largest = l;
    if (r < heap_size && harr[r] < harr[smallest])
        largest = r;
    if (largest != i)
    {
        swap(&harr[i], &harr[largest]);
        MinHeapify(largest);
    }
}
See Binary Heap for details.Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Print list after removing element at given index

31 Mar, 2020
Given an index, remove the element at that index from the list and print the new list.Examples:
Input : list = [10, 20, 30, 40, 50] 
        index = 2
Output : [10, 20, 40, 50] 

Input : list = [10, 20, 40, 50] 
        index = 0 
Output : [20, 40, 50] 

Method 1: Traversal of list
Using traversal in the list, append all the index values except the given index to a new list and then print the new list. For this we will require a new list where we can append all the values except the given index value.
Below is the Python3 implementation of the above approach
# Python3 program to remove the index # element from the list # using traversal   def remove(list1, pos):    newlist = []      # traverse in the list    for x in range(len(list1)):                  # if index not equal to pos        if x != pos:            newlist.append(list1[x])     print(*newlist)    # driver codelist1 = [10, 20, 30, 40, 50]pos = 2remove(list1, pos)
Output:
10 20 40 50

Method 2: pop()
pop() function helps us to pop the value at any desired position that is passed in the parameter, if nothing is passed in the parameter, then it removes the last index value.
Below is the Python3 implementation of the above approach:
# Python3 program to remove the index # element from the list # using pop()  def remove(list1, pos):      # pop the element at index = pos    list1.pop(pos)     print(*list1)            # driver codelist1 = [10, 20, 30, 40, 50]pos = 2remove(list1, pos)
Output:
10 20 40 50

Method 3: del function
del function can be used to remove any element at any given position. If -1 or -2 is given in the [] brackets, then it deletes the last and second last element respectively.
Below is the Python3 implementation of the above approach:
# Python3 program to remove the index element# from the list using del  def remove(list1, pos):      # delete the element at index = pos    del list1[pos]     print(*list1)            # driver codelist1 = [10, 20, 30, 40, 50]pos = 2remove(list1, pos)
Output:
10 20 40 50

SagarUtekar
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | Lemmatization with TextBlob

24 Sep, 2021
Lemmatization is the process of grouping together the different inflected forms of a word so they can be analyzed as a single item. Lemmatization is similar to stemming but it brings context to the words. So it links words with similar meanings to one word.Text preprocessing includes both Stemming as well as Lemmatization. Many times people find these two terms confusing. Some treat these two as the same. Actually, lemmatization is preferred over Stemming because lemmatization does morphological analysis of the words.Applications of lemmatization are:  
Used in comprehensive retrieval systems like search engines.
Used in compact indexing.
 
Examples of lemmatization :

-> rocks : rock
-> corpora : corpus
-> better : good
One major difference with stemming is that lemmatize takes a part of speech parameter, “pos” If not supplied, the default is “noun.”Below is the implementation of lemmatization words using TextBlob:  
Python3
# from textblob lib import Word methodfrom textblob import Word # create a Word object.u = Word("rocks") # apply lemmatization.print("rocks :", u.lemmatize()) # create a Word object.v = Word("corpora") # apply lemmatization.print("corpora :", v.lemmatize()) # create a Word object.w = Word("better")  # apply lemmatization with# parameter "a", "a" denotes adjective.print("better :", w.lemmatize("a"))
Output :  
rocks : rock
corpora : corpus
better : good
 
23620uday2021
Technical Scripter 2018
Machine Learning
Python
Technical Scripter
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL – Show Databases

28 Aug, 2020
In PostgreSQL,  there are couple of ways to list all the databases present on the server. In this article, we will explore them.
To list all the database present in the current database server use one of the following commands:
Syntax: \l or \l+
Example:
First log into the PostgreSQL server using the pSQL shell:
Now use the below command to list all databases using a superuser such as postgres:
\l
This will lead to the following:
Alternatively one can use the below command:
\l+
Output:
The SELECT statement can also be used to list all the database present on the server:
Syntax: SELECT datname FROM pg_database;
Example:
Below is the simple use of the SELECT statement to list all database present on the server:
SELECT datname FROM pg_database;
Output:
postgreSQL-managing-database
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if a number is Prime or not

In this, we’ll write a program that will test if the given number which is greater than 1 is prime or not.
A prime number is a positive integer greater than 1 and which has only two factors 1 & the number itself for example number: 2, 3, 5, 7... etc are prime numbers as they have only two factors .i.e. 1 & the number itself.
# Python program to check if the input number is prime or not
#Take input from the user
num = int(input("Please enter the number: "))
#Check if the given number is greater than 1
if num > 1:
   # Iterate through 2 to num/2.
   for i in range(2,num//2):
      #Select if the number is divisible by any number between 2 and num/2.
      if (num % i) == 0:
         print(num,"is not a prime number")
         print(i,"times",num//i,"is",num)
         break
      else:
         #If given number is not fully divisible by any number between 1 and num/2, then its prime.
         print(num,"is a prime number")
# Also, if the number is less than 1, its also not a prime number.
else:
   print(num,"is not a prime number")
Please enter the number: 47
47 is a prime number
>>>
================= RESTART: C:/Python/Python361/primeNum1.py =================
Please enter the number: -2
-2 is not a prime number
>>>
================= RESTART: C:/Python/Python361/primeNum1.py =================
Please enter the number: 3333
3333 is not a prime number
3 times 1111 is 3333
User-Input 1: num: 47
Output: Number(47) is a prime number
User-Input 2: num = -2
Output: Number(-2) is not a prime number
User-Input 3: num = 3333
Output: Number(3333) is not a prime number
In the above program, we check if the user input number is prime or not. Because numbers less than or equal to 1 are not prime numbers, therefore we only consider user-input greater than 1.
Then we check if the user-input is exactly divisible by any number between 2 to user-input/2. If we find a factor in that range, the number is not a prime number else, it’s a prime number.
How to load JSON data using jQuery?

To load JSON data using jQuery, use the getJSON() and ajax() method. The jQuery.getJSON( ) method loads JSON data from the server using a GET HTTP request.
Here is the description of all the parameters used by this method −
url − A string containing the URL to which the request is sent
data − This optional parameter represents key/value pairs that will be sent to the server.
callback − This optional parameter represents a function to be executed whenever the data is loaded successfully.
Add your JSON content in result.json file −
{
"name": "Amit",
"age" : "27",
"sex": "male"
}
The following is a code snippet showing the usage of this method. It links the above created result.json file,
  <head>  
   <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("#driver").click(function(event){
               $.getJSON('result.json', function(jd) {
                  $('#stage').html('<p> Name: ' + jd.name + '</p>');
                  $('#stage').append('<p>Age : ' + jd.age+ '</p>');
                  $('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
               });
            });
               
         });
      </script>
   </head>
   
   <body>
   
      <p>Click on the button to load result.html file:</p>
       
      <div id = "stage" style = "background-color:#cc0;">
         STAGE
      </div>
       
      <input type = "button" id = "driver" value = "Load Data" />
       
   </body>
Foreach loop with two arrays and if-condition evaluation to find matching values PHP?

Let’s say we have the following two arrays 
$firstArray=array(10,20,30,40,50);
$secondArray=array(100,80,30,40,90);
We need to find the matching i.e. the output should be 
30
40
The PHP code is as follows
 Live Demo
<!DOCTYPE html>
<html>
<body>
<?php
$firstArray=array(10,20,30,40,50);
$secondArray=array(100,80,30,40,90);
foreach($firstArray as $f){
   foreach($secondArray as $s){
      if($f==$s){
         echo "The matching result is=",$f,"<br>";
      }
   }
}
?>
</body>
</html>
This will produce the following output 
The matching result is=30
The matching result is=40
PHP - Simple XML

The simple XML parser is used to parse Name, attributes and textual content.
The simple XML functions are shown below −
This function accepts file path as a first parameter and it is mandatory.
simplexml_load_file(($fileName,$class,$options,$ns,$is_prefix)

This function accepts the string instead of file reference.
simplexml_load_string($XMLData,$class,$options,$ns,$is_prefix)

This function accepts DOM formatted XML content and it converts into simple XML.
simplexml_load_string($DOMNode,$class)

The following example shows, How to parse a xml data file.
<?php
   $data = "<?xml version = '1.0' encoding = 'UTF-8'?>
   
   <note>
      <Course>Android</Course>
      <Subject>Android</Subject>
      <Company>TutorialsPoint</Company>
      <Price>$10</Price>
   </note>";
   
   $xml = simplexml_load_string($data) or die("Error: Cannot create object");
?>
<html>

   <head>
      <body>
         
         <?php
            print_r($xml);
         ?>
      
      </body>
   </head>
   
</html>
It will produce the following result −
SimpleXMLElement Object ( [Course] => Android [Subject] => Android [Company] => TutorialsPoint [Price] => $10 )

We can also call a xml data file as shown below and it produces the same result as shown above −
<?php
   $xml = simplexml_load_file("data") or die("Error: Cannot create object");
   print_r($xml);
?>

    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Is JavaScript a case sensitive language?

JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
NOTE − Care should be taken while writing variable and function names in JavaScript.
The following example shows JavaScript is a case-sensitive language:
<!DOCTYPE html>
<html>
   <body>
      <h3>My favorite subject</h3>
      <p id="demo"></p>
      <script>
          var subject, Subject;
          subject = "Java";
          Subject = "Maths";
          document.getElementById("demo").innerHTML = subject;
      </script>
   </body>
</html>
MongoDB - Relationships

Relationships in MongoDB represent how various documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either 1:1, 1:N, N:1 or N:N.
Let us consider the case of storing addresses for users. So, one user can have multiple addresses making this a 1:N relationship.
Following is the sample document structure of user document −
{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   "name": "Tom Hanks",
   "contact": "987654321",
   "dob": "01-01-1991"
}
Following is the sample document structure of address document −
{
   "_id":ObjectId("52ffc4a5d85242602e000000"),
   "building": "22 A, Indiana Apt",
   "pincode": 123456,
   "city": "Los Angeles",
   "state": "California"
} 
In the embedded approach, we will embed the address document inside the user document.
> db.users.insert({
	{
		"_id":ObjectId("52ffc33cd85242f436000001"),
		"contact": "987654321",
		"dob": "01-01-1991",
		"name": "Tom Benzamin",
		"address": [
			{
				"building": "22 A, Indiana Apt",
				"pincode": 123456,
				"city": "Los Angeles",
				"state": "California"
			},
			{
				"building": "170 A, Acropolis Apt",
				"pincode": 456789,
				"city": "Chicago",
				"state": "Illinois"
			}
		]
	}
})
This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. The whole document can be retrieved in a single query such as −
>db.users.findOne({"name":"Tom Benzamin"},{"address":1})

Note that in the above query, db and users are the database and collection respectively.
The drawback is that if the embedded document keeps on growing too much in size, it can impact the read/write performance.
This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document's id field.
{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   "contact": "987654321",
   "dob": "01-01-1991",
   "name": "Tom Benzamin",
   "address_ids": [
      ObjectId("52ffc4a5d85242602e000000"),
      ObjectId("52ffc4a5d85242602e000001")
   ]
}
As shown above, the user document contains the array field address_ids which contains ObjectIds of corresponding addresses. Using these ObjectIds, we can query the address documents and get address details from there. With this approach, we will need two queries: first to fetch the address_ids fields from user document and second to fetch these addresses from address collection.
>var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})
>var addresses = db.address.find({"_id":{"$in":result["address_ids"]}})


    44 Lectures 
     3 hours 

 Arnab Chakraborty

    54 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    40 Lectures 
     2.5 hours 

 University Code

    26 Lectures 
     8 hours 

 Bassir Jafarzadeh

    70 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Get date format DD/MM/YYYY with MySQL Select Query?

Use the STR_TO_DATE() function from MySQL to set a date format for displaying DD/MM/YYYY date. The syntax is as follows −
SELECT STR_TO_DATE(yourColumnName,’%d/%m/%Y) as anyVariableName from yourTableName.
To understand the above syntax, let us create a table −
mysql> create table DateFormatDemo
   −> (
      −> IssueDate varchar(100)
   −> );
Query OK, 0 rows affected (0.54 sec)
Inserting some string dates into the table. The query to insert date is as follows −
mysql> insert into DateFormatDemo values('26/11/2018');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DateFormatDemo values('27/11/2018');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DateFormatDemo values('2/12/2018');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DateFormatDemo values('3/12/2018');
Query OK, 1 row affected (0.14 sec)
Now you can display all dates which I have inserted above. The query is as follows −
mysql> select *from DateFormatDemo;
The following is the output −
+------------+
| IssueDate  |
+------------+
| 26/11/2018 |
| 27/11/2018 |
| 2/12/2018  |
| 3/12/2018  |
+------------+
4 rows in set (0.00 sec)
You can implement the syntax we discussed in the beginning to convert string to date format. The query is as follows −
mysql> select STR_TO_DATE(IssueDate, '%d/%m/%Y') StringToDateFormatExample from DateFormatDemo;
The following is the output −
+---------------------------+
| StringToDateFormatExample |
+---------------------------+
| 2018-11-26                |
| 2018-11-27                |
| 2018-12-02                |
| 2018-12-03                |
+---------------------------+
4 rows in set (0.00 sec)
Changing ttk Button Height in Python

Ttk adds styles to the tkinter’s standard widget which can be configured through different properties and functions. We can change the height of the ttk button by using the grid(options) method. This method contains various attributes and properties with some different options. If we want to resize the ttk button, we can specify the value of internal padding such as ipadx and ipady.
Let us understand it with an example,
#Import tkinter library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame or window
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
#Create a button using the ttk themed widget
button = ttk.Button(win, text = "Button")
button.grid(ipadx=10, ipady=30 )
win.mainloop()
In the above code, we have added internal padding to the button widget. Now, run the program to display the output,
numpy.random.geometric() in Python - GeeksforGeeks

15 Jul, 2020
With the help of numpy.random.geometric() method, we can get the random samples of geometric distribution and return the random samples of numpy array by using this method.
geometric distribution
Syntax : numpy.random.geometric(p, size=None)
Return : Return the random samples of numpy array.
Example #1 :
In this example we can see that by using numpy.random.geometric() method, we are able to get the random samples of geometric distribution and return the random samples as numpy array by using this method.
Python3
# import numpy and geometricimport numpy as npimport matplotlib.pyplot as plt  # Using geometric() methodgfg = np.random.geometric(0.65, 1000)  count, bins, ignored = plt.hist(gfg, 40, density = True)plt.show()
Output :
Example #2 :
Python3
# import numpy and geometricimport numpy as npimport matplotlib.pyplot as plt  # Using geometric() methodgfg = np.random.geometric(0.85, 1000)  count, bins, ignored = plt.hist(gfg, 10, density = True)plt.show()
Output :
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python