code-rag-bench/online-tutorials huggingface dataset:
Android - Environment Setup

You will be glad to know that you can start your Android application development on either of the following operating systems −
Microsoft Windows XP or later version.
Microsoft Windows XP or later version.
Mac OS X 10.5.8 or later version with Intel chip.
Mac OS X 10.5.8 or later version with Intel chip.
Linux including GNU C Library 2.7 or later.
Linux including GNU C Library 2.7 or later.
Second point is that all the required tools to develop Android applications are freely available and can be downloaded from the Web. Following is the list of software's you will need before you start your Android application programming.
Java JDK5 or later version
Java JDK5 or later version
Android Studio 
Android Studio 
Here last two components are optional and if you are working on Windows machine then these components make your life easy while doing Java based application development. So let us have a look how to proceed to set required environment.
You can download the latest version of Java JDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the JDK in C:\jdk1.8.0_102, you would have to put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.8.0_102\bin;%PATH%
set JAVA_HOME=C:\jdk1.8.0_102

Alternatively, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.
On Linux, if the SDK is installed in /usr/local/jdk1.8.0_102 and you use the C shell, you would put the following code into your .cshrc file.
setenv PATH /usr/local/jdk1.8.0_102/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.8.0_102

Alternatively, if you use Android studio, then it will know automatically where you have installed your Java.
There are so many sophisticated Technologies are available to develop android applications, the familiar technologies, which are predominantly using tools as follows
Android Studio
Android Studio
Eclipse IDE(Deprecated)
Eclipse IDE(Deprecated)

    46 Lectures 
     7.5 hours 

 Aditya Dua

    32 Lectures 
     3.5 hours 

 Sharad Kumar

    9 Lectures 
     1 hours 

 Abhilash Nelson

    14 Lectures 
     1.5 hours 

 Abhilash Nelson

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    10 Lectures 
     1 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Draw Clock Design using Turtle in Python

26 Jul, 2021
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc.
Following steps are used :
Import turtle.
Create Screen object and set Screen configuration.
Create Turtle object and set its position and speed.
Draw a dashed line and print number in circular shape.
Draw center and fill color black in it
Write “GFG” and “CLOCK” at required position.
Below is the implementation:
Python3
# import packageimport turtle # create a Screen Objectscreen = turtle.Screen() # Screen configurationscreen.setup(500, 500) # Make turtle Objectclk = turtle.Turtle() # set a Turtle object colorclk.color('Green') # set a Turtle object widthclk.width(4)  def draw_hour_hand():    clk.penup()    clk.home()    clk.right(90)    clk.pendown()    clk.forward(100)  # value for numbers in clockval = 0 # loop for print clock numbersfor i in range(12):    # increment value by 1    val += 1     # move turtle in air    clk.penup()     # for circular motion    clk.setheading(-30 * (i + 3) + 75)     # move forward for space    clk.forward(22)     # move turtle to surface    clk.pendown()     # move forward for dash line    clk.forward(15)     # move turtle in air    clk.penup()     # move forward for space    clk.forward(20)     # write clock integer    clk.write(str(val), align="center",              font=("Arial",                    12, "normal")) # colored centre by setting position# sets position of turtle at given positionclk.setpos(2, -112)clk.pendown()clk.width(2) # To fill color greenclk.fillcolor('Green') # start fillingclk.begin_fill() # make a circle of radius 5clk.circle(5) # end fillingclk.end_fill() clk.penup()draw_hour_hand()clk.setpos(-20, -64)clk.pendown()clk.penup() # Write Clock by setting positionclk.setpos(-30, -170)clk.pendown()clk.write(' GfG Clock', font=("Arial", 14,                              "normal"))clk.hideturtle()turtle.done()
Output: 
 
pulkitagarwal03pulkit
anikakapoor
Python-projects
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Python | os.path.join() method
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Nested Dictionary to Multiindex Dataframe

