code-rag-bench/online-tutorials huggingface dataset:
C Program to check if two strings are same or not

Given two strings str1 and str2 we have to check whether the two strings are same or not. Like we are given two stings “hello” and “hello” so they are identical and same.
Identical are the strings which seems equal but are not equal like : “Hello” and “hello”, and same are the strings which are exactly same like : “World” and “World”.
Input: str1[] = {“Hello”}, str2[] = {“Hello”}
Output: Yes 2 strings are same
Input: str1[] = {“world”}, str2[] = {“World”}
Output: No, 2 strings are not same
The approach used below is as follows −
We can use strcmp(string2, string1).
strcmp() string compare function is a in-built function of “string.h” header file, this function accepts two parameters, both strings. This function compares two strings and checks whether both strings are same and return 0 if there is no change in the string and return a non-zero value when the two strings are not same. This function is case-sensitive, means both the strings should be exactly same.
So we will take two strings as an input.
Use strcmp() and pass both the strings as parameters
If they return zero then print “Yes 2 strings are same”
Else print “No, 2 strings are not same”.
Start
In function int main(int argc, char const *argv[])
   Step 1-> Declare and initialize 2 strings string1[] and string2[]
   Step 2-> If strcmp(string1, string2) == 0 then,
      Print "Yes 2 strings are same\n"
   Step 3-> else
      Print "No, 2 strings are not same\n"
Stop
 Live Demo
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[]) {
   char string1[] = {"tutorials point"};
   char string2[] = {"tutorials point"};
   //using function strcmp() to compare the two strings
   if (strcmp(string1, string2) == 0)
      printf("Yes 2 strings are same\n");
   else
      printf("No, 2 strings are not same\n" );
      return 0;
}
If run the above code it will generate the following output −
Yes 2 strings are same
How to make Log Plots in Plotly - Python? - GeeksforGeeks

05 Sep, 2020
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A log plot is a way of displaying numerical data over a very wide range of values in a compact way. There are two types of plots:
log-log plot: If both the vertical and horizontal axes of a plot are scaled logarithmically, the plot is referred to as a log-log plot.
Semi-logarithmic plots: If only the ordinate or abscissa is scaled logarithmically, the plot is referred to as a semi-logarithmic plot.
There is no specific function provided for creating the log plots. However, it can be created using the scatter() method of graph_objects class. We will have to change the xaxis_type and yaxis_type to log.
Example 1: log-log plot
Python3
import plotly.graph_objects as goimport numpy as np    x = np.linspace(1, 15, 20)y = np.linspace(10, 15, 20)  fig = go.Figure()  fig.add_trace(go.Scatter(    x=x,    y=y))  fig.update_layout(xaxis_type="log", yaxis_type="log")fig.show()
Output:
Example 2: semi-log plot
Python3
import plotly.graph_objects as goimport numpy as np    x = np.linspace(1, 15, 20)y = np.linspace(10, 15, 20)  fig = go.Figure()  fig.add_trace(go.Scatter(    x=x,    y=y))  fig.update_layout(xaxis_type="log")fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
File Handling with os Module

In addition to File object returned by open() function, file IO operations can also be performed using Python's built-in library has os module that provides useful operating system dependent functions. These functions perform low level read/write operations on file.
The open() function from os module is similar to the built-in open(). However, it doesn't return a file object but a file descriptor, a unique integer corresponding to file opened. File descriptor's values 0, 1 and 2 represent stdin, stdout, and stderr streams. Other files will be given incremental file descriptor from 2 onwards.
As in case of open() built-in function, os.open() function also needs to specify file access mode. Following table lists various modes as defined in os module.
os.O_RDONLY
Open for reading only
os.O_WRONLY
Open for writing only
os.O_RDWR
Open for reading and writing
os.O_NONBLOCK
Do not block on open
os.O_APPEND
Append on each write
os.O_CREAT
Create file if it does not exist
os.O_TRUNC
Truncate size to 0
os.O_EXCL
Error if create and file exists
To open a new file for writing data in it, specify O_WRONLY as well as O_CREAT modes by inserting pipe (|) operator. The os.open() function returns a file descriptor.
f=os.open("test.dat", os.O_WRONLY|os.O_CREAT)

Note that, data is written to disk file in the form of byte string. Hence, a normal string is converted to byte string by using encode() function as earlier.
data="Hello World".encode('utf-8')

The write() function in os module accepts this byte string and file descriptor.
os.write(f,data)

Don’t forget to close the file using close() function.
os.close(f)

To read contents of a file using os.read() function, use following statements:
f=os.open("test.dat", os.O_RDONLY)
data=os.read(f,20)
print (data.decode('utf-8'))

