code-rag-bench/online-tutorials huggingface dataset:
Python | Keys with Maximum value

23 Jan, 2020
Many times, we may have problem in which we require to find not just the value, but the corresponding keys to the maximum value in the entire dictionary. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using max() + list comprehension + values()The combination of above functions can be used to perform this particular task. In this, maximum value is extracted using the max function, while values of dictionary is extracted using values(). The list comprehension is used to iterate through the dictionary for matching keys with max value.
# Python3 code to demonstrate working of# Keys with Maximum value# Using max() + list comprehension + values()  # initializing dictionarytest_dict = {'Gfg' : 2, 'for' : 1, 'CS' : 2}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using max() + list comprehension + values()# Keys with Maximum valuetemp = max(test_dict.values())res = [key for key in test_dict if test_dict[key] == temp]  # printing result print("Keys with maximum values are : " + str(res))
The original dictionary is : {'CS': 2, 'Gfg': 2, 'for': 1}
Keys with maximum values are : ['CS', 'Gfg']

 
Method #2 : Using all() + list comprehensionThis task can also be performed using list comprehension and all function. In this, we take all the elements values, using all function that are smaller than values with keys and return the keys with largest values using list comprehension.
# Python3 code to demonstrate working of# Keys with Maximum value# Using all() + list comprehension  # initializing dictionarytest_dict = {'Gfg' : 2, 'for' : 1, 'CS' : 2}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using all() + list comprehension# Keys with Maximum valueres = [key for key in test_dict if all(test_dict[temp] <= test_dict[key] for temp in test_dict)]  # printing result print("Keys with maximum values are : " + str(res))
The original dictionary is : {'CS': 2, 'Gfg': 2, 'for': 1}
Keys with maximum values are : ['CS', 'Gfg']

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
SQL | Intersect & Except clause

30 Jun, 2022
1. INTERSECT clause : As the name suggests, the intersect clause is used to provide the result of the intersection of two select statements. This implies the result contains all the rows which are common to both the SELECT statements. Syntax :
SELECT column-1, column-2 ...... 
FROM table 1
WHERE.....

INTERSECT

SELECT column-1, column-2 ...... 
FROM table 2
WHERE.....
Example : Table 1 containing Employee Details  Table 2 containing details of employees who are provided bonus  Query :
SELECT ID, Name, Bonus 
FROM
table1 
LEFT JOIN
table2
ON table1.ID = table2.Employee_ID

INTERSECT

SELECT ID, Name, Bonus 
FROM
table1 
RIGHT JOIN
table2
ON table1.ID = table2.Employee_ID;
 
Result :    2. EXCEPT clause :  contains all the rows that are returned by the first SELECT operation, and not returned by the second SELECT operation.  Syntax :
SELECT column-1, column-2 ...... 
FROM table 1
WHERE.....

EXCEPT

SELECT column-1, column-2 ...... 
FROM table 2
WHERE.....
Example : Table 1 containing Employee Details  Table 2 containing details of employees who are provided bonus  Query :
SELECT ID, Name, Bonus 
FROM
table1 
LEFT JOIN
table2
ON table1.ID = table2.Employee_ID

EXCEPT

SELECT ID, Name, Bonus 
FROM
table1 
RIGHT JOIN
table2
ON table1.ID = table2.Employee_ID;
Result : 
yaraalsham86
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL Correlated Subqueries
MySQL | Regular expressions (Regexp)
What is Temporary Table in SQL?
C# | Boolean.CompareTo(Boolean) Method

06 Jan, 2022
Boolean.CompareTo(Boolean) Method is used to compare the current instance to a specified Boolean object and returns an indication of their relative values.
Syntax:
public int CompareTo (bool value);
Here, the value is a Boolean object to compare to the current instance.
Return Value: This method returns a 32-bit signed integer that indicates the relative order of this instance and value. 
Less than zero: If this instance is false and value is true.
Zero: If this instance and value are equal (either both are true or both are false).
Greater than zero: If this instance is true and value is false.
Example: 
C#
// C# program to demonstrate// Boolean.CompareTo(Boolean)// Methodusing System; class GFG {     // Main Method    public static void Main()    {         // Declaring val1 and val2        bool val1, val2;         // initializing the val1,        // and val2        val1 = true;        val2 = false;         // using CompareTo method        int i = val2.CompareTo(val1);         // checking the condition        if (i > 0)            Console.Write("val2 is greater than val1");         else if (i < 0)            Console.Write("val2 is less than val1");         else            Console.Write("val1 is equal to val1");    }}
val2 is less than val1
 
Reference: 
https://docs.microsoft.com/en-us/dotnet/api/system.boolean.compareto?view=netframework-4.8#System_Boolean_CompareTo_System_Boolean_
 
