code-rag-bench/online-tutorials huggingface dataset:
Introduction to PySimpleGUI

10 May, 2020
It is easy to use with simple yet HIGHLY customizable features of GUI for Python. It is based solely on Tkinter. It is a Python GUI For Humans that Transforms Tkinter, PyQt, Remi, WxPython into portable user-friendly Pythonic interfaces.
The Steps for using the GUI package PySimpleGUI are:-
Install PySimpleGUI
pip install PySimpleGUI 
Find a GUI that looks a lot similar to which you want to design and create.
Copy code from Cookbook.
Paste into your IDE and run.
Example: Sample Program to showcase PySimpleGUI layout.
import PySimpleGUI as sg         sg.theme('BluePurple')   layout = [[sg.Text('Your typed characters appear here:'),           sg.Text(size=(15,1), key='-OUTPUT-')],          [sg.Input(key='-IN-')],          [sg.Button('Display'), sg.Button('Exit')]]  window = sg.Window('Introduction', layout)  while True:    event, values = window.read()    print(event, values)          if event in  (None, 'Exit'):        break          if event == 'Display':        # Update the "output" text element        # to be the value of "input" element        window['-OUTPUT-'].update(values['-IN-'])  window.close()
Output:
Python-gui
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
Enumerate() in Python
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
Iterate over a list in Python
Python OOPs Concepts
Python 3 - IF...ELIF...ELSE Statements

An else statement can be combined with an if statement. An else statement contains a block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at the most only one else statement following if.
The syntax of the if...else statement is −
if expression:
   statement(s)

else:
   statement(s)

#!/usr/bin/python3

amount = int(input("Enter amount: "))

if amount<1000:
   discount = amount*0.05
   print ("Discount",discount)
else:
   discount = amount*0.10
   print ("Discount",discount)
    
print ("Net payable:",amount-discount)
In the above example, discount is calculated on the input amount. Rate of discount is 5%, if the amount is less than 1000, and 10% if it is above 10000. When the above code is executed, it produces the following result −
Enter amount: 600
Discount 30.0
Net payable: 570.0

Enter amount: 1200
Discount 120.0
Net payable: 1080.0

The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at the most one statement, there can be an arbitrary number of elif statements following an if.
if expression1:
   statement(s)
elif expression2:
   statement(s)
elif expression3:
   statement(s)
else:
   statement(s)

Core Python does not provide switch or case statements as in other languages, but we can use if..elif...statements to simulate switch case as follows −
#!/usr/bin/python3

amount = int(input("Enter amount: "))

if amount<1000:
   discount = amount*0.05
   print ("Discount",discount)
elif amount<5000:
   discount = amount*0.10
   print ("Discount",discount)
else:
   discount = amount*0.15
   print ("Discount",discount)
    
print ("Net payable:",amount-discount)
When the above code is executed, it produces the following result −
Enter amount: 600
Discount 30.0
Net payable: 570.0

Enter amount: 3000
Discount 300.0
Net payable: 2700.0

Enter amount: 6000
Discount 900.0
Net payable: 5100.0
Python | time.clock_settime() method

17 Sep, 2019
time.clock_settime() method of Time module is used to set the time (in seconds) of the specified clock clk_id. Basically, clk_id is a integer value which represents the id of the clock.
Syntax: time.clock_settime(clk_id, seconds)
Parameters:clk_id: A clk_id constant or an integer value representing clk_id of the clock.
Return type: This method does not return any value.
Code: Use of time.clock_settime() method
# Python program to explain time.clock_settime() method  # importing time moduleimport time    # clk_id for System-wide real-time clockclk_id = time.CLOCK_REALTIME    # Get the current value of# system-wide real-time clock (in seconds)# using time.clock_gettime() methodt = time.clock_gettime(clk_id)   print("Current value of system-wide real-time clock: % d seconds" % t)  # Set the new value of# time (in seconds) for# System-wide real-time clock# using time.clock_settime() methodseconds = 10000000time.clock_settime(clk_id, seconds)  print("\nTime  modified")    # Get the modified value of# system-wide real-time clock (in seconds)# using time.clock_gettime() methodt = time.clock_gettime(clk_id) print("\nCurrent value of system-wide real-time clock: % d seconds" % t)
Current value of system-wide real-time clock: 1568589568 seconds

Time  modified

Current value of system-wide real-time clock: 10000000 seconds

