code-rag-bench/online-tutorials huggingface dataset:
How to delete/remove an element from a C# array?

To delete an elements from a C# array, we will shift the elements from the position the user want the element to delete.
Here, first we have 5 elements −
int[] arr = new int[5] {35, 50, 55, 77, 98};
Now let’s say we need to delete the element at 2nd position i.e. variable “pos = 2” is set, for that shift the elements after the specified position −
// Shifting elements
for (i = pos-1; i < 4; i++) {
   arr[i] = arr[i + 1];
}
Now display the result as shown in the complete code below.
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo {
   class Program {
      static void Main() {
         int i = 0;
         int pos;
         int[] arr = new int[5] {35, 50, 55, 77, 98};

         Console.WriteLine("Elements before deletion:");
         for (i = 0; i < 5; i++) {
            Console.WriteLine("Element[" + (i) + "]: "+arr[i]);
         }

         // Let's say the position to delete the item is 2 i.e. arr[1]
         pos = 2;
         // Shifting elements
         for (i = pos-1; i < 4; i++) {
            arr[i] = arr[i + 1];
         }
         Console.WriteLine("Elements after deletion: ");
         for (i = 0; i < 4; i++) {
            Console.WriteLine("Element[" + (i + 1) + "]: "+arr[i]);
         }
         Console.WriteLine();
      }
   }
}
Elements before deletion:
Element[0]: 35
Element[1]: 50
Element[2]: 55
Element[3]: 77
Element[4]: 98
Elements after deletion:
Element[1]: 35
Element[2]: 55
Element[3]: 77
Element[4]: 98
MATLAB - Transpose of a Matrix

