code-rag-bench/online-tutorials huggingface dataset:
Scala List drop() method with example

13 Aug, 2019
The drop() method belongs to the value member of the class List. It is utilized to select all the elements except the first n elements of the list.
Method Definition: def drop(n: Int): List[A]
Where, n is the number of elements to be dropped from the stated sequence.
Return Type: It returns all the elements of the list except the first n ones.
Example #1:
   // Scala program of drop()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a List         val list = List("a", "b", "c", "d", "e", "f")                  // Applying drop method         val result = list.drop(4)                  // Displays output        println(result)          }}
List(e, f)

Example #2:
// Scala program of drop()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a List         val list = List(1, 2, 3, 4, 5, 6)                  // Applying drop method         val result = list.drop(2)                  // Displays output        println(result)          }}
List(3, 4, 5, 6)

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Crop Canvas / Export HTML5 Canvas with certain width and height

For this, create a temporary canvas for drawing on the current canvas. After that use toDataUrl() method on the temporary canvas −
var c = document.getElementsByTagName("canvas");
var ctx = c[0].getContext("2d");
var data = ctx.getImageData(0, 0, c[0].width, c[0].height);
var compositeOperation = ctx.globalCompositeOperation;

ctx.globalCompositeOperation = "destination-over";
ctx.fillStyle = "#800000";
ctx.fillRect(0,0,c[0].width,c[0].height);

var tempCanvas = document.createElement("canvas"),
tCtx = tempCanvas.getContext("2d");
tempCanvas.width = 550;
tempCanvas.height = 280;
tCtx.drawImage(canvas[0],0,0);
Convert mp3 to wav using Python - GeeksforGeeks

24 Jan, 2021
In this article, we are going to discuss various methods to convert mp3 to wave file format using Python.
First We Need To Install ffmpeg. It Is A Free Open Source Software Project Consist of a Large Suite Of Libraries And Programs For Handling Video, Audio, And Other Multimedia Files.
sudo apt-get install ffmpeg 
So First Let Us Install pydub. This is an Audio Manipulation Module. Python Provides a Module Called pydub to Work With Audio Files. pydub is a Python library to work with only .wav files.
sudo apt-get install -y python-pydub
Program:
Python3
# import required modulesfrom os import pathfrom pydub import AudioSegment  # assign filesinput_file = "hello.mp3"output_file = "result.wav"  # convert mp3 file to wav filesound = AudioSegment.from_mp3(input_file)sound.export(output_file, format="wav")
Output:
Here you can see there is a python script And hello.mp3 file which converts it into a result.wav file.
The pydub module uses either ffmpeg or avconf programs to do the actual conversion. So you do have to install ffmpeg to make this work. But if you don’t need pydub for anything else, you can just use the built-in subprocess module to call a convertor program like ffmpeg which is shown in the below method.
It is a simple two-line script or code to convert a mp3 file to wav file.
Here we don’t need the pydub module, we can use builtin the subprocess module to call converter program ffmpeg as shown below:
Program:
Python3
# import required modulesimport subprocess  # convert mp3 to wav filesubprocess.call(['ffmpeg', '-i', 'hello.mp3',                 'converted_to_wav_file.wav'])
Output:
As you can see the wave format is generated.
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
JavaScript | Coordinates of mouse - GeeksforGeeks

09 Aug, 2021
The top left corner of the screen is (0, 0) i,e, X and Y coordinate is (0, 0). This means that vertical zero is topmost point and horizontal zero is the leftmost point. So, the task is to find the coordinates of the mouse over the screen.It can be find using the clientX and clientY property:  
ClientX: It gives the horizontal coordinate of the event.
ClientY: It gives the vertical coordinate of the mouse.
Syntax: 
For X coordinate: event.ClientX
For Y coordinate: event.ClientY
Below is the required implementation: 
javascript
<html> <head>   <script>      // coordinate function that calculate the X     // coordinate and Y coordinates     function coordinate(event) {      // clientX gives horizontal coordinate     var x = event.clientX;      // clientY gives vertical coordinates     var y = event.clientY;     document.getElementById("X").value = x;     document.getElementById("Y").value = y;  }    </script></head> <!-- onmousemove event is called when the mouse     pointer is moving over the screen --> <!-- calling of coordinate function --> <body onmousemove="coordinate(event)">    <!-- X coordinate is stored in X-coordinate variable -->   X-coordinate   <input type="text" id="X">   <br>   <br>    <!-- Y coordinate is stored in Y-coordinate variable -->   Y-coordinate   <input type="text" id="Y"> </body></html>
Output:  
 
rajeev0719singh
javascript-basics
javascript-functions
JavaScript-Misc
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
How to filter object array based on attributes?
How to convert JSON data to a html table using JavaScript/jQuery ?
Introduction to Object Oriented Programming in JavaScript
How to change selected value of a drop-down list using jQuery?
How to Adjust Marker Size in Matplotlib? - GeeksforGeeks