Note that, the os.read() function needs file descriptor and number of bytes to be read (length of byte string).
If you want to open a file for simultaneous read/write operations, use O_RDWR mode. Following table shows important file operation related functions in os module.
os.close(fd)
Close the file descriptor.
os.open(file, flags[, mode])
Open the file and set various flags according to flags and possibly its mode according to mode.
os.read(fd, n)
Read at most n bytes from file descriptor fd. Return a string containing the bytes read. If the end of the file referred to by fd has been reached, an empty string is returned.
os.write(fd, str)
Write the string str to file descriptor fd. Return the number of bytes actually written.

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
RESTful Web Services - Resources

REST architecture treats every content as a resource. These resources can be Text Files, Html Pages, Images, Videos or Dynamic Business Data. REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ Global IDs. REST uses various representations to represent a resource where Text, JSON, XML. The most popular representations of resources are XML and JSON.
A resource in REST is a similar Object in Object Oriented Programming or is like an Entity in a Database. Once a resource is identified then its representation is to be decided using a standard format so that the server can send the resource in the above said format and client can understand the same format.
For example, in RESTful Web Services - First Application chapter, a user is a resource which is represented using the following XML format −
<user> 
   <id>1</id> 
   <name>Mahesh</name>
   <profession>Teacher</profession> 
</user> 
The same resource can be represented in JSON format as follows −
{ 
   "id":1, 
   "name":"Mahesh", 
   "profession":"Teacher" 
}
REST does not impose any restriction on the format of a resource representation. A client can ask for JSON representation whereas another client may ask for XML representation of the same resource to the server and so on. It is the responsibility of the REST server to pass the client the resource in the format that the client understands.
Following are some important points to be considered while designing a representation format of a resource in RESTful Web Services.
Understandability − Both the Server and the Client should be able to understand and utilize the representation format of the resource.
Understandability − Both the Server and the Client should be able to understand and utilize the representation format of the resource.
Completeness − Format should be able to represent a resource completely. For example, a resource can contain another resource. Format should be able to represent simple as well as complex structures of resources.
Completeness − Format should be able to represent a resource completely. For example, a resource can contain another resource. Format should be able to represent simple as well as complex structures of resources.
Linkablity − A resource can have a linkage to another resource, a format should be able to handle such situations.
Linkablity − A resource can have a linkage to another resource, a format should be able to handle such situations.
However, at present most of the web services are representing resources using either XML or JSON format. There are plenty of libraries and tools available to understand, parse, and modify XML and JSON data.

    71 Lectures 
     10 hours 

 Chaand Sheikh

    27 Lectures 
     2 hours 

 Vinod Kumar Kayartaya

    517 Lectures 
     57 hours 

 Chaand Sheikh

    35 Lectures 
     3.5 hours 

 Antonio Papa
 Print
 Add Notes
 Bookmark this page
Capturing browser logs with Selenium WebDriver using Java.

We can capture browser logs with Selenium. We have to type cast the RemoteWebDriver to driver and then initialize it. Next, we have to use the setLogLevel method. The import org.openqa.selenium.remote.RemoteWebDriver statement needs to be added in code for the RemoteWebDriver.
((RemoteWebDriver) driver).setLogLevel(Level.INFO);
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver
import java.util.logging.Level;
public class BrwLogs{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // Enable logging with setLogLevel method
      ((RemoteWebDriver) driver).setLogLevel(Level.INFO);
      driver.get("https://www.tutorialspoint.com/index.htm");
      //identify element
      driver.findElement(By.id("gsc−i−id1")).sendKeys("Selenium");
      driver.quit();
   }
}
Different kinds of Doctype available in HTML5 - GeeksforGeeks

02 Nov, 2021
In this article, we will know the Doctype & its types in HTML5. Before learning the different kinds of Doctypes in HTML5, you should be first familiar with the term “Doctype“. When you inspect any website, you may have noticed that before the starting of <html> tag, <!DOCTYPE html> is written.
Doctype: A Doctype or Document Type Declaration is basically the first line of code that is required when you create an HTML document. It tells the browser about the specific HTML version in which the current web page is written. All the different web browsers will render the webpage using the same version of HTML and therefore the web page will look the same in the different web browsers. This is the main intent of using the Doctype in HTML.
Note: The Doctype is not an HTML tag or element and it’s case-insensitive.
Types: In the previous versions of HTML, there were different kinds of Doctypes that were declared in each version of HTML, but in HTML5 there is only one type of Doctype available. 
Usage: In previous versions of HTML, the main usage of Doctype was to create a reference to DTD (Document Type Definition) and it was compulsory to refer to DTD but in HTML5, it doesn’t need to refer to DTD. The Document Type Definition (DTD) was majorly used to define the structure with a list of validated attributes and elements.
Syntax: Nowadays, most of the webpages are created using HTML5, so for that, we just need to create a simple doctype syntax. The following is the syntax of Doctype:
<!DOCTYPE html>
Approach: We just need to declare the Doctype as shown in the syntax at the beginning of the HTML Code.
Example: This example shows a simple HTML code with the declaration of Doctype.
HTML
<!-- Declaration of Doctype --><!DOCTYPE html><html><head>    <title>Doctypes in HTML5</title></head>  <body>    <h2>Welcome To GFG</h2>    <p>          Different kinds of Doctypes           available in HTML5      </p></body></html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Microsoft Edge
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.
HTML-Questions
HTML5
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Difference Between DAS and SAN - GeeksforGeeks