The transpose operation switches the rows and columns in a matrix. It is represented by a single quote(').
Create a script file with the following code −
a = [ 10 12 23 ; 14 8 6; 27 8 9]
b = a'
When you run the file, it displays the following result −
a =
      10    12    23
      14     8     6
      27     8     9
b =
      10    14    27
      12     8     8
      23     6     9
How to get all ID of the DOM elements with JavaScript ?

31 Dec, 2019
Given a HTML document and the task is to get the all ID of the DOM elements in an array. There are two methods to solve this problem which are discusses below:
Approach 1:
First select all elements using $(‘*’) selector, which selects every element of the document.
Use .each() method to traverse all element and check if it has ID.
If it has ID then push it in the array.
Example: This example implements the above approach.
<!DOCTYPE HTML><html>  <head>    <title>        How to get all ID of the DOM        elements with JavaScript ?    </title>          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">    </script></head>  <body style="text-align:center;">          <h1 style="color: green">         GeeksForGeeks     </h1>          <p id="GFG_UP"></p>          <button onclick="gfg_Run()">        Click Here    </button>          <p id="GFG_DOWN" style="color:green;"></p>          <script>        var el_up = document.getElementById("GFG_UP");        var el_down = document.getElementById("GFG_DOWN");        el_up.innerHTML = "Click on the button to get "                            + "all IDs in an array.";          function gfg_Run() {            var ID = [];            $("*").each(function() {                if (this.id) {                    ID.push(this.id);                }            });            el_down.innerHTML = ID;        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
First select all elements using $(‘*’) selector, Which selects every element of the Document.
Use .map() method to traverse all element and check if it has ID.
If it has ID then push it in the array using .get() method.
Example 2: This example implements the above approach.
<!DOCTYPE HTML><html>  <head>    <title>        How to get all ID of the DOM        elements with JavaScript ?    </title>          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">    </script></head>  <body style="text-align:center;">          <h1 style="color: green">         GeeksForGeeks     </h1>          <p id="GFG_UP"></p>          <button onclick="gfg_Run()">        Click Here    </button>          <p id="GFG_DOWN" style="color:green;"></p>          <script>        var el_up = document.getElementById("GFG_UP");        var el_down = document.getElementById("GFG_DOWN");        el_up.innerHTML = "Click on the button to "                    + "get all IDs in an array.";          function gfg_Run() {            var ID = [];                          ID = $("*").map(function() {                if (this.id) {                    return this.id;                }            }).get();            el_down.innerHTML = ID;        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to check if the String is Empty in Java

22 Jan, 2020
Given a string str, the task is to check if this string is empty or not, in Java.
Examples:
Input: str = "" 
Output: True

Input: str = "GFG"
Output: False

Approach:
Get the String to be checked in str
We can simply check if the string is empty or not using the isEmpty() method of String classSyntax:if (str.isEmpty())

if (str.isEmpty())

Print true if the above condition is true. Else print false.
Below is the implementation of the above approach:
// Java Program to check if// the String is empty in Java  class GFG {      // Function to check if the String is empty    public static boolean isStringEmpty(String str)    {          // check if the string is empty or not        // using the isEmpty() method        // and return the result        if (str.isEmpty())            return true;        else            return false;    }      // Driver code    public static void main(String[] args)    {        String str1 = "GeeksforGeeks";        String str2 = "";          System.out.println("Is string \"" + str1                           + "\" empty? "                           + isStringEmpty(str1));        System.out.println("Is string \"" + str2                           + "\" empty? "                           + isStringEmpty(str2));    }}
Is string "GeeksforGeeks" empty? false
Is string "" empty? true

Java-String-Programs
Java
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
Write a program to reverse an array or string
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++
Check for Balanced Brackets in an expression (well-formedness) using Stack
How to get the maximum number of occupied rows and columns in a worksheet in Selenium with python?

We can get the maximum number of occupied rows and columns in a
worksheet in Selenium. Excel is a spreadsheet which is saved with the .xlsx
extension. An excel workbook has multiple sheets and each sheet consists of rows
and columns.
Out of all the worksheets, while we are accessing a particular sheet that is called as
an active sheet. Each cell inside a sheet has a unique address which is a combination
of row and column numbers.
The column number starts from alphabetic character A and row number starts from
the number 1. A cell can contain numerous types of values and they are the main
component of a worksheet.
To work with excel in Selenium with python, we need to take help of OpenPyXL
library. This library is responsible for reading and writing operations on Excel,
having the extensions like xlsx, xlsm, xltm, xltx.
To install OpenPyXL library, we have to execute the command pip install openpyxl. This is because OpenPyXL does not come by default with python. After this we should import openpyxl in our code and then we should be ready to interact with excel.
To get the count of the occupied rows in a worksheet, first of all we need to load
the entire workbook by specifying the path where it is located. This is achieved with
load_workbook() method. Next we need to identify the active sheet among all the
worksheets with the help of active method.
Finally we need to use the max_row method that gives the count of the number of
occupied rows. Please note this method is to be used with the worksheet level
object.
And we need to use the max_column method that gives the count of the number
of occupied columns. Please note this method is to be used with the worksheet
level object.
wrkbk = load_workbook("C:\\work\\SeleniumPython.xlsx")
# to identify the active sheet
sh = wrkbk.active
# identify the number of occupied rows
sh.max_row
# identify the number of occupied rows
sh.max_column
Coding Implementation to count the maximum number of occupied rows and
columns.
import openpyxl
# load excel with its path
wrkbk = load_workbook("C:\\work\\SeleniumPython.xlsx")
# to get the active work sheet
sh = wrkbk.active
# get the value of row 2 and column 3
c=sh.cell(row=2,column=3)
# to set the value in row 2 and column 3
sh.cell(row=2,column=3).value = "Tutorialspoint"
# to print the value in console
print(sh.cell(row=2,column=3).value)
# to print the maximum number of occupied rows in console
print(sh.max_row)
# to print the maximum number of occupied columns in console
print(sh.max_column)
Java Program to convert boolean to integer

To convert boolean to integer, let us first declare a variable of boolean primitive.
boolean bool = true;
Now, to convert it to integer, let us now take an integer variable and return a value “1” for “true” and “0” for “false”.
int val = (bool) ? 1 : 0;
Let us now see the complete example to convert boolean to integer in Java.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      // boolean
      boolean bool = true;
      System.out.println("Boolean Value: "+bool);
      int val = (bool) ? 1 : 0;
      // Integer
      System.out.println("Integer value: "+val);
   }
}
Boolean Value: true
Integer value: 1
Numpy ndarray.flatten() function | Python

22 Apr, 2020
numpy.ndarray.flatten() function return a copy of the array collapsed into one dimension.
Syntax : numpy.ndarray.flatten(order=’C’)
Parameters :order : [{‘C’, ‘F’, ‘A’, ‘K’}, optional] ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.
Return : [ndarray] A copy of the input array, flattened to one dimension.
Code #1 :
# Python program explaining# numpy.ndarray.flatten() function  # importing numpy as geek import numpy as geek  arr = geek.array([[5, 6], [7, 8]])  gfg = arr.flatten()  print( gfg )
Output :
[5 6 7 8]

 Code #2 :
# Python program explaining# numpy.ndarray.flatten() function  # importing numpy as geek import numpy as geek  arr = geek.array([[5, 6], [7, 8]])  gfg = arr.flatten('F')  print( gfg )
Output :
[5 6 7 8]

Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Set | difference()

