code-rag-bench/online-tutorials huggingface dataset:
Arduino - Water Detector / Sensor

Water sensor brick is designed for water detection, which can be widely used in sensing rainfall, water level, and even liquid leakage.
Connecting a water sensor to an Arduino is a great way to detect a leak, spill, flood, rain, etc. It can be used to detect the presence, the level, the volume and/or the absence of water. While this could be used to remind you to water your plants, there is a better Grove sensor for that. The sensor has an array of exposed traces, which read LOW when water is detected.
In this chapter, we will connect the water sensor to Digital Pin 8 on Arduino, and will enlist the very handy LED to help identify when the water sensor comes into contact with a source of water.
You will need the following components −
1 × Breadboard
1 × Arduino Uno R3
1 × Water Sensor
1 × led
1 × 330 ohm resistor
Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below.
Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking on New.
#define Grove_Water_Sensor 8 // Attach Water sensor to Arduino Digital Pin 8
#define LED 9 // Attach an LED to Digital Pin 9 (or use onboard LED)

void setup() {
   pinMode(Grove_Water_Sensor, INPUT); // The Water Sensor is an Input
   pinMode(LED, OUTPUT); // The LED is an Output
}

void loop() {
   /* The water sensor will switch LOW when water is detected.
   Get the Arduino to illuminate the LED and activate the buzzer
   when water is detected, and switch both off when no water is present */
   if( digitalRead(Grove_Water_Sensor) == LOW) {
      digitalWrite(LED,HIGH);
   }else {
      digitalWrite(LED,LOW);
   }
}
Water sensor has three terminals - S, Vout(+), and GND (-). Connect the sensor as follows −
Connect the +Vs to +5v on your Arduino board.
Connect S to digital pin number 8 on Arduino board.
Connect GND with GND on Arduino.
Connect LED to digital pin number 9 in Arduino board.
When the sensor detects water, pin 8 on Arduino becomes LOW and then the LED on Arduino is turned ON.
You will see the indication LED turn ON when the sensor detects water.

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
How to loop the program after an exception is thrown in java?

Read the inputs and perform the required calculations within a method. Keep the code that causes exception in try block and catch all the possible exceptions in catch block(s). In each catch block display the respective message and call the method again.
In the following example we have an array with 5 elements, we are accepting two integers from user representing positions in the array and performing division operation with them, if the integer entered representing the positions is more than 5 (length of the exception) an ArrayIndexOutOfBoundsException occurs and, if the position chosen for denominator is 4 which is 0 an ArithmeticException occurs.
We are reading values and calculating the result in a static method. We are catching these two exceptions in two catch blocks and in each block we are invoking the method after displaying the respective message.
import java.util.Arrays;
import java.util.Scanner;
public class LoopBack {
   int[] arr = {10, 20, 30, 2, 0, 8};
   public static void getInputs(int[] arr){
      Scanner sc = new Scanner(System.in);
      System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("Error: You have chosen position which is not in the array: TRY AGAIN");
         getInputs(arr);
      }catch(ArithmeticException e) {
         System.out.println("Error: Denominator must not be zero: TRY AGAIN");
         getInputs(arr);
      }
   }
   public static void main(String [] args) {
      LoopBack obj = new LoopBack();
      System.out.println("Array: "+Arrays.toString(obj.arr));
      getInputs(obj.arr);
   }
}
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
14
24
Error: You have chosen position which is not in the array: TRY AGAIN
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
3
4
Error: Denominator must not be zero: TRY AGAIN
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
0
3
Result of 10/2: 5
AJAX - Browser Support

All the available browsers cannot support AJAX. Here is a list of major browsers that support AJAX.
Mozilla Firefox 1.0 and above.
Netscape version 7.1 and above.
Apple Safari 1.2 and above.
Microsoft Internet Explorer 5 and above.
Konqueror.
Opera 7.6 and above.
When you write your next application, do consider the browsers that do not support AJAX.
NOTE − When we say that a browser does not support AJAX, it simply means that the browser does not support the creation of Javascript object – XMLHttpRequest object.
The simplest way to make your source code compatible with a browser is to use try...catch blocks in your JavaScript.
<html>
   <body>
      <script language = "javascript" type = "text/javascript">
         <!-- 
         //Browser Support Code
         function ajaxFunction() {
            var ajaxRequest;  // The variable that makes Ajax possible!

            try {
               // Opera 8.0+, Firefox, Safari 
               ajaxRequest = new XMLHttpRequest();
            } catch (e) {

               // Internet Explorer Browsers
               try {
                  ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
               } catch (e) {
                  
                  try {
                     ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                  } catch (e) {

                     // Something went wrong
                     alert("Your browser broke!");
                     return false;
                  }
               }
            }
         }
         //-->
      </script>
      
      <form name = 'myForm'>
         Name: <input type = 'text' name = 'username' /> <br />
         Time: <input type = 'text' name = 'time' />
      </form>
      
   </body>
