code-rag-bench/online-tutorials huggingface dataset:
Customizing termination behavior for uncaught exception In C++ - GeeksforGeeks

15 Apr, 2018
Whenever an exception arises in C++, it is handled as per the behavior defined using the try-catch block. However, there is often the case when an exception is thrown but isn’t caught because the exception handling subsystem fails to find a matching catch block for that particular exception. In that case, the following set of actions takes place:
The exception handling subsystem calls the function: unexpected(). This function, provided by the default C++ library, defines the behavior when an uncaught exception arises. By default, unexpected calls terminate().The terminate function defines the actions that are to be performed during process termination. This, by default, calls abort().The process is aborted.
The exception handling subsystem calls the function: unexpected(). This function, provided by the default C++ library, defines the behavior when an uncaught exception arises. By default, unexpected calls terminate().
The terminate function defines the actions that are to be performed during process termination. This, by default, calls abort().
The process is aborted.
The terminate() and unexpected() simply call other functions to actually handle an error. As explained above, terminate calls abort(), and unexpected() calls terminate(). Thus, both functions halt the program execution when an exception handling error occurs. However, you can change the way termination occurs.
To change the terminate handler, the function used is set_terminate(terminate_handler newhandler), which is defined in the header <exception>.
The following program demonstrates how to set a custom termination handler:
// CPP program to set a new termination handler// for uncaught exceptions.#include <exception>#include <iostream>using namespace std;  // definition of custom termination functionvoid myhandler(){    cout << "Inside new terminate handler\n";    abort();}  int main(){    // set new terminate handler    set_terminate(myhandler);     try {        cout << "Inside try block\n";        throw 100;    }    catch (char a) // won't catch an int exception    {        cout << "Inside catch block\n";    }    return 0;}
Output:
Inside try block
Inside new terminate handler

Runtime Error:
Abort signal from abort(3) (SIGABRT)
It is to be duly noted that the only thing that your custom terminate handler must do is stop the program execution. It must not return to the program or resume it in any way.
cpp-exception
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Map in C++ Standard Template Library (STL)
Inheritance in C++
Constructors in C++
C++ Classes and Objects
Socket Programming in C/C++
Bitwise Operators in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
Virtual Function in C++
Finding the nth missing number from an array JavaScript

Suppose, we have a strictly increasing sequence of number (increasing by a unit) in which some elements are missing like this −
const arr = [2,3,4,7,11];
We are required to write a JavaScript function that takes in one such array as the first argument and a single number, say n, as the second argument.
The function should find the nth element that missing from the array.
For example −
If for the above array, n = 4;
Then the output should be 8, because
The missing elements are −
1, 5, 6, 8
const arr = [2, 3, 4, 7, 11];
const findMissing = (arr = [], n) => {
   let el = 0;
   let diff = 0;
   for(let i=0; i<arr.length; ++i) {
      const difference = arr[i] - el - 1;
      const sum = diff + difference;
      if(sum>=n) {
         break;
      };
      diff = sum;
      el = arr[i];
   }
   return el + n - diff;
};
console.log(findMissing(arr, 4));
This will produce the following output −
8
Average of ASCII values of characters of a given string?

Here we will see how to count the average of the ASCII values of each character in a given string. Suppose the string is “ABC”. The asci values are 65, 66, 67. So the average of these three is 66.
Begin
   sum := 0
   for each character c in String, do
      sum := sum + ASCII of c
   done
   return sum/length of String
End
 Live Demo
#include<iostream>
using namespace std;
float asciiAverage(string str){
   int sum = 0;
   for(int i = 0; i<str.size(); i++){
      sum += int(str[i]);
   }
   return sum/str.size();
}
main() {
   string str;
   cout << "Enter a string: ";
   cin >> str;
   cout << "ASCII average is: " << asciiAverage(str);
}
Enter a string: Hello
ASCII average is: 100
\hphantom - Tex Command