23 Jun, 2020
1. Directly Attached Storage (DAS) :The storage device which is permanently attached to a desktop computer. DAS is for a single user (Hard drive attached to a computer). It is well suited for a small-to-medium sized business where sufficient amounts of storage can be configured at a low startup cost. The DAS enclosure will be a separate adjacent cabinet that contains additional disk drives.
Component of Directly Attached Storage (DAS) –
1. Storage devices
2. Cables
3. Disk Array
4. Protocol
5. Storage protocols: ATA, SCSI, SAS, SASA, FC 
2. Storage Area Network (SAN) :SAN acts on block level over network. Storage which can be accessed using ISCSI or FC. Suitable for business-critical applications and where high performance is required. The main benefit to a SAN-based storage solution is ability to share storage arrays to multiple servers. This allows you to configure storage capacity as needed, usually by a dedicated SAN administrator. Higher levels of performance throughput are typical in a SAN environment, and data is highly available through redundant disk controllers and drives.
Components of Storage Area Network (SAN) –
1. Node ports
2. Cables
3. Interconnect device such as: Hubs, switches, directors
4. Storage arrays
5. SAN management Software 
Difference Between DAS and SAN :
Computer Networks
Difference Between
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Introduction and IPv4 Datagram Header
Intrusion Detection System (IDS)
Secure Socket Layer (SSL)
Cryptography and its Types
Difference between BFS and DFS
Class method vs Static method in Python
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Stack vs Heap Memory Allocation
Scala List forall() method with example - GeeksforGeeks

29 Jul, 2019
The forall() method is utilized to check if the given predicate satisfies all the elements of the list or not.
Method Definition: def forall (p: (a) => Boolean) : Boolean
Return Type: It returns true if the stated predicate holds true for all the elements of the list else it returns false.
Example #1:
// Scala program of forall()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a list        val m1 = List(3, 6, 12, 9, 21)                  // Applying forall method        val result = m1.forall(y => {y % 3 == 0})                  // Displays output        println(result)          }} 
true

Example #2:
// Scala program of forall()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {        // Creating a list        val m1 = List(3, 6, 2, 9, 21)                  // Applying forall method        val result = m1.forall(y => {y % 3 == 0})                  // Displays output        println(result)          }} 
false

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Scala Constructors
Inheritance in Scala
Scala | Arrays
How to get the first element of List in Scala
Scala String replace() method with example
Break statement in Scala
Python | Swap tuple elements in list of tuples

