code-rag-bench/online-tutorials huggingface dataset:
How to pass Drop Down Box Data to Python CGI script?

Drop Down Box is used when we have many options available but only one or two will be selected.
Here is example HTML code for a form with one drop down box −
<form action = "/cgi-bin/dropdown.py" method = "post" target = "_blank">
   <select name = "dropdown">
      <option value = "Maths" selected>Maths</option>
      <option value = "Physics">Physics</option>
   </select>
   <input type = "submit" value = "Submit"/>
</form>
The result of this code is the following form −
 Submit
Below is dropdown.py script to handle input given by web browser.
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('dropdown'):
   subject = form.getvalue('dropdown')
else:
   subject = "Not entered"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Dropdown Box - Sixth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"
Python String rindex() Method

Python string  method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists, optionally restricting the search to string[beg:end].
Following is the syntax for rindex() method −
str.rindex(str, beg=0 end=len(string))

str − This specifies the string to be searched.
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0
beg − This is the starting index, by default its 0
len − This is ending index, by default its equal to the length of the string.
len − This is ending index, by default its equal to the length of the string.
This method returns last index if found otherwise raises an exception if str is not found.
The following example shows the usage of rindex() method.
#!/usr/bin/python

str1 = "this is string example....wow!!!";
str2 = "is";

print str1.rindex(str2)
print str1.index(str2)
When we run above program, it produces following result −
5
2


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to check table status of the tables in a particular MySQL database?

We can check the status of tables in a database with the help of show table status statement. For example, in the database named tutorial, by executing this statement we can get the status of tables as follows −
mysql> show table status \G
*************************** 1. row ***************************
           Name: student
         Engine: InnoDB
        Version: 10
     Row_format: Compact
           Rows: 0
 Avg_row_length: 0
    Data_length: 16384
Max_data_length: 0
   Index_length: 0
      Data_free: 7340032
 Auto_increment: NULL
    Create_time: 2017-10-24 09:34:29
    Update_time: NULL
     Check_time: NULL
      Collation: latin1_swedish_ci
       Checksum: NULL
 Create_options:
        Comment:
1 row in set (0.00 sec)
This database is having only one table named ‘student’.
H-Index in C++

Suppose we have an array of citations (The citations are non-negative integers) of a researcher. We have to define a function to compute the researcher's h-index. According to the definition of h-index: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
So if the input is like citations = [3,0,6,1,7], then the output will be 3, as it indicates that the researcher has five papers, they have got 3, 0, 6, 1, 7 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two paper with no more than 3 citations each, then the h-index is 3.
To solve this, we will follow these steps −
n := size of the array, create one array called bucket of size n + 1
n := size of the array, create one array called bucket of size n + 1
for i in range 0 to n – 1x := c[i]if x >= n, then increase bucket[n] by 1, otherwise increase bucket[x] by 1
for i in range 0 to n – 1
x := c[i]
x := c[i]
if x >= n, then increase bucket[n] by 1, otherwise increase bucket[x] by 1
if x >= n, then increase bucket[n] by 1, otherwise increase bucket[x] by 1
cnt := 0
cnt := 0
for i in range n down to 0 −increase cnt by bucket[i]if cnt >= i, then return i
for i in range n down to 0 −
increase cnt by bucket[i]
increase cnt by bucket[i]
if cnt >= i, then return i
if cnt >= i, then return i
return – 1
return – 1
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int hIndex(vector<int>& c) {
      int n = c.size();
      vector <int> bucket(n + 1);
      for(int i = 0; i < n; i++){
         int x = c[i];
         if(x >= n){
            bucket[n]++;
         } else {
            bucket[x]++;
         }
      }
      int cnt = 0;
      for(int i = n; i >= 0; i--){
         cnt += bucket[i];
         if(cnt >= i)return i;
      }
      return -1;
   }
};
main(){
   Solution ob;
   vector<int> v = {3,0,6,1,7};
   cout << (ob.hIndex(v));
}
[3,0,6,1,7]
3
How to select a column name with spaces in MySQL?

To select a column name with spaces, use the back tick symbol with column name. The symbol is ( ` `). Back tick is displayed in the keyboard below the tilde operator ( ~).
Firstly, create a table −
mysql> CREATE table SpaceColumn
-> (
-> `Student Name` varchar(100)
-> );
Query OK, 0 rows affected (0.48 sec)
Inserting records
mysql> INSERT into SpaceColumn values('John');
Query OK, 1 row affected (0.18 sec)

mysql> INSERT into SpaceColumn values('Bob');
Query OK, 1 row affected (0.17 sec)
The syntax to get column name with space is as follows −
SELECT `column_name` from yourTableName;