</html>
In the above JavaScript code, we try three times to make our XMLHttpRequest object. Our first attempt −
ajaxRequest = new XMLHttpRequest();
It is for Opera 8.0+, Firefox, and Safari browsers. If it fails, we try two more times to make the correct object for an Internet Explorer browser with −
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
If it doesn't work, then we can use a very outdated browser that doesn't support XMLHttpRequest, which also means it doesn't support AJAX.
Most likely though, our variable ajaxRequest will now be set to whatever XMLHttpRequest standard the browser uses and we can start sending data to the server. The step-wise AJAX workflow is explained in the next chapter.

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    20 Lectures 
     1 hours 

 Laurence Svekis

    29 Lectures 
     2 hours 

 YouAccel

    20 Lectures 
     1.5 hours 

 YouAccel

    18 Lectures 
     2.5 hours 

 Stone River ELearning

    47 Lectures 
     5.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Apply CSS on a table cell based on the content in SAPUI5

You are having one of the most common requirements in the case of the table. You can achieve the end result using formatter function exposed on the cells of a table.
Here is a code snippet for your reference which you can alter as per your use case:
cells: [
   new sap.m.Text({
      text: {
         formatter: function(name) {
            if (name == "<your value>") {
               // you can add style class or do your own logic here
               this.addStyleClass("Total");
            }
         }
      }
   })
]
How to Install Turbo C++ on Linux?

13 May, 2022
In this article, we will look into how to install Turbo C++ on Linux. Turbo C++ is the free and Open-Source Software, it is a development tool for writing programs in the C/C++ language. Turbo C++ is a compiler and IDE (Integrated development environment) originally from Borland.  
To run Turbo C++ in Linux System you must have the following:
Turbo C++ Setup
DOSBox Emulator 
Note: If you have it installed on your system, just go to Linux Software Center and search for DOSBox and install the emulator or use the below command in the terminal:
sudo apt-get install dosbox
Follow the below steps to install Turbo C++ on Linux:
Step 1: Download and Extract the zip file of Turbo C++.
Step 2: Move the extracted folder to your home folder
Step 3: Go to the Dosbox configuration file and change settings. Use the following command –
satyajit@satyajit:~$ gedit .dosbox/dosbox-0.74-3.conf
Then change the following key values on that configuration file –
fullscreen=true
fulldouble=true
fullresolution=1920x1080
windowresolution=1920x1080
output=opengl
Set the fullresolution and windowresolution value the same as your screen resolution.
 
Then at the end of the file add the following lines –
mount C: ~
C:
cd TURBOC3/bin
tc.exe
 
Now to run Turbo C++ go to the terminal and write –
dosbox
It will start Turbo C++
 
Press Alt + Enter to switch between full screen and window mode.
Press Ctrl + F10 to release and lock the mouse on DOSBox
satyajit1910
how-to-install
linux
Picked
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Permanently Disable Swap in Linux?
How to Import JSON Data into SQL Server?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
Utopian Simplex Protocol in Computer Network

21 Dec, 2020
We will consider a protocol that is simple because it does not worry about the possibility of anything going wrong. Data are transmitted in one direction only. Both are transmitting and receiving network layers are always ready. Processing time can be ignored. Infinite buffer space is available. This thoroughly unrealistic protocol, which we will nickname “Utopia”, is simply to show the basic structure on which we will build. Its implementation is shown below.
A Utopian simplex Protocol :There is one direction data transmission only from sender to receiver. Here we assume the communication channel to be error-free and the receiver will infinitely quickly process the input. The sender pumps out the data onto the line as fast as it can.
typedef enum {frame_arrival} event_type;

#include"protocol.h"

void sender1(void)
{
 frame s;                     /* buffer for an outbound frame */
 packet buffer;                /* buffer for an outbound packet */
 while(true)
 {
  from_network_layer(&buffer);   /* go get something to send */
  s.info=buffer;               /* copy it into s for transmission */
  to_physical_layer(&s);        /* send it on its way */
 }                           
}