\hphantom - horizontal phantom.
{ \hphantom #1 }
The box created by \hphantom has the width of its argument, but its height and depth are zero (so it doesn't contribute to any vertical spacing issues). In other words, \hphantom   creates horizontal space equal to that produced by its argument, but doesn't create any vertical space.

\begin{array}{l}
\text{Side Angle Side}\\
\text{S}\hphantom{\text{ide }}\text{A}\hphantom{\text{ngle }}\text{S}
\end{array}

Side Angle SideSide Angle S



\begin{array}{l}
\text{Side Angle Side}\\
\text{S}\hphantom{\text{ide }}\text{A}\hphantom{\text{ngle }}\text{S}
\end{array}

Side Angle SideSide Angle S


\begin{array}{l}
\text{Side Angle Side}\\
\text{S}\hphantom{\text{ide }}\text{A}\hphantom{\text{ngle }}\text{S}
\end{array}

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Java Program to create a boolean variable from string

Use the parseBoolean() method to create a boolean variable from a string. Here for boolean variable, firstly take a boolean and pass the string to it using Boolean.parseBoolean().
boolean val1 = Boolean.parseBoolean("TRUE");
The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
Do the same for FALSE as well.
boolean val2 = Boolean.parseBoolean("FALSE");
Let us now see the complete example to form a boolean variable from string.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      boolean val1 = Boolean.parseBoolean("TRUE");
      System.out.println(val1);
      boolean val2 = Boolean.parseBoolean("FALSE");
      System.out.println(val2);
   }
}
true
false
Calculating variance for an array of numbers in JavaScript

We are required to write a JavaScript function that takes in an array of numbers sorted in increasing order.
Our function should calculate the variance for the array of numbers. Variance of a set of numbers is calculated on the basis of their mean.
Mean(M)=(∑i=0n−1arr[i]) / n
And variance (V) = (∑i=0n−1(arr[i]−M)2) / n
Following is the code −
 Live Demo
const arr = [4, 6, 7, 8, 9, 10, 10];
const findVariance = (arr = []) => {
   if(!arr.length){
      return 0;
   };
   const sum = arr.reduce((acc, val) => acc + val);
   const { length: num } = arr;
   const median = sum / num;
   let variance = 0;
   arr.forEach(num => {
      variance += ((num - median) * (num - median));
   });
   variance /= num;
   return variance;
};
console.log(findVariance(arr))
4.204081632653061
How to use <jsp:setProperty> action in JSP?

The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action. There are two basic ways to use the setProperty action −
You can use jsp:setProperty after, but outside of a jsp:useBean element, as given below −
<jsp:useBean id = "myName" ... />
...
<jsp:setProperty name = "myName" property = "someProperty" .../>
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as given below −
<jsp:useBean id = "myName" ... >
   ...
   <jsp:setProperty name = "myName" property = "someProperty" .../>
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.
Following table lists out the attributes associated with the setProperty action −
Let us define a test bean that will further be used in our example −
/* File: TestBean.java */
package action;

public class TestBean {
   private String message = "No message specified";
   public String getMessage() {
      return(message);
   }
   public void setMessage(String message) {
      this.message = message;
   }
}
Compile the above code to the generated TestBean.class file and make sure that you copied the TestBean.class in C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and the CLASSPATH variable should also be set to this folder −
Now use the following code in main.jsp file. This loads the bean and sets/gets a simple String parameter −
<html>
   <head>
      <title>Using JavaBeans in JSP</title>
   </head>
   <body>
      <center>
         <h2>Using JavaBeans in JSP</h2>
         <jsp:useBean id = "test" class = "action.TestBean" />
         <jsp:setProperty name = "test" property = "message" value = "Hello JSP..." />
         <p>Got message....</p>
         <jsp:getProperty name = "test" property = "message" />
      </center>
   </body>
</html>
Let us now try to access main.jsp, it would display the following result −
Got message....
Hello JSP...
How to launch activity only once when Android app is opened for the first time?

This example demonstrates about How to launch activity only once when Android app is opened for the first time.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:gravity="center"
      android:text="I will be launched once only" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   String prevStarted = "prevStarted";
   @Override
   protected void onResume() {
      super.onResume();
      SharedPreferences sharedpreferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
      if (!sharedpreferences.getBoolean(prevStarted, false)) {
         SharedPreferences.Editor editor = sharedpreferences.edit();
         editor.putBoolean(prevStarted, Boolean.TRUE);
         editor.apply();
      } else {
         finish();
      }
   }
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
How to display HTML in TextView in Android?

In Some situations, we should need to show HTML as text in android. Here is the simple solution to show HTML in TextView in android.
Step 1 − Create a new project in Android Studio,go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:tools = "http://schemas.android.com/tools"
   android:id = "@+id/rootview"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:orientation = "vertical"
   tools:context = ".MainActivity">
   <TextView
      android:id = "@+id/htmlToTextView"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v4.text.HtmlCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   String htmlText = "<h2>What is Android?</h2>\n" + "<p>Android is an open source and Linux-based <b>Operating System</b> for mobile devices such as smartphones and tablet computers.
