code-rag-bench/online-tutorials huggingface dataset:
How can I source a Python file from another Python file?

In order to source a Python file from another python file, you have to use it like a module. import the file you want to run and run its functions. For example, say you want to import fileB.py into fileA.py, assuming the files are in the same directory, inside fileA you'd write
import fileB
Now in fileA, you can call any function inside fileB like:
fileB.my_func()
In file B you have to define a function called my_func before you can use it in any other file.
def my_func():
    print("Hello from B")
Now when you run fileA.py, you will get the output:
Hello from B
Python - Convert String Truth values to Boolean - GeeksforGeeks

02 Sep, 2020
Given a String List, convert the String Truth values to Boolean values.
Input : test_list = [“True”, “False”, “True”, “False”]Output : [True, False, True, False]Explanation : String booleans converted to actual Boolean.
Input : test_list = [“True”]Output : [True]Explanation : String boolean converted to actual Boolean.
Method #1 : Using list comprehension
In this, we check for just the True value, rest values are automatically converted to False boolean.
Python3
# Python3 code to demonstrate working of # Convert String Truth values to Boolean# Using list comprehension  # initializing liststest_list = ["True", "False", "True", "True", "False"]  # printing stringprint("The original list : " + str(test_list))  # using list comprehension to check "True" stringres = [ele == "True" for ele in test_list]  # printing results print("The converted Boolean values : " + str(res))
The original list : ['True', 'False', 'True', 'True', 'False']
The converted Boolean values : [True, False, True, True, False]

Method #2 : Using map() + lambda
In this, we apply same approach, just the different way to solve the problem. The map() is used to extend logic of values computed by lambda function.
Python3
# Python3 code to demonstrate working of # Convert String Truth values to Boolean# Using map() + lambda  # initializing liststest_list = ["True", "False", "True", "True", "False"]  # printing stringprint("The original list : " + str(test_list))  # using map() to extend and lambda to check "True" stringres = list(map(lambda ele: ele == "True", test_list))  # printing results print("The converted Boolean values : " + str(res))
The original list : ['True', 'False', 'True', 'True', 'False']
The converted Boolean values : [True, False, True, True, False]

Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to generate XML from Python dictionary?

To generate XML from a python dictionary, you need to install the dicttoxml package. You can install it using:
$ pip install dicttoxml
Once installed, you can use the dicttoxml method to create the xml. 
a = {
   'foo': 45,
   'bar': {
      'baz': "Hello"
   }
}
xml = dicttoxml.dicttoxml(a)
print(xml)
This will give the output:
b'<?xml version="1.0" encoding="UTF-8" ?><root><foo type="int">45</foo><bar type="dict"><baz type="str">Hello</baz></bar></root>'
You can also prettyprint this output using the toprettyxml method. 
from xml.dom.minidom import parseString
a = {
   'foo': 45,
   'bar': {
      'baz': "Hello"
   }
}
xml = dicttoxml.dicttoxml(a)
dom = parseString(xml)
print(dom.toprettyxml())
This will give the output −
<?xml version = "1.0" ?>
<root>
   <foo type = "int">45</foo>
   <bar type = "dict">
      <baz type="str">Hello</baz>
   </bar>
</root>
Universal Selector in CSS

The CSS * selector is a universal selector which is used to select all elements of the HTML DOM.
The syntax for CSS universal selector is as follows −
* {
   /*declarations*/
}
The following examples illustrate CSS universal selector −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
* {
   margin: 15px;
   padding: 5px;
   border: 2px solid black;
   box-shadow: inset 30px 0 8px lightblue;
}
</style>
</head>
<body>
<table>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
* {
   margin: 15px;
   padding: 5px;
   width: 200px;
   border: 2px solid black;
}
html::before {
   content: "one";
}
</style>
</head>
<body>
two
<div>three
<div>four
<div>five</div>
</div>
</div>
</body>
</html>
Difference between Iterator and Enumeration in Java

