code-rag-bench/online-tutorials huggingface dataset:
C++ program to demonstrate multi-level inheritance

Suppose we have three classes Vehicle, FourWheeler, and Car. The class Vehicle is the base class, the class FourWheeler is derived from it and the class Car is derived from the class FourWheeler. Class Vehicle has a method 'vehicle' that prints 'I am a vehicle', class FourWheeler has a method 'fourWheeler' that prints 'I have four wheels', and class Car has a method 'car' that prints 'I am a car'. So, as this is a multi-level inheritance; we can have access to all the other classes methods from the object of the class Car. We invoke all the methods from a Car object and print the corresponding outputs of the methods.
So, if we invoke the methods in this order, car(), fourWheeler(), and vehicle(), then the output will be −
I am a car
I have four wheels
I am a vehicle
To solve this, we will follow these steps −
Define a new class Vehicle.Define a function vehicle()print("I am a vehicle")
Define a function vehicle()print("I am a vehicle")
print("I am a vehicle")
Define a new class FourWheeler inheriting from the class Vehicle.Define a function fourWheeler()print("I have four wheels")
Define a function fourWheeler()print("I have four wheels")
print("I have four wheels")
Define a new class Car inheriting from the class FourWheeler.Define a function car()print("I am a car")
Define a function car()print("I am a car")
print("I am a car")
Let us see the following implementation to get better understanding −
#include <iostream>
using namespace std;

class Vehicle{
   public:
      void vehicle(){
         cout<<"I am a vehicle\n";
      }
};

class FourWheeler : public Vehicle{
   public:
      void fourWheeler(){
         cout<<"I have four wheels\n";
      }
};

class Car : public FourWheeler{
   public:
      void car(){
         cout<<"I am a car\n";
      }
};
int main(){
   Car obj;
   obj.car();
   obj.fourWheeler();
   obj.vehicle();
   return 0;
}
Car obj;
obj.car();
obj.fourWheeler();
obj.vehicle();
I am a car
I have four wheels
I am a vehicle
Make a multiline plot from .CSV file in matplotlib

To make a multiline plot from .CSV file in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a list of columns to fetch the data from a .CSV file. Make sure the names match with the column names used in the .CSV file.
Read the data from the .CSV file.
Plot the lines using df.plot() method.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Make a list of columns
columns = ['mpg', 'displ', 'hp', 'weight']

# Read a CSV file
df = pd.read_csv("auto-mpg.csv", usecols=columns)

# Plot the lines
df.plot()

plt.show()
It will produce the following output
MoviePy – Showing Video File Clip

01 Aug, 2020
In this article we will see how we can show a video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Visual multimedia source that combines a sequence of images to form a moving picture. The video transmits a signal to a screen and processes the order in which the screen captures should be shown. Videos usually have audio components that correspond with the pictures being shown on the screen.
In order to do this we will use ipython_display method with the VideoFileClip object
Syntax : clip.ipython_display(width, height)
Argument : It takes two optional arguments i.e integers
Return : It returns HTML2 object
Note : Video length should not be too large else it will give memory error therefore to take care of this error clip the small part of video from original video.
Below is the implementation
# Import everything needed to edit video clipsfrom moviepy.editor import *  # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm")  # getting subclip as video is largeclip = clip.subclip(0, 10)    # showing clipclip.ipython_display(width = 280, height = 320)
Output :
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4

Another example
# Import everything needed to edit video clipsfrom moviepy.editor import *  # loading video gfgclip = VideoFileClip("geeks.mp4")    # showing clipclip.ipython_display()
Output :
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
                                                                                                                       
MoviePy - Done.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4

Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ program for Sorting Dates using Selection Sort

06 Apr, 2022
C
// C++ program for sorting dates using selection sort#include<bits/stdc++.h>using namespace std;struct date{    int day;    int month;    int year;}; int main(){    struct date input[5];    for(int i=0; i<5; i++)    {        cin>>input[i].day;        cin>>input[i].month;        cin>>input[i].year;     }    for (int i=0; i<4; i++)    {        for (int j=i+1; j<5; j++)        {            if (input[i].year > input[j].year)            {                struct date temp = input[i];                input[i] = input[j];                input[j] = temp;            }            else if (input[i].year == input[j].year && input[i].month > input[j].month)            {                struct date temp = input[i];                input[i] = input[j];                input[j] = temp;            }            else if (input[i].year == input[j].year && input[i].month == input[j].month && input[i].day > input[j].day)            {                struct date temp = input[i];                input[i] = input[j];                input[j] = temp;            }         }    }      for(int i=0; i<5; i++)    {        cout<<input[i].day<<" "<<input[i].month<<" "<<input[i].year;        cout<<endl;    }}
This program is contributed by Dinesh T.P.D. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
simmytarika5
date-time-program
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HeapSort
std::sort() in C++ STL
Merge two sorted arrays
Count Inversions in an array | Set 1 (Using Merge Sort)
Radix Sort
Sort an array of 0s, 1s and 2s | Dutch National Flag problem
Chocolate Distribution Problem
Find a triplet that sum to a given value
k largest(or smallest) elements in an array
sort() in Python
Write a program to reverse an array in JavaScript?