sweetyty
CSharp Boolean Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
Python | Select dictionary with condition given key greater than k

29 May, 2019
In Python, sometimes we require to get only some of the dictionary required to solve the problem. This problem is quite common in web development that we require to get only the selective dictionary satisfying some given criteria. Let’s discuss certain ways in which this problem can be solved.
Method #1: Using list comprehension
# Python3 code to demonstrate# filtering of a list of dictionary# on basis of condition  # initialising list of dictionaryini_list = [{'a':1, 'b':3, 'c':7}, {'a':3, 'b':8, 'c':17},            {'a':78, 'b':12, 'c':13}, {'a':2, 'b':2, 'c':2}]  # printing initial list of dictionaryprint ("initial_list", str(ini_list))  # code to filter list# where c is greater than 10res = [d for d in ini_list if d['c'] > 10]  # printing resultprint ("resultant_list", str(res))
Output:
initial_list [{‘c’: 7, ‘b’: 3, ‘a’: 1}, {‘c’: 17, ‘b’: 8, ‘a’: 3}, {‘c’: 13, ‘b’: 12, ‘a’: 78}, {‘c’: 2, ‘b’: 2, ‘a’: 2}]resultant_list [{‘c’: 17, ‘b’: 8, ‘a’: 3}, {‘c’: 13, ‘b’: 12, ‘a’: 78}]
 Method #2: Using lambda and filter
# Python3 code to demonstrate# filtering of list of dictionary# on basis of condition  # initialising list of dictionaryini_list = [{'a':1, 'b':3, 'c':7}, {'a':3, 'b':8, 'c':17},            {'a':78, 'b':12, 'c':13}, {'a':2, 'b':2, 'c':2}]  # printing initial list of dictionaryprint ("initial_list", str(ini_list))  # code to filter list# where c is less than 10res = list(filter(lambda x:x["c"] > 10, ini_list ))  # printing resultprint ("resultant_list", str(res))
Output:
initial_list [{‘b’: 3, ‘c’: 7, ‘a’: 1}, {‘b’: 8, ‘c’: 17, ‘a’: 3}, {‘b’: 12, ‘c’: 13, ‘a’: 78}, {‘b’: 2, ‘c’: 2, ‘a’: 2}]resultant_list [{‘c’: 17, ‘b’: 8, ‘a’: 3}, {‘c’: 13, ‘b’: 12, ‘a’: 78}]
 Method #3: Using dict comprehension and list comprehension
# Python3 code to demonstrate# filtering of list of dictionary# on basis of condition  # initialising list of dictionaryini_list = [{'a':1, 'b':3, 'c':7}, {'a':3, 'b':8, 'c':17},            {'a':78, 'b':12, 'c':13}, {'a':2, 'b':2, 'c':10}]                  # printing initial list of dictionaryprint ("initial_list", str(ini_list))  # code to filter list# where c is more than 10  res = [{ k:v for (k, v) in i.items()}         for i in ini_list if i.get('c') > 10]  # printing resultprint ("resultant_list", str(res))
Output:
initial_list [{‘a’: 1, ‘c’: 7, ‘b’: 3}, {‘a’: 3, ‘c’: 17, ‘b’: 8}, {‘a’: 78, ‘c’: 13, ‘b’: 12}, {‘a’: 2, ‘c’: 10, ‘b’: 2}]resultant_list [{‘a’: 3, ‘c’: 17, ‘b’: 8}, {‘a’: 78, ‘c’: 13, ‘b’: 12}]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
askopenfile() function in Python Tkinter

Instead of hard coding the path to a file to be used by a python program, we can allow the user to browse the os folder structure using a GUI and let the user select the file. This is achieved using the tkinter module in which we define a canvas and put a button on it to browse the files.
In the below program, we define a file opener function. We only use this function to open a text file as python can read the content of a text file and print it out in a much readable manner. We can read any text based files like .txt or .csv files.
from tkinter import *
from tkinter import filedialog
base = Tk()
# Create a canvas
base.geometry('150x150')
# Function for opening the file
def file_opener():
   input = filedialog.askopenfile(initialdir="/")
   print(input)
   for i in input:
      print(i)
# Button label
x = Button(base, text ='Select a .txt/.csv file', command = lambda:file_opener())
x.pack()
mainloop()
The below dialogue box opens to browse a file.
Then we choose a file.
Running the above code gives us the following result −
<_io.TextIOWrapper name='C:/Users/Pradeep/Documents/welcome.txt' mode='r' encoding='cp1252'>
Hello There !
Welcome to Tutorialspoint!
Difference between Test-Path and Resolve-Path in PowerShell?