Iterator and Enumeration both are the cursors to traverse and access an element from the collection. They both belong to the collection framework. Enumeration was added in JDK1.0 and Iterator in the JDK.1.2 version in the collection framework. 
Enumeration can’t make structural changes in the collection because it has read-only access to the element in the collection. It has the following methods :
*hasMoreElements()
*nextElement()
On the other hand, an iterator can read and remove the element in the collection. It has the following methods −
*hasNext()
*next()
*remove()
class EnumerationExample {
   public static void main(String args[]) {
      List list = new ArrayList(Arrays.asList( new String[] {"Apple", "Cat", "Dog", "Rat"}));
      Vector v = new Vector(list);
      delete(v, "Dog");
   }
   private static void delete(Vector v, String name) {
      Enumeration e = v.elements();
      while (e.hasMoreElements()) {
         String s = (String) e.nextElement();
         if (s.equals(name)) {
            v.remove(name);
         }
      }
      // Display the names
      System.out.println("The names are:");
      e = v.elements();
      while (e.hasMoreElements()) {
         // Prints elements
         System.out.println(e.nextElement());
      }
   }
}
class IteratorExample {
   public static void main(String args[]) {
      List list = new ArrayList(Arrays.asList( new String[] {"Apple", "Cat", "Dog", "Rat"}));
      Vector v = new Vector(list);
      delete(v, "Dog");
   }
   private static void delete(Vector v, String name) {
      Iterator i = v.iterator();
      while (i.hasNext()) {
         String s = (String) i.next();
         if (s.equals(name)) {
            i.remove();
         }
      }
      // Display the names
      System.out.println("The names are:");
      i = v.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}
Common Subexpression Elimination - Code optimization Technique in Compiler Design - GeeksforGeeks

03 Dec, 2021
Code Optimization Technique is an approach to enhance the performance of the code by either eliminating or rearranging the code lines. Code Optimization techniques are as follows:
 Compile-time evaluation Common Sub-expression elimination Dead code elimination Code movement Strength reduction
 Compile-time evaluation
 Common Sub-expression elimination
 Dead code elimination
 Code movement
 Strength reduction
The expression or sub-expression that has been appeared and computed before and appears again during the computation of the code is the common sub-expression. Elimination of that sub-expression is known as Common sub-expression elimination.
The advantage of this elimination method is to make the computation faster and better by avoiding the re-computation of the expression. In addition, it utilizes memory efficiently.
The two types of elimination methods in common sub-expression elimination are:
1. Local Common Sub-expression elimination– It is used within a single basic block. Where a basic block is a simple code sequence that has no branches.
2. Global Common Sub-expression elimination– It is used for an entire procedure of common sub-expression elimination.
Example 1:
Before elimination –
a = 10;
b = a + 1 * 2;
c = a + 1 * 2;  
//’c’ has common expression as ‘b’
d = c + a;
After elimination –
a = 10;
b = a + 1 * 2;
d = b + a;
Let’s understand Example 1 with a diagram:
fig.: Example 1
As shown in the figure (fig.: Example 1), the result of ‘d’ would be similar with both expressions. So, we will eliminate one of the common subexpressions, as it helps in faster execution and efficient memory utilization.
Example 2:
Before elimination –
x = 11;
y = 11 * 24;  
z = x * 24;
//'z' has common expression as 'y' as 'x' can be evaluated directly as done in 'y'.
After elimination –
y = 11 * 24;
Picked
Computer Subject
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Transmission Control Protocol (TCP)?
Backpatching in Compiler Design
6 Best Books to Learn Computer Networking
Difference Between User Mode and Kernel Mode
Token, Patterns, and Lexems
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Replace part of a string with another string in C++

Here we will see how to replace a part of a string by another string in C++. In C++ the replacing is very easy. There is a function called string.replace(). This replace function replaces only the first occurrence of the match. To do it for all we have used loop. This replace function takes the index from where it will replace, it takes the length of the string, and the string which will be placed in the place of matched string.
Input: A string "Hello...Here all Hello will be replaced", and another string to replace "ABCDE"
Output: "ABCDE...Here all ABCDE will be replaced"
Step 1: Get the main string, and the string which will be replaced. And the match string
Step 2: While the match string is present in the main string:
Step 2.1: Replace it with the given string.
Step 3: Return the modified string
 Live Demo
#include<iostream>
using namespace std;
main() {
   int index;
   string my_str = "Hello...Here all Hello will be replaced";
   string sub_str = "ABCDE";
   cout << "Initial String :" << my_str << endl;
   //replace all Hello with welcome
   while((index = my_str.find("Hello")) != string::npos) {    //for each location where Hello is found
      my_str.replace(index, sub_str.length(), sub_str); //remove and replace from that position
   }
   cout << "Final String :" << my_str;
}
Initial String :Hello...Here all Hello will be replaced
Final String :ABCDE...Here all ABCDE will be replaced
Find Sum, Mean and Product of a Vector in R - GeeksforGeeks

26 Mar, 2021

sum(), mean(), and prod() methods are available in R which are used to compute the specified operation over the arguments specified in the method. In case, a single vector is specified, then the operation is performed over individual elements, which is equivalent to the application of for loop. 
mean() function is used to calculate mean
Syntax: mean(x, na.rm)
Parameters:
x: Numeric Vector
na.rm: Boolean value to ignore NA value
sum() is used to calculate sum
Syntax: sum(x)
Parameters:
x: Numeric Vector
prod() is used to calculate product
Syntax: prod(x)
Parameters:
x: Numeric Vector
Given below are examples to help you understand better.
Example 1:
R
 

 
 










vec = c(1, 2, 3 , 4) 
print("Sum of the vector:") 
  
# inbuilt sum method  
print(sum(vec)) 
  
# using inbuilt mean method 
print("Mean of the vector:") 
print(mean(vec))   
  
# using inbuilt product method 
print("Product of the vector:") 
print(prod(vec))






Output
[1] “Sum of the vector:”
[1] 10
[1] “Mean of the vector:”
[1] 2.5
[1] “Product of the vector:”
[1] 24
Example 2:
R
 

 
 










vec = c(1.1, 2, 3.0 ) 
print("Sum of the vector:") 
  
# inbuilt sum method  
print(sum(vec)) 
  
# using inbuilt mean method 
print("Mean of the vector:") 
print(mean(vec))   
  
# using inbuilt product method 
print("Product of the vector:") 
print(prod(vec))






Output
[1] “Sum of the vector:”
[1] 6.1
[1] “Mean of the vector:”
[1] 2.033333
[1] “Product of the vector:”
[1] 6.6
Example 3 : Vector with NaN values 
R
 

 
 










# declaring a vector 
vec = c(1.1,NA, 2, 3.0,NA ) 
print("Sum of the vector:") 
  
# inbuilt sum method  
print(sum(vec)) 
  
# using inbuilt mean method 
print("Mean of the vector with NaN values:") 
  
# not ignoring NaN values 
print(mean(vec))   
  
# ignoring missing values 
print("Mean of the vector without NaN values:") 
print(mean(vec,na.rm = TRUE))   
  
# using inbuilt product method 
print("Product of the vector:") 
print(prod(vec))






Output
[1] “Sum of the vector:”
[1] NA
[1] “Mean of the vector with NaN values:”
[1] NA
[1] “Mean of the vector without NaN values:”
[1] 2.033333
[1] “Product of the vector:”
[1] NA

Picked


R Vector-Programs


R-Vectors


R Language


R Programs

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
How to change Row Names of DataFrame in R ?
How to Split Column Into Multiple Columns in R DataFrame?
Remove rows with NA in one column of R DataFrame
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to run PowerShell commands from the command prompt?

To run Powershell commands from the command prompt or cmd, we need to call the PowerShell process PowerShell.exe.
See the sample example,
C:\> Powershell.exe -Command "Write-Output 'Hello world'"
Hello world
Similarly, you can call any command. We will use another example to get service information
C:\> Powershell.exe -Command "Get-Service Spooler"
Status   Name    DisplayName
------   ----    -----------
Running  Spooler Print Spooler
To run multiple commands,
C:\> Powershell.exe -Command "Stop-Service Spooler -verbose -passthru;
Start-Service
Spooler -verbose -passthru"
VERBOSE: Performing the operation "Stop-Service" on target "Print Spooler (Spooler)".
Status Name DisplayName
------ ---- -----------
Stopped Spooler Print Spooler
VERBOSE: Performing the operation "Start-Service" on target "Print Spooler (Spooler)".
Running Spooler Print Spooler
The above command is similar to,
C:\> Powershell.exe Invoke-Command -scriptblock {
   "Stop-Service Spooler -verbose - passthru;
   Start-Service Spooler -verbose -passthru"
}
MySQL | BINARY Function

21 Nov, 2019
The MySQL BINARY function is used for converting a value to a binary string. The BINARY function can also be implemented using CAST function as CAST(value AS BINARY).The BINARY function accepts one parameter which is the value to be converted and returns a binary string.
Syntax:
BINARY value
Parameters Used:
value – It is used to specify the value to be converted.
Return Value:The MySQL BINARY function returns a binary string after converting a value specified by the user.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
MySQL 4.0
MySQL 3.23
Example-1: Implementing BINARY function to return a binary string.
SELECT BINARY('Geeksforgeeks');  
Output:
Geeksforgeeks 
Example-2: Character-by-character comparison of two string without using BINARY function.
SELECT 'GEEKSFORGEEKS' = 'geeksforgeeks'; 
Output:
1 
Example-3: Byte-by-Byte comparison of two string using BINARY function.
SELECT BINARY 'GEEKSFORGEEKS' = 'geeksforgeeks'; 
Output:
0 
Example-4: Byte-by-Byte comparison of two string using BINARY function.
SELECT BINARY 'GEEKSFORGEEKS' = 'GEEKSFORGEEKS'; 
Output:
1 
mysql
SQLmysql
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 Trigger | Student Database
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Window functions in SQL
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
Grouped Boxplots in Python with Seaborn

26 Nov, 2020
Boxplot depicts the distribution of quantitative data facilitating comparisons between different variables, continuous or categorical. It is a common data dispersion measure. Boxplots consist of a five-number summary which helps in detecting and removing outliers from the dataset.
Minimum observationQ1 (25% or Quartile 1)Median or Q2Q3 (75% or Quartile 2)Maximum Observation
Minimum observation
Q1 (25% or Quartile 1)
Median or Q2
Q3 (75% or Quartile 2)
Maximum Observation
Grouped Boxplots are used to visualize the data having multiple subgroups. Also, we can visualize three variables at a time with grouped boxplot where one variable is numerical and the other two are categorical variables. 
We will be using the Seaborn library of Python to create Grouped Boxplots. We will use dataset ‘tips’ from the Seaborn library.
Python3
# import seaborn libraryimport seaborn as sns  # load the datasetdata = sns.load_dataset('tips')  # view the datasetprint(data.head(5))
Output:
Example 1: Let us create a boxplot to know the distribution of the ‘total_bill’ on each ‘day’ of the ‘tips’ dataset. But we also want to group it on the basis of ‘sex’ attribute. So we will plot a grouped boxplots for these three attributes where ‘sex’ and ‘day’ are categorical attributes and ‘total_bill’ is a numeric attribute.
Python3
# create grouped boxplot sns.boxplot(x = data['day'],            y = data['total_bill'],            hue = data['sex'])
Output:
Example 2: The next example is similar to the previous one. The only difference is the value of the ‘hue’ parameter taken as the ‘smoker’ attribute. Here we want to know the distribution of ‘total_bill’ vs ‘day’ group on the basis of if a person smokes or not. 
Also, we have learned how to change the colors of the boxplots using the ‘palette’ attribute of the boxplot().
Python3
# create another grouped boxplot sns.boxplot(x = data['day'],            y = data['total_bill'],            hue = data['smoker'],            palette = 'Set2')
Output:
Example 3: In this example, we will cover how to draw more than 2 grouped boxplots. if the value for the ‘hue’ parameter has more than 2 categories, then we can plot more than 2 grouped boxplots as shown below. 
Here, ‘hue’ = data[‘size’] has six categories, and so we can see more than 2 grouped boxplots using the same method as above.
Python3
# create 3rd grouped boxplot sns.boxplot(x = data['day'],            y = data['total_bill'],            hue = data['size'],            palette = 'husl')
Output:
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Perl chop Function

This function removes the last character from EXPR, each element of LIST, or $_ if no value is specified.
Following is the simple syntax for this function −
chop VARIABLE

chop( LIST )

chop

This function returns the character removed from EXPR and in list context, the character is removed from the last element of LIST.
Following is the example code showing its basic usage −
#!/usr/bin/perl

$string1 = "This is test";
$retval  = chop( $string1 );

print " Choped String is : $string1\n";
print " Character removed : $retval\n";
When above code is executed, it produces the following result −
Choped String is : This is tes
Number of characters removed : t
Ways to print escape characters in Python

17 Nov, 2017
Escape characters are characters that are generally used to perform certain tasks and their usage in code directs the compiler to take a suitable action mapped to that character.
Example :
'\n'  -->  Leaves a line
'\t'  -->  Leaves a space 

# Python code to demonstrate escape character# string   ch = "I\nLove\tGeeksforgeeks"  print ("The string after resolving escape character is : ")print (ch)
Output :
The string after resolving escape character is : 
I
Love    Geeksforgeeks

But in certain cases it is desired not to resolve escapes, i.e the entire unresolved string hasto be printed. These are achieved by following ways.
This function returns a string in its printable format, i.e doesn’t resolve the escape sequences.
# Python code to demonstrate printing # escape characters from repr()  # initializing target string ch = "I\nLove\tGeeksforgeeks"  print ("The string without repr() is : ")print (ch)  print ("\r")  print ("The string after using repr() is : ")print (repr(ch))
Output :
The string without repr() is : 
I
Love    Geeksforgeeks


The string after using repr() is : 
'I\nLove\tGeeksforgeeks'

Adding “r” or “R” to the target string triggers a repr() to the string internally and stops from the resolution of escape characters.
# Python code to demonstrate printing # escape characters from "r" or "R"  # initializing target string ch = "I\nLove\tGeeksforgeeks"  print ("The string without r / R is : ")print (ch)  print ("\r")  # using "r" to prevent resolutionch1 = r"I\nLove\tGeeksforgeeks"  print ("The string after using r is : ")print (ch1)  print ("\r")  # using "R" to prevent resolutionch2 = R"I\nLove\tGeeksforgeeks"  print ("The string after using R is : ")print (ch2)
Output :
The string without r/R is : 
I
Love    Geeksforgeeks


The string after using r is : 
I\nLove\tGeeksforgeeks


The string after using R is : 
I\nLove\tGeeksforgeeks

Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Check if a point lies on or inside a rectangle in Python

Suppose we have a rectangle represented by two points bottom-left and top-right corner points. We have to check whether a given point (x, y) is present inside this rectangle or not.
So, if the input is like bottom_left = (1, 1), top_right = (8, 5), point = (5, 4), then the output will be True
To solve this, we will follow these steps −
Define a function solve() . This will take bl, tr, p
if x of p > x of bl and x of p < x of tr and y of p > y of bl and y of p < y of tr, thenreturn True
return True
otherwise,return False
return False
Let us see the following implementation to get better understanding −
 Live Demo
def solve(bl, tr, p) :
   if (p[0] > bl[0] and p[0] < tr[0] and p[1] > bl[1] and p[1] < tr[1]) :
      return True
   else :
      return False
bottom_left = (1, 1)
top_right = (8, 5)
point = (5, 4)
print(solve(bottom_left, top_right, point))
(1, 1), (8, 5), (5, 4)
True
What is the #define Preprocessor in C++?

The #define creates a macro, which is the association of an identifier or parameterized identifier with a token string. After the macro is defined, the compiler can substitute the token string for each occurrence of the identifier in the source file.
#define identifier token-string
This is how the preprocessor is used. The #define directive causes the compiler to substitute token-string for each occurrence of identifier in the source file. The identifier is replaced only when it forms a token. That is, identifier is not replaced if it appears in a comment, in a string, or as part of a longer identifier.
#include<iostream>
#define MY_VAR 55
using namespace std;

int main() {
   int x = 10;
   cout << x + MY_VAR;      // After preprocessing this expression becomes: x + 55
   return 0;
}

This will give the output −
65
You can read more about the #define directive in MSDN https://docs.microsoft.com/en-us/cpp/preprocessor/hash-define-directive-c-cpp
Python SQLite - Create Table

Using the SQLite CREATE TABLE statement you can create a table in a database.
Following is the syntax to create a table in SQLite database −
CREATE TABLE database_name.table_name(
   column1 datatype PRIMARY KEY(one or more columns),
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype
);

Following SQLite query/statement creates a table with name CRICKETERS in SQLite database −
sqlite> CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Age int,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255)
);
sqlite>
Let us create one more table OdiStats describing the One-day cricket statistics of each player in CRICKETERS table.
sqlite> CREATE TABLE ODIStats (
   First_Name VARCHAR(255),
   Matches INT,
   Runs INT,
   AVG FLOAT,
   Centuries INT,
   HalfCenturies INT 
);
sqlite>
You can get the list of tables in a database in SQLite database using the .tables command. After creating a table, if you can verify the list of tables you can observe the newly created table in it as −
sqlite> . tables
CRICKETERS ODIStats
sqlite>