24 Feb, 2021
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame consists of three principal components, the data, rows, and columns. A Multiindex Dataframe is a pandas dataframe having multi-level indexing or hierarchical indexing.
Pandas needs multi-index values as tuples, not as a nested dictionary. So, first, we need to convert the nested index values into tuples.
Example #1:
Python3
# Import moduleimport pandas as pd  # Nested dictionary to convert it# into multiindex dataframenested_dict = {'A': {'a': [1, 2, 3,                           4, 5],                     'b': [6, 7, 8,                           9, 10]},                 'B': {'a': [11, 12, 13,                           14, 15],                     'b': [16, 17, 18,                           19, 20]}}  reformed_dict = {}for outerKey, innerDict in nested_dict.items():    for innerKey, values in innerDict.items():        reformed_dict[(outerKey,                       innerKey)] = values  # Multiindex dataframereformed_dict
Output:
Notice that in the reformed_dict, index values are in the tuple. Now to convert reformed_dict into multiindex dataframe, we can use pd.DataFrame() method.
Python3
multiIndex_df = pd.DataFrame(reformed_dict)multiIndex_df
Output:
Here in the output, we can see the hierarchical index/ multi index for the column.
Example #2:
Python3
# Import moduleimport pandas as pd  # Nested dictionary to convert it into multiindex dataframenested_dict = {'India': {'State': ['Maharashtra', 'West Bengal',                                   'Uttar Pradesh', 'Bihar', 'Karnataka'],                         'Capital': ['Mumbai', 'Kolkata', 'Lucknow',                                     'Patna', 'Bengaluru']},                 'America': {'State': ['California', 'Florida', 'Georgia',                                     'Massachusetts', 'New York'],                           'Capital': ['Sacramento', 'Tallahassee', 'Atlanta',                                       'Boston', 'Albany']}}  reformed_dict = {}for outerKey, innerDict in nested_dict.items():    for innerKey, values in innerDict.items():        reformed_dict[(outerKey, innerKey)] = values  # Display multiindex dataframemultiIndex_df = pd.DataFrame(reformed_dict)multiIndex_df
Output:
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
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
Python | os.path.join() method
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 | Get unique values from a list
Python | datetime.timedelta() function
Python – Add Space between Potential Words

01 Sep, 2021
Given list of Strings, task is to add a space before sequence which begin with capital letters.
Input : test_list = [“gfgBest”, “forGeeks”, “andComputerScienceStudents”] Output : [‘gfg Best’, ‘for Geeks’, ‘and Computer Science Students’] Explanation : Words segregated by Capitals.
Input : test_list = [“ComputerScienceStudentsLoveGfg”] Output : [‘Computer Science Students Love Gfg’] Explanation : Words segregated by Capitals.  
Method #1 : Using loop + join()
 This is one of the ways in which this task can be performed. In this, we perform the task of iterating all the stings and then all the characters before adding space using loop in brute force manner. The isupper() is used to check for capital character.
Python3
# Python3 code to demonstrate working of# Add Space between Potential Words# Using loop + join() # initializing listtest_list = ["gfgBest", "forGeeks", "andComputerScience"] # printing original listprint("The original list : " + str(test_list)) res = [] # loop to iterate all stringsfor ele in test_list:    temp = [[]]    for char in ele:                 # checking for upper case character        if char.isupper():            temp.append([])                     # appending character at latest list        temp[-1].append(char)         # joining lists after adding space    res.append(' '.join(''.join(ele) for ele in temp)) # printing resultprint("The space added list of strings : " + str(res))
The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
The space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science']
Method #2 : Using regex() + list comprehension
The combination of above functions can also be used to solve this problem. In this we employ regex code to check for upper case letters and perform space addition and joining using list comprehension.
Python3
# Python3 code to demonstrate working of# Add Space between Potential Words# Using regex() + list comprehensionimport re # initializing listtest_list = ["gfgBest", "forGeeks", "andComputerScience"] # printing original listprint("The original list : " + str(test_list)) # using regex() to perform taskres = [re.sub(r"(\w)([A-Z])", r"\1 \2", ele) for ele in test_list] # printing resultprint("The space added list of strings : " + str(res))
The original list : ['gfgBest', 'forGeeks', 'andComputerScience']
The space added list of strings : ['gfg Best', 'for Geeks', 'and Computer Science']
sweetyty
Python list-programs
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
try and except in Python

To use exception handling in python, we first need to catch the all except clauses.
Python provides, “try” and “except” keywords to catch exceptions. The “try” block code will be executed statement by statement. However, if an exception occurs, the remaining “try” code will not be executed and the except clause will be executed.
try:
   some_statements_here
except:
   exception_handling
Let’s see above syntax with a very simple example −
 Live Demo
try:
   print("Hello, World!")
except:
   print("This is an error message!")
Hello, World!
Above is a very simple example, let’s understand the above concept with another example −
 Live Demo
import sys
List = ['abc', 0, 2, 4]
for item in List:
   try:
      print("The List Item is", item)
      r = 1/int(item)
      break
   except:
   print("Oops!",sys.exc_info()[0],"occured.")
   print('\n')
   print("Next Item from the List is: ")
   print()