31 May, 2020
The difference between the two sets in Python is equal to the difference between the number of elements in two sets. The function difference() returns a set that is the difference between two sets. Let’s try to find out what will be the difference between two sets A and B. Then (set A – set B) will be the elements present in set A but not in B and (set B – set A) will be the elements present in set B but not in set A.Example:
set A = {10, 20, 30, 40, 80}
set B = {100, 30, 80, 40, 60}

set A - set B = {10, 20}
set B - set A = {100, 60}

Explanation: A - B is equal to the elements present in A but not in B
             B - A is equal to the elements present in B but not in A

Let’s look at the Venn diagram of the following difference set function.
Syntax:
set_A.difference(set_B) for (A - B)
set _B.difference(set_A) for (B - A)

In this program, we will try to find out the difference between two sets set_A and set_B, both the way:
# Python code to get the difference between two sets# using difference() between set A and set B  # Driver CodeA = {10, 20, 30, 40, 80}B = {100, 30, 80, 40, 60}print (A.difference(B))print (B.difference(A))
{10, 20}
{100, 60}

We can also use – operator to find the difference between two sets.
# Python code to get the difference between two sets# using difference() between set A and set B  # Driver CodeA = {10, 20, 30, 40, 80}B = {100, 30, 80, 40, 60}print (A - B)print (B - A)
{10, 20}
{100, 60}

If we have equal sets then it will return the null set.
# Python code to get the difference between two sets# using difference() between set A and set B  # Driver CodeA = {10, 20, 30, 40, 80}B = {10, 20, 30, 40, 80, 100}print (A - B)
set()

Akanksha_Rai
vishnu_paregi
python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | <th> bgcolor Attribute

26 Jun, 2019
The HTML <th> bgcolor Attribute is used to specify the background color of a table header cell. It is not supported by HTML 5.
Syntax:
<th bgcolor="color_name | hex_number | rgb_number">
Attribute Values:
color_name: It sets the background color by using the color name. For example “red”.
hex_number: It sets the background color by using the color hex code. For example “#0000ff”.
rgb_number: It sets the background color by using the rgb code. For example: “RGB(0, 153, 0)” .
Example:
<!DOCTYPE html><html>  <head>    <title>      HTML th bgcolor Attribute  </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML th bgcolor Attribute</h2>      <table width="500" border="1">        <tr>            <th bgcolor="green">Name</th>            <th bgcolor="yellow">Expenses</th>        </tr>          <tr>            <td>BITTU</td>            <td>2500.00</td>        </tr>          <tr>            <td>RAKESH</td>            <td>1400.00</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <th> bgcolor attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Script to Logout Computer

14 Jul, 2019
As we know, Python is a popular scripting language because of its versatile features. In this article, we will write a Python script to logout a computer. Let’s start with how to logout the system with Python. To logout your computer/PC/laptop only by using a Python script, you have to use the os.system() function with the code “shutdown -l” . The shutdown -l command is the windows shell command for logging off.
Let’s start with how to log out the system with Python.
Note: For this to work, you have to import os library in the ide. If you don’t have it, then ‘pip install os‘ through the Command Prompt.
Causion: Please ensure that you save and close all the program before running this code on the IDLE, as the below program will immediately log out your computer.
Below is the Python implementation –
import os  logout = input("Do you wish to log out your computer ? (yes / no): ")  if logout == 'no':    exit()else:    os.system("shutdown -l")
Output:Here is the Python Program which will ask the user to log out the computer providing the option of Yes or No. Also, when you type yes & then press the ENTER key, the system will be log out instantly.
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set Background Color in HTML ?

01 Apr, 2021
In this article, we will see how to set the background color of an element. The purpose of using style attribute is to add styles to the elements. Using style attribute with different elements results in change in that element only. This attribute can be used as inline, internal or external. The style attribute provides number of properties which can be used to improve a simple html page.
The background color can be changed in three ways:
Inline style attribute
Internal CSS
External CSS
The HTML5 doesn’t support the ‘bgcolor’ attribute of <body> tag, therefore we need to use the inline style attribute and internal CSS options for changing the color of a web page. For internal CSS add <style> tag at beginning of html file and add the tag to which the changes are being applied in this case the <body> tag is used.
Syntax:
/* For inline style attribute */
<tag style="property:value">

/* For internal CSS attribute */
<style>
  tagName{
    property:value;
  }
