code-rag-bench/online-tutorials huggingface dataset:
How to check the permissions of a directory using Python?

You can use os.access(path, mode) to check the directory permission with modes for reading, writing and execution permissions. For being able to write you'll also need to check for execution permission. For example,
>>> import os
>>> os.access('my_folder', os.R_OK) # Check for read access
True
>>> os.access('my_folder', os.W_OK) # Check for write access
True
>>> os.access('my_folder', os.X_OK) # Check for execution access
True
>>> os.access('my_folder', os.X_OK | ox.W_OK) # Check if we can write file to the directory
True
You can also follow a common Python idiom: It's easier to ask for forgiveness than for permission. Following that idiom, you should try writing to the directory in question, and catch the error if you don't have the permission to do so.
GATE | Gate IT 2008 | Question 61 - GeeksforGeeks

15 Oct, 2019
Consider the following three schedules of transactions T1, T2 and T3. [Notation: In the following NYO represents the action Y (R for read, W for write) performed by transac­tion N on object O.]
(S1)    2RA    2WA    3RC    2WB    3WA    3WC    1RA    1RB    1WA    1WB
(S2)    3RC    2RA    2WA    2WB    3WA    1RA    1RB    1WA    1WB    3WC
(S3)    2RA    3RC    3WA    2WA    2WB    3WC    1RA    1RB    1WA    1WB
Which of the following statements is TRUE?
(A) S1, S2 and S3 are all conflict equivalent to each other(B) No two of S1, S2 and S3 are conflict equivalent to each other(C) S2 is conflict equivalent to S3, but not to S1(D) S1 is conflict equivalent to S2, but not to S3Answer: (D)Explanation: 
All the conflicting pairs like (3WA, 1WA) are in the same order in both S1 and S2.Quiz of this Question
Gate IT 2008
GATE-Gate IT 2008
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-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-CS-2000 | Question 41
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Python program to find all possible pairs with given sum - GeeksforGeeks

07 Jun, 2019
Given a list of integers and an integer variable K, write a Python program to find all pairs in the list with given sum K.
Examples:
Input : lst =[1, 5, 3, 7, 9]
        K = 12
Output : [(5, 7), (3, 9)]

Input : lst = [2, 1, 5, 7, -1, 4]
        K = 6
Output : [(2, 4), (1, 5), (7, -1)]

 Method #1 : Pythonic Naive
This is a naive approach to the above problem. First, we take an empty list ‘res’ and start a loop and traverse each element of the given list of integers. In each iteration, pop the element, store it in ‘num’, find remaining difference for sum K, and check if the difference exists in the given list or not.
# Python3 program to find all pairs in # a list of integers with given sum   def findPairs(lst, K):     res = []    while lst:        num = lst.pop()        diff = K - num        if diff in lst:            res.append((diff, num))              res.reverse()    return res      # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))
[(5, 7), (3, 9)]

 Method #2 : Using collections.Counter
This approach follows the same method as discussed above using collections.Counter.
# Python3 program to find all pairs in # a list of integers with given sum from collections import Counter  def findPairs(lst, K):     res = []    count = Counter(lst)      for x in lst:        y = K - x        if (x != y and count[y]) or (x == y and count[y] > 1):            res.append((x, y))             count.subtract((x, y))                  return res      # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))
[(5, 7), (3, 9)]

 Method #3 : itertools.combinations (Naive method)
This is a naive approach to use itertools.combinations. We use a for loop to traverse through each combination and find out the desired one.
# Python3 program to find all pairs in # a list of integers with given sum   from itertools import combinations  def findPairs(lst, K):       res = []    for var in combinations(lst, 2):        if var[0] + var[1] == K:            res.append((var[0], var[1]))              return res      # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))
[(5, 7), (3, 9)]

 Method #4 : itertools.combinations (Efficient method)
# Python3 program to find all pairs in # a list of integers with given sum from itertools import combinations  def findPairs(lst, K):          return [pair for pair in combinations(lst, 2) if sum(pair) == K]      # Driver codelst = [1, 5, 3, 7, 9]K = 12print(findPairs(lst, K))
[(5, 7), (3, 9)]

Python list-programs
Python
Python Programs
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
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
How to convert an object to byte array in java?

To convert an object to byte array
Make the required object serializable by implementing the Serializable interface.
Create a ByteArrayOutputStream object.
Create an ObjectOutputStream object by passing the ByteArrayOutputStream object created in the previous step.
Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class.
Flush the contents to the stream using the flush() method.
Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Sample implements Serializable {
   public void display() {
      System.out.println("This is a sample class");
   }
}
public class ObjectToByteArray {
   public static void main(String args[]) throws Exception {
      Sample obj = new Sample();
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(bos);
      oos.writeObject(obj);
      oos.flush();
      byte [] data = bos.toByteArray();
   }
}
OR Gate using Perceptron Network - GeeksforGeeks