The Cursor object contains all the methods to execute quires and fetch data etc. The cursor method of the connection class returns a cursor object.
Therefore, to create a table in SQLite database using python −
Establish connection with a database using the connect() method.
Establish connection with a database using the connect() method.
Create a cursor object by invoking the cursor() method on the above created connection object.
Create a cursor object by invoking the cursor() method on the above created connection object.
Now execute the CREATE TABLE statement using the execute() method of the Cursor class.
Now execute the CREATE TABLE statement using the execute() method of the Cursor class.
Following Python program creates a table named Employee in SQLite3 −
import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('example.db')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping EMPLOYEE table if already exists.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
#Creating table as per requirement
sql ='''CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL,
   LAST_NAME CHAR(20),
   AGE INT,
   SEX CHAR(1),
   INCOME FLOAT
)'''
cursor.execute(sql)
print("Table created successfully........")

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()
Table created successfully........


    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
C program to find the length of linked list

Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. They are defined as a collection of nodes. Here, nodes have two parts, which are data and link. The representation of data, link and linked lists is given below −
Linked lists have four types, which are as follows −
Single / Singly linked lists
Double / Doubly linked lists
Circular single linked list
Circular double linked list
The logic we used to find the length of linked list by using recursion method is −
int length(node *temp){
   if(temp==NULL)
      return l;
   else{
      l=l+1;
      length(temp->next);
   }
}
Following is the C program to find the length of linked list −
 Live Demo