We can reverse the array using reverse() method and also in a normal way.
Reversing Array using array.reverse() Method.
 Live Demo
<html>
<body>
<script>
   var a = [1,2,3,4,5];
   a.reverse();
   document.write(a);
</script>
</body>
</html>
5,4,3,2,1
Reversing Array without using any Built-in method.
 Live Demo
<html>
<body>
<p id="reverse"></p>
<script>
   var t = [];
   var a = [1,2,3,4,5];
   for(var i = 0; i < a.length;i++){
   t[i] = a[a.length-1-i]
   }
document.getElementById("reverse").innerHTML = t;
</script>
</body>
</html>
5,4,3,2,1
atan2() function in C++ STL

The atan2() function returns the tangent inverse of the coordinate in terms of y and x. Here y and x are the values of the y and x coordinates respectively. It is an inbuilt function in C++ STL.
The syntax of the atan2() function is given as follows.
atan2(dataType var1, dataType var2)
As can be seen from the syntax, the function atan2() accepts two parameters var1 and var2 of data type float, double or long double that are y and x point respectively.
The value returned by atan2() is in the range of -pi to pi and is the angle between the (x,y) and the positive x axis.
A program that demonstrates atan2() in C++ is given as follows.
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main() {
   double y = 10, x = 5, ans;
   ans = atan2(y,x);
   cout << "atan2("<< y <<"/"<< x <<") = " << ans << endl;
   return 0;
}
atan2(10/5) = 1.10715
In the above program, first the variables y and x are initialized. Then inverse tangent of y and x is found using atan2() and stored in ans. Finally the value of ans is displayed. This is demonstrated by the following code snippet.
double y = 10, x = 5, ans;
ans = atan2(y,x);
cout << "atan2("<< y <<"/"<< x <<") = " << ans << endl;
The result obtained by using the atan2() function can be converted into degrees and displayed. A program to demonstrate this is as follows.
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main() {
   double y = 10, x = 5, ans;
   ans = atan2(y,x);
   ans = ans*180/3.14159;
   cout << "atan2("<< y <<"/"<< x <<") = " << ans << endl;
   return 0;
}
atan2(10/5) = 63.435
In the above program, the inverse tangent of y and x is obtained using atan2(). Then this value is converted into degrees. Finally, the output is displayed. This is demonstrated by the following code snippet.
double y = 10, x = 5, ans;
ans = atan2(y,x);
ans = ans*180/3.14159;
cout << "atan2("<< y <<"/"<< x <<") = " << ans << endl;
Random access to text lines in Python (linecache)

Purpose of linecache module in Python’s standard library is to facilitate random access to any text file, although this module is extensively used by Python’s traceback module to generate error trace stack. Further prettyprints of reading are held in a cache so that it saves time while reading lines repeatedly.
The most important function in this module is getline() which reads a specified line number from given file. Following is the list of functions −
getline(file, x)
This function returns xth line from file. If not present it will return empty string. If the file is not present in current path, function ties to locate it in directories in sys.path – the module search path.
clearcache()
If prettyprint of previous getline() function is no longer needed, you can clear the cache by this function.
checkcache()
This function checks if the cache is valid. This is useful if files in cache may have been changed on disk.
lazycache()
Seed the cache for filename with module_globals. The module loader will be asked for the source only when getlines is called, not immediately.
getlines()
This function returns lines from file in the form of list object.
updatecache()
This function updates cache entries and returns a list of lines.
To demonstrate use of linecache functionality, first we build a text file to store the famous Zen of Python (list of software principles that influence design philosophy of Python). Output of ‘import this’ is redirected to zen.txt by following code −
import sys, io
zen = io.StringIO()
old_stdout = sys.stdout
sys.stdout = zen
import this
sys.stdout = old_stdout
f=open('zen.txt','w')
f.write(zen.getvalue())
f.close()
When above code is executed, zen.txt will be created in current directory. We shall use this text file to read lines from it with getline() function.
To read 4th line from file
>>> linecache.getline('zen.txt',4)
'Explicit is better than implicit.\n'
Note that the return string ends with newline character.
To display line numbers from 4 to 10, use slice operator on list returned by getlines() function
>>> linecache.getlines('zen.txt')[4:10]
['Simple is better than complex.\n', 'Complex is better than complicated.\n', 'Flat is better than nested.\n', 'Sparse is better than dense.\n', 'Readability counts.\n', "Special cases aren't special enough to break the rules.\n"]
In this article we learned about linecache module in Python standard library.
Java Shift Operator Examples