Android was developed by the <i>Open Handset Alliance</i>, led by Google, and other companies.</p>\n" + "<p>Android offers a unified approach to application development for mobile devices which means developers need only develop for Android, and their applications should be able to run on different devices powered by Android.</p>\n" + "<p>The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007 whereas the first commercial version, Android 1.0, was released in September 2008.</p>";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView htmlToTextView = findViewById(R.id.htmlToTextView);
      htmlToTextView.setText(HtmlCompat.fromHtml(htmlText, 0));
   }
}
In the above example, we kept HTML tags in a string as htmlText and added string to textview as shown below.
htmlToTextView.setText(HtmlCompat.fromHtml(htmlText, 0));
In the above code we are taking HTML data from fromHtml() and appending to textview using setText() . 0 is a flag. you can assign flag as per project resource.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above example, it showing HTML tags a string.
Display all the Files in Perl

There are various ways to list down all the files available in a particular directory using Perl. First let's use the simple way to get and list down all the files using the glob operator −
#!/usr/bin/perl
# Display all the files in /tmp directory.
$dir = "/tmp/*";
my @files = glob( $dir );
foreach (@files ) {
   print $_ . "\n";
}
# Display all the C source files in /tmp directory.
$dir = "/tmp/*.c";
@files = glob( $dir );
foreach (@files ) {
   print $_ . "\n";
}
# Display all the hidden files.
$dir = "/tmp/.*";
@files = glob( $dir );
foreach (@files ) {
   print $_ . "\n";
}
# Display all the files from /tmp and /home directories.
$dir = "/tmp/* /home/*";
@files = glob( $dir );
foreach (@files ) {
   print $_ . "\n";
}
Here is another example, which opens a directory and list out all the files available inside this directory.
#!/usr/bin/perl
opendir (DIR, '.') or die "Couldn't open directory, $!";
while ($file = readdir DIR) {
   print "$file\n";
}
closedir DIR;
One more example to print the list of C source files you might use is −
#!/usr/bin/perl
opendir(DIR, '.') or die "Couldn't open directory, $!";
foreach (sort grep(/^.*\.c$/,readdir(DIR))) {
   print "$_\n";
}
closedir DIR;
How can we create an exception filter to handle unhandled exceptions in C#
ASP.NET WebAPI?

An exception filter is executed when a controller method throws any unhandled
exception that is not an HttpResponseException exception. The
HttpResponseException type is a special case, because it is designed specifically for
returning an HTTP response.
Exception filters implement the System.Web.Http.Filters.IExceptionFilter interface.
The simplest way to write an exception filter is to derive from the
System.Web.Http.Filters.ExceptionFilterAttribute class and override the
OnException method.
Below is a filter that converts NotFiniteNumberException exceptions into HTTP status code 416, Requested Range Not Satisfiable.
ExceptionFilterAttribute −
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
namespace DemoWebApplication.Controllers{
   public class ExceptionAttribute : ExceptionFilterAttribute{
      public override void OnException(HttpActionExecutedContext context){
         if (context.Exception is NotFiniteNumberException){
            context.Response = new HttpResponseMessage(HttpStatusCode.RequestedRangeNotSatisfiable);
         }
      }
   }
}
Controller ActionMethod −
using DemoWebApplication.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   [Exception]
   public class StudentController : ApiController{
      List<Student> students = new List<Student>{
         new Student{
            Id = 1,
            Name = "Mark"
         },
         new Student{
            Id = 2,
            Name = "John"
         }
      };
      public Student Get(int id){
         if(id <= 0){
            throw new NotFiniteNumberException("The Id is not valid");
         }
         var studentForId = students.FirstOrDefault(x => x.Id == id);
         return studentForId;
      }
   }
}
So let us test the above ExceptionAttribute by passing id = 0 for the controller action method.
The ExceptionAttribute can be registered by any of te following approaches.
Decorate Action with exception filter.
Decorate Action with exception filter.
[Exception]
   public IHttpActionResult Get(int id){
   Return Ok();
}
Decorate Controller with exception filter.
Decorate Controller with exception filter.
[Exception]
public class StudentController : ApiController{
   public IHttpActionResult Get(int id){
      Return Ok();
   }
}
Register exception globally in WebApiConfig.cs.
Register exception globally in WebApiConfig.cs.
public static class WebApiConfig{
   public static void Register(HttpConfiguration config){
      config.Filters.Add(new ExceptionAttribute());
   }
}
Add two numbers represented by linked lists?

