code-rag-bench/online-tutorials huggingface dataset:
Sum of array object property values in new array of objects in JavaScript

Suppose we have an array of objects that contains the data about some students and their marks like this −
const arr = [
   { subject: 'Maths', marks: '40', noOfStudents: '5' },
   { subject: 'Science', marks: '50', noOfStudents: '16' },
   { subject: 'History', marks: '35', noOfStudents: '23' },
   { subject: 'Science', marks: '65', noOfStudents: '2' },
   { subject: 'Maths', marks: '30', noOfStudents: '12' },
   { subject: 'History', marks: '55', noOfStudents: '20' },
];
We are required to write a JavaScript function that takes in one such array.
The function should eliminate the redundant entries on the basis of the 'subject' property of objects. Moreover, the function should add all the marks and no of students for a unique object in that single object.
Therefore, for the above array, the output should look like −
const output = [
   { subject: 'Maths', marks: '70', noOfStudents: '17' },
   { subject: 'Science', marks: '115', noOfStudents: '18' },
   { subject: 'History', marks: '95', noOfStudents: '43' },
];
The code for this will be −
const arr = [
   { subject: 'Maths', marks: '40', noOfStudents: '5' },
   { subject: 'Science', marks: '50', noOfStudents: '16' },
   { subject: 'History', marks: '35', noOfStudents: '23' },
   { subject: 'Science', marks: '65', noOfStudents: '2' },
   { subject: 'Maths', marks: '30', noOfStudents: '12' },
   { subject: 'History', marks: '55', noOfStudents: '20' },
];
const groupBySubject = (arr = []) => {
   const map = {};
   let res = [];
   res = arr.reduce((acc, val) => {
      const { subject, marks, noOfStudents } = val;
      const { length: l } = acc;
      if(map.hasOwnProperty(subject)){
         acc[map[subject]]['marks'] = +marks;
         acc[map[subject]]['noOfStudents'] = +noOfStudents;
      }
      else{
         map[subject] = l;
         acc.push({
            subject: subject,
            marks: +marks,
            noOfStudents: +noOfStudents
         });
      };
      return acc;
   }, []);
   return res;
};
console.log(groupBySubject(arr));
And the output in the console will be −
[
   { subject: 'Maths', marks: 30, noOfStudents: 12 },
   { subject: 'Science', marks: 65, noOfStudents: 2 },
   { subject: 'History', marks: 55, noOfStudents: 20 }
]
How to create a duplicate file of an existing file using Python?

The shutil module provides functions for copying files, as well as entire folders.
Calling shutil.copy(source, destination) will copy the file at the path source to the folder at the path destination. (Both source and destination are strings.) If destination is a filename, it will be used as the new name of the copied file. This function returns a string of the path of the copied file. For example,
>>> import shutil
>>> # Copy the file in same folder with different name
>>> shutil.copy('original.txt', 'duplicate.txt')
'/home/username/duplicate.txt'
>>> shutil.copy('original.txt', 'my_folder/duplicate.txt')
'/home/username/my_folder/duplicate.txt'
QlikView - Text Object

QlikView text Object is used to show some descriptive information about the QlikView report being displayed. It can also show calculations based on certain expressions. It is mainly used for displaying nicely formatted information using colors and different font types in a box separately from the other Sheet Objects.
Let us consider the following input data, which represents the sales figure of different product lines and product categories.
Product_Line,Product_category,Value
Sporting Goods,Outdoor Recreation,5642
Food, Beverages & Tobacco,2514
Apparel & Accessories,Clothing,2365
Apparel & Accessories,Costumes & Accessories,4487
Sporting Goods,Athletics,812
Health & Beauty,Personal Care,6912
Arts & Entertainment,Hobbies & Creative Arts,5201
Arts & Entertainment,Paintings,8451
Arts & Entertainment,Musical Instruments,1245
Hardware,Tool Accessories,456
Home & Garden,Bathroom Accessories,241
Food,Drinks,1247
Home & Garden,Lawn & Garden,5462
Office Supplies,Presentation Supplies,577
Hardware,Blocks,548
Baby & Toddler,Diapering,1247
Baby & Toddler,Toys,257
Home & Garden,Pipes,1241
Office Supplies,Display Board,2177

The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. Edit the load script to add the following code. Click "OK" and press "Control+R" to load the data into the QlikView's memory.
LOAD Product_Line, 
     Product_category, 
     Value
FROM
[C:\Qlikview\data\product_sales.csv]
(txt, codepage is 1252, embedded labels, delimiter is ',', msq);
For the above data, let us create a Table Box , which will show the data in a tabular form.
Go to the menu Layout → New Sheet Object → Table Box and choose the column as shown below.
Click Apply and then OK to finish creating the Table box. The following screen appears.
For the above data, let us create a Text  Object. Go to the menu Layout → New Sheet Object → Text Object as shown below.
On the text box created above, right click and choose properties. Then enter the content to be displayed on the Text Object in the Text box under the General tab as shown below.
The background color of the Text Object can be set using the background option in the General tab.
The final Text Object is shown below. If we click on some Product Line to filter it, then the content in the Text Object changes accordingly to reflect the new values.

    70 Lectures 
     5 hours 

 Arthur Fong
 Print
 Add Notes
 Bookmark this page