12 Jun, 2019
Perceptron networks come under single-layer feed-forward networks and are also called simple perceptrons. The perceptron network consists of three units, namely, sensory unit (input unit), associator unit (hidden unit), response unit (output unit). The sensory units are connected to associator units with fixed weights having values 1, 0 or -1, which are assigned at random.The problem is to implement or gate using a perceptron network using c++ code.
#include<iostream>using namespace std;int main(){    //Array for Binary Input    int arr[4][2] = { {0,0},        {0,1},        {1,0},        {1,1}    };      //Target array for Binary Input    int t[4] = {0,1,1,1};      // Considering learning rate=1    int alp = 1;      // yi = input    // yo = output    int w1 = 0, w2 = 0, b = 0, count = 0, i, yi, yo;    int dw1,dw2,db;      while(1)    {        cout<<"x1"<<" "<<"x2"<<" "<<"b"<<" "<<"yi"<<" "<<            "yo"<<" "<<"t"<<" "<<"dw1"<<" "<<"dw2"<<" "<<"db"<<            " "<<"w1"<<" "<<"w2"<<" "<<"b"<<endl;          for(i = 0; i < 4; i++)        {            // Calaulating Input            yi = arr[i][0] * w1 + arr[i][1] * w2 + b;            if(yi >= 0)            {                yo = 1;            }            else            {                yo = 0;            }            if(t[i] == yo)            {                count++;                dw1 = 0;                dw2 = 0;                db = 0;            }            // Calaulating Change in Weight            else            {                dw1 = alp*(t[i] - yo) * arr[i][0];                dw2 = alp*(t[i] - yo) * arr[i][1];                db = alp*(t[i] - yo);            }            w1 = w1 + dw1;            w2 = w2 + dw2;            b = b + db;            cout<<arr[i][0]<<" "<<arr[i][1]<<" "<<1<<" "<<yi<<" "<<yo                <<"     "<<t[i]<<" "<<dw1<<" "<<dw2<<" "<<db<<" "<<w1<<" "<<w2                <<" "<<b<<endl;        }        cout<<endl;        if(count == 4)        {            return 0;        }        else        {            count = 0;        }    }}
Output :
x1 x2 b yi yo t dw1 dw2 db w1 w2 b
0 0 1 0 1     0 0 0 -1 0 0 -1
0 1 1 -1 0     1 0 1 1 0 1 0
1 0 1 0 1     1 0 0 0 0 1 0
1 1 1 1 1     1 0 0 0 0 1 0

x1 x2 b yi yo t dw1 dw2 db w1 w2 b
0 0 1 0 1     0 0 0 -1 0 1 -1
0 1 1 0 1     1 0 0 0 0 1 -1
1 0 1 -1 0     1 1 0 1 1 1 0
1 1 1 2 1     1 0 0 0 1 1 0

x1 x2 b yi yo t dw1 dw2 db w1 w2 b
0 0 1 0 1     0 0 0 -1 1 1 -1
0 1 1 0 1     1 0 0 0 1 1 -1
1 0 1 0 1     1 0 0 0 1 1 -1
1 1 1 1 1     1 0 0 0 1 1 -1

x1 x2 b yi yo t dw1 dw2 db w1 w2 b
0 0 1 -1 0     0 0 0 0 1 1 -1
0 1 1 0 1     1 0 0 0 1 1 -1
1 0 1 0 1     1 0 0 0 1 1 -1
1 1 1 1 1     1 0 0 0 1 1 -1


C++
Machine Learning
Machine Learning
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Map in C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects
Constructors in C++
Bitwise Operators in C/C++
Naive Bayes Classifiers
Linear Regression (Python Implementation)
Removing stop words with NLTK in Python
Agents in Artificial Intelligence
ML | Linear Regression
Find current weather of any city using OpenWeatherMap API in Python

In this tutorial, we are going to get the weather of a city using OpenWeatherMap API. To use the OpenWeatherMap API, we have to get the API key. We will get it by creating an account on their website.
Create an account and get your API Key. It's free until 60 calls per minute. You have to pay if you want more than that. For this tutorial, the free version is enough. We need requests module for the HTTP requests and JSON module to work with the response. Follow the below steps to the weather of any city.
Import the requests and JSON modules.
Import the requests and JSON modules.
Initialize the base URL of the weather API https://api.openweathermap.org/data/2.5/weather?.
Initialize the base URL of the weather API https://api.openweathermap.org/data/2.5/weather?.
Initialize the city and API key.
Initialize the city and API key.
Update the base URL with the API key and city name.
Update the base URL with the API key and city name.
Send a get request using the requests.get() method.
Send a get request using the requests.get() method.
And extract the weather info using the JSON module from the response.
And extract the weather info using the JSON module from the response.
Let's see the code.
# importing requests and json
import requests, json
# base URL
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
# City Name CITY = "Hyderabad"
# API key API_KEY = "Your API Key"
# upadting the URL
URL = BASE_URL + "q=" + CITY + "&appid=" + API_KEY
# HTTP request
response = requests.get(URL)
# checking the status code of the request
if response.status_code == 200:
   # getting data in the json format
   data = response.json()
   # getting the main dict block
   main = data['main']
   # getting temperature
   temperature = main['temp']
   # getting the humidity
   humidity = main['humidity']
   # getting the pressure
   pressure = main['pressure']
   # weather report
   report = data['weather']
   print(f"{CITY:-^30}")
   print(f"Temperature: {temperature}")
   print(f"Humidity: {humidity}")
   print(f"Pressure: {pressure}")
   print(f"Weather Report: {report[0]['description']}")
else:
   # showing the error message
   print("Error in the HTTP request")
If you run the above program, you will get the following results.
----------Hyderabad-----------
Temperature: 295.39
Humidity: 83
Pressure: 1019
Weather Report: mist
If you find any difficulty in following the tutorial, mention them in the comment section.
C program to sort names in alphabetical order using structures

