code-rag-bench/online-tutorials huggingface dataset:
Comparator reversed() method in Java with examples - GeeksforGeeks

05 Feb, 2021
The reversed() method of Comparator Interface in Java returns a comparator that imposes the reverse ordering of this comparator. If you use sort method of the array and passes this comparator after applying the reversed method then it will sort the array in reverse order.
Syntax:  
default Comparator<T> reversed()
Parameters: This method accepts nothing.
Return value: This method returns a comparator that imposes the reverse ordering of this comparator.
Below programs illustrate reversed() method: 
Program 1: 
Java
// Java program to demonstrate// Comparator.reversed()  method import java.util.*; public class GFG {    public static void main(String[] args)    {         String[] Arraystrings = { "aman", "amar", "avik" };         System.out.println("before sort : "                           + Arrays.toString(Arraystrings));         Comparator<String> comp = (String::compareTo);        Arrays.sort(Arraystrings, comp.reversed());         System.out.println("after sort : "                           + Arrays.toString(Arraystrings));    }}
before sort : [aman, amar, avik]
after sort : [avik, amar, aman]

Program 2: 
Java
// Java program to demonstrate// Comparator.reversed()  method import java.util.*; public class GFG {    public static void main(String[] args)    {         String[] list = { "KKR", "CSK", "MI", "KXIP",                          "RCB", "SRH", "DC", "RR" };         System.out.println("Before sorting:");        System.out.println(Arrays.toString(list));         Comparator<String> comp = (String::compareTo);         Arrays.sort(list, comp.reversed());         System.out.println("After sorting:");        System.out.println(Arrays.toString(list));    }}
Before sorting:
[KKR, CSK, MI, KXIP, RCB, SRH, DC, RR]
After sorting:
[SRH, RR, RCB, MI, KXIP, KKR, DC, CSK]

References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#reversed() 
lyleziegelmiller
Java - util package
Java-Comparator
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
C++ Fstream Library - is_open Function

Returns whether the stream is currently associated to a file. If streams can be associated to files by a successful call to member open or directly on construction, and disassociated by calling close or on destruction. The file association of a stream is kept by its internal stream buffer: Internally, then the function calls rdbuf()->is_open().
Following is the declaration for fstream::is_open.
bool is_open();
bool is_open() const;
It returns true, if a file is open and associated with this stream object or else returns false.
Strong guarantee − if an exception is thrown, there are no changes in the stream.
Accesses the fstream object.
Accesses the fstream object.
Concurrent access to the same stream may introduce data races.
Concurrent access to the same stream may introduce data races.
In below example explains about fstream is_open function.
#include <iostream>     
#include <fstream>      

int main () {
   std::fstream fs;
   fs.open ("test.txt");
   if (fs.is_open()) {
      fs << "lorem ipsum";
      std::cout << "Operation successfully performed\n";
      fs.close();
   } else {
      std::cout << "Error opening file";
   }
   return 0;
}
 Print
 Add Notes
 Bookmark this page
How do I stop a MySQL decimal field from being rounded?

You can stop rounding decimal field with the help of DECIMAL() function. Here is the demo of a rounded decimal field. For our example, let us first create a demo table
mysql> create table stopRoundingDemo
   -> (
   -> Amount DECIMAL(7)
   -> );
