code-rag-bench/online-tutorials huggingface dataset:
Java Guava | Chars.contains() method with Examples

31 Jan, 2019
The contains() method of Chars Class in Guava library is used to check if a specified value is present in the specified array of char values. The char value to be searched and the char array in which it is to be searched, are both taken as a parameter.
Syntax:
public static boolean contains(char[] array, 
                               char target)

Parameters: This method accepts two mandatory parameters:
array: which is an array of char values in which the target value is to be searched.
target: which is the char value to be searched for presence in the array.
Return Value: This method returns a boolean value stating whether the target char value is present in the specified char array. It returns True if the target value is present in the array. Else it returns False.
Below programs illustrate the use of contains() method:
Example 1:
// Java code to show implementation of// Guava's Chars.contains() method  import com.google.common.primitives.Chars;import java.util.Arrays;  class GFG {      // Driver's code    public static void main(String[] args)    {          // Creating a character array        char[] arr = { 'g', 'e', 'e', 'k', 's' };          char target = 'k';          // Using Chars.contains() method to search        // for an element in the array. The method        // returns true if element is found, else        // returns false        if (Chars.contains(arr, target))            System.out.println("Target is present"                               + " in the array");        else            System.out.println("Target is not present"                               + " in the array");    }}
Target is present in the array

Example 2:
// Java code to show implementation of// Guava's Chars.contains() method  import com.google.common.primitives.Chars;import java.util.Arrays;  class GFG {      // Driver's code    public static void main(String[] args)    {          // Creating a character array        char[] arr = { 'g', 'e', 'e', 'k', 's' };          char target = 'a';          // Using Chars.contains() method to search        // for an element in the array. The method        // returns true if element is found, else        // returns false        if (Chars.contains(arr, target))            System.out.println("Target is present"                               + " in the array");        else            System.out.println("Target is not present"                               + " in the array");    }}
Target is not present in the array

Reference: https://google.github.io/guava/releases/18.0/api/docs/com/google/common/primitives/Chars.html#contains(char[], %20char)
Guava-Chars
Guava-Functions
Java-Functions
java-guava
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
OUT a8 instruction in 8085 Microprocessor

In 8085 Instruction set, OUT is a mnemonic that stands for OUTput Accumulator contents to an output port whose8-bit address is indicated in the instruction as a8. It occupies 2 Bytes in the memory. First Byte specifies the opcode, and the next Byte provides the 8-bit port address. 
OUT F0H is an example instruction of this type. The result of execution of this instruction is shown below with an example.
OUT instruction is the only instruction using whichAccumulator contents can be sent out to an output port. A possible chip select circuit to connect an output port with an address as F0His as shown in the following Fig.
Chip select circuit for output port F0H
Here as the port address is F0H so the bits ranging from A7 to A0 should have the bit pattern
A7 A6 A5 A4 A3 A2 A1 A0 =1 1 1 1  0 0 0 0, with WR* = 0, and IO/M* = 1
A7 A6 A5 A4 A3 A2 A1 A0 =1 1 1 1  0 0 0 0, with WR* = 0, and IO/M* = 1
All these bits will pass through a NAND Gate to product the output logic 1 as Chip-Select (CS), and so the output port chip gets selected. Thus, the chip responds when the 8085 sends out the address as F0H, IO/M* as 1, and WR* as 0. In other words, we consider that it is having the output port number F0H.
Notice that it is possible to have an input port with the address F0H, and an output port with the same address F0H. When the 8085 sends out the address as EFH and IO/M* as 1, only one of them is selected based on the RD* and WR* signal status values. Thus, it is possible to have a total of 256 input ports and a total of 256output ports.
The timing diagram against this instruction OUT F0H execution is as follows –
Summary − So this instruction OUT requires 2-Bytes, 3-Machine Cycles (Opcode Fetch, Memory Read, I/O write) and 10 T-States for execution as shown in the timing diagram.
CICS - Nohandle

Nohandle can be specified for any CICS command. It will cause no action to be taken for any exceptional conditions that may occur during the execution of the CICS command. This command temporarily deactivates all the other handle conditions. If an exception arises during the execution of the command, the control will be transferred to the next statement after the Command. It can be used with Read, Write, Delete, etc. The syntax of Nohandle is as follows −
EXEC CICS
   program statements
   NOHANDLE    
END-EXEC.

Following is the example of Nohandle command. We are using it with a Read statement. If Read statement fails, it will not abend the program.
IDENTIFICATION DIVISION.                                         
PROGRAM-ID. HELLO.                                               
PROCEDURE DIVISION.
EXEC CICS READ   
   FILE('FILE1')                
   INTO(WS-FILE-REC)             
   RIDFLD(WS-STDID)             
   NOHANDLE                          
END-EXEC. 
 Print
 Add Notes
 Bookmark this page
What is -551 error code in DB2? How will you resolve it?

