code-rag-bench/online-tutorials huggingface dataset:
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
How to exclude PSComputerName property from Invoke-Command output in PowerShell?

When we are working with Invoke-Command, we get the PSComputerName extra field in the output table. You can remove it by using -HideComputerName parameter. For example, the Below command gives the output with the PSComputerName property.
Invoke-Command -ComputerName LabMachine2k12 -ScriptBlock{Get-Service Winrm} | ft -AutoSize
Status  Name  DisplayName                               PSComputerName
------  ----  -----------                               --------------
Running Winrm Windows Remote Management (WS-Management) LabMachine2k12
To hide the PSComputerName property,
Invoke-Command -ComputerName LabMachine2k12 -ScriptBlock{Get-Service Winrm} -HideComputerName
Status  Name  DisplayName  
------  ----  -----------  
Running Winrm Windows Remote Management (WS-Management)
How do we reference Python class attributes?

From the Python documentation −
Class objects support two kinds of operations: attribute references and instantiation.
Attribute references use the standard syntax used for all attribute references in Python: obj.name. Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this −
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of MyClass.i by assignment. __doc__ is also a valid attribute, returning the docstring belonging to the class − "A simple example class"
Run Length Encoding in Python

In this tutorial, we are going to learn how to create a run-length encoding in Python. Given a string return a new string containing char and frequency.
For example, the string tutorialspoint will be encoded as t3u1o2r1i2a1l1s1p1n1. The order is every char+frequency. Join all of them and return. See the steps below to write the program.
Write the function with the name run_length_encoding.
Write the function with the name run_length_encoding.
Initialize a dictionary with OrderedDict to get an initial count of chars as 0.
Initialize a dictionary with OrderedDict to get an initial count of chars as 0.
Iterate over every character of the string and increment the count in the dictionary.
Iterate over every character of the string and increment the count in the dictionary.
Join all the chars and their frequencies. And print it.
Join all the chars and their frequencies. And print it.
Initialize the strings and invoke the function.
Initialize the strings and invoke the function.
Let's see the code for the above text.
# importing the collections
import collections
# function
def run_length_encoding(string):
   # initialzing the count dict
   count_dict = collections.OrderedDict.fromkeys(string, 0)
   # iterating over the string
   for char in string:
      # incrementing the frequency
      count_dict[char] += 1
   # initializing the empty encoded string
   encoded_string = ""
   # joining all the chars and their frequencies
   for key, value in count_dict.items():
      # joining
      encoded_string += key + str(value)
      # printing the encoded string
print(encoded_string)
# initializing the strings
string = "tutorialspoint"
# invoking the function
run_length_encoding(string)
# another string
string = "aaaaaabbbbbccccccczzzzzz"
run_length_encoding(string)
If you run the above code, you will get the following output.
t3u1o2r1i2a1l1s1p1n1
a6b5c7z6
If you have any doubts in the tutorial, mention them in the comment section.
How can we set the foreground and background color to JComboBox items in Java?

