code-rag-bench/online-tutorials huggingface dataset:
Test whether the elements of a given NumPy array is zero or not in Python

02 Sep, 2020
In numpy, we can check that whether none of the elements of given array is zero or not with the help of numpy.all() function. In this function pass an array as parameter. If any of one element of the passed array is zero then it returns False otherwise it returns True boolean value.
Syntax: numpy.all()
Parameters: An array
Return: A boolean value (True or False)
Let’s see the examples:
Example 1:
Python
# import numpy libraryimport numpy as np  # create an arrayx = np.array([34, 56, 89,              23, 69, 980,              567])  # print arrayprint(x)  # Test if none of the elements # of the said array is zeroprint(np.all(x))
Output:
[34,56,89,23,69,980,567]
True

Example 2:
Python
# import numpy libraryimport numpy as np  # create an arrayx = np.array([1, 2, 3,              4, 6, 7,              8, 9, 10,              0, 89, 67])  # print arrayprint(x)  # Test if none of the elements# of the said array is zeroprint(np.all(x))
Output:
False

Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python – Store Function as dictionary value

14 Oct, 2020
Given a dictionary, assign its keys as function calls.
Case 1 : Without Params. 
The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets ‘()’ are added.
Python3
# Python3 code to demonstrate working of # Functions as dictionary values# Using Without params  # call Gfg fnc def print_key1():    return "This is Gfg's value"  # initializing dictionary# check for function name as keytest_dict = {"Gfg": print_key1, "is" : 5, "best" : 9}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # calling function using brackets res = test_dict['Gfg']()  # printing result print("The required call result : " + str(res)) 
The original dictionary is : {'Gfg': <function print_key1 at 0x7f1c0445be18>, 'is': 5, 'best': 9}
The required call result : This is Gfg's value

Case 2 : With params 
The task of calling with params is similar to above case, the values are passed during function call inside brackets as in usual function calls.
Python3
# Python3 code to demonstrate working of # Functions as dictionary values# Using With params   # call Gfg fnc def sum_key(a, b):    return a + b  # initializing dictionary# check for function name as keytest_dict = {"Gfg": sum_key, "is" : 5, "best" : 9}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # calling function using brackets # params inside bracketsres = test_dict['Gfg'](10, 34)  # printing result print("The required call result : " + str(res)) 
The original dictionary is : {'Gfg': <function sum_key at 0x7f538d017e18>, 'is': 5, 'best': 9}
The required call result : 44

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python | Pandas Series.median()