</style>
Example 1: Below is the example that illustrates the use of inline CSS.
HTML
<!DOCTYPE html><html>  <!--This line changes the color of background--><body style="background-color:pink">    <h1 style="color:green;text-align:center;">        GeeksForGeeks    </h1>      <h3 style="text-align:center;">        How to change color of Background?    </h3></body>  </html>
Output: This will be displayed when html file is opened in browser.
Example 2: Below is the example that illustrates the use of internal CSS.
HTML
<!DOCTYPE html><html>  <head>    <style>        body {            background-color: powderblue;        }          h1 {            color: green;            text-align: center;        }          h3 {            text-align: center;        }    </style></head>  <body>    <h1>GeeksForGeeks</h1>      <h3>        How to change color of        Background?(Using Internal CSS)    </h3></body>  </html>
Output:This will be displayed when html file is opened in browser
External CSS: In external CSS, we create a separate file which has all the style data for the html file. Storing the file externally makes it easier to apply changes to the HTML page.
CSS-Properties
CSS-Questions
HTML-Attributes
HTML-Questions
HTML-Tags
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js URL.href API

14 Oct, 2021
The url.href is an inbuilt application programming interface of class URL with in the url module which Gets and sets the serialized URL. Getting the value of the href property is equivalent to calling the url.toString() method.Setting the value of this property to a new value is equivalent to creating a new URL object using new URL(value). Each of the URL object’s properties will be modified. 
Syntax:  
const url.href 
Return value: It gets and sets the serialized URL.Below programs illustrate the use of url.href Method:Example 1:  
javascript
// node program to demonstrate the // url.href API as Setter    //importing the module 'url'const http = require('url');   // creating and initializing myURLconst myURL = new URL('https://example.com:80/foo#ram');   // Display href value of myURL before changeconsole.log("Before Change");console.log(myURL.href);   // assigning serialized URL// using hrefconsole.log();myURL.href = 'https://example.com/bar';   // Display href value of myURL after changeconsole.log("After Change");console.log(myURL.href);
Output:  
Example 2: 
javascript
// node program to demonstrate the // url.href API as Getter   //importing the module 'url'const http = require('url');  // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram');  // getting the serialized URL// using hrefconst href = myURL.href;  // Display hostname value console.log(href);
Output:  
Reference: https://nodejs.org/api/url.html#url_url_href
mridulmanochagfg
sweetyty
Node-URL
Node.js
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Installation of Node.js on Windows
Node.js forEach() function
What are the differences between npm and npx ?
How to read and write Excel file in Node.js ?
Difference between dependencies, devDependencies and peerDependencies
Threaded Port Scanner using Sockets in Python - GeeksforGeeks

28 Aug, 2020
Port scanning can be really slow yet, in most cases, is not process intensive. Thus, we can use threading to improve our speed. There can be thousands of possible ports. If it takes 5-15 seconds per port to scan, then we might have a long wait ahead of us without the use of threading.
Threading is a complex topic, but it can be broken down and conceptualized as a methodology where we can tell the computer to do another task if the processor is experiencing idle time. In the case of port scanning, we are spending a lot of time just waiting on the response from the server. While we are waiting, we can do something else. That is what threading is used for. 
Example: In this program, we can scan a number of ports in a certain range.
Python3
import threadingfrom queue import Queueimport timeimport socket  # a print_lock is used to prevent "double"# modification of shared variables this is# used so that while one thread is using a# variable others cannot access it Once it# is done, the thread releases the print_lock.# In order to use it, we want to specify a# print_lock per thing you wish to print_lock.print_lock = threading.Lock()  # ip = socket.gethostbyname(target)target = 'localhost'  def portscan(port):    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    try:        con = s.connect((target, port))        with print_lock:            print('port is open', port)        con.close()    except:        print('port is close', port)    # The threader thread pulls a worker # from a queue and processes itdef threader():    while True:        # gets a worker from the queue        worker = q.get()          # Run the example job with the available         # worker in queue (thread)        portscan(worker)          # completed with the job        q.task_done()    # Creating the queue and threaderq = Queue()  # number of threads are we going to allow forfor x in range(4):    t = threading.Thread(target=threader)      # classifying as a daemon, so they it will    # die when the main dies    t.daemon = True      # begins, must come after daemon definition    t.start()    start = time.time()  # 10 jobs assigned.for worker in range(1, 10):    q.put(worker)  # wait till the thread terminates.q.join()
Output: 
port is close 2
port is close port is close 4
port is closeport is close 1
 53

port is close 6port is close
 7