19 Dec, 2021
In this article, we are going to see how to adjust marker size in Matplotlib in Python. 
We can adjust marker size in plots of matplotlib either by specifying the size of the marker in either plot method or scatter method while plotting the graph.
plot() method used to plot the graph between 2 data points. It takes 4 parameters those are 2 data points, marker, and marker-size.
Syntax: matplotlib.pyplot.plot(data1, data2, marker=’.’, markersize=constant)
Parameters:
data1,data2- Variables that hold data.
marker=’.’ – Indicates dot symbol to mark the datapoints.
markersize- Represents size of marker
Example 1: Plot a graph using the plot method with standard marker size. (We do not need to mention the marker size in plot method)
Here we just plotted the graph using plot method with standard marker size.
Python3
# import necessary packagesimport matplotlib.pyplot as plt  # data1&data2data1 = [1, 2, 3, 4, 5]data2 = [1, 2, 1, 2, 1]  # plot graphplt.plot(data1, data2, marker=".")plt.xlabel('x-axis')plt.ylabel('y-axis')
Output:
Example 2: To adjust the size of marker in a plot use markersize parameter to plot method to adjust the marker size.
Here in this example, we adjusted the marker size to size 20 such that the maker size is increased from its standard size.
Python3
# import necessary packagesimport matplotlib.pyplot as plt  # data1&data2data1 = [1, 2, 3, 4, 5]data2 = [1, 2, 1, 2, 1]  # plot graphplt.plot(data1, data2, marker=".", markersize=20)plt.xlabel('x-axis')plt.ylabel('y-axis')
Output:
scatter is a method present in matplotlib library which is used to set individual point sizes. It takes 3 parameters 2 data points and a list of marker point sizes.
Python3
# import necessary packagesimport matplotlib.pyplot as plt  # data1&data2data1 = [1, 2, 3, 4, 5]data2 = [0, 0, 0, 0, 0]  # size of marker pointssizes = [10, 20, 30, 40, 50]  # plot graphplt.scatter(data1, data2, sizes)plt.xlabel('x-axis')plt.ylabel('y-axis')
Output:
There is flexibility in scatter that is we can specify the size for each point so that it can be easily distinguished.
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Bokeh - Setting Ranges

Numeric ranges of data axes of a plot are automatically set by Bokeh taking into consideration the dataset under process. However, sometimes you may want to define the range of values on x and y axis explicitly. This is done by assigning x_range and y_range properties to a figure() function.
These ranges are defined with the help of range1d() function.
xrange = range1d(0,10)

To use this range object as x_range property, use the below code −
fig = figure(x,y,x_range = xrange)

 Print
 Add Notes
 Bookmark this page
How To Add Google Translate Button On Your Webpage? - GeeksforGeeks

07 Aug, 2019
Google Translate is a free multilingual machine translation service developed by Google, to translate text from one language into another. It offers a website interface, mobile apps for Android and iOS, and an API that helps developers build browser extensions and software applications. Google Translate supports over 100 languages at various levels.
Follow the steps to add a google translate button on your website:
Step 1: Start with a basic web page and add a “div” element.In the code below a “div” element with the id “google_translate_element” is created.
Step 2: Add google translate api reference.
Step 3: Add Javascript function..
Example:
<!DOCTYPE html> <html lang="en-US">   <head>    <title>        How To Add Google Translate        Button On Your Webpage ?    </title></head>  <body>     <p>Hello everyone!</p>     <p>Welcome to GeeksforGeeks</p>           <p>        Translate this page in        your preferred language:    </p>           <div id="google_translate_element"></div>           <script type="text/javascript">         function googleTranslateElementInit() {             new google.translate.TranslateElement(                {pageLanguage: 'en'},                 'google_translate_element'            );         }     </script>           <script type="text/javascript" src="https://translate.google.com/translate_a/element.js?        cb=googleTranslateElementInit">    </script>           <p>        You can translate the content of this        page by selecting a language in the        select box.    </p> </body>   </html> 
Output:Output after translating into Arabic:
VasuJain3
JavaScript-Misc
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Use the JavaScript Fetch API to Get Data?
Difference Between PUT and PATCH Request
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
What is malloc in C language?

The C library memory allocation function void *malloc(size_t size) allocates the requested memory and returns a pointer to it.
Memory can be allocated in two ways as explained below −
Once memory is allocated at compile time, it cannot be changed during execution. There will be a problem of either insufficiency or else wastage of memory.
The solution is to create memory dynamically i.e. as per the requirement of the user during execution of program.
The standard library functions which are used for dynamic memory management are as follows −
malloc ( )
calloc ( )
realloc ( )
free ( )
This function is used for allocating a block of memory in bytes at runtime. It returns a void pointer, which points to the base address of allocated memory.
The syntax for malloc() is as follows −
void *malloc (size in bytes)
The following example shows the usage of malloc() function.
int *ptr;
ptr = (int * ) malloc (1000);
int *ptr;
ptr = (int * ) malloc (n * sizeof (int));
Note − It returns NULL, if memory is not FREE.
Given below is the C program to demonstrate dynamic memory allocation function - malloc().
 Live Demo