How to find an element using the attribute “class name” in Selenium?

We can find an element using the attribute class name with Selenium webdriver using the locators - class name, css, or xpath. To identify the element with css, the expression should be tagname[class='value'] and the method to be used is By.cssSelector.
To identify the element with xpath, the expression should be //tagname[@class='value']. Then, we have to use the method By.xpath to locate it. To locate an element with a locator class name, we have to use the By.className method.
Let us look at the html code of an element with class attribute −
WebElement e = driver. findElement(By.className("input"));
WebElement m = driver. findElement(By.xpath("//input[@class = 'input']"));
WebElement n = driver. findElement(By.cssSelector("input[class='input']"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LocatorClsName{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/videotutorials/subscription.php");
      // identify element with class
      WebElement n = driver.findElement(By.className("input"));
      n.sendKeys("JavaScript");
      //identify element with cssSelector
      WebElement n = driver.
      findElement(By.cssSelector("input[class='input']"));
      String str = n.getAttribute("value");
      System.out.println("Attribute value is : " + str);
      //identify element with xpath
      WebElement p = driver.
      findElement(By.xpath("//input[@class='input']"));
      p.clear();
      driver.close();
   }
}
Python Program to Print Hello world

Let us try to execute Python “Hello World” programs in different modes of Python programming.
Invoking the interpreter without passing a script file as a parameter brings up the following prompt −
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Type the following text at the Python prompt and press the Enter −
>>> print "Hello, Python!"

If you are running new version of Python, then you would need to use print statement with parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this produces the following result −
Hello, Python!
Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type the following source code in a test.py file −
 Live Demo
print "Hello, Python!"
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −
$ python test.py
This produces the following result −
Hello, Python!

Let us try another way to execute a Python script. Here is the modified test.py file −
 Live Demo
#!/usr/bin/python
print "Hello, Python!"
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −
$ chmod +x test.py # This is to make file executable
$./test.py
This produces the following result −
Hello, Python!
C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm

The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both of them.
For example: Let’s say we have two numbers that are 63 and 21.
63 = 7 * 3 * 3
21 = 7 * 3
So, the GCD of 63 and 21 is 21.
The recursive Euclid’s algorithm computes the GCD by using a pair of positive integers a and b and returning b and a%b till b is zero.
A program to find the GCD of two numbers using recursive Euclid’s algorithm is given as follows −
 Live Demo
#include <iostream>
using namespace std;
int gcd(int a, int b) {
   if (b == 0)
   return a;
   return gcd(b, a % b);
}
int main() {
   int a , b;
   cout<<"Enter the values of a and b: "<<endl;
   cin>>a>>b;
   cout<<"GCD of "<< a <<" and "<< b <<" is "<< gcd(a, b);
   return 0;
}
The output of the above program is as follows −
Enter the values of a and b: 105 30
GCD of 105 and 30 is 15
In the above program, gcd() is a recursive function. It has two parameters i.e. a and b. If b is equal to 0, then a is returned to the main() function. Otherwise the gcd() function recursively calls itself with the values b and a%b. This is demonstrated by the following code snippet −
int gcd(int a, int b) {
   if (b == 0)
   return a;
   return gcd(b, a % b);
}
In the main() function, values of a and b are requested from the user. Then gcd() function is called and the value of GCD of a and b is displayed. This is seen below −
int main() {
   int a , b;
   cout<<"Enter the values of a and b: "<<endl;
   cin>>a>>b;
   cout<<"GCD of "<< a <<" and "<< b <<" is "<< gcd(a, b);
   return 0;
}
Java Examples - Formatting Time

How to format time in AM-PM format?
This example formats the time by using  SimpleDateFormat("HH-mm-ss a") constructor and sdf.format(date) method of SimpleDateFormat class.
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main{
   public static void main(String[] args){
      Date date = new Date();
      String strDateFormat = "HH:mm:ss a";
      SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
      System.out.println(sdf.format(date));
   }
}
The above code sample will produce the following result.The result will change depending upon the current system time
06:40:32 AM

 Print
 Add Notes
 Bookmark this page
Program for EMI Calculator in C program

Given with certain values the program will develop an EMI calculator to generate the needed output. EMI stands for Equated Monthly Installment. So this calculator will generate monthly EMI amount for the user.
Input-: principal = 2000
   rate = 5
   time = 4
Output-: Monthly EMI is= 46.058037
The formula used in the below program is −
EMI : (P*R*(1+R)T)/(((1+R)T)-1)
where,
P indicates loan amount or the Principal amount.
R indicates interest rate per month
T indicates loan time period in year
Input principal, rate of interest and time in float variable
Apply the formula to calculate the EMI amount
Print the EMI amount
Start
Step 1 -> Declare function to calculate EMI
   float calculate_EMI(float p, float r, float t)
      float emi
      set r = r / (12 * 100)
      Set t = t * 12
      Set emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1)
      Return emi
Step 2 -> In main()
   Declare variable as float principal, rate, time, emi
   Set principal = 2000, rate = 5, time = 4
   Set emi = calculate_EMI(principal, rate, time)
   Print emi