When we get -551 in the SQLCODE then there is some privilege level issue. It signifies that the user does not have access to the database/tablespace/view/table that he is trying to access. As per the IBM documentation -551 SQLCODE states that.
-551 auth-id DOES NOT HAVE THE PRIVILEGE TO PERFORM OPERATION operation ON OBJECT object-name
There are DCL (Data control language) statements which are used by DBAs in order to control the access on DB2 objects. We can raise a request with DBA to provide access to the particular object for which user is getting -551 SQLCODE.
Following DCL statement will give access to user id Z5564 to execute PLAN ORDERPLAN:
GRANT EXECUTE ON PLAN ORDERPLAN TO Z5564
In a practical scenario, the access on DB2 objects such as PLAN, TABLES, VIEWS, etc., is given at RACF level rather than at user level. RACF stands for Resource Access Control Facility which is a Z/OS security management product used for providing access control and auditing purposes.
The RACF contains its own database having different RACF groups. Each user in the mainframe will be assigned to a RACF group.
For example, there are 3 departments in an organization: SALES, MARKETING, WARRANTY. So, 3 RACF groups can be created for each department and each RACF group has employee user ids for respective employees. The access to DB2 can be given based on RACF groups. So the SALES group can have access to ORDERS, TRANSACTIONS table. The MARKETING group can have access to DEALERS and INCENTIVE table and WARRANTY group can have access to PRODUCTS and VENDORS table.
If the user from one RACF group will try to access the table assigned for a different group, then the user will get -551 DB2 error code.
Java Examples - Display different shapes

How to display different shapes using GUI?
Following example demonstrates how to display different shapes using Arc2D, Ellipse2D, Rectangle2D, RoundRectangle2D classes.
import java.awt.Shape;
import java.awt.geom.*;

public class Main {
   public static void main(String[] args) {
      int x1 = 1, x2 = 2, w = 3, h = 4, 
      x = 5, y = 6, 
	   y1 = 1, y2 = 2, start = 3;
      
      Shape line = new Line2D.Float(x1, y1, x2, y2);
      Shape arc = new Arc2D.Float(x, y, w, h, start, 1, 1);
      Shape oval = new Ellipse2D.Float(x, y, w, h);
      Shape rectangle = new Rectangle2D.Float(x, y, w, h);
      Shape roundRectangle = new RoundRectangle2D.Float (x, y, w, h, 1, 2);
      System.out.println("Different shapes are created:");
   }
}
The above code sample will produce the following result.
Different shapes are created.

 Print
 Add Notes
 Bookmark this page
Java Examples - Thread completion

How to check a thread has stopped or not ?
Following example demonstrates how to check a thread has stop or not by checking with isAlive() method.
public class Main {
   public static void main(String[] argv)throws Exception { 
      Thread thread = new MyThread();
      thread.start();
      
      if (thread.isAlive()) {
         System.out.println("Thread has not finished");
      } else {
         System.out.println("Finished");
      }
      long delayMillis = 5000; 
      thread.join(delayMillis);
      
      if (thread.isAlive()) {
         System.out.println("thread has not finished");
      } else {
         System.out.println("Finished");
      }
      thread.join();
   }
}
class MyThread extends Thread {
   boolean stop = false;
   public void run() {
      while (true) {
         if (stop) {
            return;
         }
      }
   }
}
The above code sample will produce the following result.
Thread has not finished
Finished

 Print
 Add Notes
 Bookmark this page
Can we declare a top level class as protected or private in Java?


No, we cannot declare a top-level class as private or protected. It can be either public or default (no modifier). If it does not have a modifier, it is supposed to have a default access.
// A top level class
   public class TopLevelClassTest {
      // Class body
}
If a top-level class is declared as private the compiler will complain that the modifier private is not allowed here. This means that a top-level class cannot be a private, the same can be applied to protected access specifier also.
Protected means that the member can be accessed by any class in the same package and by subclasses even if they are in another package.
The top-level classes can only have public, abstract and final modifiers, and it is also possible to not define any class modifiers at all. This is called default/package accessibility.
We can declare the inner classes as private or protected, but it is not allowed in outer
classes.
More than one top-level class can be defined in a Java source file, but there can be at most one public top-level class declaration. The file name must match the name of the public class.
Live Demo
protected class ProtectedClassTest {
   int i = 10;
   void show() {
      System.out.println("Declare top-level class as protected");
   }
}
public class Test {
   public static void main(String args[]) {
      ProtectedClassTest pc = new ProtectedClassTest();
      System.out.println(pc.i);
      pc.show();
      System.out.println("Main class declaration as public");
   }
}
In the above example, we can declare the class as protected, it will throw an error says that modifier protected not allowed here. So the above code doesn't execute.
modifier protected not allowed here
Live Demo
private class PrivateClassTest {
   int x = 20;
   void show() {
      System.out.println("Declare top-level class as private");
   }
}
public class Test {
   public static void main(String args[]) {
      PrivateClassTest pc = new PrivateClassTest();
      System.out.println(pc.x);
      pc.show();
      System.out.println("Main class declaration as public");
   }
}
In the above example, we can declare the class as private, it will throw an error says that modifier private not allowed here. So the above code doesn't execute.
modifier private not allowed here
PHP Closure class