Reference: https://docs.python.org/3/library/time.html#time.clock_settime
python-utility
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
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Get timestamp date range with MySQL Select?

To select timestamp data range, use the below syntax −
SELECT *FROM yourTableName
where yourDataTimeField >= anyDateRange
and yourDataTimeField < anyDateRange
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table DateRange
   −> (
   −> DueTime timestamp
   −> );
Query OK, 0 rows affected (1.34 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into DateRange values('2016-11-13');
Query OK, 1 row affected (0.51 sec)

mysql> insert into DateRange values('2016-10-14');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DateRange values('2017-01-23');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DateRange values('2017-05-14');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DateRange values('2017-08-25');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DateRange values('2018-09-28');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DateRange values('2018-11-17');
Query OK, 1 row affected (0.47 sec)

mysql> insert into DateRange values('2018-12-13');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DateRange values('2018-12-16');
Query OK, 1 row affected (0.27 sec)
Display all records from the table using select command. The query is as follows −
mysql> select *from DateRange;
The following is the output −
+---------------------+
| DueTime             |
+---------------------+
| 2016-11-13 00:00:00 |
| 2016-10-14 00:00:00 |
| 2017-01-23 00:00:00 |
| 2017-05-14 00:00:00 |
| 2017-08-25 00:00:00 |
| 2018-09-28 00:00:00 |
| 2018-11-17 00:00:00 |
| 2018-12-13 00:00:00 |
| 2018-12-16 00:00:00 |
+---------------------+
9 rows in set (0.00 sec)
To select timestamp date range, use the following query −
mysql> select *from DateRange
   −> where DueTime >= '2017-05-14'
   −> and DueTime < '2018-12-17';
The following is the output −
+---------------------+
| DueTime             |
+---------------------+
| 2017-05-14 00:00:00 |
| 2017-08-25 00:00:00 |
| 2018-09-28 00:00:00 |
| 2018-11-17 00:00:00 |
| 2018-12-13 00:00:00 |
| 2018-12-16 00:00:00 |
+---------------------+
6 rows in set (0.00 sec)
Suppose if your timestamp is in unix timestamp, then use the following syntax.
select *from yourTableName
where yourColumnName >= unix_timestamp('anyDateValue’)
and yourColumnName < unix_timestamp('anyDateValue’)
PLSQL | FLOOR Function

19 Feb, 2021
The FLOOR is an inbuilt function in PLSQL which is used to return the largest integer value which will be either equal to or less than from a given input number. 
Syntax:  
FLOOR(number)
Parameters Used: This function accepts a parameter number which is the input number on which FLOOR function is called. 
Return Value: This function returns the largest integer value which will be either equal to or less than from a given input number. 
Supported Versions of Oracle/PLSQL:  
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Let’s see some examples which illustrate the FLOOR function: 
Example-1:  
DECLARE 
   Test_Number number1 := 2.6;
   
BEGIN 
   dbms_output.put_line(FLOOR(Test_Number number1)); 
   
END; 
Output:  
2
In the above example, some parameter is taken. Like 2.6 is taken as the parameter and 2 is returned because 2 is the greatest whole number less than 2.6 
Example-2:  
DECLARE 
   Test_Number number1 := -2.6;
   
BEGIN 
   dbms_output.put_line(FLOOR(Test_Number number1)); 
   
END; 
Output:  
-3
In the above example, some parameter is taken. In the above example, -2.6 is taken as the parameter and -3 is returned because -3 is the greatest whole number less than -2.6 
Advantage: This function is used to find out the largest integer value which will be either equal to or less than from a given input number. 
arorakashish0911
SQL-PL/SQL
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?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
Python VLC MediaPlayer – Getting Media

11 Apr, 2022
In this article we will see how we can get media of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. We can create a MediaPlayer object with the help of MediaPlayer method. Media can be video or even audio that is supported by vlc, it can be set with the help of set_media method.
In order to do this we will use get_media method with the MediaPlayer object 
Syntax : media_player.get_media() 
Argument : It takes no argument 
Return : It returns Media object
Below is the implementation 
Python3
# importing vlc moduleimport vlc # importing time moduleimport time  # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("death_note.mkv") # setting media to the media playermedia_player.set_media(media)  # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting mediavalue = media_player.get_media() # printing mediaprint("Media : ")print(value)
Output : 
Media : 
vlc.Media object at 0x00000254E3CE3408
Another example Below is the implementation 
Python3
# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("1mp4.mkv") # setting media to the media playermedia_player.set_media(media)   # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5) # getting mediavalue = media_player.get_media() # printing mediaprint("Media : ")print(value)
Output : 
Media : 
vlc.Media object at 0x00000254E3CE3A06
simranarora5sos
Python vlc-library
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
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | Pandas dataframe.quantile()

13 Jun, 2022
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.quantile() function return values at the given quantile over requested axis, a numpy.percentile. Note : In each of any set of values of a variate which divide a frequency distribution into equal groups, each containing the same fraction of the total population.
Syntax: DataFrame.quantile(q=0.5, axis=0, numeric_only=True, interpolation=’linear’) 
Parameters : q : float or array-like, default 0.5 (50% quantile). 0 <= q <= 1, the quantile(s) to compute 
axis : [{0, 1, ‘index’, ‘columns’} (default 0)] 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wise 
numeric_only : If False, the quantile of datetime and timedelta data will be computed as well 
interpolation : {‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’} 
Returns : quantiles : Series or DataFrame -> If q is an array, a DataFrame will be returned where the index is q, the columns are the columns of self, and the values are the quantiles. -> If q is a float, a Series will be returned where the index is the columns of self and the values are the quantiles.
Example #1: Use quantile() function to find the value of “.2” quantile 
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[1, 5, 3, 4, 2],                   "B":[3, 2, 4, 3, 4],                   "C":[2, 2, 7, 3, 4],                   "D":[4, 3, 6, 12, 7]}) # Print the dataframedf
 
Let’s use the dataframe.quantile() function to find the quantile of ‘.2’ for each column in the dataframe 
Python3
# find the product over the index axisdf.quantile(.2, axis = 0)
Output :
  
Example #2: Use quantile() function to find the (.1, .25, .5, .75) quantiles along the index axis. 
Python3
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[1, 5, 3, 4, 2],                   "B":[3, 2, 4, 3, 4],                   "C":[2, 2, 7, 3, 4],                   "D":[4, 3, 6, 12, 7]}) # using quantile() function to# find the quantiles over the index axisdf.quantile([.1, .25, .5, .75], axis = 0)
Output :
 