Stop
#include <math.h>
#include <stdio.h>
// Function to calculate EMI
float calculate_EMI(float p, float r, float t){
   float emi;
   r = r / (12 * 100); // one month interest
   t = t * 12; // one month period
   emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1);
   return (emi);
}
int main(){
   float principal, rate, time, emi;
   principal = 2000;
   rate = 5;
   time = 4;
   emi = calculate_EMI(principal, rate, time);
   printf("\nMonthly EMI is= %f\n", emi);
   return 0;
}
Monthly EMI is= 46.058037
Computer Storage Definitions and Notations

Computer storage contains many components that are used to store computer data. Some information about the various storage devices is given below.
The computer storage devices include Primary and Secondary Storage devices. These are explained in detail as follows −
Primary storage is also known as the main memory and is the memory directly accessible by the CPU. Some primary storage devices are −
ROM is read only memory. This memory cannot be changed, it can only be read as required. Since ROM is unchangeable memory, it is used by data and programs that are frequently required and seldom changed, like the system boot program.
RAM is random access memory. It is volatile i.e. the data in RAM is lost when the power is switched off. RAM is the major form of primary memory as it is quite fast. However, it is also quite expensive.
Cache is used to store data and instructions that are frequently required by the CPU so it doesn't have to search them in the main memory. This is a small memory that is also very fast.
Secondary or external storage is not directly accessible by the CPU. The data from secondary storage needs to be brought into the primary storage before the CPU can use it. Secondary storage contains a large amount of data permanently.
The different types of secondary storage devices are:
Hard disks are the most famously used secondary storage devices. They are round, flat pieces of metal covered with magnetic oxide. They are available in many sizes ranging from 1 to 14 inch diameter.
They are flexible plastic discs which can bend, coated with magnetic oxide and are covered with a plastic cover to provide protection. Floppy disks are also known as floppies and diskettes.
This has similar functionality to a flash drive but is in a card shape. It can easily plug into a port and removed after its work is done. A memory card is available in various sizes such as 8GB, 16GB, 64GB, etc.
This is also known as a pen drive. It helps in easy transportation of data from one system to another. A pen drive is quite compact and comes with various features and designs.
This is short for compact disk - read only memory. A CD is a shiny metal disk of silver colour. It is already pre-recorded and the data on it cannot be altered. It usually has a storage capacity of 700 MB.
There are several storage notations. These are given in detail as follows:
A bit is the smallest unit of memory storage. It can contain either 0 or 1. The value of a bit is usually displayed by a low and high in electrical discharge for 0 and 1 respectively.
The nibble contains 4 bits. It can also be represented as half a byte.
1 Nibble = 4 Bits
A byte is formed of 8 bits. It is used to store the value of characters, special symbols etc.
1 Byte = 8 Bits
A kilobyte is approximately 1000 bytes or 1024 bytes to be more precise.(2 to the 10th power)
1 KB = 1024 Bytes
A Megabyte is 1024 Kilobytes or 10,48,576 Bytes.
1 MB = 1024 KB
A Gigabyte is roughly a billion bytes or 1024 MB.
1 GB = 1024 MB
A Terabyte is 1024 Gigabytes.
1 TB = 1024 GB
Redis - String Set Command

Redis SET command is used to set some string value in Redis key.
Simple string reply. OK, if the value is set in the key. Null, if the value does not set.
Following is the basic syntax of Redis SET command.
redis 127.0.0.1:6379> SET KEY_NAME VALUE

redis 127.0.0.1:6379> SET tutorialspoint redis 
OK 

In SET command, there are many options available, that modify the behavior of command. Following is the basic syntax of SET command with available options.
redis 127.0.0.1:6379> SET KEY VALUE [EX seconds] [PX milliseconds] [NX|XX]

EX seconds − Sets the specified expire time, in seconds.
EX seconds − Sets the specified expire time, in seconds.
PX milliseconds − Sets the specified expire time, in milliseconds.
PX milliseconds − Sets the specified expire time, in milliseconds.
NX − Only sets the key if it does not already exist.
NX − Only sets the key if it does not already exist.
XX − Only sets the key if it already exists.
XX − Only sets the key if it already exists.
redis 127.0.0.1:6379> SET tutorialspoint redis EX 60 NX  
OK

The above example will set the key ‘tutorialspoint’, with expiry of 60 seconds, if the key does not exist.

    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Creating a variable with dynamic variable type in SAP ABAP

You can use RTTS related API to create a Standard table like RANGE which has components like 'LOW', 'HIGH', 'EQ' and 'OPTION'
data:
   rr_data              type ref to data,
   rt_range_string      type range of string,
   rs_range_string      like line of rt_range_string,
   rt_component         type abap_component_tab,
   rs_component         type line of abap_component_tab,
   rt_range_components  type abap_component_tab,
   ro_struc_descr       type ref to cl_abap_structdescr,
   ro_table_descr       type ref to cl_abap_tabledescr,
   ro_data_descr        type ref to cl_abap_datadescr.
<var_value> type any,
<rt_range_type> type standard table,   //<rt_range_type> is your range table
<rs_range_type> type any.
data(var_type) = 'BU_PARTNER'.

create data rr_data type (var_type).
ro_struc_descr ?= cl_abap_structdescr=>describe_by_data( p_data = rs_range_string ).
rt_component = ro_struc_descr->get_components( ).
ro_data_descr ?= cl_abap_elemdescr=>describe_by_name( var_type ).