Anonymous functions (also called lambda) return object of Closure class. This class has some additional methods that provide further control over anonymous functions.
Closure {
   /* Methods */
   private __construct ( void )
   public static bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] ) : Closure
   public bindTo ( object $newthis [, mixed $newscope = "static" ] ) : Closure
   public call ( object $newthis [, mixed $... ] ) : mixed
   public static fromCallable ( callable $callable ) : Closure
}
private Closure::__construct ( void ) — This method exists only to disallow instantiation of the Closure class. Objects of this class are created by anonymous function.
public static Closure::bind ( Closure closure,objectnewthis [, mixed $newscope = "static" ] ) − Closure — Duplicates a closure with a specific bound object and class scope. This method is a static version of Closure::bindTo().
public Closure::bindTo ( object newthis[,mixednewscope = "static" ] ) − Closure — Duplicates the closure with a new bound object and class scope. Creates and returns a new anonymous function with the same body and bound variables, but with a different object and a new class scope.
public Closure::call ( object newthis[,mixed... ] ) − mixed — Temporarily binds the closure to newthis, and calls it with any given parameters.
 Live Demo
<?php
class A {
   public $nm;
   function __construct($x){
      $this->nm=$x;
   }
}
// Using call method
$hello = function() {
   return "Hello " . $this->nm;
};
echo $hello->call(new A("Amar")). "\n";;
// using bind method
$sayhello = $hello->bindTo(new A("Amar"),'A');
echo $sayhello();
?>
Above program shows following output
Hello Amar
Hello Amar
Passing Drop Down Box Data to CGI Program in Python

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

15 Jul, 2020
this keyword represents an implicit object pointing to the current class object. It refers to the current instance of the class in a method or constructor. The this keyword is mainly used to eliminate the ambiguity between class attributes and parameters with the same name. When the class attributes and the parameter names are the same this keyword is used to avoid ambiguity by prefixing class attributes with this keyword. this keyword can be used to refer to any member of the current object from within an instance method or a constructor
It can be used to refer to the instance variable of the current classIt can be used to make or Initiate current class constructorIt can be passed as an argument in the method callIt can be passed as an argument in the constructor callIt can be used to make a current class methodIt can be used to return the current class Instance
It can be used to refer to the instance variable of the current class
It can be used to make or Initiate current class constructor
It can be passed as an argument in the method call
It can be passed as an argument in the constructor call
It can be used to make a current class method
It can be used to return the current class Instance
Example 1: The following example shows the use of this keyword 
Dart
// Dart program to illustrate// this keyword void main(){  Student s1 = new Student('S001');}  class Student{  // defining local st_id variable  var st_id;  Student(var st_id)  {    // using this keyword    this.st_id = st_id;    print("GFG - Dart THIS Example");    print("The Student ID is : ${st_id}");  }}
 
Output:
Example 2:
Dart
// Dart program to illustrate// this keyword void main() {    mob m1 = new mobile('M101'); }  class mob {    String mobile;    Car(String mobile) {              // use of this keyword      this.mobile = mobile;       print("The mobile is : ${mobile}");    } }
 
Output:
The mobile is : M101

Dart-Keywords
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
What is widgets in Flutter?
Flutter - Custom Bottom Navigation Bar
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - Google Sign in UI and Authentication
Difference Between Stateless and Stateful Widget in Flutter
Dart - Null Aware Operators
Format Dates in Flutter
Flutter - SilverAppBar Widget
Flutter - Staggered Grid View
Dart Programming - Map.remove() Function

Removes key and its associated value, if present, from the map. The function also returns the value associated with the key.
Map.remove(Object key) 

Keys − identifies the entry to be deleted.
Keys − identifies the entry to be deleted.
Return Type − Returns the value corresponding to the specified key.
void main() { 
   Map m = {'name':'Tom','Id':'E1001'}; 
   print('Map :${m}'); 
   
   dynamic res = m.remove('name'); 
   print('Value popped from the Map :${res}'); 
} 
It will produce the following output −
Map :{name: Tom, Id: E1001} 
Value popped from the Map :Tom  


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Python – List Elements Grouping in Matrix

When it is required to list elements grouping in a matrix, a simple iteration, the ‘pop’ method, list comprehension and ‘append’ methods are used.
Below is a demonstration of the same −
my_list = [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]

print("The list is :")
print(my_list)

check_list = [14, 12, 41, 62]
print("The list is :")
print(check_list)

my_result = []
while my_list:

   sub_list_1 = my_list.pop()

   sub_list_2 = [element for element in check_list if element not in sub_list_1]
   try:

      my_list.remove(sub_list_2)

      my_result.append([sub_list_1, sub_list_2])
   except ValueError:

      my_result.append(sub_list_1)