Query OK, 0 rows affected (0.67 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into stopRoundingDemo values(7836.783);
Query OK, 1 row affected, 1 warning (0.43 sec)
mysql> insert into stopRoundingDemo values(1737.67);
Query OK, 1 row affected, 1 warning (0.23 sec)
mysql> insert into stopRoundingDemo values(110.50);
Query OK, 1 row affected, 1 warning (0.33 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from stopRoundingDemo;
The following is the output
+--------+
| Amount |
+--------+
| 7837   |
| 1738   |
| 111    |
+--------+
3 rows in set (0.08 sec)
In the above sample output, the decimal is rounded.
Now, we will see how to stop decimal being rounded. For that, let us first create a new table and set the DECIMAL type in a way that would give the result without round off
mysql> create table stopRoundingDemo2
   -> (
   -> Amount DECIMAL(10,4)
   -> );
Query OK, 0 rows affected (0.81 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into stopRoundingDemo2 values(7836.783);
Query OK, 1 row affected (0.14 sec)
mysql> insert into stopRoundingDemo2 values(1737.67);
Query OK, 1 row affected (0.14 sec)
mysql> insert into stopRoundingDemo2 values(110.50);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from stopRoundingDemo2;
The output is as follows
+-----------+
| Amount    |
+-----------+
| 7836.7830 |
| 1737.6700 |
| 110.5000  |
+-----------+
3 rows in set (0.00 sec)
Difference between private, public, and protected modifiers in C++

Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type. The access restriction to the class members is specified by the labeled access modifiers − public, private, and protected sections within the class body.
The default access for members and classes is private.
class Base {
public:
   // public members go here
protected:

   // protected members go here
private:
   // private members go here
};
A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member.
A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.
A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes.
Change the curdate() (current date) format in MySQL

The current date format is ‘YYYY-mm-dd’. To change current date format, you can use date_format().
Let us first display the current date −
mysql> select curdate();
This will produce the following output −
+------------+
| curdate()  |
+------------+
| 2019-08-08 |
+------------+
1 row in set (0.00 sec)
Following is the query to change curdate() (current date) format −
mysql> select date_format(curdate(), '%m/%d/%Y');
This will produce the following output −
+------------------------------------+
| date_format(curdate(), '%m/%d/%Y') |
+------------------------------------+
| 08/08/2019                         |
+------------------------------------+
1 row in set (0.00 sec)
Let us first create a table −
mysql> create table DemoTable (
   ArrivalDate date
);
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-01-10');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('2016-12-18');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------------+
| ArrivalDate |
+-------------+
| 2019-01-10  |
| 2016-12-18  |
+-------------+
2 rows in set (0.00 sec)
Following is the query to change date format −
mysql> select date_format(ArrivalDate, '%m/%d/%Y') from DemoTable;
This will produce the following output −
+--------------------------------------+
| date_format(ArrivalDate, '%m/%d/%Y') |
+--------------------------------------+
| 01/10/2019                           |
| 12/18/2016                           |
+--------------------------------------+
2 rows in set (0.00 sec)
Packages in C#

As an alternative of Packages in Java, the C# language has namespace.
Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.
A namespace definition begins with the keyword namespace followed by the namespace name. The following shows how to work with namespace in C# −
using System;

namespace first_space {
   class namespace_cl {
      public void func() {
         Console.WriteLine("Inside first_space");
      }
   }
}

namespace second_space {
   class namespace_cl {
      public void func() {
         Console.WriteLine("Inside second_space");
      }
   }
}

class TestClass {
   static void Main(string[] args) {
      first_space.namespace_cl fc = new first_space.namespace_cl();
      second_space.namespace_cl sc = new second_space.namespace_cl();

      fc.func();
      sc.func();
      Console.ReadKey();
   }
}
Set existing column as Primary Key in MySQL?

You can set primary key on an existing column in MySQL with the help of alter command.
The syntax is as follows to add primary key to an existing column.
ALTER TABLE yourTableName ADD PRIMARY KEY(yourColumnName);
To set existing column as primary key, let us first create a table. The query to create a table −
mysql> create table AddingPrimaryKeyDemo
   −> (
      −> UniversityId int,
      −> UniversityName varchar(200)
   −> );
Query OK, 0 rows affected (1.16 sec)
Look at the above query, I haven’t added primary key. Let us check the same with the help of DESC command. The query is as follows −
mysql> desc AddingPrimaryKeyDemo;
The following is the output −
+----------------+--------------+------+-----+---------+-------+
| Field          | Type         | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| UniversityId   | int(11)      | YES |      | NULL    |       |
| UniversityName | varchar(200) | YES |      | NULL    |       |
+----------------+--------------+------+-----+---------+-------+
2 rows in set (0.09 sec)
Now you can set existing column as primary key with the help of the syntax discussed in the beginning. The query to add primary key is as follows −
mysql> alter table AddingPrimaryKeyDemo add primary key(UniversityId);
Query OK, 0 rows affected (1.48 sec)
Records: 0 Duplicates: 0 Warnings: 0
Now I have added primary to existing column ‘UniversityId’. The following command will give a result that would check the existence of primary key on column ‘UniversityId’.
mysql> desc AddingPrimaryKeyDemo;
The following is the output −
+----------------+--------------+------+-----+---------+-------+
| Field          | Type         | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| UniversityId   | int(11)      | NO   | PRI | NULL    |       |
| UniversityName | varchar(200) | YES  |     | NULL    |       |
+----------------+--------------+------+-----+---------+-------+
2 rows in set (0.04 sec)
We can see “PRI” above, therefore Primary Key successfully added.
C Program to check if two given strings are isomorphic to each other - GeeksforGeeks

04 Oct, 2021
Given two strings str1 and str2, the task is to check if the two given strings are isomorphic to each other or not. 
Two strings are said to be isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 and all occurrences of every character in str1 map to same character in str2.
Examples:
Input: str1 = “egg”, str2 = “add” Output: Yes Explanation: ‘e’ in str1 with ASCII value 101 is mapped to ‘a’ in str2 with ASCII value 97. ‘g’ in str1 with ASCII value 103 is mapped to ‘d’ in str2 with ASCII value 100. 
Input: str1 = “eggs”, str2 = “add” Output: No  
Hashing Approach: Refer to the previous post for the Hashmap based approach. 
Time Complexity: O(N) Auxiliary Space: O(256)
ASCII-value based Approach: The idea is similar to that of the above approach. Follow the steps below to solve the problem: 
Initialize two arrays of size 256.Iterate through characters of the given strings and increment the index equal to the ASCII value of the character at ith position.If the are no conflicts in the mapping of the characters, print Yes. Otherwise, print No.
Initialize two arrays of size 256.
Iterate through characters of the given strings and increment the index equal to the ASCII value of the character at ith position.
If the are no conflicts in the mapping of the characters, print Yes. Otherwise, print No.
Below is the implementation of the above approach: 
C
// C Program to implement// the above approach #include <stdio.h>#include <string.h>#include <stdbool.h> // Function to check and return if strings// str1 and str2 are isomorphicbool areIsomorphic(char *str1, char *str2){    // If the length of the strings    // are not equal    if (strlen(str1) != strlen(str2)) {        return false;    }     // Initialise two arrays    int arr1[256] = { 0 }, arr2[256] = { 0 };     // Traversing both the strings    for (int i = 0; i < strlen(str1); i++) {         // If current characters don't map        if (arr1[(int)str1[i]]        != arr2[(int)str2[i]]) {            return false;        }         // Increment the count of characters        // at their respective ASCII indices        arr1[(int)str1[i]]++;        arr2[(int)str2[i]]++;    }    return true;} // Driver Codeint main(){    char s1[] = "aab", s2[] = "xxy";     if (areIsomorphic(s1, s2))        printf("Yes\n");    else        printf("No\n");     return 0;}
Yes
 
Time Complexity: O(N) Auxiliary Space: O(256)
clintra
adnanirshad158
surindertarika1234
ASCII
C Programs
Hash
Mathematical
School Programming
Strings
Hash
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Difference between break and continue statement in C
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
Condition Coverage Testing

Condition coverage is also known as Predicate Coverage in which each one of the Boolean expression have been evaluated to both TRUE and FALSE.
if ((A || B) && C)
{
  << Few Statements >>
}
else
{
   << Few Statements >>
}
In order to ensure complete Condition coverage criteria for the above example, A, B and C should be evaluated at least once against "true" and "false".
So, in our example, the 3 following tests would be sufficient for 100% Condition coverage testing.
A = true  | B = not eval | C = false
A = false | B = true     | C = true
A = false | B = false    | C = not eval


    80 Lectures 
     7.5 hours 

 Arnab Chakraborty

    10 Lectures 
     1 hours 

 Zach Miller

    17 Lectures 
     1.5 hours 

 Zach Miller

    60 Lectures 
     5 hours 

 John Shea

    99 Lectures 
     10 hours 

 Daniel IT

    62 Lectures 
     5 hours 

 GlobalETraining
 Print
 Add Notes
 Bookmark this page
How to convert a JSON string to a bean using JSON-lib API in Java?

The JSON-lib
API is a java library to serialize and de-serialize java beans, maps, arrays, and collections in the JSON format. We need to convert a JSON string to a bean by converting a string to JSON object first then convert this to a java bean.
public static Object toBean(JSONObject jsonObject, Class beanClass)
In the below program, we can convert a JSON string to a bean.
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class ConvertJSONStringToBeanTest {
   public static void main(String[] args) {
      String jsonStr = "{\"firstName\": \"Adithya\", \"lastName\": \"Sai\", \"age\": 30, \"technology\": \"Java\"}";
      JSONObject jsonObj = (JSONObject)JSONSerializer.toJSON(jsonStr); // convert String to JSON
      System.out.println(jsonObj);
     
      Student student = (Student)JSONObject.toBean(jsonObj, Student.class); // convert JSON to Bean
      System.out.println(student.toString());
   }
   public static class Student {
      private String firstName;
      private String lastName;
      private int age;
      private String technology;
      public Student() {
      }
      public String getFirstName() {
         return firstName;
      }
      public void setFirstName(String firstName) {
         this.firstName = firstName;
      }
      public String getLastName() {
         return lastName;
      }
      public void setLastName(String lastName) {
         this.lastName = lastName;
      }
      public int getAge() {
         return age;
      }
      public void setAge(int age) {
         this.age = age;
      }
      public String getTechnology () {
         return technology;
      }
      public void setTechnology(String technology) {
         this.technology = technology;
     }
      public String toString() {
         return "Student[ " +
         "firstName = " + firstName +
         ", lastName = " + lastName +
         ", age = " + age +
         ", technology = " + technology +
         " ]";
      }
   }
}
{"firstName":"Adithya","lastName":"Sai","age":30,"technology":"Java"}
Student[ firstName = Adithya, lastName = Sai, age = 30, technology = Java ]
jQuery submit() with Examples

The submit() method in jQuery is used to trigger the submit event. It occurs when a form is submitted.
The syntax is as follows −
$(selector).submit(func)
Above, the func parameter is the function to run when the submit event is triggered
Let us now see an example to implement the jQuery submit() method −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function() {
      $("form").submit(function(){
         alert("Form Submitted");
      });
   });
</script>
</head>
<body>
<h2>Login<h2>
<form action="">
Enter Username:
<input type="text"><br>
Enter Password:
<input type="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
This will produce the following output−
Click the “Submit” button −
GATE | GATE-CS-2003 | Question 76 - GeeksforGeeks

20 Aug, 2021
Consider the following class definitions in a hypothetical Object Oriented language that supports inheritance and uses dynamic binding. The language should not be assumed to be either Java or C++, though the syntax is similar.
Class P
{
    void f(int i)
    {
        print(i);
    }
}

Class Q subclass of P
{
    void f(int i)
    {
        print(2*i);
    }
}

Now consider the following program fragment:
P x = new Q();
Q y = new Q();
P z = new Q();
x.f(1); ((P)y).f(1); z.f(1); 
Here ((P)y) denotes a typecast of y to P. The output produced by executing the above program fragment will be(A) 1 2 1(B) 2 1 1(C) 2 1 2(D) 2 2 2Answer: (D)Explanation: Since the question itself tells us that the language uses dynamic binding therefore all the function calls should be considered only on the basic of type of object stored.Quiz of this Question
chaudharysatyam3976
satyam552000
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
tooltip("show") method in Bootstrap

Use the tooltip(“show”) method in Bootstrap to display the tooltip. As shown below that the tooltip is visible on button click:
$(document).ready(function(){
  $(".btn-primary").click(function(){
    $("[data-toggle='tooltip']").tooltip('show');
  });
});
The tooltip would be visible on a link wherein I have set the data-toggle attribute and the link text as shown in the following code snippet −
<a href="#" data-toggle="tooltip" title="Tooltip is visible!">
  On clicking the below button, the tooltip would be visible.
</a>
You can try to run the following code to implement the tooltip(“show”) method −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>

<body>
  <div class="container">
    <h3>Demo</h3>
    <a href="#" data-toggle="tooltip" title="Tooltip is visible!">On clicking the below button, the tooltip would be visible.</a>
    <div>
      <button type="button" class="btn btn-primary">Click me</button>
    </div>  
  </div>

<script>
$(document).ready(function(){
  $(".btn-primary").click(function(){
    $("[data-toggle='tooltip']").tooltip('show');
  });
});
</script>

</body>
</html>
Check if Email Address is Valid or not in Java - GeeksforGeeks

22 Oct, 2021
Given a string, find if the given string is a valid email or not.
Input : email = "review-team@geeksforgeeks.org"
Output : Yes

Input : email = "contribute@geeksforgeeks..org"
Output : No
Explanation : There is an extra dot(.) before org.
Prerequisite: Regular Expressions in Java 
Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package. 
In order to check that an email address is valid or not, we use the below-given regular expression provided in the OWASP Validation Regex repository.
^[a-zA-Z0-9_+&*-] + (?:\\.[a-zA-Z0-9_+&*-]
+ )*@(?:[a-zA-Z0-9-]+\\.) + [a-zA-Z]{2, 7}$ 
Code – 
Java
// Java program to check if an email address// is valid using Regex.import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.*;  class Test{    public static boolean isValid(String email)    {        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\."+                            "[a-zA-Z0-9_+&*-]+)*@" +                            "(?:[a-zA-Z0-9-]+\\.)+[a-z" +                            "A-Z]{2,7}$";                                      Pattern pat = Pattern.compile(emailRegex);        if (email == null)            return false;        return pat.matcher(email).matches();    }      public static void main(String[] args)    {        ArrayList<String> address = new ArrayList<>();                      address.add("review-team@geeksforgeeks.org");          address.add("writing.geeksforgeeks.org");                    for(String i : address){            if (isValid(i))                System.out.println(i + " - Yes");            else                System.out.println(i + " - No");        }    }}
review-team@geeksforgeeks.org - Yes
writing.geeksforgeeks.org - No
This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nishkarshgandhi
java-regular-expression
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Overriding in Java
Stack Class in Java
Collections in Java
sigwaitinfo() - 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
#include <signal.h> 

int sigwaitinfo(const sigset_t *set, siginfo_t *info); 

int sigtimedwait(const sigset_t *set, siginfo_t *info,  
                 const struct timespec *timeout); 


int sigwaitinfo(const sigset_t *set, siginfo_t *info); 


int sigtimedwait(const sigset_t *set, siginfo_t *info,  
                 const struct timespec *timeout); 


sigwaitinfo() removes the delivered signal from the calling process’s list of pending
signals and returns the signal number as its function result.
If the
info argument is not NULL,
then it returns a structure of type
siginfo_t (see
sigaction(2))
containing information about the signal.


Signals returned via
sigwaitinfo() are delivered in the usual order; see
signal(7)
for further details.


sigtimedwait() operates in exactly the same way as
sigwaitinfo() except that it has an additional argument,
timeout, which enables an upper bound to be placed on the time for which
the process is suspended.
This argument is of the following type:




struct timespec {
    long    tv_sec;         /* seconds */
    long    tv_nsec;        /* nanoseconds */
}


If both fields of this structure are specified as 0, a poll is performed:
sigtimedwait() returns immediately, either with information about a signal that
was pending for the caller, or with an error
if none of the signals in
set was pending.


POSIX leaves the meaning of a NULL value for the
timeout argument of
sigtimedwait() unspecified, permitting the possibility that this has the same meaning
as a call to
sigwaitinfo(), and indeed this is what is done on Linux.

kill (2)
kill (2)
sigaction (2)
sigaction (2)
signal (2)
signal (2)
sigpending (2)
sigpending (2)
sigprocmask (2)
sigprocmask (2)
sigqueue (2)
sigqueue (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
bzip2 command in Linux with Examples - GeeksforGeeks

22 Aug, 2019
bzip2 command in Linux is used to compress and decompress the files i.e. it helps in binding the files into a single file which takes less storage space as the original file use to take. It has a slower decompression time and higher memory use. It uses Burrows-Wheeler block sorting text compression algorithm, and Huffman Coding. Each file is replaced by a compressed version of itself, with the name original name of the file followed by extension bz2.
Syntax:
bzip2 [OPTIONS] filenames ...
Options:
-z : This option forces compression. It is an opposite command of decompression i.e. -d Option.$ bzip2 -z input.txtExample:Note: This option deletes the original file also.
$ bzip2 -z input.txt
Example:
Note: This option deletes the original file also.
-k: This option does compression but does not deletes the original file.$ bzip2 -k input.txtExample:
$ bzip2 -k input.txt
Example:
-d : This option is used for decompression of compressed files.$ bzip2 -d input.txt.bz2Example:
$ bzip2 -d input.txt.bz2
Example:
-t : This option does the integrity check of the file and does not decompresses the file. It gives us the idea that the file is corrupt or not.$ bzip2 -t input.txt.bz2Example:
$ bzip2 -t input.txt.bz2
Example:
-v : Verbose mode show the compression ratio for each file processed. It also increases the verbosity level, spewing out lots of information which is primarily of interest for diagnostic purposes.$ bzip2 -v input.txtExample:
$ bzip2 -v input.txt
Example:
-h –help : To display the help message and exit.
-L –license -V –version : It is used to display the software version, license terms, and conditions.
-q –quiet : It will suppress non-essential warning messages. Messages pertaining to I/O errors and other critical events will not be suppressed.
-f –force : It will force overwrite of output files.
Akanksha_Rai
linux-command
Linux-file-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
MongoDB aggregate to convert multiple documents into single document with an array?

For aggregate in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo248.insertOne({"id":101,"Name":"Chris","Age":21,"CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b6651627c0c63e7dba6d")
}
> db.demo248.insertOne({"id":101,"Name":"Bob","Age":22,"CountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b6741627c0c63e7dba6e")
}
> db.demo248.insertOne({"id":102,"Name":"Mike","Age":20,"CountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46b6811627c0c63e7dba6f")
}
Display all documents from a collection with the help of find() method −
> db.demo248.find();
This will produce the following output −
{ "_id" : ObjectId("5e46b6651627c0c63e7dba6d"), "id" : 101, "Name" : "Chris", "Age" : 21, "CountryName" : "US" }
{ "_id" : ObjectId("5e46b6741627c0c63e7dba6e"), "id" : 101, "Name" : "Bob", "Age" : 22, "CountryName" : "UK" }
{ "_id" : ObjectId("5e46b6811627c0c63e7dba6f"), "id" : 102, "Name" : "Mike", "Age" : 20, "CountryName" : "AUS" }
Following is the query to convert multiple documents into single document with an array −
> db.demo248.aggregate([
...   {
...      $group : {
...         _id : "$id",
...         details : {
...            $push : {
...               id:"$id",
...               Name:"$Name",
...               Age:"$Age",
...               CountryName:"$CountryName"
...            }
...         }
...      }
...   }
...])
This will produce the following output −
{ "_id" : 102, "details" : [ { "id" : 102, "Name" : "Mike", "Age" : 20, "CountryName" : "AUS" } ] }
{ "_id" : 101, "details" : [ { "id" : 101, "Name" : "Chris", "Age" : 21, "CountryName" : "US" }, { "id" : 101, "Name" : "Bob", "Age" : 22, "CountryName" : "UK" } ] }
How to enable soft delete for Azure Storage blobs using Azure CLI in Powershell?

From the Azure portal, we need to access the Data Protection property of the Azure Storage account.
To enable soft delete using Az CLI, you first need to install the storage-preview extension with the below command.
az extension add -n storage-preview
Once the extension is installed, you need to make sure that you are connected to the Azure Account (if not then use “az login”) command and the proper azure subscription (using “az account set”).
To enable soft delete with Azure CLI use the below command.
az storage fs service-properties update
We can use this command with Key, connection string, or SAS token. Here, we will use the connection string. To retrieve the connection string, use the below command.
$rg = 'az204'
$strgaccount = 'az204storage05june'
$connectionstring = az storage account show-connection-string -g $rg -
n $strgaccount -otsv
To enable the soft delete with 10 days of the retention period, use the below command.
az storage fs service-properties update `
   --delete-retention `
   --delete-retention-period 10 `
   --account-name $strgaccount `
   --connection-string $connectionstring
You can also use the storage account key instead of the connection string as shown below.
az storage fs service-properties update `
   --delete-retention `
   --delete-retention-period 10 `
   --account-name $strgaccount `
   --account-key $storageaccountkey
Count factorial numbers in a given range in C++

We are given the range starting from an integer value holded by a variable let’s say start till the variable end and the task is to count the total number of factorial numbers available in the given range.
Factorial of a number is calculated by multiplying the digits in a number while decrementing thevalue of digit by 1. It is denoted by the symbol ‘!’ i.e. 0!, 1!, 2!, 3!, 5!,....,etc. Factorial of 0! and 1! is always 1.
I.e. factorial of 2 = 2 * (2-1) = 2 * 1 = 2
      factorial of 3 = 3 * (3-1) * (2-1) = 3 * 2 * 1 = 6
Input − start = 5, end = 600
Output − Count of factorial numbers are 3
Explanation − Since, there are 3 numbers available that have factorial numbers in the range 5-600.
Input − start = 1, end = 100
Output − Count of factorial numbers are 5
Explanation − Since, there are 5 numbers available that have factorial numbers in the range 5-600.
Input the range and store in the variables start and end
Input the range and store in the variables start and end
Take another variable, ‘fact’ to store the factorial values and initialise it with 1 and a temporary variable, ‘i’ to increase the numbers count.
Take another variable, ‘fact’ to store the factorial values and initialise it with 1 and a temporary variable, ‘i’ to increase the numbers count.
Start the loop, while fact is less than start and keep multiplying the fact with i to calculate the factorial and also, keep incrementing the value of i
Start the loop, while fact is less than start and keep multiplying the fact with i to calculate the factorial and also, keep incrementing the value of i
Start another loop, while fact is less than equals to end variable and keep incrementing the value of a variable r and keep setting fact to fact *i and keep incrementing value of i
Start another loop, while fact is less than equals to end variable and keep incrementing the value of a variable r and keep setting fact to fact *i and keep incrementing value of i
Now, return the value of r that is holding the total count of total number of factorial numbers
Now, return the value of r that is holding the total count of total number of factorial numbers
Print the result.
Print the result.
 Live Demo
#include <iostream>
using namespace std;
// To count the number of factorials
int factorials(int start, int end){
   // Starting from 1 and find the first factorial number
   // 'fact' greater than or equal to 'start'
   int fact = 1, i = 1;
   while (fact < start){
      fact = fact*i;
      i++;
   }
   // r to count factorial numbers in range start to end
   int r = 0;
   while (fact <= end){
      r++;
      fact = fact*i;
      i++;
   }
   // Return the count of factorials in range
   return r;
}
int main(){
   int start = 5, end = 600;
   cout << "Count of factorial numbers are " << factorials(start, end);
   return 0;
}
If we run the above code it will generate the following output −
Count of factorial numbers are 3
How to add a rounded border with CSS ? - GeeksforGeeks

23 Sep, 2020
The purpose of this article is to add a rounded border to a HTML element by using the border-radius property in CSS. It is used to round the corner of an element. The property sets the border-radius for the element.
Syntax:
border-radius: 1-4 length|% / 1-4 length|%|initial|inherit
Example:
<!DOCTYPE html><html>  <head>    <style>        .GFG {            border-radius: 75px 75px;            background: blue;            padding: 16px;            text-align: center;            width: 300px;            height: 120px;        }    </style></head>  <body>    <center>        <h1>            GeeksForGeeks        </h1>        <h2>            How to add a rounded             border with css ?        </h2>          <div class="GFG">            <h4>                Rounded corners Borders            </h4>        </div>    </center></body>  </html> 
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
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.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set input type date in dd-mm-yyyy format using HTML ?
HTML | <img> align Attribute
Form validation using HTML and JavaScript
How to set the default value for an HTML <select> element ?
Select parent element of known element in Selenium.

We can select the parent element of a known element with Selenium webdriver. First of all we have to identify the known element with the help of any of the locators like id, classname and so on. Then we have to identify its parent element with findElement(By.xpath()) method.
We can identify the parent element from its child by localizing it with the child and then passing ( ./..) as a parameter to the findElement(By.xpath()). Let us identify the parent element with tagname ul from the child element with the tagname li in below html code −
Also we can identify the parent element of a known element with the help of Javascript Executor. We have to pass the Javascript command return arguments[0].parentNode and the webelement as parameters to the method executeScript. The parentNode command in Javascript is used to point to the parent of an element.
Code Implementation with xpath
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ParentElement{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement c=driver.findElement(By.xpath("//li[@class='heading']"));
      //identify parent element with ./.. expression in xpath
      WebElement p = c.findElement(By.xpath("./.."));
      //getTagName to get tagname of parent
      System.out.println("Parent tagname is: " + p.getTagName());
      driver.close();
   }
}
Code Implementation with Javascript Executor.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ParentElementJS{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement c=driver.findElement(By.xpath("//li[@class='heading']"));
      //identify parent element parentNode expression in Javascript command
      WebElement p = (WebElement) ((JavascriptExecutor) driver).executeScript( "return arguments[0].parentNode;", c);
      //getTagName to get tagname of parent
      System.out.println("Parent tagname is: " + p.getTagName());
      driver.close();
   }
}
How to set the layout weight of a textview programmatically in Android?

This example demonstrates how do I set the layout weight of a textView programmatically in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center"
   tools:context=".MainActivity">
   <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textStyle="bold"
      android:onClick="expand"
      android:textSize="24sp"
      android:text="Hello World"
      android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
   Button button;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   public void expand(View view) {
      int height = RelativeLayout.LayoutParams.MATCH_PARENT;
      int width = 500;
      RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(width,height);
      button = findViewById(R.id.button);
      button.setLayoutParams(layoutParams);
   }
}
Step 4 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
Angular 2 - Navigation