vinayedula
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
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
Enumerate() in Python
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
Iterate over a list in Python
Python OOPs Concepts
PostgreSQL – REGEXP_REPLACE Function

16 Aug, 2021
The PostgreSQL REGEXP_REPLACE() function is used to replaces substrings that match a POSIX regular expression with a new substring.
Syntax: REGEXP_REPLACE(source, pattern, replacement_string, [, flags])
Let’s analyze the above syntax:
The source is a string where the search and replace operation in executed.
The pattern is a POSIX regular expression for matching substrings which is to be replaced.
The replacement_string is a string which replaces the substrings using match the regular expression pattern.
The flags argument is used to control the behaviour of the function for matching characters.
The PostgreSQL REGEXP_REPLACE() function returns the final string after the replacement of the original string with the substring.
Example 1:
For instance imagine you have a name of a person in the following format:
first_name last_name
And you want to rearrange the name as follows:
last_name, first_name
To do this, you can use the REGEXP_REPLACE() function as shown below:
SELECT REGEXP_REPLACE('Raju Kumar', '(.*) (.*)', '\2, \1');
Output:
Example 2:
Suppose you have data in the form of a string. This string is mixed with alphabets and digits as follows:
ABC12345xyz
The following query removes all alphabets e.g., A, B, C, etc from the source string:
SELECT REGEXP_REPLACE('ABC12345xyz', '[[:alpha:]]', '', 'g');
Output:
singghakshay
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Rename Table
PostgreSQL - Joins
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - REPLACE Function
PostgreSQL - Introduction to Stored Procedures
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
GATE | GATE CS 2013 | Question 25 - GeeksforGeeks

28 Jun, 2021
Which of the following statements is/are TRUE for undirected graphs?
P: Number of odd degree vertices is even.
Q: Sum of degrees of all vertices is even. 
(A) P only(B) Q only(C) Both P and Q(D) Neither P nor QAnswer: (C)Explanation: See https://www.geeksforgeeks.org/data-structures-graph-question-27/Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
How to create a bookmark link in HTML?