port is close 8
port is close 9
Python-threading
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python - assertLessEqual() function in unittest - GeeksforGeeks

24 Oct, 2020
assertLessEqual() in Python is an unittest library function that is used in unit testing to check whether the first given value is less than or equal to the second value or not. This function will take three parameters as input and return a boolean value depending upon the assert condition.
This function checks that if the first given value is less than or equal to the second value and returns true if it is so, else return false if the first value is not less than or equal to the second value.
Syntax: assertLessEqual(first, second, message=None)
Parameters: assertLessEqual() accept three parameters which are listed below with explanation:
first: first input value (integer)
second:  second input value (integer)
message: a string sentence as a message which got displayed when the test case got failed.
Listed below is an example illustrating the positive and negative test case for given assert function:
Example 1:
Python3
# test suiteimport unittest  class TestStringMethods(unittest.TestCase):        # negative test function to test if values1 is less or equal than value2    def test_negativeForLessEqual(self):        first = 6        second = 5                  # error message in case if test case got failed        message = "first value is not less than or equal to second value."                  # assert function() to check if values1 is less or equal than value2        self.assertLessEqual(first, second, message)  if __name__ == '__main__':    unittest.main()
Output:
F======================================================================FAIL: test_negativeForLessEqual (__main__.TestStringMethods)———————————————————————-Traceback (most recent call last): File “p1.py”, line 13, in test_negativeForLessEqual   self.assertLessEqual(first, second, message)AssertionError: 6 not less than or equal to 5 : first value is not less than or equal to second value.
———————————————————————-Ran 1 test in 0.000s
FAILED (failures=1)
Example 2:
Python
# test suiteimport unittest  class TestStringMethods(unittest.TestCase):        # positive test function to test if value1 is less or equal than value2    def test_positiveForLessEqual(self):        first = 4        second = 4                  # error message in case if  test case got failed        message = "first value is not less than or equal to second value."                  # assert function() to check if values1 is less or equal than value2        self.assertLessEqual(first, second, message)    if __name__ == '__main__':    unittest.main()
Output:
.———————————————————————-Ran 1 test in 0.000s
OK
Python unittest-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Pandas Dataframe.iat[ ] - GeeksforGeeks

16 Jul, 2021
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 iat[] method is used to return data in a dataframe at the passed location. The passed location is in the format [position in the row, position in the column]. This method works similarly to Pandas iloc[] but iat[] is used to return only a single value and hence works faster than it.
Syntax: Dataframe.iat[row, column]Parameters: position: Position of element in column label: Position of element in rowReturn type: Single element at passed position  
To download the data set used in the following example, click here.
In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: In this example, A dataframe is created by passing URL of csv to Pandas .read_csv() method. After that 3 is passed as column position and 7 as the position in row and value at that position is returned using .iat[ ] method. 
Python3
# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # creating column and row variablescolumn = 7row = 3     # calling .iat[] methodoutput = data.iat[row, column] # displayprint(output) # df displaydata.head()
Output: As shown in the output image, the output can be compared and it can be seen that the Value of the 3rd element in the 7th column was returned. 
Note:  
Unlike, .iloc[ ], This method only returns single value. Hence, dataframe.at[3:6, 4:2] will return an error
Since this method only works for single values, it is faster than .iloc[] method
 
debjyotidasadhikary
surindertarika1234
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Reading and Writing to text files in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
sum() function in Python
numpy.unwrap() in Python - GeeksforGeeks

05 Jul, 2021
numpy.unwrap(p, discount=3.141592653589793, axis=-1) function helps user to unwrap a given array by changing deltas to values of 2*pi complement. It unwraps radian phase p by changing absolute jumps greater than discount to their 2*pi complement along the given axis. Result is an unwrapped array. 
Parameters:p : [array like] input array discount : [float, optional] Maximum discontinuity between values, default is pi axis : [int, optional] Axis along which unwrap will operate, default is last axisReturns: [ndarray] output array
Note: If the discontinuity in p is smaller than pi, but larger than discount, no unwrapping is done because taking the 2*pi complement would only make the discontinuity larger.Code #1: Default Values Working  
Python3
import numpy as np l1 =[1, 2, 3, 4, 5]print("Result 1: ", np.unwrap(l1)) l2 =[0, 0.78, 5.49, 6.28]print("Result 2: ", np.unwrap(l2))
Output:  
Result 1: array([1., 2., 3., 4., 5.])
Result 2: array([ 0.,  0.78, -0.79318531, -0.00318531])
In l2, discount > 2*pi (between 0.78 and 5.49), so array values are changed.Code #2: Custom Values Working  
Python3
import numpy as np l1 =[5, 7, 10, 14, 19, 25, 32]print("Result 1: ", np.unwrap(l1, discount = 4)) l2 =[0, 1.34237486723, 4.3453455, 8.134654756, 9.3465456542]print("Result 2: ", np.unwrap(l2, discount = 3.1))
Output:  
Result 1: [ 5., 7., 10., 7.71681469, 6.43362939, 6.15044408, 6.86725877] Result 2: [0., 1.34237487, 4.3453455, 1.85146945, 3.06336035]
References: https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.unwrap.html 
singghakshay
Picked
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Change Icon for Tkinter MessageBox - GeeksforGeeks