print("The result is :")
print(my_result)
The list is :
[[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]
The list is :
[14, 12, 41, 62]
The result is :
[[[41, 14], [12, 62]], [78, 87], [51, 23], [14, 62]]
A list of list of integers is defined and is displayed on the console.
A list of list of integers is defined and is displayed on the console.
Another list of integers is defined and displayed on the console.
Another list of integers is defined and displayed on the console.
An empty list is defined.
An empty list is defined.
A simple iteration is used, and the top most element is popped using ‘pop’ method.
A simple iteration is used, and the top most element is popped using ‘pop’ method.
This is assigned to a variable ‘sub_list_1’.
This is assigned to a variable ‘sub_list_1’.
A list comprehension is used to iterate over the second list, and check if element is not there in ‘sub_list_1’.
A list comprehension is used to iterate over the second list, and check if element is not there in ‘sub_list_1’.
The ‘try’ and ‘except’ block is used to append specific elements to the empty list.
The ‘try’ and ‘except’ block is used to append specific elements to the empty list.
This list is displayed as the output on the console.
This list is displayed as the output on the console.
How to position text to bottom right on an image with CSS

To position text to bottom left, use the bottom and right property. You can try to run the following code to position text to bottom right on an image:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .box {
            position: relative;
         }
         img {
            width: 100%;
            height: auto;
            opacity: 0.6;
         }
         .direction {
            position: absolute;
            bottom: 10px;
            right: 19px;
            font-size: 13px;
         }
      </style>
   </head>
   <body>
      <h1>Heading One</h1>
      <p>Below image has text in the bottom right:</p>
      <div class = "box">
         <img src = "https://www.tutorialspoint.com/python/images/python_data_science.jpg" alt = "Tutorial" width = "800" height = "400">
         <div class = "direction">Bottom Right Corner</div>
      </div>
   </body>
</html>
Java 16 - Sealed Classes

Java 15 introduces a sealed classes as preview feature which provides a fine grained control over inheritance. Java 16 provides some minor enhancements and keep this feature as Preview. Following are salient points to consider for a sealed class −
Sealed class is declared using sealed keyword.
Sealed class is declared using sealed keyword.
Sealed classes allow to declare which class can be a subtype using permits keyword.
Sealed classes allow to declare which class can be a subtype using permits keyword.
A class extending sealed class must be declared as either sealed, non-sealed or final.
A class extending sealed class must be declared as either sealed, non-sealed or final.
Sealed classes helps in creating a finite and determinable hiearchy of classes in inheritance.
Sealed classes helps in creating a finite and determinable hiearchy of classes in inheritance.
Consider the following example −
ApiTester.java
public class APITester {
   public static void main(String[] args) {
      Person manager = new Manager(23, "Robert");
      manager.name = "Robert";
      System.out.println(getId(manager));
   }
   public static int getId(Person person) {
      if (person instanceof Employee) {
         return ((Employee) person).getEmployeeId();
      } 
      else if (person instanceof Manager) {
         return ((Manager) person).getManagerId();
      }
      return -1;
   }
}
abstract sealed class Person permits Employee, Manager {
   String name;
   String getName() {
      return name;
   }
}
final class Employee extends Person {
   String name;
   int id;
   Employee(int id, String name){
      this.id = id;
      this.name = name;
   }
   int getEmployeeId() {
      return id;
   }
}
non-sealed class Manager extends Person {
   int id;
   Manager(int id, String name){
      this.id = id;
      this.name = name;
   }
   int getManagerId() {
      return id;
   }
}
$javac -Xlint:preview --enable-preview -source 16 APITester.java
$java --enable-preview APITester

23


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
On/Off Toggle Button Switch in Tkinter

Tkinter provides features for adding different kinds of widgets necessary for an
application. Some of these widgets are: Button widget, Entry Widget, Text Box, Slider,
etc. In this article, we will see how we can create an application with a button such that it can either be on or off.
In this example, we will use these two buttons for demonstration,
Switch On
Switch On
Switch Off
Switch Off
# Import tkinter in the notebook
from tkinter import *

# Create an instance of window of frame
win =Tk()

# set Title
win.title('On/Off Demonstration')

# Set the Geometry
win.geometry("600x400")
win.resizable(0,0)
#Create a variable to turn on the button initially
is_on = True

# Create Label to display the message
label = Label(win,text = "Night Mode is On",bg= "white",fg ="black",font =("Poppins bold", 22))
label.pack(pady = 20)

# Define our switch function
def button_mode():
   global is_on
   
   #Determine it is on or off
   if is_on:
      on_.config(image=off)
      label.config(text ="Day Mode is On",bg ="white", fg= "black")
      is_on = False
   else:
      on_.config(image = on)
      label.config(text ="Night Mode is On", fg="black")
      is_on = True

# Define Our Images
on = PhotoImage(file ="on.png")
off = PhotoImage(file ="off.png")

# Create A Button
on_= Button(win,image =on,bd =0,command = button_mode)
on_.pack(pady = 50)

#Keep Running the window
win.mainloop()
Running the above code will create a Button to operate on/off mode.
If you click the button, it will change as follows −
Add week to current date using Calendar.add() method in Java

Import the following package for Calendar class in Java
import java.util.Calendar;
Firstly, create a Calendar object and display the current date and time
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date and Time = " + calendar.getTime());
Now, let us increment the weeks using the calendar.add() method and Calendar.WEEK_OF_YEAR constant.
calendar.add(Calendar.WEEK_OF_YEAR, 2);
The following is an example
 Live Demo
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance();
      System.out.println("Current Date = " + calendar.getTime());
      // Adding 2 weeks
      calendar.add(Calendar.WEEK_OF_YEAR, 2);
      System.out.println("Updated Date = " + calendar.getTime());
   }
}
Current Date = Thu Nov 22 18:13:38 UTC 2018
Updated Date = Thu Dec 06 18:13:38 UTC 2018
How to make two histograms have the same bin width in Matplotlib?