11 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.median() function return the median of the underlying data in the given Series object.
Syntax: Series.median(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameter :axis : Axis for the function to be applied on.skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.numeric_only : Include only float, int, boolean columns**kwargs : Additional keyword arguments to be passed to the function.
Returns : median : scalar or Series (if level specified)
Example #1: Use Series.median() function to find the median of the underlying data in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.median() function to find the median of the given series object.
# return the medianresult = sr.median()  # Print the resultprint(result)
Output :As we can see in the output, the Series.median() function has successfully returned the median of the given series object. Example #2: Use Series.median() function to find the median of the underlying data in the given series object. The given series object contains some missing values.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, 16.8, 20.124, None, 18.1002, 19.5])  # Print the seriesprint(sr)
Output :
Now we will use Series.median() function to find the median of the given series object. we are going to skip the missing values while calculating the median in the given series object.
# return the medianresult = sr.median(skipna = True)  # Print the resultprint(result)
Output :As we can see in the output, the Series.median() function has successfully returned the median of the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Axes to a Figure in Matplotlib with Python?

02 Dec, 2020
Matplotlib is a library in Python used to create figures and provide tools for customizing it. It allows plotting different types of data, geometrical figures. In this article, we will see how to add axes to a figure in matplotlib.
We can add axes to a figure in matplotlib by passing a list argument in the add_axes() method.
Syntax: matplotlib.pyplot.figure.add_axes(rect)
Parameters:
rect: This parameter is the dimensions [xmin, ymin, dx, dy] of the new axes. It takes the below elements as arguments in the list:
xmin: Horizontal coordinate of the lower left corner.
ymin: Vertical coordinate of the lower left corner.
dx: Width of the subplot.
dy: Height of the subplot.
Returns: This method return the axes class depends on the projection used. 
Example 1:
Python3
# Importing libraryimport matplotlib  # Create figure() objects# This acts as a container# for the different plotsfig = matplotlib.pyplot.figure()  # Creating axis# add_axes([xmin,ymin,dx,dy])axes = fig.add_axes([0.5, 1, 0.5, 1])  # Depict illustrationfig.show()
Output:
Example 2:
Python3
# Importing libraryimport matplotlib  # Create figure() objects# This acts as a container # for the different plotsfig=matplotlib.pyplot.figure()   # Creating two axes# add_axes([xmin,ymin,dx,dy])axes=fig.add_axes([0,0,2,2]) axes1=fig.add_axes([0,1,2,2])  # Depict illustrationfig.show()
Output:
Example 3:
Python3
# Import librariesimport matplotlibimport numpy  # Create figure() objects# This acts as a container# for the different plotsfig = matplotlib.pyplot.figure()  # Generate line graphx = numpy.arange(0, 1.414*2, 0.05)y1 = numpy.sin(x)y2 = numpy.cos(x)  # Creating two axes# add_axes([xmin,ymin,dx,dy])axes1 = fig.add_axes([0, 0, 1, 1])axes1.plot(x, y1)axes2 = fig.add_axes([0, 1, 1, 1])axes2.plot(x, y2)  # Show plotplt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Append Text to End of File in Linux?

07 Mar, 2021
On Linux, while working with files in a terminal sometimes we need to append the same data of a command output or file content. Append means simply add the data to the file without erasing existing data. Today we are going to see how can we append the text in the file on the terminal.
The >> operator redirects output to a file. If the mentioned file doesn’t exist the file is created and then the text is appended to the file.
Examples:
We can use the echo command to append the text to the file, like
echo "Which is the best Linux Distro?"  >>  file.txt
Alternatively, we can use printf command to append text into a file.
printf "Which is the best Linux Distro?\n"  >>  file.txt
We can also use the cat command to append the content of one file to another file.
Example:
In this example, we have to append the content of file file1.txt to the file file2.txt
cat file1.txt >> file2.txt
Note: Don’t use > of >> This will erase the data of the target file. This may cause data loss.
The tee command copies the text from standard input and writes it to the standard output file. The tee provides -a option to append the text to the file.
echo "Which is the best Linux Distro?"   | tee -a file.txt
We can also append the content of a file into another file using the tee command
Example:
In this example, we have to append the content of file file1.txt to the file file2.txt
cat file1.txt | tee -a file2.txt
This is how we append the text into a file in Linux.
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
Program to find longest common prefix from list of strings in Python

Suppose we have a list of lowercase strings, we have to find the longest common prefix.
So, if the input is like ["antivirus", "anticlockwise", "antigravity"], then the output will be "anti"
To solve this, we will follow these steps −
sort the list words alphabetically
prefix := a new list
flag := 0
for i in range 0 to size of words[0], dofor each j in words, doif j[i] is not same as last element of prefix, thendelete last element from prefixflag := 1come out from the loopif flag is same as 1, thencome out from the loop
for each j in words, doif j[i] is not same as last element of prefix, thendelete last element from prefixflag := 1come out from the loop
if j[i] is not same as last element of prefix, thendelete last element from prefixflag := 1come out from the loop
delete last element from prefix
flag := 1
come out from the loop
if flag is same as 1, thencome out from the loop
come out from the loop
return string after concatenating all elements present in prefix array
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, words):
      words.sort()
      prefix = []
      flag = 0
      for i in range(len(words[0])):
         prefix.append(words[0][i])
         for j in words:
            if j[i] != prefix[-1]:
               prefix.pop()
               flag = 1
               break
         if flag == 1:
            break
         return ''.join(prefix)
ob = Solution()
words = ["antivirus", "anticlockwise", "antigravity"]
print(ob.solve(words))
["antivirus", "anticlockwise", "antigravity"]
anti
How to preselect Dropdown Using JavaScript Programmatically?

To preselect a dropdown item using JavaScript, use the selectedIndex property. Add an index of what item you want to be selected.
Dropdown item list is created in HTML using the <select> tag. For JavaScript, we use the <script> tag. Here, under the <script> tag, add_select_id is the id of the <select> tag, whereas add_item_index is the index in numbers. This index is the list item index; you need to add for the item you want to be preselected.
You can try to run the following code to preselect dropdown using JavaScript programmatically −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML select tag</title>
   </head>
   <body>
      <p> Select any one:</p>
      <form>
         <select id="dropdown" name="dropdown" class="form-control">
            <option value = "Android">Android</option>
            <option value = "CSS">CSS</option>
            <option value = "Python">Python</option>
         </select>
      </form>
      <script>
         document.getElementById("dropdown").selectedIndex = "1";
      </script>
   </body>
