code-rag-bench/online-tutorials huggingface dataset:
Python: os.path.abspath() method with example

29 Dec, 2019
OS module in Python provides various methods for interacting with the operating system. It comes under Python’s standard utility module, so there is no need to install it externally. os.path is a submodule of OS module which contains some useful functions on pathnames. The path parameters are either strings or bytes. These functions here are used for different purposes such as for merging, normalizing and retrieving path names in Python.
According to docs os.path.abspath() returns a normalized absolutized version of the pathname path which may sound fancy but it simply means that this method returns the pathname to the path passed as a parameter to this function.
Syntax: os.path.abspath(path)
Parameter:Path: A path-like object representing a file system path.
Return Type: This method returns a normalized version of the pathname path.
Example 1:
# Python program to demonstrate# os.path.abspath()    import os.path  # file name   file_name = 'GFG.txt'    # prints the absolute path of current# working directory with  file nameprint(os.path.abspath(file_name))
Output:
/home/geeks/Desktop/gfg/GFG.txt

Example 2: This function can also return the normalized path after changing the current working directory.
# Python program to demonstrate# os.path.abspath()    import os  # file name   file_name = 'GFG.txt'  # change the current working# directoryos.chdir("/home/geeks/")  # prints the absolute path of current# working directory with  file nameprint(os.path.abspath(file_name))
Output:
/home/geeks/GFG.txt

Python directory-program
Python OS-path-module
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Java Program to double the size of an array

To double the size of an array, let us first create an array −
int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
Now, get the length of the above array −
int len = arr.length;
Double the size of the above array −
intnewArray[] = new int[len*2];
Now, newArray[] will be having twice the length of the array arr[].
public class Demo {
   public static void main (String args[]) {
      int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
      System.out.println("Length of initial array = " + arr.length);
      int len = arr.length;
      int newArray[] = new int[len*2];
      System.arraycopy(arr, 0, newArray, 0, len);
      System.out.println("Length of new array = "+newArray.length);
   }
}
Length of initial array = 10
Length of new array = 20
Python | Pandas Series.sum()

10 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Series.sum() method is used to get the sum of the values for the requested axis.
Syntax: Series.sum(axis=None, skipna=None, level=None, numeric_only=None, min_count=0)
Parameters:axis : {index (0)}skipna[boolean, default True] : Exclude NA/null values. If an entire row/column is NA, the result will be NAlevel[int or level name, default None] : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.numeric_only[boolean, default None] : Include only float, int, boolean data. If None, will attempt to use everything, then use only numeric data
Returns: Returns the sum of the values for the requested axis
Code #1: By default, the sum of an empty or all-NA Series is 0.
# importing pandas module import pandas as pd   # min_count = 0 is the defaultpd.Series([]).sum()  # When passed  min_count = 1,# sum of an empty series will be NaNpd.Series([]).sum(min_count = 1)
Output:
0.0
nan
 Code #2:
# importing pandas module import pandas as pd     # making data frame csv at url  data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   # sum of all salaryval = data['Salary'].sum()  val
Output:
2159837111.0
 
Code #3:
# importing pandas module import pandas as pd     # making a dict of listdata = {'name': ['John', 'Peter', 'Karl'],        'age' : [23, 42, 19]}  val = pd.DataFrame(data)  # sum of all salaryval['total'] = val['age'].sum()  val
Output:
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How to get the seed value of an identity column in MySQL?

For this, you can use SHOW VARIABLES command −
mysql> SHOW VARIABLES LIKE 'auto_inc%';
This will produce the following output −
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| auto_increment_increment | 1     |
| auto_increment_offset    | 1     |
+--------------------------+-------+
2 rows in set (0.95 sec)
You can control over AUTO_INCREMENT outside.
Let us first create a table −
mysql> create table DemoTable
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY
   -> );
Query OK, 0 rows affected (0.94 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.44 sec)

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.26 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| StudentId |
+-----------+
| 1         |
| 2         |
+-----------+
2 rows in set (0.00 sec)
Now you can control over the AUTO_INCREMENT −
mysql> alter table DemoTable AUTO_INCREMENT=1000;
Query OK, 0 rows affected (0.50 sec)
Records: 0  Duplicates: 0  Warnings: 0
Insert some records in the table using insert command −
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.51 sec)