Test-Path command checks if the particular path exists or not and returns the Boolean output (True or False) while Resolve-Path command displays the particular directory if exists otherwise throws an exception. For example,
For the path to exist,
PS C:\> Test-Path C:\Temp\
True
PS C:\> Resolve-Path C:\Temp\
Path
----
C:\Temp\
For the path doesn’t exist,
PS C:\> Test-Path C:\Temp11\
False
PS C:\> Resolve-Path C:\Temp11\
Resolve-Path : Cannot find path 'C:\Temp11\' because it does not exist.
At line:1 char:1
+ Resolve-Path C:\Temp11\
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Temp11\:String) [Resolve-Path], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand
Resolve-Path is also used to get the file content using the wildcard character. For example,
Resolve-Path C:\Temp\*
The above command will get all the files and folders inside the C:\temp path.
Resolve-Path C:\Temp\web*
The above command will get all the files from the C:\temp with the Web starting keyword.
Path
----
C:\Temp\WebImages
C:\Temp\web.html
C:\Temp\web1.html
How to get file last modified time in Java?

He class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
The lastModified() method of the File class returns the last modified time of the file/directory represented by the current File object. You can get the last modified time of a particular file using this method.
Following Java program gets the last modified time of a directory −
import java.io.File;
import java.util.Date;
public class GettingLastmodifiedTime {
   public static void main(String args[]) {
      String filePath = "D://ExampleDirectory//";
      //Creating the File object
      File file = new File(filePath);
      //Getting the last modified time
      long lastModified = file.lastModified();
      Date date = new Date(lastModified);
      System.out.println("Given file was last modified at: ");
      System.out.println(date);
   }
}
Given file was last modified at:
Wed Jul 03 19:20:50 IST 2019
How to limit the values in a Number JSpinner Component with Java?

To limit the values in a number JSpinner component, use the SpinnerNumberModel that allows to set the min, max, step size and even the initial value −
value − current value of the model
min − first number in the sequence
max − last number in the sequence
stepSize − difference between elements of the sequence
Let us set the above values −
int min = 0;
int max = 10;
int step = 1;
int i = 1;
SpinnerModel value = new SpinnerNumberModel(i, min, max, step);
Now, we will set these values to our JSpinner −
JSpinner spinner = new JSpinner(value);
The following is an example to limit the values in a number JSpinner component −
package my;
import java.awt.GridBagLayout;
import javax.swing.*;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Spinner Demo");
      JPanel panel = new JPanel();
      JLabel label = new JLabel("Rank − ");
      panel.setLayout(new GridBagLayout());
      int min = 0;
      int max = 10;
      int step = 1;
      int i = 1;
      SpinnerModel value = new SpinnerNumberModel(i, min, max, step);
      JSpinner spinner = new JSpinner(value);
      spinner.setBounds(50, 80, 70, 100);
      panel.add(label);
      panel.add(spinner);
      frame.add(panel);
      frame.setSize(550,300);
      frame.setVisible(true);
   }
}
This will produce the following output −
Jump Search

Jump search technique also works for ordered lists. It creates a block and tries to find the element in that block. If the item is not in the block, it shifts the entire block. The block size is based on the size of the list. If the size of the list is n then block size will be √n. After finding a correct block it finds the item using a linear search technique. The jump search lies between linear search and binary search according to its performance.
Time Complexity: O(√n)
Space Complexity: O(1)
Input:
A sorted list of data:
10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995
The search key 356
Output:
Item found at location: 11
jumpSearch(array, size, key)
Input: An sorted array, size of the array and the search key
Output − location of the key (if found), otherwise wrong location.
Begin
   blockSize := √size
   start := 0
   end := blockSize
   while array[end] <= key AND end < size do
      start := end
      end := end + blockSize
      if end > size – 1 then
         end := size
   done
   for i := start to end -1 do
      if array[i] = key then
         return i
   done
   return invalid location
End
#include<iostream>
#include<cmath>

using namespace std;
int jumpSearch(int array[], int size, int key) {
   int start = 0;
   int end = sqrt(size); //the square root of array length

   while(array[end] <= key && end < size) {
      start = end; //it it is not correct block then shift block
      end += sqrt(size);
      if(end > size - 1)
         end = size; //if right exceeds then bound the range
   }

   for(int i = start; i<end; i++) { //perform linear search in selected block
      if(array[i] == key)
         return i; //the correct position of the key
   }
   return -1;
}