The following program is a simple example that demonstrates the bitwise operators. Copy and paste the following Java program into Test.java file and compile and run this program −
Online Demo
public class Test {
   public static void main(String args[]) {

      int a = 60;/* 60 = 0011 1100 */
      int b = 13;/* 13 = 0000 1101 */
      int c = 0;

      c = a & b;        /* 12 = 0000 1100 */
      System.out.println("a & b = " + c );

      c = a | b;        /* 61 = 0011 1101 */
      System.out.println("a | b = " + c );

      c = a ^ b;        /* 49 = 0011 0001 */
      System.out.println("a ^ b = " + c );

      c = ~a;           /*-61 = 1100 0011 */
      System.out.println("~a = " + c );

      c = a << 2;       /* 240 = 1111 0000 */
      System.out.println("a << 2 = " + c );

      c = a >> 2;       /* 15 = 1111 */
      System.out.println("a >> 2  = " + c );

      c = a >>> 2;      /* 15 = 0000 1111 */
      System.out.println("a >>> 2 = " + c );
   }
}
This will produce the following result −
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2  = 15
a >>> 2 = 15
Pre-increment (or pre-decrement) in C

Increment operators are used to increase the value by one while decrement works opposite increment. Decrement operator decreases the value by one.
Here is the syntax of pre-increment operator in C language,
++variable_name;
Here is the syntax of pre-decrement operator in C language,
--variable_name;
Let us see the difference between pre-increment and pre-decrement operator.
Pre-increment − Before assigning the value to the variable, the value is incremented by one.
Here is an example of pre-increment in C language,
 Live Demo
#include <stdio.h>
int main() {
   int i = 5;
   printf("The pre-incremented value : %d\n",i);
   while(++i < 10 )
   printf("%d\t",i);
   return 0;
}
The pre-incremented value : 5
6789
Pre-decrement − Before assigning the value to the variable, the value is decremented by one.
Here is an example of pre-decrement in C language,
 Live Demo
#include <stdio.h>
int main() {
int i = 10;
   printf("The pre-decremented value : %d\n",i);
   while(--i > 5 )
   printf("%d\t",i);
   return 0;
}
The pre-decremented value : 10
9876
Check whether a HashSet is empty or not in Java

To check whether a HashSet is empty or not, use the isEmpty() method.
Create a HashSet −
HashSet hs = new HashSet();
Add elements to the HashSet −
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");
hs.add("M");
hs.add("N");
Now, check whether the HashSet is empty or not. Since we added elements above, it won’t be empty −
hs.isEmpty();
The following is an example that checks whether a HashSet is empty or not −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // create a hash set
      HashSet hs = new HashSet();
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      hs.add("K");
      hs.add("M");
      hs.add("N");
      System.out.println("Elements: "+hs);
      System.out.println("Is the set empty? = "+hs.isEmpty());
   }
}
Elements: [A, B, C, D, E, F, K, M, N]
Is the set empty? = false
Let us see another example −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet hs = new HashSet();
      // empty set
      System.out.println("Is the set empty? = "+hs.isEmpty());
   }
}
Is the set empty? = true
Java program to convert floating to binary

To convert floating to binary, the Java code is as follows −
 Live Demo
import java.io.*;
public class Demo {
   static void decimal_to_bin(int n){
      int[] bin_num = new int[50];
      int i = 0;
      while (n > 0){
         bin_num[i] = n % 2;
         n = n / 2;
         i++;
      }
      for (int j = i - 1; j >= 0; j--)
      System.out.print(bin_num[j]);
   }
   public static void main (String[] args){
      int n = 89;
      System.out.println("The conversion from floating to binary is ");
      decimal_to_bin(n);
   }
}
The conversion from floating to binary is
1011001
A class named Demo contains a function named ‘decimal_to_bin’ that converts a given decimal
number into a binary number by iterating through every digit of the number and dividing by 2, and
taking its remainder, and again dividing the number by 2. In the main function, the number that
needs to be converted is defined and the function is called by passing this number as the parameter.
How to run Java package program

Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces.
Following package example contains interface named animals −
/* File name : Animal.java */
package animals;
interface Animal {
   public void eat();
   public void travel();
}
Now, let us implement the above interface in the same package animals −
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal {
   public void eat() {
      System.out.println("Mammal eats");
   }
   public void travel() {
      System.out.println("Mammal travels");
   }
   public int noOfLegs() {
      return 0;
   }
   public static void main(String args[]) {
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
   }
}
Now compile the java files as shown below −
$ javac -d . Animal.java
$ javac -d . MammalInt.java
Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below.
You can execute the class file within the package
$ java animals.MammalInt
and get the result as shown below.
Mammal eats
Mammal travels
Average of given numbers in Bash

30 Jun, 2021
Program to compute average in bash.Examples:  
Input :  1 2 3 4 5
Output : average : 3.0

Input :  1 2 3 4 10
Output : average : 5.0
Program to compute average is simple. It is also called as Mean. Formula:  
 
(sum of all elements) / (total no. of elements)
The extension for bash programs end with .sh. Elements are stored in array which are traversed in while loop to calculate the sum. It is recommended to understand Arrays in Shell. The avg is calculated using bc command. bc command is used for command line calculator. Programs in bash is executed as follows :  
sh program_name.sh
     OR
./program_name.sh
 
CPP
# Total numbersn=5  # copying the value of nm=$n  # initialized sum by 0sum=0  # array initialized with# some numbersarray=(1 2 3 4 5)  # loop until n is greater# than 0while [ $n -gt 0 ]do    # copy element in a    # temp variable    num=${array[`expr $n - 1`]}         # add them to sum    sum=`expr $sum + $num`      # decrement count of n    n=`expr $n - 1`done  # displaying the average# by piping with bc command# bc is bash calculator# commandavg=`echo "$sum / $m" | bc -l`printf '%0.3f' "$avg"
Output :  
3.0
 
surinderdawra388
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting
How to increase the X-axis labels font size using ggplot2 in R?

To increase the X-axis labels font size using ggplot2, we can use axis.text.x argument of theme function where we can define the text size for axis element. This might be required when we want viewers to critically examine the X-axis labels and especially in situations when we change the scale for X-axis.
Check out the below given example to understand how it can be done.
Following snippet creates a sample data frame −
x<-rnorm(20)
y<-rnorm(20)
df<-data.frame(x,y)
df
The following dataframe is created −
        x           y
1  -0.98190157   1.080447960
2   1.00247425   1.268177956
3   1.93521281   1.396761171
4  -0.05125250   1.116289059
5  -0.96090929  -0.710364525
6  -1.24432105  -0.146794806
7  -2.36365700   0.900933342
8  -0.04993840  -0.654018782
9   1.00789255   0.528862194
10 -0.87029207   0.515485209
11 -1.96332523  -2.288145618
12 -0.61780404   0.113034383
13 -0.73750813   0.716358061
14 -0.67379795  -0.002136233
15  0.04409529   1.353033640
16  2.35756367   0.361340419
17  1.33416796   0.331124217
18 -0.71829594  -1.067921280
19  0.38769673  -0.435514111
20  0.27477924   1.996037117
To load ggplot2 package and create point chart between x and y, add the following code to the above snippet −
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()
If you execute all the above given snippets as a single program, it generates the following output −
To create point chart between x and y with X-axis labels of larger size, add the following code to the above snippet −
ggplot(df,aes(x,y))+geom_point()+theme(axis.text.x=element_text(size=15))

If you execute all the above given snippets as a single program, it generates the following output −
CSS | inset Property