void receiver1(void)
{
 frame r;
 event_type event;             /* filled in by wait, but not used here */
 while(true)
  {
   wait_for_event(&event);       /* only possibility is frame_arrival */
   from_physical_layer(&r);      /* go get the inbound frame */
   to_network_layer(&r.info);     /* pass the data to the network layer */
  }
}
This protocol has two different procedures, a sender and a receiver. MAX_SEQ is not needed because no sequence numbers or acknowledgments are used. The only event type possible is frame_arrival (i.e. the arrival of an undamaged frame).
The sender pumps out the data in an infinite while loop as fast as it can. The loop body consists of three actions and they are –
Fetch a packet from the network layer,
Construct an outbound frame using the variable s,
Send the frame on its way.
Other fields have to do with error and flow control and there are no errors or flow control restrictions here so only the info field is used here.
The receiver is equally simple. The procedure wait_for_event returns when the frame arrives and the event set to frame_arrival. The newly arrived frame from the hardware buffer is removed by the call from_physical_layer and puts in the variable r, so that receiver can get it. The data link layer settles back to wait for the next frame when the data portion is passed on to the network layer, suspending itself until the frame arrives. It does not handle either flow control or error correction therefore it is unrealistic.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set position of an image in CSS ?

13 Jul, 2021
You can easily position an image by using the object-position property. You can also use a bunch of other ways like float-property that will be discussed further in this article.
Methods:
object-position property: Specify how an image element is positioned with x, y coordinates inside its content box.
float property: Specify how an element should float and place an element on its container’s right or left side.
Method 1: Using object-position Property
Syntax:
object-position: <position>
 
Property values:
position: It takes 2 numerical values corresponding to the distance from the left of the content-box (x-axis) and the distance from the top of the content-box (y-axis) respectively.
Note:
We can align elements using position property with some helper property left | right | top | bottom.
You can either use string values like right, left, center, top, or you can use numerical value in pixel like 200px, 250px.
Example:
HTML
<!DOCTYPE html><html>  <head>    <style>        #object1 {            width: 500px;            height: 200px;            background-color: green;            object-fit: none;            object-position: center top;            /* String value */        }          #object2 {            width: 500px;            height: 200px;            background-color: green;            object-fit: none;            object-position: 50px 30px;            /* Numeric value */        }    </style></head>  <body>    <center>        <h2 style="color:green">            GeeksforGeeks        </h2>        <h4>object-position Property</h4>        <img id="object1"            src="https://media.geeksforgeeks.org/wp-content/uploads/20210412211244/Screenshotfrom20210412211213-300x159.png" />          <img id="object2"            src="https://media.geeksforgeeks.org/wp-content/uploads/20210412211244/Screenshotfrom20210412211213-300x159.png" />    </center></body>  </html>
Output:
object-position
Method 2: Using float Property
Syntax:
float: none|inherit|left|right|initial;
Note: Elements are floated only horizontally i.e. left or right
Property Value:
left: Place an element on its container’s right.
right: Place an element on its container’s left.
inherit: Element inherits floating property from it’s parent (div, table etc...) elements.
none: Element is displayed as it is (Default).
Example:
HTML
<!DOCTYPE html><html>  <head>    <style>        #object1 {            width: 300px;            height: 200px;            float: right;        }          center {            width: 500px;            height: 500px;            background-color: green;        }    </style></head>  <body>    <center>        <h2 style="color:green">            GeeksforGeeks        </h2>        <h4>Float Property</h4>        <img id="object1"            src="https://media.geeksforgeeks.org/wp-content/uploads/20210412211244/Screenshotfrom20210412211213-300x159.png" />    </center></body>  </html>
Output:
Float property
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to select different values from same column and display them in different columns with MySQL?

To select different values on the basis of condition, use CASE statement. Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(40),
Score int
) ;
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name,Score) values('Chris',45);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(Name,Score) values('David',68);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name,Score) values('Robert',89);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Name,Score) values('Bob',34);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Name,Score) values('Sam',66);
Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+-------+
| Id | Name   | Score |
+----+--------+-------+
|  1 | Chris  |    45 |
|  2 | David  |    68 |
|  3 | Robert |    89 |
|  4 | Bob    |    34 |
|  5 | Sam    |    66 |
+----+--------+-------+
5 rows in set (0.00 sec)
Following is the query to select different values from same column −
mysql> select Score,
   case when Score < 40 then Score end as ' Score Less than 40',
   case when Score between 60 and 70 then Score end as 'Score Between 60 and 70 ',
   case when Score > 80 then Score end as 'Score greater than 80'
   from DemoTable;