mysql> insert into DemoTable values();
Query OK, 1 row affected (1.37 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| StudentId |
+-----------+
|         1 |
|         2 |
|      1000 |
|      1001 |
+-----------+
4 rows in set (0.00 sec)
Python | Pandas Series.tz_convert

30 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.tz_convert() function works with time zone aware indexes. It convert tz-aware axis to target time zone.
Syntax: Series.tz_convert(tz, axis=0, level=None, copy=True)
Parameter :tz : string or pytz.timezone objectaxis : the axis to convertlevel : int, str, default Nonecopy : Also make a copy of the underlying data.
Returns : Series
Example #1: Use Series.tz_convert() function to convert the time zone aware index of the given Series to the target time zone.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                            periods = 6, tz = 'Asia/Calcutta')   # set the indexsr.index = didx  # Print the seriesprint(sr)
Output :
Now we will use Series.tz_convert() function to convert the given time zone index to time zone aware index to the target time zone which is ‘US/Central’.
# convert to 'US / Central'sr.tz_convert('US/Central')
Output :As we can see in the output, the Series.tz_convert() function has converted the time zone of the index of the given series object to the desired time zone. Example #2: Use Series.tz_convert() function to convert the time zone aware index of the given Series to the target time zone.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])  # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                      periods = 5, tz = 'Asia/Calcutta')   # set the indexsr.index = didx  # Print the seriesprint(sr)
Output :
Now we will use Series.tz_convert() function to convert the given time zone index to time zone aware index to the target time zone which is ‘Europe/Berlin’
# convert to 'Europe / Berlin'sr.tz_convert('Europe/Berlin')
Output :
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Site Reliability Engineering

10 Sep, 2020
Site Reliability Engineering, it is a practice that tech giants are practicing now a days where operation problems of an organization are treated as software engineering problem, in other way when a developer is assigned to solve operations problem. Basically, SREs are software engineers who build various softwares to make better reliable systems. The question that arises is isn’t that DevOps? or which is better SRE vs DevOps?
History :This term was first coined by Ben treynor, a software engineer at google in 2003, this practice started lot earlier than DevOps movement. Shortly, after implementing SRE at their premises treynor’s team shortly launched SRE ebook to aware the industry about the practice.
Responsibilities Of Site Reliability Engineers (SREs) :
SREs are accountable and take on-call duties for the systems that are running in production.
SREs are responsible for developing software(s) that improves the reliability of systems.
They are responsible for performing post incident reviews of the systems that fails.
SRE vs DevOps : Which is better?There’s a great analogy to understand the two terms better. So, here it goes, let’s consider DevOps as an interface i.e. similar to abstract class containing methods without definitions, and SRE as a concrete class implementing DevOps.
Interface DevOps{
Reduce Organizational silos();
Accepting failures();
Implement gradual changes();
Leverage Automation();
Measure Everything();
}

Now, SRE as a concrete class will implements DevOps, alongwith defining all methods as :
Reducing the organizational silos, by sharing the ownership among software engineers, product team and SREs by using same set of tools.
Accepting Failures, as no system is 100% reliable so faults will be there, SREs do Blameless post-martems of systems and generate metadata for the same.
Implementing small changes, smaller the change is, easier it is to identify the problem or faster it is to fix the change or rollback. Thereby, reducing the cost of failure.
Leveraging Automation, automating manual tasks, wherever possible on the production system such as user creation, installing packages, alerting or logging etc.
Measuring Everything, at the end monitoring the right things that has implemented, as on the end of the day you should have numbers or clear metrics that supports success.So, SRE and DevOps are not competing standards, rather they go hand in hand together. So, it is SRE with DevOps.
So, SRE and DevOps are not competing standards, rather they go hand in hand together. So, it is SRE with DevOps.
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Software Engineering | Black box testing
Unit Testing | Software Testing
System Testing
Software Engineering | Integration Testing
What is DFD(Data Flow Diagram)?
Software Engineering | Calculation of Function Point (FP)
Difference Between Edge Computing and Fog Computing
Software Development Life Cycle (SDLC)
Software Processes in Software Engineering
Software Engineering | Software Design Process
How to create a Confirmation Dialog Box in Java?

To create a confirmation dialog box in Java, use the Java Swing JOptionPane.showConfirmDialog() method, which allows you to create a dialog box that asks for confirmation from the user. For example, Do you want to restart the system?, “This file contains a virus, Do you want to still download?”, etc. Kt comes with a type JOptionPane.YES_NO_CANCEL_OPTION for the same confirmation.
The following is an example to create a Confirmation Dialog Box in Java −
package my;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class SwingDemo {
   public static void main(String[] args) {
      ImageIcon icon = new ImageIcon("E −\\new.PNG");
      JPanel panel = new JPanel();
      panel.setSize(new Dimension(250, 100));
      panel.setLayout(null);
      JLabel label1 = new JLabel("The file may contain virus.");
      label1.setVerticalAlignment(SwingConstants.BOTTOM);
      label1.setBounds(20, 20, 200, 30);
      label1.setHorizontalAlignment(SwingConstants.CENTER);
      panel.add(label1);
      JLabel label2 = new JLabel("Do you still want to save it?");
      label2.setVerticalAlignment(SwingConstants.TOP);
      label2.setHorizontalAlignment(SwingConstants.CENTER);
      label2.setBounds(20, 80, 200, 20);
      panel.add(label2);
      UIManager.put("OptionPane.minimumSize", new Dimension(400, 200));
      int res = JOptionPane.showConfirmDialog(null, panel, "File",
      JOptionPane.YES_NO_CANCEL_OPTION,
      JOptionPane.PLAIN_MESSAGE, icon);
      if(res == 0) {
         System.out.println("Pressed YES");
      } else if (res == 1) {
         System.out.println("Pressed NO");
      } else {
         System.out.println("Pressed CANCEL");
      }
   }
}
Now, let’s say we clicked on the Yes button. In that case, we have displayed the following on Console. Here, 0 is returned for YES, 1 for NO and 2 for CANCEL −
Explain subn() methods of “re” module in Python ?

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. The re module in python refers to the module Regular Expressions (RE). It specifies a set of strings or patterns that matches it. Metacharacters are used to understand the analogy of RE. 
subn()method is similar to sub() and also returns the new string along with the no. of replacements.
Syntax
re.subn (pattern, repl, string, count=0, flags=0)
Example
import re
print(re.subn('ov', '~*' , 'movie tickets booking in online'))
t = re.subn('ov', '~*' , 'movie tickets booking in online', flags = re.IGNORECASE)
print(t)
print(len(t))
print(t[0])
Here you can see that, subn() method It returns a tuple with count of total of all the replacements as well as the new string.
('m~*ie tickets booking in online', 1)
('m~*ie tickets booking in online', 1)
2
m~*ie tickets booking in online
time.Time.Before() Function in Golang With Examples

19 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Before() function in Go language is used to check if the stated time instant t is before the stated u or not. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) Before(u Time) bool