#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables and pointer//
   int numofele,i;
   int *p;
   //Reading elements as I/p//
   printf("Enter the number of elements in the array: ");
   scanf("%d",&numofele);
   //Declaring malloc function//
   p = (int *)malloc(numofele * (sizeof(int)));
   //Reading elements into array of pointers//
   for(i=0;i<numofele;i++){
      p[i]=i+1;
      printf("Element %d of array is : %d\n",i,p[i]);
   }
}
When the above program is executed, it produces the following result −
Enter the number of elements in the array: 4
Element 0 of array is : 1
Element 1 of array is : 2
Element 2 of array is : 3
Element 3 of array is : 4
Following is the C program to display the elements using dynamic memory allocation functions −
First five blocks should be empty, second five blocks should have the logic.
 Live Demo
#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables and pointers,sum//
   int numofe,i,sum=0;
   int *p;
   //Reading number of elements from user//
   printf("Enter the number of elements : ");
   scanf("%d",&numofe);
   //Calling malloc() function//
   p=(int *)malloc(numofe*sizeof(int));
   /*Printing O/p -
   We have to use if statement because we have to check if memory
   has been successfully allocated/reserved or not*/
   if (p==NULL){
      printf("Memory not available");
      exit(0);
   }
   //Printing elements//
   printf("Enter the elements : \n");
   for(i=0;i<numofe;i++){
      scanf("%d",p+i);
      sum=sum+*(p+i);
   }
   printf("\nThe sum of elements is %d",sum);
   free(p);//Erase first 2 memory locations//
   printf("\nDisplaying the cleared out memory location : \n");
   for(i=0;i<numofe;i++){
      printf("%d\n",p[i]);//Garbage values will be displayed//
   }
}
When the above program is executed, it produces the following result −
Enter the number of elements : 5
Enter the elements :
12
10
24
45
67
The sum of elements is 158
Displaying the cleared out memory location :
7804032
0
7799120
0
67
Xamarin - Android Dialogs

In this section, we are going to create a button which on clicked displays an alert dialog box. The dialog box contains two buttons, i.e., Delete and Cancel buttons.
First of all, go to main.axml and create a new button inside the linear layout as shown in the following code.
<?xml version = "1.0" encoding = "utf-8"?> 
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" 
   android:orientation = "vertical" 
   android:layout_width = "fill_parent" 
   android:background = "#d3d3d3" 
   android:layout_height = "fill_parent"> 
   <Button 
      android:id="@+id/MyButton" 
      android:layout_width = "fill_parent" 
      android:layout_height = "wrap_content" 
      android:text = "Click to Delete" 
      android:textColor = "@android:color/background_dark" 
      android:background = "@android:color/holo_green_dark" /> 
</LinearLayout>
Next, open MainActivity.cs to create the alert dialog and add its functionality.
protected override void OnCreate(Bundle bundle) { 
   base.OnCreate(bundle); 
   SetContentView(Resource.Layout.Main); 
   Button button = FindViewById<Button>(Resource.Id.MyButton); 
   button.Click += delegate { 
      AlertDialog.Builder alertDiag = new AlertDialog.Builder(this); 
      alertDiag.SetTitle("Confirm delete"); 
      alertDiag.SetMessage("Once deleted the move cannot be undone"); 
      alertDiag.SetPositiveButton("Delete", (senderAlert, args) => { 
         Toast.MakeText(this, "Deleted", ToastLength.Short).Show();
      }); 
      alertDiag.SetNegativeButton("Cancel", (senderAlert, args) => { 
         alertDiag.Dispose(); 
      }); 
      Dialog diag = alertDiag.Create(); 
      diag.Show(); 
   }; 
} 
Once done, build and run your Application to view the outcome.
In the above code, we have created an alert dialog called alertDiag, with the following two buttons −
setPositiveButton − It contains the Delete button action which on clicked displays a confirmation message Deleted.
setPositiveButton − It contains the Delete button action which on clicked displays a confirmation message Deleted.
setNegativeButton − It contains a Cancel button which when clicked simply closes the alert dialog box.
setNegativeButton − It contains a Cancel button which when clicked simply closes the alert dialog box.
 Print
 Add Notes
 Bookmark this page
Fractional Knapsack Problem

A list of items is given, each item has its own value and weight. Items can be placed in a knapsack whose maximum weight limit is W. The problem is to find the weight that is less than or equal to W, and value is maximized.
There are two types of Knapsack problem.
0 – 1 Knapsack
Fractional Knapsack
For the 0 – 1 Knapsack, items cannot be divided into smaller pieces, and for fractional knapsack, items can be broken into smaller pieces.
Here we will discuss the fractional knapsack problem.
The time complexity of this algorithm is O(n Log n).
Input:
Maximum weight = 50. List of items with value and weight.
{(60, 10), (100, 20), (120, 30)}
Output:
Maximum value: 240
By taking the items of weight 20 and 30
fractionalKnapsack(weight, itemList, n)
Input − maximum weight of the knapsack, list of items and the number of items
Output: The maximum value obtained.
Begin
   sort the item list based on the ration of value and weight
   currentWeight := 0
   knapsackVal := 0

   for all items i in the list do
      if currentWeight + weight of item[i] < weight then
         currentWeight := currentWeight + weight of item[i]
         knapsackVal := knapsackVal + value of item[i]
      else
         remaining := weight – currentWeight
         knapsackVal “= knapsackVal + value of item[i] * (remaining/weight of item[i])
         break the loop
   done
End
#include <iostream>
#include<algorithm>
using namespace std;

struct item {
   int value, weight;
};

bool cmp(struct item a, struct item b) {     //compare item a and item b based on the ration of value and weight
   double aRatio = (double)a.value / a.weight;
   double bRatio = (double)b.value / b.weight;
   return aRatio > bRatio;
}

double fractionalKnapsack(int weight, item itemList[], int n) {
   sort(itemList, itemList + n, cmp);      //sort item list using compare function
   int currWeight = 0;        // Current weight in knapsack
   double knapsackVal = 0.0;

   for (int i = 0; i < n; i++) {       //check through all items
      if (currWeight + itemList[i].weight <= weight) {     //when the space is enough for selected item, add it
         currWeight += itemList[i].weight;
         knapsackVal += itemList[i].value;

      }else{       //when no place for whole item, break it into smaller parts
         int remaining = weight - currWeight;
         knapsackVal += itemList[i].value * ((double) remaining / itemList[i].weight);
         break;
      }
   }
   return knapsackVal;
}

int main() {
   int weight = 50;     // Weight of knapsack
   item itemList[] = {{60, 10}, {100, 20}, {120, 30}};
   int n = 3;
   cout << "Maximum value: " << fractionalKnapsack(weight, itemList, n);
}
Maximum value: 240
C# | How to change the WindowHeight of the Console - GeeksforGeeks

28 Jan, 2019
Given the normal Console in C#, the task is to change the WindowHeight of the Console.
Approach: This can be done using the WindowHeight property in the Console class of the System package in C#. The WindowHeight refers to the height of the console window measured in rows.
Program 1: Getting the value of WindowHeight
// C# program to illustrate the// Console.WindowHeight Property using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Get the WindowHeight        Console.WriteLine("Current WindowHeight: {0}",                                Console.WindowHeight);    }}}
Output:
Program 2: Setting the value of WindowHeight
// C# program to illustrate the// Console.WindowHeight Property using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Get the WindowHeight        Console.WriteLine("Current WindowHeight: {0}",                                Console.WindowHeight);          // Set the WindowHeight        Console.WindowHeight = 50;          // Get the WindowHeight        Console.Write("Current WindowHeight: {0}",                            Console.WindowHeight);    }}}
Output:
Note: See the height of the Window in both the images.
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Constructors
C# | Class and Object
C# | Delegates
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
C# | Abstract Classes
ExpressJS - Serving static files

Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default does not allow you to serve static files. You need to enable it using the following built-in middleware.
app.use(express.static('public'));