print("The reciprocal of",item,"is",r)
The List Item is abc
Oops! <class 'ValueError'> occured.
Next Item from the List is:
The List Item is 0
Oops! <class 'ZeroDivisionError'> occured.
Next Item from the List is:
The List Item is 2
The reciprocal of 2 is 0.5
In the above program, the loops run until we get (as user input) an integer that has a valid reciprocal. The code which causes an exception to raise is placed within the try block.
In case some exception occurs, it will be caught by the except block. We can test the above program with different exception errors. Below are some of the common exception errors −
IOErrorRaised in case we cannot open the file.
IOError
Raised in case we cannot open the file.
ImportErrorRaised in case module is missing.
ImportError
Raised in case module is missing.
ValueErrorIt happened whenever we pass the argument with the correct type but an inappropriate value of a built-in operator or function.
ValueError
It happened whenever we pass the argument with the correct type but an inappropriate value of a built-in operator or function.
KeyboardInterruptWhenever the user hits the interrupt key (generally control-c)
KeyboardInterrupt
Whenever the user hits the interrupt key (generally control-c)
EOFErrorException raised when the built-in functions hit an end-of-file condition (EOF) without reading any data.
EOFError
Exception raised when the built-in functions hit an end-of-file condition (EOF) without reading any data.
Saving a Pandas Dataframe as a CSV

21 Aug, 2020
Pandas is an open source library which is built on top of NumPy library. It allows user for fast analysis, data cleaning & preparation of data efficiently. Pandas is fast and it has high-performance & productivity for users.
Most of the datasets you work with are called DataFrames. DataFrames is a 2-Dimensional labeled Data Structure with index for rows and columns, where each cell is used to store a value of any type. Basically, DataFrames are Dictionary based out of NumPy Arrays.
Let’s see how to save a Pandas DataFrame as a CSV file using to_csv() method.
Example #1: Save csv to working directory.
# importing pandas as pd import pandas as pd    # list of name, degree, scorenme = ["aparna", "pankaj", "sudhir", "Geeku"]deg = ["MBA", "BCA", "M.Tech", "MBA"]scr = [90, 40, 80, 98]   # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr}      df = pd.DataFrame(dict)  # saving the dataframedf.to_csv('file1.csv')
Output: Example #2: Saving CSV without headers and index.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
# importing pandas as pd import pandas as pd    # list of name, degree, scorenme = ["aparna", "pankaj", "sudhir", "Geeku"]deg = ["MBA", "BCA", "M.Tech", "MBA"]scr = [90, 40, 80, 98]   # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr}      df = pd.DataFrame(dict)  # saving the dataframedf.to_csv('file2.csv', header=False, index=False)
Output: Example #3: Save csv file to a specified location.
# importing pandas as pd import pandas as pd    # list of name, degree, scorenme = ["aparna", "pankaj", "sudhir", "Geeku"]deg = ["MBA", "BCA", "M.Tech", "MBA"]scr = [90, 40, 80, 98]   # dictionary of lists dict = {'name': nme, 'degree': deg, 'score': scr}      df = pd.DataFrame(dict)  # saving the dataframedf.to_csv(r'C:\Users\Admin\Desktop\file3.csv', index=False)
Output:
Example #4: Write a DataFrame to CSV file using tab separator.
import pandas as pdimport numpy as npusers = {'Name': ['Amit', 'Cody', 'Drew'],     'Age': [20,21,25]}df = pd.DataFrame(users, columns=['Name','Age'])#create DataFrameprint("Original DataFrame:")print(df)print('Data from Users.csv:')df.to_csv('Users.csv', sep='\t', index=False,header=True)new_df = pd.read_csv('Users.csv')print(new_df)
Output:
Original DataFrame:
   Name  Age
0  Amit   20
1  Cody   21
2  Drew   25
Data from Users.csv:
  Name\tAge
0  Amit\t20
1  Cody\t21
2  Drew\t25

gauravbabbar25
Picked
Python pandas-basics
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Enumerate() in Python
Rotate axis tick labels in Seaborn and Matplotlib
Python Dictionary
Deque in Python
Stack in Python
Queue in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Python String Title method

02 Dec, 2020
The title() function in python is the Python String Method which is used to convert the first character in each word to Uppercase and remaining characters to Lowercase in the string and returns a new string. 
Syntax: 
str.title()
parameters:str is a valid string which we need to convert.
return: This function returns a string which 
has first letter in each word is uppercase and all 
remaining letters are lowercase.
 
Python
# Python title() Method Example  str1 = 'geeKs foR geEks'str2 = str1.title()print 'First Output after Title() method is = ', str2 # observe the original stringprint 'Converted String is = ', str1.title()print 'Original String is = ', str1  # Performing title() function directlystr3 = 'ASIPU pawan kuMAr'.title()print 'Second Output after Title() method is = ', str3  str4 = 'stutya kUMari sHAW'.title()print 'Third Output after Title() method is = ', str4  str5 = '6041'.title()print 'Fourth Output after Title() method is = ', str5
Output:  
First Output after title() method is =  Geeks For Geeks
Converted String is =  Geeks For Geeks
Original String is =  geeKs foR geEks
Second Output after title() method is =  Asipu Pawan Kumar
Third Output after title() method is =  Stutya Kumari Shaw
Fourth Output after title() method is =  6041
 