Here, “t” is the stated time and “u” is the time that is present as an argument in the Before() method.
Return Value: It returns true if “t” is present before “u” else it returns false.
Example 1:
// Golang program to illustrate the usage of// Time.Before() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Declaring t and u in UTC    t := time.Date(2019, 0, 0, 0, 0, 0, 0, time.UTC)    u := time.Date(2020, 0, 0, 0, 0, 0, 0, time.UTC)      // Calling Before method    res := t.Before(u)      // Prints output    fmt.Printf("%v", res)}
Output:
true

Example 2:
// Golang program to illustrate the usage of// Time.Before() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Declaring t and u in UTC    t := time.Date(2030, 0, 0, 0, 0, 0, 0, time.UTC)    u := time.Date(2025, 0, 0, 0, 0, 0, 0, time.UTC)      // Calling Before method    res := t.Before(u)      // Prints output    fmt.Printf("%v", res)}
Output:
false

GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
How to iterate over an Array using for loop in Golang?
Structures in Golang
Loops in Go Language
Time Durations in Golang
Constants- Go Language
Strings in Golang
time.Parse() Function in Golang With Examples
Go Variables
Class and Object in Golang
How to run multiple test cases using TestNG Test Suite in Selenium?

We can run multiple test cases using TestNG test suite in Selenium webdriver. To execute test cases simultaneously, we have to enable parallel execution in TestNG.
A TestNG execution is driven by the TestNG xml file. To trigger parallel execution we have to use the attributes – parallel and thread-count. The attribute threadcount controls the number of threads to be triggered while executing the tests in a parallel mode. The values that can be set for parallel attributes are – tests, classes, instances and methods.
import org.testng.annotations.Test;
public class TestNG15 {
   @Test
   public void tC1() {
      System.out.println("Test Case 1");
   }
   @Test
   public void tC2() {
      System.out.println("Test Case 2");
   }
   @Test
   public void tC3() {
      System.out.println("Test Case 3");
   }
   @Test
   public void tC4() {
      System.out.println("Test Case 4");
   }
}
TestNG XML Implementation.
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<!—parallel methods set for execution with 2 threads-->
<suite name="Test-Suite" parallel="methods" thread-count="2">
   <test name="Tutorialspoint" >
      <classes>
         <class name="TestNG15" />
      </classes>
   </test>