</html>
Binary Search in C++ program?

binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array. Even though the idea is simple, implementing binary search correctly requires attention to some subtleties about its exit conditions and midpoint calculation, particularly if the values in the array are not all of the whole numbers in the range.
Binary search is the most popular search algorithm. It is efficient and also one of the most commonly used techniques that are used to solve problems.
If all the names in the world are written down together in order and you want to search for the position of a specific name, binary search will accomplish this in a maximum of 35 iterations.
Binary search works only on a sorted set of elements. To use binary search on a collection, the collection must first be sorted.
When a binary search is used to perform operations on a sorted set, the number of iterations can always be reduced on the basis of the value that is being searched.
Let us consider the following array −
By using a linear search, the position of element 8 will be determined in the 9th iteration.
Let's see how the number of iterations can be reduced by using a binary search. Before we start the search, we need to know the start and end of the range. Let's call them Low and High.
Low = 0
High = n-1
Now, compare the search value K with the element located at the median of the lower and upper bounds. If the value K is greater, increase the lower bound, else decrease the upper bound.
Referring to the image above, the lower bound is 0 and the upper bound is
9
The median of the lower and upper bounds is (lower_bound + upper_bound) / 2 = 4. Here a[4] = 4. The value 4>2, which is the value that you are searching for. Therefore, we do not need to conduct a search on any element beyond 4 as the elements beyond it will obviously be greater than 2.
Therefore, we can always drop the upper bound of the array to the position of element 4. Now, we follow the same procedure on the same array with the following values −
Low: 0
High: 3
Repeat this procedure recursively until Low > High. If at any iteration, we get a[mid]=key, we return value of mid. This is the position of key in the array. If key is not present in the array, we return −1.
int binarySearch(int low,int high,int key){
   while(low<=high){
      int mid=(low+high)/2;
      if(a[mid]<key){
         low=mid+1;
      }
      else if(a[mid]>key){
         high=mid-1;
      }
      else{
         return mid;
      }
   }
   return -1; //key not found
}
PostgreSQL - DROP INDEX - GeeksforGeeks

28 Aug, 2020
In PostgreSQL, the DROP INDEX statement to remove an existing index.
Syntax:
DROP INDEX  [ CONCURRENTLY]
[ IF EXISTS ]  index_name 
[ CASCADE | RESTRICT ];

Let’s analyze the above syntax:
index_name : This is used to specify the name of the index that you want to remove after the DROP INDEX clause.
IF EXISTS: Attempting to remove a non-existent index will result in an error. To avoid this, you can use the IF EXISTS option. In case you remove a non-existent index with IF EXISTS, PostgreSQL issues a notice instead.
CASCADE: If the index has dependent objects, you use the CASCADE option to automatically drop these objects and all objects that depend on those objects.
RESTRICT: The RESTRICT option instructs PostgreSQL to refuse to drop the index if any objects depend on it. The DROP INDEX uses RESTRICT by default.
CONCURRENTLY: When you execute the DROP INDEX statement, PostgreSQL acquires an exclusive lock on the table and block other accesses until the index removal completes. To force the command waits until the conflicting transaction completes before removing the index, you can use the CONCURRENTLY option.
For the purpose of example, we will use the actor table from the sample database for the demonstration.
Example:
The following statement creates an index for the first_name column of the actor table:
CREATE INDEX idx_actor_first_name 
ON actor (first_name);

Sometimes, the Query Optimizer does not use the index. For example, the following statement finds the actor with the name ‘John’:
SELECT * FROM actor
WHERE first_name = 'John';

The query did not use the idx_actor_first_name index defined earlier as explained in the following EXPLAIN statement:
EXPLAIN SELECT *
FROM actor
WHERE first_name = 'John';
This is because the query optimizer thinks that it is more optimal to just scan the whole table to locate the row. Hence, the idx_actor_first_name is not useful in this case and we need to remove it:
DROP INDEX idx_actor_first_name;
Output:
postgreSQL-indexes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - GROUP BY clause
PostgreSQL - LEFT JOIN
PostgreSQL - Rename Table
PostgreSQL - Copy Table
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Record type variable
PostgreSQL - While Loops
PostgreSQL - Select Into
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Cursor
Check if a list exists in given list of lists in Python