10 May, 2020
We know many modules and one of them is Tkinter. Tkinter is a module which is a standard interface of Python to the Tk GUI toolkit. This interface Tk and the Tkinter modules, both of them are available on most of the Unix platforms. it is also available on Windows OS and many others. But it is usually a shared library or DLL file, for some cases, it is statically linked with the Python interpreter.
Whenever we create a message box using the Tkinter, we always see a similar icon in the message box. Let us see it again with an example.
Example:
import tkinter as tk    win = tk.Tk()  # as it does not have any mentions # of the icon we get a default icon.win.title("example") win.mainloop()
Output :
In the above example, within the circle that is the default icon we get, when it is not mentioned in the code. And yes, we can change it according to our wishes. Select the photo you want to keep it as an icon. Select and then [Right click–> Properties]. Type of File you see will be in the format of (.png).
But we need it in the format of (.ico). There might be a question that why we need to convert .png to .ico? Why can’t we use it in the format of .png? For that, the answer will be the icon bitmap function (depending on the programming language) should be used to set a bitmap image to the window when the window is iconified. For that just search online for online icoconverter, go there, and simply convert the image you want to convert it to (.ico). So we got our image ready to the desired format, next get back to the coding part and let’s learn how to change the default icon to our selected icon follow the steps.
Step 1: Add a line, defining the icon bitmap i.e. win.iconbitmap(r”)
import tkinter as to


win = tk.Tk()
win.title("example")
win.iconbitmap(r'')
win.mainloop()
Step 2: Mentioning the file path of the image we want as an icon. Copy the File location and paste it inside “win.iconbitmap(r”)”.
win.iconbitmap(r'C:\Users\Madhusudan\Downloads\')
Step 3: Mention the file name. Copy the file name and paste it after “\” where you mentioned the file location.
win.iconbitmap(r'C:\Users\Madhusudan\Downloads\favicon(2).ico')

Finally, we get the complete code for how we can change the icon. Let’s put it together.
import tkinter as tk    win = tk.Tk()win.title("example")win.iconbitmap(r'C:\Users\Madhusudan\Downloads\favicon(2).ico')  win.mainloop() 
Output :
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Perform Bubble Sort on strings in Java

To perform Bubble Sort, try the below given code. In this each each pair of adjacent elements is compared and the elements are swapped if they are not in order.
The following is an example.
 Live Demo
public class Demo {
   public static void main(String []args) {
      String str[] = { "s", "k", "r", "v", "n"};
      String temp;
      System.out.println("Sorted string...");
      for (int j = 0; j < str.length; j++) {
         for (int i = j + 1; i < str.length; i++) {
            // comparing strings
            if (str[i].compareTo(str[j]) < 0) {
               temp = str[j];
               str[j] = str[i];
               str[i] = temp;
            }
         }
         System.out.println(str[j]);
      }
   }
}
Sorted string...
k
n
r
s
v
How to specify values on Y-axis in Python Matplotlib?

To specify values on Y-axis in Python, we can take the following steps−
Create x and y data points using numpy.
To specify the value of axes, create a list of characters.
Use xticks and yticks method to specify the ticks on the axes with x and y ticks data points respectively.
Plot the line using x and y, color=red, using plot() method.
Make x and y margin 0.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.array([0, 2, 4, 6])
y = np.array([1, 3, 5, 7])
ticks = ['a', 'b', 'c', 'd']
plt.xticks(x, ticks)
plt.yticks(y, ticks)
plt.plot(x, y, c='green')
plt.margins(x=0, y=0)
plt.show()
Jackson Annotations - @JsonManagedReference

@JsonManagedReferences and JsonBackReferences are used to display objects with parent child relationship. @JsonManagedReferences is used to refer to parent object and @JsonBackReferences is used to mark child objects.
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();     
      Student student = new Student(1, "Mark");
      Book book1 = new Book(1,"Learn HTML", student);
      Book book2 = new Book(1,"Learn JAVA", student);

      student.addBook(book1);
      student.addBook(book2);

      String jsonString = mapper 
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(book1);
      System.out.println(jsonString);
   }
}
class Student {
   public int rollNo;
   public String name;