In Angular 2, it is also possible to carry out manual navigation. Following are the steps.
Step 1 − Add the following code to the Inventory.component.ts file.
import { Component } from '@angular/core'; 
import { Router }  from '@angular/router';  

@Component ({  
   selector: 'my-app',  
   template: 'Inventory 
   <a class = "button" (click) = "onBack()">Back to Products</a>' 
})  

export class AppInventory {  
   constructor(private _router: Router){} 

   onBack(): void { 
      this._router.navigate(['/Product']); 
   } 
}
The following points need to be noted about the above program −
Declare an html tag which has an onBack function tagged to the click event. Thus, when a user clicks this, they will be directed back to the Products page.
Declare an html tag which has an onBack function tagged to the click event. Thus, when a user clicks this, they will be directed back to the Products page.
In the onBack function, use the router.navigate to navigate to the required page.
In the onBack function, use the router.navigate to navigate to the required page.
Step 2 − Now, save all the code and run the application using npm. Go to the browser, you will see the following output.
Step 3 − Click the Inventory link.
Step 4 − Click the ‘Back to products’ link, you will get the following output which takes you back to the Products page.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to find the first date of a given year using Python?

In this program, we have to print the first day of the year. We have to take a year as a user input.
Step 1: Import the datetime library.
Step 2: Take year as input from the user.
Step 3: Get the first day of the year by passing month, day and year as parameters to the datetime.datetime() function
Step 4: Display the first day using strftime() function.
Live Demo
import datetime
year = int(input("Enter year: "))
firstday = datetime.datetime(year, 1,1)
print("First Day of ", year, " = ", firstday.strftime("%A"))
First Day of  2021  =  Friday
Python - API.retweets() in Tweepy - GeeksforGeeks

05 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The API.retweets() method of the API class in Tweepy module is used to return a list of retweets of a tweet.
Syntax : API.retweets(parameters)
Parameters :
id : The ID of the tweet which has to be retweeted.
count : The number of retweets to be retrieved.
Returns : a list of objects of the class Status
Example 1 : List of users who retweeted the following tweet :
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the ID of the tweetID = 1265889240300257280  # getting the retweetersretweets_list = api.retweets(ID)  # printing the screen names of the retweetersfor retweet in retweets_list:    print(retweet.user.screen_name)
Output :
harshitabambure
codedailybot
UVahalkar
codedailybot
ProjectLearn_io
codedailybot
ryokugyu_
AaronCuddeback

strong>Example 2 : Using the retweets() method with count parameter to only fetch a certain number of retweets. Print the screen names of only 3 retweeters of the following tweet :
# the ID of the tweetID = 1263387365051183107  # number to retweets to be retrievedcount = 3  # getting the retweetersretweets_list = api.retweets(ID, count)  # printing the screen names of the retweetersfor retweet in retweets_list:    print(retweet.user.screen_name)
Output :
murali_ch
sushmitaraj13
rgsharma_me

Python-Tweepy
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
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Selecting rows in pandas DataFrame based on conditions