To create a bookmark link in HTML, you need to create a bookmark using the <a> tag name attribute. Now, add a link to the bookmark. Bookmarks are also known as named anchors. This is quite useful to take readers to a specific section of the web page.
Just keep in mind the <a> tag name attribute deprecated in HTML5. Do not use.
You can try to run the following code to create a bookmark link in HTML.
Live Demo
<html>
   <head>
      <title>HTML Bookmark Link</title>
   </head>
   <body>
      <h1>Tutorials</h1>
      <p>
         <a href="#z">Learn about Scripting Languages</a>
      </p>
      <h2>Programming</h2>
      <p>Here are the tutorials on Programming.</p>
      <h2>Mobile</h2>
      <p>Here are the tutorials on App Development</p>
      <h2>Design</h2>
      <p>Here are the tutorials on Website Designing</p>
      <h2>Databases</h2>
      <p>Here are the tutorials on Databases.</p>
      <h2>Networking</h2>
      <p>Here are the tutorials on Networking</p>
      <h2>Java Technologies</h2>
      <p>Here are the tutorials on Java Technologies.</p>
      <h2>Digital Marketing</h2>
      <p>Here are the tutorials on Digital Marketing.</p>
      <h2>
         <a name="z">Scripting Languages</a>
      </h2>
      <p>Here are the tutorials on Scripting Languages.</p>
   </body>
</html>
How do I get a parent HTML Tag with Selenium WebDriver using Java?

We can get a parent HTML tag with Selenium webdriver. First of all we need to identify the child element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the parent with the findElement(By.xpath()) method.
We can identify the parent from the child, by localizing it with the child and then passing (parent::*) as a parameter to the findElement(By.xpath()). Next to get the tagname of the parent, we have to use the getTagName() method.
child.findElement(By.xpath("parent::*"));
Let us identify tagname of parent of child element li in below html code−
The tagname of the parent should be ul.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class ParentTagname{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement p=driver.findElement(By.xpath("//li[@class='heading']"));
      //identify parent from child element
      WebElement t= p.findElement(By.xpath("parent::*"));
      //getTagName() to get parent element tag
      System.out.println("Parent tagname: " + t.getTagName());
      driver.close();
   }
}
How to create an image gallery with CSS

To create an image gallery with CSS is quite easy. You can try to run the following code to achieve this. A gallery of 3 images is created here,
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         div.myGallery {
            margin: 3px;
            border: 2px solid orange;
            float: left;
            width: 220px;
         }
         div.myGallery:hover {
            border: 1px solid blue;
         }
         div.myGallery img {
            width: 100%;
            height: auto;
         }
         div.desc {
            padding: 20px;
            text-align: center;
         }
      </style>
   </head>
   <body>
      <div class = "myGallery">
         <a target = "_blank" href="https://www.tutorialspoint.com/assets/videotutorials/courses/3d_animation_online_training/380_course_211_image.jpg">
            <img src = "https://www.tutorialspoint.com/assets/videotutorials/courses/3d_animation_online_training/380_course_211_image.jpg" alt="3D Animation Tutorial" width="600" height="500">
         </a>
         <div class = "mydiv">3D Animation Tutorial</div>
      </div>
      <div class = "myGallery">
         <a target="_blank" href="https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg">
            <img src = "https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg" alt="Swift Video Tutorial" width="600" height="500">
         </a>
         <div class = "mydiv">Swift Video Tutorial</div>
      </div>
      <div class = "myGallery">
         <a target = "_blank" href = "https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg">
            <img src = "https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg" alt="CSS Video Tutorial" width="600" height="500">
         </a>
         <div class = "mydiv">CSS Tutorial</div>
      </div>
   </body>
</html>
Python program to find average score of each students from dictionary of scores

Suppose we have a dictionary of students marks. The keys are names and the marks are list of numbers. We have to find the average of each students.
So, if the input is like scores = {'Amal' : [25,36,47,45],'Bimal' : [85,74,69,47],'Tarun' : [65,35,87,14],'Akash' : [74,12,36,75]}, then the output will be [38.25, 68.75, 50.25, 49.25] so 38.25 is average score for Amal, 68.75 is average score for Bimal and so on.
To solve this, we will follow these steps −
avg_scores := a new map
for each name in scores dictionary, doavg_scores[name] := average of scores present in the list scores[name]
avg_scores[name] := average of scores present in the list scores[name]
return list of all values of avg_scores
Let us see the following implementation to get better understanding
def solve(scores):
   avg_scores = dict()
   for name in scores:
      avg_scores[name] = sum(scores[name])/len(scores[name])