#include <stdio.h>
#include <stdlib.h>
typedef struct linklist{
   int data;
   struct linklist *next;
}node;
int l=0;
int main(){
   node *head=NULL,*temp,*temp1;
   int len,choice,count=0,key;
   do{
      temp=(node *)malloc(sizeof(node));
      if(temp!=NULL){
         printf("\nenter the elements in a list : ");
         scanf("%d",&temp->data);
         temp->next=NULL;
         if(head==NULL){
            head=temp;
         }else{
            temp1=head;
            while(temp1->next!=NULL){
               temp1=temp1->next;
            }
            temp1->next=temp;
         }
      }else{
         printf("\nMemory is full");
      }
      printf("\npress 1 to enter data into list: ");
      scanf("%d",&choice);
   }while(choice==1);
   len=length(head);
   printf("The list has %d no of nodes",l);
   return 0;
}
//recursive function to find length
int length(node *temp){
   if(temp==NULL)
      return l;
   else{
      l=l+1;
      length(temp->next);
   }
}
When the above program is executed, it produces the following result −
Run 1:
enter the elements in a list: 3
press 1 to enter data into list: 1
enter the elements in a list: 56
press 1 to enter data into list: 1
enter the elements in a list: 56
press 1 to enter data into list: 0
The list has 3 no of nodes
Run 2:
enter the elements in a list: 12
press 1 to enter data into list: 1
enter the elements in a list: 45
press 1 to enter data into list: 0
The list has 2 no of nodes
How to Get the Minimum and maximum Value of a Column of a MySQL Table Using Python? - GeeksforGeeks

23 Dec, 2020
Prerequisite: Python: MySQL Create Table
In this article, we are going to see how to get the Minimum and Maximum Value of a Column of a MySQL Table Using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. 
Database in use:
We are going to use geeks(Database name) database and table describing the salary.
Approach:
Import module.
Make a connection request with the database.
Create an object for the database cursor.
Execute the following MySQL query:
SELECT MIN(Column_name) AS minimum FROM Table_name.
SELECT MAX(Column_name) AS minimum FROM Table_name.
And print the result.
Example 1: Getting the minimum value of a column.
Python3
# Establish connection to MySQL databaseimport mysql.connector  mydb = mysql.connector.connect(  host = "localhost",  user = "root",  password = "root123",  database = "geeks")  # Create a cursor objectcursor = mydb.cursor()  # Execute the query cursor.execute("SELECT MIN(Value) AS minimum FROM salary")  result = cursor.fetchall()  for i in result:    maximum= float(i[0])    print(maximum)  # Close database connectionmydb.close()
Output:
200.0
Example 2: Getting the maximum value of a column.
Python3
# Establish connection to MySQL databaseimport mysql.connector  mydb = mysql.connector.connect(  host = "localhost",  user = "root",  password = "root123",  database = "geeks")  # Create a cursor objectcursor = mydb.cursor()  cursor.execute("SELECT MAX(Value) AS maximum FROM salary")  result = cursor.fetchall()  for i in result:    maximum = float(i[0])    print(maximum)  # Close database connectionmydb.close()
Output:
350030.0
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Python program for removing i-th character from a string - GeeksforGeeks