Lists can be nested, means the elements of a list are themselves lists. In this article we will see how to find out if a given list is present as an element in the outer bigger list.
This is a very simple and straight forward method. We use the in clause just to check if the inner list is present as an element in the bigger list.
 Live Demo
listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_list = [-4,434,0]

# Given list
print("Given List :\n", listA)
print("list to Search: ",search_list)

# Using in
if search_list in listA:
print("Present")
else:
print("Not Present")
Running the above code gives us the following result −
Given List :
[[-9, -1, 3], [11, -8], [-4, 434, 0]]
list to Search: [-4, 434, 0]
Present
We can also use the any clause where we take an element and test if it is equal to any element present in the list. Of course with help of a for loop.
 Live Demo
listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_list = [-4,434,0]

# Given list
print("Given List :\n", listA)
print("list to Search: ",search_list)

# Using in
if any (x == search_list for x in listA):
print("Present")
else:
print("Not Present")
Running the above code gives us the following result − 
Given List :
[[-9, -1, 3], [11, -8], [-4, 434, 0]]
list to Search: [-4, 434, 0]
Present
How to set initial value and auto increment in MySQL?

The AUTO_INCREMENT attribute is used to generate a unique identify for new rows. If a column is declared as ‘NOT NULL’, it is possible to assign NULL to that column to generate a sequence of numbers.
When any value is inserted into an AUTO_INCREMENT column, the column gets set to that value, and the sequence also gets reset so that it generates values automatically, in the sequential range from largest column value.
An existing ‘AUTO_INCREMENT’ column can be updated that will reset the ‘AUTO_INCREMENT’ sequence as well. The most recent auto-generated ‘AUTO_INCREMENT; value can be retrieved using the ‘LAST_INSERT_ID()’ function in SQL or using the ‘mysql_insert_id()’ which is a C API function.
These functions are connection-specific, which means their return values are not affected by other connections which perform the insert operations. The smallest integer data type for ‘AUTO_INCREMENT’ column can be used, which would be large enough to hold the maximum sequence value which is required by the user.
The following rules need to be followed while using the AUTO_INCREMENT attribute −
Every table has only one AUTO_INCREMENT column whose data type would be an
integer typically.
Every table has only one AUTO_INCREMENT column whose data type would be an
integer typically.
The AUTO_INCREMENT column needs to be indexed. This means it can either be a
PRIMARY KEY or a UNIQUE index.
The AUTO_INCREMENT column needs to be indexed. This means it can either be a
PRIMARY KEY or a UNIQUE index.
The AUTO_INCREMENT column must have a NOT NULL constraint on it.
The AUTO_INCREMENT column must have a NOT NULL constraint on it.
When the AUTO_INCREMENT attribute is set to a column, MySQL automatically adds
the NOT NULL constraint to the column on its own.
When the AUTO_INCREMENT attribute is set to a column, MySQL automatically adds
the NOT NULL constraint to the column on its own.
If an id column hasn’t been added to the table, the below statement can be used −
ALTER TABLE tableName ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD INDEX (id);
If an id column is already present, then the below command can be used −
ALTER TABLE tableName AUTO_INCREMENT=specificValue;
Here, tableName refers to the name of the table fr which the ‘AUTO_INCREMENT’ column needs to be set. The ‘specificValue’ refers to an integer from where the ‘AUTO_INCREMENT’ values are specified by the user to begin.
Associative arrays in C++ - GeeksforGeeks

09 Feb, 2022
Associative arrays are also called map or dictionaries. In C++. These are special kind of arrays, where indexing can be numeric or any other data type i.e can be numeric 0, 1, 2, 3.. OR character a, b, c, d... OR string geek, computers... These indexes are referred as keys and data stored at that position is called value. So in associative array we have (key, value) pair. We use STL maps to implement the concept of associative arrays in C++. 
Example: Now we have to print the marks of computer geeks whose names and marks are as follows  
  Name        Marks
       Jessie       100
       Suraj        91
       Praveen      99   
       Bisa         78
       Rithvik      84
 