return list(avg_scores.values())

scores = {'Amal' : [25,36,47,45],'Bimal' : [85,74,69,47],'Tarun' : [65,35,87,14],'Akash' : [74,12,36,75]}
print(solve(scores))
[['Amal',37],['Bimal',37],['Tarun',36],['Akash',41],['Himadri',39]]
[38, 68, 50, 49]
How to use <jsp:getProperty> action in JSP?

The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.
The getProperty action has only two attributes, both of which are required. The syntax of the getProperty action is as follows −
<jsp:useBean id = "myName" ... />
...
<jsp:getProperty name = "myName" property = "someProperty" .../>
Following table lists out the required attributes associated with the getProperty action −
Let us define a test bean that will further be used in our example −
/* File: TestBean.java */
package action;

public class TestBean {
   private String message = "No message specified";

   public String getMessage() {
      return(message);
   }
   public void setMessage(String message) {
      this.message = message;
   }
}
Compile the above code to the generated TestBean.class file and make sure that you copied the TestBean.class in C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and the CLASSPATH variable should also be set to this folder −
Now use the following code in main.jsp file. This loads the bean and sets/gets a simple String parameter −
<html>
   <head>
      <title>Using JavaBeans in JSP</title>
   </head>
   <body>
      <center>
         <h2>Using JavaBeans in JSP</h2>
         <jsp:useBean id = "test" class = "action.TestBean" />
         <jsp:setProperty name = "test" property = "message" value = "Hello JSP..." />
         <p>Got message....</p>
         <jsp:getProperty name = "test" property = "message" />
      </center>
   </body>
</html>
Let us now try to access main.jsp, it would display the following result −
Got message....
Hello JSP...
Easily Query ORC Data in Python with PySpark | by Holly Emblem | Towards Data Science

Optimized Row Columnar, or ORC, is an column-oriented data storage format, that is part of the Apache Hadoop family. While ORC files and processing them might not be typically within the wheelhouse of a data scientist, there are occasions where you’ll need to pull these files out and handle them using the data munging libraries of your choice.
Recently, I hit a situation where I wanted to process some object data, stored in the ORC format. When reading this out, I was unable to directly write it to a dataframe. I wanted to share some tips on taking data in an ORC format and converting it into something a little more palatable, such as a Pandas dataframe or CSV.
To do so, we’ll utilise Pyspark. If you’re just getting started with Pyspark, there is a great introduction here. For this tutorial, we’ll take a quick walkthrough of the PySpark library and show how we can read in an ORC file, and read it out into Pandas.
We’ll install the PySpark library from within the Terminal
Pip install pyspark
From here, we’ll then pull into two parts of the PySpark library, SparkContext and SQLContext. If you’re new to Spark, then I recommend this tutorial. You can think of the SparkContext as the entry point into all of the Apache Spark services, and the heart of our Spark application. SQLContext is considered the entry point into Spark SQL functionality, and using SQLContext allows you to query Spark data in a familiar, SQL-like way.
from pyspark import SparkContext, SQLContextsc = SparkContext(“local”, “SQL App”)sqlContext = SQLContext(sc)
You can see in the code above we have also declared some details for our SparkContext. In this instance, we say that our code is running locally, and we give it an appName, which we have called ‘SQL App’ in this instance.
Once we have created our SparkContext, known as sc here, we then pass it to our SQLContext class to initialise our SparkSQL.
At this point, we have installed PySpark and created a Spark and SQL Context. Now to the important bit, reading and converting ORC data! Let’s say we have our data stored in the same folder as our python script, and it’s called ‘objectHolder’. To read it into a PySpark dataframe, we simply run the following:
df = sqlContext.read.format(‘orc’).load(‘objectHolder’)
If we then want to convert this dataframe into a Pandas dataframe, we can simply do the following:
pandas_df = df.toPandas()
Putting it all together, our code is as follows:
from pyspark import SparkContext, SQLContextsc = SparkContext(“local”, “SQL App”)sqlContext = SQLContext(sc)df = sqlContext.read.format(‘orc’).load(‘objectHolder’)pandas_df = df.toPandas()
And there we have it. In just a few lines we can read a local orc file and convert it into a format we’re more used to, in this example, a Pandas dataframe.
Apex - For Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Consider a business case wherein, we are required to process or update the 100 records in one go. This is where the Loop syntax helps and makes work easier.
for (variable : list_or_set) { code_block }