To make two histograms having same bin width, we can compute the histogram of a set of data.
Create random data, a, and normal distribution, b.
Create random data, a, and normal distribution, b.
Initialize a variable, bins, for the same bin width.
Initialize a variable, bins, for the same bin width.
Plot a and bins using hist() method.
Plot a and bins using hist() method.
Plot b and bins using hist() method.
Plot b and bins using hist() method.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
a = np.random.random(100) * 0.5
b = 1 - np.random.normal(size=100) * 0.1
bins = 10
bins = np.histogram(np.hstack((a, b)), bins=bins)[1]
plt.hist(a, bins, edgecolor='black')
plt.hist(b, bins, edgecolor='black')
plt.show()
Aptitude - Percentages Online Quiz

Following quiz provides Multiple Choice Questions (MCQs) related to Percentages. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - Half of 1% written as a decimal is :
A - 0.005
B - 5
C - 0.5
D - 0.005
Half of 1% = (1⁄2 x 1⁄100)
= 0.5⁄100 = 0.005 %
Q 2 - If 120 is 20% of a number, then 120% of that number will be?
A - 120
B - 620
C - 720
D - 20
let z be the number.
Then, 20% of z = 120 i.e (20⁄100 x z) = 120
Therefore, z = 600
120% of z = (120⁄100 x 600) = 720
Q 3 - A batsman scored 110 runs which included 3 boundaries and 8 sixes. What percent of his total score did he make by running between the wickets?
A - 5⁄11%
B - 45%
C - 11 5⁄45%
D - 45 5⁄11%
Number of runs made by running = 110 - (3 x 4 + 8 x 6) = 50
Therefore, percentage = (50⁄100 x 100)% = 45 5⁄11%
Q 4 - If A = p% of q and B = q% of p, then which of the following is true?
A - A is smaller than B
B - A is greater than B
C - Relationship between A and B cannot be determined
D - A = B
p% of q = (p⁄100 x q) = (q⁄100 x p) = q% of p
→ A = B
Q 5 - The wheat production of a farmer increased from 180 quintals to 190 quintals. Find the percentage increase in production.
A - 4.56%
B - 5.00%
C - 5.50%
D - 5.56%
Increase =190-180=10
%Increase=(10/180)*100 = 5.56%
Q 6 - In a recent survey 40% houses contained 2 or more people. Of those houses containing only one person, 25% were having only a male. What is the percentage of all the houses which contain exactly one females and no males?
A - 75
B - 40
C - 15
D - 45
As per question, 40% houses contain two or more people.
i.e. 60% houses have only one person. O these houses 25% have male.
∴ 75% of 60% of the total houses have only one female and no males.
 = .75 * 60% = 45%
Q 7 - 50% of a number when added to 50, is equal to a number .the number is 
A - 100
B - 125
C - 140
D - 150
50 + 50% of x =x
x - 1/2x = 50
x=100
Q 8 - The population of a town is 176400. It increases annually at the rate of 5% p.a. What was it 2 years ago?
A - 160000
B - 260000
C - 360000
D - 460000
Population 2 years ago = 176400/(1+5/100)2 =(176400*20/21*20/21)=160000.
Q 9 - (9% of 386) * (6.5%  of 144) = ?
A - 328.0
B - 333.3
C - 340.1
D - 253.8
(9% of 386) * (6.5%  of 144) = 347.4 - 93.6 = 253.8
Q 10 - The population of a city increases at the rate of 4% per annum. There is additional annual increase of 1% due to influx of job seekers. The percentage increase in population after two years is:
A - 10
B - 10.25
C - 10.50
D - 10.75
Let the initial population be 100.
Total percentage change = 4 + 1 = 5%
∴ Population after 2 years = 100(1 + 5/100)2
= 100(21/20)2
= 441/4 = 110.25
∴ Percentage increase = 110.25 � 100 = 10.25%

    87 Lectures 
     22.5 hours 

 Programming Line
 Print
 Add Notes
 Bookmark this page
How to use the CAST function in a MySQL SELECT statement?

The CAST() function in MySQL converts a value of any type into a value that has a specified
type. Let us first create a table −
mysql> create table castFunctionDemo
   -> (
   -> ShippingDate date
   -> );