This will produce the following output −
+-------+--------------------+--------------------------+-----------------------+
| Score | Score Less than 40 | Score Between 60 and 70  | Score greater than 80 |
+-------+--------------------+--------------------------+-----------------------+
|    45 |               NULL |                     NULL |                  NULL |
|    68 |               NULL |                       68 |                  NULL |
|    89 |               NULL |                     NULL |                    89 |
|    34 |                 34 |                     NULL |                  NULL |
|    66 |               NULL |                       66 |                  NULL |
+-------+--------------------+--------------------------+-----------------------+
5 rows in set, 1 warning (0.03 sec)
What does the CSS rule “clear: both” do?

15 Feb, 2019
The clear property is used to specify that which side of floating elements are not allowed to float. It sets or returns the position of the element in relation to floating the objects.
The “clear: both” means floating the elements are not allowed to float on both sides. It is used when no need of any element float on the left and right side as related to the specified element and wanted the next element only shown below. It also indicates that no other element takes up space on the left and right side.
Syntax:
clear:both; 
Example:
<!DOCTYPE html> <html>     <head>         <style>             div {                 width:100px;                 height:100px;                 background-color:green;                 color:white;                 font-weight:bold;                 font-size:25px;                 text-align:center;                 float: left;                 padding:15px;             }             p.GFG {                 clear: both;             }             h1 {                 color:green;                 text-align:center;             }         </style>     </head>     <body>         <h1>GeeksForGeeks</h1>         <h1>clear:both;</h1>         <div><pre>GFG</pre></div>         <p>GeeksforGeeks: A computer science portal for geeks</p>         <p class="GFG">GeeksforGeeks</P>     </body> </html>                     
Output:
Supported Browsers: The supported browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Extract values from HashMap in Java

To extract values from HashMap, let us first create a HashMap with keys and values −
HashMap<Integer, Integer>m = new HashMap<Integer, Integer>();
Now, add some elements to the HashMap −
m.put(10, 20);
m.put(30, 40);
m.put(50, 60);
m.put(70, 80);
m.put(90, 100);
m.put(110, 120);
m.put(130, 140);
m.put(150, 160);
Now, extract the values from the HashMap −
for (Integer i: m.keySet()) {
   System.out.println(m.get(i));
}
 Live Demo
import java.util.HashMap;
public class Demo {
   public static void main(String args[]) {
      HashMap<Integer, Integer>m = new HashMap<Integer, Integer>();
      m.put(10, 20);
      m.put(30, 40);
      m.put(50, 60);
      m.put(70, 80);
      m.put(90, 100);
      m.put(110, 120);
      m.put(130, 140);
      m.put(150, 160);
      System.out.println("Displaying values from HashMap...");
      for (Integer i: m.keySet()) {
         System.out.println(m.get(i));
      }
   }
}
Displaying values from HashMap...
60
140
80
160
20
100
40
120
List clear() method in Java with Examples

11 Dec, 2018
The clear() method of List interface in Java is used to remove all of the elements from the List container. This method does not deleted the List container, instead it justs removes all of the elements from the List.
Syntax:
public void clear()
Parameter: This method accepts does not accepts any parameter.
Return Value: The return type of the function is void and it does not returns anything.
Exceptions: This method throws an UnsupportedOperationException if the clear() operation is not supported by this list.
Below programs illustrate the List.clear() method:
Program 1:
// Java code to illustrate clear() methodimport java.io.*;import java.util.*;  public class ListDemo {    public static void main(String[] args)    {          // create an empty list with an initial capacity        List<String> list = new ArrayList<String>(5);          // use add() method to initially        // add elements in the list        list.add("Geeks");        list.add("For");        list.add("Geeks");          // Remove all elements from the List        list.clear();          // print the List        System.out.println(list);    }}
[]

Program 2:
// Java code to illustrate clear() methodimport java.io.*;import java.util.*;  public class ListDemo {    public static void main(String[] args)    {          // create an empty list with an initial capacity        List<Integer> list = new ArrayList<Integer>(5);          // use add() method to initially        // add elements in the list        list.add(10);        list.add(20);        list.add(30);          // clear the list        list.clear();          // prints all the elements available in list        System.out.println(list);    }}
[]

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#clear()
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML – Gradient Boosting

02 Sep, 2020
Gradient Boosting is a popular boosting algorithm. In gradient boosting, each predictor corrects its predecessor’s error. In contrast to Adaboost, the weights of the training instances are not tweaked, instead, each predictor is trained using the residual errors of predecessor as labels.
There is a technique called the Gradient Boosted Trees whose base learner is CART (Classification and Regression Trees).
The below diagram explains how gradient boosted trees are trained for regression problems.
Gradient Boosted Trees for Regression
The ensemble consists of N trees. Tree1 is trained using the feature matrix X and the labels y. The predictions labelled y1(hat) are used to determine the training set residual errors r1. Tree2 is then trained using the feature matrix X and the residual errors r1 of Tree1 as labels. The predicted results r1(hat) are then used to determine the residual r2. The process is repeated until all the N trees forming the ensemble are trained.
There is an important parameter used in this technique known as Shrinkage.
Each tree predicts a label and final prediction is given by the formula,
y(pred) = y1 + (eta *  r1) + (eta * r2) + ....... + (eta * rN)