Consider that we have an Invoice object which stores information of the daily invoices like CreatedDate, Status, etc. In this example, we will be fetching the invoices created today and have the status as Paid.
Note − Before executing this example, create at least one record in Invoice Object.
// Initializing the custom object records list to store the Invoice Records created today
List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();

// SOQL query which will fetch the invoice records which has been created today
PaidInvoiceNumberList = [SELECT Id,Name, APEX_Status__c FROM APEX_Invoice__c WHERE
   CreatedDate = today];

// List to store the Invoice Number of Paid invoices
List<string> InvoiceNumberList = new List<string>();

// This loop will iterate on the List PaidInvoiceNumberList and will process each record
for (APEX_Invoice__c objInvoice: PaidInvoiceNumberList) {
   
   // Condition to check the current record in context values
   if (objInvoice.APEX_Status__c == 'Paid') {
      
      // current record on which loop is iterating
      System.debug('Value of Current Record on which Loop is iterating is'+objInvoice);
      
      // if Status value is paid then it will the invoice number into List of String
      InvoiceNumberList.add(objInvoice.Name);
   }
}

System.debug('Value of InvoiceNumberList '+InvoiceNumberList);

    14 Lectures 
     2 hours 

 Vijay Thapa

    7 Lectures 
     2 hours 

 Uplatz

    29 Lectures 
     6 hours 

 Ramnarayan Ramakrishnan

    49 Lectures 
     3 hours 

 Ali Saleh Ali

    10 Lectures 
     4 hours 

 Soham Ghosh

    48 Lectures 
     4.5 hours 

 GUHARAJANM
 Print
 Add Notes
 Bookmark this page
“lateinit” Variable in Kotlin

24 Jan, 2022
In Kotlin, there are some tokens that cannot be used as identifiers for naming variables, etc. Such tokens are known as keywords. In simple words, keywords are reserved and have special meaning to the compiler, hence they can’t be used as identifiers. For example,
as
break
class
continue
lateinit
“lateinit” keyword:
The “lateinit” keyword in Kotlin as the name suggests is used to declare those variables that are guaranteed to be initialized in the future.
“lateinit” variable: 
A variable that is declared using “lateinit” keyword is known as “lateinit” variable.
Syntax:
lateinit var myVariable: Int
This article focuses on how to check whether “lateinit” variable is initialized.
In Kotlin 1.2 version some changes were made using which we can check whether “lateinit” variable is initialized with the help of isInitialized method.
Syntax:
myVariable.isInitialized
Return value:
false: If myVariable is not initialized yet
true: If myVariable is initialized
Example 1:
In the below program we have declared “myVariable” using “lateinit” keyword. Before initialization, we have checked whether this variable is initialized using isInitialized method. Later we have initialized it as “GFG”. Now we are checking again whether this variable is initialized.
Kotlin
// Kotlin program to demonstrate how to check// whether lateinit variable is initialized or notclass GFG {          // Declaring a lateinit variable of Int type    lateinit var myVariable: String    fun initializeName() {                    // Check using isInitialized method        println("Is myVariable initialized? " + this::myVariable.isInitialized)                    // initializing myVariable          myVariable = "GFG"                    // Check using isInitialized method          println("Is myVariable initialized? " + this::myVariable.isInitialized)    }}  fun main(args: Array<String>) {          // Calling method    GFG().initializeName()}
Output:
Example 2:
In the below program we have declared “myVariable” using “lateinit” keyword. Before initialization, we have checked whether this variable is initialized using isInitialized method. Later we have initialized it as “GeeksforGeeks”. Now we are checking again whether this variable is initialized.
Kotlin
// Kotlin program to demonstrate how to check// whether lateinit variable is initialized or notclass GFG {          // Declaring a lateinit variable    lateinit var myVariable: String    fun initializeName() {                    // Check using isInitialized method        println("Is myVariable initialized? " + this::myVariable.isInitialized)                    // initializing myVariable          myVariable = "GeeksforGeeks"                     // Check using isInitialized method          println("Is myVariable initialized? " + this::myVariable.isInitialized)    }}  fun main(args: Array<String>) {        // Calling method    GFG().initializeName()}
Output:
simmytarika5
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas dataframe.pow()