rt_range_components = value #( for comp in rt_component (
   name = comp-name
   type = cond #(
      when comp-name eq 'SIGN'
      or comp-name eq 'OPTION'
      then comp-type
      else ro_data_descr )
) ).
ro_struc_descr ?= cl_abap_structdescr=>create( rt_range_components ).
ro_table_descr ?= cl_abap_tabledescr=>create( ro_struc_descr ).
create data rr_data type handle ro_table_descr.
assign rr_data->* to <rt_range_type>.

create data rr_data like line of <rt_range_type>.
assign rr_data->* to <rs_range_type>.
assign component 'SIGN' of structure <rs_range_type> to <var_value>.
<var_value> = 'I'.

assign component 'OPTION' of structure <rs_range_type> to <var_value>.
<var_value> = 'EQ'.

assign component 'LOW' of structure <rs_range_type> to <var_value>.
<var_value> = 'X1'.

assign component 'HIGH' of structure <rs_range_type> to <var_value>.
<var_value> = 'X2'.
How to Install Grunt on Ubuntu?

Grunt (The JavaScript assignment Runner) is an automation tool to perform repetitive duties like compilation, unit testing etc. Grunt and Grunt plugins are hooked up and managed through NPM, the Node.Js package manager. This article explains about – How to install Grunt on Ubuntu.
To install grunt on ubuntu, it should require pre-installed Node.js and NPM. To verify the version of Node.js, use the following command –
$ node --version
The sample output should be like this –
v6.9.2
To verify the version of NPM, use the following command –
$ npm --version
The sample output should be like this –
3.10.9
If you wants to install Node.js and NPM, read this article
To install grunt, use the following command –
$ sudo npm install -g grunt-cli
The sample output should be like this –
/usr/bin/grunt -> /usr/lib/node_modules/grunt-cli/bin/grunt
/usr/lib
      `-- grunt-cli@1.2.0
      +-- findup-sync@0.3.0
      | `-- glob@5.0.15
      |  +-- inflight@1.0.6
      |  | `-- wrappy@1.0.2
      |  +-- inherits@2.0.3
      |  +-- minimatch@3.0.3
      |  | `-- brace-expansion@1.1.6
      |  | +-- balanced-match@0.4.2
      |  | `-- concat-map@0.0.1
      | +-- once@1.4.0
      | `-- path-is-absolute@1.0.1
      +-- grunt-known-options@1.1.0
      +-- nopt@3.0.6
      | `-- abbrev@1.0.9
      `-- resolve@1.1.7
To verify the version of grunt, use the following command –
$ grunt --version
The sample output should be like this –
grunt-cli v1.2.0
In the above article, we have learnt – How to Install Grunt on Ubuntu. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!
Dictionary with index as value in Python

In this article we will learn how to create a dictionary from another frequently used python collection namely list. An index or key is not part a list content. But in dictionary we need to have a key or index attached to every element which is referred as value.
The enumerate function adds a counter as the key of the enumerate object. SO we apply it to a given list and using a for loop. That creates the required dictionary where the keys are generated by the enumerate function.
 Live Demo
Alist = ['Mon', 'Tue', 'Wed', 'Wed',11,11]

# Given list
print("Given list : " , Alist)

# Converting to DIctionary
NewDict = {val: key + 1 for key, val in enumerate(Alist)}

# print result
print("Dictionary created with index : ",NewDict)
Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Wed', 'Wed', 11, 11]
Dictionary created with index : {'Mon': 1, 'Tue': 2, 'Wed': 4, 11: 6}
Please note when there are duplicate elements only them is displayed having a higher index value from among the duplicates.
Another approach is to apply the range function to create the keys starting from 1 and going up to the length of the list supplied. Finally, we apply the dict function to create the dictionary.
 Live Demo
Alist = ['Mon', 'Tue', 'Wed', 'Wed',11,11]

# Given list
print("Given list : " , Alist)

# Converting to DIctionary
NewDict = dict(zip(Alist, range(1, len(Alist)+1)))

# print result
print("Dictionary created with index : ",NewDict)
Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Wed', 'Wed', 11, 11]
Dictionary created with index : {'Mon': 1, 'Tue': 2, 'Wed': 4, 11: 6}
Consecutive element maximum product in Python

Python has great libraries to manipulate data. We may come across a need to find the maximum product of two consecutive numbers which are part of the big string. In this article we will see the ways to achieve that.
We convert the string into a list. Then create pairs from the consecutive elements with help of slicing. Applying * we multiply the pair and then take the max value from the result of the multiplication from each of the pairs.
 Live Demo
Astring = '5238521'
# Given string
print("Given String : ",Astring)
# Convert to list
Astring = list(Astring)
print("String converted to list:\n",Astring)
# Using max()
res = max(int(a) * int(b) for a, b in zip(Astring, Astring[1:]))
# Result
print("The maximum consecutive product is : " ,res)
Running the above code gives us the following result −
Given String : 5238521
String converted to list:
['5', '2', '3', '8', '5', '2', '1']
The maximum consecutive product is : 40
We take a similar approach as above. But we use map function to keep generating the pair of consecutive integers. Then use the mul function from operator module to multiply the numbers in this pair. Finally apply the max function to get the max value of the result.
from operator import mul
Astring = '5238521'
# Given string
print("Given String : ",Astring)
# Convert to list
Astring = list(Astring)
print("String converted to list:\n",Astring)
# Using max()
res = max(map(mul, map(int, Astring), map(int, Astring[1:])))
# Result
print("The maximum consecutive product is : " ,res)
Running the above code gives us the following result −
Given String : 5238521
String converted to list:
['5', '2', '3', '8', '5', '2', '1']
The maximum consecutive product is : 40
Sqoop - Job