int main() {
   int n, searchKey, loc;
   cout << "Enter number of items: ";
   cin >> n;
   int arr[n]; //create an array of size n
   cout << "Enter items: " << endl;

   for(int i = 0; i< n; i++) {
      cin >> arr[i];
   }

   cout << "Enter search key to search in the list: ";
   cin >> searchKey;
   if((loc = jumpSearch(arr, n, searchKey)) >= 0)
      cout << "Item found at location: " << loc << endl;
   else
      cout << "Item is not found in the list." << endl;
}
Enter number of items: 20
Enter items:
10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995
Enter search key to search in the list: 356
Item found at location: 11
Python Program to Count number of binary strings without consecutive 1’

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a positive integer N, we need to count all possible distinct binary strings available with length N such that no consecutive 1’s exist in the string.
Now let’s observe the solution in the implementation below −
 Live Demo
# count the number of strings
def countStrings(n):
   a=[0 for i in range(n)]
   b=[0 for i in range(n)]
   a[0] = b[0] = 1
   for i in range(1,n):
      a[i] = a[i-1] + b[i-1]
      b[i] = a[i-1]
   return a[n-1] + b[n-1]
# main
n=5
print("The number of strings: ",countStrings(n))
The number of strings: 13
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python Program to Count number of binary strings without consecutive 1’
Disconnecting Inactive SSH Connections in Linux - GeeksforGeeks

19 Feb, 2021
SSH or Secure Shell is a cryptographic network protocol that establishes a secure connection between systems remotely. Any user can use this protocol to manage the system remotely but mainly system administrators use it because it transmits data over encrypted channels, which increases its security at a high level. SSH can be used to manage the system, move between files and folders, etc. To disconnect inactive or idle SSH connections we have to set the timeout period for an SSH within which if a server does not receive any request from the client then it will disconnect the connection.
Follow the steps to set the timeout period for an SSH connection:
Step 1: On the server, head over to the /etc/ssh/sshd_config configuration file.
$ sudo vi /etc/ssh/sshd_config 
Step 2: Scroll and locate the following parameters and remove the ‘#’ symbol to uncomment it:
#ClientAliveInterval
#ClientAliveCountMax
Here,
ClientAliveInterval: Sets a timeout interval in seconds after which if no data has been received from the client, sshd will send a message through the encrypted channel to request a response from the client. In simple ways, the number of seconds that the server waits before sending a null packet to the client.
ClientAliveCountMax: Sets the number of client alive messages which may be sent without sshd receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session.
The timeout value is given by the product of the above parameters i.e.
Timeout value = ClientAliveInterval * ClientAliveCountMax
For example let’s define our parameter 
ClientAliveInterval = 30
ClientAliveCountMax = 3
The Timeout value will be 30 seconds * 3 = 90 seconds. This is an equivalent of 1 minute and 30 seconds, which implies that your ssh session will remain alive for idle time of 1 minute 30 seconds without dropping.
Step 3: Once done, reload the “sshd” for the changes to come into effect.
$ sudo systemctl reload sshd
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
mv command in Linux with examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
How to loop through an array in Java?

To process array elements, we often use either for loop or for each loop because all of the elements in an array are of the same type and the size of the array is known. Suppose we have an array of 5 elements we can print all the elements of this array as −
Live Demo
public class ProcessingArrays {
   public static void main(String args[]) {
      int myArray[] = {22, 23, 25, 27, 30};
     
      for(int i=0; i<myArray.length; i++) {
         System.out.println(myArray[i]);
      }
   }
}
22
23
25
27
30
Generating random numbers in C#

To generate random numbers, use Random class.
Create an object −
Random r = new Random();
Now, use the Next() method to get random numbers in between a range −
r.Next(10,50);
The following is the complete code −
 Live Demo
using System;
public class Program {
   public static void Main() {
      Random r = new Random();
      int genRand= r.Next(10,50);
      Console.WriteLine("Random Number = "+genRand);
   }
}
Random Number = 24
D3.js count() method - GeeksforGeeks

14 Sep, 2020
With the help of d3.count() method, we can get the count of valid values in the specified iterable data structure.
Syntax:
d3.count(iterable[, accessor])

Return value: It returns the count of valid values.
Note: To execute the below examples you have to install the d3 library by using the command prompt for the following command.
npm install d3

Example 1: In this example we can see that by using d3.count() method, we are able to get the count of valid values in the specified iterables.
Javascript
// Defining d3 contrib variable  var d3 = require('d3');  data = [  {name: "ABC",   amount: "34.0",   date: "11/12/2015"},  {name: "DEF",  amount: "120.11", date: "11/12/2015"},  {name: "MNO", amount: "12.01",  date: "01/04/2016"},  {name: "ABC", amount: "34.05",  date: "01/04/2016"}]  var gfg = d3.count(data, d => d.amount);console.log(gfg);
Output:
4