22 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.pow() function calculates the exponential power of dataframe and other, element-wise (binary operator pow). This function is essentially same as the dataframe ** other but with a support to fill the missing values in one of the input data.
Syntax: DataFrame.pow(other, axis=’columns’, level=None, fill_value=None)
Parameters :other : Series, DataFrame, or constantaxis : For Series input, axis to match Series index onlevel : Broadcast across a level, matching Index values on the passed MultiIndex levelfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.**kwargs : Additional keyword arguments are passed into DataFrame.shift or Series.shift.
Returns : result : DataFrame
Example #1: Use pow() function to find the power of each element in the dataframe. Raise each element in a row to a different power using a series.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df1 = pd.DataFrame({"A":[14, 4, 5, 4, 1],                    "B":[5, 2, 54, 3, 2],                    "C":[20, 20, 7, 3, 8],                    "D":[14, 3, 6, 2, 6]})  # Print the dataframedf
Let’s create a Series
# importing pandas as pdimport pandas as pd  # Create the Seriessr = pd.Series([2, 3, 4, 2], index =["A", "B", "C", "D"])  # Print the seriessr
Now, let’s use the dataframe.pow() function to raise each element in a row to different power.
# find the powerdf.pow(sr, axis = 1)
Output : Example #2: Use pow() function to raise each element of first data frame to the power of corresponding element in the other dataframe.
# importing pandas as pdimport pandas as pd  # Creating the first dataframe df1 = pd.DataFrame({"A":[14, 4, 5, 4, 1],                    "B":[5, 2, 54, 3, 2],                     "C":[20, 20, 7, 3, 8],                    "D":[14, 3, 6, 2, 6]})  # Creating the second dataframedf2 = pd.DataFrame({"A":[1, 5, 3, 4, 2],                    "B":[3, 2, 4, 3, 4],                    "C":[2, 2, 7, 3, 4],                    "D":[4, 3, 6, 12, 7]})  # using pow() function to raise each element# in df1 to the power of corresponding element in df2df1.pow(df2)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
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
Enumerate() in Python
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
How to drop one or multiple columns in Pandas Dataframe
Working with Titles and Heading – Python docx Module

03 Jan, 2021
Prerequisites: docx
Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. 
Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. To add a title or heading we will use the inbuilt .add_heading() method of the document object.
Syntax: doc.add_heading(String s, level)
Parameters:
String s: It is the string data that is to be added as a heading or a title.
level: It is an integer number in the range 0-9. It raises ValueError if any value other than from this range is given as input.
When the level is set to 0, the string is printed as the title of the document. For all other values it prints a heading. The size of heading decreases as the level increases. If no level is set, by default its value is always 1.
Pip command to install this module is:
pip install python-docx
Import module
Declare docx object
Use add_heading() with appropriate parameters to add heading
Save doc file.
Program:
Python3
# Import docx NOT python-docximport docx  # Create an instance of a word documentdoc = docx.Document()  # Add a heading of level 0 (Also called Title)doc.add_heading('Title for the document', 0)  # Add a heading of level 1doc.add_heading('Heading level 1', 1)  # Add a heading of level 2doc.add_heading('Heading level 2', 2)  # Add a heading of level 3doc.add_heading('Heading level 3', 3)  # Add a heading of level 4doc.add_heading('Heading level 4', 4)  # Add a heading of level 5doc.add_heading('Heading level 5', 5)  # Add a heading of level 6doc.add_heading('Heading level 6', 6)  # Add a heading of level 7doc.add_heading('Heading level 7', 7)  # Add a heading of level 8doc.add_heading('Heading level 8', 8)  # Add a heading of level 9doc.add_heading('Heading level 9', 9)  # Now save the document to a locationdoc.save('gfg.docx')
Output:
Document gfg.docx
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Examples - Display different shapes

How to draw a solid rectangle using GUI?
Following example demonstrates how to display a solid rectangle using fillRect() method of Graphics class.
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
   public static void main(String[] a) {
      JFrame f = new JFrame();
      f.setSize(400, 400);
      f.add(new Main());
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setVisible(true);
   }
   public void paint(Graphics g) {
      g.fillRect (5, 15, 50, 75);
   }
}
The above code sample will produce the following result.
Solid rectangle is created.

The following is an example to draw a solid rectangle using GUI.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Panel extends JPanel {
   public void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2d = (Graphics2D) g;
      g2d.setColor(new Color(31, 21, 1));
      g2d.fillRect(250, 195, 90, 60);
   } 
   public static void main(String[] args) {
      Panel rects = new Panel();
      JFrame frame = new JFrame("Rectangles");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(rects);
      frame.setSize(360, 300);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}