   @JsonBackReference
   public List<Book> books;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
      this.books = new ArrayList<Book>();
   }
   public void addBook(Book book){
      books.add(book);
   }
}
class Book {
   public int id;
   public String name;

   Book(int id, String name, Student owner){
      this.id = id;
      this.name = name;
      this.owner = owner;
   }
   @JsonManagedReference
   public Student owner;
}
{
   "id" : 1,
   "name" : "Learn HTML",
   "owner" : {
      "rollNo" : 1,
      "name" : "Mark"
   }
}

 Print
 Add Notes
 Bookmark this page
MySQL case statement inside a select statement?

For this, you can use CASE WHEN statement. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> FirstName varchar(20),
   -> Score int
   -> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John',46);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('John',78);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('John',69);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Chris',78);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Chris',89);
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+-------+
| FirstName | Score |
+-----------+-------+
| John      |    46 |
| John      |    78 |
| John      |    69 |
| Chris     |    78 |
| Chris     |    89 |
+-----------+-------+
5 rows in set (0.00 sec)
Following is the query to implement case statement inside a select statement −
mysql> select FirstName,max(case when Score=69 then 1 else 0 end ) as isExistsOrNot
   -> from DemoTable
   -> group by FirstName;
This will produce the following output −
+-----------+---------------+
| FirstName | isExistsOrNot |
+-----------+---------------+
| John      |             1 |
| Chris     |             0 |
+-----------+---------------+
2 rows in set (0.00 sec)
Difference between ArrayList and HashSet in Java

HashSet and ArrayList both are some of the most important classes of the Java Collection framework.
The following are the important differences between ArrayList and HashSet.
JavaTester.java
 Live Demo
import java.io.*;
import java.util.*;
public class JavaTester {
   public static void main(String[] args) throws IOException{
      int n = 5;
      List<Integer> al = new ArrayList<>(n);
      for (int i = 1; i <= n; i++) {
         al.add(i);
      }
      System.out.println(al);
      al.remove(3);
      System.out.println(al);
      for (int i = 0; i < al.size(); i++) {
         System.out.print(al.get(i) + " ");
      }
   }
}

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5
JavaTester.java
import java.util.HashSet;
import java.util.Set;
public class JavaTester {
   public static void main(String[] args){
      Set<Integer> hs = new HashSet<>();
      hs.add(1);
      hs.add(2);
      hs.add(3);
      hs.add(4);
      hs.add(4);
      for (Integer temp : hs) {
         System.out.print(temp + " ");
      }
   }
}

1 2 3 4
html.escape() in Python

22 Apr, 2020
With the help of html.escape() method, we can convert the html script into a string by replacing special characters with the string with ascii characters by using html.escape() method.
Syntax : html.escape(String)
Return : Return a string of ascii character script from html.
Example #1 :In this example we can see that by using html.escape() method, we are able to convert the html script to ascii string by using this method.
# import htmlimport html  s = '<html><head></head><body><h1>This is python</h1></body></html>'# Using html.escape() methodgfg = html.escape(s)  print(gfg)
Output :
<html><head></head><body><h1>This is python</h1></body></html>
Example #2 :
# import htmlimport html  s = '<html><head></head><body><h1>GeeksForGeeks</h1></body></html>'# Using html.escape() methodgfg = html.escape(s)  print(gfg)
Output :
<html><head></head><body><h1>GeeksForGeeks</h1></body></html>
Python html-module
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
PHP program to check if a number is prime or not

To check if a number is prime or not, the code is as follows −
 Live Demo
<?php
function check_prime($num)
{
   if ($num == 1)
   return 0;
   for ($i = 2; $i <= $num/2; $i++)
   {
      if ($num % $i == 0)
      return 0;
   }
   return 1;
}
$num = 47;
$flag_val = check_prime($num);
if ($flag_val == 1)
   echo "It is a prime number";
else
   echo "It is a non-prime number"
?>
It is a prime number
A function named ‘check_prime’ is used to check if the number is prime or not. A number that needs to be checked for being prime is passed as a parameter to the function. The number is defined and this function is called by passing the number as parameter. Relevant message is displayed on the console.
GATE | GATE CS 2010 | Question 36