The class of the gradient boosting regression in scikit-learn is GradientBoostingRegressor. A similar algorithm is used for classification known as GradientBoostingClassifier.
Code: Python code for Gradient Boosting Regressor
# Import models and utility functionsfrom sklearn.ensemble import GradientBoostingRegressorfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error as MSEfrom sklearn import datasets  # Setting SEED for reproducibilitySEED = 1  # Importing the dataset bike = datasets.load_bike()X, y = bike.data, bike.target  # Splitting datasettrain_X, test_X, train_y, test_y = train_test_split(X, y, test_size = 0.3, random_state = SEED)  # Instantiate Gradient Boosting Regressorgbr = GradientBoostingRegressor(n_estimators = 200, max_depth = 1, random_state = SEED)  # Fit to training setgbr.fit(train_X, train_y)  # Predict on test setpred_y = gbr.predict(test_X)  # test set RMSEtest_rmse = MSE(test_y, pred_y) ** (1 / 2)  # Print rmseprint('RMSE test set: {:.2f}'.format(test_rmse))
Output:
RMSE test set: 4.01

Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Support Vector Machine Algorithm
Elbow Method for optimal value of k in KMeans
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python | Generate random numbers within a given range and store in a list

14 Jan, 2022
Given lower and upper limits, generate a given count of random numbers within a given range, starting from ‘start’ to ‘end’ and store them in list.Examples:  
Input : num = 10, start = 20, end = 40
Output : [23, 20, 30, 33, 30, 36, 37, 27, 28, 38]
The output contains 10 random numbers in
range [20, 40].

Input : num = 5, start = 10, end = 15
Output : [15, 11, 15, 12, 11]
The output contains 5 random numbers in
range [10, 15].
 
Python provides a random module to generate random numbers. To generate random numbers we have used the random function along with the use of the randint function. Syntax:  
randint(start, end)
randint accepts two parameters: a starting point and an ending point. Both should be integers and the first value should always be less than the second. 
Python3
# Python code to generate# random numbers and# append them to a listimport random # Function to generate# and append them# start = starting range,# end = ending range# num = number of# elements needs to be appendeddef Rand(start, end, num):    res = []     for j in range(num):        res.append(random.randint(start, end))     return res # Driver Codenum = 10start = 20end = 40print(Rand(start, end, num))
Output:  
[23, 20, 30, 33, 30, 36, 37, 27, 28, 38]
Method 2:  Using numpy random.randint() method to generate random numbers.
Python3
# Python code to generate# random numbers and# append them to a listimport numpy as npdef Rand(start, end, num):    res = []     for j in range(num):        res.append(np.random.randint(start, end))     return res  # Driver Codenum = 10start = 20end = 40print(Rand(start, end, num))
Output:
[30, 30, 38, 39, 39, 37, 24, 25, 28, 32]
pulamolusaimohan
varshagumber28
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON
Static Dropdown verification with Cypress

Cypress handles static dropdowns with the help of its in built commands. For a
static dropdown, the tagname of the element should be <select> and its child
elements should have the tagname <option>.
The command used is select(). This command needs to be chained with a command
that gives DOM elements having tagname as select. The various usage of select commands are listed below −
select(value) − The select() command with argument value selects the option
with that value. The get method should have the css selector of the static dropdown when chained with select().
select(value) − The select() command with argument value selects the option
with that value. The get method should have the css selector of the static dropdown when chained with select().
cy.get('select').select('value1')
select(text) − The select() command with argument text selects the option
with that text content. The get method should have the css selector of the static dropdown when chained with select().
select(text) − The select() command with argument text selects the option
with that text content. The get method should have the css selector of the static dropdown when chained with select().
cy.get('select').select('text')
select('Value1', 'Value2') − The select() command with arguments selects the
array of options with those values or text contents. The get method should have the css selector of the static dropdown when chained with select().
select('Value1', 'Value2') − The select() command with arguments selects the
array of options with those values or text contents. The get method should have the css selector of the static dropdown when chained with select().
cy.get('select').select(['Tutorialspoint', 'Cypress'])
select({ force: true }) − The select() command with option as argument
changes the default behavior of static dropdown. There can be three types of options − log, force and timeout having default values as true, false and
defaultCommandTimeout (4000 milliseconds) respectively.
select({ force: true }) − The select() command with option as argument
changes the default behavior of static dropdown. There can be three types of options − log, force and timeout having default values as true, false and
defaultCommandTimeout (4000 milliseconds) respectively.
cy.get('select').select('Cypress', { force: true})
The option force is used by Cypress to interact with hidden elements and
then forces to select an option from the dropdown internally.
We can apply assertions with the select() command in Cypress.
cy.get('select').select('Cypress').should('have.value', 'Cypress')
Code Implementation with select().
describe('Tutorialspoint Test', function () {
   // test case
   it('Test Case2', function (){
      cy.visit("https://www.tutorialspoint.com/selenium /selenium_automation_practice.htm");
      // checking by values
      cy.get('input[type="checkbox"]')
      .check(['Manual Tester','Automation Tester']);
      // selecting a value from static dropdown
      cy.get('select[name="continents"]').select('Europe')
      // asserting the option selected
      .should('have.text', 'Europe')
   });
});
Tokenizing a String in Java