Structure is a collection of different datatype variables, grouped together under a single name.
The features of structure in the C programming language are as follows −
It is possible to copy the contents of all the structure elements of different datatypes to another structure variable of its type by using an assignment operator.
It is possible to copy the contents of all the structure elements of different datatypes to another structure variable of its type by using an assignment operator.
For handling the complex datatypes, it is better to create structure within another structure, which is called nested structures.
For handling the complex datatypes, it is better to create structure within another structure, which is called nested structures.
It is possible to pass an entire structure, individual elements of structure and an address of structure to a function.
It is possible to pass an entire structure, individual elements of structure and an address of structure to a function.
It is possible to create structure pointers.
It is possible to create structure pointers.
General form of structure declaration is as follows −
datatype member1;
   struct tagname{
      datatype member2;
      datatype member n;
};
Here,
struct is the keyword.
tagname specifies name of structure.
member1, member2 are the data items.
For example,
struct book{
   int pages;
   char author [30];
   float price;
};
Following is the C program to sort the names in an alphabetical order by using the structures −
 Live Demo
#include<stdio.h>
#include<string.h>
struct tag{
   char name[10];
   int rno;
};
typedef struct tag node;
node s[5];
sort(int no){
   int i,j;
   node temp;
   for(i=0;i<no-1;i++)
   for(j=i+1;j<no;j++)
   if(strcmp(s[i].name,s[j].name)>0){
      temp=s[i];
      s[i]=s[j];
      s[j]=temp;
   }
}
void main(){
   int no,i;
   fflush(stdin);
   printf("Enter The Number Of Students:");
   scanf("%d",&no);
   for(i=0;i<no;i++){
      printf("Enter The Name:");
      fflush(stdin);
      gets(s[i].name);
      printf("Enter the Roll:");
      scanf("%d",&s[i].rno);
   }
   sort(no);
   for(i=0;i<no;i++){
      printf("%s\t",s[i].name);
      printf("%d\n",s[i].rno);
   }
}
When the above program is executed, it produces the following result −
Enter The Number of Students:5
Enter The Name:Priya
Enter the Roll:3
Enter The Name:Hari
Enter the Roll:5
Enter The Name:Pinky
Enter the Roll:7
Enter The Name:Lucky
Enter the Roll:1
Enter The Name:Krishna
Enter the Roll:2
Hari 5
Krishna 2
Lucky 1
Pinky 7
Priya 3
GATE | GATE-CS-2015 (Set 1) | Question 42 - GeeksforGeeks

28 Jun, 2021
Consider a max heap, represented by the array: 40, 30, 20, 10, 15, 16, 17, 8, 4. Now consider that a value 35 is inserted into this heap. After insertion, the new heap is(A) 40, 30, 20, 10, 15, 16, 17, 8, 4, 35(B) 40, 35, 20, 10, 30, 16, 17, 8, 4, 15(C) 40, 30, 20, 10, 35, 16, 17, 8, 4, 15(D) 40, 35, 20, 10, 15, 16, 17, 8, 4, 30Answer: (B)Explanation: The array 40, 30, 20, 10, 15, 16, 17, 8, 4 represents following heap

         40
       /    \
     30      20
    / \      / \
   10  15  16   17
  / \
 8   4
After insertion of 35, we get
         40
       /    \
     30      20
    / \       / \
   10  15  16   17
  / \  /
 8   4 35  
After swapping 35 with 15 and swapping 35 againwith 30, we get
         40
       /    \
     35      20
    / \       / \
   10  30  16   17
  / \  /
 8   4 15  
Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2000 | Question 43
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | Gate IT 2007 | Question 30
Validate IP Address in C#

An IP Address is an Internet Protocol address that is a series of numbers assigned to each device on a computer network. In C#, the class IPAddress class in the namespace System.Net deals with IP addresses.
A program that is used to validate an IP address is given as follows −
 Live Demo
using System;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
namespace IPaddressDemo {
   class Example {
      public static void Main() {
         IPAddress IP;
         Console.WriteLine("Enter the IP Address: ");
         string ipAddr = Console.ReadLine();
         bool flag = IPAddress.TryParse(ipAddr, out IP);
         if (flag)
         Console.WriteLine("{0} is a valid IP address", ipAddr);
         else
         Console.WriteLine("{0} is not a valid IP address", ipAddr);
      }
   }
}
The output of the above program is as follows.
Enter the IP Address: 130.45.78.200
130.45.78.200 is a valid IP address
Now, let us understand the above program.
An object IP is created of the IPAddress class. Then the required IP address is obtained from the user. The IP address is validated using the method TryParse() in the class IPAddress as this methods validates if a string is an IP address or not. The result is stored in flag. Then the if statement is used to print if the string is IP address or not depending on the value in flag. The code snippet for this is as follows −
IPAddress IP;
Console.WriteLine("Enter the IP Address: ");
string ipAddr = Console.ReadLine();
bool flag = IPAddress.TryParse(ipAddr, out IP);
if (flag)
Console.WriteLine("{0} is a valid IP address", ipAddr);
else
Console.WriteLine("{0} is not a valid IP address", ipAddr);
Batch Script - Moving Files

For moving files, Batch Script provides the MOVE command.
MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination

Following are the description of the options which can be presented to the DEL command.
[drive:][path]filename1
Specifies the location and name of the file or files you want to move
destination
Specifies the new location of the file. Destination can consist of a drive letter and colon, a directory name, or a combination. If you are moving only one file, you can also include a filename if you want to rename the file when you move it.
[drive:][path]dirname1
Specifies the directory you want to rename.
dirname2
Specifies the new name of the directory.
/Y
Suppresses prompting to confirm you want to overwrite an existing destination file.
/-Y
Causes prompting to confirm you want to overwrite an existing destination file.
Let’s look at some examples of renaming files.
move c:\windows\temp\*.* c:\temp

The above command will move the files of c:\windows\temp to the temp directory in root.
move new.txt, test.txt c:\example

The above command will move the files new.txt and test.txt into the c:\example folder.
 Print
 Add Notes
 Bookmark this page
Anonymous Array in Java - GeeksforGeeks

22 Apr, 2022
An array in Java without any name is known as an anonymous array. It is an array just for creating and using instantly. Using an anonymous array, we can pass an array with user values without the referenced variable.
Properties of Anonymous Arrays:
We can create an array without a name. Such types of nameless arrays are called anonymous arrays.
The main purpose of an anonymous array is just for instant use (just for one-time usage).
An anonymous array is passed as an argument of a method.
Note: For Anonymous array creation, do not mention size in []. The number of values passing inside {} will become the size.
Syntax: 
new <data type>[]{<list of values with comma separator>};
Examples:
// anonymous int array 
new int[] { 1, 2, 3, 4};  

// anonymous char array 
new char[] {'x', 'y', 'z'}; 

// anonymous String array
new String[] {"Geeks", "for", "Geeks"}; 

// anonymous multidimensional array
new int[][] { {10, 20}, {30, 40, 50} };
Java
// Java program to illustrate the// concept of anonymous array class Test {    public static void main(String[] args)    {          // anonymous array          sum(new int[]{ 1, 2, 3 });    }       public static void sum(int[] a)    {        int total = 0;         // using for-each loop        for (int i : a)            total = total + i;                 System.out.println("The sum is: " + total);    }}
The sum is: 6
Explanation: In the above example, just to call the sum method, we required an array, but after implementing the sum method, we are not using the array anymore. Hence for this one-time requirement anonymous array is the best choice. Based on our requirement, we can later give the name to the anonymous array, and then it will no longer be anonymous. 
This article is contributed by Bishal Kumar Dubey. 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
pramodask003
Java-Array-Programs
Java-Arrays
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java
Get distinct levels of array field in MongoDB?