Now I will apply the above syntax to get the result for my column. The query is as follows −
mysql> SELECT `Student Name` from SpaceColumn;
The following is the output −
+--------------+
| Student Name |
+--------------+
| John         |
| Bob          |
+--------------+
2 rows in set (0.00 sec)
Start Coding - Java | Practice | GeeksforGeeks

When learning a new language, we first learn to output some message. Here, we'll start with the famous Hello World message. Now, here you are given a function to complete. Don't worry about the ins and outs of functions, just add the command (System.out.print("Hello World")) to print Hello World.
Example:
Input:
No input

Output:
Hello World

Explanation:
Hello World is printed.
User Task:
Your task is to complete the function below to print hello world.
0
nivruttidahake305 days ago
// { Driver Code Starts//Initial Template for Java
// } Driver Code Ends//User function Template for Java
class Geeks{      // Function to print hello   static void printHello(){              // Your code here       System.out.println("Hello World");   }   }
// { Driver Code Starts.
class GfG{      public static void main(String args[]){            //Creating an Object of Class Geeks       Geeks g = new Geeks();              //Calling printHello() function of the Class Geeks       g.printHello();   }   }  // } Driver Code Ends
0
maquickstop1 week ago
class hello{
public void m1(){
System.out.println("Hello World");
}
}
0
vadaliyaravi22 weeks ago
class Geeks{      // Function to print hello   static void printHello(){             System.out.println("Hello World")          }   }
0
roxsonu92 weeks ago
class Geeks{      // Function to print hello   static void printHello(){              System.out.print("Hello World");          }   }
0
priyanshukumar235652 weeks ago
class Geeks{      // Function to print hello   static void printHello(){       System.out.println("Hello World");              // Your code here          }   }
0
shubhamkumar0285s2 weeks ago
class Geeks{      // Function to print hello   static void printHello(){              // Your code here       System.out.println("Hello World");   }   }
0
arpandutta5033 weeks ago
System.out.println(hello world)
0
arpandutta5033 weeks ago
System.out.println(Hello world);
0
ddarshu7713 weeks ago
Darshan K R
System.out.println("Hello World);
0
ashishreddy0333 weeks ago
System.out.println("Hello World");
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
How to set background image in CSS using jQuery?

To set the background image using jQuery, use the jQuery css() method.
Use the background-image property to add background image to the web page.
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $(".bg").css("background-image", "url('/css/images/css.jpg')");
});
</script>
</head>
<body class="bg">
</body>
</html>
Display 3 decimal places in MySQL?

To display 3 digits after decimal, use TRUNCATE(). Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Value DECIMAL(10,5)
);
Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Value) values(109.4567);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable(Value) values(15.9875);
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable(Value) values(1234.2346789);
Query OK, 1 row affected, 1 warning (0.14 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+------------+
| Id | Value      |
+----+------------+
| 1  | 109.45670  |
| 2  | 15.98750   |
| 3  | 1234.23468 |
+----+------------+
3 rows in set (0.00 sec)
Here is the query to display 3 digits after decimal i.e. 3 decimal places −
mysql> select truncate(Value,3) from DemoTable;
This will produce the following output −
+-------------------+
| truncate(Value,3) |
+-------------------+
| 109.456           |
| 15.987            |
| 1234.234          |
+-------------------+
3 rows in set (0.00 sec)
C# Enum GetValues Method

Get the array of the values of the constants in a specified enumeration.
Here is our enum.
enum Rank { Jack = 10, Tom = 19, Tim = 26 };
Now, get all the values of the enum as an array and display using GetValues() method.
foreach(int res in Enum.GetValues(typeof(Rank))) {
   Console.WriteLine(res);
}
Let us see the entire example.
 Live Demo
using System;
public class Demo {
   enum Rank { Jack = 10, Tom = 19, Tim = 26 };
   public static void Main() {
      Console.WriteLine("Here are the university rank of MCA Students College ABC:");
      foreach(int res in Enum.GetValues(typeof(Rank))) {
         Console.WriteLine(res);
      }
   }
}
Here are the university rank of MCA Students College ABC:
10
19
26
Ansible - YAML Basics

Ansible uses YAML syntax for expressing Ansible playbooks. This chapter provides an overview of YAML. Ansible uses YAML because it is very easy for humans to understand, read and write when compared to other data formats like XML and JSON.
Every YAML file optionally starts with “---” and ends with “...”.
In this section, we will learn the different ways in which the YAML data is represented.
YAML uses simple key-value pair to represent the data. The dictionary is represented in key: value pair.
Note − There should be space between : and value.
--- #Optional YAML start syntax 
james: 
   name: james john 
   rollNo: 34 
   div: B 
   sex: male 
... #Optional YAML end syntax 

You can also use abbreviation to represent dictionaries.
James: {name: james john, rollNo: 34, div: B, sex: male}

We can also represent List in YAML. Every element(member) of list should be written in a new line with same indentation starting with “- “ (- and space).
---
countries:  
   - America 
   - China 
   - Canada 
   - Iceland 
...

You can also use abbreviation to represent lists.
Countries: [‘America’, ‘China’, ‘Canada’, ‘Iceland’] 

We can use list inside dictionaries, i.e., value of key is list.
---  
james: 
   name: james john 
   rollNo: 34 
   div: B 
   sex: male 
   likes: 
      - maths 
      - physics 
      - english 
... 

We can also make list of dictionaries.
---  
- james: 
   name: james john 
   rollNo: 34 
      div: B 
   sex: male 
   likes: 
      - maths 
      - physics 
      - english 

- robert: 
      name: robert richardson 
      rollNo: 53 
      div: B 
      sex: male 
   likes: 
      - biology 
      - chemistry 
...  

YAML uses “|” to include newlines while showing multiple lines and “>” to suppress newlines while showing multiple lines. Due to this we can read and edit large lines. In both the cases intendentation will be ignored.
We can also represent Boolean (True/false) values in YAML. where boolean values can be case insensitive.
---  
- james: 
   name: james john 
   rollNo: 34 
   div: B 
   sex: male 
   likes: 
      - maths 
      - physics 
      - english 
   
   result: 
      maths: 87 
      chemistry: 45 
      biology: 56 
      physics: 70 
      english: 80 
   
   passed: TRUE 
   
   messageIncludeNewLines: | 
      Congratulation!! 
      You passed with 79% 
   
   messageExcludeNewLines: > 
      Congratulation!! 
      You passed with 79% 

Service/Server − A process on the machine that provides the service.
Machine − A physical server, vm(virtual machine) or a container.
Target machine − A machine we are about to configure with Ansible.
Task − An action(run this, delete that) etc managed by Ansible.
Playbook − The yml file where Ansible commands are written and yml is executed on a machine.

    41 Lectures 
     5 hours 

 AR Shankar

    11 Lectures 
     58 mins

 Musab Zayadneh

    59 Lectures 
     15.5 hours 

 Narendra P

    11 Lectures 
     1 hours 

 Sagar Mehta

    39 Lectures 
     4 hours 

 Vikas Yadav

    4 Lectures 
     3.5 hours 

 GreyCampus Inc.
 Print
 Add Notes
 Bookmark this page
Where are the python modules stored?

Python Modules are usually stored in /lib/site-packages in your Python folder. If you want to see what directories Python checks when importing modules, you can log the following:
>>> import sys
>>> print sys.path
['', 'C:\\Python27', 'C:\\Python27\\Lib\\site-packages', 'C:\\Python27\\Lib', 'C:\\Python27\\DLLs', 'C:\\Python27\\Lib\\lib-tk', 'C:\\Python27\\Scripts', 'C:\\WINDOWS\\SYSTEM32\\python27.zip', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\site-packages\\win32', 'C:\\Python27\\lib\\site-packages\\win32\\lib', 'C:\\Python27\\lib\\site-packages\\Pythonwin']
You can also list where individual modules being used by a script(say hello.py) reside on the system using the python -v command. For example,
$ python -v hello.py
PS C:\Users\Ayush> echo 'import scrapy' > hello.py
PS C:\Users\Ayush> python -v hello.py
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# C:\Python27\Lib\site.pyc matches C:\Python27\Lib\site.py
import site # precompiled from C:\Python27\Lib\site.pyc
# C:\Python27\Lib\os.pyc matches C:\Python27\Lib\os.py
...
...
Program to find union of two given linked lists in Python

Suppose we have two sorted linked lists L1 and L2, we have to return a new sorted linked list that is the union of the two given lists.
So, if the input is like L1 = [10,20,30,40,50,60,70] L2 = [10,30,50,80,90], then the output will be [10, 20, 30, 40, 50, 60, 70, 80, 90, ]
To solve this, we will follow these steps −
Define a function solve() . This will take L1, L2
if L1 is empty, thenreturn L2
return L2
if L2 is empty, thenreturn L1
return L1
if value of L1 < value of L2, thenres := L1next of res := solve(next of L1, L2)
res := L1
next of res := solve(next of L1, L2)
otherwise when value of L2 < value of L1, thenres := L2next of res := solve(next of L2, L1)
res := L2
next of res := solve(next of L2, L1)
otherwise,res := L1next of res := solve(next of L1, next of L2)
res := L1
next of res := solve(next of L1, next of L2)
return res
Let us see the following implementation to get better understanding −
 Live Demo
class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
      ptr.next = ListNode(element)
   return head
def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
   print(']')
class Solution:
   def solve(self, L1, L2):
      if not L1:
         return L2
      if not L2:
         return L1
      if L1.val < L2.val:
         res = L1
         res.next = self.solve(L1.next, L2)
      elif L2.val < L1.val:
         res = L2
         res.next = self.solve(L2.next, L1)
      else:
         res = L1
         res.next = self.solve(L1.next, L2.next)
   return res
ob = Solution()
L1 = make_list([10,20,30,40,50,60,70])
L2 = make_list([10,30,50,80,90])
print_list(ob.solve(L1, L2))
[10,20,30,40,50,60,70], [10,30,50,80,90]
[10, 20, 30, 40, 50, 60, 70, 80, 90, ]
JavaScript SyntaxError – Identifier starts immediately after numeric literal

23 Jul, 2020
This JavaScript exception identifier starts immediately after numeric literal occurs if an identifier starts with a number.
Message:
SyntaxError: Unexpected identifier after numeric literal 
             (Edge)
SyntaxError: identifier starts immediately after numeric 
             literal (Firefox)
SyntaxError: Unexpected number (Chrome)

Error Type:
SyntaxError

Cause of Error: Any JavaScript identifier should start with a letter, underscore (_), or a dollar sign ($). If they start with a digit(0-9), it will cause an error.
Example 1: In this example, there is a valid identifier, So the error has not occurred.
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>        // valid identifier        var GFG = 'This is GeeksforGeeks';         document.write(GFG)    </script></body></html>
Output:
This is GeeksforGeeks

Example 2: In this example, there is an identifier starting with a digit(1), So the error has occurred.
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>      // Invalid identifier      var 1GFG = 'This is GeeksForGeeks';       document.write(1GFG)    </script></body></html>
Output(in console): 
SyntaxError: Invalid or unexpected token

JavaScript-Errors
JavaScript
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Remove elements from a JavaScript Array
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Python | Numpy matrix.argsort()

10 Apr, 2019
With the help of Numpy matrix.argmax() method, we are able to find the sort the elements in the given matrix having one or more dimension and it would return the index value of sorted elements.
Syntax : matrix.argsort()
Return : Return index number of sorted elements in matrix
Example #1 :In this example we can see that with the help of matrix.argsort() method, we are able to find the sorted element in a given matrix and gives output as index of sorted array.
# import the important module in pythonimport numpy as np           # make a matrix with numpygfg = np.matrix('[1, -2, 3, -4]')           # applying matrix.argsort() methodgeeks = gfg.argsort()     print(geeks)
[[3 1 0 2]]

Example #2 :
# import the important module in pythonimport numpy as np           # make a matrix with numpygfg = np.matrix('[-1, 2, 3; 4, -5, 6; 7, -8, 9]')           # applying matrix.argsort() methodgeeks = gfg.argsort()     print(geeks)
[[0 1 2]
 [1 0 2]
 [1 0 2]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
PostgreSQL – Random Number Generation

28 Aug, 2020
PostgreSQL provides the random() function that returns a random number between 0 and 1. In this article, we will look into the process of developing a user-defined function for generating random numbers within a range.
Syntax:SELECT random();


If you try the above syntax it will lead to the following:
To generate a random number between 1 and 10, you use the following statement:
SELECT random() * 10 + 1 AS RAND_1_10;


If you try the above syntax it will lead to the following:
If you want to generate the random number as an integer, you apply the floor() function to the expression as follows:
SELECT floor(random() * 10 + 1)::int;


The above query results in the following:
Generally, to generate a random number between two integers l and h, you use the following statement:
SELECT floor(random() * (h-l+1) + l)::int;


To create a user-generated function that returns a random number between two numbers l and h:
CREATE OR REPLACE FUNCTION random_between(low INT ,high INT) 
   RETURNS INT AS
$$
BEGIN
   RETURN floor(random()* (high-low + 1) + low);
END;
$$ language 'plpgsql' STRICT;


The following statement calls the random_between() function and returns a random number between 1 and 100:
SELECT random_between(1,100);


Output:
If you want to get multiple random numbers between two integers, you use the following statement:
SELECT random_between(1,100)
FROM generate_series(1,5);


Output:
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - INSERT
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - EXISTS Operator
PostgreSQL - LEFT JOIN
PostgreSQL - SELECT
Scala Char isUpper() method with example

03 Nov, 2019
The isUpper() method is utilized to check if the stated character value is in uppercase or not.
Method Definition: def isUpper: Boolean
Return Type: It returns true if the stated character is in uppercase else it returns false.
Example: 1#
// Scala program of isUpper()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying isUpper() method         val result = ('A').isUpper                  // Displays output        println(result)              }} 
true

Example: 2#
// Scala program of isUpper()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying isUpper() method        val result = ('a').isUpper                  // Displays output        println(result)          }} 
false

Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala String substring() method with example
Scala Constructors
Scala | Arrays
Enumeration in Scala
Inheritance in Scala
Python | numpy.cov() function

08 Oct, 2021
Covariance provides the a measure of strength of correlation between two variable or more set of variables. The covariance matrix element Cij is the covariance of xi and xj. The element Cii is the variance of xi. 
If COV(xi, xj) = 0 then variables are uncorrelated
If COV(xi, xj) > 0 then variables positively correlated
If COV(xi, xj) > < 0 then variables negatively correlated
Syntax: numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)Parameters: m : [array_like] A 1D or 2D variables. variables are columns y : [array_like] It has the same form as that of m. rowvar : [bool, optional] If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: bias : Default normalization is False. If bias is True it normalize the data points. ddof : If not None the default value implied by bias is overridden. Note that ddof=1 will return the unbiased estimate, even if both fweights and aweights are specified. fweights : fweight is 1-D array of integer frequency weights aweights : aweight is 1-D array of observation vector weights.Returns: It returns ndarray covariance matrix  
Example #1: 
Python3
# Python code to demonstrate the# use of numpy.covimport numpy as np x = np.array([[0, 3, 4], [1, 2, 4], [3, 4, 5]]) print("Shape of array:\n", np.shape(x)) print("Covariance matrix of x:\n", np.cov(x))
Output: 
Shape of array:
 (3, 3)
Covariance matrix of x:
 [[ 4.33333333  2.83333333  2.        ]
 [ 2.83333333  2.33333333  1.5       ]
 [ 2.          1.5         1.        ]]
Example #2: 
Python3
# Python code to demonstrate the# use of numpy.covimport numpy as np x = [1.23, 2.12, 3.34, 4.5] y = [2.56, 2.89, 3.76, 3.95] # find out covariance with respect  columnscov_mat = np.stack((x, y), axis = 0) print(np.cov(cov_mat))
[[ 2.03629167  0.9313    ]
 [ 0.9313      0.4498    ]]
 
Example #3: 
Python3
# Python code to demonstrate the# use of numpy.covimport numpy as np x = [1.23, 2.12, 3.34, 4.5] y = [2.56, 2.89, 3.76, 3.95] # find out covariance with respect  rowscov_mat = np.stack((x, y), axis = 1) print("shape of matrix x and y:", np.shape(cov_mat)) print("shape of covariance matrix:", np.shape(np.cov(cov_mat))) print(np.cov(cov_mat))
shape of matrix x and y: (4, 2)
shape of covariance matrix: (4, 4)
[[ 0.88445  0.51205  0.2793  -0.36575]
 [ 0.51205  0.29645  0.1617  -0.21175]
 [ 0.2793   0.1617   0.0882  -0.1155 ]
 [-0.36575 -0.21175 -0.1155   0.15125]]
 
adnanirshad158
abhishek0719kadiyan
Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to sort Palindrome Words in a Sentence

01 Apr, 2021
Given a string S representing a sentence, the task is to reorder all the palindromic words present in the sentence in sorted order.
Examples:
Input: S = “Please refer to the madam to know the level”Output: Please level to the madam to know the referExplanation: Here “refer”, “madam”, “level” are the palindromic words. Sorting them generates the sequence {“level”, “madam”, “refer”}.
Input: S = “refer to dad”Output: dad to refer
Approach: Follow the steps below to solve the problem:
Iterate over the characters of the string.
Split the words in the sentence by spaces using split() and store it as a list, say lis.
Store all the palindromic words present in the sentence S in a list, say newlis[].
Sort the list newlis[] using sort() function.
Initialize a pointer, say j = 0.
Traverse the list lis and replace all the palindromic words with newlis[j] and increment j by 1.
Print the updated sentence
Below is the implementation of the above approach:
Python3
# Python implementation of above program  # Function to check if a# string is a palindrome or notdef palindrome(string):    if(string == string[::-1]):        return True    else:        return False  # Function to print the updated sentencedef printSortedPalindromes(sentence):        # Stores palindromic words    newlist = []          # Stores the words split by spaces    lis = list(sentence.split())          # Traversing the list    for i in lis:                # If current word is palindrome        if(palindrome(i)):                        # Update newlist            newlist.append(i)      # Sort the words in newlist    newlist.sort()      # Pointer to iterate newlis    j = 0          # Traverse the list    for i in range(len(lis)):                # If current word is palindrome        if(palindrome(lis[i])):                        # Replacing word with            # current word in newlist            lis[i] = newlist[j]                          # Increment j by 1            j = j + 1      # Print the updated sentence    for i in lis:        print(i, end =" ")    # Driver Code  sentence = "please refer to the madam to know the level"  printSortedPalindromes(sentence)
please level to the madam to know the refer

Time Complexity : O(N * logN)Auxiliary Space : O(N)
palindrome
Python list-programs
Python Programs
Sorting
Strings
Strings
Sorting
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python program to check whether a number is Prime or not
Python program to add two numbers
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
HTTP Non-Persistent & Persistent Connection | Set 1

09 Nov, 2021
The Hypertext Transfer Protocol (HTTP) is an application-level protocol that uses TCP as an underlying transport and typically runs on port 80. HTTP is a stateless protocol i.e. server maintains no information about past client requests.
HTTP Connections
Non-PersistentPersistent
Non-Persistent
Persistent
Before starting with persistent and non-persistent HTTP connection lets know what is RTT.
RTT-> Time for a small packet to travel from client to server and back.
RTT= 2*propagation time
1. For a connection Persistent or Non-persistent it is sure that to initiate TCP connection one RTT is used.2. One RTT is used for HTTP request and first few bytes to HTTP response to return.
So in order to know total file transmission time->
 total = 2RTT+transmit time
Difference between Persistent & Non-Persistent connection.
Non-Persistent Connection
Without parallel connectionWith parallel connection
Without parallel connection
With parallel connection
Without parallel connection Non-PersistentEach objection takes two RTT (assuming no window limit) one for TCP connection and other for HTTP image/text file.
With parallel connection Non-Persistent
Persistent connection
Non-PipelinedPipelined
Non-Pipelined
Pipelined
In Non-pipeline connection we first establish connection which takes two RTT then we send all the objects images/text files which takes 1 RTT each (TCP for each object is not required).
In Pipelined connection 2RTT for connection establishment and then 1RTT(assuming no window limit) for all the objects i.e. images/text.
Advantages of persistent connections :1) Lower CPU and memory usage because there are less number of connections.2) Allows HTTP pipelining of requests and responses.3) Reduced network congestion (fewer TCP connections).4) Reduced latency in subsequent requests (no handshaking).5) Errors can be reported without the penalty of closing the TCP connection.
Disadvantages of persistent connections :Resources may be kept occupied even when not needed and may not be available to others.
Most of the modern browsers like Chrome, Firefox and Internet Explorer use persistent connections.
Reference : https://en.wikipedia.org/wiki/HTTP_persistent_connection
This article is contributed by SHAURYA UPPAL. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
23603vaibhav2021
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Socket Programming in Python
GSM in Wireless Communication
Differences between IPv4 and IPv6
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
UDP Server-Client implementation in C
Caesar Cipher in Cryptography
Advanced Encryption Standard (AES)
Read contents of a CSV File in R Programming – read.csv() Function

19 Jun, 2020
read.csv() function in R Language is used to read “comma separated value” files. It imports data in the form of a data frame.
Syntax:read.csv(file, header, sep, dec)
Parameters:file: the path to the file containing the data to be imported into R.header: logical value. If TRUE, read.csv() assumes that your file has a header row, so row 1 is the name of each column. If that’s not the case, you can add the argument header = FALSE.sep: the field separator characterdec: the character used in the file for decimal points.
Example 1: Reading file from same folder
# R program to read a csv file  # Get content into a data frame data <- read.csv("CSVFileExample.csv",                    header = FALSE, sep = "\t")     # Printing content of Text File print(data) 
Output:
   V1 V2 V3
1 100 AB ab
2 200 CD cd
3 300 EF ef
4 400 GH gh
5 500 IJ ij

Example 2: Reading file from different directory
# Simple R program to read csv file x <- read.csv("D://Datas//myfile.csv")     # print x print(x) 
Output:
  X  V1 V2 V3
1 1 100 a1 b1
2 2 200 a2 b2
3 3 300 a3 b3

R-FileHandling
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Logistic Regression in R Programming
std::minus in C++

27 Jul, 2017
Binary function object class whose call returns the result of subtracting its second argument from its first argument (as returned by the binary operator -).
Syntax :
template  struct minus : binary_function  
{
  T operator() (const T& x, const T& y) const {return x-y;}
};

Template parameters :
T - Type of the arguments and return type of the functional call.
    The type shall support the operation (binary operator-).

Member types :
x : Type of the first argument in member operator()
y : Type of the second argument in member operator()
result_type : Type returned by member operator()

// C++ program to illustrate std::minus// by subtracting all array elements from a number#include <bits/stdc++.h>  int main(){    // Array with elements to be subtracted    int arr[] = { 10, 20, 30 };      // size of array    int size = sizeof(arr) / sizeof(arr[0]);      // Variable from which array is to be subtracted    int num = 100;      // Variable to store result    int result;      // using std::accumulate to perform subtraction on array from num    // using std::minus    result = std::accumulate(arr, arr + size, num, std::minus<int>());      // Printing the result    std::cout << "The result of 100-10-20-30 is " << result;      return 0;}
Output:
The result of 100-10-20-30 is 40
Another Example:
// C++ program to illustrate std::minus// by subtracting the respective elements of 2 arrays#include <iostream> // std::cout#include <functional> // std::plus#include <algorithm> // std::transform  int main(){    // First array    int first[] = { 100, 200, 300, 400, 500 };      // Second array    int second[] = { 10, 20, 30, 40, 50 };      // Result array    int results[5];      // std::transform applies std::minus to the whole array    std::transform(first, first + 5, second, results, std::minus<int>());      // Printing the result array    for (int i = 0; i < 5; i++)        std::cout << results[i] << " ";      return 0;}
Output:
90 180 270 360 450

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert Int to Bytes in Python?

23 Dec, 2020
An int object can be used to represent the same value in the format of the byte. The integer represents a byte, is stored as an array with its most significant digit (MSB) stored at either the start or end of the array. 
Method 1: int.tobytes()
An int value can be converted into bytes by using the method int.to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.
Syntax: int.to_bytes(length, byteorder)
Arguments : 
length – desired length of the array in bytes .
byteorder – order of the array to carry out conversion of an int to bytes. byteorder can have values as either “little” where most significant bit is stored at the end and least at the beginning, or big, where MSB is stored at start and LSB at the end. 
Exceptions : 
OverflowError is returned in case the integer value length is not large enough to be accommodated in the length of the array. 
The following programs illustrate the usage of this method in Python : 
Python3
# declaring an integer valueinteger_val = 5  # converting int to bytes with length # of the array as 2 and byter order as bigbytes_val = integer_val.to_bytes(2, 'big')  # printing integer in byte representationprint(bytes_val)
b'\x00\x05'
Python3
# declaring an integer valueinteger_val = 10  # converting int to bytes with length # of the array as 5 and byter order as # littlebytes_val = integer_val.to_bytes(5, 'little')  # printing integer in byte representationprint(bytes_val)
b'\n\x00\x00\x00\x00'
Method 2: Converting integer to string and string to bytes 
This approach works is compatible in both Python versions, 2 and 3. This method doesn’t take the length of the array and byteorder as arguments. 
An integer value represented in decimal format can be converted to string first using the str() function , which takes as argument the integer value to be converted to the corresponding string equivalent.
This string equivalent is then converted to a sequence of bytes by choosing the desired representation for each character, that is encoding the string value. This is done by the str.encode() method.
Python3
# declaring an integer valueint_val = 5  # converting to stringstr_val = str(int_val)  # converting string to bytesbyte_val = str_val.encode()print(byte_val)
b'5'
python-basics
Python
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 ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
Python Pytorch full() method

22 Apr, 2020
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes.
The function torch.full() returns a tensor of size size filled with fill_value.
Syntax: torch.ones(size, fill_value, out=None)
Parameters:size: a sequence of integers defining the shape of the output tensorfill_value: the number to fill the output tensor with.out (Tensor, optional): the output tensor
Return type: A tensor
Code #1:
# Importing the PyTorch libraryimport torch    # Applying the full function and# storing the resulting tensor in 'a'a = torch.full([3, 4], 3)print("a = ", a)  b = torch.full([2, 5], 3.5)print("b = ", b)
Output:
a =  tensor([[3., 3., 3., 3.],
        [3., 3., 3., 3.],
        [3., 3., 3., 3.]])
b =  tensor([[3.5000, 3.5000, 3.5000, 3.5000, 3.5000],
        [3.5000, 3.5000, 3.5000, 3.5000, 3.5000]])


 
Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
SQL | Except Clause

06 Sep, 2018
In SQL, EXCEPT returns those tuples that are returned by the first SELECT operation, and not returned by the second SELECT operation.
This is the same as using a subtract operator in relational algebra.
Example:Say we have two relations, Students and TA (Teaching Assistant). We want to return all those students who are not teaching assistants. The query can be formulated as:
Students Table:
TA Table:
SELECT Name
       FROM Students
EXCEPT
SELECT NAME
       FROM TA;

Output:
Rohan
Mansi
Megha

To retain duplicates, we must explicitly write EXCEPTALL instead of EXCEPT.
SELECT Name
       FROM Students
EXCEPTALL
SELECT Name
       FROM TA;

Output:
Rohan
Mansi
Mansi
Megha

Difference between EXCEPT and NOT IN ClauseEXCEPT automatically removes all duplicates in the final result, whereas NOT IN retains duplicate tuples. It is also important to note that EXCEPT is not supported by MySQL.
This article is contributed by Anannya Uberoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
lonewolf_ab
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Views
CTE in SQL
Difference between DELETE, DROP and TRUNCATE
SQL using Python
SQL | DDL, DML, TCL and DCL
SQL | TRANSACTIONS
SQL | Sub queries in From Clause
Difference between Where and Having Clause in SQL
SQL Trigger | Student Database
Difference between DDL and DML in DBMS
Score After Flipping Matrix in C++

Suppose we have a two dimensional matrix A where each value is 0 or 1. Here a move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s. Now after making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. So our task is to find the highest possible score. If the input is like −
The output will be 39 as after toggling, the matrix will be −
So the numbers are 15 + 9 + 15 = 39
To solve this, we will follow these steps −
n := row count and m := column count
n := row count and m := column count
ret := n x (2^(m – 1))
ret := n x (2^(m – 1))
for j in range 1 to m – 1cnt : = 0for i in range 0 to n – 1cnt := cnt + A[i, j] = A[i, 0]temp := 2^(m – j – 1) * maximum of cnt and n – cntret := ret + temp
for j in range 1 to m – 1
cnt : = 0
cnt : = 0
for i in range 0 to n – 1cnt := cnt + A[i, j] = A[i, 0]
for i in range 0 to n – 1
cnt := cnt + A[i, j] = A[i, 0]
cnt := cnt + A[i, j] = A[i, 0]
temp := 2^(m – j – 1) * maximum of cnt and n – cnt
temp := 2^(m – j – 1) * maximum of cnt and n – cnt
ret := ret + temp
ret := ret + temp
return ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int matrixScore(vector<vector<int>>& A) {
      int n = A.size();
      int m = A[0].size();
      int ret = (1 << (m - 1)) * n;
      for(int j = 1; j < m; j++){
         int cnt = 0;
         for(int i = 0; i < n; i++){
            cnt += (A[i][j] == A[i][0]);
         }
         int temp = ((1 << (m - (j + 1))) * max(cnt, n - cnt));
         ret += temp;
      }
      return ret;
   }
};
main(){
   vector<vector<int>> v = {{0,0,1,1},{1,0,1,0},{1,1,0,0}};
   Solution ob;
   cout << (ob.matrixScore(v));
}
[[0,0,1,1],[1,0,1,0],[1,1,0,0]]
39
Python Pandas - Draw a boxplot for each numeric variable in a DataFrame with Seaborn