Query OK, 0 rows affected (0.74 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into castFunctionDemo values('2019-01-31');
Query OK, 1 row affected (0.20 sec)

mysql> insert into castFunctionDemo values('2018-07-12');
Query OK, 1 row affected (0.16 sec)

mysql> insert into castFunctionDemo values('2016-12-06');
Query OK, 1 row affected (0.16 sec)

mysql> insert into castFunctionDemo values('2017-08-25');
Query OK, 1 row affected (0.19 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from castFunctionDemo;
This will produce the following output −
+--------------+
| ShippingDate |
+--------------+
| 2019-01-31   |
| 2018-07-12   |
| 2016-12-06   |
| 2017-08-25   |
+--------------+
4 rows in set (0.00 sec)
Here is the query to use the cast() function correctly in a MySQL select statement −
mysql> select CAST(ShippingDate AS CHAR(12)) as Conversion FROM castFunctionDemo;
This will produce the following output −
+------------+
| Conversion |
+------------+
| 2019-01-31 |
| 2018-07-12 |
| 2016-12-06 |
| 2017-08-25 |
+------------+
4 rows in set (0.00 sec)
HTTP headers | Host - GeeksforGeeks

20 Nov, 2019
The HTTP Host represents the domain name of the server. It may also represent the Transmission Control Protocol (TCP) port number which the server uses. Defining the port number is optional, the default value is considered. For example, “80” is assigned as the port number for an HTTP URL when there is no port number specified. The HTTP Host header is a request type header. The host header field must be sent in all HTTP/1.1 request messages. If a request message does not have any header field or more than one header field, a 400 Bad Request is sent.
Syntax :
Host: <host>:<port>
Directives: The HTTP header Host accepts two directives mentioned above and described below:
<host>: This directive represents the domain name of the server.
<port>: This directive is an optional one. It represents the TCP port number in which the server is working.Note: You can check any website hoster in this link.Examples:Host for GeeksforGeeks cdn page.Host: www.cdn.geeksforgeeks.orgHost for GeeksforGeeks home page.Host: www.geeksforgeeks.orgSupported Browsers: The browsers compatible with HTTP Host header are listed below:Google ChromeInternet ExplorerEdgeMozilla FirefoxOperaSafariMy Personal Notes
arrow_drop_upSave
Note: You can check any website hoster in this link.Examples:
Host for GeeksforGeeks cdn page.Host: www.cdn.geeksforgeeks.org
Host: www.cdn.geeksforgeeks.org
Host for GeeksforGeeks home page.Host: www.geeksforgeeks.org
Host: www.geeksforgeeks.org
Supported Browsers: The browsers compatible with HTTP Host header are listed below:
Google Chrome
Internet Explorer
Edge
Mozilla Firefox
Opera
Safari
HTTP-headers
Picked
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
Difference between Definition and Declaration in Java.

For the difference between definition and declaration, one should consider their literal meaning first which includes Declare means to announce or proclaim while Define means to describe some entity.
The following are the important differences between the Definition and the Declaration.
JavaTester.java
 Live Demo
public class JavaTester{
   public static void main(String args[]){
      int a; // declaration of variable
      a=10; // definition of variable
      functionA(a); // declaration of function
   }
   public static void functionA(int a){
      System.out.println("value of a is " + a); // definition of function
   }
}
value of a is 10
How to get the size of an array within a nested JSON in Rest Assured?

We can get the size of an array within a nested JSON in Rest Assured. First, we shall obtain a Response body which is in JSON format from a request. Then convert it to string.
Finally, to obtain JSON array size, we have to use the size method. We shall send a GET request via Postman on a mock API, and observe the Response.
Using Rest Assured, let us get the size of the Location array within the nested JSON response. The size should be three since it contains information about three locations - Michigan, Indiana, and New York.
Code Implementation
import static io.restassured.RestAssured.given;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
public class NewTest {
   @Test
   public void jsonArySize() {

      //base URI with Rest Assured class
      RestAssured.baseURI = "https://run.mocky.io/v3";

      //obtain Response from GET request
      Response res = given()
      .when()
      .get("/8ec8f4f7-8e68-4f4b-ad18-4f0940d40bb7");

      //convert JSON to string
      JsonPath j = new JsonPath(res.asString());

      //length of JSON Location array
      int s = j.getInt("Location.size()");
      System.out.println("Array size of Location: " +s);
   }
}
How to count the total number of frames in OpenCV using C++?

We will learn how to calculate the total number of frames in OpenCV. Using OpenCV, it is elementary to count and show the total number of frames of a video. However, you have to store one thing in mind that we cannot count the total number of real-time video frames. Because a real-time video does not have a specific number of frames.
The following program counts the number of total frames and shows it in the console window.
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main() {
   int frame_Number;//Declaring an integervariable to store the number of total frames//
   VideoCapture cap("video.mp4");//Declaring an object to capture stream of frames from default camera//
   frame_Number = cap.get(CAP_PROP_FRAME_COUNT);//Getting the total number of frames//
   cout << "Total Number of frames are:" << frame_Number << endl;//Showing the number in console window//
   system("pause");//Pausing the system to see the result//
   cap.release();//Releasing the buffer memory//
   return 0;
}
As the output, we will get an integer value.
AWK - Basic Examples

This chapter describes several useful AWK commands and their appropriate examples. Consider a text file marks.txt to be processed with the following content −
1) Amit     Physics   80
2) Rahul    Maths     90
3) Shyam    Biology   87
4) Kedar    English   85
5) Hari     History   89