Here we will see how to add two numbers stored into separate linked list. In the linked list, each digit of the numbers is stored. If the number is 512, then it will be stored like below −
512 = (5)-->(1)-->(2)-->NULL
We are providing two lists of this type, our task is to add them and get the result after calculating the sum. Here we are using the C++ STL linked list. Let us see the algorithm to bet better idea.
Begin
   Adjust the l1 and l2 lengths by adding leading 0s with the smaller one
   carry := 0
   res := an empty list
   for each node n from l1, scan from last to first, do
      item := (l1.item + l2.item + carry) mod 10
      insert item at the beginning of res
      carry := (l1.item + l2.item + carry) / 10
   done
   if carry is not 0, then
      add carry at the beginning of res
   end if
   return res
End
#include<iostream>
#include<list>
using namespace std;
list addListNumbers(list<int> l1, list<int> l2){
   //add leading 0s to the shortest number to make them equal length
   if(l1.size() > l2.size()){
      for(int i = l2.size(); i != l1.size(); i++){
         l2.push_front(0);
      }
   }else if(l1.size() < l2.size()){
      for(int i = l1.size(); i != l2.size(); i++){
         l1.push_front(0);
      }
   }
   list<int>::reverse_iterator it1 = l1.rbegin();
   list<int>::reverse_iterator it2 = l2.rbegin();
   list<int> result;
   int carry = 0;
   while(it1 != l1.rend()){
      result.push_front((*it1 + *it2 + carry) % 10);
      carry = (*it1 + *it2 + carry) / 10;
      it1++; it2++;
   }
   if(carry != 0){
      result.push_front(carry);
   }
   return result;
}
list<int> numToList(int n){
   list<int> numList;
   while(n != 0){
      numList.push_front(n % 10);
      n /= 10;
   }
   return numList;
}
void displayListNum(list<int> numList){
   for(list<int>::iterator it = numList.begin(); it != numList.end();
   it++){
      cout<<*it;
   }
   cout << endl;
}
int main() {
   int n1 = 512;
   int n2 = 14578;
   list<int> n1_list = numToList(n1);
   list<int> n2_list = numToList(n2);
   list<int> res = addListNumbers(n1_list, n2_list);
   cout << "First number: "; displayListNum(n1_list);
   cout << "Second number: "; displayListNum(n2_list);
   cout << "Result: "; displayListNum(res);
}
First number: 512
Second number: 14578
Result: 15090
Program to remove all nodes of a linked list whose value is same as in Python

Suppose we have a singly linked list, and one target, we have to return the same linked after
deleting all nodes whose value is same as target.
So, if the input is like [5,8,2,6,5,2,9,6,2,4], then the output will be [5, 8, 6, 5, 9, 6, 4, ]
To solve this, we will follow these steps −
head := node
while node and node.next are not null, dowhile value of next of node is same as target, donext of node := next of next of nodenode := next of node
while value of next of node is same as target, donext of node := next of next of node
next of node := next of next of node
node := next of node
if value of head is same as target, thenreturn next of head
return next of head
otherwise,return head
return head
Let us see the following implementation to get better understanding −
class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
   while ptr.next:
      ptr = ptr.next
      ptr.next = ListNode(element)
   return head
def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
      print(']')
class Solution:
   def solve(self, node, target):
      head = node
      while (node and node.next):
         while node.next.val == target:
            node.next = node.next.next
            node = node.next
         if head.val == target:
            return head.next
         else:
      return head
ob = Solution()
head = make_list([5,8,2,6,5,2,9,6,2,4])
ob.solve(head, 2)
print_list(head)
[5,8,2,6,5,2,9,6,2,4]
[5, 8, 6, 5, 9, 6, 4, ]
How to find numeric columns in Pandas?

To find numeric columns in Pandas, we can make a list of integers and then include it into select_dtypes() method. Let's take an example and see how to apply this method.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame, df.
Make a list of data type, i.e., numerics, to select a column.
Return a subset of the DataFrame's columns based on the column dtypes.
Print the column whose data type is int.
import pandas as pd

df = pd.DataFrame(
   dict(
      name=['John', 'Jacob', 'Tom', 'Tim', 'Ally'],
      marks=[89, 23, 100, 56, 90],
      subjects=["Math", "Physics", "Chemistry", "Biology", "English"]
   )
)

print "Input DataFrame is:\n", df
numerics = ['int16', 'int32', 'int64']
df = df.select_dtypes(include=numerics)
print "Numeric column in input DataFrame is:\n", df
Input DataFrame is:
    name   marks   subjects
0   John    89         Math
1  Jacob    23      Physics
2    Tom   100    Chemistry
3    Tim    56      Biology
4   Ally    90      English

Numeric column in input DataFrame is:
    marks
0    89
1    23
2   100
3    56
4    90
What is the use of underscore keyword in Java 9?