A JComboBox is a subclass of JComponent class and it is a combination of a text field and a drop-down list from which the user can choose a value. A JComboBox can generate an ActionListener, ChangeListener and ItemListener interfaces when the user actions on a combo box. We can also set the foreground and background color to JComboBox items by using setForeground() and setBackground() methods of a JComboBox class.
import java.awt.*;
import javax.swing.*;
public class JComboBoxItemColorTest extends JFrame{
   private JComboBox jcb;
   public JComboBoxItemColorTest() {
      setTitle("JComboBoxItemColor Test");
      String[] countries = {"India", "Australia", "England", "South Africa", "Newzealand"};
      jcb = new JComboBox(countries);
      jcb.setForeground(Color.blue);
      jcb.setBackground(Color.white);
      add(jcb, BorderLayout.NORTH);
      setSize(500,300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[]args) {
      new JComboBoxItemColorTest();
   }
}
How to Compute the Average of a Column of a MySQL Table Using Python? - GeeksforGeeks

28 Oct, 2021
A MySQL connector is needed to generate a connection between Python and the MySQL server. Here we will import mysql.connector library to get the average of the specified column in the given database. 
If you need to know how to install MySQL, see How to Install MySQL in Python 3.
SQL AVG() function returns the average of values of a numeric column in a table. It is generally used with the WHERE clause.
AVG() Function Syntax
SELECT AVG(column_name)  FROM table_name WHERE condition; 
The following program will help you understand this better.
Database used:
Students Table in school database
So we first must import mysql.connector . Once that is imported, we gain connection to the MySQL database using the mysql.connector.connect() function.
We then have to create a cursor for the table.
Next, we execute our function to find the average of the Marks column of the Students table using the cursor.execute() function. Inside of this function, we place in the line, “SELECT AVG(Marks) AS average FROM students”.
We then create a variable named rows and set it equal to cursor.fetchall().
We then use a for loop and print out i[0], which represents the average of the Marks column.
We then close the database once we’ve done what we’ve needed to.
And by this is we can find the average of all the rows of a column in a MySQL table using Python. 
Implementation:
Program to find Average using MySQL connector in Python 3.
Python3
import mysql.connector # database connectionconnection = mysql.connector.connect(    host="localhost", user="root",      password="", database="school")cursor = connection.cursor() # queries for retrievint all rowsretrieve = "Select AVG(Marks) AS average from students;" # executing the queriescursor.execute(retrieve)rows = cursor.fetchall()for i in rows:    print("Average marks is :" + str(i[0]))  # committing the connection then closing it.connection.commit()connection.close()
Output:
Output of Marks Column Average of Students Table.
adnanirshad158
Python-mySQL
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
How to Change color of Button in Android when Clicked using Kotlin?

This example demonstrates how to Change color of Button in Android when Clicked using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/text2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="70dp"
      android:background="#008080"
      android:padding="5dp"
      android:text="TutorialsPoint"
      android:textColor="#fff"
      android:textSize="24sp"
      android:textStyle="bold" />
   <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Click here to change color!" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.graphics.Color
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val button: Button = findViewById(R.id.button)
      button.setOnClickListener { button.setBackgroundColor(Color.BLUE) }
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
How to check if a string only contains certain characters in Python?

You can check if a string only contains certain characters result by using Sets. Declare a set using the characters you want to allow. For example if we want to check if a string only contains 1, 2, 3 and 4, we can use −
from sets import Set
allowed_chars = Set('1234')
validationString = '121'
if Set(validationString).issubset(allowed_chars):
    print True
else:
    print False
This will give you the result −
True
You can also use regexes for the same result. For matching only 1, 2, 3 and 4, we can call the re.match(regex, string) using the regex: "^[1234]+$". 
import re
print(bool(re.match('^[1234]+$', '123abc')))
print(bool(re.match('^[1234]+$', '123')))
False
True
 Keep in mind that regexes have special uses for some characters and hence require escaping them. re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().
MySQL Tryit Editor v1.0

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
HTML DOM NodeList.values() Method - GeeksforGeeks

24 Jul, 2020
The NodeList values() method returns an iterator allowing you to go through all values contained in the NodeList object. The values are Node objects.
Syntax:
NodeList.values();
Parameters: This method takes no parameter.
Return value: This method returns an iterator.
Example: In this example, we will create a NodeList and hence will get an iterator to get all values from NodeList using this method.
<!DOCTYPE HTML> <html>  <head>    <meta charset="UTF-8">    <title>HTML | DOM NodeList.values() Method</title></head>     <body style="text-align:center;">    <h1 style="color:green;">       GeeksforGeeks    </h1>     <p> HTML | DOM NodeList.values() Method    </p>      <button onclick = "Geeks()">    Click Here    </button>    <p id="a"></p>    <script>         var a = document.getElementById("a");        a.innerHTML = "elements are : "        function Geeks(){           var parentNode = document.createElement("div");             var c1 = document.createElement("p");             var c2 = document.createElement("span");             var c3 = document.createElement("h1");             parentNode.appendChild(c1);             parentNode.appendChild(c2);             parentNode.appendChild(c3);             var nodelist = parentNode.childNodes;              for(var values of nodelist.values()) {                console.log(values);                a.innerHTML += "<li>"+values.localName + `</li>`;            }            console.log(nodelist.values())        }</script></body>   </html>
Output:
Before Clicking Button:
After Clicking Button: Elements are called using values iterator.
In the console: Iterator values can be seen.
Supported Browsers:
Google Chrome
Edge
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
How to serialize a JSON string to an Output Handler in Java?

The Flexjson is a lightweight library for serializing and deserializing Java objects into and from JSON format. A JSONSerializer is the main class for performing serialization of Java objects to JSON. We can serialize a JSON string to an Output Handler using the WriterOutputHandler class and it implements the OutputHandler interface.
public class WriterOutputHandler extends Object implements OutputHandler
import java.io.*;
import flexjson.JSONSerializer;
import flexjson.OutputHandler;
import flexjson.WriterOutputHandler;
public class JsonOutputHandlerTest {
   public static void main(String[] args) {
      JSONSerializer serializer = new JSONSerializer().prettyPrint(true); // pretty print JSON
      Employee emp = new Employee("Raja", "Ramesh", 28, "Hyderabad");
      OutputHandler out = new WriterOutputHandler(new StringWriter());
      serializer.serialize(emp, out);
      System.out.println(out.toString());
   }
}
// Employee class
class Employee {
   private String firstName;
   private String lastName;
   private int age;
   private String address;
   public Employee() {
   }
   public Employee(String firstName, String lastName, int age, String address) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.address = address;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public int getAge() {
      return age;
   }
   public String getAddress() {
      return address;
   }
   public String toString() {
      return "Employee[ " +
             "firstName = " + firstName +
             ", lastName = " + lastName +
             ", age = " + age +
             ", address = " + address +
             " ]";
   }
}
{
 "address": "Hyderabad",
 "age": 28,
 "class": "Employee",
 "firstName": "Raja",
 "lastName": "Ramesh"
}
Load class with forName() method in Java

The class object associated with the class with the given string name can be returned with the method java.lang.Class.forName(String name, boolean initialize, ClassLoader loader), using the class loader that is used to load the class.
The parameters in the forName() method are name, initialize and loader. If the value of the parameter loader is null, then the class is loaded using the bootstrap class loader. Also, if the initialize parameter is true, then only the class is initialized if it has not been initialized earlier.
A program that loads the class using the forName() method is given as follows −
 Live Demo
import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      try {
         Class c1 = Class.forName("Demo");
         ClassLoader classLoader = c1.getClassLoader();
         Class c2 = Class.forName("java.lang.String", true, classLoader);
         System.out.println("Class = " + c1.getName());
         System.out.println("Class = " + c2.getName());
      }
      catch(ClassNotFoundException e) {
         System.out.println("Excepton: " + e.toString());
      }
   }
}
Class = Demo
Class = java.lang.String
MariaDB - Join