preyash2047
Python-Built-in-functions
Python-Library
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
CSS | :target Selector

21 Dec, 2018
The target selector is used to represent a unique element (the target element) with an id matching the URL’s fragment. It can be used to style the current active target element. URLs with a # followed by an anchor name link to a certain element within a document. The element being linked to is the target element.
Syntax:
:target {
    // CSS Property
} 

Example 1:
<!DOCTYPE html><html>    <head>        <title>CSS | :target Selector</title>        <style>                      /* CSS property of target selector */            :target {                border: 2px solid #D4D4D4;                background-color: green;                color: white;                padding: 10px;                font-size: 20px;            }        </style>    </head>          <body style = "text-align:center">        <h2>            :target selector        </h2>          <p>            <a href="#geek">                Jump to Algorithms            </a>        </p>                  <p id="geek">            <b>Algorithms</b>        </p>    </body></html>                    
Output:Before Click on the link:
After Click on the link:
Example 2:
<!DOCTYPE html><html>    <head>        <title>:target Selector</title>        <style>            .tab div {                display: none;            }            .tab div:target {                display: block;                color: white;                background: green;                padding: 5px;                margin: 20px 5px;            }        </style>    </head>          <body style = "text-align:center">                  <h2>            :target selector        </h2>        <div class = "tab">            <a href = "#geek">Geeks Classes</a>             <div id = "geek">                <h3>Welcome to Geeks Classes.</h3>                <p>Hello World!</p>            </div>        </div>    </body></html>                    
Output:Before Click on the link:
After Click on the link:
Supported Browsers: The browser supported by :target Selector are listed below:
Apple Safari 3.2
Google Chrome 4.0
Firefox 3.5
Opera 9.6
Internet Explorer 9.0
CSS-Selectors
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SUBSTRING() function in MySQL

22 Sep, 2020
SUBSTRING() :function in MySQL is used to derive substring from any given string .It extracts a string with a specified length, starting from a given location in an input string. The purpose of substring is to return a specific portion of the string.
Syntax :
SUBSTRING(string, start, length)
OR
SUBSTRING(string FROM start FOR length)

Parameters :This method accepts three-parameter as mentioned above and described below.
string –Input String from which to extract.
start –The starting position. If it is a positive number, this function extracts from the beginning of the string. If it is a negative number, this function extracts from the end of the string.
length –It is optional. It identifies the number of characters to extract. If it is not given The whole string is returned from the starting position.
Example-1 :Deriving substring from a given string without giving length parameter.
SELECT SUBSTRING("GeeksForGeeks", 3) AS Sub_String;

Output :
Example-2 :Deriving substring from a given string when length parameter is given.
SELECT SUBSTRING("GeeksForGeeks", 3, 8) AS Sub_String; 

Output :
Example-3 :Deriving substring from a given string when starting position is -ve, i.e: starting from end.
 
SELECT SUBSTRING("GeeksForGeeks", -3 ) AS Sub_String; 

Output :
Example-4 :Extracting all substring from the text column in a Table.
Table : Student_Details
SELECT SUBSTRING( Student_Name, 2 ) AS Sub_String FROM Student_Details ;

Output :
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
What is Temporary Table in SQL?
SQL using Python
SQL Query to Convert VARCHAR to INT
SQL Query to Convert Rows to Columns in SQL Server
SQL | DROP, TRUNCATE
Introduction to NoSQL
Groovy - any() & every()

Method any iterates through each element of a collection checking whether a Boolean predicate is valid for at least one element.
boolean any(Closure closure) 
boolean every(Closure closure)

The condition to be met by the collection element is specified in the closure that must be some Boolean expression.
The find method returns a Boolean value.
Following is an example of the usage of this method −
class Example {
   static void main(String[] args) {
      def lst = [1,2,3,4];
      def value;
		
      // Is there any value above 2
      value = lst.any{element -> element > 2}
      println(value);
		
      // Is there any value above 4
      value = lst.any{element -> element > 4}
      println(value); 
   } 
}
When we run the above program, we will get the following result −
true 
false

Following is an example of the usage of this method of the every method −
class Example {
   static void main(String[] args) {
      def lst = [1,2,3,4];
      def value;
		
      // Are all value above 2
      value = lst.every{element -> element > 2}
      println(value);
		
      // Are all value above 4 
      value = lst.every{element -> element > 4}
      println(value);  
      def largelst = [4,5,6];
		
      // Are all value above 2
      value = largelst.every{element -> element > 2}
      println(value);
   } 
}
When we run the above program, we will get the following result −
PyQt5 – checkState() method for Check Box

22 Apr, 2020
There are basically two states in check box that are checked or unchecked, although using setTristate method we can add an intermediate state.
checkState method is used to check the state of the check box, it returns CheckState object but when we print it output will be as follows:
0 for un-checked state
2 for checked state
1 for intermediate state
Syntax : checkbox.checkState()
Argument : It takes no argument.
Return : It returns CheckState object
Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating the check-box        checkbox = QCheckBox('Geek ?', self)          # setting geometry of check box        checkbox.setGeometry(200, 150, 100, 40)          # getting the checked state        check = checkbox.checkState()          # printing the state        print("Before check status : ", check)          # checking the check box        checkbox.setChecked(True)          # getting the checked state        check = checkbox.checkState()          # printing the state        print("After check status : ", check)          # exiting the program        sys.exit()      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Before check status :  0
After check status :  2
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON
Matrix Multiplication in NumPy

02 Sep, 2020
Let us see how to compute matrix multiplication with NumPy. We will be using the numpy.dot() method to find the product of 2 matrices.
For example, for two matrices A and B.
A = [[1, 2], [2, 3]]
B = [[4, 5], [6, 7]]

So, A.B = [[1*4 + 2*6, 2*4 + 3*6], [1*5 + 2*7, 2*5 + 3*7]
So the computed answer will be: [[16, 26], [19, 31]]

In Python numpy.dot() method is used to calculate the dot product between two arrays.
Example 1 : Matrix multiplication of 2 square matrices.
# importing the moduleimport numpy as np  # creating two matricesp = [[1, 2], [2, 3]]q = [[4, 5], [6, 7]]print("Matrix p :")print(p)print("Matrix q :")print(q)  # computing productresult = np.dot(p, q)  # printing the resultprint("The matrix multiplication is :")print(result)
Output :
Matrix p :
[[1, 2], [2, 3]]
Matrix q :
[[4, 5], [6, 7]]
The matrix multiplication is :
[[16 19]
 [26 31]]

Example 2 : Matrix multiplication of 2 rectangular matrices.
# importing the moduleimport numpy as np  # creating two matricesp = [[1, 2], [2, 3], [4, 5]]q = [[4, 5, 1], [6, 7, 2]]print("Matrix p :")print(p)print("Matrix q :")print(q)  # computing productresult = np.dot(p, q)  # printing the resultprint("The matrix multiplication is :")print(result)
Output :
Matrix p :
[[1, 2], [2, 3], [4, 5]]
Matrix q :
[[4, 5, 1], [6, 7, 2]]
The matrix multiplication is :
[[16 19  5]
 [26 31  8]
 [46 55 14]]

Python numpy-Mathematical Function
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 | os.path.join() method
Introduction To PYTHON
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 | Get unique values from a list
Create a directory in Python
Groovy - replaceAll()

Replaces all occurrences of a captured group by the result of a closure on that text.
void replaceAll(String regex, String replacement)

regex − the regular expression to which this string is to be matched.
regex − the regular expression to which this string is to be matched.
replacement − the string which would replace found expression.
replacement − the string which would replace found expression.
This method returns the resulting String.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      String a = "Hello World Hello"; 
      println(a.replaceAll("Hello","Bye")); 
      println(a.replaceAll("World","Hello"));     
   } 
}
When we run the above program, we will get the following result −
Bye World Bye 
Hello Hello Hello


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Check if values of two arrays are the same/equal in JavaScript