This chapter describes how to create and maintain the Sqoop jobs. Sqoop job creates and saves the import and export commands. It specifies parameters to identify and recall the saved job. This re-calling or re-executing is used in the incremental import, which can import the updated rows from RDBMS table to HDFS.
The following is the syntax for creating a Sqoop job.
$ sqoop job (generic-args) (job-args)
   [-- [subtool-name] (subtool-args)]

$ sqoop-job (generic-args) (job-args)
   [-- [subtool-name] (subtool-args)]
Here we are creating a job with the name myjob, which can import the table data from RDBMS table to HDFS. The following command is used to create a job that is importing data from the employee table in the db database to the HDFS file.
$ sqoop job --create myjob \
-- import \
--connect jdbc:mysql://localhost/db \
--username root \
--table employee --m 1
‘--list’ argument is used to verify the saved jobs. The following command is used to verify the list of saved Sqoop jobs.
$ sqoop job --list
It shows the list of saved jobs.
Available jobs: 
   myjob

‘--show’ argument is used to inspect or verify particular jobs and their details. The following command and sample output is used to verify a job called myjob.
$ sqoop job --show myjob
It shows the tools and their options, which are used in myjob.
Job: myjob 
 Tool: import Options:
 ---------------------------- 
 direct.import = true
 codegen.input.delimiters.record = 0
 hdfs.append.dir = false 
 db.table = employee
 ...
 incremental.last.value = 1206
 ...

‘--exec’ option is used to execute a saved job. The following command is used to execute a saved job called myjob.
$ sqoop job --exec myjob
It shows you the following output.
10/08/19 13:08:45 INFO tool.CodeGenTool: Beginning code generation 
...


    50 Lectures 
     4 hours 

 Navdeep Kaur
 Print
 Add Notes
 Bookmark this page
C++ Stdexcept Library - out_of_range

It is an out-of-range exception and this class defines the type of objects thrown as exceptions to report an out-of-range error.
Following is the declaration for std::out_of_range.
class out_of_range;
class out_of_range;
none
none
constructor − Here the string passed as what_arg has the same content as the value returned by member what.
In below example for std::out_of_range.
#include <iostream>
#include <stdexcept>
#include <vector>

int main (void) {
   std::vector<int> myvector(10);
   try {
      myvector.at(20) = 100;
   } catch (const std::out_of_range& oor) {
      std::cerr << "Out of Range error: " << oor.what() << '\n';
   }
   return 0;
}
The output should be like this −
Out of Range error: vector::_M_range_check

 Print
 Add Notes
 Bookmark this page
MySQL query to keep only first 2 characters in column value and delete rest of the characters?

To keep only first two characters and delete rest of the characters, use SUBSTRING().
Let us first create a table −
mysql> create table DemoTable743 (SubjectName varchar(100));
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable743 values('MySQL');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable743 values('Java');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable743 values('MongoDB');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable743 values('Python');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable743 values('Data Structure');
Query OK, 1 row affected (0.68 sec)
mysql> insert into DemoTable743 values('Algorithm');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable743;
This will produce the following output -
+----------------+
| SubjectName    |
+----------------+
| MySQL          |
| Java           |
| MongoDB        |
| Python         |
| Data Structure |
| Algorithm      |
+----------------+
6 rows in set (0.00 sec)
Following is the query to keep first 2 characters in column value and delete rest of the characters−
mysql> update DemoTable743 set SubjectName=SUBSTRING(SubjectName,1,2);
Query OK, 6 rows affected (0.12 sec)
Rows matched: 6 Changed: 6 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable743;
This will produce the following output -
+-------------+
| SubjectName |
+-------------+
| My          |
| Ja          |
| Mo          |
| Py          |
| Da          |
| Al          |
+-------------+
6 rows in set (0.00 sec)
C library function - getchar()

The C library function int getchar(void) gets a character (an unsigned char) from stdin. This is equivalent to getc with stdin as its argument.
Following is the declaration for getchar() function.
int getchar(void)
NA
NA
This function returns the character read as an unsigned char cast to an int or EOF on end of file or error.
The following example shows the usage of getchar() function.
#include <stdio.h>

int main () {
   char c;
 
   printf("Enter character: ");
   c = getchar();
 
   printf("Character entered: ");
   putchar(c);

   return(0);
}
Let us compile and run the above program that will produce the following result −
Enter character: a
Character entered: a


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to convert a list collection into a dictionary in Java?

Following is an example to convert a list collection into a dictionary in Java.
 Live Demo
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;