20 Apr, 2020
Given the string, we have to remove the ith indexed character from the string.
In any string, indexing always start from 0. Suppose we have a string geeks then its indexing will be as –
g e e k s
0 1 2 3 4

Examples :
Input : Geek
        i = 1
Output : Gek 

Input : Peter 
        i = 4
Output : Pete

 
Approach 1 : From the given string, i-th indexed element has to be removed. So, Split the string into two halves, before indexed character and after indexed character. Return the merged string.
Below is the implementation of above approach :
# Python3 program for removing i-th # indexed character from a string  # Removes character at index idef remove(string, i):       # Characters before the i-th indexed    # is stored in a variable a    a = string[ : i]           # Characters after the nth indexed    # is stored in a variable b    b = string[i + 1: ]          # Returning string after removing    # nth indexed character.    return a + b      # Driver Codeif __name__ == '__main__':          string = "geeksFORgeeks"          # Remove nth index element    i = 5        # Print the new string    print(remove(string, i))
geeksORgeeks

Approach 2 : The idea is to use string replace in Python
# Python3 program for removing i-th # indexed character from a string  # Removes character at index idef remove(string, i):       for j in range(len(string)):        if j == i:            string = string.replace(string[i], "", 1)    return string      # Driver Codeif __name__ == '__main__':          string = "geeksFORgeeks"          # Remove nth index element    i = 5        # Print the new string    print(remove(string, i))
geeksORgeeks

kunchamaparna509
Python string-programs
python-string
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to print without newline in Python?
Intersection() function Python - GeeksforGeeks

05 Oct, 2021
Python intersection() function return a new set with an element that is common to all set
The intersection of two given sets is the largest set which contains all the elements that are common to both sets. The intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B. 
Input: Let set A = {2, 4, 5, 6}
       and set B = {4, 6, 7, 8}
Output: {4,6} 
Explanation: Taking the common elements in both the sets, we get {4,6} as the intersection of both the sets.
set1.intersection(set2, set3, set4....) In parameters, any number of sets can be given
The intersection() function returns a set, which has the intersection of all sets(set1, set2, set3...) with set1. It returns a copy of set1 only if no parameter is passed. 
Python3
# Python3 program for intersection() functionset1 = {2, 4, 5, 6}set2 = {4, 6, 7, 8}set3 = {4, 6, 8} # union of two setsprint("set1 intersection set2 : ",      set1.intersection(set2)) # union of three setsprint("set1 intersection set2 intersection set3 :",      set1.intersection(set2, set3))
Output: 
set1 intersection set2 :  {4, 6}
set1 intersection set2 intersection set3 : {4, 6}
we can also get intersection using & operator.
Python3
# Python3 program for intersection() functionset1 = {2, 4, 5, 6}set2 = {4, 6, 7, 8}set3 = {1, 0, 12} print(set1 & set2)print(set1 & set3) print(set1 & set2 & set3)
Output:
{4, 6}
set()
set()
symmetric_difference() is a opposite to the set.intersection() methods.
Python3
# Python3 program for intersection() functionset1 = {2, 4, 5, 6}set2 = {4, 6, 7, 8}set3 = {1, 0, 12} print(set1.symmetric_difference(set2))print(set1.symmetric_difference(set3))print(set2.symmetric_difference(set3))
Output:
{2, 5, 7, 8}
{0, 1, 2, 4, 5, 6, 12}
{0, 1, 4, 6, 7, 8, 12}
Python3
set1 = {}set2 = {} # union of two setsprint("set1 intersection set2 : ",      set(set1).intersection(set(set2)))
Output:
set1 intersection set2 :  set()
kumar_satyam
Python-Built-in-functions
python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python Program to print unique values from a list