You can instruct AWK to print only certain columns from the input field. The following example demonstrates this −
[jerry]$ awk '{print $3 "\t" $4}' marks.txt
On executing this code, you get the following result −
Physics   80
Maths     90
Biology   87
English   85
History   89

In the file marks.txt, the third column contains the subject name and the fourth column contains the marks obtained in a particular subject. Let us print these two columns using AWK print command. In the above example, $3 and $4 represent the third and the fourth fields respectively from the input record.
By default, AWK prints all the lines that match pattern.
[jerry]$ awk '/a/ {print $0}' marks.txt
On executing this code, you get the following result −
2) Rahul    Maths     90
3) Shyam    Biology   87
4) Kedar    English   85
5) Hari     History   89

In the above example, we are searching form pattern a. When a pattern match succeeds, it executes a command from the body block. In the absence of a body block − default action is taken which is print the record. Hence, the following command produces the same result −
[jerry]$ awk '/a/' marks.txt
When a pattern match succeeds, AWK prints the entire record by default. But you can instruct AWK to print only certain fields. For instance, the following example prints the third and fourth field when a pattern match succeeds.
[jerry]$ awk '/a/ {print $3 "\t" $4}' marks.txt
On executing this code, you get the following result −
Maths    90
Biology  87
English  85
History  89

You can print columns in any order. For instance, the following example prints the fourth column followed by the third column.
[jerry]$ awk '/a/ {print $4 "\t" $3}' marks.txt
On executing the above code, you get the following result −
90   Maths
87   Biology
85   English
89   History

Let us see an example where you can count and print the number of lines for which a pattern match succeeded.
[jerry]$ awk '/a/{++cnt} END {print "Count = ", cnt}' marks.txt
On executing this code, you get the following result −
Count = 4

In this example, we increment the value of counter when a pattern match succeeds and we print this value in the END block. Note that unlike other programming languages, there is no need to declare a variable before using it.
Let us print only those lines that contain more than 18 characters.
[jerry]$ awk 'length($0) > 18' marks.txt
On executing this code, you get the following result −
3) Shyam   Biology   87
4) Kedar   English   85

AWK provides a built-in length  function that returns the length of the string. $0 variable stores the entire line and in the absence of a body block, default action is taken, i.e., the print action. Hence, if a line has more than 18 characters, then the comparison results true and the line gets printed.
 Print
 Add Notes
 Bookmark this page
Format date with DateFormat.SHORT in Java

DateFormat.SHORT is a constant for short style pattern.
Firstly, we will create date object
Date dt = new Date();
DateFormat dateFormat;
Let us format date for different locale with DateFormat.SHORT
// FRENCH
dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.FRENCH);
// GERMANY
dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);
The following is an example −
 Live Demo
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class Demo {
   public static void main(String args[]) {
      Date dt = new Date();
      DateFormat dateFormat;
// Date Format SHORT constant
      dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.FRENCH);
      System.out.println("Locale FRENCH = " + dateFormat.format(dt));
      dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);
      System.out.println("Locale GERMANY = " + dateFormat.format(dt));
      dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CHINESE);
      System.out.println("Locale CHINESE = " + dateFormat.format(dt));
      dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CANADA);
      System.out.println("Locale CANADA = " + dateFormat.format(dt));
      dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ITALY);
      System.out.println("Locale ITALY = " + dateFormat.format(dt));
      dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.TAIWAN);
      System.out.println("Locale TAIWAN = " + dateFormat.format(dt));
   }
}
Locale FRENCH = 22/11/18
Locale GERMANY = 22.11.18
Locale CHINESE = 18-11-22
Locale CANADA = 22/11/18
Locale ITALY = 22/11/18
Locale TAIWAN = 2018/11/22
Count set bits in an integer using Lookup Table - GeeksforGeeks

13 Apr, 2022
Write an efficient program to count number of 1s in binary representation of an integer.Examples  
Input : n = 6
Output : 2
Binary representation of 6 is 110 
and has 2 set bits

Input : n = 13
Output : 3
Binary representation of 11 is 1101 
and has 3 set bits
 
In the previous post we had seen different method that solved this problem in O(log n) time. In this post we solve in O(1) using lookup table. Here we assume that the size of INT is 32-bits. It’s hard to count all 32 bits in one go using lookup table (” because it’s infeasible to create lookup table of size 232-1 “). So we break 32 bits into 8 bits of chunks( How lookup table of size (28-1 ) index : 0-255 ).LookUp Table In lookup tale, we store count of set_bit of every number that are in a range (0-255) LookupTable[0] = 0 | binary 00000000 CountSetBits 0 LookupTable[1] = 1 | binary 00000001 CountSetBits 1 LookupTable[2] = 1 | binary 00000010 CountSetBits 1 LookupTable[3] = 2 | binary 00000011 CountSetBits 2 LookupTable[4] = 1 | binary 00000100 CountSetBits 1 and so...on upto LookupTable[255].Let’s take an Example How lookup table work. 
Let's number be : 354 
in Binary : 0000000000000000000000101100010