public class CollectionDictionary {
   public static void main(String[] args) {
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFx");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      System.out.println(list);
      Dictionary dictionary = new Hashtable();
      Hashtable<Integer, String> hashTable = new Hashtable<Integer, String>();
      hashTable.put(1, list.get(0));
      hashTable.put(2, list.get(1));
      hashTable.put(3, list.get(2));
      hashTable.put(4, list.get(3));
      System.out.println(hashTable);
   }
}
[JavaFx, Java, WebGL, OpenCV]
{4=OpenCV, 3=WebGL, 2=Java, 1=JavaFx}
Adding table within the plotting region of a ggplot in R - GeeksforGeeks

24 Jun, 2021
In this article, we are going to see how to add the data frame table in the region of the plot using ggplot2 library in R programming language.
Dataset in use:
Here we are plotting a scatterplot, the same can be done for any other plot. To plot a scatter plot in ggplot2, we use the function geom_point( ). 
Syntax:
geom_point(mapping=NULL, data=NULL, stat=”identity”, position=”identity”,...)
Parameter:
size : To assign size to the points.
shape : To assign the shape, ggplot2 library has various shapes which are assigned with a numeric value ranging in [0,25].
Let us first draw a regular plot without a table, so that the difference is apparent.
Example:
R
library(ggplot2)  # Inserting datavacc <- data.frame(catgry=rep(c("Covishield", "Covaxin"), each=2),                   dose=rep(c("D1", "D2"),2),                   slots=c(33, 45, 66, 50))  # To create ggplot2 scatter plotplt <- ggplot(vacc, aes(dose, slots, color = catgry))+  geom_point(shape=8,size = 5)  plt
Output:
To add table to the plot first we create the table using the cbind(). Now we annotate the table using the function annotate(). It is used to specify the location of the table in the ggplot. 
Syntax:
annotate(geom,x,y,xmin,xmax,ymin,ymax,label,vjust,hjust,....)
Parameters :
geom : The name of the geom which is table here for which annotation has to be done
x,y,xmax,ymax,xmin,ymin : Any two of these has to be mentioned in order to set the location of table in plot.
label : Label is the ggp_table here which we want to add in the region of plot.
vjust, hjust : Setting the horizontal and vertical adjust of the table
Before proceeding further we need to install and load another library in R named ggpmisc which stands to Miscellaneous Extensions to ggplot. To install and load write the below command in R Console :
install.packages(“ggpmisc”)
library(ggpmisc)
This library is helpful to put the table in the plot region using the keyword :
geom=”table” // inside the annotate function
Example:
R
library(ggplot2)library(ggpmisc)  # Inserting datavacc <- data.frame(catgry=rep(c("Covishield", "Covaxin"), each=2),                   dose=rep(c("D1", "D2"),2),                   slots=c(33, 45, 66, 50))head(vacc)  # To create ggplot2 scatter plotggplot(vacc, aes(dose, slots, color = catgry))+geom_point(shape=8,size = 5)+ annotate(geom = "table",x = 4,y = 12,                                       label = list(cbind(vacc)))
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
How to do case-sensitive string comparison in JavaScript?

As JavaScript is case sensitive, so case-sensitive comparison are simple string comparisons. This can be done without using any JavaScript method:
<!DOCTYPE html>
<html>
   <body>
      <h3>JavaScript Strings</h3>
      <p id="test"></p>
      <script>
         var str1 = "amit";
         if (str1 === "amit") {
            document.getElementById("test").innerHTML = "correct"
         }
      </script>
   </body>
</html>
Find fibonacci series upto n using lambda in Python

A fibinacci series is a widley known mathematical series that explains many natural phenomenon. It starts with 0 and 1 and then goes on adding a term to its previous term to get the next term. In this article we will see how to generate a given number of elements of the Fibonacci series by using the lambda function in python.
We use the map function to apply the lambda function to each element of the list. We design a list slicing mechanism to get sum of previous two terms and use range to keep count of how many terms we are going to generate.
 Live Demo
def fibonacci(count):
   listA = [0, 1]

   any(map(lambda _:listA.append(sum(listA[-2:])),
         range(2, count)))

   return listA[:count]

print(fibonacci(8))
Running the above code gives us the following result −
[0, 1, 1, 2, 3, 5, 8, 13]
In this approach we use the reduce function along with the lambda function to get the sum of previous two terms. We have to apply lambda twice along with range to keep count of number of terms required and get the final result.
 Live Demo
from functools import reduce

fib_numbers = lambda y: reduce(lambda x, _: x + [x[-1] + x[-2]], range(y - 2), [0, 1])

print(fib_numbers(8))
Running the above code gives us the following result −
[0, 1, 1, 2, 3, 5, 8, 13]
C++ Program to Implement Singly Linked List

Singly linked list is a type of data structure that is made up of nodes that are created using self referential structures. Each of these nodes contain two parts, namely the data and the reference to the next list node. Only the reference to the first list node is required to access the whole linked list. This is known as the head. The last node in the list points to nothing so it stores NULL in that part.
A program to implement singly linked list is given as follows.
 Live Demo