27 Aug, 2019
While doing competitive programming, one can come across a question in which one requires to work with 2D plane and work with coordinates. One such subproblem can be swapping x, y coordinate elements. Let’s discuss certain ways in which this problem can be solved using tuple element swapping.
Method #1 : Using list comprehensionThis is just a brute method to perform the longer method of loop for swapping the elements. In this a new list of tuple is created rather than an inplace swap.
# Python3 code to demonstrate working of# Swap tuple elements in list of tuples# Using list comprehension  # initializing listtest_list = [(3, 4), (6, 5), (7, 8)]  # printing original listprint("The original list is : " + str(test_list))  # Swap tuple elements in list of tuples# Using list comprehensionres = [(sub[1], sub[0]) for sub in test_list]          # printing resultprint("The swapped tuple list is : " + str(res))
The original list is : [(3, 4), (6, 5), (7, 8)]
The swapped tuple list is : [(4, 3), (5, 6), (8, 7)]

 
Method #2 : Using map() + lambdaYet another way to perform this task is using map and lambda. This is a bit slower in execution but a more compact way to perform this task.
# Python3 code to demonstrate working of# Swap tuple elements in list of tuples# Using map() + lambda  # initializing listtest_list = [(3, 4), (6, 5), (7, 8)]  # printing original listprint("The original list is : " + str(test_list))  # Swap tuple elements in list of tuples# Using map() + lambdares = list(map(lambda sub: (sub[1], sub[0]), test_list))          # printing resultprint("The swapped tuple list is : " + str(res))
The original list is : [(3, 4), (6, 5), (7, 8)]
The swapped tuple list is : [(4, 3), (5, 6), (8, 7)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
FETCH in SQL

19 May, 2021
FETCH is an SQL command used along with ORDER BY clause with an OFFSET(Starting point) to retrieve or fetch selected rows sequentially using a cursor that moves and processes each row one at a time till the number of rows mentioned in the query are displayed.
With FETCH the OFFSET clause is mandatory. You are not allowed to use, ORDER BY ... FETCH.
You are not allowed to combine TOP with OFFSET and FETCH.
The OFFSET/FETCH row count expression can only be any arithmetic, constant, or parameter expression which will return an integer value.
With the OFFSET and FETCH clause, the ORDER BY is mandatory to be used. 
Syntax:
SELECT *
FROM table_name
ORDER BY col_name
OFFSET starting point
FETCH NEXT k(constant) ROWS ONLY;
Steps to implement FETCH:
Here, we will discuss the steps to implement the FETCH command in SQL. 
Step 1: Reference table: 
Let us consider a table is created based on marks of students in the class that contains data displayed below.
Step 2: Creating a database:
CREATE DATABASE gfg;
Step 3: Using the database:
USE gfg;
Step 4: Creating a table:
Creating table MarketList with 5 columns using the following SQL query:
CREATE TABLE MarkList
(
    id int,
    name varchar(20),
    mathematics int, 
    physics int,
    chemistry int
);
Step 5: Inserting the data into the table:
INSERT INTO MarkList VALUES(501,'Surya',99,97,85);
INSERT INTO MarkList VALUES(502,'Charan',99,93,88);
INSERT INTO MarkList VALUES(503,'Sravan',91,98,94);
INSERT INTO MarkList VALUES(504,'Ram',92,99,82);
INSERT INTO MarkList VALUES(505,'Aryan',94,99,88);
INSERT INTO MarkList VALUES(506,'Sathwik',91,88,91);
INSERT INTO MarkList VALUES(507,'Madhav',90,97,89);
Step 6: After inserting, the table will look like this.
Step 7: Now fetching the data using the fetch command: 
To retrieve the names, id and total marks of the top 3 students, the fetch command is used as follows:
SELECT Id, name, mathematics+physics+chemistry AS total
FROM MarketList
ORDER BY mathematics+physics+chemistry DESC
OFFSET 0 ROWS
FETCH NEXT 3 ROWS ONLY;
So, the SQL FETCH command is used to retrieve selected rows from a table sequentially. It’s handy to use when you want to select a limited number of rows from an ordered set, like top 3, top 10, or bottom 3, etc.
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Enable virtualization (VT-x) in Windows 10 BIOS?

29 Oct, 2021
When you install a virtual machine on your system, it is possible that the machine may not start and you may encounter an error telling you that VT-x is disabled (or referencing a problem with AMD-V if you have an AMD CPU). This means that the hardware acceleration settings required by the CPU to support virtualization are currently disabled in your BIOS. In this article, we will be resolving this issue.
Note: Accessing the BIOS might differ from manufacturer to manufacturer. Additionally, it is also possible that the same manufacturer may implement different BIOS versions depending on the age or model of the computer.
Follow the below steps to check  if virtualization s disabled:
Step 1: Open up the command prompt.
 windows+r 
Step 2: Now run the below command:
systeminfo.exe 
systeminfo.exe
Find hyper v requirements and to the right, you will find virtualization enabled in the firmware.
If it is disabled that is if it is No we can move on.
Follow the below steps to enable virtualization on your windows 10 system:
Step 1: Navigate to the start menu and click on settings.
Step 2: Find update and security and click on it.
Step 3: A tab will open now find recovery and click on it.
Step 4: In recovery, you have to find advance startup, under advance startup you will see the restart now button, click on restart now.
Step 5: Once you see the blue screen with some icons, you have to select the Troubleshoot one.
Step 6: Select Advanced options.
Step 7: Since our problem is with the firmware we have to find that setting. Once we find UEFI firmware settings select that and again restart button will appear so hit enter on restart.
click on UEFI Filmware setting ( windows 10)
Click on restart
Step 8: We have to find the BIOS setup and click on the respective function key. Here it is F10. So press F10 (for Lenovo system press Fn+F10).
Step 9: New panel will open, here go to the System configuration (just by pressing up down left right key you can move here )and find Virtualization Technology. Once you go to virtualization technology hit the enter key.
Click on enable
Your virtualization technology is enabled at this point. You can press F10 to exit here.
How To
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU.
Top Programming Languages for Android App Development
Check if Table Exists in SQLite using Python

26 Jul, 2021
In this article, we will discuss how to check if a table exists in an SQLite database using the sqlite3 module of Python.
In an SQLite database, the names of all the tables are enlisted in the sqlite_master table. So in order to check if a table exists or not we need to check that if the name of the particular table is in the sqlite_master table or not.
In order to perform this task execute the below query and store it in a variable.
SELECT tableName FROM sqlite_master WHERE type=’table’ AND tableName=’STUDENT’;
Then use the fetchall() method on that variable to generate a list of tables containing the name of the that is found. If the list is empty then the table does not exist in the database.
Example: First, let’s connect to the g4gdata.db SQLite database and then create a cursor object. Now using the cursor object we execute some queries to create multiple tables: EMPLOYEE, STUDENT, STAFF. Then we check if the STUDENT and TEACHER table exists in g4gdata.db database or not. 
Python3
# import required moduleimport sqlite3 # connect to databasecon = sqlite3.connect('g4gdata.db') # create cursor objectcur = con.cursor() # create tablescur.execute(  """CREATE TABLE EMPLOYEE(FIRST_NAME VARCHAR(255),  LAST_NAME VARCHAR(255),AGE int, SEX CHAR(1), INCOME int);""")print('EMPLOYEE table created') cur.execute(  """CREATE TABLE STUDENT(NAME VARCHAR(255),AGE int, SEX CHAR(1));""")print('STUDENT table created') cur.execute(  """CREATE TABLE STAFF(NAME VARCHAR(255), INCOME int);""")print('STAFF table created')print() # check if table existsprint('Check if STUDENT table exists in the database:')listOfTables = cur.execute(  """SELECT tableName FROM sqlite_master WHERE type='table'  AND tableName='STUDENT'; """).fetchall() if listOfTables == []:    print('Table not found!')else:    print('Table found!') # check if table existsprint('Check if TEACHER table exists in the database:')listOfTables = cur.execute(  """SELECT name FROM sqlite_master WHERE type='table'  AND name='TEACHER'; """).fetchall() if listOfTables == []:    print('Table not found!')else:    print('Table found!') # commit changescon.commit() # terminate the connectioncon.close()
Output:
surindertarika1234
Picked
Python-SQLite
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
Where to put JavaScript in an HTML Document ?

03 Jun, 2022
JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body.
JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked.
Examples:
<!DOCTYPE html><html>   <head>      <script>         function gfg() {           document.getElementById("demo").innerHTML = "Geeks For Geeks";         }      </script>   </head>   <body>      <h2>JavaScript in Head</h2>      <p id="demo" style="color:green;">geeksforgeeks.</p>      <button type="button" onclick="gfg()">click it</button>   </body></html>
Output:Before clicking the buttonAfter clicking the button
JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked.Example:
<!DOCTYPE html><html>   <center>      <body>         <h2>JavaScript in Body</h2>         <p id="demo">geeksforgeeks.</p>         <button type="button" onclick="gfg()">Try it</button>         <script>            function gfg() {              document.getElementById("demo").innerHTML = "Geeks For Geeks";            }         </script>      </body>   </center></html>
Output:Before clicking the buttonAfter click on button
External JavaScript: JavaScript can also be used as external files. JavaScript files have file extension .js . To use an external script put the name of the script file in the src attribute of a script tag. External scripts cannot contain script tags.Example:
<!DOCTYPE html><html>   <center>   <body>      <h2>External JavaScript</h2>      <p id="demo">Geeks For Geeks.</p>      <button type="button" onclick="myFunction()">Try it</button>      <script src="myScript.js"></script>   </body>   <center></html>
Output before clicking:Output after clicking:
Advantages of External JavaScript:
Cached JavaScript files can speed up page loading
It makes JavaScript and HTML easier to read and maintain
It separates the HTML and JavaScript code
It focuses on code re usability that is one JavaScript Code can run in various HTML files.
raj2002
javascript-basics
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Stack and Queue in Python using queue Module

09 May, 2022
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java.
1. Creating a FIFO Queue
// Initialize queue
Syntax: queue.Queue(maxsize)

// Insert Element
Syntax: Queue.put(data)

// Get And remove the element
Syntax: Queue.get()

Initializes a variable to a maximum size of maxsize. A maxsize of zero ‘0’ means a infinite queue. This Queue follows FIFO rule. This module also has a LIFO Queue, which is basically a Stack. Data is inserted into Queue using put() and the end. get() takes data out from the front of the Queue. Note that Both put() and get() take 2 more parameters, optional flags, block and timeout.
import queue  # From class queue, Queue is# created as an object Now L# is Queue of a maximum # capacity of 20L = queue.Queue(maxsize=20)  # Data is inserted into Queue# using put() Data is inserted# at the endL.put(5)L.put(9)L.put(1)L.put(7)  # get() takes data out from# the Queue from the head # of the Queueprint(L.get())print(L.get())print(L.get())print(L.get())
Output:
5
9
1
7

2. UnderFlow and OverFlowWhen we try to add data into a Queue above is maxsize, it is called OverFlow(Queue Full) and when we try removing an element from an empty, it’s called Underflow. put() and get() do not give error upon Underflow and Overflow, but goes into an infinite loop.
import queue  L = queue.Queue(maxsize=6)  # qsize() give the maxsize# of the Queueprint(L.qsize())  L.put(5)L.put(9)L.put(1)L.put(7)  # Return Boolean for Full# Queueprint("Full: ", L.full())  L.put(9)L.put(10)print("Full: ", L.full())  print(L.get())print(L.get())print(L.get())  # Return Boolean for Empty# Queueprint("Empty: ", L.empty())  print(L.get())print(L.get())print(L.get())  print("Empty: ", L.empty())print("Full: ", L.full())  # This would result into Infinite# Loop as the Queue is empty.# print(L.get())
Output:
0
Full:  False
Full:  True
5
9
1
Empty:  False
7
9
10
Empty:  True
Full:  False

3. StackThis module queue also provides LIFO Queue which technically works as a Stack.
import queue  L = queue.LifoQueue(maxsize=6)  # qsize() give the maxsize of# the Queueprint(L.qsize())  # Data Inserted as 5->9->1->7, # same as QueueL.put(5)L.put(9)L.put(1)L.put(7)L.put(9)L.put(10)print("Full: ", L.full())print("Size: ", L.qsize())  # Data will be accessed in the# reverse order Reverse of that# of Queueprint(L.get())print(L.get())print(L.get())print(L.get())print(L.get())print("Empty: ", L.empty())
Output:
0
Full:  True
Size: 6
10
9
7
1
9
Empty:  False

Reference:https://docs.python.org/3/library/asyncio-queue.html
Python-Data-Structures
Python
Queue
Stack
Stack
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.clip() in Python

29 Nov, 2018
numpy.clip() function is used to Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.
Syntax : numpy.clip(a, a_min, a_max, out=None)
Parameters :a : Array containing elements to clip.a_min : Minimum value.    –> If None, clipping is not performed on lower interval edge. Not more than one of a_min and a_max may be None.a_max : Maximum value.    –> If None, clipping is not performed on upper interval edge. Not more than one of a_min and a_max may be None.    –> If a_min or a_max are array_like, then the three arrays will be broadcasted to match their shapes.out : Results will be placed in this array. It may be the input array for in-place clipping. out must be of the right shape to hold the output. Its type is preserved.
Return : clipped_array
Code #1 :
# Python3 code demonstrate clip() function  # importing the numpyimport numpy as np  in_array = [1, 2, 3, 4, 5, 6, 7, 8 ]print ("Input array : ", in_array)  out_array = np.clip(in_array, a_min = 2, a_max = 6)print ("Output array : ", out_array)
Output :
Input array :  [1, 2, 3, 4, 5, 6, 7, 8]
Output array :  [2 2 3 4 5 6 6 6]
 Code #2 :
# Python3 code demonstrate clip() function  # importing the numpyimport numpy as np  in_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]print ("Input array : ", in_array)  out_array = np.clip(in_array, a_min =[3, 4, 1, 1, 1, 4, 4, 4, 4, 4],                                                         a_max = 9)print ("Output array : ", out_array)
Output :
Input array :  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output array :  [3 4 3 4 5 6 7 8 9 9]

Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python
Maximum value of unsigned char in C++

18 Jan, 2021
In this article, we will discuss the maximum value of unsigned char data type in C++.
Some properties of the unsigned char data type are:
Being an unsigned data type, it can store only positive values.
Unsigned char data type in C++ is used to store 8-bit characters.
A maximum value that can be stored in an unsigned char data type is typically 255, around 28 – 1(but is compiler dependent).
The maximum value that can be stored in an unsigned char is stored as a constant in the <climits> header file, whose value can be used as UCHAR_MAX.
A minimum value that can be stored in an unsigned char data type is 0.
In case of overflow or underflow of data type, the value is wrapped around.
For example, if 0 is stored in an unsigned char data type and 1 is subtracted from it, the value in that variable will become equal to 255. Similarly, in the case of overflow, the value will round back to 0.
Below is the program to get the highest value that can be stored in unsigned char in C++:
C++
// C++ program to obtain the maximum// value that can be stored in an// unsigned char  #include <climits>#include <iostream>using namespace std;  // Function to find the maximum value// stored in unsigned charvoid maxUnsignedChar(){    // From the constant of climits    // header file    unsigned char valueFromLimits = UCHAR_MAX;    cout << "Value from climits "         << "constant : "         << (int)valueFromLimits         << "\n";      // Using the wrap around property    // of data types      // Initialize a variable with    // value 0    unsigned char value = 0;      // Subtract 1 from value since    // unsigned data type cannot store    // negative number, the value will    // wrap around and store the maximum    // value that we can store in it    value = value - 1;      cout << "Value using the wrap "         << "around property : "         << (int)value << "\n";}  // Driver Codeint main(){    // Function call    maxUnsignedChar();      return 0;}
Value from climits constant : 255
Value using the wrap around property : 255

C Basics
C-Data Types
CPP-Basics
Data Types
C++
C++ Programs
Programming Language
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
Java Program 0-1 Knapsack Problem

23 Oct, 2019
Recursive Solution
/* A Naive recursive implementation of 0-1 Knapsack problem */class Knapsack {      // A utility function that returns maximum of two integers    static int max(int a, int b) { return (a > b) ? a : b; }      // Returns the maximum value that can     // be put in a knapsack of capacity W    static int knapSack(int W, int wt[], int val[], int n)    {        // Base Case        if (n == 0 || W == 0)            return 0;          // If weight of the nth item is more         // than Knapsack capacity W, then        // this item cannot be included in the optimal solution        if (wt[n - 1] > W)            return knapSack(W, wt, val, n - 1);          // Return the maximum of two cases:        // (1) nth item included        // (2) not included        else            return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),                       knapSack(W, wt, val, n - 1));    }      // Driver program to test above function    public static void main(String args[])    {        int val[] = new int[] { 60, 100, 120 };        int wt[] = new int[] { 10, 20, 30 };        int W = 50;        int n = val.length;        System.out.println(knapSack(W, wt, val, n));    }}/*This code is contributed by Rajat Mishra */
220

Dynamic Programming Solution
// A Dynamic Programming based solution for 0-1 Knapsack problemclass Knapsack {      // A utility function that returns maximum of two integers    static int max(int a, int b) { return (a > b) ? a : b; }      // Returns the maximum value that can be put in a knapsack    // of capacity W    static int knapSack(int W, int wt[], int val[], int n)    {        int i, w;        int K[][] = new int[n + 1][W + 1];          // Build table K[][] in bottom up manner        for (i = 0; i<= n; i++) {            for (w = 0; w<= W; w++) {                if (i == 0 || w == 0)                    K[i][w] = 0;                else if (wt[i - 1]<= w)                    K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);                else                    K[i][w] = K[i - 1][w];            }        }          return K[n][W];    }      // Driver program to test above function    public static void main(String args[])    {        int val[] = new int[] { 60, 100, 120 };        int wt[] = new int[] { 10, 20, 30 };        int W = 50;        int n = val.length;        System.out.println(knapSack(W, wt, val, n));    }}/*This code is contributed by Rajat Mishra */
220

Please refer complete article on Dynamic Programming | Set 10 ( 0-1 Knapsack Problem) for more details!
knapsack
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - Convert one datatype to another in a Pandas DataFrame

Use the astype() method in Pandas to convert one datatype to another. Import the required library −
import pandas as pd
Create a DataFrame. Here, we have 2 columns, “Reg_Price” is a float type and “Units” int type −
dataFrame = pd.DataFrame(
   {
      "Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
      "Units": [90, 120, 100, 150, 200, 130]
   }
)


Check the datatypes of the columns created above −
dataFrame.dtypes
Convert both the types to int32 −
dataFrame.astype('int32').dtypes

Following is the code −
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000],
      "Units": [90, 120, 100, 150, 200, 130]
   }
)