19 Jun, 2020
The inset property in CSS is used to define physical offset, not for the inline offset or logical block. This property can apply to any writing-mode property.
Syntax:
inset: length|percentage|auto|inherit|initial|unset;
Property values:
length: It sets a fixed value defined in px, cm, pt etc. Negative values are also allowed. Its default value is 0px.
percentage: It is same as length but it set the size in terms of percentage of the window size.
auto: It is used when it is desired that the browser determines the inset size.
initial: It is used to set the value of the inset property to its default value.
inherit: It inherits the inset property value from its parent element.
unset: It is used to unset the inset property and it is the default value.
Below examples illustrate the inset property in CSS:
Example 1:
<!DOCTYPE html><html>  <head>    <title>CSS | inset Property</title>    <style>        h1 {            color: green;        }                  div {            background-color: purple;            width: 200px;            height: 100px;            position: relative;        }                  .one {            position: relative;            inset: 10px 40px 30px 0px;            background-color: #c8c800;        }    </style></head>  <body>    <center>        <h1>Geeksforgeeks</h1>        <b>CSS | inset Property</b>        <br><br>        <div>            <p class="one">            A Computer Science Portal            </p>        </div>    </center></body>  </html>
Output:
Example 2:
<!DOCTYPE html><html>  <head>    <title>CSS | inset Property</title>    <style>        h1 {            color: green;        }                  div {            background-color: purple;            width: 200px;            height: 100px;            position: relative;        }                  .one {            position: relative;            inset: 10% 5% 5% 0%;            background-color: green;        }    </style></head>  <body>    <center>        <h1>Geeksforgeeks</h1>        <b>CSS | inset Property</b>        <br><br>        <div>            <p class="one">            A Computer Science Portal            </p>        </div>    </center></body>  </html>
Output:
Supported Browsers: The browser supported by inset property are listed below:
Firefox
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/inset
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Extract Script and CSS Files from Web Pages in Python ?

08 Sep, 2021
Prerequisite:
Requests
BeautifulSoup
File Handling in Python
In this article, we will discuss how to extract Script and CSS Files from Web Pages using Python.
For this, we will be downloading the CSS and JavaScript files that were attached to the source code of the website during its coding process. Firstly, the URL of the website needed to be scraped is determined and a request is sent to it. After retrieving Websites’ content two folders for two file types are created and the files are placed into them and then we can perform various operations on them according to our need.
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come in built-in with Python.
requests:  Requests allow you to send HTTP/1.1 requests extremely easily. This module also does not come in built-in with Python.
Example 1: 
Here we are counting the number of fetched links for each respective type.
Python3
# Import Required Libraryimport requestsfrom bs4 import BeautifulSoup  # Web URLweb_url = "https://www.geeksforgeeks.org/"  # get HTML contenthtml = requests.get(web_url).content  # parse HTML Contentsoup = BeautifulSoup(html, "html.parser")  js_files = []cs_files = []  for script in soup.find_all("script"):    if script.attrs.get("src"):                  # if the tag has the attribute         # 'src'        url = script.attrs.get("src")        js_files.append(web_url+url)    for css in soup.find_all("link"):    if css.attrs.get("href"):                  # if the link tag has the 'href'         # attribute        _url = css.attrs.get("href")        cs_files.append(web_url+_url)  print(f"Total {len(js_files)} javascript files found")print(f"Total {len(cs_files)} CSS files found")
Output:
Total 7 javascript files found
Total 14 CSS files found
We can also use file handling to import fetched links into the text files.
Example 2:
Python3
# Import Required Libraryimport requestsfrom bs4 import BeautifulSoup  # Web URLweb_url = "https://www.geeksforgeeks.org/"  # get HTML contenthtml = requests.get(web_url).content  # parse HTML Contentsoup = BeautifulSoup(html, "html.parser")  js_files = []cs_files = []  for script in soup.find_all("script"):    if script.attrs.get("src"):                # if the tag has the attribute         # 'src'        url = script.attrs.get("src")        js_files.append(web_url+url)    for css in soup.find_all("link"):    if css.attrs.get("href"):                # if the link tag has the 'href'        # attribute        _url = css.attrs.get("href")        cs_files.append(web_url+_url)  # adding links to the txt fileswith open("javajavascript_files.txt", "w") as f:    for js_file in js_files:        print(js_file, file=f)  with open("css_files.txt", "w") as f:    for css_file in cs_files:        print(css_file, file=f)
Output:
gulshankumarar231
Python BeautifulSoup
Python bs4-Exercises
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array combination() operation

10 Feb, 2020
Array#combination() : combination() is an Array class method which invokes with a block yielding all combinations of length ‘n’ of elements of the array.
Syntax:  Array.combination()

Parameter:  Arrays in which we want elements to be invoked

Return:  all combinations of length 'n' of elements of the array.

Code #1 : Example for combination() method
# Ruby code for combination() method  # declaring arraya = [1, 2, 56, 23]  # combination of length 2puts "combination a : #{a.combination(2).to_a}\n\n"  # combination of length 3puts "combination a : #{a.combination(3).to_a}\n\n"
Output :
combination a : [[1, 2], [1, 56], [1, 23], [2, 56], [2, 23], [56, 23]]

combination a : [[1, 2, 56], [1, 2, 23], [1, 56, 23], [2, 56, 23]]

Code #2 : Example for combination() method
# Ruby code for combination() method  # declaring arraya = [[1, 2, 56, 23],    [34, 54, 23, 1]]  # combination of length 2puts "collect a : #{a.combination(2).to_a}\n\n"  # combination of length 1puts "collect a : #{a.combination(1).to_a}\n\n"
Output :
collect a : [[[1, 2, 56, 23], [34, 54, 23, 1]]]

collect a : [[[1, 2, 56, 23]], [[34, 54, 23, 1]]]


timcustard
Ruby Array-class
Ruby Collections
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker – ARG Instruction

28 Oct, 2020
You can use the ARG command inside a Dockerfile to define the name of a parameter and its default value. This default value can also be overridden using a simple option with the Docker build command. The difference between ENV and ARG is that after you set an environment variable using ARG, you will not be able to access that later on when you try to run the Docker Container.
In this article, we will discuss how to use the ARG instruction inside a Dockerfile to set parameters. Follow the below steps to implement ARG instruction in a Dockerfile:
You can create a Dockerfile with ARG instruction using the following template.
FROM ubuntu:latest
ARG GREET=GeeksForGeeks
RUN echo "Hey there! Welcome to $GREET" > greeting.txt
CMD cat greeting.txt

The above Dockerfile pulls the Ubuntu Base Image from Docker Hub and sets a parameter called GREET to GeeksForGeeks. It then uses the parameter to create a text file and then prints the message inside the text file.
You can build the Docker Image using the following command.
sudo docker build -t arg-demo .

To run the Docker Container, you can use the following Docker Run command.
sudo docker run -it arg-demo bash

You can see that the file greetings.txt has been created with the message created using the parameter GREET.
You can override the default value of ARG by using the –build-arg option along with the build command.
sudo docker build -t arg-demo --build-arg GREET=World .

You can now run the container, print the file and you will see the updated message.
To conclude, in this article, we discussed how to use the ARG command to set parameter values to be used throughout the Dockerfile. We also discussed how to override the parameter value using the –build-arg option along with the Docker build command.
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Fuzzy Logic | Introduction
Monolithic vs Microservices architecture
OpenCV - Overview
How to Install GNU Octave in Linux?

06 Oct, 2021
Octave is open-source, free available for many of the platforms. It is actually a High-level Language. It comes up with a text interface along with an experimental graphical interface. It is also used for various Machine Learning algorithms for solving various numeric problems. You can say that it is similar to MATLAB but slower than MATLAB.
We can easily solve operations like Matrix Multiplication, Transpose of a Matrix, or any other operation on Vector and Matrix very easily with just a few lines of code.
Step 1: Open the terminal and then add repository for Octave with below command and then press Enter.
sudo apt-add-repository ppa:octave/stable
If you are facing an error for ‘apt-add-repository’ command not found like the below image which means that you have not installed the common properties or dependencies to use this command.
But it can be easily installed with the below command(after this run the previous command).
sudo apt install software-properties-common
Step 2: Now you have added the repository then with below command get all the package information from all configured sources:
sudo apt-get update
Step 3: Install the octave for your system with the below command.
sudo apt-get install octave
Step 4: Now, you have successfully installed octave to your Linux system, launch octave with the octave command.
octave
how-to-install
GBlog
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
How to Learn Data Science in 10 weeks?
What is Hashing | A Complete Tutorial
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
Java Tutorial
How to filter object array based on attributes?
SVG text-anchor Attribute

31 Mar, 2022
The text-anchor attribute is used to align a text which is auto-wrapped or pre-formatted. The wrapping area is decided from the inline-size property with respect to a given point. In case of multiple line text, the alignment is made for each line. It has effect only on the following elements <altGlyph>, <text>, <textPath>, <tref>, and <tspan>
Syntax:
text-anchor = start | middle | end

Attribute Values: The text-anchor attribute accepts the values mentioned above and described below:
start: With this attribute value, characters are aligned such that the start of the text string is at the initial current text position.
middle: With this attribute value, characters are aligned such that the middle of the text string is at the current text position.
end: With this attribute value, characters are shifted such that the end of the resulting rendered text is at the initial current text position.
Example 1: Below examples illustrates the use of text-anchor attribute.
HTML
<!DOCTYPE html><html>  <head>    <style>        text {            font: 20px sans-serif;        }    </style></head>  <body>    <svg viewBox="0 0 420 420"         xmlns="http://www.w3.org/2000/svg">                  <path d="M60 15 L60, 50 M30, 40                 L90, 40" stroke="green" />                  <text text-anchor="start" x="60"             y="40" stroke="green">            GeeksforGeeks        </text>                  <circle cx="60" cy="40" r="3"             fill="green" />    </svg></body>  </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html>  <head>    <style>        text {            font: 20px sans-serif;        }    </style></head>  <body>    <svg viewBox="0 0 420 420"         xmlns="http://www.w3.org/2000/svg">                  <path d="M60 15 L60, 50 M30,             40 L90, 40" stroke="green" />                  <text text-anchor="middle" x="60"            y="40" stroke="green">            GeeksforGeeks        </text>                  <circle cx="60" cy="40" r="3" fill="green" />    </svg></body>  </html>
Output:
Example 3:
HTML
<!DOCTYPE html><html>  <head>    <style>        text {            font: 20px sans-serif;        }    </style></head>  <body>    <svg viewBox="0 0 420 420"         xmlns="http://www.w3.org/2000/svg">                  <path d="M60 15 L60, 50 M30,             40 L90, 40" stroke="green" />                  <text text-anchor="end" x="60"             y="40" stroke="green">            GeeksforGeeks        </text>                  <circle cx="60" cy="40" r="3" fill="green" />    </svg></body>  </html>
Output:
HTML-SVG
SVG-Attribute
HTML
Web Technologies
HTML
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 ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Matplotlib.pyplot.tick_params() in Python

19 Apr, 2020
Matplotlib is a visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
matplotlib.pyplot.tick_params() is used to change the appearance of ticks, tick labels, and gridlines.
Syntax:
matplotlib.pyplot.tick_params(axis='both', **kwargs)
Parameters :
Example #1: Default plot
# importing librariesimport matplotlib.pyplot as plt     # values of x and y axes x = [i for i in range(5, 55, 5)]y = [1, 4, 3, 2, 7, 6, 9, 8, 10, 5]     plt.plot(x, y) plt.xlabel('x') plt.ylabel('y')     plt.show() 
Output : Example #2:
# importing librariesimport matplotlib.pyplot as pltfrom matplotlib.ticker import MultipleLocator, ScalarFormatter  fig, ax = plt.subplots()ax.plot([0, 10, 20, 30], [0, 2, 1, 2])  ax.xaxis.set_minor_locator(MultipleLocator(1))ax.xaxis.set_minor_formatter(ScalarFormatter())  ax.tick_params(axis ='both', which ='major',                labelsize = 16, pad = 12,                colors ='r')  ax.tick_params(axis ='both', which ='minor',               labelsize = 8, colors ='b')  plt.show()
Output:
Python-matplotlib
Python
Write From Home
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
Python String | replace()
How to Install PIP on Windows ?
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java
How to get the first element of List in Scala

19 Nov, 2021
In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data. Let’s see how to get the first element of given List in Scala.List in Scala contains many suitable methods to perform simple operations like head(), tail(), isEmpty(). Coming to list, head() method is used to get the head/top element of the list. below are examples to get first element of list. 
Example :  
scala
// Scala program to print immutable listsimport scala.collection.immutable._ // Creating objectobject GFG{    // Main method    def main(args:Array[String])    {        // Creating and initializing immutable lists        val mylist: List[String] = List("Geeks", "For", "geeks", "is",                                        "a", "fabulous", "portal")         println("The head of the list is:")        println(mylist.head)    }}
Output:  
The head of the list is:
Geeks
Example : 
scala
// Scala program to creating a uniform listimport scala.collection.immutable._ // Creating objectobject GFG{    // Main method    def main(args:Array[String])    {        // Repeats Scala three times.        val myList = List.range(10, 19)        println(myList)         println("First element is: " + myList.head)    }}
Output:  
List(10, 11, 12, 13, 14, 15, 16, 17, 18)
First element is: 10
 
sumitgumber28
Scala
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Scala String substring() method with example
Scala Constructors
Lambda Expression in Scala
How to Install Scala with VSCode?
Enumeration in Scala
Inheritance in Scala
Python PyTorch from_numpy()

22 Apr, 2020
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes.
The function torch.from_numpy() provides support for the conversion of a numpy array into a tensor in PyTorch. It expects the input as a numpy array (numpy.ndarray). The output type is tensor. The returned tensor and ndarray share the same memory. The returned tensor is not resizable.
It currently accepts ndarray with dtypes of numpy.float64, numpy.float32, numpy.float16, numpy.int64, numpy.int32, numpy.int16, numpy.int8, numpy.uint8, and numpy.bool.
Syntax: torch.sinh(ndarray)
Parameters:ndarray: Input Numpy array (numpy.ndarray)
Return type: A tensor with the same type as that of x.
Code #1:
# Importing the PyTorch libraryimport torchimport numpy  # A numpy array of size 6a = numpy.array([1.0, -0.5, 3.4, -2.1, 0.0, -6.5])print(a)  # Applying the from_numpy function and# storing the resulting tensor in 't't = torch.from_numpy(a)print(t)
Output:
[ 1.  -0.5  3.4 -2.1  0.  -6.5]
tensor([ 1.0000, -0.5000,  3.4000, -2.1000,  0.0000, -6.5000],
       dtype=torch.float64)

 
Modifications to the tensor will be reflected in the ndarray and vice versa.
Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python – Convert List to List of dictionaries

05 Jan, 2022
Given list values and keys list, convert these values to key value pairs in form of list of dictionaries.
Input : test_list = [“Gfg”, 3, “is”, 8], key_list = [“name”, “id”]Output : [{‘name’: ‘Gfg’, ‘id’: 3}, {‘name’: ‘is’, ‘id’: 8}]Explanation : Values mapped by custom key, “name” -> “Gfg”, “id” -> 3.
Input : test_list = [“Gfg”, 10], key_list = [“name”, “id”]Output : [{‘name’: ‘Gfg’, ‘id’: 10}]Explanation : Conversion of lists to list of records by keys mapping.
Method #1 : Using loop + dictionary comprehension
This is one of the ways in which this task can be performed. In this, we perform mapping values using dictionary comprehension. The iteration is performed using loop.
Python3
# Python3 code to demonstrate working of # Convert List to List of dictionaries# Using dictionary comprehension + loop  # initializing liststest_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]  # printing original listprint("The original list : " + str(test_list))  # initializing key list key_list = ["name", "number"]  # loop to iterate through elements# using dictionary comprehension# for dictionary constructionn = len(test_list)res = []for idx in range(0, n, 2):    res.append({key_list[0]: test_list[idx], key_list[1] : test_list[idx + 1]})  # printing result print("The constructed dictionary list : " + str(res))
The original list : [‘Gfg’, 3, ‘is’, 8, ‘Best’, 10, ‘for’, 18, ‘Geeks’, 33]The constructed dictionary list : [{‘name’: ‘Gfg’, ‘number’: 3}, {‘name’: ‘is’, ‘number’: 8}, {‘name’: ‘Best’, ‘number’: 10}, {‘name’: ‘for’, ‘number’: 18}, {‘name’: ‘Geeks’, ‘number’: 33}]
Method #2 : Using dictionary comprehension + list comprehension
The combination of above functions is used to solve this problem. In this, we perform a similar task as above method. But difference is that its performed as shorthand.
Python3
# Python3 code to demonstrate working of # Convert List to List of dictionaries# Using zip() + list comprehension  # initializing liststest_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]  # printing original listprint("The original list : " + str(test_list))  # initializing key list key_list = ["name", "number"]  # using list comprehension to perform as shorthandn = len(test_list)res = [{key_list[0]: test_list[idx], key_list[1]: test_list[idx + 1]}       for idx in range(0, n, 2)]  # printing result print("The constructed dictionary list : " + str(res))
The original list : [‘Gfg’, 3, ‘is’, 8, ‘Best’, 10, ‘for’, 18, ‘Geeks’, 33]The constructed dictionary list : [{‘name’: ‘Gfg’, ‘number’: 3}, {‘name’: ‘is’, ‘number’: 8}, {‘name’: ‘Best’, ‘number’: 10}, {‘name’: ‘for’, ‘number’: 18}, {‘name’: ‘Geeks’, ‘number’: 33}]
simmytarika5
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MongoDB query which represents not equal to null or empty?

To set a query for not equal to null or empty, use the $nin operator. The syntax is as follows
db.yourCollectionName.find({yourFieldName:{$nin:[null,""]}});
Let us create a collection with documents
> db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"Larry","UserAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d20b6a629b87623db1b26")
}
> db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"","UserAge":29});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d20bea629b87623db1b27")
}
> db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"Sam","UserAge":32});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d20c7a629b87623db1b28")
}
> db.notEqualToNullOrEmptyDemo.insertOne({"UserName":null,"UserAge":27});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d20d2a629b87623db1b29")
}
> db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"Robert","UserAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d20dda629b87623db1b2a")
}
> db.notEqualToNullOrEmptyDemo.insertOne({"UserName":"","UserAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d20e7a629b87623db1b2b")
}
Following is the query to display all documents from a collection with the help of find() method
> db.notEqualToNullOrEmptyDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9d20b6a629b87623db1b26"),
   "UserName" : "Larry",
   "UserAge" : 24
}
{
   "_id" : ObjectId("5c9d20bea629b87623db1b27"),
   "UserName" : "",
   "UserAge" : 29
}
{
   "_id" : ObjectId("5c9d20c7a629b87623db1b28"),
   "UserName" : "Sam",
   "UserAge" : 32
}
{
   "_id" : ObjectId("5c9d20d2a629b87623db1b29"),
   "UserName" : null,
   "UserAge" : 27
}
{
   "_id" : ObjectId("5c9d20dda629b87623db1b2a"),
   "UserName" : "Robert",
   "UserAge" : 26
}
{
   "_id" : ObjectId("5c9d20e7a629b87623db1b2b"),
   "UserName" : "",
   "UserAge" : 23
}
Following is the query to set condition for not equal to null or empty
> db.notEqualToNullOrEmptyDemo.find({UserName:{$nin:[null,""]}}).pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9d20b6a629b87623db1b26"),
   "UserName" : "Larry",
   "UserAge" : 24
}
{
   "_id" : ObjectId("5c9d20c7a629b87623db1b28"),
   "UserName" : "Sam",
   "UserAge" : 32
}
{
   "_id" : ObjectId("5c9d20dda629b87623db1b2a"),
   "UserName" : "Robert",
   "UserAge" : 26
}
Python program to sort a list of tuples by second Item

When it is required to sort a list of tuples based on the second item, the lambda function and ‘sorted’ method can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list.
Anonymous function is a function which is defined without a name.
In general, functions in Python are defined using ‘def’ keyword, but anonymous function is defined with the help of ‘lambda’ keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.
The ‘sorted’ method is used to sort the elements of a list.
Below is a demonstration for the same −
 Live Demo
def tuple_sort(my_tuple):
   return(sorted(my_tuple, key = lambda x: x[1]))
my_tuple = [('bill', 11), ('rick', 45), ('john', 89), ('liv', 25)]
print("The list of tuple is : ")
print(my_tuple)
print("After sorting, the list of tuple becomes : ")
print(tuple_sort(my_tuple))
The list of tuple is :
[('bill', 11), ('rick', 45), ('john', 89), ('liv', 25)]
After sorting, the list of tuple becomes :
[('bill', 11), ('liv', 25), ('rick', 45), ('john', 89)]
A function named ‘tuple_sort’ is defined, that takes a list of tuple as parameter.
It is first iterated over using lambda function, and sorted using the ‘sorted’ function.
This is returned as output.
A list of tuple is defined and is displayed on the console.
The ‘tuple_sort’ method is called by passing this list of tuple as parameter.
This value is displayed as output on the console.