We have two arrays of numbers, let’s say −
[2, 4, 6, 7, 1]
[4, 1, 7, 6, 2]
Assume, we have to write a function that returns a boolean based on the fact whether or not
they contain the same elements irrespective of their order.
For example −
[2, 4, 6, 7, 1] and [4, 1, 7, 6, 2] should yield true because they have the same elements but
ordered differently.
Now, let’s write the code for this function −
const first = [2, 4, 6, 7, 1];
const second = [4, 1, 7, 6, 2];
const areEqual = (first, second) => {
   if(first.length !== second.length){
      return false;
   };
   for(let i = 0; i < first.length; i++){
      if(!second.includes(first[i])){
         return false;
      };
   };
   return true;
};
console.log(areEqual(first, second));
The output in the console will be −
true
Print all Subsequences of String which Start with Vowel and End with Consonant in C++

In this problem, we are given a string and we have to find the substring from the given string. The substring to be found should start with a vowel and end with constant character.
A string is an array of characters.
The substring that is to be generated in this problem can be generated by deleting some characters of the string. And without changing the order of the string.
Input: ‘abc’
Output: ab, ac, abc
To solve this problem, we will iterate the string and fix vowels and check for the next sequence. Let’s see an algorithm to find a solution −
Step 1: Iterate of each character of the string, with variable i.
Step 2: If the ith character is a vowel.
Step 3: If the jth character is a consonant.
Step 4: Add to the HashSet, substring from 1st character to jth character.
Step 5: Repeat the following steps and find substrings from the string.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
set<string> st;
bool isaVowel(char c);
bool isaConsonant(char c);
void findSubSequence(string str);
int main(){
   string s = "abekns";
   findSubSequence(s);
   cout<<"The substring generated are :\n";
   for (auto i : st)
      cout<<i<<" ";
   cout << endl;
   return 0;
}
bool isaVowel(char c) {
   return (c=='a'||c=='e'||c=='i'||c=='o'||c=='u');
}
bool isaConsonant(char c) {
   return !isaVowel(c);
}
void findSubSequence(string str) {
   for (int i = 0; i < str.length(); i++) {
      if (isaVowel(str[i])) {
         for (int j = str.length() - 1; j >= i; j--) {
            if (isaConsonant(str[j])) {
               string str_sub = str.substr(i, j + 1);
               st.insert(str_sub);
               for (int k = 1; k < str_sub.length() - 1; k++){
                  string sb = str_sub;
                  sb.erase(sb.begin() + k);
                  findSubSequence(sb);
               }
            }
         }
      }
   }
}
The substring generated are −
ab abek abekn abekns abeks aben abens abes abk abkn abkns abks abn abns abs aek aekn aekns aeks aen aens aes ak akn akns aks an ans as ek ekn ekns eks en ens es
How to plot two histograms together in R?

Consider the below data frames −
> glucose  <- data.frame(length = rnorm(100, 2.5))
> fructose <- data.frame(length = rnorm(500, 2.5))
We need to combine these two data frames but before that we have to make a new
column in each of these data frames to create their identification
> glucose$sweetener  <- 'glucose'
> fructose$sweetener <- 'fructose'
> sweeteners <- rbind(glucose, fructose)
Now let’s create the histograms
> library(ggplot2)
> ggplot(sweeteners, aes(length, fill = sweetener)) + geom_density(alpha = 0.2)
bar() function in C graphics

bar() function is a C graphics function that is used to draw graphics in the C programming language. The graphics.h header contains functions that work for drawing graphics. The bar() function is also defined in the header file.
void bar(int left, int top, int right, int bottom );
The bar() function is used to draw a bar ( of bar graph) which is a 2-dimensional figure. It is filled rectangular figure. The function takes four arguments that are the coordinates of (X, Y) coordinates of the top-left corner of the bar {left and top } and (X, Y) coordinates of the bottom-right corner of the bar {right and bottom}.
#include <graphics.h>
#include <conio.h>

int main() {
   int gd = DETECT, gm;
   initgraph(&gd, &gm, "C:\\TC\\BGI");
   bar(120, 120, 250, 250);
   getch();
   closegraph();
   return 0;
}
How can one modify the outline color of a node in networkx using Matplotlib?

To modify the outline color of a node in networkx, we can use set_edgecolor() method.
Create a Pandas dataframe with from and to keys.
Return a graph from Pandas DataFrame containing an edge list.
Get the position of the nodes.
Draw the nodes of the graph using draw_networkx_nodes().
Set the outline color of the nodes using set_edgecolor().
To display the figure, use show() method.
from networkx import *
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame({'from': ['A', 'B', 'C', 'A'], 'to': ['D', 'A', 'E', 'C']})
G = nx.from_pandas_edgelist(df, 'from', 'to')
pos = spring_layout(G)
nodes = draw_networkx_nodes(G, pos)
nodes.set_edgecolor('red')
plt.show()
How to add shadow to text using CSS ? - GeeksforGeeks

15 Sep, 2020
The approach of this article is to add a shadow using text-shadow property in CSS. This property accepts a list of a comma-separated list of shadows to be applied to the text. The default value of the text-shadow property is “none”.
Syntax:
text-shadow: h-shadow v-shadow blur-radius color|none|initial|
Example:
HTML
<!DOCTYPE html><html>  <head>    <style>        h1 {            text-shadow: 4px 4px green;        }          h2 {            text-shadow: 2px 3px blue;        }    </style></head>  <body style="text-align:center;">    <h1>        GeeksForGeeks    </h1>    <h2>        How to apply shadow effects        to text using CSS?    </h2></body>  </html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Primer CSS Flexbox Flex Direction
HTML Course | First Web Page | Printing Hello World
Design a web page using HTML and CSS
Search Bar using HTML, CSS and JavaScript
How to wrap the text around an image using HTML and CSS ?
How to set input type date in dd-mm-yyyy format using HTML ?
Form validation using HTML and JavaScript
HTML | <img> align Attribute
How to set the default value for an HTML <select> element ?
Python Program for Identity Matrix - GeeksforGeeks

