code-rag-bench/online-tutorials huggingface dataset:
Running multiple commands when a button is pressed in Tkinter

The Button widget provides a way to communicate through all the existing functionalities of an application. We can perform a certain action with the help of a Button that encapsulates the function and the objects. However, there might be cases when we want to perform multiple operations with a single button. This can be achieved by defining the lambda functions which target multiple events or callback in the application.
In this example, we will add multiple events to a specific Button.
#Import the Tkinter Library
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry of window
win.geometry("700x350")

#Define functions
def display_msg():
   label.config(text="Top List of Programming Language")

def show_list():
   listbox= Listbox(win, height=10, width= 15, bg= 'grey', activestyle= 'dotbox',font='aerial')
   listbox.insert(1,"Go")
   listbox.insert(1,"Java")
   listbox.insert(1,"Python")
   listbox.insert(1,"C++")
   listbox.insert(1,"Ruby")
   listbox.pack()
   button.destroy()

#Create a Label widget to display the message
label= Label(win, text= "", font= ('aerial 18 bold'))
label.pack(pady= 20)

#Define a Button widget
button= Button(win, text= "Click Here",command= lambda:[display_msg(), show_list()])
button.pack()
win.mainloop()
Running the above code will display a window containing a button.
When we click the Button, it will perform two tasks in parallel. It will display a window containing a Label widget and a List of strings.
Flexible Array Members in a structure in C

Flexible Array members in a structure in C means we can declare array without its dimension within a structure and its size will be flexible in nature. Flexible array member must be the last member of class.
Here is an example:
#include
#include
#include
//structure of type employee and must contain at least one more named member
in addition to the flexible array member.
struct employee
{
   int emp_id;
   int name_len;
   int emp_size; //‘emp_size’ variable is used to store the size of flexible
   character array emp_name[].
   char emp_name[]; //Flexible array member emp_name[] should be the last member of class.
};
struct employee *createEmployee(struct employee *e, int id, char a[])
{
   e = (struct employee *)malloc( sizeof(*e) + sizeof(char) * strlen(a)); //memory allocation
   e->emp_id = id;
   e->name_len = strlen(a);
   //Assigning size according to size of emp_name which is a copy of user provided
   array a[].
   strcpy(e->emp_name, a);
   return e;
}
void printEmployee(struct employee *e) //print the details of the employee.
{
   printf("Employee_id : %d\n" "Employee Name : %s\n" "Name Length: %d\n\n", e->emp_id, e->emp_name, e->name_len);
}
int main()
{
   struct employee *e1 = createEmployee(e1, 26, "Ram");
   struct employee *e2 = createEmployee(e2, 53, "Madhu");
   printEmployee(e1);
   printEmployee(e2);
   printf("Size of structure Employee: %lu\n",
   sizeof(struct employee));
   return 0;
}
Employee_id : 26
Employee Name : Ram
Name Length: 3
Employee_id : 53
Employee Name : Madhu
Name Length: 5
Size of structure Employee: 12
Insert a new axis within a NumPy array

29 Aug, 2020
This post deals with the ways to increase the dimension of an array in NumPy. NumPy provides us with two different built-in functions to increase the dimension of an array i.e., 
1D array will become 2D array
2D array will become 3D array
3D array will become 4D array
4D array will become 5D array

Method 1: Using numpy.newaxis()The first method is to use numpy.newaxis object. This object is equivalent to use None as a parameter while declaring the array. The trick is to use the numpy.newaxis object as a parameter at the index location in which you want to add the new axis.Example: 
Python3
import numpy as np    arr = np.arange(5*5).reshape(5, 5)print(arr.shape)  # promoting 2D array to a 5D array# arr[None, ..., None, None]arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]  print(arr_5D.shape)
Output: 
(5, 5)
(1, 5, 5, 1, 1)

Method 2: Using numpy.expand_dims()
The second method is to use numpy.expand_dims() function that has an intuitive axis kwarg. This function takes two parameters. The first is the array of which you want to increase the dimension of and the second is index/indexes of array on which you want to create a new axis.Example: 
Python3
import numpy as np    x = np.zeros((3, 4))y = np.expand_dims(x, axis=1).shapeprint(y)
Output: 
(3, 1, 4)

Example 2: Simultaneously insert many new axes in the array.
Python3
import numpy as np    arr = np.arange(5*5).reshape(5,5)print(arr.shape)  newaxes = (0, 3, -1)arr_5D = np.expand_dims(arr, axis=newaxes)print(arr_5D.shape)
Output: 
(5, 5)
(1, 5, 5, 1, 1)

Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pascal - Passing Pointers to Subprograms

