code-rag-bench/online-tutorials huggingface dataset:
Collectors toSet() in Java with Examples

06 Dec, 2018
Collectors toSet() returns a Collector that accumulates the input elements into a new Set. There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned. This is an unordered Collector i.e, the collection operation does not commit to preserving the encounter order of input elements.
Syntax:
public static <T> Collector<T, ?, Set<T>> toSet()

where:
T: The type of the input elements.
Interface Collector<T, A, R>: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.T: The type of input elements to the reduction operation.A: The mutable accumulation type of the reduction operation.R: The result type of the reduction operation.
T: The type of input elements to the reduction operation.
A: The mutable accumulation type of the reduction operation.
R: The result type of the reduction operation.
Set: A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.
Return Value: A Collector which collects all the input elements into a Set.
Below are the examples to illustrate toSet() method:
Example 1:
// Java code to show the implementation of// Collectors toSet() function  import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {        // creating a Stream of strings        Stream<String> s = Stream.of("Geeks",                                     "for",                                     "GeeksforGeeks",                                     "Geeks Classes");          // using Collectors toSet() function        Set<String> mySet = s.collect(Collectors.toSet());          // printing the elements        System.out.println(mySet);    }}
[Geeks Classes, GeeksforGeeks, Geeks, for]

Example 2:
// Java code to show the implementation of// Collectors toSet() function  import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {          // creating a Stream of strings        Stream<String> s = Stream.of("1", "2", "3", "4");          // using Collectors toSet() function        Set<String> mySet = s.collect(Collectors.toSet());          // printing the elements        System.out.println(mySet);    }}
[1, 2, 3, 4]

Java - util package
Java-Collectors
Java-Functions
java-stream
Java-Stream-Collectors
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove HTML tags with RegExp in JavaScript?

06 Sep, 2019
Here, the task is to remove the HTML tags from the string. Here string contains a part of the document and we need to extract only the text part from it. Here we are going to do that with the help of JavaScript.
Approach:
Take the string in a variable.
Anything between the less than symbol and the greater than symbol is removed from the string by the RegExp.
Finally we will get the text.
Example 1: This example using the approach defined above.
<!DOCTYPE HTML><html>  <head>    <title>        How to remove HTML tags with RegExp in JavaScript?    </title></head>  <body id="body" style="text-align:center;">    <h1 style="color:green;">              GeeksForGeeks          </h1>    <p id="GFG_UP"        style="font-size: 15px;              font-weight: bold;">    </p>    <button onclick="GFG_Fun()">        click here    </button>    <p id="GFG_DOWN"        style="color:green;              font-size: 20px;              font-weight: bold;">    </p>    <script>        var up = document.getElementById('GFG_UP');        var str2 = '<p> GeeksForGeeks </p>';                // same as the str2.         var str1 = "< p > GeeksForGeeks < /p >";         up.innerHTML = "Click on button to remove the "+          "HTML tags from the string.<br>String = '" + str1 + "'";        var down = document.getElementById('GFG_DOWN');          function GFG_Fun() {            var regex = /( |<([^>]+)>)/ig;            down.innerHTML = str2.replace(regex, "");        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example using the approach defined above but by a different RegExp.
<!DOCTYPE HTML><html>  <head>    <title>        How to remove HTML tags       with RegExp in JavaScript?    </title></head>  <body id="body" style="text-align:center;">    <h1 style="color:green;">              GeeksForGeeks          </h1>    <p id="GFG_UP"        style="font-size: 15px;              font-weight: bold;">    </p>    <button onclick="GFG_Fun()">        click here    </button>    <p id="GFG_DOWN"        style="color:green;               font-size: 20px;              font-weight: bold;">    </p>    <script>        var up = document.getElementById('GFG_UP');        var str2 = '<p> GeeksForGeeks </p>';                 // same as the str2.        var str1 = "< p > GeeksForGeeks < /p >";          up.innerHTML = "Click on button to remove the HTML"+          " tags from the string.<br>String = '" + str1 + "'";        var down = document.getElementById('GFG_DOWN');          function GFG_Fun() {            var regex = /(<([^>]+)>)/ig;            down.innerHTML = str2.replace(regex, "");        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Conversion of S-R Flip-Flop into D Flip-Flop