</suite>
TestNG report in html format obtained from project folder test-output→index.html.
AtomicInteger set() method in Java with examples - GeeksforGeeks

29 Jan, 2019
The java.util.concurrent.atomic.AtomicInteger.set() is an inbuilt method in java that updates the previous value and sets it to a new value which is passed in the parameter.
Syntax:
public final void set(int newVal)

Parameters: The function accepts a single mandatory parameter newVal which is to be updated.
Return value: The function does not returns anything.
Program below demonstrates the function:
Program 1:
// Java program that demonstrates// the set() function  import java.util.concurrent.atomic.AtomicInteger;  public class GFG {    public static void main(String args[])    {          // Initially value as 0        AtomicInteger val            = new AtomicInteger(0);          System.out.println("Previous value: "                           + val);          val.set(10);          // Prints the updated value        System.out.println("Current value: "                           + val);    }}
Previous value: 0
Current value: 10

Program 2:
// Java program that demonstrates// the set() function  import java.util.concurrent.atomic.AtomicInteger;  public class GFG {    public static void main(String args[])    {          // Initially value as 18        AtomicInteger val            = new AtomicInteger(18);          System.out.println("Previous value: "                           + val);          val.set(200);          // Prints the updated value        System.out.println("Current value: "                           + val);    }}
Previous value: 18
Current value: 200

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#set–
Java - util package
Java-AtomicInteger
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
LinkedList in Java
Stack Class in Java
Multithreading in Java
Java Inheritance (Subclass and Superclass)

In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:
subclass (child) - the class that inherits from another class
superclass (parent) - the class being inherited from
To inherit from a class, use the extends 
keyword.
In the example below, the Car class 
(subclass) inherits the attributes and methods from the Vehicle class 
(superclass):
class Vehicle {
  protected String brand = "Ford";        // Vehicle attribute
  public void honk() {                    // Vehicle method
    System.out.println("Tuut, tuut!");
  }
}