Split it into 8 bits chunks  :
In Binary  :  00000000 | 00000000 | 00000001 | 01100010
In decimal :     0          0          1         98

Now Count Set_bits using LookupTable
LookupTable[0] = 0
LookupTable[1] = 1
LookupTable[98] = 3

so Total bits count : 4 
 
CPP
// c++ count to count number of set bits// using lookup table in O(1) time #include <iostream>using namespace std; // Generate a lookup table for 32 bit integers#define B2(n) n, n + 1, n + 1, n + 2#define B4(n) B2(n), B2(n + 1), B2(n + 1), B2(n + 2)#define B6(n) B4(n), B4(n + 1), B4(n + 1), B4(n + 2) // Lookup table that store the reverse of each tableunsigned int lookuptable[256] = { B6(0), B6(1), B6(1), B6(2) }; // function countset Bits Using lookup table// ans return set bits countunsigned int countSetBits(int N){    // first chunk of 8 bits from right    unsigned int count = lookuptable[N & 0xff] +                          // second chunk from  right                         lookuptable[(N >> 8) & 0xff] +                                                   // third and fourth chunks                         lookuptable[(N >> 16) & 0xff] +                         lookuptable[(N >> 24) & 0xff];    return count;} int main(){    unsigned int N = 354;    cout << countSetBits(N) << endl;     return 0;}
Output:  
4 
Time Complexity : O(1) 
avtarkumar719
shobhitvjain
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Bit Tricks for Competitive Programming
Write an Efficient Method to Check if a Number is Multiple of 3
Check for Integer Overflow
Convert decimal fraction to binary number
Reverse actual bits of the given number
Builtin functions of GCC compiler
Hamming code Implementation in C/C++
Check if a Number is Odd or Even using Bitwise Operators
Python | Element repetition in list - GeeksforGeeks

26 Jan, 2019
Sometimes we require to add a duplicate value in the list for several different utilities. This type of application is sometimes required in day-day programming. Let’s discuss certain ways in which we add a clone of a number to its next position.
Method #1 : Using list comprehensionIn this method, we just iterate the loop twice for each value and add to the desired new list. This is just a shorthand alternative to the naive method.
# Python3 code to demonstrate # to perform element duplication# using list comprehension  # initializing list  test_list = [4, 5, 6, 3, 9]  # printing original listprint ("The original list is : " + str(test_list))  # using list comprehension# to perform element duplicationres = [i for i in test_list for x in (0, 1)]  # printing result print ("The list after element duplication " +  str(res))
Output :
The original list is : [4, 5, 6, 3, 9]
The list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]

 
Method #2 : Using reduce() + addWe can also use the reduce function to act the the function to perform the addition of a pair of similar numbers simultaneously in the list.
# Python3 code to demonstrate # to perform element duplication# using reduce() + addfrom operator import add  # initializing list  test_list = [4, 5, 6, 3, 9]  # printing original listprint ("The original list is : " + str(test_list))  # using reduce() + add# to perform element duplicationres = list(reduce(add, [(i, i) for i in test_list]))  # printing result print ("The list after element duplication " +  str(res))
Output :
The original list is : [4, 5, 6, 3, 9]
The list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]

 
Method #3 : Using itertools.chain().from_iterable()from_iterable function can also be used to perform this task of adding a duplicate. It just makes the pair of each iterated element and inserts it successively.
# Python3 code to demonstrate # to perform element duplication# using itertools.chain.from_iterable()import itertools  # initializing list  test_list = [4, 5, 6, 3, 9]  # printing original listprint ("The original list is : " + str(test_list))  # using itertools.chain.from_iterable()# to perform element duplicationres = list(itertools.chain.from_iterable([i, i] for i in test_list))  # printing result print ("The list after element duplication " +  str(res))
Output :
The original list is : [4, 5, 6, 3, 9]
The list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]

Python list-programs
python-list
Python
python-list
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
Horizontal stacked bar chart in Matplotlib

To plot stacked bar chart in Matplotlib, we can use barh() methods
Set the figure size and adjust the padding between and around the subplots.
Create a list of years, issues_addressed and issues_pending, in accordance with years.
Plot horizontal bars with years and issues_addressed data.
To make stacked horizontal bars, use barh() method with years, issues_pending and issues_addressed data
Place the legend on the plot.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

year = [2014, 2015, 2016, 2017, 2018, 2019]
issues_addressed = [10, 14, 0, 10, 15, 15]
issues_pending = [5, 10, 50, 2, 0, 10]

b1 = plt.barh(year, issues_addressed, color="red")

b2 = plt.barh(year, issues_pending, left=issues_addressed, color="yellow")

plt.legend([b1, b2], ["Completed", "Pending"], title="Issues", loc="upper right")

plt.show()