28 Apr, 2020
Prerequisite – Flip-flop
1. S-R Flip-Flop :S-R flip-flop is similar to S-R latch expect clock signal and two AND gates. The circuit responds to the positive edge of clock pulse to the inputs S and R.
2. D Flip-Flop :D Flip-Flop is a modified SR flip-flop which has an additional inverter. It prevents the inputs from becoming the same value.
Conversion of S-R Flip-Flop into D Flip-Flop :
Step-1:We construct the characteristic table of D flip-flop and excitation table of S-R flip-flop.
Step-2:Using the K-map we find the boolean expression of S and R in terms of D.S = D
R = D' 
S = D
R = D' 
Step-3:We construct the circuit diagram of the conversion of S-R flip-flop into D flip-flop.
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find size of a list in Python

12 Nov, 2018
In Python, List is a collection data-type which is ordered and changeable. A list can have duplicate entry as well. Here, the task is find the number of entries in a list. See the examples below.
Examples:
Input : a = [1, 2, 3, 1, 2, 3]
Output : 6
Count the number of entries in the list a.

Input : a = []
Output : 0

The idea is to use len() in Python
# Python program to demonstrate working# of len()a = []a.append("Hello")a.append("Geeks")a.append("For")a.append("Geeks")print("The length of list is: ", len(a))
The length of list is:  4

Example 2:
# Python program to demonstrate working# of len()n = len([10, 20, 30])print("The length of list is: ", n)
The length of list is:  3

How does len() work?len() works in O(1) time as list is an object and has a member to store its size. Below is description of len() from Python docs.
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
How to check if a list is empty in Python
Picked
python-list
Technical Scripter 2018
Python
Technical Scripter
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
java.lang.reflect.Method.getModifiers() Method Example

The java.lang.reflect.Method.getModifiers() method returns the Java language modifiers for the method represented by this Method object, as an integer. The Modifier class should be used to decode the modifiers.
Following is the declaration for java.lang.reflect.Method.getModifiers() method.
public int getModifiers()

the Java language modifiers for the underlying member.
The following example shows the usage of java.lang.reflect.Method.getModifiers() method.
package com.tutorialspoint;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class MethodDemo {

   public static void main(String[] args) {

      Method[] methods = SampleClass.class.getMethods();
      for (Method method : methods) {
         System.out.println("Modifier: " + Modifier.toString(method.getModifiers()));
         System.out.println("Method: " + method.toGenericString());
      }
   }
}

class SampleClass {
   private String sampleField;

   public String getSampleField() throws ArrayIndexOutOfBoundsException {
      return sampleField;
   }

   public void setSampleField(String sampleField) {
      this.sampleField = sampleField; 
   } 
}
Let us compile and run the above program, this will produce the following result −
Modifier: public
Method: public java.lang.String com.tutorialspoint.SampleClass.getSampleField() throws java.lang.ArrayIndexOutOfBoundsException
Modifier: public
Method: public void com.tutorialspoint.SampleClass.setSampleField(java.lang.String)
Modifier: public final
Method: public final void java.lang.Object.wait() throws java.lang.InterruptedException
Modifier: public final
Method: public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
Modifier: public final native
Method: public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
Modifier: public
Method: public boolean java.lang.Object.equals(java.lang.Object)
Modifier: public
Method: public java.lang.String java.lang.Object.toString()
Modifier: public native
Method: public native int java.lang.Object.hashCode()
Modifier: public final native
Method: public final native java.lang.Class<?> java.lang.Object.getClass()
Modifier: public final native
Method: public final native void java.lang.Object.notify()
Modifier: public final native
Method: public final native void java.lang.Object.notifyAll()

 Print
 Add Notes
 Bookmark this page
Python String find() Method

Python string method find() determines if string str occurs in string, or in a substring of string if starting index beg and ending index end are given.
str.find(str, beg=0, end=len(string))

str − This specifies the string to be searched.
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the length of the string.
end − This is the ending index, by default its equal to the length of the string.
Index if found and -1 otherwise.
#!/usr/bin/python

str1 = "this is string example....wow!!!";
str2 = "exam";

print str1.find(str2)
print str1.find(str2, 10)
print str1.find(str2, 40)
15
15
-1


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Match element in array of MongoDB?