#include <iostream>
using namespace std;
struct Node {
   int data;
   struct Node *next;
};
struct Node* head = NULL;
void insert(int new_data) {
   struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
   new_node->data = new_data;
   new_node->next = head;
   head = new_node;
}
void display() {
   struct Node* ptr;
   ptr = head;
   while (ptr != NULL) {
      cout<< ptr->data <<" ";
      ptr = ptr->next;
   }
}
int main() {
   insert(3);
   insert(1);
   insert(7);
   insert(2);
   insert(9);
   cout<<"The linked list is: ";
   display();
   return 0;
}
The linked list is: 9 2 7 1 3
In the above program, the structure Node forms the linked list node. It contains the data and a pointer to the next linked list node. This is given as follows.
struct Node {
   int data;
   struct Node *next;
};
The function insert() inserts the data into the beginning of the linked list. It creates a new_node and inserts the number in the data field of the new_node. Then the new_node points to the head. Finally the head is the new_node i.e. the linked list starts from there. This is given below.
void insert(int new_data) {
   struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
   new_node->data = new_data;
   new_node->next = head;
   head = new_node;
}
The function display() displays the whole linked list. First ptr points to head. Then it is continuously forwarded to the next node until all the data values of the nodes are printed. This is given below.
void display() {
   struct Node* ptr;
   ptr = head;
   while (ptr != NULL) {
      cout<< ptr->data <<" ";
      ptr = ptr->next;
   }
}
In the function main(), first various values are inserted into the linked list by calling insert(). Then the linked list is displayed. This is given below.
int main() {
   insert(3);
   insert(1);
   insert(7);
   insert(2);
   insert(9);
   cout<<"The linked list is: ";
   display();
   return 0;
}
*args and **kwargs in Python

When we define a function in a python program, the purpose is to execute the code again and again by supplying different values to the function's arguments. One challenge in this design is, what if we are not sure about the number of arguments we want to process each time we call that function. This is where the special arguments called **args and **kwargs are needed. Let's look at them one by one.
The *args enables us to use variable number of arguments as input to the function. In the below example we are finding out the result of multiplication of a series of numbers. The count of these numbers vary each time we call the function.
def findproduct(*many_nums):
result = 1
for num in many_nums:
result = result * num
print("Multiplication result:",result)

findproduct(3,9)
findproduct(2,11,10)
Running the above code gives us the following result −
('Multiplication result:', 27)
('Multiplication result:', 220)
Next, there are scenarios when we want to pass keyword arguments, which are basically key-value pairs as arguments to a function.
Here again, we can pass the variable number of such keyword arguments to the function. Such arguments are named as **kwargs. Please note there are two asterisks when using such arguments. In reality, such keyword arguments are passed on to the program as a python dictionary which holds a number of key-value pairs.
def country_details(**state_info):
   print('\n\n')
   for k,v in state_info.items():
      print("{} is {}".format(k,v))

country_details(StateName="Telangana", Capital="Hyderabad",Population=3400000)
country_details(StateName="Andhra Pradesh", Capital="Amaravati",Population=1000000,ForestCoverage="30%")
Running the above code gives us the following result −
StateName is Telangana
Population is 3400000
Capital is Hyderabad

StateName is Andhra Pradesh
Population is 1000000
ForestCoverage is 30%
Capital is Amaravati
Tryit Editor v3.7

Tryit: Responsive font size
Tryit Editor v3.7

HTML Input attributes
Tryit: The readonly attribute
C++ Program to Sort Elements in Lexicographical Order (Dictionary Order)

Lexicographical order denotes the way the words are ordered in a list, based on alphabetical order according to their alphabets. For example −
List of words:
Harry
Adam
Sam

Lexicographical order of words:
Adam
Harry
Sam
A program to sort elements in lexicographical order is as follows −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int i,j;
   string s[5], temp;
   cout<<"Enter the elements..."<<endl;

   for(i = 0; i < 5; ++i)
   getline(cin, s[i]);
   
   for(i = 0; i < 4; ++i)
   for(j = i+1; j < 5; ++j) {
      if(s[i] > s[j]) {
         temp = s[i];
         s[i] = s[j];
         s[j] = temp;
      }
   }
   cout << "The elements in lexicographical order are... " << endl;
   for(int i = 0; i < 5; ++i)
   cout << s[i] << endl;
   return 0;
}
The output of the above program is as follows −
Enter the elements...
Orange
Grapes
Mango
Apple
Guava

The elements in lexicographical order are...
Apple
Grapes
Guava
Mango
Orange
In the above program, string s[] is defined and the elements are entered by the user. This is given below −
string s[5], temp;
cout<<"Enter the elements..."<<endl;
for(i = 0; i < 5; ++i)
getline(cin, s[i]);
The elements are arranged alphabetically by using nested for loops. The code snippet for this is as follows −
for(i = 0; i < 4; ++i)
for(j = i+1; j < 5; ++j) {
   if(s[i] > s[j]) {
      temp = s[i];
      s[i] = s[j];
      s[j] = temp;
   }
}
Finally all the elements in lexicographical order are displayed. This is given below −
cout << "The elements in lexicographical order are... " << endl;
for(int i = 0; i < 5; ++i)
cout << s[i] << endl;
How to create Titled Border for a component in Java?

To create a titled border for a component in Java, use the createTitledBorder() method. Let’s say we have a panel and we need to set a titled border to it. Here’s our panel −
JPanel panel = new JPanel();
Now, set the border and set the text for the tites border −
panel.setBorder(BorderFactory.createTitledBorder(
   BorderFactory.createEtchedBorder(), "My Demo Table", TitledBorder.LEFT, TitledBorder.TOP));