Given a list, our task is to print all the unique numbers.
Input:A = [1, 2, 3, 4, 2, 1, 9]
Unique list is [1, 2, 3, 4, 9]
Step 1: Create user input list.
Step 2: Create an empty list.
Step 3: Traverse all elements in the list.
Step 4: Check the unique element is present or not.
Step 5: Append unique element one by one into that empty list.
Step 6: Display that list.
# Python program to print unique values from a list

def unique(A):
   # intilize a null list
   uniquevalues = []

   # traversing the list
   for i in A:
   # check unique valueis present or not
   if i not in uniquevalues:
      uniquevalues.append(i)
      # print (A)
      for i in uniquevalues:
      print (i),

      # Driver code
      A=list()
      n=int(input("Enter the size of the List ::"))
      print("Enter the Element of List ::")
      for i in range(int(n)):
      k=int(input(""))
      A.append(k)

print("The unique values from the List is ::>")
unique(A)
Enter the size of the List :: 6
Enter the Element of List ::
1
2
5
2
1
7
The unique values from the List is ::>
1
2
5
7
C Program for compound interest?

Here we will see how to get the compound interest by writing one C program. The logic is very easy. Here we need some parameters −
P − Principle amount
R − Rate of interest
T − Time span
The compound interest formula is like below
#include<stdio.h>
#include<math.h>
float compoundInterest(float P, float T, float R) {
   return P*(pow(1+(R/100), T));
}
int main() {
   float p, t, r;
   printf("Enter Princple amount, rate of interest, and time: ");
   scanf("%f%f%f", &p, &r, &t);
   printf("Interest value: %f", compoundInterest(p, t, r));
}
Enter Princple amount, rate of interest, and time: 5000 7.5 3
Interest value: 6211.485352
Extracting Keys and Values from Hash in Perl

You can get a list of all of the keys from a hash in Perl by using keys function, which has the following syntax −
keys %HASH
This function returns an array of all the keys of the named hash. Following is the example −
 Live Demo
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@names = keys %data;
print "$names[0]\n";
print "$names[1]\n";
print "$names[2]\n";
This will produce the following result −
Lisa
John Paul
Kumar
Similarly, you can use values function to get a list of all the values. This function has the following syntax −
values %HASH
This function returns a normal array consisting of all the values of the named hash. Following is the example −
 Live Demo
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
@ages = values %data;
print "$ages[0]\n";
print "$ages[1]\n";
print "$ages[2]\n";
This will produce the following result −
30
45
40
JavaTuples - Create Tuples

A tuple using JavaTuple classes can be created using multiple options. Following are the examples −
Each tuple class has a with() method with corresponding parameters. For example −
Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5));
Triplet<String, Integer, Double> triplet = Triplet.with("Test", Integer.valueOf(5), 
   Double.valueOf(32.1));	

Each tuple class has a constructor with corresponding parameters. For example −
Pair<String, Integer> pair = new Pair("Test", Integer.valueOf(5));
Triplet<String, Integer, Double> triplet = new Triplet("Test", Integer.valueOf(5), 
   Double.valueOf(32.1));	

Each tuple class has a fromCollection() method with corresponding parameters. For example −
Pair<String, Integer> pair = Pair.fromCollection(listOfTwoElements);	

Each tuple class has a fromIterable() method to get elements in generic fashion. For example −
// Retrieve three values from an iterable starting at index 5
Triplet<Integer,Integer,Integer> triplet = Triplet.fromIterable(listOfInts, 5);

Let's see JavaTuples in action. Here we'll see how to create tupels using various ways.
Create a java class file named TupleTester in C:\>JavaTuples.
File: TupleTester.java
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
import org.javatuples.Pair;

public class TupleTester {
   public static void main(String args[]){
      //Create using with() method
      Pair<String, Integer> pair = Pair.with("Test", Integer.valueOf(5));   
      //Create using constructor()
      Pair<String, Integer> pair1 = new Pair("Test", Integer.valueOf(5)); 
      List<Integer> listOfInts = new ArrayList<Integer>();
      listOfInts.add(1);
      listOfInts.add(2);
      //Create using fromCollection() method
      Pair<Integer, Integer> pair2 = Pair.fromCollection(listOfInts);	  
      listOfInts.add(3);
      listOfInts.add(4);
      listOfInts.add(5);
      listOfInts.add(6);
      listOfInts.add(8);
      listOfInts.add(9);
      listOfInts.add(10);
      listOfInts.add(11);
      //Create using fromIterable() method
      // Retrieve three values from an iterable starting at index 5
      Pair<Integer,Integer> pair3 = Pair.fromIterable(listOfInts, 5);
      //print all tuples
      System.out.println(pair);
      System.out.println(pair1);
      System.out.println(pair2);
      System.out.println(pair3);
   }
}
Verify the result
Compile the classes using javac compiler as follows −
C:\JavaTuples>javac -cp javatuples-1.2.jar ./com/tutorialspoint/TupleTester.java