The above code sample will produce the following result.
Solid rectangle is created.

 Print
 Add Notes
 Bookmark this page
C++ ios Library - Boolalpha Function

It is used to sets the boolalpha format flag for the str stream. When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.
Following is the declaration for std::boolalpha function.
ios_base& boolalpha (ios_base& str);
str − Stream object whose format flag is affected.
It returns Argument str.
Basic guarantee − if an exception is thrown, str is in a valid state.
It modifies str. Concurrent access to the same stream object may cause data races.
In below example explains about std::boolalpha function.
#include <iostream>     

int main () {
   bool b = true;
   std::cout << std::boolalpha << b << '\n';
   std::cout << std::noboolalpha << b << '\n';
   return 0;
}
Let us compile and run the above program, this will produce the following result −
true
1

 Print
 Add Notes
 Bookmark this page
How to set background drawable programmatically in android?

This example demonstrates how do I set background drawable programmatically in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/rl"
   tools:context=".MainActivity">
   <Button
      android:text="Set Drawable"
      android:id="@+id/btnSetDrawable"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="10dp"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
   Button button;
   RelativeLayout relativeLayout;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      relativeLayout = findViewById(R.id.rl);
      button = findViewById(R.id.btnSetDrawable);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            relativeLayout.setBackgroundResource(R.drawable.image);
         }  
      });
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
Display time zone with SimpleDateFormat(“z”) in Java

You can display timezone easily in Java using SimpleDateFormat(“z”).
Firstly, to work with SimpleDateFormat class in Java, import the following package −
import java.text.SimpleDateFormat;
Now, set the format with SimpleDateFormat(“z”) to display timezone −
Format f = new SimpleDateFormat(”z”);
Now, get the timezone in a string −
String strTimeZone = f.format(new Date());
The following is an example −
 Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) throws Exception {
      // displaying current date and time
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s z");
      System.out.println("Today's date = "+simpleformat.format(cal.getTime()));
      // displaying hour
      Format f = new SimpleDateFormat("H");
      String strHour = f.format(new Date());
      System.out.println("Current Hour = "+strHour);
      // displaying minutes
      f = new SimpleDateFormat("mm");
      String strMinute = f.format(new Date());
      System.out.println("Current Minutes = "+strMinute);
      // displaying seconds in two-digits
      f = new SimpleDateFormat("ss");
      String strSeconds = f.format(new Date());
      System.out.println("Current Seconds = "+strSeconds);
      f = new SimpleDateFormat("a");
      String strMarker = f.format(new Date());
      System.out.println("Current AM/PM Marker = "+strMarker);
      // display timezone
      f = new SimpleDateFormat("z");
      String strTimeZone = f.format(new Date());
      System.out.println("TimeZone = "+strTimeZone);
   }
}
Today's date = 26/November/2018 08:11:21 UTC
Current Hour = 8
Current Minutes = 11
Current Seconds = 21
Current AM/PM Marker = AM
TimeZone = UTC
How to install the specific version of the PowerShell module version?

To install the specific version of the PowerShell module, we need to use the -RequiredVersion parameter with the Install-Module command.
To find which module versions are available, we can use the Find-Module command with the -AllVersions parameter which retrieves all the versions of the module available in the PSGallery.
In this example, we will use the 7Zip4PowerShell module.
Find-Module 7zip4PowerShell -AllVersions | ft -AutoSize
When you run this command, you can see there are multiple versions available for this module.
Version  Name            Repository
-------  ----            ----------
1.13.0   7Zip4Powershell PSGallery
1.12.0   7Zip4Powershell PSGallery
1.11.0   7Zip4Powershell PSGallery
1.10.0.0 7Zip4Powershell PSGallery
1.9.0    7Zip4Powershell PSGallery
1.8.0    7Zip4Powershell PSGallery
1.7.1    7Zip4Powershell PSGallery
We need to install here version 1.9.0 for all the users, so we will use the below command.
Install-Module 7Zip4PowerShell -RequiredVersion 1.8.0 -Scope AllUsers -Force -Verbose
To install PowerShell module on the remote server, use the below command,
Invoke-Command -ComputerName RemoteMachine1 -ScriptBlock {Install-Module 7Zip4PowerShell -RequiredVersion 1.8.0 -Scope AllUsers -Force -Verbose}