The following is an example to create a titled border −
package my;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createTitledBorder(
         BorderFactory.createEtchedBorder(), "My Demo Table", TitledBorder.LEFT, TitledBorder.TOP));
      String[][] rec = {
         { "001", "David", "AUS" },
         { "002", "Steve", "AUS" },
         { "003", "Yuvraj", "IND" },
         { "004", "Kane", "NZ" },
         { "005", "Ben", "ENG" },
         { "006", "Eion", "ENG" },
         { "007", "Miller", "SA" },
         { "008", "Rohit", "IND" }
      };
      String[] header = { "Id", "Player", "Team" };
      JTable table = new JTable(rec, header);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}
C++ Program to Generate a Random Directed Acyclic Graph DAC for a Given Number of Edges

In this program we generate a random directed acyclic graph for the given edges ‘e’. The time complexity of this program is O(e*v*e).
Begin
   function GenerateRandomGraphs(), has ‘e’ as the number edges in the argument list.
   generate a connection between two random numbers, for sample a small case, limit the number of vertex to 20.
   Check for the cycle in the graph Using CheckAcyclic(),
   if it returns false discard this edge.
      Else maintain the edge in the graph.
   Print all the directed connection of each vertex.
   If the in+out degree of each vertex is zero then print the vertex as “isolated vertex”.
End
#include<iostream>
#include<stdlib.h>
#define N 10
using namespace std;
bool Checkcyclic(int ed[][2], int edge, bool check[], int v)//to check for the cycle, on addition of a new edge in the random graph.{
   int i;
   // If the current vertex is visited already, then the graph contains cycle.
   if(check[v] == true) {
      return false;
   } else {
      check[v] = true;
      // For each vertex, go for all the vertex connected to it.
      for(i = edge; i >= 0; i--) {
         if(ed[i][0] == v) {
            return Checkcyclic(ed, edge, check, ed[i][1]);
         }
      }
   }
   // In case, if the path ends then reassign the vertexes visited in that path to false again.
   check[v] = false;
   if(i == 0)
      return true;
}

void GenerateRandomGraphs(int e) {
   int i, j, ed[e][2], count;
   bool c[11];
   i = 0;
   while(i < e) {
      ed[i][0] = rand()%N+1;
      ed[i][1] = rand()%N+1;
      for(j = 1; j <= 10; j++)
         c[j] = false;
      if(Checkcyclic(ed, i, c, ed[i][0]) == true)
         i++;
   }
   cout<<"\nThe generated random random graph is: ";
   for(i = 0; i < N; i++) {
      count = 0;
      cout<<"\n\t"<<i+1<<"-> { ";
         for(j = 0; j < e; j++) {
            if(ed[j][0] == i+1) {
               cout<<ed[j][1]<<" ";
               count++;
            } else if(ed[j][1] == i+1) {
               count++;
            } else if(j == e-1 && count == 0)
               cout<<"Isolated Vertex!";
         }
         cout<<" }";
      }
   }
   int main() {
      int e;
      cout<<"Enter the number of edges for the random graphs: ";
      cin>>e;
      GenerateRandomGraphs(e);
   }
}
Enter the number of edges for the random graphs: 4
The generated random random graph is:
1-> { }
2-> { 8 }
3-> { 5 }
4-> { Isolated Vertex! }
5-> { 1 }
6-> { Isolated Vertex! }
7-> { Isolated Vertex! }
8-> { }
9-> { Isolated Vertex! }
10-> { 5 }
File isDirectory() method in Java with Examples - GeeksforGeeks

28 Jan, 2019
The isDirectory() function is a part of File class in Java . This function determines whether the is a file or directory denoted by the abstract filename is Directory or not.The function returns true if the abstract file path is Directory else returns false.
Function signature:
public boolean isDirectory()
Syntax:
file.isDirectory()
Parameters: This method does not accept any parameter.
Return Value: The function returns boolean value representing whether the abstract file path is a directory or not
Exception: This method throws Security Exception if the read access to the file is denied
Below programs illustrates the use of isDirectory() function:
Example 1: The file “F:\\program.txt” is a existing file in F: directory .
// Java program to demonstrate// isDirectory() method of File Class  import java.io.*;  public class solution {    public static void main(String args[])    {          // Get the file        File f = new File("F:\\program");          // Check if the specified path        // is a directory or not        if (f.isDirectory())            System.out.println("Directory");        else            System.out.println("is not Directory");    }}
Output:
Directory
Example 2: The file “F:\\program1” is a non existing directory in F: directory .
// Java program to demonstrate// isDirectory() method of File Class  import java.io.*;  public class solution {    public static void main(String args[])    {          // Get the file        File f = new File("F:\\program1");          // Check if the specified path        // is a directory or not        if (f.isDirectory())            System.out.println("Directory");        else            System.out.println("Not a Directory");    }}
Output:
Not a Directory
Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file.
Java-File Class
Java-Functions
Java-IO package
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Java Programming Examples
How to Iterate HashMap in Java?
How to Apply Different Styles to a Cell in a Spreadsheet using Java?
Iterate through List in Java
Traverse Through a HashMap in Java
Factory method design pattern in Java
Java program to count the occurrence of each character in a string using Hashmap
Java Program to Remove Duplicate Elements From the Array
Create Password Protected Zip File in Java
Min Heap in Java