In previous discussions and examples, we examined retrieving from a single table, or retrieving multiple values from multiple sources. Most real-world data operations are much more complex, requiring aggregation, comparison, and retrieval from multiple tables.
JOINs allow merging of two or more tables into a single object. They are employed through SELECT, UPDATE, and DELETE statements.
Review the general syntax of a statement employing a JOIN as shown below −
SELECT column
FROM table_name1
INNER JOIN table_name2
ON table_name1.column = table_name2.column;

Note the old syntax for JOINS used implicit joins and no keywords. It is possible to use a WHERE clause to achieve a join, but keywords work best for readability, maintenance, and best practices.
JOINs come in many forms such as a left join, right join, or inner join. Various join types offer different types of aggregation based on shared values or characteristics.
Employ a JOIN either at the command prompt or with a PHP script.
At the command prompt, simply use a standard statement −
root@host# mysql -u root -p password;
Enter password:*******
mysql> use PRODUCTS;
Database changed

mysql> SELECT products.ID_number, products.Nomenclature, inventory.inventory_ct
   FROM products
   INNER JOIN inventory
   ON products.ID_numbeer = inventory.ID_number;
+-------------+----------------+-----------------+
| ID_number   | Nomenclature   | Inventory Count |
+-------------+----------------+-----------------+
| 12345       | Orbitron 4000  | 150             |
+-------------+----------------+-----------------+
| 12346       | Orbitron 3000  | 200             |
+-------------+----------------+-----------------+
| 12347       | Orbitron 1000  | 0               |
+-------------+----------------+-----------------+
Use the mysql_query() function to perform a join operation −
<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $sql = 'SELECT a.product_id, a.product_manufacturer, b.product_count   
      FROM products_tbl a, pcount_tbl b 
      WHERE a.product_manufacturer = b.product_manufacturer';

   mysql_select_db('PRODUCTS');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }

   while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
      echo "Manufacturer:{$row['product_manufacturer']} <br> ".
         "Count: {$row['product_count']} <br> ".
         "Product ID: {$row['product_id']} <br> ".
         "--------------------------------<br>";
   }

   echo "Fetched data successfully\n";
   mysql_close($conn);
?>
On successful data retrieval, you will see the following output −
ID Number: 12345
Nomenclature: Orbitron 4000
Inventory Count: 150
--------------------------------------
ID Number: 12346
Nomenclature: Orbitron 3000
Inventory Count: 200
--------------------------------------
ID Number: 12347
Nomenclature: Orbitron 1000
Inventory Count: 0
--------------------------------------
mysql> Fetched data successfully

 Print
 Add Notes
 Bookmark this page
Binary Subarrays With Sum in C++

Suppose an array A of 0s and 1s is given, we have to find how many non-empty subarrays have sum S? So if the input is like [1,0,1,0,1], and S = 2, then the result will be 4, as the subarrays are [1,0,1,0,1], [1,0,1,0,1], [1,0,1,0,1], [1,0,1,0,1].
To solve this, we will follow these steps −
Define a method called atMost(), this will take array A and integer x
Define a method called atMost(), this will take array A and integer x
if x < 0, then return 0, set j := 0 and set ret := 0
if x < 0, then return 0, set j := 0 and set ret := 0
for i in range 0 to size of Adecrease x by A[i]while x < 0increase x by A[j], increase j by 1ret := ret + i – j + 1
for i in range 0 to size of A
decrease x by A[i]
decrease x by A[i]
while x < 0increase x by A[j], increase j by 1
while x < 0
increase x by A[j], increase j by 1
increase x by A[j], increase j by 1
ret := ret + i – j + 1
ret := ret + i – j + 1
return ret
return ret
From the main method do the following −
From the main method do the following −
ret := atMost(A, S) – atMost(A, S – 1)
ret := atMost(A, S) – atMost(A, S – 1)
return ret
return ret
Let us see the following implementation to get better understanding &mius;
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int atMost(vector <int>& A, int x){
      if(x < 0) return 0;
      int j = 0;
      int ret = 0;
      for(int i = 0; i < A.size(); i++){
         x -= A[i];
         while(x < 0){
            x += A[j];
            j++;
         }
         ret += i - j + 1;
      }
      return ret;
   }
   int numSubarraysWithSum(vector<int>& A, int S) {
      return atMost(A, S) - atMost(A, S - 1);
   }
};
main(){
   vector<int> v1 = {1,0,1,0,1};
   Solution ob;
   cout << (ob.numSubarraysWithSum(v1, 2));
}
[1,0,1,0,1]
4
Python Program for Find sum of even factors of a number

In this article, we will learn about the solution to the problem statement given below −
Given a number input n, the task is to Find the sum of even factors of a number.
Here we first need to eliminate all the odd factors.
If the number input is odd it has no even factors therefor return zero directly , otherwise, we will follow the approach in the code below
Below is the implementation −
 Live Demo
import math
# Returns sum of all even factors of n.
def sumofFactors(n) :
   # If n is odd
   if (n % 2 != 0) :
      return 0
   #all prime factors
   res = 1
   for i in range(2, (int)(math.sqrt(n)) + 1) :
      count = 0
      curr_sum = 1
      curr_term = 1
      while (n % i == 0) :
         count= count + 1
         n = n // i
         # here we remove the 2^0 that is 1. All other factors
         if (i == 2 and count == 1) :
            curr_sum = 0
         curr_term = curr_term * i
         curr_sum = curr_sum + curr_term
      res = res * curr_sum
   # if n is prime number
   if (n >= 2) :
      res = res * (1 + n)
   return res
# main
n = 20
print(sumofFactors(n))
36
All the variables are declared in the global frame as shown in the figure given below −
In this article, we learned about the approach to Find the sum of even factors of a number
How to Filter rows using Pandas Chaining? - GeeksforGeeks