print"DataFrame ...\n",dataFrame
print"\nDataFrame Types ...\n",dataFrame.dtypes
print"\nCast all columns to int32..."

print"\nUpdated DataFrame Types ...\n",dataFrame.astype('int32').dtypes


This will produce the following output −
DataFrame ...
   Reg_Price   Units
0 7000.50570     90
1 1500.00000    120
2 5000.00000    100
3 8000.00000    150
4 9000.75768    200
5 6000.00000    130

DataFrame Types ...
Reg_Price   float64
Units         int64
dtype: object

Cast all columns to int32...

Updated DataFrame Types ...
Reg_Price   int32
Units       int32
dtype: object
Lua - Arrays

Arrays are ordered arrangement of objects, which may be a one-dimensional array containing a collection of rows or a multi-dimensional array containing multiple rows and columns.
In Lua, arrays are implemented using indexing tables with integers. The size of an array is not fixed and it can grow based on our requirements, subject to memory constraints.
A one-dimensional array can be represented using a simple table structure and can be initialized and read using a simple for loop. An example is shown below.
array = {"Lua", "Tutorial"}

for i = 0, 2 do
   print(array[i])
end
When we run the above code, we wil get the following output.
nil
Lua
Tutorial

As you can see in the above code, when we are trying to access an element in an index that is not there in the array, it returns nil. In Lua, indexing generally starts at index 1. But it is possible to create objects at index 0 and below 0 as well. Array using negative indices is shown below where we initialize the array using a for loop.
array = {}