28 Jun, 2021
The following C function takes a simply-linked list as input argument. It modifies the list by moving the last element to the front of the list and returns the modified list. Some part of the code is left blank.
typedef struct node {  int value;  struct node *next;}Node;   Node *move_to_front(Node *head) {  Node *p, *q;  if ((head == NULL: || (head->next == NULL))     return head;  q = NULL; p = head;  while (p-> next !=NULL)   {    q = p;    p = p->next;  }  _______________________________  return head;}
Choose the correct alternative to replace the blank line.(A) q = NULL; p->next = head; head = p;(B) q->next = NULL; head = p; p->next = head;(C) head = p; p->next = q; q->next = NULL;(D) q->next = NULL; p->next = head; head = p;Answer: (D)Explanation: When the while loop ends, q contains address of second last node and p contains address of last node. So we need to do following things after while loop.i) Set next of q as NULL (q->next = NULL).ii) Set next of p as head (p->next = head).iii) Make head as p ( head = p)Step (ii) must be performed before step (iii). If we change head first, then we lose track of head node in the original linked list.See https://www.geeksforgeeks.org/move-last-element-to-front-of-a-given-linked-list/ for more details.Quiz of this Question
GATE-CS-2010
GATE-GATE CS 2010
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2010 | Question 19

21 Dec, 2021
A relational schema for a train reservation database is given below.Passenger (pid, pname, age)Reservation (pid, class, tid)
Table: Passenger
pid   pname   age
-----------------
 0    Sachin   65
 1    Rahul    66
 2    Sourav   67
 3    Anil     69

Table : Reservation
pid  class  tid
---------------
 0    AC   8200
 1    AC   8201
 2    SC   8201
 5    AC   8203
 1    SC   8204
 3    AC   8202
What pids are returned by the following SQL query for the above instance of the tables?
SELECT pid
FROM Reservation ,
WHERE class ‘AC’ AND
    EXISTS (SELECT *
       FROM Passenger
       WHERE age > 65 AND
       Passenger. pid = Reservation.pid)
(A) 1, 0(B) 1, 2(C) 1, 3(D) 1, 5Answer: (C)Explanation: When a subquery uses values from outer query, the subquery is called correlated subquery. The correlated subquery is evaluated once for each row processed by the outer query.
The outer query selects 4 entries (with pids as 0, 1, 5, 3) from Reservation table. Out of these selected entries, the subquery returns Non-Null values only for 1 and 3.Quiz of this Question
ManasChhabra2
GATE-CS-2010
GATE-GATE CS 2010
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
numpy.tanh() in Python

04 Dec, 2020
The numpy.tanh()is a mathematical function that helps user to calculate hyperbolic tangent for all x(being the array elements).
Equivalent to np.sinh(x) / np.cosh(x) or -1j * np.tan(1j*x).
Syntax : numpy.tanh(x[, out]) = ufunc ‘tanh’)Parameters :
array : [array_like] elements are in radians.2pi Radians = 36o degrees
Return : An array with hyperbolic tangent of x for all x i.e. array elements
 Code #1 : Working
# Python3 program explaining# tanh() function  import numpy as npimport math  in_array = [0, math.pi / 2, np.pi / 3, np.pi]print ("Input array : \n", in_array)  tanh_Values = np.tanh(in_array)print ("\nTangent Hyperbolic values : \n", tanh_Values)
Output :
Input array : 
 [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]

Tangent Hyperbolic values : 
 [ 0.          0.91715234  0.78071444  0.99627208]

 Code #2 : Graphical representation
# Python program showing Graphical# representation of tanh() functionimport numpy as npimport matplotlib.pyplot as plt  in_array = np.linspace(-np.pi, np.pi, 12)out_array = np.tanh(in_array)  print("in_array : ", in_array)print("\nout_array : ", out_array)  # red for numpy.tanh()plt.plot(in_array, out_array, color = 'red', marker = "o")plt.title("numpy.tanh()")plt.xlabel("X")plt.ylabel("Y")plt.show()
Output :
in_array :  [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798   -0.28559933
  0.28559933  0.856798    1.42799666  1.99919533  2.57039399  3.14159265]

out_array :  [-0.99627208 -0.98836197 -0.96397069 -0.89125532 -0.69460424 -0.27807943
  0.27807943  0.69460424  0.89125532  0.96397069  0.98836197  0.99627208]
 References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.tanh.html#numpy.tanh.
Python numpy-Mathematical Function
Python-numpy
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
Convert integer to string in Python