01 Oct, 2020
In this article we will learn how to filter rows using Pandas chaining. For this first we have look into some previous terms which are given below :
Pandas DataFrame : It is a two-dimensional data structure, i.e. the data is tabularly aligned in rows and columns. The Pandas DataFrame has three main components i.e. data, rows and columns.
Pandas Chaining : Method chaining, in which methods are called on an object sequentially, one after the another. It has always been a programming style that’s been possible with pandas, and over the past few releases, many methods have been introduced that allow even more chaining.
Here we use the concept of chaining in Pandas to filter the dataframe and get the same rows as an output. This can be easily explained with the help of examples. Here we use a dataframe which consists of some data of person as shown below :
Python
# import packageimport pandas as pd  # define datadata = pd.DataFrame(  {'ID': {0: 105, 1: 102, 2: 101, 3: 106, 4: 103, 5: 104, 6: 107},      'Name': {0: 'Ram Kumar', 1: 'Jack Wills', 2: 'Deepanshu Rustagi',           3: 'Thomas James', 4: 'Jenny Advekar', 5: 'Yash Raj',           6: 'Raman Dutt Mishra'},      'Age': {0: 40, 1: 23, 2: 20, 3: 34, 4: 18, 5: 56, 6: 35},      'Country': {0: 'India', 1: 'Uk', 2: 'India', 3: 'Australia',                4: 'Uk', 5: 'India', 6: 'India'}  })  # view datadata
Output:
Here, we select the rows with a specific value in a particular column. The Country column in dataframe is selected with value ‘India’ to filter rows.
Python3
# select the rows with specific value in # a particular columnprint(data[data.Country.eq('India')])
Output:
Here, we select the rows with specific grouped values in a particular column. The Age column in dataframe is selected with value less than 30 to filter rows.
Python3
# select the rows with specific grouped # values in a particular columnprint(data[data.Age<30])
Output:
Here, we select the rows with specific character or string value in a particular column. The Name column in dataframe is selected with value contains ‘am’ to filter rows.
Python3
# select the rows with specific string# or character value in a particular columnprint(data[data.Name.str.contains('am')])
Output:
Here, we select the rows from specific set of values in a particular column. The Country column in dataframe is selected and matched with the given set of values to filter rows.
Python3
# define the set of valueslst=['Uk','Australia']  # select the rows from specific set # of values in a particular columnprint(data[data.Country.isin(lst)])
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to make random colors in Python - Turtle? - GeeksforGeeks

16 Sep, 2021
The turtle is a built-in module from the Python library. The turtle module is used to draw interesting shapes or drawings. We can use the turtle module by calling import turtle. The random module is used to generate random numbers. 
randint(0,255): It is used to generate numbers between 0 and 255.
speed(0): It is used to set speed to display the drawing on board.
colormode(255): It should be set to 255 to generate a color number till 255.
begin_fill(): It begins to fill the circle with color.
end_fill(): It ends to fill the circle with color.
penup(): It will stop drawing on the board.
pendown(): Turtle operates with pendown() state by default. To go back to the past drawing state on board.
circle(radius): It is used to generate a circle of a particular radius.
All the above methods will be called inside an infinite loop in order to illustrate a randomly generated coloured circles of the same radius.
Below is the implementation.
Python3
# import turtlefrom turtle import *# import randomfrom random import randint  # speed to draw to colorspeed(0) # size of the penpensize(10) # colormode should be 255 to# show every type of colorcolormode(255)  # To display the color continuously the# while loop is truewhile True:         # randint will have random color based on    # every randint the color will be called    color(randint(0, 255),          randint(0, 255),          randint(0, 255))         # it will begin to fill the circle with color    begin_fill()         # generate circle    circle(20)         # it will end to fill color    end_fill()         # it will start to draw    penup()         # x axis and y axis    goto(randint(-500, 500), randint(-300, 270))         # it wil stop to draw    pendown()
Output
Random color 
sweetyty
gabaa406
Picked
Python-turtle
Technical Scripter 2020
Python
Technical Scripter
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 | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
expect command in Linux with Examples - GeeksforGeeks

15 May, 2019
expect command or scripting language works with scripts that expect user inputs. It automates the task by providing inputs.
// We can install expect command using following if not installed
// On Ubuntu$sudo apt install expect
// On Redhat based systems$ yum install expect
First we write a script that will be needing inputs from users and then we will write another script using expect to automate the task.
#!/bin/bash
 
echo "Enter your name"
 
read $REPLY
 
echo "Enter your age"
 
read $REPLY
 
echo "Enter your salary"
 
read $REPLY

Ok, so let’s write down the script to answer questions of the above script.
#!/usr/bin/expect -f
 
set timeout -1
 
spawn ./que.sh
 
expect "Enter your name\r"
 
send -- "I am Nikhil\r"
 
expect "Enter your age\r"
 
send -- "24\r"
 
expect "Enter your salary\r"
 
send -- "100k\r"
 
expect eof