Pointer variables may be passed as parameters in function and procedure arguments. Pointer variables can be passed on both as value and variable parameters; however, when passed as variable parameters, the subprogram might inadvertently alter the value of the pointer which will lead to strange results.
The following program illustrates passing pointer to a function −
program exPointertoFunctions;
type
   iptr = ^integer;

var
   i: integer;
   ptr: iptr;

function getNumber(p: iptr): integer;
var
   num: integer;

begin
   num:=100;
   p:= @num;
   getNumber:=p^;
   end; 

begin
   i := getNumber(ptr);
   
   writeln(' Here the pointer brings the value ', i);
end.
When the above code is compiled and executed, it produces the following result −
Here the pointer brings the value: 100
How to set a background color to full page using Tailwind CSS ?

26 May, 2021
In this article, we will learn to apply background color using Tailwind CSS.
Approach:
We can set a full-page background color by simply changing the screen height of an HTML body. In Tailwind  CSS, we use an alternative of CSS background-color property which is represented as background-color-opacity ( eg: bg-blue-200 ) and it is used to specify the background color of an element. The background covers the total size of the element with padding and border but excluding margin.
Note: For screen height, you can use ‘h-screen’ to make an element span the entire height of the view port. 
Syntax:
<body class="h-screen bg-gradient-to-b from-green-200 to-green-500" >
Example 1: The following example sets the full background color of an HTML document with 3 divs.
HTML
<!DOCTYPE html><html>    <head>        <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"               rel="stylesheet" />        <style>            h2 {                text-align: center;            }        </style>    </head>      <body class="h-screen bg-gradient-to-b                 from-green-200 to-green-500">        <h2 class="text-green-600 text-5xl font-bold">            GeeksforGeeks        </h2>        <center>            <b>Tailwind CSS background color</b>        </center>        <br />        <div class="mx-2 grid grid-cols-3 gap-2                    bg-blue-800 rounded-lg">            <div class="p-6 bg-green-600 border-dashed                         border-4 border-green-300">                Dashed border            </div>            <div class="p-6 bg-green-600 border-double                        border-4 border-green-300">                Double border            </div>            <div class="p-6 bg-green-600 border-dotted                        border-4 border-green-300">                Dotted border            </div>        </div>    </body></html>
Output:
Example 2: If you avoid using utilities for setting the height of an element like h-screen as in the above code then you will get the same result, by simply using background-color-opacity ( bg-blue-200 ) on the HTML body.
HTML
<!DOCTYPE html><html>    <head>        <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"               rel="stylesheet" />    </head>      <body class="bg-blue-200 text-center">        <h2 class="text-green-600 text-5xl font-bold">            GeeksforGeeks        </h2>        <b>Tailwind CSS Background Color Class</b>          <p>            Using Tailwind CSS background color is fun        </p>    </body></html>
Output:
Picked
Tailwind CSS
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in C/C++ program

The array is a collection of a fixed number of items of the same data type. These elements are stored in contiguous memory locations in the memory.
Every single element of the value can be accessed from its index value using the brackets “[]” and the array name like a[4], a[3], etc.
In c/c++ programming languages, arrays are declared by defining the type and length (number of elements) of the array. The below syntax show declaration of an array in c/c++ −
data_tpye array_name[length];
For example, declaring an array of type float named the percentage of length 10.
float percentage[10]
In c++ programming language, you have multiple ways to initialize values i.e. either one by one or using a single statement for declaring all values.
one by one −
percentage[5] = 45.3;
declaring all values at once −
float percentage[] = {56.4 , 99.0, 12.20, 67.2}
To access array values, we will use index values in curly braces with the name of an array. Example,
float anam’spercentage = percentage[4];
program to print all values of array using for loop
 Live Demo
#include <iostream>
using namespace std;
int main(){
   float percentage[] = {56.4 , 99.0, 12.20, 67.2};
   cout<<"printing all values of the array :\n";
   for(int i = 0; i<4 ; i++){
      cout<<"element "<<i+1<<" = "<<percentage[i]<<endl;
   }
   return 0;
}
printing all values of the array :
element 1 = 56.4
element 2 = 99
element 3 = 12.2
element 4 = 67.2
print a specific value of the array −
 Live Demo
#include <iostream>
using namespace std;
int main(){
   float percentage[4];
   percentage[0] = 56.3;
   percentage[1] = 99.12;
   percentage[2] = 78.32;
   percentage[3] = 61.3;
   cout<<"3rd element is "<<percentage[2];
   return 0;
}
3rd element is 78.32
reinitializing array values −
 Live Demo