In earlier versions of Java, the underscore ("_") has used as an identifier or to create a variable name. Since Java 9, the underscore character is a reserved keyword and can't be used as an identifier or variable name. If we use a single underscore character as an identifier, the program fails to compile and throws a compile-time error because now it is a keyword and can't be used as a variable name in Java 9 or later versions.
public class UnderscoreKeywordTest {
   public static void main(String args[]) {
      int _ = 50
      System.out.println(_);
   }
}
UnderscoreKeywordTest.java:3: error: as of release 9, '_' is a keyword, and may not be used as an identifier
int _ = 50;
^
UnderscoreKeywordTest.java:4: error: as of release 9, '_' is a keyword, and may not be used as an identifier
System.out.println(_);
MySQL ALTER TABLE Statement

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on 
an existing table.
To add a column in a table, use the following syntax:
The following SQL adds an "Email" column to the "Customers" table:
To delete a column in a table, use the following syntax (notice that some 
database systems don't allow deleting a column):
The following SQL deletes the "Email" column from the "Customers" table:
To change the data type of a column in a table, use the following syntax:
Look at the "Persons" table:
Now we want to add a column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
Notice that the new column, "DateOfBirth", is of type date and is going to hold a 
date. The data type specifies what type of data the column can hold. For a complete 
reference of all the data types available in MySQL, 
go to our complete Data Types reference.
The "Persons" table will now look like this:
Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or four-digit format.
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
The "Persons" table will now look like this:
Add a column of type DATE called Birthday.
 Persons
;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Terminator – A Linux terminal emulator

30 Jun, 2021
As the name suggests, ‘Terminator’ is a pretty badass emulator which provides you with functionalities like split horizontally, split vertically, etc, as one wants in a single window. Not only does it provide split horizontally or vertically, but, also one can give a custom title to each and every terminal and several other features such as multigrid-like structure, layouts savings, etc.
Split terminal horizontally.
Split terminal vertically.
Custom title to terminal.
Multigrid-like structure.
Layout savings.
Installing terminator is a very simple and easy process and can be achieved in one step.
For kali Linux:
sudo apt-get install terminator
For Ubuntu:
sudo apt install terminator
For Arch Linux:
sudo pacman -S terminator
For CentOS:
sudo yum install terminator
Demo:
Let’s quickly install it and use it.
Let’s use its split-screen feature.
Here we can see that we have split the terminal horizontally and vertically, and then running different services at the same time and getting their results at one go.
We can also collapse the terminal if we want.
Firstly, run “terminator” command in your terminal to use it. Once you fire the command, you will be able to see the screen shown below.
To split Terminal horizontally, use– Ctrl+Shift+0.
To split Terminal vertically, use – Ctrl+Shift+E
To clear the active terminal, use Ctrl+shift+X.
Shortcuts:
Below are the few shortcuts by which one can navigate to the terminator.
Both the default terminal and terminator look identical but are very different when it comes to features offered by them. As we can see, the splitting screen feature is so helpful and cool and can be used by someone who is working on a project and doesn’t want to switch terminals to run different services at the same time. One can split the screen horizontally or vertically as one wishes too. Therefore, it can be seen, that, again, Linux is very powerful and useful when used correctly. 
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
Introduction to Linux Operating System
SED command in Linux | Set 2
Array Basics in Shell Scripting | Set 1
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting
numpy.linspace() in Python

19 May, 2022
The numpy.linspace() function returns number spaces evenly w.r.t interval. Similar to numpy.arange() function but instead of step it uses sample number. Syntax :  
numpy.linspace(start,
               stop,
               num = 50,
               endpoint = True,
               retstep = False,
               dtype = None)
Parameters : 
-> start  : [optional] start of interval range. By default start = 0
-> stop   : end of interval range
-> restep : If True, return (samples, step). By default restep = False
-> num    : [int, optional] No. of samples to generate
-> dtype  : type of output array
Return :  
-> ndarray
-> step : [float, optional], if restep = True
Code 1 : Explaining linspace function  
Python
# Python Programming illustrating# numpy.linspace method import numpy as geek # restep set to Trueprint("B\n", geek.linspace(2.0, 3.0, num=5, retstep=True), "\n") # To evaluate sin() in long rangex = geek.linspace(0, 2, 10)print("A\n", geek.sin(x))
Output : 
B
 (array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)

A
 [ 0.          0.22039774  0.42995636  0.6183698   0.77637192  0.8961922
  0.9719379   0.99988386  0.9786557   0.90929743]
Code 2 : Graphical Representation of numpy.linspace() using matplotlib module – pylab 
Python
# Graphical Representation of numpy.linspace()import numpy as geekimport pylab as p # Start = 0# End = 2# Samples to generate = 10x1 = geek.linspace(0, 2, 10, endpoint = False)y1 = geek.ones(10) p.plot(x1, y1, '*')p.xlim(-0.2, 1.8)
Output :  
Code 3 : Graphical Representation of numpy.linspace() using pylab  
Python
# Graphical Representation of numpy.linspace()import numpy as geekimport pylab as p # Start = 0# End = 2# Samples to generate = 15x1 = geek.linspace(0, 2, 15, endpoint = True)y1 = geek.zeros(15) p.plot(x1, y1, 'o')p.xlim(-0.2, 2.1)
Output :  
Note : These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore them .This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nidhi_biet
anikaseth98
sagar0719kumar
adnanirshad158
sandeshkale1234
kothavvsaakash
mitalibhola94
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scrape Instagram using Instagramy in Python

17 May, 2022
In this article, we will learn how can we get Instagram profile details using web scraping. Python provides powerful tools for web scraping, we will be using Instagramy here. This tool is specifically made for Instagram and also analyzes the data using Pandas.
The python package Instagramy is used to scrape Instagram quick and easily. This package is installed by running the following command. Based on the network connection it scrapes the data for you.
pip install instagramy
Example 1: Scraping basic details
Python3
from instagramy import InstagramUser  # Connecting the profileuser = InstagramUser("geeks_for_geeks") # printing the basic details like# followers, following, bioprint(user.is_verified())print(user.popularity())print(user.get_biography()) # return list of dictsposts = user.get_posts_details() print('\n\nLikes', 'Comments')for post in posts:    likes = post["likes"]    comments = post["comment"]    print(likes,comments)
Output:
Example 2: Analysing the data
Python3
from instagramy import Instalysis # Instagram user_id of ipl teamsteams = ["chennaiipl", "mumbaiindians",         "royalchallengersbangalore", "kkriders",         "delhicapitals", "sunrisershyd",         "kxipofficial"] data = Instalysis(teams) # return the dataframedata_frame = data.analysis()data_frame
Output:
 
as5853535
mohan19
Python web-scraping-exercises
python-modules
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | DOM Canvas Object

11 Jul, 2022
The DOM Canvas Object is used to represent the HTML <Canvas> element. The <canvas> tag is used to draw a graphics in the document using javascript. It is new in HTML5. The canvas element is accessed by getElementById(). 
Syntax:
accessed by getElementById("id"). 
Where “id” is the ID assigned to the Canvas tag. 
Example-1: 
html
<!DOCTYPE html><html> <head>    <title>canvas Tag</title></head> <body>    <center>        <h1 style="color:green; Font-size:35px;" >           GeeksForGeeks        </h1>        <h2>DOM Canvas Object</h2>               <!-- canvas Tag starts here -->        <canvas id="geeks" height="200" width="200"                style="border:1px solid green">        </canvas>        <!-- canvas Tag ends here -->               <br>        <br>               <button onclick="myGeeks()">Submit</button>              <script>            function myGeeks() {                 var gfg = document.getElementById("geeks");                               var sudo = gfg.getContext("2d");                sudo.beginPath();                sudo.arc(100, 100, 90, 0, 2 * Math.PI);                sudo.stroke();            }        </script></body> </html>
Output: 
Before Clicking On Button:
  
After Clicking on Button:
  
Example-2: Canvas Object can be created by using the document.createElement method. 
html
<!DOCTYPE html><html> <head>    <style>        canvas {            border: 3px solid black;        }    </style></head> <body>    <h1 style = "color: green; font-size:40px;" >      GeeksForGeeks    </h1>    <h2>DOM Canvas Object</h2>       <button onclick="myGeeks()">      Submit    </button>     <script>        function myGeeks() {            var geeks = document.createElement("CANVAS");            var gfg = geeks.getContext("2d");            gfg.fillStyle = "green";            gfg.fillRect(40, 40, 200, 100);            document.body.appendChild(geeks);        }    </script> </body> </html>
Output: 
Before Clicking on Button:
  
After Clicking on Button:
  
Supported Browsers: The browser supported by DOM Canvas Object are listed below:
Google Chrome 1
Edge 12
Internet Explorer 9
Firefox 1.5
Opera 9
Safari 2
geeksr3ap
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Number System and Base Conversions

07 Jul, 2021
Electronic and Digital systems may use a variety of different number systems, (e.g. Decimal, Hexadecimal, Octal, Binary). 
A number N in base or radix b can be written as: 
(N)b = dn-1 dn-2 -- -- -- -- d1 d0 . d-1 d-2 -- -- -- -- d-m
In the above, dn-1 to d0 is the integer part, then follows a radix point, and then d-1 to d-m is the fractional part. 
dn-1 = Most significant bit (MSB) d-m = Least significant bit (LSB)
 
How to convert a number from one base to another?
Follow the example illustrations: 
(10.25)10 
 
Note: Keep multiplying the fractional part with 2 until decimal part 0.00 is obtained. (0.25)10 = (0.01)2 
Answer: (10.25)10 = (1010.01)2  
(1010.01)2 
1x23 + 0x22 + 1x21+ 0x20 + 0x2 -1 + 1x2 -2 = 8+0+2+0+0+0.25 = 10.25 
(1010.01)2 = (10.25)10 
(10.25)10 
(10)10 = (12)8 
Fractional part: 
0.25 x 8 = 2.00 
Note: Keep multiplying the fractional part with 8 until decimal part .00 is obtained. (.25)10 = (.2)8
Answer: (10.25)10 = (12.2)8  
(12.2)8
1 x 81 + 2 x 80 +2 x 8-1 = 8+2+0.25 = 10.25 
(12.2)8 = (10.25)10 
To convert from Hexadecimal to Binary, write the 4-bit binary equivalent of hexadecimal.
 
(3A)16 = (00111010)2 
To convert from Binary to Hexadecimal, start grouping the bits in groups of 4 from the right-end and write the equivalent hexadecimal for the 4-bit binary. Add extra 0’s on the left to adjust the groups. 
1111011011
0011 1101 1011
(001111011011 )2 = (3DB)16 
This article is contributed by Kriti Kushwaha. 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.  
thekuntalpaul1
base-conversion
CBSE - Class 11
school-programming
Digital Electronics & Logic Design
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
IEEE Standard 754 Floating Point Numbers
Difference between RAM and ROM
Introduction to memory and memory units
Analog to Digital Conversion
Difference between Half adder and full adder
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Calculate Cumulative Sum of a Numeric Object in R Programming – cumsum() Function

12 Apr, 2022
The cumulative sum can be defined as the sum of a set of numbers as the sum value grows with the sequence of numbers.
cumsum() function in R Language is used to calculate the cumulative sum of the vector passed as argument.
Syntax: cumsum(x) 
Parameters: 
x: Numeric Object
Example 1: 
Python3
# R program to illustrate# the use of cumsum() Function # Calling cumsum() Functioncumsum(1:4)cumsum(-1:-6)
Output:
[1]  1  3  6 10
[1]  -1  -3  -6 -10 -15 -21
Example 2: 
Python3
# R program to illustrate# the use of cumsum() Function # Creating Vectorsx1 <- c(2, 4, 5, 7)x2 <- c(2.4, 5.6, 3.4) # Calling cumsum() Functioncumsum(x1)cumsum(x2)
Output:
[1]  2  6 11 18
[1]  2.4  8.0 11.4
aarushirohitkumar
R DataFrame-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use the Properties file to declare global variables in a framework in Selenium?

We can declare global variables in Selenium with the help of the Properties class which works with .properties file. In the .properties file, the data is stored in key value pairs. We can read and write values in the .properties file.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Propert {
   public static void main(String[] args) throws IOException {
      // TODO Auto-generated method stub
      Propert t = new Propert();
      t.login();
   }
   public void login() throws IOException {
      Properties prop = new Properties();
      FileInputStream ips = new FileInputStream(
      "C:\\Users\\ghs6kor\\eclipse- workspace\\Inheritance\\config.properties");
      prop.load(ips);
      // read from properties file with getProperty() method
      if (prop.getProperty("browser").equalsIgnoreCase("firefox")) {
         System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
         WebDriver driver = new FirefoxDriver();
         driver.manage().window().maximize();
         driver.get(prop.getProperty("url"));
         FileOutputStream ops = new FileOutputStream(
         "C:\\Users\\ghs6kor\\eclipse- workspace\\Inheritance\\config.properties");
         String urlnm = driver.getTitle();
         // writing in the properties file with setProperty() method
         prop.setProperty("title", urlnm);
         prop.store(ops, null);
      }
   }
}
Clojure - Atoms

Atoms are a data type in Clojure that provide a way to manage shared, synchronous, independent state. An atom is just like any reference type in any other programming language. The primary use of an atom is to hold Clojure’s immutable datastructures. The value held by an atom is changed with the swap! method.
Internally, swap! reads the current value, applies the function to it, and attempts to compare-and-set it in. Since another thread may have changed the value in the intervening time, it may have to retry, and does so in a spin loop. The net effect is that the value will always be the result of the application of the supplied function to a current value, atomically.
Atoms are created with the help of the atom method. An example on the same is shown in the following program.
(ns clojure.examples.example
   (:gen-class))
(defn example []
   (def myatom (atom 1))
   (println @myatom))
(example)
The above program produces the following result.
1

The value of atom is accessed by using the @ symbol. Clojure has a few operations that can be performed on atoms. Following are the operations.
Sets the value of atom to a new value without regard for the current value.
Atomically sets the value of atom to the new value if and only if the current value of the atom is identical to the old value held by the atom. Returns true if set happens, else it returns false.
Atomically swaps the value of the atom with a new one based on a particular function.
 Print
 Add Notes
 Bookmark this page
Java command line arguments

A command-line argument is an information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ).
The following program displays all of the command-line arguments that it is called with -
public class CommandLine {
   public static void main(String args[]) {
      for(int i = 0; i<args.length; i++) {
         System.out.println("args[" + i + "]: " + args[i]);
      }
   }
}
Try executing this program as shown here -
$java CommandLine this is a command line 200 -100
This will produce the following result -
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
Get a List of Installed Softwares in Windows using Python - GeeksforGeeks