Note − Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.
Note that the root route is now set to your public dir, so all static files you load will be considering public as root. To test that this is working fine, add any image file in your new public dir and change its name to "testimage.jpg". In your views, create a new view and include this file like −
html
   head
   body
      h3 Testing static file serving:
      img(src = "/testimage.jpg", alt = "Testing Image

You should get the following output −
We can also set multiple static assets directories using the following program −
var express = require('express');
var app = express();

app.use(express.static('public'));
app.use(express.static('images'));

app.listen(3000);
We can also provide a path prefix for serving static files. For example, if you want to provide a path prefix like '/static', you need to include the following code in your index.js file −
var express = require('express');
var app = express();

app.use('/static', express.static('public'));

app.listen(3000);
Now whenever you need to include a file, for example, a script file called main.js residing in your public directory, use the following script tag −
<script src = "/static/main.js" />

This technique can come in handy when providing multiple directories as static files. These prefixes can help distinguish between multiple directories.

    16 Lectures 
     1 hours 

 Anadi Sharma
 Print
 Add Notes
 Bookmark this page
How to extract the first n characters from a string using Java?

To find the consonants in the given String compare every character in it using the charAt() method with the vowel letters and remaining are consonants.
Live Demo
public class FindingConsonants {
   public static void main(String args[]) {

      String str = new String("Hi Welcome to Tutorialspoint");
      for(int i=0; i<str.length(); i++) {
         if(str.charAt(i) == 'a'|| str.charAt(i) == 'e'|| str.charAt(i) == 'i' ||
            str.charAt(i) == 'o' || str.charAt(i) == 'u'|| str.charAt(i) == ' ') {
         }else{
            System.out.println("Given string contains "+str.charAt(i)+" at the index "+i);
         }
      }
   }
}
Given string contains H at the index 0
Given string contains W at the index 3
Given string contains l at the index 5
Given string contains c at the index 6
Given string contains m at the index 8
Given string contains t at the index 11
Given string contains T at the index 14
Given string contains t at the index 16
Given string contains r at the index 18
Given string contains l at the index 21
Given string contains s at the index 22
Given string contains p at the index 23
Given string contains n at the index 26
Given string contains t at the index 27
Create a stored procedure with delimiter in MySQL

You can create a stored procedure using create procedure command. The syntax is as follows −
delimiter //
CREATE PROCEDURE yourStoreProcedureName()
BEGIN
   Declare variable here
   The query statement
END //

delimiter //
Apply the above syntax to create a stored procedure. The query is as follows −
mysql> use test;
Database changed
mysql> delimiter //
mysql> create procedure Sp_callTableStoredProcTable()
   −> begin
   −> select *from StoredProcTable;
   −> end //
Query OK, 0 rows affected (0.54 sec)
Now you need to change the delimiter with ; to call stored procedure −
mysql> delimiter ;
You can call stored procedure using CALL command. The syntax is as follows −
CALL yourStoredProcedureName();
The above stored procedure can be called using CALL command as shown in the below query −
mysql> call Sp_callTableStoredProcTable();
The following is the output −
+-----------+------+
| FirstName | Age  |
+-----------+------+
| John      | 23   |
| Bob       | 24   |
| David     | 20   |
+-----------+------+
3 rows in set (0.03 sec)

Query OK, 0 rows affected (0.06 sec)
Above, we have used the table ‘StoredProcTable’ and this table has three records. Displayed all records using stored procedure.
You can check how many records are in the table using stored procedure −
mysql> delimiter //
mysql> create procedure CountingRecords()
   −> begin
   −> select count(*) as AllRecords from StoredProcTable;
   −> end //
Query OK, 0 rows affected (0.19 sec)

mysql> delimiter ;
Call the stored procedure using CALL command. The query is as follows −
mysql> call CountingRecords();
The following output displays the count of records −
+------------+
| AllRecords |
+------------+
|          3 |
+------------+
1 row in set (0.31 sec)

Query OK, 0 rows affected (0.33 sec)
HTML | <thead> align Attribute

06 Jun, 2022
The HTML <thead> align attribute is used to set the horizontal alignment of text content inside the table head (thead) section. 
Syntax:
<thead align="left|right|center|justify|char">
Note: This attribute has been DEPRECATED and is no longer recommended.
Attribute Value:
left: It sets the text left-align.
right: It sets the text right-align.
center: It sets the text center-align.
justify: It stretches the text to set the width of all lines equal in table head.
char: It sets the text-align to a specific character.
Example: 
html
<!DOCTYPE html><html> <head>    <title>        HTML thead align Attribute    </title>         <style>        h1 {            color: green;        }        thead {            color: blue;        }        table, tbody, td {            border: 1px solid black;            border-collapse: collapse;        }    </style></head> <body>    <center>        <h1>GeeksforGeeks</h1>        <h2>HTML thead align Attribute</h2>                 <table>            <!-- thead tag starts from here -->            <thead align="char" valign="bottom"                        char="M">                <tr>                    <th>Name</th>                    <th>User Id</th>                </tr>            </thead>            <!-- thead tag ends here -->             <tbody>                <tr>                    <td>Ram</td>                    <td>@ram_b</td>                </tr>                <tr>                    <td>Shashank</td>                    <td>@shashankla</td>                </tr>            </tbody>        </table>    </center></body> </html>
Output:
  
Supported Browsers: The browser supported by HTML <thead> align attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
kumargaurav97520
HTML-Attributes
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Scala String lastIndexOf() method with example

03 Oct, 2019
The lastIndexOf() method is utilized to return the index of the last appearance of the character we specify in the argument from the stated string.
Method Definition: int lastIndexOf(int ch)Return Type: It returns the index of the last appearance of the character in the argument.
Example #1:
// Scala program of int lastIndexOf()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying lastIndexOf method        val result = "GeeksforGeeks".lastIndexOf('G')                  // Displays output        println(result)          }} 
8

Example #2:
// Scala program of int lastIndexOf()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying lastIndexOf method        val result = "GeeksforGeeks".lastIndexOf('e')                  // Displays output        println(result)          }} 
10

Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install Scala with VSCode?
Inheritance in Scala
Scala | Option
Hello World in Scala
Scala ListBuffer
Scala | Traits
Implicit Parameters In Scala
Data Types in Scala
Scala Sequence
Scala String trim() method with example
Grand Central Dispatch (GCD)

Grand Central Dispatch (GCD) - a technology for Apple’s Mac OS X and iOS operating systems-is a combination of extensions to the C language, an API, and a run-time library that allows application developers to identify sections of code to run in parallel. Like OpenMP, GCD manages most of the details of threading. GCD identifies extensions to the C and C++ languages known as blocks. A block is simply a self-contained unit of work. It is specified by a caret ˆ inserted in front of a pair of braces { }. A simple example of a block is shown below &minus;
{
   ˆprintf("This is a block");
}
It schedules blocks for run-time execution by placing them on a dispatch queue. When it removes a block from a queue, it assigns the block to an available thread from the thread pool it manages. GCD identifies two types of dispatch queues: serial and concurrent. Blocks placed on a serial queue are removed in FIFO order. Once a block has been removed from the queue, it must complete execution before another block is removed. Each process has its own serial queue (known as main queue). Developers can create additional serial queues that are local to particular processes. Serial queues are useful for ensuring the sequential execution of several tasks. Blocks placed on a concurrent queue are also removed in FIFO order, but several blocks may be removed at a time, thus allowing multiple blocks to execute in parallel. There are three system-wide concurrent dispatch queues, and they are distinguished according to priority: low, default, and high. Priorities represent an approximation of the relative importance of blocks. Quite simply, blocks with a higher priority should be placed on the high priority dispatch queue. The following code segment illustrates obtaining the default-priority concurrent queue and submitting a block to the queue using the dispatch async() function −
dispatch_queue_t queue = dispatch_get_global_queue
(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch async(queue, ˆ{ printf("This is a block."); });
Internally, GCD’s thread pool is composed of POSIX threads. GCD actively manages the pool, allowing the number of threads to grow and shrink according to application demand and system capacity.
MySQL BETWEEN Operator

The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
Below is a selection from the "Products" table in the Northwind 
sample database:
The following SQL statement selects all products with a price between 10 and 20:
To display the products outside the range of the previous example, use 
NOT BETWEEN:
The following SQL statement selects all products with a price between 10 and 
20. In addition; do not show products with a CategoryID of 1,2, or 3:
The following SQL statement selects all products with a ProductName between "Carnarvon 
Tigers" and "Mozzarella di Giovanni":
The following SQL statement selects all products with a ProductName between "Carnarvon 
Tigers" and "Chef Anton's Cajun Seasoning":
The following SQL statement selects all products with a ProductName not 
between "Carnarvon 
Tigers" and "Mozzarella di Giovanni":
Below is a selection from the "Orders" table in the Northwind 
sample database:
The following SQL statement selects all orders with an OrderDate between '01-July-1996' and 
'31-July-1996':
Use the BETWEEN operator to select all the records where the value of the Price column is between 10 and 20.
SELECT * FROM Products
WHERE Price ;

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.
What is Addition Assignment Operator (+=) in JavaScript?

It adds the right operand to the left operand and assigns the result to the left operand.
You can try to run the following code to learn how to work with Addition Assignment Operator −
<html>
   <body>
      <script>
         var a = 33;
         var b = 10;

         document.write("Value of a => (a += b) => ");
         result = (a += b);
         document.write(result);
         document.write(linebreak);
      </script>
   </body>
</html>
Django rest-framework JWT authentication

If you ever worked with Django REST framework, then you surely know about JWT authentication. JWT authentication is used for token authentication and it is really a popular method for authentication in Django. JWT stand for JSON Web Token. Let's see how to work with it.
First, install a package −
pip install djangorestframework-simplejwt
pip install djangorestframework
We are not going to need an App for this, we will just do a basic setup for
Django REST framework frontend and authentication backend.
In settings.py, add the following −
INSTALLED_APPS = [
...
'rest_framework_simplejwt',
'rest_framework'
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
   )
}
Here, we added the rest_framework and JWT auth framework as an app and for authentication backend, we added JWT auth.
In project's urls.py −
from django.urls import path
from rest_framework_simplejwt.views import (
   TokenObtainPairView,
   TokenRefreshView,
)
urlpatterns = [
   path('admin/', admin.site.urls),
   path('api/token/', TokenObtainPairView.as_view(), name='t
oken_obtain_pair'),
   path('api/token/refresh/', TokenRefreshView.as_view(), na
me='token_refresh'),
]
Here, we added two extra urls, one is for generating token in with username and password and the other is for authentication using generated token.
Multiline macros in C

In this section we will see, how can write multiline macros in C. We can write multiline macros like functions, but for macros, each line must be terminated with backslash ‘\’ character. If we use curly braces ‘{}’ and the macros is ended with ‘}’, then it may generate some error. So we can enclose the entire thing into parenthesis.
Please check the following program to get the idea about multiline macros.
#include<stdio.h>
#define PRINT(x, str) ({\
   printf("The number %d", x);\
   printf(" is ");\
   printf(#str);\
   printf("\n");\
})
int main() {
   int x = 10;
   if(x % 2 == 0){
      PRINT(x, EVEN);
   }
}
The number 10 is EVEN
Insertion Sort