The first line defines the expect command path which is #!/usr/bin/expect .
On the second line of code, we disable the timeout. Then start our script using spawn command.We can use spawn to run any program we want or any other interactive script. The spawn command is used to start a script or a program like the shell, FTP, Telnet, SSH, SCP, and so on.The remaining lines are the Expect script that interacts with our shell script.The last line if the end of file which means the end of the interaction.
First we have to make the file executable and then run it.You can do this by typing the following:
$ chmod +x ./ans.sh
$ ./ans.sh

This will produce an output like this :Output:
To build an expect script automatically, you can the use autoexpect command.autoexpect works like expect, but it builds the automation script for you. The script you want to automate is passed to autoexpect as a parameter and you answer the questions and your answers are saved in a file.
$ autoexpect ./que.sh  

A file is generated called script.exp contains the same code as we did above with some additions.if you run the file script.exp you will see the same answers that you provided.
linux-command
Linux-misc-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
find_elements_by_name() driver method - Selenium Python - GeeksforGeeks

14 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task.
This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_elements_by_name() is discussed in this article. This method returns a list with type of elements specified.To grab a single first element, checkout – find_element_by_name() driver method – Selenium Python
driver.find_elements_by_name("name")

Example –For instance, consider this page source:
<html> <body>  <form id="loginForm">   <input name="1" type="text" />   <input name="1" type="password" />   <input name="1" type="submit" value="Login" />  </form> </body><html>
Now after you have created a driver, you can grab an element using –
login_form = driver.find_elements_by_name('1')

Let’s try to practically implement this method and get a element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its name “articleTitle”.Create a file called run.py to demonstrate find_elements_by_name method –
# Python program to demonstrate# selenium  # import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # enter keyword to searchkeyword = "geeksforgeeks"  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get elementselements = driver.find_elements_by_name("articleTitle")  # print complete elements listprint(element)
Now run using –
Python run.py
First, it will open firefox window with geeksforgeeks, and then select the element and print it on terminal as show below.Browser Output –Terminal Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python - Random Replacement of Word in String - GeeksforGeeks

01 Aug, 2020
Given a string and List, replace each occurrence of K word in string with random element from list. 
Input : test_str = “Gfg is x. Its also x for geeks”, repl_list = [“Good”, “Better”, “Best”], repl_word = “x”Output : Gfg is Best. Its also Better for geeksExplanation : x is replaced by random replace list values.
Input : test_str = “Gfg is x. Its also x for geeks”, repl_list = [“Good”, “Better”, “Nice”], repl_word = “x”Output : Gfg is Best. Its also Nice for geeksExplanation : x is replaced by random replace list values, “Best” and “Nice”.
Method #1 :  Using shuffle() + loop + replace()
The combination of above functions can be used to solve this problem. In this, we replace each occurrence of K word with random string from list using replace().
Python3
# Python3 code to demonstrate working of # Random Replacement of Word in String# Using replace() + shuffle() + loopfrom random import shuffle  # initializing stringtest_str = "Gfg is val. Its also val for geeks"  # printing original stringprint("The original string is : " + str(test_str))  # initializing list repl_list = ["Good", "Better", "Best"]  # initializing replace wordrepl_word = "val"  # shuffing list ordershuffle(repl_list)for ele in repl_list:          # replacing with random string     test_str = test_str.replace(repl_word, ele, 1)      # printing result print("String after random replacement : " + str(test_str)) 
The original string is : Gfg is val. Its also val for geeks
String after random replacement : Gfg is Best. Its also Better for geeks


Method #2 : Using list comprehension + replace() + shuffle()
This is one of the ways in which this task can be performed. In this, we encapsulate entire logic in one-liner using similar functionalities as above method.
Python3
# Python3 code to demonstrate working of # Random Replacement of Word in String# Using list comprehension + replace() + shuffle()from random import shuffle  # initializing stringtest_str = "Gfg is val. Its also val for geeks"  # printing original stringprint("The original string is : " + str(test_str))  # initializing list repl_list = ["Good", "Better", "Best"]  # initializing replace wordrepl_word = "val"  # one-liner to solve problemshuffle(repl_list)res = [test_str.replace(repl_word, ele, 1) for ele in repl_list]      # printing result print("String after random replacement : " + str(res)) 
The original string is : Gfg is val. Its also val for geeksString after random replacement : [‘Gfg is Good. Its also val for geeks’, ‘Gfg is Better. Its also val for geeks’, ‘Gfg is Best. Its also val for geeks’]
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.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
HTML | oninput Event Attribute - GeeksforGeeks