class Car extends Vehicle {
  private String modelName = "Mustang";    // Car attribute
  public static void main(String[] args) {

    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}
 


Try it Yourself »

Did you notice the protected modifier in Vehicle?
We set the brand attribute in Vehicle to a protected access 
modifier. If it was set to private, the Car class would not be able to access 
it.
- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods to perform different tasks.
If you don't want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:
final class Vehicle {
  ...
}

class Car extends Vehicle {
  ...
}

The output will be something like this:
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.
How to create pivot table with sum for data stored in R data frame?

To create pivot table with sum for data stored in R data frame, we can follow the below steps −
First of all, create a data frame with two categorical and one numerical column.
First of all, create a data frame with two categorical and one numerical column.
Then, use dcast function from reshape2 package to create pivot table for the data stored in data frame.
Then, use dcast function from reshape2 package to create pivot table for the data stored in data frame.
Let’s create a data frame as shown below −
Group<-sample(LETTERS[1:5],25,replace=TRUE)
Gender<-sample(c("Male","Female"),25,replace=TRUE)
Score<-sample(1:100,25)
df<-data.frame(Group,Gender,Score)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
 Group Gender Score
1  B  Male    69
2  B  Male    66
3  D  Male    34
4  D  Male    25
5  E  Male    51
6  B  Male    38
7  E  Male    48
8  A  Female  29
9  D  Male    10
10 C  Female  96
11 E  Female   8
12 D  Male    39
13 E  Female  94
14 D  Female  61
15 A  Female  70
16 B  Male    90
17 B  Female 100
18 B  Female  27
19 A  Female  33
20 A  Female  98
21 A  Male    32
22 B  Female  78
23 E  Male    86
24 D  Male    74
25 A  Female  99
Create pivot table
Using dcast function from reshape2 package to create pivot table for the data stored in data frame df −
Group<-sample(LETTERS[1:5],25,replace=TRUE)
Gender<-sample(c("Male","Female"),25,replace=TRUE)
Score<-sample(1:100,25)
df<-data.frame(Group,Gender,Score)
library(reshape2)
dcast(data=df,formula=Group~Gender,fun.aggregate=sum,value.var="Score")
   Group Female Male
1  A      152   181
2  B      177   117
3  C       83    66
4  D      137    51
5  E      196   149
How do inline variables work in C++/C++17?

In C++, we can use the inline keyword for functions. In C++ 17 version, the inline variable concept has come.
The inline variable is allowed to be defined in multiple translation units. It also follows the one definition rule. If this is defined more than one time, the compiler merges them all into a single object in final program.
In C++ (before C++17 version), we cannot initialize the value of static variables directly in the class. We have to define them outside of the class.
#include<iostream>
using namespace std;
class MyClass {
   public:
      MyClass() {
         ++num;
      }
      ~MyClass() {
         --num;
      }
      static int num;
};
int MyClass::num = 10;
int main() {
   cout<<"The static value is: " << MyClass::num;
}
The static value is: 10
In C++17, we can initialize the static variables inside the class using inline variables.
#include<iostream>
using namespace std;
class MyClass {
   public:
      MyClass() {
         ++num;
      }
      ~MyClass() {
         --num;
      }
      inline static int num = 10;
};
int main() {
   cout<<"The static value is: " << MyClass::num;
}
The static value is: 10
Count the number of objects using Static member function in C++

Here we will see how to count number of objects are created from a specific class using some static member functions. The static members are class properties, not the object properties. For a single class there will be only one instance for static members. No new members are created for each objects.
In this problem we are using one static counter variable to keep track the number of objects, then static member will be there to display the count
value.
When a new object is created, so the constructor will be called. Inside the constructor, the count value is increased. Thus we can get the output.
#include <iostream>
using namespace std;
class My_Class{
   private:
      static int count;
   public:
      My_Class() { //in constructor increase the count value
         cout << "Calling Constructor" << endl;
         count++;
      } static int objCount() {
         return count;
      }
   };
int My_Class::count;
main() {
   My_Class my_obj1, my_obj2, my_obj3;
   int cnt;
   cnt = My_Class::objCount();
   cout << "Number of objects:" << cnt;
}
Calling Constructor
Calling Constructor
Calling Constructor
Number of objects:3
Python SQLite - Join

When you have divided the data in two tables you can fetch combined records from these two tables using Joins.
Assume we have created a table with name CRICKETERS using the following query −
sqlite> CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Age int,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255)
);
sqlite>

Let us create one more table OdiStats describing the One-day cricket statistics of each player in CRICKETERS table.
sqlite> CREATE TABLE ODIStats (
   First_Name VARCHAR(255),
   Matches INT,
   Runs INT,
   AVG FLOAT,
   Centuries INT,
   HalfCenturies INT
);
sqlite>
Following statement retrieves data combining the values in these two tables −
sqlite> SELECT
   Cricketers.First_Name, Cricketers.Last_Name, Cricketers.Country,
   OdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies
   from Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name;
First_Name Last_Name    Country  Matches    Runs          Centuries  HalfCenturies
---------- ----------   -------  ---------- ------------- ---------- ----------
Shikhar    Dhawan       Indi     133        5518          17         27
Jonathan   Trott        Sout     68         2819          4          22
Kumara     Sangakkara   Sril     404        14234         25         93
Virat      Kohli        Indi     239        11520         43         54
Rohit      Sharma       Indi     218        8686          24         42
sqlite>

Following SQLite example, demonstrates the JOIN clause using python −
import sqlite3