This sorting technique is similar with the card sorting technique, in other words, we sort cards using insertion sort mechanism. For this technique, we pick up one element from the data set and shift the data elements to make a place to insert back the picked up an element into the data set.
Time Complexity: O(n) for best case, O(n^2) for average and worst case
Space Complexity: O(1)
Input:
The unsorted list: 9 45 23 71 80 55
Output:
Array before Sorting: 9 45 23 71 80 55
Array after Sorting: 9 23 45 55 71 80
insertionSort(array, size)
Input − An array of data, and the total number in the array
Output &−  The sorted Array
Begin
   for i := 1 to size-1 do
      key := array[i]
      j := i
      while j > 0 AND array[j-1] > key do
         array[j] := array[j-1];
         j := j – 1
      done
      array[j] := key
   done
End
#include<iostream>
using namespace std;

void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}

 void insertionSort(int *array, int size) {
   int key, j;

   for(int i = 1; i<size; i++) {
      key = array[i];//take value
      j = i;

      while(j > 0 && array[j-1]>key) {
         array[j] = array[j-1];
         j--;
      }

      array[j] = key;//insert in right place
   }
}

int main() {
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   int arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;

   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }

   cout << "Array before Sorting: ";
   display(arr, n);
   insertionSort(arr, n);
   cout << "Array after Sorting: ";
   display(arr, n);
}
Enter the number of elements: 6
Enter elements:
9 45 23 71 80 55
Array before Sorting: 9 45 23 71 80 55
Array after Sorting: 9 23 45 55 71 80
Difference between List and Tuples in Python.