Box Plot in Seaborn is used to draw a box plot to show distributions with respect to categories. The seaborn.boxplot() is used for this. Use the "orient” parameter for orientation of each numeric variable.
Let’s say the following is our dataset in the form of a CSV file − Cricketers.csv
At first, import the required libraries −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt
Load data from a CSV file into a Pandas DataFrame −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv")
Plotting box plot using the orient parameter for orientation of each numeric variable −
sb.boxplot( data = dataFrame, orient="h")
Following is the code −
import seaborn as sb
import pandas as pd
import matplotlib.pyplot as plt

# Load data from a CSV file into a Pandas DataFrame:
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\Cricketers.csv")

# plotting box plot
# using the orient parameter for orientation of each numeric variable
sb.boxplot( data = dataFrame, orient="h")

# display
plt.show()
This will produce the following output −
C# program to remove a range of characters by index using StringBuilder

Use the Remove() method to remove a range of characters by index.
Let’s say you need to remove the last 5 characters from the following string −
StringBuilder myStr = new StringBuilder("Framework");
For that, set the Remove() method as −
str.Remove(3, 4);
The following is the complete code −
 Live Demo
using System;
using System.Text;

public class Program {
   public static void Main() {
      StringBuilder myStr = new StringBuilder("Framework");
      Console.WriteLine("Initial String: " + myStr);

      // removing four characters
      Console.Write("New string: ");
      myStr.Remove(5, 4);
      Console.WriteLine(myStr);
   }
}
Initial String: Framework
New string: Frame
Python | sympy.init_printing() method - GeeksforGeeks

18 Jun, 2019
With the help of sympy.init_printing() method, we are able to print the unicode characters for mathematical expressions.
Syntax : sympy.init_printing()Return : Return the beautiful printing using unicode char.
Example #1 :In this example we can see that by using sympy.init_printing() method, we are able to print the unicode characters.
# Import sympyfrom sympy import * init_printing()  # Define symbols and trigo expressionx, y = symbols('x y')gfg = Integral(sqrt(1 / x), x)  print(gfg)
Output :
Example #2 :
# Import sympyfrom sympy import * init_printing()  # Define symbols and trigo expressionx, y = symbols('x y')gfg = sqrt(1 / x)  print(gfg)
Output :
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python
Stack in Python
Bar Plot in Matplotlib