Now run the TupleTester to see the result −
C:\JavaTuples>java  -cp .;javatuples-1.2.jar com.tutorialspoint.TupleTester

Verify the Output
[Test, 5]
[Test, 5]
[1, 2]
[6, 8]

 Print
 Add Notes
 Bookmark this page
Scala String trim() method with example - GeeksforGeeks

29 Oct, 2019
The trim() method is utilized to omit the leading and trailing spaces in the stated string.
Method Definition: String trim()
Return Type: It returns the stated string after removing all the white spaces.
Example: 1#
// Scala program of trim()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying trim method        val result = "     Nidhi Singh ".trim()                  // Displays output        println(result)          }} 
Nidhi Singh

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

Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Scala Tutorial – Learn Scala with Step By Step Guide
Scala List filter() method with example
Scala Map
Type Casting in Scala
Scala Lists
Class and Object in Scala
Scala List contains() method with example
Break statement in Scala
Operators in Scala
Scala | Arrays
Display month by name and number in Java

Use the ‘b’ conversion character for month name in Java.
Use the ‘m’ conversion character for month number in Java.
Here, we are using Formatter and Calendar class, therefore import the following packages.
import java.util.Calendar;
import java.util.Formatter;
The following is an example to display month name and number −
 Live Demo
import java.util.Calendar;
import java.util.Formatter;
public class Demo {
   public static void main(String args[]) {
      Formatter f = new Formatter();
      Calendar cal = Calendar.getInstance();
      System.out.println("Current date and time: "+cal.getTime());
      f = new Formatter();
      System.out.println(f.format("Month = %tb \nMonth Number = %tm", cal, cal));
   }
}
Current date and time: Mon Nov 26 07:07:31 UTC 2018
Month = Nov
Month Number = 11
PyQt5 QSpinBox - Making text bold - GeeksforGeeks

19 May, 2020
In this article we will see how we can make the text of the spin box bold, in order to set the font use setFont method which takes QFont object as argument. In order to make the the text i.e font bold we have to get the QFont object of the spin box then make it bold then reassign it to the spin box.
In order to do this we use setBold method with the QFont object of the spin box
Syntax : font.setBold(True)
Argument : It takes bool as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for widgets    def UiComponents(self):        # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 250, 40)          # setting range to the spin box        self.spin.setRange(0, 999999)          # setting prefix to spin        self.spin.setPrefix("Prefix ")          # setting suffix to spin        self.spin.setSuffix(" Suffix")          # getting font of the spin box        font = self.spin.font()          # making font bold        font.setBold(True)          # setting back this font to the spin box        self.spin.setFont(font)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
How to update the value of a key in a dictionary in Python?

Python dictionary object is an unordered collection of key:value pairs. Ina dictionary object d, the value associated to any key can be obtained by d[k].
>>> d={'one':1, 'two':2,'three':3,'four':4}
>>> d['two']
2
The assignment d[k]=v will update the dictionary object. If existing key is used in the expression, its associated value will be updated. If the key has not been used, a new key-value pair will be added in the dictionary object.
>>> d={'one':1, 'two':2,'three':3,'four':4}
>>> d['two']=22
>>> d
{'one': 1, 'two': 22, 'three': 3, 'four': 4}
>>> d['five']=5
>>> d
{'one': 1, 'two': 22, 'three': 3, 'four': 4, 'five': 5}
TypeScript - String slice()

This method extracts a section of a string and returns a new string.
string.slice( beginslice [, endSlice] );

beginSlice − The zero-based index at which to begin extraction.
beginSlice − The zero-based index at which to begin extraction.
endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string.
endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string.
If successful, slice returns the index of the regular expression inside the string. Otherwise, it returns -1.
var str = "Apples are round, and apples are juicy."; 
var sliced = str.slice(3, -2); 
console.log(sliced);

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
les are round, and apples are juic


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: Responsive framework: W3.CSS
Nth element of the Fibonacci series JavaScript

We are required to write a JavaScript function that takes in a single number as the first and the only argument, let’s call that number n.
The function should return the nth element of the Fibonacci series.
For example −
fibonacci(10) should return 55
fibonacci(3) should return 2
fibonacci(6) should return 8
fibonacci(2) should return 1
const fibonacci = (num = 1) => {
   const series = [1, 1];
   for (let i = 2; i < num; i++) {
      const a = series[i - 1];
      const b = series[i - 2];
      series.push(a + b);
   };
   return series[num - 1];
};
console.log(fibonacci(10));
console.log(fibonacci(6));
console.log(fibonacci(3));
console.log(fibonacci(2));
And the output in the console will be −
55
8
2
1