Example 2:
Javascript
// Defining d3 contrib variable  var d3 = require('d3');  data = [  {name: "ABC",   amount: "34.0",   age: 20},  {name: "DEF",  amount: "120.11", age: NaN},  {name: "MNO", amount: "12.01",  age: 23},  {name: "DEF", amount: "34.05",  age: 24}]  var gfg = d3.count(data, d => d.age);console.log(gfg);
Output :
3

D3.js
JavaScript
Node.js
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
Enumeration of Binary Trees

26 Oct, 2021
A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. 
 
Below two are considered same unlabelled trees
    o                 o
  /   \             /   \ 
 o     o           o     o 

Below two are considered different labelled trees
    A                C
  /   \             /  \ 
 B     C           A    B 
How many different Unlabelled Binary Trees can be there with n nodes?  
For n  = 1, there is only one tree
   o

For n  = 2, there are two trees
   o      o
  /        \  
 o          o

For n  = 3, there are five trees
    o      o           o         o      o
   /        \         /  \      /         \
  o          o       o    o     o          o
 /            \                  \        /
o              o                  o      o
The idea is to consider all possible pairs of counts for nodes in left and right subtrees and multiply the counts for a particular pair. Finally, add the results of all pairs. 
 
For example, let T(n) be count for n nodes.
T(0) = 1  [There is only 1 empty tree]
T(1) = 1
T(2) = 2

T(3) =  T(0)*T(2) + T(1)*T(1) + T(2)*T(0) = 1*2 + 1*1 + 2*1 = 5

T(4) =  T(0)*T(3) + T(1)*T(2) + T(2)*T(1) + T(3)*T(0)
     =  1*5 + 1*2 + 2*1 + 5*1 
     =  14 
The above pattern basically represents n’th Catalan Numbers. First few Catalan numbers are 1 1 2 5 14 42 132 429 1430 4862,... Here, T(i-1) represents the number of nodes on the left-sub-tree T(n−i-1) represents the number of nodes on the right-sub-tree 
n’th Catalan Number can also be evaluated using the direct formula. 
   T(n) = (2n)! / (n+1)!n!
The number of Binary Search Trees (BST) with n nodes is also the same as the number of unlabelled trees. The reason for this is simple, in BST also we can make any key a root, If the root is i’th key in sorted order, then i-1 keys can go on one side, and (n-i) keys can go on another side. 
How many labeled Binary Trees can be there with n nodes? To count labeled trees, we can use the above count for unlabelled trees. The idea is simple, every unlabelled tree with n nodes can create n! different labeled trees by assigning different permutations of labels to all nodes. 
Therefore, 
Number of Labelled Trees = (Number of unlabelled trees) * n!
                       = [(2n)! / (n+1)!n!]  × n!
For example for n = 3, there are 5 * 3! = 5*6 = 30 different labelled trees 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
satyajitmahunta98
anikaseth98
reenadevi98412200
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Concatenate two columns when one of such column values is null in MySQL

To avoid any issues while running a query, use IFNULL(). Let us first create a table −
mysql> create table DemoTable1793
     (
     StudentFirstName varchar(20),
     StudentLastName varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1793 values('John','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1793 values('Carol',NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1793 values(NULL,'Brown');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1793;
This will produce the following output −
+------------------+-----------------+
| StudentFirstName | StudentLastName |
+------------------+-----------------+
| John             |           Smith |
| Carol            |            NULL |
| NULL             |           Brown |
+------------------+-----------------+
3 rows in set (0.00 sec)
Here is the query to concatenate two columns when one of such column values is null −
mysql> select concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) from DemoTable1793;
This will produce the following output −
+----------------------------------------------------------------+
| concat(ifnull(StudentFirstName,''),ifnull(StudentLastName,'')) |
+----------------------------------------------------------------+
| JohnSmith                                                      |
| Carol                                                          |
| Brown                                                          |
+----------------------------------------------------------------+
3 rows in set (0.00 sec)
Java - acos() Method

The method returns the arccosine of the specified double value.
double acos(double d)

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

   public static void main(String args[]) {
      double degrees = 45.0;
      double radians = Math.toRadians(degrees);

      System.out.format("The value of pi is %.4f%n", Math.PI);
      System.out.format("The arccosine of %.4f is %.4f degrees %n", Math.cos(radians),
         Math.toDegrees(Math.acos(Math.cos(radians))));
   }
}
This will produce the following result −
The value of pi is 3.1416
The arccosine of 0.7071 is 45.0000 degrees


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Data Visualization in Pandas. Quick data visualization using only... | by C K | Towards Data Science