We have the following string −
String str = "This is demo text, and demo line!";
To tokenize the string, let us split them after every period (.) and comma (,)
String str = "This is demo text, and demo line!";
The following is the complete example.
 Live Demo
public class Demo {
    public static void main(String[] args) {
       String str = "This is demo text, and demo line!";
       String[] res = str.split("[, .]", 0);
       for(String myStr: res) {
          System.out.println(myStr);
       }
    }
}
This
is
demo
text

and
demo
line!
Perform NAND/NOR operations in MySQL

Let us first see how we can perform NAND/NOR operations in MySQL. The concept is as follows −
NAND= NOT( yourColumnName1 AND yourColumnName2)
NOR=NOT( yourColumnName1 OR yourColumnName2)
Let us first create a table −
mysql> create table DemoTable
(
   Value1 boolean ,
   Value2 boolean
);
Query OK, 0 rows affected (0.72 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(true,true);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(false,false);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(false,true);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(true,false);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+--------+
| Value1 | Value2 |
+--------+--------+
|      1 |      1 |
|      0 |      0 |
|      0 |      1 |
|      1 |      0 |
+--------+--------+
4 rows in set (0.00 sec)
Following is the query to perform NAND/NOR operations −
mysql> select Value1,Value2, NOT(Value1 AND Value2) AS NAND_Result,NOT(Value1 OR Value2) AS NOR_Result from DemoTable;
This will produce the following output −
+--------+--------+-------------+------------+
| Value1 | Value2 | NAND_Result | NOR_Result |
+--------+--------+-------------+------------+
|      1 |      1 |           0 |          0 |
|      0 |      0 |           1 |          1 |
|      0 |      1 |           1 |          0 |
|      1 |      0 |           1 |          0 |
+--------+--------+-------------+------------+
4 rows in set (0.00 sec)
ASP Server.MapPath Method - GeeksforGeeks

02 Mar, 2021
The MapPath method is used to define a relative virtual path for a physical directory on the server.       
Note: This method cannot be used in Session.OnEnd and Application.OnEnd.
Syntax:
Server.MapPath(path)                                                               
  Parameter Value:
path: It stores a string value that defines the relative or virtual path to map to a physical directory. If the path starts with either a forward slash(/) or backward slash(\) the MapPath Method returns a path as if the path is a full virtual path. If the path doesn’t start with a slash, the MapPath Method returns a path relative to a directory of the .asp file being processed.
Example Code: Below code that demonstrates the use of the Server.MapPath Method.
<%
response.write(Server.MapPath("test.asp") & "<br>")
response.write(Server.MapPath("script/test.asp") & "<br>")
response.write(Server.MapPath("/script/test.asp") & "<br>")
response.write(Server.MapPath("\script") & "<br>")
response.write(Server.MapPath("/") & "<br>")
response.write(Server.MapPath("\") & "<br>")
%>
Output  
c:\inetpub\wwwroot\script\test.asp
c:\inetpub\wwwroot\script\script\test.asp
c:\inetpub\wwwroot\script\test.asp
c:\inetpub\wwwroot\script
c:\inetpub\wwwroot
c:\inetpub\wwwroot
ASP-Methods
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to redirect to another page in ReactJS ?
How to Insert Form Data into Database using PHP ?
How to pass data from child component to its parent in ReactJS ?
How to execute PHP code using command line ?
REST API (Introduction)
Python PIL | Image.frombytes() Method - GeeksforGeeks

07 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
PIL.Image.frombytes() Creates a copy of an image memory from pixel data in a buffer. In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data).
Syntax: PIL.Image.frombytes(mode, size, data, decoder_name=’raw’, *args)
Parameters:mode – The image mode. See: Modes.size – The image size.data – A byte buffer containing raw data for the given mode.decoder_name – What decoder to use.args – Additional parameters for the given decoder.
Returns: An Image object.
     # importing image object from PILfrom PIL import Image  # using tobytes data as raw for frombyte functiontobytes = b'xd8\xe1\xb7\xeb\xa8\xe5 \xd2\xb7\xe1'img = Image.frombytes("L", (3, 2), tobytes)  # creating list img1 = list(img.getdata())print(img1)
Output:
[120, 100, 56, 225, 183, 235]

Another Example: Here we use different raw in tobytes.
     # importing image object from PILfrom PIL import Image  # using tobytes data as raw for frombyte functiontobytes = b'\xbf\x8cd\xba\x7f\xe0\xf0\xb8t\xfe'img = Image.frombytes("L", (3, 2), tobytes)  # creating list img1 = list(img.getdata())print(img1)
Output:
[191, 140, 100, 186, 127, 224]

Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Wand scale() function - Python - GeeksforGeeks

10 Aug, 2021
The scale() function is an inbuilt function in the Python Wand ImageMagick library which is used to change the image size by scaling each pixel value by given columns and rows. 
Syntax: 
scale(columns, rows)
Parameters: This function accepts two parameters as mentioned above and defined below:  
columns: This parameter stores the number of columns to scale the image horizontally. It is in pixels.
rows: This parameter stores the number of columns to scale the image vertically. It is in pixels.
Return Value: This function returns the Wand ImageMagick object.
Original Image:  
Example 1:  
Python3
# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image:    # Clone the image in order to process    with image.clone() as scale:        # Invoke scale function with threshold as 0.8        scale.scale(200, 100)        # Save the image        scale.save(filename ='scale1.jpg')
Output: 
Example 2: 
Python3
# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw:    # Set Stroke color the circle to black    draw.stroke_color = Color('black')    # Set Width of the circle to 2    draw.stroke_width = 1    # Set the fill color to 'White (# FFFFFF)'    draw.fill_color = Color('white')     # Invoke Circle function with center at 50, 50 and radius 25    draw.circle((200, 200), # Center point                (100, 100)) # Perimeter point    # Set the font style    draw.font = '../Helvetica.ttf'    # Set the font size    draw.font_size = 30         with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic:        # Set the text and its location        draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !')        # Draw the picture        draw(pic)        # Invoke scale function method with threshold 0.6        pic.scale(50, 100)        # Save the image        pic.save(filename ='scale2.jpg')
Output:  
 
sagartomar9927
Image-Processing
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
How to fix auto keyword error in Dev-C++ - GeeksforGeeks

15 Jul, 2020
The auto keyword in C++ specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime.
// C++ program to illustrate the auto// keyword in DevC++ compiler#include <bits/stdc++.h>using namespace std;  // Driver Codeint main(){    // Initialize vector    vector<int> v = { 1, 2, 3, 4, 5 };      // Traverse vector using auto    for (auto x : v) {          // Print elements of vector        cout << x << " ";    }}
1 2 3 4 5

If you want to traverse a vector using an auto keyword (as shown in the above code), then it will show error as:
The auto keyword introduces in C++ 11, and it is allowed to the user to leave the type deduction to the compiler itself. But while running a program in Dev-C++ then it will be showing error, because in Dev-C++ inbuilt C++98 compiler so that’s by that error occurs.
Below are the steps to solve the error:
Open Dev C++ go to ->tools.Click on ->compiler options(1st option).A new window will open and in that window click on -> settings:Go to -> code generation:In language standard column(std) choose ->ISO C++11:Click on OK and After that the code will execute and will give no error.
Open Dev C++ go to ->tools.
Click on ->compiler options(1st option).
A new window will open and in that window click on -> settings:
Go to -> code generation:
In language standard column(std) choose ->ISO C++11:
Click on OK and After that the code will execute and will give no error.
Now the code works fine and prints the expected output.
C++
C++ Programs
How To
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
How can we sort a Map by both key and value using lambda in Java?

A Map interface implements the Collection interface that provides the functionality of the map data structure. A Map doesn't contain any duplicate keys and each key is associated with a single value. We can able to access and modify values using the keys associated with them.
In the below two examples, we can able to sort a Map by both key and value with the help of lambda expression.
import java.util.*;
import java.util.stream.*;

public class MapSortUsingKeyTest {
   public static void main(String args[]) {
     
      // Sort a Map by their key
      Map<Integer, String> map = new HashMap<Integer, String>();

      map.put(2, "India");
      map.put(5, "Australia");
      map.put(3, "England");
      map.put(1, "Newzealand");
      map.put(4, "Scotland");

      Map<Integer, String> sortedMap = map.entrySet().stream()
                               .sorted(Map.Entry.comparingByKey())
                               .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                               (e1, e2) -> e2, LinkedHashMap::new));
      System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));
   }
}