for i= -2, 2 do
   array[i] = i *2
end

for i = -2,2 do
   print(array[i])
end
When we run the above code, we will get the following output.
-4
-2
0
2
4

Multi-dimensional arrays can be implemented in two ways.
Array of arrays
Single dimensional array by manipulating indices
An example for multidimensional array of 3. 3 is shown below using array of arrays.
-- Initializing the array
array = {}

for i=1,3 do
   array[i] = {}
	
   for j=1,3 do
      array[i][j] = i*j
   end
	
end

-- Accessing the array

for i=1,3 do

   for j=1,3 do
      print(array[i][j])
   end
	
end
When we run the above code, we will get the following output.
1
2
3
2
4
6
3
6
9

An example for multidimensional array is shown below using manipulating indices.
-- Initializing the array

array = {}

maxRows = 3
maxColumns = 3

for row=1,maxRows do

   for col=1,maxColumns do
      array[row*maxColumns +col] = row*col
   end
	
end

-- Accessing the array

for row=1,maxRows do

   for col=1,maxColumns do
      print(array[row*maxColumns +col])
   end
	
end
When we run the above code, we will get the following output.
1
2
3
2
4
6
3
6
9

As you can see in the above example, data is stored based on indices. It is possible to place the elements in a sparse way and it is the way Lua implementation of a matrix works. Since it does not store nil values in Lua, it is possible to save lots of memory without any special technique in Lua as compared to special techniques used in other programming languages.

    12 Lectures 
     2 hours 

 Manish Gupta

    80 Lectures 
     3 hours 

 Sanjeev Mittal

    54 Lectures 
     3.5 hours 

 Mehmet GOKTEPE
 Print
 Add Notes
 Bookmark this page