24 Dec, 2021
This attribute works when it gets user input value. This attribute mainly fires when the user change the value of <input> and <textarea> element. This attribute is quite similar to onchange attribute but the basic difference is that the oninput event attribute occurs immediately when the value of the element changes while the onchange attribute occurs when the element loses Focus. The other difference is that onchange attribute also works with the <select> element.Supported Tags:
<input type=”password”>
<input type=”search”>
<input type=”text”> 
<textarea>
Syntax: 
<element oninput = "script">
Attribute Value: This attribute contains value script and it works when oninput event triggered. This attribute is supported by many HTML tags: <input type=”password”>, <input type=”search”>, <input type=”text”> and <textarea>.
Example:  
HTML
<!DOCTYPE html><html>    <head>        <title>oninput attribute</title>        <style>            body {                text-align:center;            }            h1 {                color:green;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>oninput Attribute</h2>        Enter some Text here: <input type="text" id="GFG"        oninput="Geeks()">        <p id="sudo"></p>          <script>            function Geeks() {                var x = document.getElementById("GFG").value;                document.getElementById("sudo").innerHTML =                "Entered Text: " + x;            }        </script>    </body></html>                   
Output: 
Supported Browsers: The browser supported by oninput event attribute are listed below:  
Apple Safari 5.0
Google Chrome
Firefox 4.0
Opera
Internet Explorer 9.0
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
arorakashish0911
HTML-Attributes
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Java int Keyword

❮ Java Keywords

int myNum = 100000;
System.out.println(myNum);


Try it Yourself »

The int keyword is a data type that can store whole numbers from -2147483648 to 2147483647.
Read more about data types in our Java Data Types Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Count the pairs of vowels in the given string in C++

We are given with a string of characters and the task is to calculate the count of pairs having both the elements as vowels. As we know there are five vowels in English alphabet i.e. a, i, e, o, u and other characters are known as Consonants.
Input − string str = "tutorials point”
Output − Count the pairs of vowels in the given string are: 2
Explanation − From the given string we can form pairs as (t, u), (u, t), (t, o), (o, r), (r, i), (i, a), (a, l), (l, s), (s, p), (p, o), (o, i), (i, n) and (n , t). So, the pairs with both the elements as vowels are (i, a) and (o, i) therefore the count of pairs of vowels is 2.
Input − string str = "learning”
Output − Count the pairs of vowels in the given string are: 1
Input −From the given string we can form pairs as (l, e), (e, a), (a, r), (r, n), (n, i), (i, n) and (n, g). So, the pairs with both the elements as vowels is (e, a) only therefore the count of pairs of vowels is 1.
Input the string of characters in a string type variable
Input the string of characters in a string type variable
Calculate the length of a string using length() function that will return the total number of characters in a string
Calculate the length of a string using length() function that will return the total number of characters in a string
Take a temporary variable count to store the count of pairs of vowels.
Take a temporary variable count to store the count of pairs of vowels.
Start loop For from i to 0 till the length of a string
Start loop For from i to 0 till the length of a string
Inside the loop, check IF str[i] is ‘a’ OR ‘i’ OR ‘e’ OR ‘o’ OR ‘u’ then check IF str[i+1] is ‘a’ OR ‘i’ OR ‘e’ OR ‘o’ OR ‘u’ then increment the value of count by 1
Inside the loop, check IF str[i] is ‘a’ OR ‘i’ OR ‘e’ OR ‘o’ OR ‘u’ then check IF str[i+1] is ‘a’ OR ‘i’ OR ‘e’ OR ‘o’ OR ‘u’ then increment the value of count by 1
Return the count
Return the count
Print the result
Print the result
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int count_pairs(string str, int length){
   int count = 0;
   for(int i=0 ;i<length-1; i++){
      if(str[i]=='a' || str[i]=='i'||str[i]=='e'||str[i]=='o'||str[i]=='u'){
         if(str[i+1]=='a'||str[i+1]=='i'||str[i+1]=='e'||str[i+1]=='o'||str[i+1]=='u'){
            count++;
         }
      }
   }
   return count;
}
int main(){
   string str = "tutorials point";
   int length = str.length();
   cout<<"Count the pairs of vowels in the given string are: "<<count_pairs(str, length);
   return 0;
}
If we run the above code it will generate the following output −
Count the pairs of vowels in the given string are: 2