#Connecting to sqlite
conn = sqlite3.connect('example.db')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Retrieving data
sql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID'''

#Executing the query
cursor.execute(sql)

#Fetching 1st row from the table
result = cursor.fetchall();
print(result)

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()
[('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, 'Krishna@mymail.com', 'Hyderabad'), 
   ('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102,'Raja@mymail.com', 'Vishakhapatnam'), 
   ('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, 'Krishna@mymail.com', 'Pune'), 
   ('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, 'Raja@mymail.com', 'Mumbai')]


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Grant all privileges of a database to a MySQL user?

First, create a user and password using CREATE command. The syntax is as follows.
CREATE USER 'yourUserName'@'localhost' IDENTIFIED BY 'yourPassword';
The syntax to give all privileges of the specific database to the user is as follows.
GRANT ALL PRIVILEGES ON yourDatabaseName . * TO 'yourUserName'@'localhost';
Now you can implement the above syntaxes to create a user and grant all privileges. The query is as follows to create a user.
mysql> create user 'Adam Smith'@'localhost' IDENTIFIED BY 'Adam123456';
Query OK, 0 rows affected (0.29 sec)
Now, grant all privileges to the user. The query is as follows.
mysql> GRANT ALL PRIVILEGES ON test . * TO 'Adam Smith'@'localhost';
Query OK, 0 rows affected (0.19 sec)
How can I use a script to create users in MongoDB?

You can use createUser() method for this. Following is the syntax −
db.createUser(
   {
      user: "yourUserName",
      pwd: "yourPassword",
      roles: [ { role: "read", db: "yourDatabaseName" } ]
   }
);
Let us create a user in MongoDB. Here, we are using database ‘test’ −
> db.createUser(
...    {
...       user: "David",
...       pwd: "David123456",
...       roles: [ { role: "read", db: "test" } ]
...    }
... );
This will produce the following output −
Successfully added user: {
   "user" : "David",
   "roles" : [
      {
         "role" : "read",
         "db" : "test"
      }
   ]
}
How to find a matching substring using regular expression in C#?

Our string is −
string str = " My make ";

Use the following regular expression to find the substring “make”
@"\bmake\b"

Here is the complete code −
 Live Demo
using System;
using System.Text.RegularExpressions;

namespace RegExApplication {
   public class Program {
      private static void showMatch(string text, string expr) {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);

         foreach(Match m in mc) {
            Console.WriteLine("Found:" + m);
         }
      }

      public static void Main(string[] args) {
         string str = "My make";

         Console.WriteLine("Matching words start with 'm' and ends with 'e':");
         showMatch(str, @"\bmake\b");
      }
   }
}
Matching words start with 'm' and ends with 'e':
The Expression: \bmake\b
Found:make
Common error in Group By - GeeksforGeeks

19 Jun, 2019
Prerequisite: SQL | GROUP BY
Error:Column ‘col’ is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Examples:
Input: 
select empId, empName, empAmount from emp group by empId, empName

Output: Error 
Explanation:empAmount is not in group by list and is neither an aggregate function, the query will give above error. For empId and empName there are multiple empAmount, Database engine could not choose one empAmount.
Input: 
select empId, sum(empAmount) as debit from emp group by empId

Output:
empId | debit
1     | 300
2     | 400 
GROUP BY:From the above examples it is clear that we can have only those columns which are there in the group by or arguments of an aggregate function in the select clause. but that’s not completely true.
“The 1999 and 2003 versions of the SQL standard require that the columns appearing in the SELECT list are functionally dependent upon the groups defined by the GROUP BY clause. In other words, if we know that a column contains only one value for any given combination of values in the columns appearing in the GROUP BY clause, we may reference the column in the SELECT list even if it does not appear in an aggregate expression”–By Roland Bouman
In layman terms:
If columns in group by has a column which is either the primary key or unique key then the combination will only have one value for other columns.
But grouping by a unique column does not make sense but it will become useful when other tables are involved.
A Few Exceptions:MySQL lets you SELECT anything in a query with group by. It will select in random order and whatever is first will return you.
Example:
Input:
select empId, empName, empAmount from emp group by empId, empName 
The above query will not give any error. It will pick random empAmount from the list and pair it with the empID and empName.
The correct behavior can be enabled by adding a flag (i.e., ONLY_FULL_GROUP_BY) or by using MySQL v5.7.5 or higher. In that case, the query would raise the above error.
DBMS-SQL
SQL-basics
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Delete Duplicate Rows
SQL Query to Convert VARCHAR to INT
SQL - SELECT from Multiple Tables with MS SQL Server
How to Select Data Between Two Dates and Times in SQL Server?
Program to find Smallest and Largest Word in a String in C++

In this problem, we are given string str. Our task is to create a program to
find Smallest and Largest Word in a String in C++.
Problem Description − Here, we have a string we need to find the word whose length is maximum and minimum out of all words in the string. The word is separated using white spaces or null(\0) characters.
Let’s take an example to understand the problem
str = “Learn Programming at TutorialsPoint”
smallest word = at
largest word = Tutorialspoint
To find the smallest and largest word, we will find the length of each word
by using two indexes, one for the start of the word and one for the ending
which is marked using the ‘ ’ (space character) or ‘\0’ character. Then using
the start and end index, we will find the maxLength and minlength. And
update the smallestWord and largestWord based on the current word’s
length.
Program to illustrate the working of our solution
 Live Demo
#include<iostream>
#include<cstring>
using namespace std;
void minMaxLengthWords(string str){
   int StrLength = str.length();
   int startIndex = 0, endIndex = 0;
   int minLength = StrLength, maxLength = 0, currentLength;
   string smallest, largest;
   while (endIndex <= StrLength){
      if (str[endIndex] != '\0' && str[endIndex] != ' ')
         endIndex++;
      else{
         currentLength = endIndex - startIndex;
         if (currentLength < minLength){
            smallest = str.substr(startIndex, currentLength);
            minLength = currentLength;
         }
         if (currentLength > maxLength){
            largest = str.substr(startIndex, currentLength);
            maxLength = currentLength;
         }
         endIndex++;
         startIndex = endIndex;
      }
   }
   cout<<"Smallest Word from the string is "<<smallest<<"\n";
   cout<<"Smallest Word from the string is "<<largest;
}
int main() {
   string a = "Learn Programming at TutorialsPoint";
   minMaxLengthWords(a);
}
Smallest Word from the string is at
Smallest Word from the string is TutorialsPoint
\bigcap - Tex Command

\bigcap - Used to draw bigcap symbol.
{ \bigcap }
\bigcap command is used to draw bigcap symbol.

\bigcap

⋂



\bigcap

⋂


\bigcap

    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 Get the Size of Given File in Bytes, KiloBytes and MegaBytes

09 Mar, 2021
The in-built File.length() method in java can be used to get file size in java. The length() function is a part of the File class in Java. This function returns the length of the file whose path was specified. If the file does not exist or some error happens then it returns 0.
Parameters: This method does not accept any parameter.
Syntax:
long len = file.length()
In the same way, exists() function is also a part of the File class in Java. This function determines whether the file or directory denoted by the abstract filename exists or not. The function returns true if the file whose path is given exists and if not then it returns false
Syntax:
file.exists()
Parameters: This method also does not accept any parameter.
Returns: True or False
This example shows how to get a file’s size in bytes by using file.exists() and file.length() method of File class.
Java
// Simple Java Program find  the size of the fileimport java.io.File;public class GFG {    public static void main(String[] args)    {        // create file object enter the path of        // the file for which size is to be found        File file = new File("/home/user/GFG.txt");        if (file.exists()) {            double bytes = file.length();            double kilobytes = (bytes / 1024);              // converting file size to bytes to kb            double megabytes = (kilobytes / 1024);              // converting file size tolb to mb            double gigabytes = (megabytes / 1024);              System.out.println("bytes : " + bytes);            System.out.println("kilobytes : " + kilobytes);            System.out.println("megabytes : " + megabytes);        }        else {            System.out.println("File does not exists!");        }    }}
bytes : 17,07,91,615
kilobytes : 1,66,788.686
megabytes : 162.8795766
Note: If you want file size in Gigabytes then again you have to divide mb value by 1024 and so on.
But Nowadays we can directly use File.size(path) after Java 7. In this we do not have to create file object we can directly find the size of the file.
Java-Files
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Factory method design pattern in Java
Implementing a Linked List in Java using Class
Java Program to Remove Duplicate Elements From the Array
Tuple Relational Calculus (TRC) in DBMS

30 Nov, 2021
Tuple Relational Calculus is a non-procedural query language unlike relational algebra. Tuple Calculus provides only the description of the query but it does not provide the methods to solve it. Thus, it explains what to do but not how to do. In Tuple Calculus, a query is expressed as 
{t| P(t)}
where t = resulting tuples, P(t) = known as Predicate and these are the conditions that are used to fetch t 
Thus, it generates set of all tuples t, such that Predicate P(t) is true for t. 
P(t) may have various conditions logically combined with OR (∨), AND (∧), NOT(¬). It also uses quantifiers: ∃ t ∈ r (Q(t)) = ”there exists” a tuple in t in relation r such that predicate Q(t) is true. ∀ t ∈ r (Q(t)) = Q(t) is true “for all” tuples in relation r. 
Example: Table-1: Customer 
Table-2: Branch 
Table-3: Account 
Table-4: Loan 
Table-5: Borrower 
Table-6: Depositor 
Queries-1: Find the loan number, branch, amount of loans of greater than or equal to 10000 amount.  
{t| t ∈ loan  ∧ t[amount]>=10000}
Resulting relation: 
In the above query, t[amount] is known as tuple variable. 
Queries-2: Find the loan number for each loan of an amount greater or equal to 10000.  
{t| ∃ s ∈ loan(t[loan number] = s[loan number]  
                   ∧ s[amount]>=10000)}
Resulting relation: 
Queries-3: Find the names of all customers who have a loan and an account at the bank.  
{t | ∃ s ∈ borrower( t[customer-name] = s[customer-name])   
     ∧  ∃ u ∈ depositor( t[customer-name] = u[customer-name])}
Resulting relation: 
Queries-4: Find the names of all customers having a loan at the “ABC” branch.  
{t | ∃ s ∈ borrower(t[customer-name] = s[customer-name]  
   ∧ ∃ u ∈  loan(u[branch-name] = “ABC” ∧ u[loan-number] = s[loan-number]))}
Resulting relation: 
Nityananda Gohain
VijaykumarSakhare
simmytarika5
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
CTE in SQL
Difference between Clustered and Non-clustered index
Layers of OSI Model
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
GATE | GATE CS Mock 2018 | Set 2 | Question 42 - GeeksforGeeks

08 Mar, 2018
S1 : Anyone of the followings can be used to declare a node for a singly linked list. If we use the first declaration, “struct node * nodePtr;” would be used to declare pointer to a node. If we use the second declaration, “NODEPTR nodePtr;” can be used to declare pointer to a node.
/* First declaration */
struct node {
int data;
struct node * nextPtr;
};

/* Second declaration */
typedef struct node{
int data;
NODEPTR nextPtr;
} * NODEPTR;

S2 : Anyone of the following can be used to declare a node for a singly linked list and “NODEPTR nodePtr;” can be used to declare pointer to a node using any of the following
/* First declaration */
typedef struct node
{
 int data;
 struct node *nextPtr;
}* NODEPTR;

/* Second declaration */
struct node
{
 int data;
 struct node * nextPtr;
};
typedef struct node * NODEPTR;

(A) Statement S1 is true and statement S2 is false(B) Statement S2 is true and statement S1 is false(C) Both statements S1 and S2 are true(D) Neither statement S1 nor statement S2 is trueAnswer: (B)Explanation: S1 : The typedef usage is incorrect. Basically, we can’t use yet to be typedef-ed data type inside while applying typedef itself. Here, NODEPTR is yet to be defined (i.e. typedef-ed) and we are using NODEPTR inside the struct itself.
S2 : Yes. Both are equivalent. Either of the above declarations can be used for “NODEPTR nodePtr;”. In fact, first one is the compact form of second one.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
journalctl Command in Linux with Examples

10 Feb, 2022
journalctl command in Linux is used to view systemd, kernel and journal logs. The logs are presented in the following way:
-- Logs begin at [date_time_stamp], end at [dat_time_stamp]
[date_time_stamp] [host_name] kernel:

It displays the paginated output, hence it is a bit easy to navigate through a lot of logs. It prints the log in the chronological order with the oldest first.
1. To display all logs
$journalctl

It displays all the logs in the paginated view.
2. To reverse the order or to display the new entries first.
$journalctl -r

This will display the logs in the chronological order with the newest first.
3. To display only a few log entries
$journalctl -n 2

This will display just 2 log entries.
4. To get log entries containing a specific keyword.
$journalctl | grep Centaur

This will display all the entries containing the word Centaur in them.
5. To display priority specific log entries.
$journalctl -p warning

It displays all log entries with priority as a warning.
6. To print verbose customized output.
$journalctl -o verbose

This will display the formatted output in verbose mode.
7. To display the boots of the system.
$journalctl --list-boots

To display all the boots of the system.
8. To display journalctl help.
$journalctl --help

The above command will display the help section of the journalctl command.
rkbhola5
linux-command
Linux-system-commands
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
SED command in Linux | Set 2
mv command in Linux with examples
chmod command in Linux with examples
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting