code-rag-bench/online-tutorials huggingface dataset:
Create Classes Dynamically in Python - GeeksforGeeks

09 Mar, 2020
A class defines a collection of instance variables and methods to specify an object type. A class can be used to make as many object instances of the type of object as needed. An object is an identified entity with certain attributes (data members) and behaviours (member functions). Group of objects having similar characteristics and behaviour are the instance of the same class.
Python is a dynamic programming language and due to its flexibility Python has a significant advantage over statically typed languages. Python Code can be dynamically imported and classes can be dynamically created at run-time.
Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object.
Syntax:
type(object)

The above syntax returns the type of object.
Example:
# program to illustrate the use of type()  print(type("Geeks4Geeks !")) print(type(1706256))
Output:
class 'str'
class 'int'

Classes can be created dynamically using the below syntax:Syntax:
type(name, bases, attributes) 

Parameters:
name: The user defined name of the class
bases: A list of base classes, and its type is tuple
attributes: the data members and methods contained in the class

The above Syntax returns a new type of object.
Example:
# program to create class dynamically  # constructordef constructor(self, arg):    self.constructor_arg = arg  # methoddef displayMethod(self, arg):    print(arg)  # class method@classmethoddef classMethod(cls, arg):    print(arg)  # creating class dynamicallyGeeks = type("Geeks", (object, ), {    # constructor    "__init__": constructor,          # data members    "string_attribute": "Geeks 4 geeks !",    "int_attribute": 1706256,          # member functions    "func_arg": displayMethod,    "class_func": classMethod})  # creating objectsobj = Geeks("constructor argument")print(obj.constructor_arg)print(obj.string_attribute)print(obj.int_attribute)obj.func_arg("Geeks for Geeks")Geeks.class_func("Class Dynamically Created !")
Output:
constructor argument
Geeks 4 geeks!
1706256
Geeks for GeeksClass Dynamically Created!

In the above program, class Geeks is dynamically created which has a constructor. The data members of Geeks are string_attribute and int_attribute and member functions of Geeks are displayMethod() and classMethod(). An object obj of class Geeks is created and all the data members are assigned and displayed, all the member functions of Geeks are also called.
Python-OOP
python-oop-concepts
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
Java program to find the Frequency of a character in a given String

To find the Frequency of a character in a given String
 Read a string from the user.
 Read the character.
 Create an integer variable initialize it with 0.
 Compare each character in the given string with the entered character increment the above created integer variable each time a match occurs.
import java.util.Scanner;
public class FrequencyOfACharacter {
   public static void main(String args[]){
      System.out.println("Enter a string value ::");
      Scanner sc = new Scanner(System.in);
      String str = sc.nextLine();

      System.out.println("Enter a particular character ::");
      char character = sc.nextLine().charAt(0);
      int count = 0;

      for (int i=0; i<str.length(); i++){
         if(character == str.charAt(i)){
            count++;
         }
      }
      System.out.println("Frequency of the give character:: "+count);
   }
}
Enter a string value ::
Hi welcome to Tutorialspoint
Enter a particular character ::
t
Frequency of the give character:: 3
ThaiBuddhistDate now(ZoneId) method in Java with Examples - GeeksforGeeks

20 May, 2020
The now() method of java.time.chrono.ThaiBuddhistDate class is used to get the current ThaiBuddhist date according to the ThaiBuddhist calendar system in the specified zone.
Syntax:
public static ThaiBuddhistDate
              now(ZoneId zone)

Parameter: This method takes the object of zone id on the basis of which ThaiBuddhist date is going to be formed.
Return Value: This method returns the current ThaiBuddhist date according to the ThaiBuddhist calendar system from the specified clock.
Below are the examples to illustrate the now() method:
Example 1:
Java
// Java program to demonstrate now() method  import java.util.*;import java.io.*;import java.time.*;import java.time.chrono.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] argv)    {        try {              // Creating and initializing ZoneId            ZoneId id                = ZoneId.systemDefault();              // Creating and initializing            // ThaiBuddhistDate Object            ThaiBuddhistDate hidate                = ThaiBuddhistDate.now(id);              // Display the result            System.out.println(                "ThaiBuddhistDate: "                + hidate);        }        catch (DateTimeException e) {            System.out.println(                "Passed parameter can"                + " not form a date");              System.out.println(                "Exception thrown: "                + e);        }    }}
ThaiBuddhistDate: ThaiBuddhist BE 2563-05-08

Example 2:
Java
// Java program to demonstrate now() method  import java.util.*;import java.io.*;import java.time.*;import java.time.chrono.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] argv)    {        try {              // Creating and initializing ZoneId            ZoneId id                = ZoneId.of("Z");              // Creating and initializing            // ThaiBuddhistDate Object            ThaiBuddhistDate hidate                = ThaiBuddhistDate.now(id);              // Display the result            System.out.println(                "ThaiBuddhistDate: "                + hidate);        }        catch (DateTimeException e) {              System.out.println(                "passed parameter can"                + " not form a date");              System.out.println(                "Exception thrown: "                + e);        }    }}
ThaiBuddhistDate: ThaiBuddhist BE 2563-05-08

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ThaiBuddhistDate.html#now-java.time.ZoneId-
Java-Functions
Java-Time-Chrono package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Strings in Java
StringBuilder Class in Java with Examples
numpy.fv() in Python - GeeksforGeeks

29 Nov, 2018
numpy.fv(rate, nper, pmt, pv, when = ‘end’) : This financial function helps user to compute future values.
Parameters :
rate : [scalar or (M, )array] Rate of interest as decimal (not per cent) per periodnper : [scalar or (M, )array] total compounding periodspmt : [scalar or (M, )array] fixed paymentpv : [scalar or (M, )array] present valuewhen : at the beginning (when = {‘begin’, 1}) or the end (when = {‘end’, 0}) of each period. Default is {‘end’, 0}
Return :
value at the end of nper periods

Equation being solved :
fv + pv*(1+rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
or when rate == 0
fv + pv + pmt * nper == 0
Code 1 : Working
# Python program explaining fv() function  import numpy as np'''Question :   Future value after 10 years of saving $100 now, with an additional monthly savings of $100. Assume the interest rate is 5% (annually) compounded monthly ?'''  #                 rate       np      pmt    pvSolution = np.fv(0.05/12, 10*12, -100, -100)  print("Solution : ", Solution)
Output :
Solution :  15692.9288943

References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.fv.html#numpy.fv.
Python numpy-Financial Functions
Python-numpy
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 ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
break, continue and label in Java loop

Following example showcases labels 'first', 'second' before a for statement and use the break/continue controls to jump to that label. See the example below.
Live Demo
public class Tester {
   public static void main(String args[]) {
      first:
         for (int i = 0; i < 3; i++) {
            for (int j = 0; j< 3; j++){
               if(i == 1){
                  continue first;
               }      
               System.out.print(" [i = " + i + ", j = " + j + "] ");
            }
         }
     
         System.out.println();
     
         second:
            for (int i = 0; i < 3; i++) {
               for (int j = 0; j< 3; j++){
                  if(i == 1){
                     break second;
                  }    
 
                  System.out.print(" [i = " + i + ", j = " + j + "] ");
               }
            }
    }
}
first is the label for first outermost for loop and continue first cause the loop to skip print statement if i = 1;
second is the label for second outermost for loop and continue second cause the loop to break the loop.
GATE | GATE-CS-2014-(Set-1) | Question 65 - GeeksforGeeks

14 Feb, 2018
Consider the following set of processes that need to be scheduled on a single CPU. All the times are given in milliseconds.
Process Name      Arrival Time      Execution Time
    A                  0                  6
    B                  3                  2
    c                  5                  4
    D                  7                  6
    E                  10                 3
Using the shortest remaining time first scheduling algorithm, the average process turnaround time (in msec) is ____________________.(A) 7.2(B) 8(C) 7(D) 7.5Answer: (A)Explanation: Turn around time of a process is total time between submission of the process and its completion. Shortest remaining time (SRT) scheduling algorithm selects the process for execution which has the smallest amount of time remaining until completion.
Solution:Let the processes be A, ,C,D and E. These processes will be executed in following order. Gantt chart is as follows:
First 3 sec, A will run, then remaining time A=3, B=2,C=4,D=6,E=3 Now B will get chance to run for 2 sec, then remaining time. A=3, B=0,C=4,D=6,E=3Now A will get chance to run for 3 sec, then remaining time. A=0, B=0,C=4,D=6,E=3 By doing this way, you will get above gantt chart.
Scheduling table:
As we know, turn around time is total time between submission of the process and its completion. i.e turn around time=completion time-arrival time. i.e. TAT=CT-ATTurn around time of A = 8 (8-0)Turn around time of B = 2 (5-3)Turn around time of C = 7 (12-5)Turn around time of D = 14 (21-7)Turn around time of E = 5 (15-10)Average turn around time is (8+2+7+14+5)/5 = 7.2.Answer is 7.2.Reference:https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/5_CPU_Scheduling.html
This solution is contributed by Nitika Bansal
Alternate Explanatio:
After drawing Gantt Chart

Completion Time for processes A, B, C, D 
and E are 8, 5, 12, 21 and 15 respectively.

Turnaround Time = Completion Time - Arrival Time
Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | Gate IT 2007 | Question 30
GATE | GATE CS 2011 | Question 7
How to grant replication privilege to a database in MySQL?

To grant replication privilege, use GRANT REPLICATION SLAVE ON.
First list all the user names along with host from MySQL.user table −
mysql> select user,host from mysql.user;
This will produce the following output −
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| Bob              | %         |
| Charlie          | %         |
| Robert           | %         |
| User2            | %         |
| mysql.infoschema | %         |
| mysql.session    | %         |
| mysql.sys        | %         |
| root             | %         |
| @UserName@       | localhost |
| Adam             | localhost |
| Adam Smith       | localhost |
| Chris            | localhost |
| David            | localhost |
| James            | localhost |
| John             | localhost |
| John Doe         | localhost |
| Mike             | localhost |
| User1            | localhost |
| am               | localhost |
| hbstudent        | localhost |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
+------------------+-----------+
22 rows in set (0.00 sec)
Let us implement the above syntax to grant replication privilege to a database in MySQL −
mysql> GRANT REPLICATION SLAVE ON *.* TO 'Mike'@'localhost';
Query OK, 0 rows affected (0.20 sec)
Let us check the grant is successful or not −
mysql> SHOW GRANTS FOR 'Mike'@'localhost';
This will produce the following output −
+------------------------------------------------------+
| Grants for Mike@localhost                            |
+------------------------------------------------------+
| GRANT REPLICATION SLAVE ON *.* TO `Mike`@`localhost` |
+------------------------------------------------------+
1 row in set (0.04 sec)
How to maximize and minimize browsers in Selenium with python?

We can maximize and minimize the browser while we are testing an application in Selenium.
For maximizing the browser, maximize() method is to be used.
For minimizing the browser, minimize() method is to be used.
Both these methods can be used simultaneously in the same program.
Code Implementation
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# to minimize the browser window
driver.minimize_window()
#to close the browser
driver.close()
Assign multiple variables with a Python list values

Depending on the need of the program we may an requirement of assigning the values in a list to many variables at once. So that they can be further used for calculations in the rest of the part of the program. In this article we will explore various approaches to achieve this.
The for loop can help us iterate through the elements of the given list while assigning them to the variables declared in a given sequence.We have to mention the index position of values which will get assigned to the variables.
 Live Demo
listA = ['Mon', ' 2pm', 1.5, '11 miles']

# Given list
print("Given list A: " ,listA)

# using for in
vDay, vHrs, vDist = [listA[i] for i in (0, 2, 3)]

# Result
print ("The variables : " + vDay + ", " + str(vHrs) + ", " +vDist)
Running the above code gives us the following result −
Given list A: ['Mon', ' 2pm', 1.5, '11 miles']
The variables : Mon, 1.5, 11 miles
The itergetter function from the operator module will fetch the item for specified indexes. We directly assign them to the variables.
 Live Demo
from operator import itemgetter

listA = ['Mon', ' 2pm', 1.5, '11 miles']

# Given list
print("Given list A: " ,listA)


# using itemgetter
vDay, vHrs, vDist = itemgetter(0, 2, 3)(listA)

# Result
print ("The variables : " + vDay + ", " + str(vHrs) + ", " +vDist)
Running the above code gives us the following result −
Given list A: ['Mon', ' 2pm', 1.5, '11 miles']
The variables : Mon, 1.5, 11 miles
The compress function from itertools module will catch the elements by using the Boolean values for index positions. So for index position 0,2 and 3 we mention the value 1 in the compress function and then assign the fetched value to the variables.
 Live Demo
from itertools import compress

listA = ['Mon', ' 2pm', 1.5, '11 miles']

# Given list
print("Given list A: " ,listA)

# using itemgetter
vDay, vHrs, vDist = compress(listA, (1, 0,1, 1))

# Result
print ("The variables : " + vDay + ", " + str(vHrs) + ", " +vDist)
Running the above code gives us the following result −
Given list A: ['Mon', ' 2pm', 1.5, '11 miles']
The variables : Mon, 1.5, 11 miles
Print all permutation of a string using ArrayList in Java

In this problem, we are given a string of size n and we have to print all permutations of the string. But this time we have to print this permutation using ArrayList.
Let’s take an example to understand the problem -
Input − string = ‘XYZ’
Output − XYZ, XZY, YXZ, YZX, ZXY, ZYX
To solve this problem, we will be generating all permutations of the character of the string. We will use a recursive function and will return arrayList.
The following is ArrayList implementation of the algorithm −
 Live Demo
import java.util.ArrayList;
public class Main{
   static void printArrayList(ArrayList<String> combo) {
      combo.remove("");
      for (int i = 0; i < combo.size(); i++)
      System.out.print(combo.get(i)+"\t");
   }
   public static ArrayList<String> generatePermutation(String str) {
      if (str.length() == 0) {
         ArrayList<String> empty = new ArrayList<>();
         empty.add("");
         return empty;
      }
      char ch = str.charAt(0);
      String subStr = str.substring(1);
      ArrayList<String> lastCombination = generatePermutation(subStr);
      ArrayList<String> newCombination = new ArrayList<>();
      for (String val : lastCombination) {
      for (int i = 0; i <= val.length(); i++) {
            newCombination.add(val.substring(0, i) + ch + val.substring(i));
         }
       }
      return newCombination;
    }
   public static void main(String[] args) {
      String str = "NOPQ";
      System.out.println("Permutations of string are :");
      printArrayList(generatePermutation(str));
   }
}
Permutations of string are :
NOPQ ONPQ OPNQ OPQN NPOQ PNOQ
PONQ POQN NPQO PNQO PQNO
PQON NOQP ONQP OQNP OQPN
NQOP QNOP QONP QOPN NQPO
QNPO QPNO QPON
SymPy - Entities

The geometry module in SymPy allows creation of two dimensional entities such as line, circle, etc. We can then obtain information about them such as checking colinearity or finding intersection.
Point class represents a point in Euclidean space. Following example checks for collinearity of points −
>>> from sympy.geometry import Point 
>>> from sympy import * 
>>> x=Point(0,0) 
>>> y=Point(2,2) 
>>> z=Point(4,4) 
>>> Point.is_collinear(x,y,z)

Output
True
>>> a=Point(2,3) 
>>> Point.is_collinear(x,y,a)

Output
False
The distance() method of Point class calculates distance between two points
>>> x.distance(y)

Output
22
The distance may also be represented in terms of symbols.
Line entity is obtained from two Point objects. The intersection() method returns point of intersection if two lines intersect each other.
>>> from sympy.geometry import Point, Line 
>>> p1, p2=Point(0,5), Point(5,0) 
>>> l1=Line(p1,p2)
>>> l2=Line(Point(0,0), Point(5,5)) 
>>> l1.intersection(l2)

Output
[Point2D(5/2, 5/2)]
>>> l1.intersection(Line(Point(0,0), Point(2,2)))

Output
[Point2D(5/2, 5/2)]
>>> x,y=symbols('x y') 
>>> p=Point(x,y) 
>>> p.distance(Point(0,0))

Output
x2+y2
This function builds a triangle entity from three point objects.
Triangle(a,b,c)
>>> t=Triangle(Point(0,0),Point(0,5), Point(5,0)) 
>>> t.area

Output
−252
An elliptical geometry entity is constructed by passing a Point object corresponding to center and two numbers each for horizontal and vertical radius.
ellipse(center, hradius, vradius)
>>> from sympy.geometry import Ellipse, Line 
>>> e=Ellipse(Point(0,0),8,3) 
>>> e.area

Output
24π
The vradius can be indirectly provided by using eccentricity parameter.
>>> e1=Ellipse(Point(2,2), hradius=5, eccentricity=Rational(3,4)) 
>>> e1.vradius

Output
574
The apoapsis of the ellipse is the greatest distance between the focus and the contour.
>>> e1.apoapsis

Output
354
Following statement calculates circumference of ellipse −
>>> e1.circumference

Output
20E(916)
The equation method of ellipse returns equation of ellipse.
>>> e1.equation(x,y)

Output
(x5−25)2+16(y−2)2175−1
 Print
 Add Notes
 Bookmark this page
What is ({$natural: 1}) in MongoDB?

The ({$natural − 1}) works like LIFO(LAST IN FIRST OUT), that means last inserted document will be shown first.
Let us create a collection with documents −
> db.demo614.insertOne({"CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e988cddf6b89257f5584d8e")
}
> db.demo614.insertOne({"CountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e988ce0f6b89257f5584d8f")
}
> db.demo614.insertOne({"CountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e988ce3f6b89257f5584d90")
}
> db.demo614.insertOne({"CountryName":"IND"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e988cebf6b89257f5584d91")
}
Display all documents from a collection with the help of find() method −
> db.demo614.find();
This will produce the following output −
{ "_id" : ObjectId("5e988cddf6b89257f5584d8e"), "CountryName" : "US" }
{ "_id" : ObjectId("5e988ce0f6b89257f5584d8f"), "CountryName" : "UK" }
{ "_id" : ObjectId("5e988ce3f6b89257f5584d90"), "CountryName" : "AUS" }
{ "_id" : ObjectId("5e988cebf6b89257f5584d91"), "CountryName" : "IND" }
Following is the query to work with ({$natural: 1}) −
> db.demo614.find().sort({$natural:-1})
This will produce the following output −
{ "_id" : ObjectId("5e988cebf6b89257f5584d91"), "CountryName" : "IND" }
{ "_id" : ObjectId("5e988ce3f6b89257f5584d90"), "CountryName" : "AUS" }
{ "_id" : ObjectId("5e988ce0f6b89257f5584d8f"), "CountryName" : "UK" }
{ "_id" : ObjectId("5e988cddf6b89257f5584d8e"), "CountryName" : "US" }
Gson - First Application

Before going into the details of the Google Gson library, let's see an application in action. In this example, we've created a Student class. We'll create a JSON string with student details and deserialize it to student object and then serialize it to an JSON String.
Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.
File − GsonTester.java
import com.google.gson.Gson; 
import com.google.gson.GsonBuilder;  

public class GsonTester { 
   public static void main(String[] args) { 
      String jsonString = "{\"name\":\"Mahesh\", \"age\":21}"; 
      
      GsonBuilder builder = new GsonBuilder(); 
      builder.setPrettyPrinting(); 
      
      Gson gson = builder.create(); 
      Student student = gson.fromJson(jsonString, Student.class); 
      System.out.println(student);    
      
      jsonString = gson.toJson(student); 
      System.out.println(jsonString);  
   } 
} 

class Student { 
   private String name; 
   private int age; 
   public Student(){} 
   
   public String getName() { 
      return name; 
   }
   
   public void setName(String name) { 
      this.name = name; 
   } 
   
   public int getAge() { 
      return age; 
   }
   
   public void setAge(int age) { 
      this.age = age; 
   }
   
   public String toString() { 
      return "Student [ name: "+name+", age: "+ age+ " ]"; 
   }  
}
Compile the classes using javac compiler as follows −
C:\GSON_WORKSPACE>javac GsonTester.java

Now run the GsonTester to see the result −
C:\GSON_WORKSPACE>java GsonTester

Verify the output.
Student [ name: Mahesh, age: 21 ] 
{ 
   "name" : "Mahesh", 
   "age" : 21 
}

Following are the important steps to be considered here.
Create a Gson object. It is a reusable object.
GsonBuilder builder = new GsonBuilder(); 
builder.setPrettyPrinting(); 
Gson gson = builder.create();

Use fromJson() method to get the Object from the JSON. Pass Json string / source of Json string and object type as parameter.
//Object to JSON Conversion 
Student student = gson.fromJson(jsonString, Student.class);

Use toJson() method to get the JSON string representation of an object.
//Object to JSON Conversion   
jsonString = gson.toJson(student); 

 Print
 Add Notes
 Bookmark this page
How to create a popup chat window with CSS and JavaScript?

To create popup chat window with CSS and JavaScript, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   * {
      box-sizing: border-box;
   }
   .openChatBtn {
      background-color: rgb(123, 28, 179);
      color: white;
      padding: 16px 20px;
      border: none;
      font-weight: 500;
      font-size: 18px;
      cursor: pointer;
      opacity: 0.8;
      position: fixed;
      bottom: 23px;
      right: 28px;
      width: 280px;
   }
   .openChat {
      display: none;
      position: fixed;
      bottom: 0;
      right: 15px;
      border: 3px solid #ff08086b;
      z-index: 9;
   }
   form {
      max-width: 300px;
      padding: 10px;
      background-color: white;
   }
   form textarea {
      width: 100%;
      font-size: 18px;
      padding: 15px;
      margin: 5px 0 22px 0;
      border: none;
      font-weight: 500;
      background: #d5e7ff;
      color: rgb(0, 0, 0);
      resize: none;
      min-height: 200px;
   }
   form textarea:focus {
      background-color: rgb(219, 255, 252);
      outline: none;
   }
   form .btn {
      background-color: rgb(34, 197, 107);
      color: white;
      padding: 16px 20px;
      font-weight: bold;
      border: none;
      cursor: pointer;
      width: 100%;
      margin-bottom: 10px;
      opacity: 0.8;
   }
   form .close {
      background-color: red;
   }
   form .btn:hover, .openChatBtn:hover {
      opacity: 1;
   }
</style>
</head>
<body>
<h1>Popup Chat Window Example</h1>
<h2>Click the below button to start chatting</h2>
<button class="openChatBtn" onclick="openForm()">Chat</button>
<div class="openChat">
<form>
<h1>Chat</h1>
<label for="msg"><b>Message</b></label>
<textarea placeholder="Type message.." name="msg" required></textarea>
<button type="submit" class="btn">Send</button>
<button type="button" class="btn close" onclick="closeForm()">
Close
</button>
</form>
</div>
<script>
   document .querySelector(".openChatBtn") .addEventListener("click", openForm);
   document.querySelector(".close").addEventListener("click", closeForm);
   function openForm() {
      document.querySelector(".openChat").style.display = "block";
   }
   function closeForm() {
      document.querySelector(".openChat").style.display = "none";
   }
</script>
</body>
</html>
The above code will produce the following output −
On clicking the Chat button the chat window will popup as follows −
How to set python environment variable PYTHONPATH on Windows?

To set the PYTHONPATH on windows to point Python to look in other directories for module and package imports, go to:
My Computer > Properties > Advanced System Settings > Environment Variables
Then under system variables edit the PythonPath variable. At the end of the current PYTHONPATH, add a semicolon and then the directory you want to add to this path:
C:\Python27;C:\foo
, In this case, are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble.
round() in C++.

The round() function in C++ is used to round off the double, float or long double value passed to it as a parameter to the nearest integral value. The header file used to use the
round() function in a c++ program is <cmath> or <tgmath>.
Following are the overloaded versions of round() after C++ 11 standard
double round( double D )
float round( float F )
long double round( long double LD )
double round ( T var )
Note − The value returned is the nearest integer represented as floating point, i.e for 2.3 nearest value returned will be 2.0 and not 2.
Following program is used to demonstrate the usage of round function in a C++ program −
 Live Demo
#include <cmath>
#include <iostream>
int main(){
   double num1=10.5;
   double num2=10.3;
   double num3=9.7;
   std::cout << "Nearest integer after round("<<num1<<") :" << round(num1)<< "\n";
   std::cout << "Nearest integer after round("<<num2<<") :" << round(num2)<< "\n";
   std::cout << "Nearest integer after round("<<num3<<") :" << round(num3)<< "\n";
   num1=-9.3;
   num2=-0.3;
   num3=-9.9;
   std::cout << "Nearest integer after round("<<num1<<") :" << round(num1)<< "\n";
   std::cout << "Nearest integer after round("<<num2<<") :" << round(num2)<< "\n";
   std::cout << "Nearest integer after round("<<num3<<") :" << round(num3)<< "\n";
   return 0;
}
Nearest integer after round(10.5) :11
Nearest integer after round(10.3) :10
Nearest integer after round(9.7) :10
Nearest integer after round(-9.3) :-9
Nearest integer after round(-0.3) :-0
Nearest integer after round(-9.9) :-10
Sort the array of strings according to alphabetical order defined by another string in C++

Suppose we have an array of strings, and another string is there for the reference. We have to take the reference string and using the order of the characters in the reference string we will sort the string array. Here we are considering the strings in the array, and the reference string is in lower case letters.
Suppose the string array is like: [“hello”, “programming”, “science”, “computer”, “india”], the reference string is like: “pigvxbskyhqzelutoacfjrndmw”, After sorting the output string will be like [“programming”, “india”, “science”, “hello”, “computer”]
The task is simple. We have to traverse the reference string, then store the character into the map as key, and the index as value. Now to sort the string, we have to compare the strings based on that map, not the ASCII character ordering. Compare the values mapped to those particular characters in the map, if the character c1 appears before c2, then c1 < c2.
 Live Demo
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
unordered_map<char, int> char_map;
bool compare(string c1, string c2) {
   for (int i = 0; i < min(c1.size(), c2.size()); i++) {
      if (char_map[c1[i]] == char_map[c2[i]])
         continue;
      return char_map[c1[i]] < char_map[c2[i]];
   }
   return c1.size() < c2.size();
}
int main() {
   string str = "pigvxbskyhqzelutoacfjrndmw";
   vector<string> v{ "hello", "programming", "science", "computer", "india" };
   char_map.clear();
   for (int i = 0; i < str.size(); i++)
   char_map[str[i]] = i;
   sort(v.begin(), v.end(), compare);
   // Print the strings after sorting
   for (auto x : v)
   cout << x << " ";
}
programming india science hello computer
numpy string operations | rjust() function - GeeksforGeeks

05 Feb, 2019
numpy.core.defchararray.rjust(arr, width, fillchar=' ') is another function for doing string operations in numpy. It returns an array with the elements of arr right-justified in a string of length width.It fills remaining space of each array element using fillchr parameter.If fillchr is not passed then it fills remaining spaces with blank space.
Parameters:arr : array_like of str or unicode.Input array.width : The final width of the each string .fillchar : The character to fill in remaining space.
Returns : [ndarray] Output right justified array of str or unicode, depending on input type.
Code #1 :
# Python program explaining# numpy.char.rjust() method   # importing numpy import numpy as geek  # input array  in_arr = geek.array(['Numpy', 'Python', 'Pandas'])print ("Input array : ", in_arr)   # setting the width of each string to 8width = 8  # output array when fillchar is not passedout_arr = geek.char.rjust(in_arr, width)print ("Output right justified array: ", out_arr) 
Input array :  ['Numpy' 'Python' 'Pandas']
Output right justified array:  ['   Numpy' '  Python' '  Pandas']

 
Code #2 :
# Python program explaining# numpy.char.rjust() method   # importing numpy import numpy as geek  # input array  in_arr = geek.array(['Numpy', 'Python', 'Pandas'])print ("Input array : ", in_arr)   # setting the width of each string to 8width = 8  # output array out_arr = geek.char.rjust(in_arr, width, fillchar ='*')print ("Output right justified array: ", out_arr) 
Input array :  ['Numpy' 'Python' 'Pandas']
Output right justified array:  ['***Numpy' '**Python' '**Pandas']

 
Code #3 :
# Python program explaining# numpy.char.rjust() method   # importing numpy import numpy as geek  # input array  in_arr = geek.array(['1', '11', '111'])print ("Input array : ", in_arr)  # setting the width of each string to 5width = 5  # output arrayout_arr = geek.char.rjust(in_arr, width, fillchar ='-')print ("Output right justified array: ", out_arr) 
Input array :  ['1' '11' '111']
Output right justified array:  ['----1' '---11' '--111']

Python numpy-String Operation
Python-numpy
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
*args and **kwargs in Python
How to call a function after a delay in Kotlin?

Kotlin is based on Java, hence we can use Java-based library functions to delay a function call. In this article, we will be using a Java library function to delay the function call using Timer() and schedule().
import java.util.Timer
import kotlin.concurrent.schedule

fun main(args: Array<String>) {

   // Execution starting point
   println("Hello world!!")

   // Delay of 5 sec
   Timer().schedule(5000){

      //calling a function
      newMethod()
   }
}

fun newMethod(){
   println("Delayed method call!")
}
Once executed, the above piece of code will yield the following output −
Hello world!!
Delayed method call!
Java Image Translation example using OpenCV.

The warpAffine() method of the Imgproc class applies an affine transformation to the specified image. This method accepts −
Three Mat objects representing the source, destination, and transformation
matrices.
Three Mat objects representing the source, destination, and transformation
matrices.
An integer value representing the size of the output image.
An integer value representing the size of the output image.
To translate an image Create a translation matrix and pass it as a transformation matrix to this method along with the other parameters.
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class TranslatingAnImage extends Application {
   public void start(Stage stage) throws IOException {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading image data
      String file ="D:\\Images\\elephant.jpg";
      Mat src = Imgcodecs.imread(file);
      //Creating destination matrix
      Mat dst = new Mat(src.rows(), src.cols(), src.type());
      Point p1 = new Point( 0,0 );
      Point p2 = new Point( src.cols() - 1, 0 );
      Point p3 = new Point( 0, src.rows() - 1 );
      Point p4 = new Point( src.cols()*0.0, src.rows()*0.33 );
      Point p5 = new Point( src.cols()*0.85, src.rows()*0.25 );
      Point p6 = new Point( src.cols()*0.15, src.rows()*0.7 );
      MatOfPoint2f ma1 = new MatOfPoint2f(p1,p2,p3);
      MatOfPoint2f ma2 = new MatOfPoint2f(p4,p5,p6);
      //Creating the transformation matrix
      Mat tranformMatrix = Imgproc.getAffineTransform(ma1,ma2);
      //Creating object of the class Size
      Size size = new Size(src.cols(), src.cols());
      //Applying Wrap Affine
      Imgproc.warpAffine(src, dst, tranformMatrix, size);
      //Converting matrix to JavaFX writable image
      Image img = HighGui.toBufferedImage(dst);
      WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);
      //Setting the image view
      ImageView imageView = new ImageView(writableImage);
      imageView.setX(10);
      imageView.setY(10);
      imageView.setFitWidth(575);
      imageView.setPreserveRatio(true);
      //Setting the Scene object
      Group root = new Group(imageView);
      Scene scene = new Scene(root, 595, 400);
      stage.setTitle("Image Translation example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]) {
      launch(args);
   }
}
On executing the above program generates the following output −
Python – Group and calculate the sum of column values of a Pandas DataFrame

We will consider an example of Car Sale Records and group month-wise to calculate the sum of Registration Price of car monthly. To sum, we use the sum() method.
At first, let’s say the following is our Pandas DataFrame with three columns −
dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW", "Toyota", "Nissan", "Bentley", "Mustang"],

      "Date_of_Purchase": [
         pd.Timestamp("2021-06-10"),
         pd.Timestamp("2021-07-11"),
         pd.Timestamp("2021-06-25"),
         pd.Timestamp("2021-06-29"),
         pd.Timestamp("2021-03-20"),
         pd.Timestamp("2021-01-22"),
         pd.Timestamp("2021-01-06"),
         pd.Timestamp("2021-01-04"),
         pd.Timestamp("2021-05-09")
      ],

      "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
   }
)


Use the Grouper to select Date_of_Purchase column within groupby() function. The frequency freq is set ‘M’ to group by month-wise and sum is calculates using the sum() function −
print"\nGroup Dataframe by month...\n",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='M')).sum()
Following is the code −
import pandas as pd

# dataframe with one of the columns as Date_of_Purchase
dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW", "Toyota", "Nissan", "Bentley", "Mustang"],

      "Date_of_Purchase": [
         pd.Timestamp("2021-06-10"),
         pd.Timestamp("2021-07-11"),
         pd.Timestamp("2021-06-25"),
         pd.Timestamp("2021-06-29"),
         pd.Timestamp("2021-03-20"),
         pd.Timestamp("2021-01-22"),
         pd.Timestamp("2021-01-06"),
         pd.Timestamp("2021-01-04"),
         pd.Timestamp("2021-05-09")
      ],

      "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
   }
)

print"DataFrame...\n",dataFrame

# Grouper to select Date_of_Purchase column within groupby function
# calculation the sum month-wise
print"\nGroup Dataframe by month...\n",dataFrame.groupby(pd.Grouper(key='Date_of_Purchase', axis=0, freq='M')).sum()


This will produce the following output −
DataFrame...
        Car   Date_of_Purchase   Reg_Price
0      Audi        2021-06-10        1000
1     Lexus        2021-07-11        1400
2     Tesla        2021-06-25        1100
3  Mercedes        2021-06-29         900
4       BMW        2021-03-20        1700
5    Toyota        2021-01-22        1800
6    Nissan        2021-01-06        1300
7   Bentley        2021-01-04        1150
8   Mustang        2021-05-09        1350

Group Dataframe by month...
                   Reg_Price
Date_of_Purchase
2021-01-31           4250.0
2021-02-28              NaN
2021-03-31           1700.0
2021-04-30              NaN
2021-05-31           1350.0
2021-06-30           3000.0
2021-07-31           1400.0
CTR Full Form - GeeksforGeeks

29 Dec, 2020
CTR stands for click-through rate. It is a metric that measures the number of clicks advertisers receive on their ads per number of impressions. A ratio showing how often people who see your ad end up clicking it. Clickthrough rate (CTR) can be used to gauge how well your keywords and ads are performing.
Formula : CTR is the number of clicks that your ad receives divided by the number of times your ad is shown: clicks ÷ impressions = CTR.For example, if you had 5 clicks and 100 impressions, then your CTR would be 5%.
In short,
CTR = ( Total Measured Ad Impressions / Total Measured Clicks ) × 100 
​Benefits of High CTR :
Organic Search Positions Get A Boost
Conversion Rates Increase
Much Higher Ad Impression Share
Free Clicks From Social Ads
More people seeing, opening and engaging with owner’s emails
Good Click-Through Rate Examples :
Facebook Ad click-through rates range from 0.5% to 1.6%.
For paid digital ads, Wordstream reported that the average Adwords click-through rate is 1.91% on search and 0.35% on display.
Importance of CTR :
Without a high CTR, one’s ads aren’t operating at peak performance.
Low CTRs can increase the cost of one’s ads.
Low CTRs can make it harder for one’s ads to show up.
Conclusion of CTR :Your click-through rates are typically a litmus test for how your web campaigns are performing. Low click-through rates indicates that something’s not right. By segmenting your audience, speaking to their needs with effective headlines and ad copy, and using emojis to show your more laid-back side, you could see a significant boost to your click-through rates.
Once your ads, emails, and organic listings are targeted and dressed up for a boost in CTRs, your campaigns will improve and your conversions should also rise in kind.
Technical Scripter 2020
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advantages and Disadvantages of OOP
Lex Program to count number of words
Consensus Algorithms in Blockchain
Challenges in Internet of things (IoT)
Election algorithm and distributed processing
Spatial Filtering and its Types
Characteristics of Internet of Things
Bubble Sort algorithm using JavaScript
Activation Functions
Introduction to Parallel Computing
Input/Output from external file in C/C++, Java and Python for Competitive Programming

In this article, we will learn about Input/Output from an external files in C/C++, Java, and Python for Competitive Programming.
In python, the sys module is used to take input from a file and write output to the file. Let’s look at the implementation in the form of code.
import sys
# For getting input
sys.stdin = open('sample.txt', 'r')
# Printing the Output
sys.stdout = open('sample.txt', 'w')
Here we take the help of buffered reader method to take input associated with file reader to read input from file and print writer to print the data back to the file.
// Java program For handling Input/Output
import java.io.*;
class Input {
   public static void main(String[] args) throws IOException {
      BufferedReader br = new BufferedReader(new
      FileReader("sampleinp.txt"));
      PrintWriter pw=new PrintWriter(new
      BufferedWriter(new
      FileWriter("sampleout.txt")));
      pw.flush();
   }
}
Here we take the help of free open() function and define the mode in which we want to open the file and what kind of operation we want to perform. By default mode is set to read-only
#include<stdio.h>
int main() {
   // For getting input
   freopen("sampleinp.txt", stdin);
   // Printing the Output
   freopen("sampleout.txt", "w", stdout);
   return 0;
}
In this tutorial, we will learn about Input/Output from an external files in C/C++, Java, and Python for Competitive Programming.
How to create a process in Linux?

A program loaded into memory and executing is called a process. In simple, a process is a program in execution.
A new process can be created by the fork() system call. The new process consists of a copy of the address space of the original process. fork() creates new process from existing process. Existing process is called the parent process and the process is created newly is called child process. The function is called from parent process. Both the parent and the child processes continue execution at the instruction after the fork(), the return code for the fork() is zero for the new process, whereas the process identifier of the child is returned to the parent.
Fork() system call is situated in <sys/types.h> library.
System call getpid() returns the Process ID of the current process and getppid() returns the process ID of the current process’s parent process.
Let’s take an example how to create child process using fork() system call.
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
int main( ){
   pid_t child_pid;
   child_pid = fork (); // Create a new child process;
   if (child_pid < 0) {
      printf("fork failed");
      return 1;
   } else if (child_pid == 0) {
      printf ("child process successfully created!\n");
      printf ("child_PID = %d,parent_PID = %d\n",
      getpid(), getppid( ) );
   } else {
      wait(NULL);
      printf ("parent process successfully created!\n");
      printf ("child_PID = %d, parent_PID = %d", getpid( ), getppid( ) );
   }
   return 0;
}
child process successfully created!
child_PID = 31497, parent_PID = 31496
parent process successfully created!
child_PID = 31496, parent_PID = 31491
Here, getppid() in the child process returns the same value as getpid() in the parent process.
pid_t is a data type which represents the process ID. It is created for process identification. Each process has a unique ID number. Next, we call the system call fork() which will create a new process from calling process. Parent process is the calling function and a new process is a child process. The system call fork() is returns zero or positive value if the process is successfully created.
jsoup - Loading from File

Following example will showcase fetching an HTML from the disk using a file and then find its data.
String url = "http://www.google.com";
Document document = Jsoup.connect(url).get();

Where
document − document object represents the HTML DOM.
document − document object represents the HTML DOM.
Jsoup − main class to connect the url and get the HTML String.
Jsoup − main class to connect the url and get the HTML String.
url − url of the html page to load.
url − url of the html page to load.
The connect(url) method makes a connection to the url and get() method return the html of the requested url.
Create the following java program using any editor of your choice in say C:/> jsoup.
JsoupTester.java
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class JsoupTester {
   public static void main(String[] args) throws IOException, URISyntaxException {
      
      URL path = ClassLoader.getSystemResource("test.htm");
      File input = new File(path.toURI());
      Document document = Jsoup.parse(input, "UTF-8");
      System.out.println(document.title());
   }
}
test.htm
Create following test.htm file in C:\jsoup folder.
<html>
   <head>
      <title>Sample Title</title>
   </head>
   <body>
      <p>Sample Content</p>
   </body>
</html>
Compile the class using javac compiler as follows:
C:\jsoup>javac JsoupTester.java

Now run the JsoupTester to see the result.
C:\jsoup>java JsoupTester

See the result.
Sample Title

 Print
 Add Notes
 Bookmark this page