01 Oct, 2020
In this article, we are going to write a Python script to get the installed software list in windows. We will use the subprocess module to interact with cmd and to retrieve information into your Python IDE. We can read the cmd command through the subprocess module.
Let’s see the logic, if we run this wmic product get name code into our terminal then we got like this:
Let’s write the Python code to get installed software list information.
Approach:
Import the subprocess module.
Get the output for the command “wmic product get name” using subprocess.check_output()
Now split the string and arrange your data with your own needs.
Implementation:
Python3
# importing the moduleimport subprocess  # traverse the software listData = subprocess.check_output(['wmic', 'product', 'get', 'name'])a = str(Data)  # try blocktry:        # arrange the string    for i in range(len(a)):        print(a.split("\\r\\r\\n")[6:][i])  except IndexError as e:    print("All Done")
Output:
python-utility
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?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Tryit Editor v3.6 - Show Python

import matplotlib.pyplot as plt
​
x = numpy.random.uniform(0.0, 5.0, 100000)
Sublime Text - Spell Check

Sublime Text Editor uses Hunspell for spell checking process. Hunspell is the spell checker of LibreOffice, Mozilla Thunderbird, Google chrome and many proprietary packages. Sublime Text editor includes dictionary support for proper spell check of words.
Sublime Text includes UTF-8 encoded dictionaries. To implement a dictionary with Sublime Text editor, it should be first converted into UTF-8. If the user has UTF-8 encoded dictionary, it can be installed using the Preferences option in Sublime Text editor.
You can select the dictionary from View → Dictionary menu as shown in the given screenshot −
There are two settings defined for the spell check of Sublime Text Editor −
Spell_check
Dictionary
// Set to true to turn spell checking on by default
"spell_check": false,