To get distinct levels of array field, use $addToSet in MongoDB. Let us create a collection with documents −
> db.demo122.insertOne({"ListOfValues":[100,10]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2f20f1140daf4c2a3544b6")
}
> db.demo122.insertOne({"ListOfValues":[240,10]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2f20f7140daf4c2a3544b7")
}
Display all documents from a collection with the help of find() method −
> db.demo122.find();
This will produce the following output −
{ "_id" : ObjectId("5e2f20f1140daf4c2a3544b6"), "ListOfValues" : [ 100, 10 ] }
{ "_id" : ObjectId("5e2f20f7140daf4c2a3544b7"), "ListOfValues" : [ 240, 10 ] }
Following is the query to get distinct levels of array field in MongoDB −
> db.demo122.aggregate([
...    {
...       "$group": {
...          "_id": 0,
...          "ListOfValues": { "$addToSet": "$ListOfValues" }
...       }
...    }
... ])
This will produce the following output −
{ "_id" : 0, "ListOfValues" : [ [ 240, 10 ], [ 100, 10 ] ] }
What is Operator Precedence Parsing?

Operator Precedence Parsing is also a type of Bottom-Up Parsing that can be used to a class of Grammars known as Operator Grammar.
A Grammar G is Operator Grammar if it has the following properties −
Production should not contain ε on its right side.
Production should not contain ε on its right side.
There should not be two adjacent non-terminals at the right side of production.
There should not be two adjacent non-terminals at the right side of production.
Example1 − Verify whether the following Grammar is operator Grammar or not.
E → E A E |(E)|id
A → +| − | ∗
Solution
No, it is not an operator Grammar as it does not satisfy property 2 of operator Grammar.
As it contains two adjacent Non-terminals on R.H.S of production E → E A E.
We can convert it into the operator Grammar by substituting the value of A in E → E A E.
E → E + E |E − E |E * E |(E) | id.
Operator Precedence Relations
Three precedence relations exist between the pair of terminals.
Depending upon these precedence Relations, we can decide which operations will be executed or parsed first.
Association and Precedence Rules
If operators have different precedence
Since * has higher precedence than +
Example−
In a statement a + b * c
∴ + <. *
In statement a * b + c
∴ ∗ . > +
If operators have Equal precedence, then use Association rules.
(a) Example minus; In statement a + b + c here + operators are having equal precedence.
As '+' is left Associative in a + b + c
∴ (a + b) will be computed first, and then it will be added to c.
i.e., (a + b) + c
+ .> +
Similarly, '*' is left Associative in a * b * c
(b) Example − In a statement a ↑ b ↑ c here, ↑ is the Right Associative operator
∴ It will become a ↑ (b ↑ c)
∴ (b ↑ c) will be computed first.
∴ ↑<. ↑
Identifier has more precedence then all operators and symbols.
∴ θ <. id           $ <. id
id . > θ            id . > $
id . >)
(<. id.
$ has less precedence than all other operators and symbols.
$ <.           ( id . > $
$ <. +         ). > $
$ <.*
Example2 − Construct the Precedence Relation table for the Grammar.
E → E + E | E ∗ E/id
Solution
Operator-Precedence Relations
Advantages of Operator Precedence Parsing
It is accessible to execute.
Disadvantages of Operator Precedence Parsing
Operator Like minus can be unary or binary. So, this operator can have different precedence’s in different statements.
Operator Like minus can be unary or binary. So, this operator can have different precedence’s in different statements.
Operator Precedence Parsing applies to only a small class of Grammars.
Operator Precedence Parsing applies to only a small class of Grammars.
OpenCV - Scharr Operator

Scharr is also used to detect the second derivatives of an image in horizontal and vertical directions. You can perform scharr operation on an image using the method scharr(). Following is the syntax of this method −
Scharr(src, dst, ddepth, dx, dy)

This method accepts the following parameters −
src − An object of the class Mat representing the source (input) image.
src − An object of the class Mat representing the source (input) image.
dst − An object of the class Mat representing the destination (output) image.
dst − An object of the class Mat representing the destination (output) image.
ddepth − An integer variable representing the depth of the image (-1)
ddepth − An integer variable representing the depth of the image (-1)
dx − An integer variable representing the x-derivative. (0 or 1)
dx − An integer variable representing the x-derivative. (0 or 1)
dy − An integer variable representing the y-derivative. (0 or 1)
dy − An integer variable representing the y-derivative. (0 or 1)
The following program demonstrates how to apply scharr to a given image.
import org.opencv.core.Core;
import org.opencv.core.Mat;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class ScharrTest {

   public static void main( String[] args ) {

      // Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );

      // Reading the Image from the file and storing it in to a Matrix object
      String file ="E:/OpenCV/chap16/sobel_input.jpg";
      Mat src = Imgcodecs.imread(file);

      // Creating an empty matrix to store the result
      Mat dst = new Mat();

      // Applying Box Filter effect on the Image
      Imgproc.Scharr(src, dst, Imgproc.CV_SCHARR, 0, 1);

      // Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap16/scharr_output.jpg", dst);

      System.out.println("Image processed");
   }
}
Assume that following is the input image scharr_input.jpg specified in the above program.
On executing it, you will get the following output −
Image Processed

If you open the specified path you can observe the output image as follows −
On passing different values to the last to parameters (dx and dy) (among 0 and 1) you will get different outputs −
// Applying scharr on the Image
Imgproc.Scharr(src, dst, -1, 1, 1);

Following is a table listing various values for the variables dx and dy of the method scharr() and their respective outputs.

    70 Lectures 
     9 hours 

 Abhilash Nelson

    41 Lectures 
     4 hours 

 Abhilash Nelson

    20 Lectures 
     2 hours 

 Spotle Learn

    12 Lectures 
     46 mins

 Srikanth Guskra

    19 Lectures 
     2 hours 

 Haithem Gasmi

    67 Lectures 
     6.5 hours 

 Gianluca Mottola
 Print
 Add Notes
 Bookmark this page
Check existence of an element in Java ArrayList

The java.util.ArrayList.contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present.
A program that demonstrates this is given as follows
 Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add("A");
      aList.add("B");
      aList.add("C");
      aList.add("D");
      aList.add("E");
      System.out.println("The element C is available in ArrayList? " + aList.contains("C"));
      System.out.println("The element Z is available in ArrayList? " + aList.contains("Z"));
   }
}
The output of the above program is as follows
The element C is available in ArrayList? true
The element Z is available in ArrayList? false
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.contains() is used to check if “C” and “Z” are available in the ArrayList and the result is displayed. A code snippet which demonstrates this is as follows
List aList = new ArrayList();
aList.add("A");
aList.add("B");
aList.add("C");
aList.add("D");
aList.add("E");
System.out.println("The element C is available in ArrayList? " + aList.contains("C"));
System.out.println("The element Z is available in ArrayList? " + aList.contains("Z"));
How to convert a string into upper case using JavaScript?

To convert a string into upper case, use the JavaScript toUpperCase() method. This method returns the calling string value converted to uppercase.
You can try to run the following code to convert a string into the upper case −
Live Demo
<html>
   <head>
      <title>JavaScript String toUpperCase() Method</title>
   </head>

   <body>
      <script>
         var str = "demo text";
         document.write(str.toUpperCase( ));
      </script>
   </body>
</html>
Tryit Editor v3.7 - Show Java