You can use $or operator along with limit(1) to match element in array. Let us first create a collection with documents −
> db.matchElementInArrayDemo.insertOne(
...   {
...      "StudentName" : "Chris" ,
...      "StudentOtherDetails" :
...      [
...         {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"},
...         {"StudentCountryName" : "UK" , "StudentSkills" : "Java"}
...       ]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd423282cba06f46efe9ee2")
}
> db.matchElementInArrayDemo.insertOne(
...   {
...      "StudentName" : "Chris" ,
...      "StudentOtherDetails" :
...      [
...         {"StudentCountryName" : "AUS" , "StudentSkills" : "PHP"},
...         {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"}
...      ]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd423412cba06f46efe9ee3")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.matchElementInArrayDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd423282cba06f46efe9ee2"),
   "StudentName" : "Chris",
   "StudentOtherDetails" : [
      {
         "StudentCountryName" : "US",
         "StudentSkills" : "MongoDB"
      },
      {
         "StudentCountryName" : "UK",
         "StudentSkills" : "Java"
      }
   ]
}
{
   "_id" : ObjectId("5cd423412cba06f46efe9ee3"),
   "StudentName" : "Chris",
   "StudentOtherDetails" : [
      {
         "StudentCountryName" : "AUS",
         "StudentSkills" : "PHP"
      },
      {
         "StudentCountryName" : "US",
         "StudentSkills" : "MongoDB"
      }
   ]
}
Here is the query to match element in array of MongoDB −
> db.matchElementInArrayDemo.find( { $or : [ {"StudentOtherDetails.StudentCountryName": "US" } ,{"StudentOtherDetails.StudentSkills": "MongoDB" } ] } ).limit(1);
This will produce the following output −
{ "_id" : ObjectId("5cd423282cba06f46efe9ee2"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" }, { "StudentCountryName" : "UK", "StudentSkills" : "Java" } ] }
Arduino - Keyboard Message

In this example, when the button is pressed, a text string is sent to the computer as keyboard input. The string reports the number of times the button is pressed. Once you have the Leonardo programmed and wired up, open your favorite text editor to see the results.
Warning − When you use the Keyboard.print() command, the Arduino takes over your computer's keyboard. To ensure you do not lose control of your computer while running a sketch with this function, set up a reliable control system before you call Keyboard.print(). This sketch includes a pushbutton to toggle the keyboard, so that it only runs after the button is pressed.
You will need the following components −
1 × Breadboard
1 × Arduino Leonardo, Micro, or Due board
1 × momentary pushbutton
1 × 10k ohm resistor
Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below.
Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New.
/*
   Keyboard Message test For the Arduino Leonardo and Micro,
      Sends a text string when a button is pressed.
   The circuit:
   * pushbutton attached from pin 4 to +5V
   * 10-kilohm resistor attached from pin 4 to ground
*/

#include "Keyboard.h"
const int buttonPin = 4; // input pin for pushbutton
int previousButtonState = HIGH; // for checking the state of a pushButton
int counter = 0; // button push counter

void setup() {
   pinMode(buttonPin, INPUT); // make the pushButton pin an input:
   Keyboard.begin(); // initialize control over the keyboard:
}

void loop() {
   int buttonState = digitalRead(buttonPin); // read the pushbutton:
   if ((buttonState != previousButtonState)&& (buttonState == HIGH)) // and it's currently pressed: {
      // increment the button counter
      counter++;
      // type out a message
      Keyboard.print("You pressed the button ");
      Keyboard.print(counter);
      Keyboard.println(" times.");
   }
   // save the current button state for comparison next time:
   previousButtonState = buttonState;
}
Attach one terminal of the pushbutton to pin 4 on Arduino. Attach the other pin to 5V. Use the resistor as a pull-down, providing a reference to the ground, by attaching it from pin 4 to the ground.
Once you have programmed your board, unplug the USB cable, open a text editor and put the text cursor in the typing area. Connect the board to your computer through USB again and press the button to write in the document.
By using any text editor, it will display the text sent via Arduino.

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
Can we cast an object reference to an interface reference in java? If so when?

Yes, you can.
If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.
But, using this you can access the methods of the interface only, if you try to access the methods of the class a compile time error is generated.
In the following Java example, we have an interface named MyInterface with an abstract method display().
We have a class with name InterfaceExample with a method (show()). In addition to it, we are implementing the display() method of the interface.
In the main method we are assigning the object of the class to the reference variable of the interface and trying to invoke both the method.
interface MyInterface{
   public static int num = 100;
   public void display();
}
public class InterfaceExample implements MyInterface{
   public void display() {
      System.out.println("This is the implementation of the display method");
   }
   public void show() {
      System.out.println("This is the implementation of the show method");
   }
   public static void main(String args[]) {
      MyInterface obj = new InterfaceExample();
      obj.display();
      obj.show();
   }
}
On compiling, the above program generates the following compile time error −
InterfaceExample.java:16: error: cannot find symbol
   obj.show();
      ^
symbol: method show()
location: variable obj of type MyInterface
1 error
To make this program work you need to remove the line calling the method of the class as −
 Live Demo
interface MyInterface{
   public static int num = 100;
   public void display();
}
public class InterfaceExample implements MyInterface{
   public void display() {
      System.out.println("This is the implementation of the display method");
   }
   public void show() {
      System.out.println("This is the implementation of the show method");
   }
   public static void main(String args[]) {
      MyInterface obj = new InterfaceExample();
      obj.display();
      //obj.show();
   }
}
Now, the program gets compiled and executed successfully.
This is the implementation of the display method
Therefore, you need to cast an object reference to an interface reference. Whenever you need to call the methods of the interface only.
Find one extra character in a string using C++.

Suppose we have two strings S and T, the length of S is n, and the length of T is n + 1. The T will hold all characters that are present in S, but it will hold one extra character. Our task is to find the extra character using some efficient approach.
To solve this problem, we will take one empty hash table, and insert all characters of the second string, then remove each character from the first string, the remaining character is an extra character.
 Live Demo
#include<iostream>
#include<unordered_map>
using namespace std;
char getExtraCharacter(string S, string T) {
   unordered_map<char, int> char_map;
   for (int i = 0; i < T.length(); i++)
      char_map[T[i]]++;
   for (int i = 0; i < S.length(); i++)
      char_map[S[i]]--;
   for (auto item = char_map.begin(); item != char_map.end(); item++) {
      if (item->second == 1)
      return item->first;
   }
}
int main() {
   string S = "PQRST";
   string T = "TUQPRS";
   cout << "Extra character: " << getExtraCharacter(S, T);
}
Extra character: U
\cdot - Tex Command

\cdot - Used to draw centered dot.
{ \cdot }
\cdot command draws centered dot.

a\cdot b 

a⋅b


a\cdotp b 

a⋅b


a\centerdot b 

a⋅b



a\cdot b 

a⋅b


a\cdot b 
a\cdotp b 

a⋅b


a\cdotp b 
a\centerdot b 

a⋅b


a\centerdot b 

    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
Assertions in C/C++ - GeeksforGeeks

28 Feb, 2022
Assertions are statements used to test assumptions made by programmers. For example, we may use assertion to check if the pointer returned by malloc() is NULL or not. Following is the syntax for assertion. 
void assert( int expression ); 
If the expression evaluates to 0 (false), then the expression, sourcecode filename, and line number are sent to the standard error, and then abort() function is called. For example, consider the following program.  
C
#include <stdio.h>#include <assert.h> int main(){    int x = 7;     /*  Some big code in between and let's say x       is accidentally changed to 9  */    x = 9;     // Programmer assumes x to be 7 in rest of the code    assert(x==7);     /* Rest of the code */     return 0;}
Output 
Assertion failed: x==7, file test.cpp, line 13 
This application has requested the Runtime to terminate it in an unusual 
way. Please contact the application's support team for more information.
Assertion Vs Normal Error Handling Assertions are mainly used to check logically impossible situations. For example, they can be used to check the state of a code which is expected before it starts running, or the state after it finishes running. Unlike normal error handling, assertions are generally disabled at run-time. Therefore, it is not a good idea to write statements in assert() that can cause side effects. For example, writing something like assert(x = 5) is not a good idea as x is changed and this change won’t happen when assertions are disabled. See this for more details.Ignoring Assertions In C/C++, we can completely remove assertions at compile time using the preprocessor NDEBUG.  
C
// The below program runs fine because NDEBUG is defined# define NDEBUG# include <assert.h> int main(){    int x = 7;    assert (x==5);    return 0;}
The above program compiles and runs fine. In Java, assertions are not enabled by default and we must pass an option to the run-time engine to enable them.Reference: http://en.wikipedia.org/wiki/Assertion_%28software_development%29Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Jaideep Kaiwart
bbsusheelkumar
syedmuhammadalimustafa
srinathvarda
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
How to resize an array in Java?

An array cannot be resized dynamically in Java. 
One approach is to use java.util.ArrayList(or java.util.Vector) instead of a native array.
Another approach is to re-allocate an array with a different size and copy the contents of the old array to the new array.
class ResizableArray {
   public static void main (String[] args) {
         int[] a = {1, 2, 3};
         a = (int[])resizeArray(a, 5);
         a[3] = 4;
         a[4] = 5;
         for (int i=0; i<a.length; i++)
            System.out.println(a[i]);
  }
      private static Object resizeArray (Object oldArray, int newSize) {
            int oldSize = java.lang.reflect.Array.getLength(oldArray);
            Class elementType = oldArray.getClass().getComponentType();
            Object newArray = java.lang.reflect.Array.newInstance(elementType, newSize);
            int preserveLength = Math.min(oldSize, newSize);
               if (preserveLength > 0)
                  System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
            return newArray;
      }
}

1
2
3
4
5
How do I adjust (offset) the colorbar title in Matplotlib?

To adjust (offset) the colorbar title in matplotlib, we can take the following steps −
Create a random data of 4×4 dimension.
Create a random data of 4×4 dimension.
Use imshow() method to display the data as an imgage.
Use imshow() method to display the data as an imgage.
Create a colorbar for a scalar mappable instance using colorbar() method, with im mappable instance.
Create a colorbar for a scalar mappable instance using colorbar() method, with im mappable instance.
Now, adjust (offset) the colorbar title in matplotlib, with labelpad=-1. You can assign different values to labelpad to see how it affects the colorbar title.
Now, adjust (offset) the colorbar title in matplotlib, with labelpad=-1. You can assign different values to labelpad to see how it affects the colorbar title.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt, cm
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(4, 4)
im = plt.imshow(data, cmap=cm.jet)
cb = plt.colorbar(im)
cb.set_label('Image Colorbar', labelpad=-1)
plt.show()
fstatat() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
fstatat - get file status relative to a directory file descriptor
#include <sys/stat.h> 

int fstatat(int dirfd, const char *path, struct stat * 
buf ", int " flags );


int fstatat(int dirfd, const char *path, struct stat * 
buf ", int " flags );

The fstatat() system call operates in exactly the same way as
stat(2), except for the differences described in this manual page.
If the pathname given in
path is relative, then it is interpreted relative to the directory
referred to by the file descriptor
dirfd (rather than relative to the current working directory of
the calling process, as is done by
stat(2)
for a relative pathname).
If the pathname given in
path is relative and
dirfd is the special value
AT_FDCWD, then
path is interpreted relative to the current working
directory of the calling process (like
stat(2)).
If the pathname given in
path is absolute, then
dirfd is ignored.
flags can either be 0, or include the following flag:
On success,
fstatat() returns 0. 
On error, -1 is returned and
errno is set to indicate the error.
The same errors that occur for
stat(2)
can also occur for
fstatat(). The following additional errors can occur for
fstatat(): 
See openat(2)
for an explanation of the need for
fstatat().
This system call is non-standard but is proposed for inclusion in a future revision of POSIX.1. A similar system call exists on Solaris.
fstatat() was added to Linux in kernel 2.6.16.
openat (2)
openat (2)
path_resolution (2)
path_resolution (2)
stat (2)
stat (2)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to insert an array of values in a MySQL table with a single INSERT?

Let us first create a table −
mysql> create table DemoTable
(
   ClientId int,
   ClientName varchar(50)
);
Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command. Here, we are inserting multiple values using only a single INSERT −
mysql> insert into DemoTable values(101,'Adam'),(102,'Chris'),(103,'Robert'),(104,'Sam'),(105,'Mike');
Query OK, 5 rows affected (0.16 sec)
Records: 5 Duplicates: 0 Warnings: 0
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+------------+
| ClientId | ClientName |
+----------+------------+
|      101 | Adam       |
|      102 | Chris      |
|      103 | Robert     |
|      104 | Sam        |
|      105 | Mike       |
+----------+------------+
5 rows in set (0.00 sec)
Type Erasure in Java

To support generic programming, as well as perform a stricter type check, Java implements type
erasure.
All type parameters in generic types are replaced with the bound (if unbounded) or object
type. This way, the bytecode will only contain classes, methods, and interfaces.
All type parameters in generic types are replaced with the bound (if unbounded) or object
type. This way, the bytecode will only contain classes, methods, and interfaces.
Type casts to preserve the type.
Type casts to preserve the type.
Bridge methods are generated so as to preserve the polymorphism concept in extended
generic types.
Bridge methods are generated so as to preserve the polymorphism concept in extended
generic types.
 Live Demo
import java.io.PrintStream;
import java.util.*;
public class Demo{
   public Demo(){
   }
   public static void main(String args[]){
      List my_list = new ArrayList();
      my_list.add("Hi there");
      String my_str;
      for (Iterator iter = my_list.iterator(); iter.hasNext();
         System.out.println(my_str))
      my_str = (String)iter.next();
   }
}
Hi there
A class named Demo contains a constructor that basically has no body defined inside it. In the main
function, a new array list is created, and elements are added into it using the ‘add’ function. An
iterator is defined, and a string is defined. An iterator iterates over the elements in the string using
the ‘hasNext’ function that checks if there is an element and then moves over to it. The output is
printed on the screen.
Python | Pandas Series.get() - GeeksforGeeks

13 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.get() function get item from object for given key (DataFrame column, Panel slice, etc.). Returns default value if not found.
Syntax: Series.get(key, default=None)
Parameter :key : object
Returns : value : same type as items contained in object
Example #1: Use Series.get() function to get the value for the passed index label in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', None, 'Rio'])  # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']   # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :Now we will use Series.get() function to return the value for the passed index label in the given series object.
# return the value corresponding to# the passe index labelresult = sr.get(key = 'City 3')  # Print the resultprint(result)
Output :As we can see in the output, the Series.get() function has returned the value corresponding to the passed index label. Example #2 : Use Series.get() function to get the value for the passed index label in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.get() function to return the value for the passed index label in the given series object.
# return the value corresponding to# the passe index labelresult = sr.get(key = '2011-03-31')  # Print the resultprint(result)
Output :As we can see in the output, the Series.get() function has returned the value corresponding to the passed index label.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
chpasswd command in Linux with examples - GeeksforGeeks

15 May, 2019
chpasswd command is used to change password although passwd command can also do same. But it changes the password of one user at a time so for multiple users chpasswd is used. Below figure shows the use of passwd command. Using passwd we are changing the password of the guest user. Here first you have to enter the password of the currently signed user and then you change the password of any other user. One must have administrator privileges.
chpasswd command reads a number of username and password which are separated by colon using standard input or file, and then encrypt as per the options.
Syntax:
$chpasswd
user1:user1_password
user2:user2_password
user3:user3_password

Note: After completion please press ctrl+d to exit from the command. As soon as ctrl + d is pressed password gets changed.
A simple text file can also be used to store username and password and then use them to change the password.
$cat > pass.txt
user1:user1_password
user2:user2_password
user3:user3_password

Then provide this to chpasswd command.
$chpasswd < file_name.txt

Options:
-c, –crypt-method Method_Name : This command option is used for the crypt method. The method can be DES, MD5, SHA256, SHA512 or NONE.
-e, –encrypted : It is used to supply the encrypted passwords.
-h, –help : Used to display the command options and messages.
-m, –md5 : It is used to encrypt the clear text password using the MD5 algorithm.
-s, –sha-no_of_rounds : Here you can give the number of rounds for the SHA crypt algorithm.
Example: The encryption algorithm can also be applied to the password.
$chpasswd -c SHA512
user1:user1_password
user2:user2_password
user3:user3_password

or

$chpasswd --md5
user1:user1_password
user2:user2_password
user3:user3_password

Note: Both are a different type of encryption algorithm
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
SORT command in Linux/Unix with examples
curl command in Linux with Examples
'crontab' in Linux with Examples
UDP Server-Client implementation in C
diff command in Linux with examples
Conditional Statements | Shell Script
Cat command in Linux with examples
How regular expression anchors work in  Python?



Anchors are regex tokens that don't match any characters but that say or assert something about the string or the matching process. Anchors inform us that the engine's current position in the string matches a determined location: for example, the beginning of the string/line, or the end of a string/line.
This type of assertion is useful for  many reasons. First, it lets you specify that you want to match alphabets/digits at the beginning/end of a string/line, but not anywhere else. Second, when you tell the engine that you want to find a pattern at a certain location, it  need not find that pattern at any other locations. This is why  it is recommended to use anchors whenever possible.
^ and $ are two examples of  anchor tokens in regex.
The following code shows the use of anchors ^ and $
import re
s = 'Princess Diana was a beauty icon'
result = re.search(r'^\w+', s)
print result.group()
result2 = re.search(r'\w+$', s)
print result2.group()
This gives the output
Princess
icon
Remove duplicates from a List in C#

Use the Distinct() method to remove duplicates from a list in C#.
Firstly, add a new list −
List<int> arr1 = new List<int>();
arr1.Add(10);
arr1.Add(20);
arr1.Add(30);
arr1.Add(40);
arr1.Add(50);
arr1.Add(30);
arr1.Add(40);
arr1.Add(50);
To remove duplicate elements, use the Distinct() method as shown below −
List<int> distinct = arr1.Distinct().ToList();
Here is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
   public static void Main() {
      List<int> arr1 = new List<int>();
      arr1.Add(10);
      arr1.Add(20);
      arr1.Add(30);
      arr1.Add(40);
      arr1.Add(50);
      arr1.Add(30);
      arr1.Add(40);
      arr1.Add(50);
      Console.WriteLine("Initial List ...");
      foreach (int i in arr1) {
         Console.WriteLine(i);
      }
      // Removing duplicate elements
      List<int> distinct = arr1.Distinct().ToList();
      Console.WriteLine("List after removing duplicate elements ...");
      foreach (int res in distinct) {
         Console.WriteLine("{0}", res);
      }
   }
}
Initial List ...
10
20
30
40
50
30
40
50
List after removing duplicate elements ...
10
20
30
40
50
How to show/hide dropdown menu on mouse hover using CSS ?

06 Jun, 2022
The approach of this article is to show and hide the dropdown menu on mouse hover using CSS. The task can be done by using the display property and :hover selector.
Example:  
HTML
<!DOCTYPE html><html lang="en"><head>    <title>        How to Show Hide Dropdown Using CSS    </title>     <style>        ul {            padding: 0;            list-style: none;            background: #f2f2f2;            width: 500px;        }         ul li {            display: block;            position: relative;            line-height: 21px;            text-align: left;        }        ul li a {            display: block;            padding: 8px 25px;            color: #333;            text-decoration: none;        }        ul li a:hover {            color: #fff;            background: #939393;        }        ul li ul.dropdown {            min-width: 100%;            /* Set width of the dropdown */            background: #f2f2f2;            display: none;            position: absolute;            z-index: 999;            left: 0;        }        ul li:hover ul.dropdown {            display: block;            /* Display the dropdown */        }    </style></head> <body>    <h1>        GeeksForGeeks    </h1>     <h2>        How to show and hide dropdown        menu on mouse hover using CSS?    </h2>     <ul>        <li>            <a href="#">Programming languages</a>            <ul class="dropdown">                <li><a href="#">C++</a></li>                <li><a href="#">JAVA</a></li>                <li><a href="#">PHP</a></li>            </ul>        </li>    </ul> </body> </html>
Output:
 
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of web pages and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
sanjyotpanure
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas MultiIndex.sortlevel()

24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas MultiIndex.sortlevel() function sort MultiIndex at the requested level. The result will respect the original ordering of the associated factor at that level.
Syntax: MultiIndex.sortlevel(level=0, ascending=True, sort_remaining=True)
Parameters :level : [list-like, int or str, default 0] If a string is given, must be a name of the level If list-like must be names or ints of levelsascending : False to sort in descending order Can also be a list to specify a directed orderingsort_remaining : sort by the remaining levels after level.
Returns :sorted_index : Resulting indexindexer : Indices of output values in original index
Example #1: Use MultiIndex.sortlevel() function to sort the 0th level of the MultiIndex in descending order.
# importing pandas as pdimport pandas as pd  # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography',                                      'Anthropology', 'Science'],                                             [88, 84, 98, 95]])  # Print the MultiIndexprint(midx)
Output :
Now let’s sort the 0th level of the MultiIndex in descending order.
# sort the 0th level in descending order.midx.sortlevel(level = 0, ascending = False)
Output :As we can see in the output, the function has returned a new object having the 0th level sorted in descending order. Example #2: Use MultiIndex.sortlevel() function to sort the 1st level of the MultiIndex in the increasing order.
# importing pandas as pdimport pandas as pd  # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography',                                      'Anthropology', 'Science'],                                              [88, 84, 98, 95]])  # Print the MultiIndexprint(midx)
Output :
Now let’s sort the 1st level of the MultiIndex in increasing order.
# sort the 1st level of the MultiIndex in increasing order.midx.sortlevel(level = 1, ascending = True)
Output :As we can see in the output, the function has returned a new object having the first level sorted in increasing order.
Python pandas-multiIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.item()

12 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.item() function return the first element of the underlying data of the given series object as a python scalar.
Note : This function can only convert an array of size 1 to a Python scalar
Syntax: Series.item()
Parameter : None
Returns : scalar
Example #1: Use Series.item() function to return the first element of the given series object as a scalar.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([248])  # Create the Indexindex_ = ['Coca Cola']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.item() function to return the first element of the given series object as a scalar.
# return a scalarresult = sr.item()  # Print the resultprint(result)
Output :
As we can see in the output, the Series.item() function has successfully returned a scalar value. Example #2 : Use Series.item() function to iterate over all the elements in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([11])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 1, freq ='M')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.item() function to return the first element of the given series object as a scalar.
# return a scalarresult = sr.item()  # Print the resultprint(result)
Output :
As we can see in the output, the Series.item() function has successfully returned a scalar value.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MongoDB query to find documents with specific FirstName and LastName

To find documents with specific FirstName and LastName, use $and along with $in. Implement this in MongoDB find(). Let us create a collection with documents −
> db.demo692.insertOne({FirstName:"Chris","LastName":"Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea585dca7e81adc6a0b396a")
}
> db.demo692.insertOne({FirstName:"John","LastName":"Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea585e2a7e81adc6a0b396b")
}
> db.demo692.insertOne({FirstName:"John","LastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea585e7a7e81adc6a0b396c")
}
> db.demo692.insertOne({FirstName:"John","LastName":"Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea585efa7e81adc6a0b396d")
}
> db.demo692.insertOne({FirstName:"Adam","LastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea585faa7e81adc6a0b396e")
}
Display all documents from a collection with the help of find() method −
> db.demo692.find();
This will produce the following output −
{ "_id" : ObjectId("5ea585dca7e81adc6a0b396a"), "FirstName" : "Chris", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e2a7e81adc6a0b396b"), "FirstName" : "John", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e7a7e81adc6a0b396c"), "FirstName" : "John", "LastName" : "Smith" }
{ "_id" : ObjectId("5ea585efa7e81adc6a0b396d"), "FirstName" : "John", "LastName" : "Doe" }
{ "_id" : ObjectId("5ea585faa7e81adc6a0b396e"), "FirstName" : "Adam", "LastName" : "Smith" }
Following is the query to find documents with specific FirstName and LastName −
> db.demo692.find({$and:[ {FirstName: {$in: ["Chris", "John"]}},
... {LastName:{$in:["Brown", "Smith"]}}
... ]
... }
... );
This will produce the following output −
{ "_id" : ObjectId("5ea585dca7e81adc6a0b396a"), "FirstName" : "Chris", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e2a7e81adc6a0b396b"), "FirstName" : "John", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e7a7e81adc6a0b396c"), "FirstName" : "John", "LastName" : "Smith" }
First Missing Positive in Python

Suppose we have one unsorted integer array; we have to find the smallest missing positive number. So if the array is like [4, -3, 1, -1], then the result will be 2.
To solve this, we will follow these steps −
set i := 0 and update array nums by adding one 0 before all numbers
set i := 0 and update array nums by adding one 0 before all numbers
for i in range 0 to length of numswhile nums[i] >= 0 and nums[i] < length of nums and nums[nums[i]] is not
nums[i] −nums[nums[i]] := nums[i]nums[i] := nums[nums[i]]
for i in range 0 to length of nums
while nums[i] >= 0 and nums[i] < length of nums and nums[nums[i]] is not
nums[i] −nums[nums[i]] := nums[i]nums[i] := nums[nums[i]]
while nums[i] >= 0 and nums[i] < length of nums and nums[nums[i]] is not
nums[i] −
nums[nums[i]] := nums[i]
nums[nums[i]] := nums[i]
nums[i] := nums[nums[i]]
nums[i] := nums[nums[i]]
num := 1
num := 1
for i in range 1 to length of numsif num = nums[i], then increase num by 1
for i in range 1 to length of nums
if num = nums[i], then increase num by 1
if num = nums[i], then increase num by 1
return num
return num
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def firstMissingPositive(self, nums):
   i = 0
   nums = [0] + nums
   for i in range(len(nums)):
      while nums[i]>=0 and nums[i]<len(nums) and nums[nums[i]]!=nums[i]:
         nums[nums[i]],nums[i] = nums[i],nums[nums[i]]
      num = 1
      for i in range(1,len(nums)):
         if num == nums[i]:
            num+=1
      return num

ob = Solution()
print(ob.firstMissingPositive([4,-3,1,-1]))
[4,-3,1,-1]
2