C# Program to Display the Abbreviation of a Text - GeeksforGeeks

24 Oct, 2021
Given a text, we need to display the Abbreviation of the text. An abbreviation is the shortest form of any word or phrase. It contains a group of letters that takes from the full form of the word or phrase. For example, GeeksforGeeks abbreviation is GFG, or the abbreviation of Advance Data Structure is ADS. 
Examples:
Input : Geeks For Geeks
Output: G.F.G

Input : Data Structures Algorithms
Output: D.S.A
Approach:
To print the abbreviation of a text follow the following steps:
Initialize an empty string (i.e. abbr).
Append the first letter of string to abbr and also append a  ‘ . ‘  to abbr.
Now the String is iterated from left to right if space or tab or a newline character is encountered then append the next letter to the abbr and also append  ‘ . ‘  to the abbr.
At the end of the iteration, the abbr will have the abbreviation of the given string.
Example:
C#
// C# program to print the abbreviation of a Textusing System;  class GFG{  public static string Abbreviation(string inputstr){    string abbr = "";    int i = 0;    abbr += inputstr[0];    abbr += '.';      for(i = 0; i < inputstr.Length - 1; i++)    {        if (inputstr[i] == ' ' || inputstr[i] == '\t' ||             inputstr[i] == '\n')        {            abbr += inputstr[i + 1];            abbr += '.';        }    }    return abbr;}  // Driver codepublic static void Main(){    string str = "Geeks For Geeks";    string abr = "";      abr = Abbreviation(str);      Console.Write("The Abbreviation : " + abr);}}
The Abbreviation : G.F.G.
Explanation: In this example, we create an Abbreviation() method which returns the abbreviation of the specified string. Or we can say that it returns a string that contains the first letter of a word is added to the abbr string if there is space or tab or a newline character before the word, along with that a ‘ . ‘ is also added. Like in string “Geeks For Geeks” the abbreviation is G.F.G. 
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
Partial Classes in C#
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#