13 Jan, 2022
Introduction to Identity Matrix :
 The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1’s and all other elements are zeros. In the below image, every matrix is an Identity Matrix.  
In linear algebra, this is sometimes called as a Unit Matrix, of a square matrix (size = n x n) with ones on the main diagonal and zeros elsewhere. The identity matrix is denoted by “ I “. Sometimes U or E is also used to denote an Identity Matrix. A property of the identity matrix is that it leaves a matrix unchanged if it is multiplied by an Identity Matrix.
Examples:  
Input  : 2
Output : 1 0
         0 1

Input :  4
Output : 1 0 0 0
         0 1 0 0
         0 0 1 0
         0 0 0 1
The explanation is simple. We need to make all
the elements of principal or main diagonal as 
1 and everything else as 0.
Program to print Identity Matrix : The logic is simple. You need to the print 1 in those positions where row is equal to column of a matrix and make all other positions as 0. 
Python3
# Python code to print identity matrix  # Function to print identity matrixdef Identity(size):    for row in range(0, size):        for col in range(0, size):              # Here end is used to stay in same line            if (row == col):                print("1 ", end=" ")            else:                print("0 ", end=" ")        print()  # Driver Code        size = 5Identity(size)
Output: 
1  0  0  0  0  
0  1  0  0  0  
0  0  1  0  0  
0  0  0  1  0  
0  0  0  0  1  
 Program to check if a given square matrix is Identity Matrix : 
Python3
# Python3 program to check # if a given matrix is identityMAX = 100;def isIdentity(mat, N):    for row in range(N):        for col in range(N):            if (row == col and                 mat[row][col] != 1):                return False;            elif (row != col and                   mat[row][col] != 0):                return False;    return True;  # Driver CodeN = 4;mat = [[1, 0, 0, 0],       [0, 1, 0, 0],       [0, 0, 1, 0],       [0, 0, 0, 1]]; if (isIdentity(mat, N)):    print("Yes ");else:    print("No ");  # This code is contributed# by mits
Output:
Yes
 
Mathematical
Matrix
Python
Python Programs
School Programming
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Program to multiply two matrices
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Sudoku | Backtracking-7
Rat in a Maze | Backtracking-2
What is different between constant and variable in C++?

Variable and constant are two commonly used mathematical concepts. Simply put, a variable is a value that is changing or that have the ability to change. A constant is a value which remains unchanged.
For example, if you have a program that has a list of 10 radii and you want to calculate the area for all of these circles. To find the area of these circles, you'll write a program that will have a variable that will store the value of PI and this value will not change throughout the program. Such values can be declared as a constant.
In the same example, if you're calculating the area in a loop, you can use the same variable to temporarily store the value of the area and print it and then reuse it for some other calculation. The code for the above will look something like −
float area;
const float PI = 3.141;
for(int i = 0; i < 10; i++) {
   area = PI * radii[i] * radii[i]; // Calculate area
   cout << area;  // Print area
}
The value of PI remains same throughout the life of this program.
How do I print a Python datetime in the local timezone?

The easiest way in Python date and time to handle timezones is to use the pytz and tzlocal modules. These libraries allows accurate and cross platform timezone calculations. pytz brings the Olson tz database into Python. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo).
Before you use it you'll need to install it using −
$ pip install pytz tzlocal
You can use the pytz library as follows −
from datetime import datetime
from pytz import timezone
from tzlocal import get_localzone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
# Convert to local time zone
now_local = now_utc.astimezone(get_localzone())
print(now_local.strftime(format))
This will give the output −
2018-01-03 07:05:50 UTC+0000
2018-01-03 12:35:50 IST+0530
Reverse mapping an object in JavaScript

Suppose, we have an object like this −
const products = {
   "Pineapple":38,
   "Apple":110,
   "Pear":109
};
All the keys are unique in themselves and all the values are unique in themselves.
We are required to write a function that accepts a value and returns its key. Let' say we have created a function findKey().
For example, findKey(110) should return "Apple".
We will approach this problem by first reverse mapping the values to keys and then simply using object notations to find their values.
Therefore, let’s write the code for this function −
The code for this will be −
const products = {
   "Pineapple":38,
   "Apple":110,
   "Pear":109
};
const findKey = (obj, val) => {
   const res = {};
   Object.keys(obj).map(key => {
      res[obj[key]] = key;
   });
   // if the value is not present in the object
   // return false
   return res[val] || false;
};
console.log(findKey(products, 110));
The output in the console will be −
Apple
Batch Script - SET

Displays the list of environment variables on the current system.
Set

@echo off 
set
The above command displays the list of environment variables on the current system.
 Print
 Add Notes
 Bookmark this page
How to left align components vertically using BoxLayout with Java?

To align components vertically, use the BoxLayout −
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
Now, create a Panel and add some buttons to it. After that set left alignment of components which are already arranged vertically using Component.LEFT_ALIGNMENT constant −
JPanel panel = new JPanel();
JButton btn1 = new JButton("One");
JButton btn2 = new JButton("Two");
JButton btn3 = new JButton("Three");
JButton btn4 = new JButton("Four");
JButton btn5 = new JButton("Five");
panel.add(btn1);
panel.add(btn2);
panel.add(btn3);
panel.add(btn4);
panel.add(btn5);
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
The following is an example to left align components vertically with BoxLayout −
package my;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
      JPanel panel = new JPanel();
      JButton btn1 = new JButton("One");
      JButton btn2 = new JButton("Two");
      JButton btn3 = new JButton("Three");
      JButton btn4 = new JButton("Four");
      JButton btn5 = new JButton("Five");
      panel.add(btn1);
      panel.add(btn2);
      panel.add(btn3);
      panel.add(btn4);
      panel.add(btn5);
      panel.setAlignmentX(Component.LEFT_ALIGNMENT);
      panel.setPreferredSize(new Dimension(100, 500));
      panel.setMaximumSize(new Dimension(100, 500));
      panel.setBorder(BorderFactory.createTitledBorder("demo"));
      frame.getContentPane().add(panel);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}
grubby - Unix, Linux Command

On Intel x86 platforms, grub is the default bootloader and the
configuration file is in /boot/grub/grub.conf. On Intel ia64 platforms,
elilo mode is used and the default location for the configuration file
is /boot/grub/grub.conf. On PowerPC platforms, yaboot parsing
is used and the configuration file should be in /etc/yaboot.conf.


There are a number of ways to specify the kernel used for --info,
--remove-kernel, and --update-kernel. Specificying DEFAULT
or ALL selects the default entry and all of the entries, respectively.
If a comma separated list of numbers is given, the boot entries indexed
by those numbers are selected. Finally, the title of a boot entry may
be specified by using TITLE=title as the argument; all entries
with that title are used.































































grub (8)
grub (8)
lilo (8)
lilo (8)
yaboot (8)
yaboot (8)
mkinitrd (8)
mkinitrd (8)
Erik Troan <ewt@redhat.com>
Jeremy Katz <katzj@redhat.com>


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
Groovy - find()

The find method finds the first value in a collection that matches some criterion.
Object find(Closure closure)

The condition to be met by the collection element is specified in the closure that must be some Boolean expression.
Return Value − The find method returns the first value found or null if no such element exists.
Following is an example of the usage of this method −
class Example {
   static void main(String[] args) {
      def lst = [1,2,3,4];
      def value;
		
      value = lst.find {element -> element > 2}
      println(value);
   } 
}
When we run the above program, we will get the following result −
3


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
How to install requests in Python – For windows, linux, mac

06 Oct, 2021
Requests is an elegant and simple HTTP library for Python, built for human beings. One of the most famous libraries for python used by developers al over the world. This article revolves around how one can install requests library of python in Windows/ Linux/ macOS, etc.
For installing requests in windows, one would require Python (preferably latest version), so if you don’t have python installed, head to – How to download and install Python Latest Version on Windows. Now open command prompt from the windows and run following command –
python -m pip install requests
Booom..!! Done Now, requests library is downloaded successfully.
For installing requests in linux, one would require Python (preferably latest version) and pip latest version, so if you don’t have python installed, head to – How to download and install Python Latest Version on Linux. To install pip in linux – How to install PIP in Linux?. Now run,
pip install requests
For installing requests in mac, one would require Python (preferably latest version) and pip latest version, so if you don’t have python installed, head to – How to download and install Python Latest Version on mac. To install pip mac Os. Run,
sudo easy_install pip
sudo pip install --upgrade pip 
Now to install requests,
pip install requests
THe last method for installation of requests on any operating system is to grab the base files and install requests manually and Requests is actively developed on GitHub, where the code is always available. For code – visit here.You can either clone the public repository:
git clone git://github.com/psf/requests.git
Or, download the tarball:
curl -OL https://github.com/psf/requests/tarball/master
# optionally, zipball is also available (for Windows users).
Once you have a copy of the source, you can embed it in your own Python package, or install it into your site-packages easily:
cd requests
pip install .
For documentation of requests library – visit here
how-to-install
Python-requests
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.