Sorted Map: [1=Newzealand, 2=India, 3=England, 4=Scotland, 5=Australia]
import java.util.*;
import java.util.stream.*;

public class MapSortUsingValueTest {
   public static void main(String args[]) {
     
      //Sort a Map by their Value
      Map<Integer, String> map = new HashMap<Integer, String>();

      map.put(1, "Jaidev");
      map.put(2, "Adithya");
      map.put(3, "Vamsi");
      map.put(4, "Krishna");
      map.put(5, "Chaitanya");

      Map<Integer, String> sortedMap = map.entrySet().stream()
                               .sorted(Map.Entry.comparingByValue())
                               .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                               (e1, e2) -> e2, LinkedHashMap::new));
      System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));
   }
}
Sorted Map: [2=Adithya, 5=Chaitanya, 1=Jaidev, 4=Krishna, 3=Vamsi]
Selection Sort program in C#

Selection Sort is a sorting algorithm that finds the minimum value in the array for each iteration of the loop. Then this minimum value is swapped with the current array element. This procedure is followed until the array is sorted.
A program that demonstrates selection sort in C# is given as follows.
 Live Demo
using System;
public class Example {
   static void Main(string[] args) {
      int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 };
      int n = 10;
      Console.WriteLine("Selection sort");
      Console.Write("Initial array is: ");
      for (int i = 0; i < n; i++) {
         Console.Write(arr[i] + " ");
      }
      int temp, smallest;
      for (int i = 0; i < n - 1; i++) {
         smallest = i;
         for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[smallest]) {
               smallest = j;
            }
         }
         temp = arr[smallest];
         arr[smallest] = arr[i];
         arr[i] = temp;
      }
      Console.WriteLine();
      Console.Write("Sorted array is: ");
      for (int i = 0; i < n; i++) {
         Console.Write(arr[i] + " ");
      }
   }
}
The output of the above program is as follows.
Selection sort
Initial array is: 56 1 99 67 89 23 44 12 78 34
Sorted array is: 1 12 23 34 44 56 67 78 89 99
Now, let us understand the above program.
First the array is initialized and its value is printed using a for loop. This can be seen in the following code snippet.
int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 };
int n = 10;
Console.WriteLine("Selection sort");
Console.Write("Initial array is: ");
for (int i = 0; i < n; i++) {
   Console.Write(arr[i] + " ");
}
A nested for loop is used for the actual sorting process. In each pass of the outer for loop, the smallest element in the array is found and replaced by the current element. This process continues until the array is sorted. This can be seen in the following code snippet.
for (int i = 0; i < n - 1; i++) {
   smallest = i;
   for (int j = i + 1; j < n; j++) {
      if (arr[j] < arr[smallest]) {
         smallest = j;
      }
   }
   temp = arr[smallest];
   arr[smallest] = arr[i];
   arr[i] = temp;
}
Finally the sorted array is displayed. This can be seen in the following code snippet.
Console.Write("Sorted array is: ");
for (int i = 0; i < n; i++) {
   Console.Write(arr[i] + " ");
}
DATEADD or DATE_ADD in MySQL query?

You need to use DATE_ADD() in MySQL.
The syntax is as follows
DATE_ADD(NOW(), INTERVAL yourValue MINUTE);
Arithmetic operator can also be used.
The syntax is as follows
NOW() + INTERVAL 30 MINUTE
Here is the demo of DATE_ADD() function.
The query is as follows
mysql> select date_add(now(), interval 30 minute);
The following is the output
+-------------------------------------+
| date_add(now(), interval 30 minute) |
+-------------------------------------+
| 2019-02-27 15:38:27                 |
+-------------------------------------+
1 row in set (0.00 sec)
Let us now use arithmetic + operator instead of DATE_ADD().
The query is as follows
mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2019-02-27 15:09:18 |
+---------------------+
1 row in set (0.00 sec)
Now add 30 minutes in NOW().
The query is as follows
mysql> select now()+interval 30 minute;
The following is the output
+--------------------------+
| now()+interval 30 minute |
+--------------------------+
| 2019-02-27 15:39:33      |
+--------------------------+
1 row in set (0.00 sec)