In this article, I will demonstrate how to visualize data using only Pandas. It is not as flexible as Matplotlib or Seaborn, but it is very convenient for quick data exploration.
First, let’s import pandas and load Iris dataset as an example.
import pandas as pdimport seaborndf=seaborn.load_dataset('iris')
and check the dataframe
It contains 4 numerical columns and one categorical column.
Let’s start with the simple line plot.
It plots the numerical columns in different colors. The x-axis here is the index. You can also customize the plot, for example, if you only want to see sepal_length and sepal_width, you can do this:
You can also change the axis. For example, plot sepal_length against petal_length (does not make sense here to use line plot though)
The proper plot to show the relationship between sepal_length and petal_length should be a scatter plot.
You can plot for different columns by replacing x and y.
One trick to check the correlations for all the numerical columns is to plot the scatter plot matrix. You can do it by:
It shows a matrix of scatter plots of different columns against others and histograms of the columns.
The histogram is a useful plot to see the distribution of data, in Pandas you can quickly plot it using hist()
It shows the histograms of the numerical variables. You can also plot the columns you want.
Another useful plot the see the data distribution is the box plot. You can simply plot it by using df.plot.box()
You might also want to compare different species, you can do this by combining pandas groupby() and plot.bar()
It shows the mean value of the columns against species.
It is also possible to plot a bar chart. Simply call plot.pie() .
Please be noted that the plot() function in Pandas is built on top of Matplotlib, so you can always use matplotlib to modify the plot.
For example, you can change the location of legend and hide the ylabel.
That’s it. These plotting techniques in Pandas might not be as flexible and report-ready as matplotlib or seaborn, but they are still quite convenient in the early stage data exploration.
Thanks for reading.
You can check my other articles about Pandas, Numpy and Python.
Use of _SYS_REPO in SAP HANA database

In SAP HANA system _SYS_REPO user is required to create run time objects that are saved in HANA database under _SYS_BIC schema. When you activate modeling views in HANA, SYS REPO provides the read access to users on these modeling views. That is why it is required to grant _SYS_REPO with SELECT with GRANT privilege to user schemas.
GRANT SELECT ON SCHEMA "SCHEMA_NAME" TO _SYS_REPO WITH GRANT OPTION
This is required when you use objects of a table/view of a schema to build HANA Modeling Views. You need to grant _SYS_REPO the SELECT WITH GRANT privilege on this schema.
How to convert BLOB to Byte Array in java?

You can contents of a blob into a byte array using the getBytes() method.
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
public class BlobToByteArray {
   public static void main(String[] args) throws Exception {
      Image image = new BufferedImage(300,400, BufferedImage.TYPE_INT_RGB);
      String JDBC_DRIVER = "com.mysql.jdbc.Driver";
      String DB_URL = "jdbc:mysql://localhost/mydb";
      String USER = "root";
      String PASS = "password";
      Connection conn = null;
      Statement stmt = null;
      Class.forName("com.mysql.jdbc.Driver");
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");
      System.out.println("getting blob.......");
      stmt = conn.createStatement();
      String sql = "SELECT * FROM sample";
      ResultSet rs = stmt.executeQuery(sql);
      while(rs.next()) {
         Blob blob = rs.getBlob("image");
         byte [] bytes = blob.getBytes(1l, (int)blob.length());
         for(int i=0; i<bytes.length;i++) {
            System.out.println(Arrays.toString(bytes));
         }
      }
   }
}
Connecting to a selected database...
Connected database successfully...
getting blob.......
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
[100, 58, 115, 97, 109, 112, 108, 101, 46, 106, 112, 103]
What are different ways of defining functions in JavaScript?

The following are some of the ways of defining functions in JavaScript −
The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.
Here’s an example showing normal function definition −
<script>
   <!--
      function Display()
      {
         alert("Hello World!");
      }
   //-->