public class GetFileInfo {  
  public static void main(String[] args) {  
    File myObj = new File("filename.txt");
    if (myObj.exists()) {
      System.out.println("File name: " + myObj.getName()); 
      System.out.println("Absolute path: " + myObj.getAbsolutePath()); 
      System.out.println("Writeable: " + myObj.canWrite()); 
      System.out.println("Readable: " + myObj.canRead()); 
      System.out.println("File size in bytes: " + myObj.length());
    } else {
      System.out.println("The file does not exist.");
Ubuntu - Secure Shell

The Secure Shell (SSH) in Linux is used to log into the machine in an encrypted and safe manner. This helps in providing a secure channel to streamline all requests to the Ubuntu server. SSH uses cryptographic keys to log into the server.
On Windows, the most common tool to perform a secure shell to a Linux server is putty. In this chapter, we will learn how to use putty to Secure Shell into a server.
Step 1 − Download putty from the http://www.putty.org/ site.
Step 2 − Before connecting to use putty, we need to know the IP address of our Ubuntu box. To do this, type ifconfig in the command shell of the Ubuntu server.
From the above screenshot, we know that the IP address of the server is 192.168.0.20
Step 3 − Next step is installing SSH on the server. In order to SSH to a server, you need to make sure it is installed. Run the following command in the Ubuntu server command prompt session.
sudo apt-get install openssh-server

Step 4 − Launch PuTTY. Enter the IP address of the Ubuntu server and click the Open button.
Step 5 − The next screen requests to accept the encrypted key sent from the server.
Step 6 − Finally, enter the username and password to log into the server. We have successfully established a secure shell to the server.

    8 Lectures 
     31 mins

 Musab Zayadneh

    14 Lectures 
     1.5 hours 

 Satish

    26 Lectures 
     1.5 hours 

 YouAccel
 Print
 Add Notes
 Bookmark this page
DoubleStream sum() method in Java

The sum() method of the DoubleStream class in Java returns the sum of elements in this stream.
The syntax is as follows
double sum()
To use the DoubleStream class in Java, import the following package
import java.util.stream.DoubleStream;
Create DoubleStream and add some elements
DoubleStream doubleStream = DoubleStream.of(23.6, 45.3, 59.6, 60.6, 73.6, 84.7, 94.8);
Now, sum the elements of the stream
double sum = doubleStream.sum();

The following is an example to implement DoubleStream sum() method in Java
 Live Demo
import java.util.*;
import java.util.stream.DoubleStream;
public class Demo {
   public static void main(String[] args) {
      DoubleStream doubleStream = DoubleStream.of(23.6, 45.3, 59.6, 60.6, 73.6, 84.7, 94.8);
      double sum = doubleStream.sum();
      System.out.println("The sum of all the elements of the stream = "+sum);
   }
}
The sum of all the elements of the stream = 442.2
error_reporting() function in PHP

The error_reporting() function specifies which errors are reported. It sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script. It returns the old error reporting level or the current error reporting level if no level parameter is given.
error_reporting(level)
level − It specifies the error report level for the current script. Value number and constant name are accepted.
level − It specifies the error report level for the current script. Value number and constant name are accepted.
The error_reporting() function returns the old error reporting level or the current error reporting level if no level parameter is given.
The following is an example −
 Live Demo
<?php
   // Turn off error reporting
   error_reporting(0);

   // Report runtime errors
   error_reporting(E_ERROR | E_WARNING | E_PARSE);
?>
Let us see another example to report all errors −
<?php
   error_reporting(E_ALL);
?>
Make the button size small with Bootstrap

To make a small button, use the .btn-sm Bootstrap class.
You can try to run the following code to make small size of button −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <meta name = "viewport" content = "width=device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <button type = "button" class = "btn btn-default btn-sm">
         Small button
      </button>
   </body>
</html>
showq - Unix, Linux Command

showq [generic Postfix daemon options]


The showq(8) daemon can also be run in stand-alone mode
by the superuser. This mode of operation is used to emulate
the ‘mailq’ command while the Postfix mail system is down.








The text below provides only a parameter summary. See
postconf(5) for more details including examples.

/var/spool/postfix, queue directories

pickup(8), local mail pickup service
cleanup(8), canonicalize and enqueue mail
qmgr(8), queue manager
postconf(5), configuration parameters
master(8), process manager
syslogd(8), system logging



Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA


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
Left Shift and Right Shift Operators in C/C++

In the left shift operator, the left operands value is moved left by the number of bits specified by the right operand.
Here is an example of left shift operator in C language,
 Live Demo
#include <stdio.h>

int main() {
   int y = 28; // 11100
   int i = 0;

   for(i;i<=3;++i)
   printf("Left shift by %d: %d\n", i, y<<i);

   return 0;
}
Here is the output
Left shift by 0: 28
Left shift by 1: 56
Left shift by 2: 112
Left shift by 3: 224
In the right shift operator, the left operands value is moved right by the number of bits specified by the right operand.
Here is an example of right shift operator in C language,
 Live Demo
#include <stdio.h>

int main() {
   int x = 10; // 1010
   int i = 0;

   for(i;i<2;i++)
   printf("Right shift by %d: %d\n", i, x>>i);

   return 0;
}
Here is the output
Right shift by 0: 10
Right shift by 1: 5
Call a method Asynchronously in C#

Asynchronous programming in C# is an efficient approach towards activities blocked or access is delayed. If an activity is blocked like this in a synchronous process, then the complete application waits and it takes more time. The application stops responding. Using asynchronous approach, the applications continues with other tasks as well.
An application with a GUI, check the content of the queue and if an unprocessed task is there, it takes it out and processes it first. The code executes synchronously and the unprocessed task is completed first. The application will show stop responding messages if the processing takes more time than expected.
Let us see what is discussed above.
private void OnRequestDownload(object sender, RoutedEventArgs e) {
   var req = HttpWebRequest.Create(_requestedUri);
   var res = req.GetResponse();
}
To solve the above issue, use the async and await keywords.
private async void OnRequestDownload(object sender, RoutedEventArgs e) {
   var req= HttpWebRequest.Create(_requestedUri);
   var res = await req.GetResponseAsync();
}
How to find the number of non-empty values in an R data frame column?

To find the number of non-empty values, we can find the negation of the sum of empty values which is actually the total number of non-empty values. For example, if we have a data frame df that contains a column x which has some empty values then to find the total number of non-empty values we can find the opposite/negation of total empty values. This can be done with the help of sum function and negation operator as shown in the below examples.
Consider the below data frame −
Live Demo
> x<-sample(c(1,2,""),20,replace=TRUE)
> df1<-data.frame(x)
> df1
   x
1  1
2  2
3  
4  
5  
6  
7  
8  2
9  
10
11 2
12 2
13 2
14 2
15 2
16
17
18
19
20 1
Finding total number of non-empty values in column x of df1 −
> sum(df1$x!="")
[1] 9
Live Demo
> y<-sample(c(5,""),20,replace=TRUE)
> df2<-data.frame(y)
> df2
   y
1  5
2  
3  5
4  
5  5
6  5
7  
8  5
9  5
10 5
11 5
12
13
14 5
15
16
17
18
19
20
Finding total number of non-empty values in column y of df2 −
> sum(df2$y!="")
[1] 9
Live Demo
> z<-sample(c(5,3,2,""),20,replace=TRUE)
> df3<-data.frame(z)
> df3
   z
1  5
2  3
3  
4  3
5  
6  
7  
8  3
9  2
10 2
11 2
12
13 2
14 2
15
16 3
17
18 2
19
20 3
Finding total number of non-empty values in column z of df3 −
> sum(df3$z!="")
[1] 12
How to draw a rectangle in OpenCV using C++?

To draw a rectangle, we need four points. Look at the following figure.
In the figure, there are four points x1, x2, y1 and y2. These four points are forming the four coordinates. To draw a rectangle using OpenCV, we have to define these points and show the rectangle we need a matrix. We have to declare other relevant values like the color of the line and line width.
The basic syntax of this method is as follows −
rectangle(whiteMatrix, starting, ending, line_Color, thickness);
The following program represents how to draw a rectangle in OpenCV.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main() {
   Mat whiteMatrix(200, 200, CV_8UC3, Scalar(255, 255, 255));// Declaring a white matrix//
   Point starting(40, 40);//Declaring the starting coordinate//
   Point ending(160, 100);//Declaring the ending coordinate
   Scalar line_Color(0, 0, 0);//Color of the rectangle//
   int thickness = 2;//thickens of the line//
   namedWindow("whiteMatrix");//Declaring a window to show the rectangle//
   rectangle(whiteMatrix, starting, ending, line_Color, thickness);//Drawing the rectangle//
   imshow("WhiteMatrix", whiteMatrix);//Showing the rectangle//
   waitKey(0);//Waiting for Keystroke
   return 0;
}
Collapsing Table Borders in CSS

The CSS border-collapse property is used to specify whether <table>elements have shared or separate borders. It can take two values: separate and collapse.
The syntax of CSS border-collapse property is as follows −
Selector {
   border-collapse: /*value*/
}
The following examples illustrate CSS border-collapse −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
#cdemo {
   border-collapse: collapse;
}
#sdemo {
   border-collapse: separate;
}
table {
   display: inline-table;
   margin: 30px;
}
th,td {
   border: 3px ridge orange;
}
td {
   border-color: red;
}
caption {
   box-shadow: 0px -5px 4px 3px green;
}
</style>
</head>
<body>
<h2>Employee Records</h2>
<table id="sdemo">
<caption> Employee Details (Separate Border) </caption>
<tr>
<th>Employee</th>
<th>Department</th>
</tr>
<tr>
<td>Tim</td>
<td>Operations</td>
</tr>
<tr>
<td>Nathan</td>
<td>Finance</td>
</tr>
<tr>
<td>John </td>
<td>Marketing</td>
</tr>
</table>
<table id="cdemo">
<caption> Employee Details (Collapse Border) </caption>
<tr>
<th>Employee</th>
<th>Department</th>
</tr>
<tr>
<td>Tim</td>
<td>Operations</td>
</tr>
<tr>
<td>Nathan</td>
<td>Finance</td>
</tr>
<tr>
<td>John </td>
<td>Marketing</td>
</tr>
</table>
</body>
</html>
This gives the following output −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
table {
   border-collapse: separate;
   empty-cells: hide;
   display: inline-table;
   margin: 30px;
}
table+table {
   border-collapse: collapse;
   empty-cells: hide;
}
td {
   border: 3px ridge lightblue;
}
caption {
   box-shadow: 0px -5px 4px 3px grey;
}
</style>
</head>
<body>
<h2>Demo Tables</h2>
<table>
<caption>Demo caption</caption>
<tr>
<td>demo</td>
<td>demo</td>
</tr>
<tr>
<td>demo</td>
<td>demo</td>
</tr>
<tr>
<td>demo</td>
<td>demo</td>
<td></td>
</tr>
</table>
<table>
<caption>Demo caption</caption>
<tr>
<td>demo</td>
<td>demo</td>
</tr>
<tr>
<td>demo</td>
<td>demo</td>
</tr>
<tr>
<td>demo</td>
<td>demo</td>
<td></td>
</tr>
</table>
</body>
</html>
This gives the following output −
Difference between 3-address instruction and 0-address instruction - GeeksforGeeks

16 May, 2020
Prerequisite – Instruction Formats1. Three-Address Instructions :Three-address instruction is a format of machine instruction. It has one opcode and three address fields. One address field is used for destination and two address fields for source.
Example:
X = (A + B) x (C + D) 
Solution:
ADD R1, A, B      R1 <- M[A] + M[B]
ADD R2, C, D      R2 <- M[C] + M[D]
MUL X, R1, R2     M[X] <- R1 x R2 
2. Zero-Address Instructions :Zero-address instruction is a format of machine instruction. It has one opcode and no address fields.
Example:
X = (A + B) x (C + D) 
Solution:
LOAD A      AC <- M[A]
PUSH A      TOS <- A
PUSH B      TOS <- B
ADD         TOS <- (A + B)
PUSH C      TOS <- C
PUSH D      TOS <- D
ADD         TOS <- (C + D)
MUL         TOS <- (C + D) x (A + B)
POP X       M[X] <- TOS 
Difference between Three-Address Instruction and Zero-Address Instruction :
Computer Organization & Architecture
Difference Between
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
I2C Communication Protocol
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Google BigQuery SQL Dates and Times Cheat Sheet | by Rebecca Vickery | Towards Data Science

I have just started working on a time series forecasting project this morning. The first step in this project, as with most data science tasks, was to gather the data first. This meant a relatively simple SQL query in Google BigQuery. Once again I found myself googling how to extract the year from a timestamp, and scrolling through the documentation to find the correct function and realised that I needed to write this down somewhere. I am writing this into a blog post so that I have something to refer back to, and hopefully this may also help others. Please note all expressions are based on Standard SQL.
List of all date parts that can be used in the expressions listed below:
DAYOFWEEK (returns 1-7 Sunday is 1)DAYDAYOFYEAR (0-365)WEEK (week of year 0-53, week begins on Sunday)WEEK(<chosen weekday>) (week of year begins on your chosen day e.g. SUNDAY)ISOWEEK (ISO 8601 week number, week begins on Monday)MONTHQUARTER (1-4)YEAR (ISO 8601 year number) 
EXTRACT(part FROM date_expression)Example: EXTRACT(YEAR FROM 2019-04-01)Output: 2019
DATE(year, month, day)Example: DATE(2019, 04, 01)Output: 2019-04-01
DATE_ADD(date_expression, INTERVAL INT64_expr date_part)Example: DATE_ADD('2019-04-01', INTERVAL 1 DAY)Output: 2019-04-02DATE_SUB(date_expression, INTERVAL INT64_expr date_part)Example: DATE_SUB('2019-04-01', INTERVAL 1 DAY)Output: 2019-03-31Example use case - dynamic dates:where my_date between DATE_SUB(current_date, INTERVAL 7 DAY) and DATE_SUB(current_date, INTERVAL 1 DAY)
DATE_DIFF(date_expression, date_expression, date_part)Example: DATE_DIFF(2019-02-02, 2019-02-01, DAY)Output: 1
DATE_TRUNC(date_expression, date_part)Example: DATE_TRUNC(2019-04-12, WEEK)Output: 2019-04-07
MICROSECONDMILLISECONDSECONDMINUTEHOUR
DATETIME(year, month, day, hour, minute, second)DATETIME(date_expression, time_expression)DATETIME(timestamp_expression [, timezone])Example: DATETIME(2019, 04, 01, 11, 55, 00)Output: 2019-04-01 11:55:00
DATETIME_ADD(datetime_expression, INTERVAL INT64_expr part)Example: DATETIME_ADD('2019-04-01 11:55:00', INTERVAL 1 MINUTE)Output: 2019-04-01 11:56:00DATETIME_SUB(datetime_expression, INTERVAL INT64_expr part)Example: DATETIME_SUB('2019-04-01 11:55:00', INTERVAL 1 MINUTE)Output: 2019-04-01 11:54:00
DATETIME_DIFF(datetime_expression, datetime_expression, part)Example: DATETIME_DIFF('2019-04-01 11:56:00', '2019-04-01 11:55:00', MINUTE)Output: 1
DATETIME_TRUNC(datetime_expression, part)Example: DATETIME_TRUNC('2019-04-01 11:55:00', HOUR)Output: 2019-04-01 11:00:00
This is not by any means an exhaustive guide to date and time expressions in BigQuery. It is only meant as a quick reference to those I use most often. For a more comprehensive guide please see the Google BigQuery documentation.
JSON - Syntax

Let's have a quick look at the basic syntax of JSON. JSON syntax is basically considered as a subset of JavaScript syntax; it includes the following −
Data is represented in name/value pairs.
Data is represented in name/value pairs.
Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma).
Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma).
Square brackets hold arrays and values are separated by ,(comma).
Square brackets hold arrays and values are separated by ,(comma).
Below is a simple example −
{
   "book": [

      {
         "id": "01",
         "language": "Java",
         "edition": "third",
         "author": "Herbert Schildt"
      },

      {
         "id": "07",
         "language": "C++",
         "edition": "second",
         "author": "E.Balagurusamy"
      }

   ]
}
JSON supports the following two data structures −
Collection of name/value pairs − This Data Structure is supported by different programming languages.
Collection of name/value pairs − This Data Structure is supported by different programming languages.
Ordered list of values − It includes array, list, vector or sequence etc.
Ordered list of values − It includes array, list, vector or sequence etc.

    20 Lectures 
     1 hours 

 Laurence Svekis

    16 Lectures 
     1 hours 

 Laurence Svekis

    10 Lectures 
     1 hours 

 Laurence Svekis

    23 Lectures 
     2.5 hours 

 Laurence Svekis

    9 Lectures 
     48 mins

 Nilay Mehta

    18 Lectures 
     2.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page