#include <iostream>
using namespace std;
int main(){
   float percentage[4];
   percentage[0] = 56.3;
   percentage[1] = 99.12;
   percentage[2] = 78.32;
   percentage[3] = 61.3;
   cout<<"3rd element is "<<percentage[2];
   percentage[2] = 12.22;
   cout<<"\nafter change :\n";
   cout<<"3rd element is "<<percentage[2];
   return 0;
}
3rd element is 78.32
after change :
3rd element is 12.22
How to Add Audio Files to Android App in Android Studio? - GeeksforGeeks

18 Feb, 2021
The audio file format is a file format for saving digital audio data on a computer system and all are aware of audio files. So in this article, we are going to discuss how can we add audio files to the android app. There are three major groups of audio file formats:
Format Name
Description
Examples
Note: Android supports the following audio format
MP3
MIDI
Opus
Vorbis
PCM/WAVE
FLAC
AMR-WB
AMR-NB etc.
Step 1: Open your android studio go to the app > res > right-click > New > Android Resource Directory as shown in the below image. 
Step 2: Then a pop-up screen will arise like below. Here in Resource type choose raw.
Step 3: After choosing the raw from the dropdown menu click on the OK button and keep all the things as it is.
Step 4: Now you can see the raw folder has been created and you can find the folded in the app > res > raw as shown in the below image. 
Step 5: After creating the raw folder successfully go to your own system and copy the required audio files as we do normally. Now again come back to the android studio and right-click on the raw folder. Then click on the Paste button as shown in the below image.
Step 6: Here on this screen you can rename your audio file name as your requirement. And click on the Refactor button. And you are done.
Now go to the app > res > raw and you can find your audio file as shown in the below figure.
Now open the Java File of the desired activity, here we are adding audio in the MainActivity.java file and add this following code in the MainActivity.java file.
Java
MediaPlayer music = MediaPlayer.create(MainActivity.this, R.raw.music);music.start();
android
Android-Studio
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Services in Android with Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
CardView in Android With Example
Navigation Drawer in Android
How to Update Gradle in Android Studio?
Flutter - Custom Bottom Navigation Bar
Ruby | DateTime now() function - GeeksforGeeks

09 Jan, 2020
DateTime#now() : now() is a DateTime class method which returns a DateTime object denoting the given calendar date.
Syntax: DateTime.now()
Parameter: DateTime values
Return: DateTime object denoting the given calendar date.
Example #1 :
# Ruby code for DateTime.now() method  # loading libraryrequire 'date'  # declaring DateTime valuedate_a = DateTime.now()    #  now methodputs "DateTime now form : #{date_a}\n\n"
Output :
DateTime now form : 2019-08-30T15:14:33+02:00


Example #2 :
# Ruby code for DateTime.now() method   # loading libraryrequire 'date'   # declaring DateTime valuedate_b = DateTime.now()   #  now methodputs "DateTime now form : #{date_b}\n\n"
Output :
DateTime now form : 2019-09-02T10:36:47+00:00


Note : The output depends on the time at which the code runs on your system.
Ruby DateTime-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Ruby | Numeric round() function
Ruby | String capitalize() Method
p5.js | pixelDensity() function - GeeksforGeeks