</script>
Another way of defining functions in JavaScript is to use Immediately Invoked Functions. The purpose of wrapping is to the namespace and control the visibility of member functions. It wraps the code inside a function scope and decreases clashing with other libraries. This is what we call Immediately Invoked Function Expression (IIFE) or Self Executing Anonymous Function.
Here’s the syntax −
(function() {
   // code
})();
As you can see above, the following pair of parentheses converts the code inside the parentheses into an expression −
function(){...}
In addition, the next pair, i.e. the second pair of parentheses continues the operation. It calls the function, which resulted from the expression above.
Anonymous functions are always loaded using a variable name. Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. Call them using a variable name −
This is how JavaScript anonymous functions can be used −
var func = function() {
   alert(‘This is anonymous');
}
func();
//anonymous function
var a = function() {
   return 5;
}
The function() constructor is used in JavaScript to create a new function object. The objects created are parsed when the function is created.
You can try to run the following code to learn how to work with function() constructor −
<html>
   <body>
      <script>
         var num = new Function('p', 'q', 'r', 'return p * q * r');
         document.write("Value after multiplication: "+num(5, 2, 9));
      </script>
   </body>
</html>
Sentiment Analysis using ALBERT. Let’s fine-tune Google’s latest NLP... | by Gagandeep Singh | Towards Data Science

Every researcher or NLP practitioner is well aware of BERT which came in 2018. Since then the NLP industry has transformed by a much larger extent.
Albert which is A Lite BERT was made in focus to make it as light as possible by reducing parameter size.
The great advantage of Deep Learning for Sentiment Analysis Task is that the step where we preprocess data gets reduced. The only preprocessing required would be to convert them to lower case. If we are using machine learning methods like logistic regression with TF-IDF then you’ll need to lemmatize words and also remove the unnecessary words. If you are thinking about removing Stopwords then check this article
towardsdatascience.com
If you want to learn about the latest text preprocessing steps then check out this article.
towardsdatascience.com
First clone this GitHub repo.Prepare the dataset. A tab-separated(.tsv) file is required. The dataset needs to be placed inside a folder in the same directory.Dataset will have 2 columns. One will contain text and the other will contain the label.Write train command
First clone this GitHub repo.
Prepare the dataset. A tab-separated(.tsv) file is required. The dataset needs to be placed inside a folder in the same directory.
Dataset will have 2 columns. One will contain text and the other will contain the label.
Write train command
$ python run_glue.py --data_dir data --model_type albert --model_name_or_path albert-base-v2 --output_dir output --do_train --task_type sst-2
data-dir - where train.tsv file is placed
model_type - The model which you want to use for sentiment analysis task. Here we are using ALBERT.
model_name_or_path - The variant of the model that you want to use. Here we are using albert-base-v2.
output-dir- The directory where you want to save the model. The script will automatically create the folder.
do-train - Because we are performing train operation.
task_type - Two tasks can be performed — SST-2 and SST-5.
Here is a list of various models that you can use
5. After the model has been trained, all the model files will be inside a folder.
6. Replace the model directory in the api.py file.
7. Run api.py file
$ python api.py
8. If you want to call its predict method then
$ from api import SentimentAnalyzer$ classifier = SentimentAnalyszer()$ classifier.predict('It was a good movie')
Python | Summation of tuples in list - GeeksforGeeks

25 Aug, 2021
Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have application in cases in which we deal with a lot of records data. Let’s discuss certain ways in which this problem can be solved.Method #1 : Using sum() + map() Combination of above functions can be used to solve this particular problem. In this the task of summation is performed by sum(), and applying the summation functionality to each element in tuple list is performed by map(). 
Python3
# Python3 code to demonstrate working of# Summation of tuples in list# using sum() + map() # initialize list of tupletest_list = [(1, 3), (5, 6, 7), (2, 6)] # printing original tuples listprint("The original list : " + str(test_list)) # Summation of tuples in list# using sum() + map()res = sum(map(sum, test_list)) # printing resultprint("The summation of all tuple elements are : " + str(res))
The original list : [(1, 3), (5, 6, 7), (2, 6)]
The summation of all tuple elements are : 30
 
 Method #2 : Using sum() + izip() The combination of above functions can be used to perform this particular task. In this, we perform the task of map() using izip(). It helps to club all the elements for summation by sum(). Works only for single element tuple and only with Python2. 
Python3
# Python3 code to demonstrate working of# Summation of tuples in list# using sum() + izip()from itertools import izip # initialize list of tupletest_list = [(1, ), (5, ), (2, )] # printing original tuples listprint("The original list : " + str(test_list)) # Summation of tuples in list# using sum() + map()res = sum(*izip(*test_list)) # printing resultprint("The summation of all tuple elements are : " + str(res))
The original list : [(1, ), (5, ), (2, )]
The summation of all tuple elements are : 8
 
gabaa406
Python tuple-programs
Python
Python Programs
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
HTML - Button Tag

The HTML <button> tag is used for creating a button within HTML form. You can also use <input> tag to create similar buttons.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML Button Tag</title>
   </head>

   <body>
      <form>
         <button name = "button" value = "OK" type = "button">Click Me</button>
      </form>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in HTML Attribute Reference
The HTML <button> tag also supports the following  additional attributes −
This tag supports all the event attributes described in HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
VBScript Len Function

The Len Function returns the length of the given input string including the blank spaces.
Len(String)

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         var1 = "Microsoft VBScript"
         document.write("Length of var1 is : " & Len(var1) & "<br />")

         var2 = "Microsoft VBScript"
         document.write("Length of var2 is : " & Len(var2) & "<br />")

      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Length of var1 is : 18
Length of var2 is : 36


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
C++ Program for the Common Divisors of Two Numbers?

The common divisor of two numbers are the numbers that are divisors of both of them.
For example,
The divisors of 12 are 1, 2, 3, 4, 6, 12.
The divisors of 18are 1, 2, 3, 6, 9, 18.
Thus, the common divisors of 12 and 18 are 1, 2, 3, 6.
The greatest among these is, perhaps unsurprisingly, called the greatest common divisor of 12 and 18. The usual mathematical notation for the greatest common divisor of two integers a and b are denoted by (a, b). Hence, (12, 18) = 6.
The greatest common divisor is important for many reasons. For example, it can be used to calculate the LCM of two numbers, i.e., the smallest positive integer that is a multiple of these numbers. The least common multiple of the numbers a and b can be calculated as ab(a, b).
For example, the least common multiple of 12 and 18 is
12·18(12, 18) =12 · 18.6
Input: a = 10, b = 20
Output: 1 2 5 10
// all common divisors are 1 2 5 10
Integers that can exactly divide both numbers (without a remainder).
#include <iostream>
using namespace std;
int main() {
   int n1, n2, i;
   n1=10;
   n2=20;
   for(i=1; i <= n1 && i <= n2; ++i) {
      if(n1%i==0 && n2%i==0) {
         cout<<i<<"\t";
      }
   }
}
Tryit Editor v3.7

Tryit: Text shadow with blur effect
basic_string c_str function in C++ STL - GeeksforGeeks

17 Jul, 2018
The basic_string::c_str() is a builtin function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object. This array includes the same sequence of characters that make up the value of the basic_string object plus an additional terminating null-character at the end.
Syntax:
const CharT* c_str() const

Parameter: The function does not accept any parameter.
Return Value : The function returns a constant Null terminated pointer to the character array storage of the string.
Below is the implementation of the above function:
Program 1:
// C++ code for illustration of// basic_string::c_str function#include <bits/stdc++.h>#include <string>using namespace std;  int main(){    // declare a example string    string s1 = "GeeksForGeeks";      // check if the size of the string is same as the    // size of character pointer given by c_str    if (s1.size() == strlen(s1.c_str())) {        cout << "s1.size is equal to strlen(s1.c_str()) " << endl;    }    else {        cout << "s1.size is not equal to strlen(s1.c_str())" << endl;    }      // print the string    printf("%s \n", s1.c_str());}
s1.size is equal to strlen(s1.c_str()) 
GeeksForGeeks 

Program 2:
// C++ code for illustration of// basic_string::c_str function#include <bits/stdc++.h>#include <string>using namespace std;  int main(){    // declare a example string    string s1 = "Aditya";      // print the characters of the string    for (int i = 0; i < s1.length(); i++) {        cout << "The " << i + 1 << "th character of string " << s1             << " is " << s1.c_str()[i] << endl;    }}
The 1th character of string Aditya is A
The 2th character of string Aditya is d
The 3th character of string Aditya is i
The 4th character of string Aditya is t
The 5th character of string Aditya is y
The 6th character of string Aditya is a


CPP-Functions
cpp-string
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Destructors in C++
Python | Pandas Index.dropna() - GeeksforGeeks

12 Jan, 2022
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.dropna() function return Index without NA/NaN values. All the missing values are removed and a new object is returned which does not have any NaN values present in it.
Syntax: Index.dropna(how=’any’)
Parameters :how : {‘any’, ‘all’}, default ‘any’If the Index is a MultiIndex, drop the value when any or all levels are NaN.
Returns : valid : Index
Example #1: Use Index.dropna() function to remove all missing values from the given Index containing datetime data.
Python3
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index(['2015-10-31', '2015-12-02', None, '2016-01-03',                '2016-02-08', '2017-05-05', None, '2014-02-11'])  # Print the Indexidx
Output :
Let’s drop all the NaN values from the Index.
Python3
# drop all missing values.idx.dropna(how ='all')
Output :
As we can see in the output, the Index.dropna() function has removed all the missing values. Example #2: Use Index.dropna() function to delete all the missing values in the Index. Index contains string type data.
Python3
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index(['Jan', 'Feb', 'Mar', None, 'May', 'Jun',                None, 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])  # Print the Indexidx
Output :
Let’s drop all the missing values.
Python3
# drop the missing valuesidx.dropna(how ='any')
Output :As we can see in the output all missing values of months has been removed.
surindertarika1234
Python pandas-indexing
Python-pandas
Technical Scripter 2018
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python