CPP
// CPP program to demonstrate associative arrays#include <bits/stdc++.h>using namespace std;int main(){    // the first data type i.e string represents    // the type of key we want the second data type    // i.e int represents the type of values we    // want to store at that location    map<string, int> marks{ { "Rithvik", 78 },            { "Suraj", 91 }, { "Jessie", 100 },            { "Praveen", 99 }, { "Bisa", 84 } };      map<string, int>::iterator i;    cout << "The marks of all students are" << endl;    for (i = marks.begin(); i != marks.end(); i++)        cout << i->second << " ";          cout << endl;     // the marks of the students based on there names.    cout << "the marks of Computer geek Jessie are"         << " " << marks["Jessie"] << endl;     cout << "the marks of geeksforgeeks contributor"          " Praveen are " << marks["Praveen"] << endl;}
The marks of all students are
84 100 99 78 91 
the marks of Computer geek Jessie are 100
the marks of geeksforgeeks 
 Praveen are 99
 
simranarora5sos
cpp-map
STL
C++
Technical Scripter
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Socket Programming in C/C++
C++ Classes and Objects
Operator Overloading in C++
Multidimensional Arrays in C / C++
Virtual Function in C++
Bitwise Operators in C/C++
Constructors in C++
Templates in C++ with Examples
Copy Constructor in C++
GATE | GATE-CS-2003 | Question 79 - GeeksforGeeks

28 Jun, 2021
A processor uses 2-level page tables for virtual to physical address translation. Page tables for both levels are stored in the main memory. Virtual and physical addresses are both 32 bits wide. The memory is byte addressable. For virtual to physical address translation, the 10 most significant bits of the virtual address are used as index into the first level page table while the next 10 bits are used as index into the second level page table. The 12 least significant bits of the virtual address are used as offset within the page. Assume that the page table entries in both levels of page tables are 4 bytes wide. Further, the processor has a translation look-aside buffer (TLB), with a hit rate of 96%. The TLB caches recently used virtual page numbers and the corresponding physical page numbers. The processor also has a physically addressed cache with a hit rate of 90%. Main memory access time is 10 ns, cache access time is 1 ns, and TLB access time is also 1 ns.
Suppose a process has only the following pages in its virtual address space: two contiguous code pages starting at virtual address 0x00000000, two contiguous data pages starting at virtual address 0×00400000, and a stack page starting at virtual address 0×FFFFF000. The amount of memory required for storing the page tables of this process is:(A) 8 KB(B) 12 KB(C) 16 KB(D) 20 KBAnswer: (C)Explanation:
Breakup of given addresses into bit form:-
32bits are broken up as 10bits (L2) | 10bits (L1) | 12bits (offset)

first code page:
0x00000000 = 0000 0000 00 | 00 0000 0000 | 0000 0000 0000

so next code page will start from
0x00001000 = 0000 0000 00 | 00 0000 0001 | 0000 0000 0000

first data page:
0x00400000 = 0000 0000 01 | 00 0000 0000 | 0000 0000 0000

so next data page will start from
0x00401000 = 0000 0000 01 | 00 0000 0001 | 0000 0000 0000

only one stack page:
0xFFFFF000 = 1111 1111 11 | 11 1111 1111 | 0000 0000 0000

Now, for second level page table, we will just require 1 Page 
which will contain following 3 distinct entries i.e. 0000 0000 00,
0000 0000 01, 1111 1111 11.
Now, for each of these distinct entries, we will have 1-1 page
in Level-1.

Hence, we will have in total 4 pages and page size = 2^12 = 4KB.
Therefore, Memory required to store page table = 4*4KB = 16KB.
Quiz of this Question
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-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE-IT-2004 | Question 71
Python PIL | ImageDraw.Draw.arc() - GeeksforGeeks

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.arc() draws an arc (a portion of a circle outline) between the start and end angles, inside the given bounding box.
Syntax: PIL.ImageDraw.Draw.ellipse(xy, fill=None, outline=None)
Parameters:
xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].start – Starting angle, in degrees. Angles are measured from 3 o’clock, increasing clockwise.end – Ending angle, in degrees.fill – Color to use for the arc.
Returns: An Image object in arc shape.
     # importing image object from PILimport mathfrom PIL import Image, ImageDraw  w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)]  # creating new Image objectimg = Image.new("RGB", (w, h))  # create rectangle imageimg1 = ImageDraw.Draw(img)  img1.arc(shape, start = 20, end = 130, fill ="pink")img.show()
Output:
Another Example: Here we use different colour for filling.
     # importing image object from PILimport mathfrom PIL import Image, ImageDraw  w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)]  # creating new Image objectimg = Image.new("RGB", (w, h))  # create rectangle imageimg1 = ImageDraw.Draw(img)  img1.arc(shape, start = 20, end = 130, fill ="red")img.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