List is a container to contain different types of objects and is used to iterate objects.
Example
list = ['a', 'b', 'c', 'd', 'e']
Tuple is also similar to list but contains immutable objects. Tuple processing is faster than List.
Example
tuples = ('a', 'b', 'c', 'd', 'e')
Following are the important differences between List and Tuple.
How to add a new column in an R data frame with count based on factor column?

While doing the data analysis, often we have to deal with factor data and we might want to find the frequency or count of a level of factor and the other variable combination. This helps us to make comparison within and between factor levels. Therefore, we can add a new column as count to find the required frequency and it can be done by using group_by and mutate function of dplyr package.
Consider the below data frame −
 Live Demo
> Group<-rep(c("A","B","C","D","E"),times=10)
> Rating<-sample(1:10,50,replace=TRUE)
> df<-data.frame(Group,Rating)
> head(df,20)
   Group Rating
1    A    1
2    B    6
3    C    2
4    D    4
5    E    9
6    A    3
7    B    5
8    C    7
9    D    1
10   E    9
11   A    9
12   B    8
13   C    9
14   D    2
15   E    6
16   A    2
17   B    2
18   C    2
19   D    2
20   E    2
> tail(df,20)
   Group Rating
31    A    1
32    B    7
33    C    10
34    D    8
35    E    6
36    A    8
37    B    4
38    C    4
39    D    10
40    E    4
41    A    6
42    B    4
43    C    3
44    D    7
45    E    5
46    A    1
47    B    6
48    C    7
49    D    1
50    E    6
Loading dplyr package and finding the count −
> library(dplyr)
> df_with_count<-df%>%group_by(Group,Rating)%>%mutate(count=n())
> head(df_with_count,20)
# A tibble: 20 x 3
# Groups: Group, Rating [17]
Group Rating count
 <fct> <int> <int>
1 A      1    4
2 B      6    3
3 C      2    3
4 D      4    1
5 E      9    2
6 A      3    1
7 B      5    1
8 C      7    2
9 D      1    3
10 E     9    2
11 A     9    1
12 B     8    1
13 C     9    1
14 D     2    3
15 E     6    3
16 A     2    1
17 B     2    1
18 C     2    3
19 D     2    3
20 E     2    1
> tail(df_with_count,20)
# A tibble: 20 x 3
# Groups: Group, Rating [17]
Group Rating count
 <fct> <int> <int>
1 A      1    4
2 B      7    1
3 C      10   2
4 D      8    1
5 E      6    3
6 A      8    1
7 B      4    2
8 C      4    1
9 D      10   1
10 E      4   1
11 A      6    1
12 B      4    2
13 C     3     1
14 D     7     1
15 E     5     2
16 A     1     4
17 B     6     3
18 C     7     2
19 D     1     3
20 E     6     3
Pyspark – Import any data. A brief guide to import data with Spark | by Alexandre Wrg | Towards Data Science