// Word list to use for spell checking
"dictionary": "Packages/Language - English/en_US.dic"

These configurations are included in the settings file. Added and ignored words are stored in the user settings under the added_words and ignored_words keys, respectively.
 Print
 Add Notes
 Bookmark this page
Python program to Display Hostname and IP address?

Python provides gethostname(),gethostbyname() two function. gethostname() retrives the standard host name for the local machine. gethostbyname() retrives host information corresponding to a host name from a host database.
Socket. gethostname()
Socket. gethostbyname()

Step 1: use module socket.
Step 2: use gethostname() retrives the standard host name for the local machine.
Step 3: use gethostbyname() retrives host information corresponding to a host name from a host database.

# Display hostname andIP address
import socket
def host_IP():
   try:
      hname = socket.gethostname()
      hip = socket.gethostbyname(hname)
      print("Hostname:  ",hname)
      print("IP Address: ",hip)
   except:
      print("Unable to get Hostname and IP")
# Driver code
host_IP() #Function call
Hostname:   Satyajit-PC
IP Address:  192.168.1.66
How to print a triangle formed of '#' using JavaScript?

To print a triangle formed of “#”, you need to use a nested “for loop”.
Try the following code to print a triangle −
Live Demo
<html>
   <head>
      <body>
         <p>Printing a triangle</p>
         <script>
            var i, j;
            for(i=1; i < 5; i++) {
               //inner loop
              for(j=1; j<=i; j++) {
                 document.write('#');
            }
            document.write('<br/>');
         }
      </script>
   </body>
</html> 
Printing a triangle
#
##
###
####