16 Apr, 2019
The pixelDensity() function in p5.js is used to set the pixel scaling for high pixel density displays. The default value of pixel density is set to match display density. The pixelDensity(1) is used to turn off display density. The pixelDensity() function without arguments returns the current pixel density of the sketch.
Syntax:
pixelDensity(c)
Parameters: This function accepts single parameter c which stores the value of the scale.
Below programs illustrate the pixelDensity() function in p5.js:
Example 1: This example uses pixelDensity() function to display the pixel density.
function setup() {          // Create canvas of window size    createCanvas(windowWidth, windowHeight);          // Set Pixel Density to 9    pixelDensity(9);}   function draw() {          // Set the background color    background(0, 200, 0);        color("green");          // Set the text size    textSize(30);          // Set the text align    textAlign(CENTER);          // Display text on the screen    text("GeeksForGeeks!", windowWidth/2,                windowHeight/2);    text("PixelDensity is " + pixelDensity(),         windowWidth/2, windowHeight/2 + 40);   }
Output:
Example 2: This example uses pixelDensity() function to display the pixel density.
function setup() {          // Create canvas of window size    createCanvas(windowWidth, windowHeight);          // Set Pixel Density to 9    pixelDensity(3);}   function draw() {          // Set the background color    background(160, 200, 50);          // Set the text size    textSize(30);          // Set the text align    textAlign(CENTER);          // Display text on the screen    text("GeeksForGeeks!", windowWidth/2,                windowHeight/2);    text("PixelDensity is " + pixelDensity(),         windowWidth/2, windowHeight/2 + 40);   }
Output:
Reference: https://p5js.org/reference/#/p5/pixelDensity
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Find length of longest subsequence of one string which is substring of another string in C++

Suppose, we have two strings X and Y, and we have to find the length of longest subsequence of string X, which is substring in sequence Y. So if X = “ABCD” and Y = “BACDBDCD”, then output will be 3. As “ACD” is the longest sub-sequence of X, which is substring of Y.
Here we will use the dynamic programming approach to solve this problem. So if the length of X is n, and length of Y is m, then create DP array of order (m+1)x(n+1). Value of DP[i, j] is maximum length of subsequence of X[0...j], which is substring of Y[0...i]. Now for each cell of DP, it will follow like below:
for i in range 1 to m:for j in range 1 to nwhen X[i – 1] is same as Y[j – i], then DP[i, j] := 1 + DP[i – 1, j – 1]Otherwise DP[i, j] := 1 + DP[i, j – 1]
for j in range 1 to nwhen X[i – 1] is same as Y[j – i], then DP[i, j] := 1 + DP[i – 1, j – 1]Otherwise DP[i, j] := 1 + DP[i, j – 1]
when X[i – 1] is same as Y[j – i], then DP[i, j] := 1 + DP[i – 1, j – 1]
Otherwise DP[i, j] := 1 + DP[i, j – 1]
And finally the length of longest subsequence of x, which is substring of y is max(DP[i, n]), where 1 <= i <= m.
 Live Demo
#include<iostream>
#define MAX 100
using namespace std;
int maxSubLength(string x, string y) {
   int table[MAX][MAX];
   int n = x.length();
   int m = y.length();
   for (int i = 0; i <= m; i++)
      for (int j = 0; j <= n; j++)
   table[i][j] = 0;
   for (int i = 1; i <= m; i++) {
      for (int j = 1; j <= n; j++) {
         if (x[j - 1] == y[i - 1])
            table[i][j] = 1 + table[i - 1][j - 1];
         else
            table[i][j] = table[i][j - 1];
      }
   }
   int ans = 0;
   for (int i = 1; i <= m; i++)
   ans = max(ans, table[i][n]);
   return ans;
}
int main() {
   string x = "ABCD";
   string y = "BACDBDCD";
   cout << "Length of Maximum subsequence substring is: " << maxSubLength(x, y);
}
Length of Maximum subsequence substring is: 3
Checking for vowels in array of numbers using JavaScript

We are required to write a JavaScript function that takes in takes in an array of numbers. If in that array there exists any number which is the char code any vowel in ascii we should switch that number to the corresponding vowel and return the new array.
Following is the code −
 Live Demo
const arr = [5, 23, 67, 101, 56, 111];
const changeVowel = (arr = []) => {
   for (let i=0, l=arr.length; i<l; ++i){
      let char = String.fromCharCode(arr[i])
      if ('aeiou'.indexOf(char) !== -1){
         arr[i] = char;
      };
   };
   return arr;
};
console.log(changeVowel(arr));
[ 5, 23, 67, 'e', 56, 'o' ]
Next Permutation in Python

Suppose we want to implement the next permutation method, that method rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, this method will rearrange it as the lowest possible order (That is actually, sorted in ascending order). The replacement must be in-place and do not use any extra memory. For example, if the Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
Let us see the steps −
found := false, i := length of the array – 2
while i >= 0if A[i] < A[i + 1], then found := True, and terminate the loopincrease i by 1
if A[i] < A[i + 1], then found := True, and terminate the loop
increase i by 1
if found := false, then sort the array A,
otherwisem := find maximum element index from index i + 1, from A, and from the current element A[i]swap the elements A[i] and A[m]reverse all the elements from i+1 to the end in A
m := find maximum element index from index i + 1, from A, and from the current element A[i]
swap the elements A[i] and A[m]
reverse all the elements from i+1 to the end in A
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def nextPermutation(self, nums):
      found = False
      i = len(nums)-2
      while i >=0:
         if nums[i] < nums[i+1]:
            found =True
            break
         i-=1
      if not found:
         nums.sort()
      else:
         m = self.findMaxIndex(i+1,nums,nums[i])
         nums[i],nums[m] = nums[m],nums[i]
         nums[i+1:] = nums[i+1:][::-1]
      return nums
   def findMaxIndex(self,index,a,curr):
      ans = -1
      index = 0
      for i in range(index,len(a)):
         if a[i]>curr:
            if ans == -1:
               ans = curr
               index = i
            else:
               ans = min(ans,a[i])
               index = i
      return index
ob1 = Solution()
print(ob1.nextPermutation([1,2,5,4,3]))
[1,2,5,4,3]
[1, 3, 2, 4, 5]
Threads and Thread Synchronization in C#

Using Synchronization, you can synchronize access to resources in multithreaded applications.
A mutex can be used to synchronize threads across processes Use it to prevent the simultaneous execution of a block of code by more than one thread at a time.
C# lock statement is used to ensure that a block of code runs without interruption by other threads. A Mutual-exclusion lock is obtained for a given object for the duration of the code block.
Thread pool in C# is a collection of threads. It is used to perform tasks in the background. When a thread completes a task, it is sent to the queue wherein all the waiting threads are present. This is done so that it can be reused.
Let us see how to create a thread pool.
Firstly, use the following namespace −
using System.Threading;
Now, call the threadpool class, using the threadpool object. Call the method QueueUserWorkItem.
ThreadPool.QueueUserWorkItem(new WaitCallback(Run));

The Mutex class in C# is a synchronization primitive that can also be used for interprocess synchronization.
Let us see how to create a new Mutex −
private static Mutex m = new Mutex();
Node.js | path.join() Method - GeeksforGeeks

14 Feb, 2020
The path.join() method is used to join a number of path-segments using the platform-specific delimiter to form a single path. The final path is normalized after the joining takes place. The path-segments are specified using comma-separated values.
Syntax: 
path.join( [...paths] )

Parameters: This function accepts one parameter as mentioned above and described below: 
paths: It is a comma-separated sequence of paths that would be joined together to make the final path.
Return Value: It returns a string with the complete normalized path containing all the segments.
Below examples illustrate the path.join() method in Node.js:
Example 1: 
Node.js
// Node.js program to demonstrate the   // path.join() Method    // Import the path moduleconst path = require('path');   // Joining 2 path-segmentspath1 = path.join("users/admin/files", "index.html");console.log(path1)   // Joining 3 path-segmentspath2 = path.join("users", "geeks/website", "index.html");console.log(path2)   // Joining with zero-length pathspath3 = path.join("users", "", "", "index.html");console.log(path3)
Output: 
users\admin\files\index.html
users\geeks\website\index.html
users\index.html

Example 2: 
Node.js
// Node.js program to demonstrate the   // path.join() Method    // Import the path moduleconst path = require('path');   // Normalizing of the final pathpath1 = path.join("users", "..", "files", "readme.md");console.log(path1)   // Zero length final path// returns a period (.)path2 = path.join("users", "..");console.log(path2)   // Getting the directory path one folder aboveconsole.log("Current Directory: ", __dirname);path3 = path.join(__dirname, "..");console.log("Directory above:", path3)
Output: 
files\readme.md
.
Dirname:  G:\tutorials\nodejs-path-join
Directory above: G:\tutorials

Reference: https://nodejs.org/api/path.html#path_path_join_paths
Node.js-path-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.readFileSync() Method
How to update Node.js and NPM to next version ?
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Underline Text in Tkinter Label widget

Tkinter label widgets can be styled using the predefined attributes and functions in the library. Labels are useful in place of adding text and displaying images in the application. Sometimes, we need to style the font property of Label Text such as fontfamily, font-style (Bold, strike, underline, etc.), font-size, and many more. If we want to make the label text underlined, then we can use the underline property in the font attribute.
#Import the required library
from tkinter import*
#Create an instance of tkinter frame
win= Tk()
#Define geometry of the window
win.geometry("750x250")
#Create a Label widget
label= Label(win, text= "Hey, How're you?", font= ('Helvetica 15 underline'))
label.pack()
win.mainloop()
Running the example code will make the text label underlined. In fact, we can remove the underline property just by removing it from the font values.
Python While Loops

Python has two primitive loop commands:
while loops
for loops
With the while loop we can execute a set of statements as long as a condition is true.
Print i as long as i is less than 6:
Note: remember to increment i, or else the loop will continue forever.
The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, 
which we set to 1.
With the break statement we can stop the loop even if the 
while condition is true:
Exit the loop when i is 3:
With the continue statement we can stop the 
current iteration, and continue with the next:
Continue to the next iteration if i is 3:
With the else statement we can run a block of code once when the 
condition no longer is true:
Print a message once the condition is false:
Print i as long as i is less than 6.
i = 1
 i < 6
  print(i)
  i += 1

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.
Pandas Series

A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type.
Create a simple Pandas Series from a list:
If nothing else is specified, the values are labeled with their index number. First value 
has index 0, second value has index 1 etc.
This label can be used to access a specified value.
Return the first value of the Series:
With the index argument, you can name your own labels.
Create you own labels:
When you have created labels, you can access an item by referring to the label.
Return the value of "y":
You can also use a key/value object, like a dictionary, when creating a Series.
Create a simple Pandas Series from a dictionary:
Note: The keys of the dictionary become the labels.
To select only some of the items in the dictionary, use the index 
argument and specify only the items you want to include in the Series.
Create a Series using only data from "day1" and "day2":
Data sets in Pandas are usually multi-dimensional tables, called DataFrames.
Series is like a column, a DataFrame is the whole table.
Create a DataFrame from two Series:
You will learn about DataFrames in the next chapter.
Insert the correct Pandas method to create a Series.
pd.(mylist)

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.
jQuery - toggle( speed, [callback] ) Method

The toggle( speed, [callback]) method toggles displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion.
Here is the simple syntax to use this method −
selector.toggle( speed, [callback]);

Here is the description of all the parameters used by this method −
speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
callback − This is optional parameter representing a function to call once the animation is complete.
callback − This is optional parameter representing a function to call once the animation is complete.
Following is a simple example a simple showing the usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
   
         $(document).ready(function() {

            $("#toggle").click(function(){
               $(".target").toggle( 'slow', function(){ 
                  $(".log").text('Toggle Transition Complete');
               });
            });
         });
			
      </script>
		
      <style>
         p {background-color:#bca; width:200px; border:1px solid green;}
      </style>
   </head>
	
   <body>
      <p>Click on the following button:</p>
      <button id = "toggle"> Toggle </button>

      <div class = "target">
         <img src = "../images/jquery.jpg" alt = "jQuery" />
      </div>
		
      <div class = "log"></div>
   </body>
</html>
This will produce following result −
Click on the following button −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
\notin - Tex Command

\notin - Used to create notin symbol.
{ \notin}
\notin command draws notin symbol.

\notin

∉



\notin

∉


\notin

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
How to Hide NavigationBar in Android? - GeeksforGeeks

27 Sep, 2021
NavigationBar in Android is a row comprising the back button, home button, and Recent button located at the bottom of the application. Most Android 5.0 Lollipop and above devices have no physical navigation buttons and hence come as buttons present on the screen throughout the screen life.
However, these buttons become unnecessary for applications involving games and videos. Moreover, accidental touch on these buttons can result in data loss, especially on applications that run on servers in real-time. So, in this article, we will show you how you could hide NavigationBar on Android.
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.Viewimport androidx.annotation.RequiresApiimport androidx.core.view.WindowCompatimport androidx.core.view.WindowInsetsCompatimport androidx.core.view.WindowInsetsControllerCompat  class MainActivity : AppCompatActivity() {      @RequiresApi(Build.VERSION_CODES.R)    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // A function to hide NavigationBar        hideSystemUI()    }      // Function to hide NavigationBar    @RequiresApi(Build.VERSION_CODES.R)    private fun hideSystemUI() {        WindowCompat.setDecorFitsSystemWindows(window, false)        WindowInsetsControllerCompat(window,            window.decorView.findViewById(android.R.id.content)).let { controller ->            controller.hide(WindowInsetsCompat.Type.systemBars())                          // When the screen is swiped up at the bottom             // of the application, the navigationBar shall            // appear for some time            controller.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE        }    }}
Output:
You can see that the NavigationBar is now hidden. However, we have programmed it such that when a swipe up is made at the bottom of the screen, NavigationBar will appear for a few seconds.
Before and after hiding the navigation bar
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters
Difference between write() and writelines() function in Python - GeeksforGeeks

22 Sep, 2021
In Python, there are many functions for reading and writing files. Both reading and writing functions work on open files (files opened and linked via a file object). In this section, we are going to discuss the write functions to manipulate our data through files.
The write() function will write the content in the file without adding any extra characters.
Syntax: 
# Writes string content referenced by file object.
file_name.write(content) 
As per the syntax, the string that is passed to the write() function is written into the opened file. The string may include numbers, special characters, or symbols. While writing data to a file, we must know that the write function does not add a newline character(\n) to the end of the string. The write() function returns None.
Example: 
Python3
file = open("Employees.txt", "w")  for i in range(3):   name = input("Enter the name of the employee: ")   file.write(name)   file.write("\n")     file.close()  print("Data is written into the file.")
Output:
Data is written into the file.
Sample Run:
Enter the name of the employee: Aditya
Enter the name of the employee: Aditi
Enter the name of the employee: Anil
This function writes the content of a list to a file.
Syntax:   
# write all the strings present in the list "list_of_lines" 
# referenced by file object.
file_name.writelines(list_of_lines)
As per the syntax, the list of strings that is passed to the writelines() function is written into the opened file. Similar to the write() function, the writelines() function does not add a newline character(\n) to the end of the string.
Example:
Python3
file1 = open("Employees.txt", "w")lst = []for i in range(3):    name = input("Enter the name of the employee: ")    lst.append(name + '\n')      file1.writelines(lst)file1.close()print("Data is written into the file.") 
Output:
Data is written into the file.
Sample Run:
Enter the name of the employee: Rhea
Enter the name of the employee: Rohan
Enter the name of the employee: Rahul
The only difference between the write() and writelines() is that write() is used to write a string to an already opened file while writelines() method is used to write a list of strings in an opened file.
Blogathon-2021
Picked
Blogathon
Class 12
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
Libraries in Python
GeeksforGeeks School
Reading Rows from a CSV File in Python
Data Communication - Definition, Components, Types, Channels
Sorting Algorithms in Python
PostgreSQL - CHAR Data Type - GeeksforGeeks

28 Aug, 2020
PostgreSQL supports a character data type called CHAR. This data type is used to store character of limited length. It is represented as char(n) in PostgreSQL, where n represents the limit of the length of the characters. If n is not specified it defaults to char(1) or character(1). Any attempt to store a longer string in the column that defined with char(n) results in PostgreSQL issuing an error. However, one exception is that if the excess characters are all spaces, PostgreSQL will truncate the spaces to the maximum length and store the string.
Syntax: variable_name CHAR(n)
Example :Let’s create a new table(say, char_test) for the demonstration using the below commands:
CREATE TABLE char_test (
    id serial PRIMARY KEY,
    x CHAR (1),
        y CHAR(10)
);
Now let’s insert a new row into the char_test table using the below command:
INSERT INTO char_test (x, y)
VALUES
    (
        'Geeks',
        'This is a test for char'
        
    );
At this stage PostgreSQL will raise an error as the data type of the x column is char(1) and we tried to insert a string with three characters into this column as shown below:
ERROR:  value too long for type character(1)
So, now let’s fix it.
INSERT INTO char_test (x, y)
VALUES
    (
        'G',
        'This is a test for char'
        
    );
Now, we will get the same error for the y column as the number of characters entered is greater than 10 as shown below:
ERROR:  value too long for type character(10)
Let’s fix it too.
INSERT INTO char_test (x, y)
VALUES
    (
        'G',
        'hello Geek'
        
    );
Now that we have managed to successfully assign the values to the character data type, check it by running the below command:
SELECT * FROM char_test;
Output:
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - CREATE PROCEDURE
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Cursor
How to embed a video using HTML code?

To embed a video in an HTML page, use the <iframe> element. The source attribute included the video URL. For the dimensions of the video player, set the width and height of the video appropriately.
The Video URL is the video embed link. The video we will be embedding our example will be YouTube.
To get the embed link, go to a YouTube Video and click embed as shown below. You will get a link fro embed here −
You can try to run the following code to learn how to embed a video using HTML code. Copy the embed link as shown above and add it to the HTML document
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Video embed</title>
   </head>
   <body>
      <p>Learn Eclipse</p>
      <br />
      <iframe width="560" height="315" src="https://www.youtube.com/embed/y881t8ilMyc" frameborder="0" allowfullscreen></iframe>
      </iframe>
   </body>
</html>
Click a href button with Selenium and Python?

We can click a link/button with its href link in Selenium webdriver. This can be achieved by multiple ways. We can use find_element_by_link_text() and find_element_by_partial_link_text() methods to perform this task.
The find_element_by_link_text() method is used to identify an element with the text within the anchor tag as specified in the method parameter . If there is no matching text, NoSuchElementException is thrown.
Syntax
find_element_by_link_text("Coding Ground")
The find_element_by_partial_link_text() method is used to identify an element by partially matching with the text within the anchor tag as specified in the method parameter. If there is no matching text, NoSuchElementException is thrown.
Syntax −
find_element_by_partial_link_text("Coding")
Code Implementation with find_element_by_link_text().
from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
# implicit wait for 5 seconds
driver.implicitly_wait(5)
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
# identify element with link text and click()
l=driver.find_element_by_link_text("Privacy Policy")
l.click()
driver.quit()
Code Implementation with find_element_by_partial_link_text().
from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
# implicit wait for 5 seconds
driver.implicitly_wait(5)
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
# identify element with partial link text and click()
l=driver.find_element_by_partial_link_text("Privacy")
l.click()
driver.quit()
How to measure the time taken by a function in Java?

java.lang.System.currentTimeMillis() method can be used to compute the time taken by a function in java. Trick is simple. Get the before time and after time using currentTimeMillis() where before time is the time when method is invoked and after time is when method has executed. See the example below −
 Live Demo
public class Tester{
   public static void main(String[] args) {
      long startTime = System.currentTimeMillis();
      longRunningMethod();
      long endTime = System.currentTimeMillis();
      System.out.println("Time taken: " + (endTime -startTime) + " ms");
   }

   private static void longRunningMethod() {
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
   }
}
Time taken: 1000 ms
How to Calculate Mean Absolute Error in Python? - GeeksforGeeks

28 Nov, 2021
Mean Absolute Error calculates the average difference between the calculated values and actual values. It is also known as scale-dependent accuracy as it calculates error in observations taken on the same scale. It is used as evaluation metrics for regression models in machine learning. It calculates errors between actual values and values predicted by the model. It is used to predict the accuracy of the machine learning model.
Formula:
Mean Absolute Error = (1/n) * ∑|yi – xi|
where,
Σ: Greek symbol for summation
yi: Actual value for the ith observation
xi: Calculated value for the ith observation
n: Total number of observations
Mean Absolute Error (MAE) is calculated by taking the summation of the absolute difference between the actual and calculated values of each observation over the entire array and then dividing the sum obtained by the number of observations in the array.
Example:
Python3
# Python program for calculating Mean Absolute Error  # consider a list of integers for actualactual = [2, 3, 5, 5, 9]  # consider a list of integers for actualcalculated = [3, 3, 8, 7, 6]  n = 5sum = 0  # for loop for iterationfor i in range(n):    sum += abs(actual[i] - calculated[i])  error = sum/n  # displayprint("Mean absolute error : " + str(error))
Mean absolute error : 1.8
sklearn.metrics module of python contains functions for calculating errors for different purposes. It provides a method named mean_absolute_error() to calculate the mean absolute error of the given arrays. 
Syntax:
mean_absolute_error(actual,calculated)
where
actual- Array of  actual values as first argument
calculated  – Array of predicted/calculated values as second argument
 It will return the mean absolute error of the given arrays.
Example:
Python3
# Python program for calculating Mean Absolute# Error using sklearn  # import the modulefrom sklearn.metrics import mean_absolute_error as mae  # list of integers of actual and calculatedactual = [2, 3, 5, 5, 9]calculated = [3, 3, 8, 7, 6]  # calculate MAEerror = mae(actual, calculated)  # displayprint("Mean absolute error : " + str(error))
Output
Mean absolute error : 1.8
Picked
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
MongoDB - db.collection.deleteone() - GeeksforGeeks

09 Feb, 2021
The deleteOne() method deletes the first document from the collection that matches the given selection criteria. It will delete/remove a single document from the collection. It takes four parameters, the first parameter is the selection criteria and the others are optional. If you use this method in the chapped collection, then this method will give a WriteError exception, so to delete documents from the chapped collection use drop() method. If you use this method in shared collection, then the query expression passed in this method must contain the shared key/_id field, if not then this method will give an error. You can also use this method in multi-document transactions.
Syntax:
db.Collection_name.deleteOne(
selection_criteria:<document>,
{
    writeConcern: <document>,
    collation: <document>,
    hint: <document|string>
})
Parameter:
The first parameter is the selection criteria. The type of this parameter is document.
Other parameters are optional.
Optional Parameter:
writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
Collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error.
Return:
This method returns a document that contains the following fields:
acknowledged: It is a boolean field, if the value of this field is true then the operation run with write concern. If the value of this field is false, then the operation runs without write concern.
deleteCount: This field contains the total number of deleted documents.
Examples:
In the following examples, we are working with:
Database: gfg
Collections: student
Document: Four documents contains the name and the age of the students
Delete the first matched document whose age is 17:
db.student.deleteOne({age:17})
Here, we delete the first document that matches the filter query(i.e., age:17) from the student collection using deleteOne() method.
After deletion:
Delete the first matched document whose age is less than 18:
db.student.deleteOne({age:{$lt:18}})
Here, we delete the first document that matches the filter query(i.e., {age:{$lt:18}}) from the student collection using the deleteOne() method.
Note: $lt operator means less than.
After deletion:
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
MongoDB - sort() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB Cursor
MongoDB updateMany() Method - db.Collection.updateMany()
MongoDB - Update() Method