With this article, I will start a series of short tutorials on Pyspark, from data pre-processing to modeling. The first will deal with the import and export of any type of data, CSV , text file, Avro, Json ...etc. I work on a virtual machine on google cloud platform data comes from a bucket on cloud storage. Let’s import them.
Spark has an integrated function to read csv it is very simple as:
csv_2_df = spark.read.csv("gs://my_buckets/poland_ks")#print itcsv_2_df.show()
The data is loaded with the right number of columns and there does not seem to be any problem in the data, however the header is not fixed. We need to set header = True parameters.
csv_2_df = spark.read.csv("gs://my_buckets/poland_ks", header = "true")
There’s others syntax possible like.
csv_2_df= spark.read.load("gs://my_buckets/poland_ks", format="csv", header="true")
and parameters like sep to specify a separator or inferSchema to infer the type of data, let’s look at the schema by the way.
csv_2_df.printSchema()
Our dataframe has all types of data set in string, let’s try to infer the schema.
csv_2_df = spark.read.csv("gs://my_buckets/poland_ks", header =True, inferSchema=True)csv_2_df.printSchema()
We can specify our Schema manualy
from pyspark.sql.types import *schema = StructType([    StructField("ID_DAY", DateType()),    StructField("SID_STORE", IntegerType()),    StructField("NB_TICKET", IntegerType()),    StructField("F_TOTAL_QTY", IntegerType()),    StructField("F_VAL_SALES_AMT_TCK", DoubleType()),    StructField("SITE_FORMAT", StringType())])csv_2_df = spark.read.csv("gs://alex_precopro/poland_ks", header = 'true', schema=schema)
json_to_df = spark.read.json("gs://my_bucket/poland_ks_json")
parquet_to_df = spark.read.parquet("gs://my_bucket/poland_ks_parquet")
In the case of an Avro we need to call an external databricks package to read them.
df = spark.read.format("com.databricks.spark.avro").load("gs://alex_precopro/poland_ks_avro", header = 'true')
In the same way spark has a built-in function
textFile = spark.read.text('path/file.txt')
you can also read textfile as rdd
# read input text file to RDDlines = sc.textFile('path/file.txt')# collect the RDD to a listlist = lines.collect()
To export data you have to adapt to what you want to output if you write in parquet, avro or any partition files there is no problem. If we want to write in CSV we must group the partitions scattered on the different workers to write our CSV file
#partitioned fileoutput.write.parquet(“gs://my_bucket/my_output")#csv partitioned_output.coalesce(1).write.mode("overwrite")\.format("com.databricks.spark.csv")\.option("header", "true")\.option("sep", "|")\.save('gs://my_bucket/my_output_csv')
By using coalesce(1) or repartition(1) all the partitions of the dataframe are combined in a single block.
We saw how to import our file and write it now. Let’s go to my next article to learn how to filter our dataframe. Thanks. You can find the code here : https://github.com/AlexWarembourg/Medium
How to write, generate and use Javadoc in Eclipse?

To generate Java docs for your project you need to write the required information about the field, method or class as.
/**
   *
   * The method prints a simple message on the Console.
   *
*/
Then to generate the document follow the steps given below −
Step 1 − Open eclipse, select the option Project →Generate Javadoc.
Step 2 − Select the javadoc.exe file from the bin folder of java installation directory,select the destination folder for the generated java doc and select Next.
Step 3 − Type the title of the documentation in the Document title and select thefinish button.
Step 4 − Finally, you can observe the generated doc files in the generated folder.
You can view the document by opening the index.html file with the browser.
How to connect Java to MySQL?

To connect Java to MySQL, the Java code is as follows −
import java.sql.Connection;
import java.sql.DriverManager;
public class LostConnectionURLDemo {
   public static void main(String[] args){
      String JDBCURL="jdbc:mysql://localhost:3306/web?autoReconnect=true";
      Connection con=null;
       try{
          con = DriverManager.getConnection(JDBCURL,"root","123456");
          System.out.println("connection is established");
       }
      catch(Exception e){
         e.printStackTrace();
      }
   }
}
This will produce the following output −
Display Month in MMM format in Java

The MMM format for months is the short name i.e. Jan, Feb, Mar, Apr, etc. Here, we will use the following.
SimpleDateFormat("MMM");
Let us see an example.
// displaying month in MMM format SimpleDateFormat simpleformat = new SimpleDateFormat("MMM");
String strMonth= simpleformat.format(new Date());
System.out.println("Month in MMM format = "+strMonth);
Above, we have used the SimpleDateFormat class, therefore the following package is imported.
import java.text.SimpleDateFormat;
The following is an example.
 Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) throws Exception {
      // displaying current date and time
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss");
      System.out.println("Date and time = "+simpleformat.format(cal.getTime()));
      // displaying date
      simpleformat = new SimpleDateFormat("dd/MMMM/yyyy");
      String str = simpleformat.format(new Date());
      System.out.println("Current Date = "+str);
      // displaying month in MMM format
      simpleformat = new SimpleDateFormat("MMM");
      String strMonth= simpleformat.format(new Date());
      System.out.println("Month in MMM format = "+strMonth);
      // current time
      simpleformat = new SimpleDateFormat("HH.mm.ss");
      String strTime = simpleformat.format(new Date());
      System.out.println("Current Time = "+strTime);
   }
}
Date and time = Mon, 26 Nov 2018 10:43:56
Current Date = 26/November/2018
Month in MMM format = Nov
Current Time = 10.43.56
div() function in C++

The C / C++ library function div_t div(int numer, int denom) divides numer
(numerator) by denom (denominator). Following is the declaration for div()
function.
div_t div(int numer, int denom)
The parameters are numerator and the denominator. This function returns the value
in a structure defined in <cstdlib>, which has two members. For div_t:int quot; int
rem;
 Live Demo
#include <iostream>
#include <cstdlib>
using namespace std;
int main () {
   div_t output;
   output = div(27, 4);
   cout << "Quotient part of (27/ 4) = " << output.quot << endl;
   cout << "Remainder part of (27/4) = " << output.rem << endl;
   output = div(27, 3);
   cout << "Quotient part of (27/ 3) = " << output.quot << endl;
   cout << "Remainder part of (27/3) = " << output.rem << endl;
   return(0);
}
Quotient part of (27/ 4) = 6
Remainder part of (27/4) = 3
Quotient part of (27/ 3) = 9
Remainder part of (27/3) = 0