How to sum elements at the same index in array of arrays into a single array? JavaScript

We have an array of arrays and are required to write a function that takes in this array and
returns a new array that represents the sum of corresponding elements of original array.
If the original array is −
[
   [43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1]
]
Then the output should be −
[60, 93, 30, 55]
Let’s write a sample function addArray()
The full code for this function will be −
const arr = [
   [43, 2, 21],[1, 2, 4, 54],[5, 84, 2],[11, 5, 3, 1]
];
const sumArray = (array) => {
   const newArray = [];
   array.forEach(sub => {
      sub.forEach((num, index) => {
         if(newArray[index]){
            newArray[index] += num;
         }else{
            newArray[index] = num;
         }
      });
   });
   return newArray;
}
console.log(sumArray(arr));
The output in the console will be −
[ 60, 93, 30, 55 ]
Above, we iterate over each element of the original array and then each number, checking if the
sum of that index already existed, we just added the corresponding number to it othewise we
set the corresponding num equal to it.
Are the private variables and private methods of a parent class inherited by the child class in Java?

No, a child class can’t inherit private members of the parent class, it can inherit only protected, default, and public members of it. If you try it gives you a compile time error as: −
class Super{
   private int data = 30;
   public void display(){
      System.out.println("Hello this is the method of the super class");
   }
}
public class Sub extends Super{
   public void greet(){
      System.out.println("Hello this is the method of the sub class");
   }
   public static void main(String args[]){
      Sub obj = new Sub();
      System.out.println(obj.data);
   }
}
On executing this example it will give an compiletime error as shown below −
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
   The field Super.data is not visible
   at Sub.main(Sub.java:13)
Python program to find occurrence to each character in given string

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a string, we need to find the occurrence of each character in a given string.
Here we will be discussing 3 approaches as discussed below:L
 Live Demo
test_str = "Tutorialspoint"
#count dictionary
count_dict = {}
for i in test_str:
   #for existing characters in the dictionary
   if i in count_dict:
      count_dict[i] += 1
   #for new characters to be added
   else:
      count_dict[i] = 1
print ("Count of all characters in Tutorialspoint is :\n "+
str(count_dict))
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}
 Live Demo
from collections import Counter
test_str = "Tutorialspoint"
# using collections.Counter() we generate a dictionary
res = Counter(test_str)
print ("Count of all characters in Tutorialspoint is :\n "+
str(dict(res)))
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}
 Live Demo
test_str = "Tutorialspoint"
# using set() to calculate unique characters in the given string
res = {i : test_str.count(i) for i in set(test_str)}
print ("Count of all characters in Tutorialspoint is :\n "+
str(dict(res)))
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}
In this article, we have learned about how we can find the occurrence of each character in a given string.
Python | Numpy dstack() method

19 Sep, 2019
With the help of numpy.dstack() method, we can get the combined array index by index and store like a stack by using numpy.dstack() method.
Syntax : numpy.dstack((array1, array2))
Return : Return combined array index by index.
Example #1 :In this example we can see that by using numpy.dstack() method, we are able to get the combined array in a stack index by index.
# import numpyimport numpy as np  gfg1 = np.array([1, 2, 3])gfg2 = np.array([4, 5, 6])  # using numpy.dstack() methodprint(np.dstack((gfg1, gfg2)))
Output :
[[[1 4][2 5][3 6]]]
Example #2 :
# import numpyimport numpy as np  gfg1 = np.array([[10], [2], [13]])gfg2 = np.array([[41], [55], [6]])  # using numpy.dstack() methodprint(np.dstack((gfg1, gfg2)))
Output :
[[[10 41]]
[[ 2 55]]
[[13 6]]]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python - Pandas dataframe.append()
Create a directory in Python
Ruby For Beginners

30 Jul, 2018
Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro “Matz” Matsumoto in Japan. This article will cover its basic syntax and some basic programs. This article is divided into various sections for various topics.1.SetUp : Let’s start by doing setup of the Ruby programming language.
For Linux Users, Go to terminal and type:
 apt-get install ruby
Windows users, click here and install ruby on your windows.
And the Ruby will be installed to your system.
In order to compile the a ruby program, Open your text editor and save the program with ‘.rb’ extension. After this, go to terminal(or command prompt) and type : ruby ‘file.rb’ where file is the name of the program you just made, and hence the program will be compiled.
2. A good first programputs is used to print something on the console in Ruby.For eg. A string
puts "Hello World"
puts "Hello Again"

3. Comments
# is called the pound character in ruby and it is used to add comments to your code.
=begin, =end are used for multi-line comments
Example:
# this is a comment and wont be executed
= begin
this is 
a multi line
comment in ruby
= end

4. Maths: Simple mathematical functions can be carried out within the puts statements.Just as we use ‘%d’ or ‘%f’ and ‘&’ in C,we will use ‘#{ } in Ruby to get our work done.
puts "Alok has #{25+30/6} Rupees in his pocket"

Output : Alok has 30 Rupees in his pocketThe use of #{ } is how you insert Ruby computations into text strings.
5. Variables and Names : Variables in ruby are the same as that of any other dynamic programming language. You just don’t need to mention its type and ruby will know its type automatically.Example:
cars = 100
drivers = 30
puts "There are #{cars} cars and #{drivers} drivers."
Output: There are 100 cars and 30 drivers.
6. Getting input
‘gets.chomp’ is used to take input from user.
‘print’ can be used instead for ‘puts’to print without a new line.
Example:
print "How old are you ? "
age = gets.chomp
print "How tall are you ?"
height = gets.chomp
puts " You are #{age} year old and your height is #{height} cms"

Run this code on your system as output will be given by the user
7. Prompting people for numbers
gets.chomp.to_i is used to get integer input from user.
gets.chomp.to_f is used to get float(decimal) input from user.
Example:
print "Give a number"
number = gets.chomp.to_i
puts "You just entered #{number}"

These are the most basic topics of Ruby that are essential for the beginner of Ruby programming language.We will cover more topics of Ruby in our upcoming articles.
This article is contributed by Harsh Wardhan Chaudhary (Intern). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Ruby-Basics
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python PIL | ImageOps.flip() method

11 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageOps module contains a number of ‘ready-made’ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.
ImageOps.flip() Flip the image vertically (top to bottom).
Syntax: PIL.ImageOps.flip(image)
Parameters:image – The image to flip. The image will be flip vertically.
Returns: An image.
Image Used:
# Importing Image and ImageOps module from PIL package from PIL import Image, ImageOps       # creating a image1 object im1 = Image.open(r"C:\Users\System-Pc\Desktop\a.JPG")   # applying flip method im2 = ImageOps.flip(im1)   im2.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What does the “+” (plus sign) CSS selector mean?

04 Dec, 2018
The “+” sign selector is used to select the elements that are placed immediately after the specified element but not inside the particular elements.
Note: The IE8 and earlier versions </DOCTYPE> must be declared to work element + element selector.
Syntax:
element + element {
    // CSS property
} 

Example:
<!DOCTYPE html><html>    <head>        <title>+ sign selector</title>        <style>            h2 + div {                font-size:20px;                font-weight:bold;                display:inline;                background-color: yellow;                color:green;            }            h1 {            color:green;            }            body {                text-align:center;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>+ sign Selector</h2>        <div>A computer science portal for geeks</div>    </body></html>                    
Output:
Supported Browsers: The browser supported by “+” selector are listed below:
Apple Safari
Google Chrome
Firefox
Opera
Internet Explorer 7.0
CSS-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
OpenCV - Filter2D

The Filter2D operation convolves an image with the kernel. You can perform this operation on an image using the Filter2D() method of the imgproc class. Following is the syntax of this method −
filter2D(src, dst, ddepth, kernel)

This method accepts the following parameters −
src − A Mat object representing the source (input image) for this operation.
src − A Mat object representing the source (input image) for this operation.
dst − A Mat object representing the destination (output image) for this operation.
dst − A Mat object representing the destination (output image) for this operation.
ddepth − A variable of the type integer representing the depth of the output image.
ddepth − A variable of the type integer representing the depth of the output image.
kernel − A Mat object representing the convolution kernel.
kernel − A Mat object representing the convolution kernel.
The following program demonstrates how to perform the Filter2D operation on an image.
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class Filter2D {
   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/chap11/filter_input.jpg";
      Mat src = Imgcodecs.imread(file);

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

      // Creating kernel matrix
      Mat kernel = Mat.ones(2,2, CvType.CV_32F);
      
      for(int i = 0; i<kernel.rows(); i++) {
         for(int j = 0; j<kernel.cols(); j++) {
            double[] m = kernel.get(i, j);

            for(int k = 1; k<m.length; k++) {
               m[k] = m[k]/(2 * 2);
            }
            kernel.put(i,j, m);
         }
      }
      Imgproc.filter2D(src, dst, -1, kernel);
      Imgcodecs.imwrite("E:/OpenCV/chap11/filter2d.jpg", dst);
      System.out.println("Image Processed");
   }
}
Assume that following is the input image filter_input.jpg specified in the above program.
On executing the program, you will get the following output −
Image Processed

If you open the specified path, you can observe the output image as follows −
How to Create Gradient Background Animation using HTML and CSS ?

12 Jun, 2020
Gradient animation can be added to the background of your websites by using simple HTML and CSS @keyframes rule that generate the desired animation.
HTML Code: In the following example, the basic structure of the HTML page is implemented.
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    <title>Gradient Background Animation</title></head>  <body>    <section>        <div>            <h2>GeeksforGeeks</h2>            <p>Gradient background Animation</p>        </div>    </section></body>  </html>
CSS Code: In the following section, designing of the background is implemented using simple CSS @keyframes rule that provide the animation feature. Providing different gradient colors is done using linear-gradient() function.
<style>    body {        margin: 0;        padding: 0;        animation: effect 3s linear infinite;    }      section {        width: 100%;        height: 100vh;    }      div {        position: absolute;        top: 50%;        left: 50%;        transform: translate(-50%, -50%);        font-size: 3em;    }      h2 {        text-align: center;    }      @keyframes effect {        0% {            background: linear-gradient(#008000, #00FF00);        }          50% {            background: linear-gradient(#220080, #0084ff);        }          100% {            background: linear-gradient(#e78f3c, #ff4800);        }    }</style>
Complete Code: It is the combination of the above two code sections.
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">    <title>Gradient Background Animation</title></head>  <style>    body {        margin: 0;        padding: 0;        animation: effect 3s linear infinite;    }      section {        width: 100%;        height: 100vh;    }      div {        position: absolute;        top: 50%;        left: 50%;        transform: translate(-50%, -50%);        font-size: 3em;    }      h2 {        text-align: center;    }      @keyframes effect {        0% {            background: linear-gradient(#008000, #00FF00);        }          50% {            background: linear-gradient(#220080, #0084ff);        }          100% {            background: linear-gradient(#e78f3c, #ff4800);        }    }</style>  <body>    <section>        <div>            <h2>GeeksforGeeks</h2>            <p>Gradient background Animation</p>        </div>    </section></body>  </html>
Output:
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP - Logical Operators Example

Try following example to understand all the logical operators. Copy and paste following PHP program in test.php file and keep it in your PHP Server's document root and browse it using any browser.
<html>
   
   <head>
      <title>Logical Operators</title>
   </head>
   
   <body>
      
      <?php
         $a = 42;
         $b = 0;
         
         if( $a && $b ) {
            echo "TEST1 : Both a and b are true<br/>";
         }else{
            echo "TEST1 : Either a or b is false<br/>";
         }
         
         if( $a and $b ) {
            echo "TEST2 : Both a and b are true<br/>";
         }else{
            echo "TEST2 : Either a or b is false<br/>";
         }
         
         if( $a || $b ) {
            echo "TEST3 : Either a or b is true<br/>";
         }else{
            echo "TEST3 : Both a and b are false<br/>";
         }
         
         if( $a or $b ) {
            echo "TEST4 : Either a or b is true<br/>";
         }else {
            echo "TEST4 : Both a and b are false<br/>";
         }
         
         $a = 10;
         $b = 20;
         
         if( $a ) {
            echo "TEST5 : a is true <br/>";
         }else {
            echo "TEST5 : a  is false<br/>";
         }
         
         if( $b ) {
            echo "TEST6 : b is true <br/>";
         }else {
            echo "TEST6 : b  is false<br/>";
         }
         
         if( !$a ) {
            echo "TEST7 : a is true <br/>";
         }else {
            echo "TEST7 : a  is false<br/>";
         }
         
         if( !$b ) {
            echo "TEST8 : b is true <br/>";
         }else {
            echo "TEST8 : b  is false<br/>";
         }
      ?>
      
   </body>
</html>
This will produce the following result −
TEST1 : Either a or b is false
TEST2 : Either a or b is false
TEST3 : Either a or b is true
TEST4 : Either a or b is true
TEST5 : a is true 
TEST6 : b is true 
TEST7 : a is false
TEST8 : b is false