code-rag-bench/online-tutorials huggingface dataset:
File structures (sequential files, indexing, B and B+ trees) - GeeksforGeeks

09 Oct, 2019
Here block size is 10^3 B.
No. of entries in the FAT = Disk capacity/ Block size 
                          = 10^8/10^3 
                          = 10^5
Total space consumed by FAT = 10^5 *4B 
                            = 0.4*10^6B
Max. size of file that can be stored = 100*10^6-0.4*10^6
                                     = 99.6*10^6B.
So answer 99.6.

Name     Age    Occupation    Category
Rama     27       CON            A
Abdul    22       ENG            A
Jeniffer 28       DOC            B
Maya     32       SER            D
Dev      24       MUS            C

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
Axios in React: A Guide for Beginners
How to pass property from a parent component props to a child component ?
BigInt (BIG INTEGERS) in C++ with Example
How to Install Flutter on Visual Studio Code?
How to calculate MOVING AVERAGE in a Pandas DataFrame?
Retrofit with Kotlin Coroutine in Android
Get Hired With GeeksforGeeks and Win Exciting Rewards!
How to insert a pandas DataFrame to an existing PostgreSQL table?
Delete Cookies On All Domains using Selenium Webdriver.

We can delete cookies on all domains with Selenium. The method deleteAllCookies is used to delete all cookies from the present domain. First, we shall add cookies, then get them and finally delete all the cookies.
driver.manage().deleteAllCookies();
import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class DeleteCookies{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      // wait of 4 seconds
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // setting name and value for cookie
      Cookie c = new Cookie("test", "selenium");
      Cookie r = new Cookie("subject", "Java");
      // cookie addition
      driver.manage().addCookie(c);
      driver.manage().addCookie(r);
      // obtain the cookies
      Set ck = driver.manage().getCookies();
      System.out.println("Cookie count: "+ck.size());
      // delete cookies
      driver.manage().deleteAllCookies();
      // obtain the cookies after delete
      Set ch = driver.manage().getCookies();
      System.out.println("Cookie count after delete: "+ch.size());
   }
}
Difference between DELETE, DROP and TRUNCATE - GeeksforGeeks

24 Dec, 2021
Basically, it is a Data Manipulation Language Command (DML). It is used to delete one or more tuples of a table. With the help of the “DELETE” command, we can either delete all the rows in one go or can delete rows one by one. i.e., we can use it as per the requirement or the condition using the Where clause. It is comparatively slower than the TRUNCATE command. The TRUNCATE command does not remove the structure of the table.
SYNTAX – If we want to delete all the rows of the table:
DELETE from;
SYNTAX – If we want to delete the row of the table as per the condition then we use the WHERE clause,
DELETE from  WHERE  ;
Note – Here we can use the “ROLLBACK” command to restore the tuple because it does not auto-commit.
It is a Data Definition Language Command (DDL). It is used to drop the whole table. With the help of the “DROP” command we can drop (delete) the whole structure in one go i.e. it removes the named elements of the schema. By using this command the existence of the whole table is finished or say lost. 
SYNTAX – If we want to drop the table:
DROP table ;
Note – Here we can’t restore the table by using the “ROLLBACK” command because it auto commits.
It is also a Data Definition Language Command (DDL). It is used to delete all the rows of a relation (table) in one go. With the help of the “TRUNCATE” command, we can’t delete the single row as here WHERE clause is not used. By using this command the existence of all the rows of the table is lost. It is comparatively faster than the delete command as it deletes all the rows fastly. 
SYNTAX – If we want to use truncate :
TRUNCATE;
Note – Here we can’t restore the tuples of the table by using the “ROLLBACK” command.
chandradharrao
DBMS
GATE CS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of B-Tree
Difference between Clustered and Non-clustered index
CTE in SQL
Introduction of ER Model
SQL | Views
Layers of OSI Model
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems
Differences between TCP and UDP
How to catch EnvironmentError Exception in Python?

EnvironmentError is the base class for errors that come from outside of Python (the operating system, filesystem, etc.). EnvironmentError Exception is a subclass of the StandarError class. It is the base class for IOError and OSError exceptions. It is not actually raised unlike its subclass errors like IOError and OSError.
Any example of an IOError or OSError should be an example of Environment Error as well.
import sys
try:
f = open ( "JohnDoe.txt", 'r' )
except Exception as e:
print e
print sys.exc_type
[Errno 2] No such file or directory: 'JohnDoe.txt'
<type 'exceptions.IOError'>
What is overloading in C#?

C# provides two techniques to implement static polymorphism −
Function overloading
Operator overloading
Two or more than two methods having the same name but different parameters is what we call function overloading in C#.
Function overloading in C# can be performed by changing the number of arguments and the data type of the arguments.
Let’s say you have a function that prints multiplication of numbers, then our overloaded methods will have the same name but different number of arguments −
public static int mulDisplay(int one, int two) { }
public static int mulDisplay(int one, int two, int three) { }
public static int mulDisplay(int one, int two, int three, int four) { }
The following is an example showing how to implement function overloading −
 Live Demo
using System;
public class Demo {
   public static int mulDisplay(int one, int two) {
      return one * two;
   }

   public static int mulDisplay(int one, int two, int three) {
      return one * two * three;
   }
   
   public static int mulDisplay(int one, int two, int three, int four) {
      return one * two * three * four;
   }
}

public class Program {
   public static void Main() {
      Console.WriteLine("Multiplication of two numbers: "+Demo.mulDisplay(10, 15));
      Console.WriteLine("Multiplication of three numbers: "+Demo.mulDisplay(8, 13, 20));
      Console.WriteLine("Multiplication of four numbers: "+Demo.mulDisplay(3, 7, 10, 7));
   }
}
Multiplication of two numbers: 150
Multiplication of three numbers: 2080
Multiplication of four numbers: 1470
Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined.
The following shows which operators can be overloaded and which you cannot overload −
How to create a new column in an R data frame based on some condition of another column?

Sometimes we want to change a column or create a new by using other columns of a data frame in R, this is mostly required when we want to create a categorical column but it can be done for numerical columns as well. For example, we might want to create a column based on salary for which if salaries are greater than the salary in another column then adding those salaries otherwise taking the difference between them. This will help us to understand whether the salaries in two columns are equivalent, lesser, or greater. In R, we can use transform function for this purpose.
Consider the below data frame:
Live Demo
> set.seed(1001)
> x1<-rpois(20,1)
> y1<-rpois(20,5)
> df1<-data.frame(x1,y1)
> df1
  x1 y1
1  4  6
2  1  4
3  1  9
4  1  6
5  1  4
6  2  7
7  0  6
8  0  3
9  0  8
10 2  4 
11 1  5
12 0  9
13 2 10
14 1  4
15 0  3
16 2  2
17 0  2
18 0  6
19 0  6
20 2  2
Creating a column z1 in which y1 will be subtracted from x1 if x1 is greater than y1, otherwise added:
> df1<-transform(df1,z1=ifelse(x1>y1,x1-y1,x1+y1))
> df1
  x1 y1 z1
1  4  6 10
2  1  4  5
3  1  9 10
4  1  6  7
5  1  4  5
6  2  7  9
7  0  6  6
8  0  3  3
9  0  8  8
10 2  4  6
11 1  5  6
12 0  9  9
13 2 10 12
14 1  4  5
15 0  3  3
16 2  2  4
17 0  2  2
18 0  6  6
19 0  6  6
20 2  2  4
> df2<-transform(df1,z1=ifelse(x1 df2
  x1 y1 z1
1  4  6  2
2  1  4  3
3  1  9  8
4  1  6  5
5  1  4  3
6  2  7  5
7  0  6  6
8  0  3  3
9  0  8  8
10 2  4  2
11 1  5  4
12 0  9  9
13 2 10  8
14 1  4  3
15 0  3  3
16 2  2  4
17 0  2  2
18 0  6  6
19 0  6  6
20 2  2  4
> df3<-transform(df1,z1=ifelse(x1==y1,x1*y1,x1/y1))
> df3
  x1 y1 z1
1 4 6 0.6666667
2 1 4 0.2500000
3 1 9 0.1111111
4 1 6 0.1666667
5 1 4 0.2500000
6 2 7 0.2857143
7 0 6 0.0000000
8 0 3 0.0000000
9 0 8 0.0000000
10 2 4 0.5000000
11 1 5 0.2000000
12 0 9 0.0000000
13 2 10 0.2000000
14 1 4 0.2500000
15 0 3 0.0000000
16 2 2 4.0000000
17 0 2 0.0000000
18 0 6 0.0000000
19 0 6 0.0000000
20 2 2 4.0000000
What are sealed modifiers in C#?

When you use sealed modifiers in C# on a method, then the method loses its capabilities of overriding. The sealed method should be part of a derived class and the method must be an overridden method.
Let us see an example −
The following example won’t allow you to override the method display() because it has a sealed modifier for the ClassTwo derived class −
ClassOne is our base class, whereas ClassTwo and ClassThree are derived classes −
class ClassOne {
   public virtual void display() {
      Console.WriteLine("baseclass");
   }
}

class ClassTwo : ClassOne {
   public sealed override void display() {
      Console.WriteLine("ClassTwoderivedClass");
   }
}

class ClassThree : ClassTwo {
   public override void display() {
      Console.WriteLine("ClassThree: Another Derived Class");
   }
}
Above, under ClassThree derived class we have tried to override the sealed method. This will show an error since it is not allowed when you use the sealed method.
Convert C/C++ code to assembly language

Here we will see how to generate assembly language output from C or C++ source code using gcc.
The gcc provides a great feature to get all intermediate outputs from a source code while executing. To get the assembler output we can use the option ‘-S’ for the gcc. This option shows the output after compiling, but before sending to the assembler. The syntax of this command is like below.
gcc –S program.cpp
Now, let us see how to output will be look like. Here we are using a simple program. In this program two numbers are stored into the variables x and y, then store the sum into another variable, after that print the result.
#include <iostream>
using namespace std;
main() {
   int x, y, sum;
   x = 50;
   y = 60;
   sum = x + y;
   cout << "Sum is: " << sum << endl;
}
.file "test_cpp.cpp"
.text
.section .rodata
.type _ZStL19piecewise_construct, @object
.size _ZStL19piecewise_construct, 1
_ZStL19piecewise_construct:
.zero 1
.local _ZStL8__ioinit
.comm _ZStL8__ioinit,1,1
.LC0:
.string "Sum is: "
.text
.globl main
.type main, @function
main:
.LFB1493:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl $50, -12(%rbp)
movl $60, -8(%rbp)
movl -12(%rbp), %edx
movl -8(%rbp), %eax
addl %edx, %eax
movl %eax, -4(%rbp)
leaq .LC0(%rip), %rsi
leaq _ZSt4cout(%rip), %rdi
call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT
movq %rax, %rdx
movl -4(%rbp), %eax
movl %eax, %esi
movq %rdx, %rdi
call _ZNSolsEi@PLT
movq %rax, %rdx
movq
_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_@GOTPCREL(%rip),
%rax
movq %rax, %rsi
movq %rdx, %rdi
call _ZNSolsEPFRSoS_E@PLT
movl $0, %eax
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE1493:
.size main, .-main
.type _Z41__static_initialization_and_destruction_0ii, @function
_Z41__static_initialization_and_destruction_0ii:
.LFB1982:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl %edi, -4(%rbp)
movl %esi, -8(%rbp)
cmpl $1, -4(%rbp)
jne .L5
cmpl $65535, -8(%rbp)
jne .L5
leaq _ZStL8__ioinit(%rip), %rdi
call _ZNSt8ios_base4InitC1Ev@PLT
leaq __dso_handle(%rip), %rdx
leaq _ZStL8__ioinit(%rip), %rsi
movq _ZNSt8ios_base4InitD1Ev@GOTPCREL(%rip), %rax
movq %rax, %rdi
call __cxa_atexit@PLT
.L5:
nop
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE1982:
.size _Z41__static_initialization_and_destruction_0ii,
.-_Z41__static_initialization_and_destruction_0ii
.type _GLOBAL__sub_I_main, @function
_GLOBAL__sub_I_main:
.LFB1983:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $65535, %esi
movl $1, %edi
call _Z41__static_initialization_and_destruction_0ii
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE1983:
.size _GLOBAL__sub_I_main, .-_GLOBAL__sub_I_main
.section .init_array,"aw"
.align 8
.quad _GLOBAL__sub_I_main
.hidden __dso_handle
.ident "GCC: (Ubuntu 7.3.0-16ubuntu3) 7.3.0"
.section .note.GNU-stack,"",@progbits
Add the element in a Python list with help of indexing

A python list is a collection data type that is ordered and changeable. Also, it allows duplicate members. It is the most frequently used collection data type used in Python programs. We will see how we can add an element to a list using the index feature.
But before adding the element in an existing link, let's access the elements in a list using the index feature.
every element in the list is associated with an index and that is how the elements remain ordered. We can access the elements by looping through the indexes. The below program prints the elements at indices 1 and 2. The last index value is not included in the search.
 Live Demo
vowels_list = ['a','i','o', 'u']
print(vowels_list[1:3])
Running the above code gives us the following result:
['i', 'o']
We can also use the same concept to add the element at a particular index. In the below program we are adding the element at index position 1.
 Live Demo
vowels = ['a','i','o', 'u']

print("values before indexing are :",vowels)
#index
vowels.insert(1, 'e')

print('\nafter adding the element at the index 1 is : ', vowels)
Running the above code gives us the following result:
values before indexing are : ['a', 'i', 'o', 'u']
after adding the element at the index 1 is : ['a', 'e', 'i', 'o', 'u']
Find column with maximum sum in a Matrix using C++.

Suppose we have a matrix of size M x N. We have to find the column, that has a maximum sum. In this program we will not follow some tricky approach, we will traverse the array column-wise, then get the sum of each column, if the sum is the max, then print the sum and the column index.
#include<iostream>
#define M 5
#define N 5
using namespace std;
int colSum(int colIndex, int mat[M][N]){
   int sum = 0;
   for(int i = 0; i<M; i++){
      sum += mat[i][colIndex];
   }
   return sum;
}
void maxColumnSum(int mat[M][N]) {
   int index = -1;
   int maxSum = INT_MIN;
   for (int i = 0; i < N; i++) {
      int sum = colSum(i, mat);
      if (sum > maxSum) {
         maxSum = sum;
         index = i;
      }
   }
   cout << "Index: " << index << ", Column Sum: " << maxSum;
}
int main() {
   int mat[M][N] = {
      { 1, 2, 3, 4, 5 },
      { 5, 3, 1, 4, 2 },
      { 5, 6, 7, 8, 9 },
      { 0, 6, 3, 4, 12 },
      { 9, 7, 12, 4, 3 },
   };
   maxColumnSum(mat);
}
Index: 4, Column Sum: 31
Setting up PostgreSQL in Debian-based Linux | by Colton Magnant | Towards Data Science

In trying to set up a PostgreSQL server in my Linux boxes to practice SQL commands on my own, I ran into a few snags along the way, so I decided to put together this tutorial for my future self in case I ever needed to install again. After installing the base system, I was also able to obtain a dump from a small test database for practice purposes... so I’ve also included the commands I used to load this database file.
Note: This process was tested on Linux Mint 19 Tara and Ubuntu 18.04 around November of 2019.
Many of the steps below were obtained from this nice Wixel post: https://wixelhq.com/blog/how-to-install-postgresql-on-ubuntu-remote-access
Preparation and Installation
The default repositories for Ubuntu and Mint (and others) have the Postgres packages so we can use apt to install.
$ sudo apt update$ sudo apt install postgresql postgresql-contrib
Setup of Roles
The installation of Postgres creates a user postgres with access to a default postgres database. Access this by first switching to the postgres user and running psql.
$ sudo -i -u postgrespostgres@server:~$ psql
You now have direct access to the default postgres database. Note that “\q” allows you to exit the Postgres prompt.
postgres=# \q
Now that you have confirmed the functionality of Postgres, it’s time to set up roles. Still within the postgres account, execute the following.
postgres@server:~$ createuser --interactive
This will guide you through the process of setting up a new user. More details on other flags can be found in the createuser man pages.
Note: it may be useful to first create a role with the same name as your user account as the superuser.
Running psql now (as the username with the same name as the role you just created) will result in an error. Although you have created a role, the default database for each role is the database with the same name as the role. It is therefore necessary to either supply the name of the database you wish to connect to or create a corresponding database, addressed in the following sections.
Access a Particular Database
Assuming that your role (your username) has been granted access to a database {dbname}, you can simply run the following from your command prompt.
$ psql {dbname}
You may also specify a role {role} other than your username as follows.
$ psql -U {role} {dbname}
Creating a New Database
As the postgres user, execute the following command. Note: replace {dbname} with the name of your desired database, often the name of the role created above.
postgres@server:~$ createdb {dbname}
Loading of Database
If you have been given a dump of a database, here denoted by {filename}.sql, the following will create the database in your PostgreSQL server and load the file data into the database. Note: replace {username} with an existing role in your PostgreSQL server, replace {dbname} with the name of an existing database in your PostgreSQL server, and replace {filename} with the name of your .sql file.
$ createdb -U {username} {dbname}$ psql {dbname} < {filename}.sql
Now you’re all ready to SELECT something FROM your_tables.
Array of Doubled Pairs in C++

Suppose we have an array of integers A with even length, now we have to say true if and only if it is possible to reorder it in such a way that A[2 * i + 1] = 2 * A[2 * i] for every 0 <= i < len(A) / 2. So if the input is like [3,1,3,6] then the result will be false, where as [4,-2,2,-4], will return true.
To solve this, we will follow these steps −
Create a map m, n := size of A, store the frequency of each element in A into map m
Create a map m, n := size of A, store the frequency of each element in A into map m
cnt := size of A
cnt := size of A
for each key-value pair kv in mapif m[key of kv] > 0, thenif m[key of kv] is not 0 and m[2* key of kv] > 0x := min of m[key of kv] and m[2* key of kv]cnt := cnt – (x * 2)decrease m[2 * key of kv] by xdecrease m[key of kv] by xotherwise when key of kv = 0, thencnt := cnt – m[key of kv]m[key of kv] := 0
for each key-value pair kv in map
if m[key of kv] > 0, thenif m[key of kv] is not 0 and m[2* key of kv] > 0x := min of m[key of kv] and m[2* key of kv]cnt := cnt – (x * 2)decrease m[2 * key of kv] by xdecrease m[key of kv] by xotherwise when key of kv = 0, thencnt := cnt – m[key of kv]m[key of kv] := 0
if m[key of kv] > 0, then
if m[key of kv] is not 0 and m[2* key of kv] > 0x := min of m[key of kv] and m[2* key of kv]cnt := cnt – (x * 2)decrease m[2 * key of kv] by xdecrease m[key of kv] by x
if m[key of kv] is not 0 and m[2* key of kv] > 0
x := min of m[key of kv] and m[2* key of kv]
x := min of m[key of kv] and m[2* key of kv]
cnt := cnt – (x * 2)
cnt := cnt – (x * 2)
decrease m[2 * key of kv] by x
decrease m[2 * key of kv] by x
decrease m[key of kv] by x
decrease m[key of kv] by x
otherwise when key of kv = 0, thencnt := cnt – m[key of kv]m[key of kv] := 0
otherwise when key of kv = 0, then
cnt := cnt – m[key of kv]
cnt := cnt – m[key of kv]
m[key of kv] := 0
m[key of kv] := 0
return false when cnt is non-zero, otherwise true
return false when cnt is non-zero, otherwise true
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool canReorderDoubled(vector<int>& A) {
      map <int, int> m;
      int n = A.size();
      for(int i = 0; i < n; i++){
         m[A[i]]++;
      }
      int cnt = A.size();
      map <int, int> :: iterator it = m.begin();
      while(it != m.end()){
         if(m[it->first] > 0){
            if(it->first != 0 && m[it->first * 2] > 0){
               int x = min(m[it->first], m[it->first * 2]);
               cnt -= (x * 2);
               m[it->first * 2] -= x;
               m[it->first] -= x;
            }else if(it->first == 0){
               cnt -= m[it->first];
               m[it->first] = 0;
            }
         }
         it++;
      }
      return !cnt;
   }
};
main(){
   vector<int> v1 = {3,1,3,6};
   Solution ob;
   cout << (ob.canReorderDoubled(v1)) << endl;
   v1 = {4,-2,2,-4};
   cout << (ob.canReorderDoubled(v1));
}
[3,1,3,6]
[4,-2,2,-4]
0
1
How To Change The Size Of Figures In Matplotlib | Towards Data Science

Resizing figures generated through matplotlib in Python is a common task when it comes to visualizing data. In today’s short guide we will discuss a few possible ways for adjusting the size of the generated plots.
Specifically, we will discuss how to do so:
Using matplotlib.pyplot.figure()
Using set_size_inches()
by modifying rcParams['figure.figsize']
Additionally, we will discuss how to resize a figure using a factor/ratio of the existing (default) size.
First, let’s create a figure using some dummy data that we’ll use throughout this article in order to demonstrate a couple of concepts.
import matplotlib.pyplot as pltx = y = range(1, 10)plt.plot(x, y)plt.show()
The figure shown below is generated using the default size, as defined in rcParams['figure.figsize'] .
The first option you have is to call matplotlib.pyplot.figure that is used to create a new figure or activate an existing one. The method accepts an argument called figsize that is used to specify the width and height of the figure (in inches). Additionally, you can even specify dpi that corresponds to the resolution of the figure in dots-per-inch.
import matplotlib.pyplot as pltfrom matplotlib.pyplot import figurefigure(figsize=(3, 2), dpi=80)x = y = range(1, 10)plt.plot(x, y)plt.show()
The second option you have is matplotlib.figure.set_size_inches() that is used to set the figure size in inches.
import matplotlib.pyplot as pltx = y = range(1, 10)plt.plot(x, y)plt.gcf().set_size_inches(3, 2)plt.show()
If you want to modify the size of a figure without using the figure environment, then you can also update matplotlib.rcParams which is an instance of RcParams for handling default Matplotlib values.
import matplotlib.pyplot as pltplt.rcParams['figure.figsize'] = (3, 2)x = y = range(1, 10)plt.plot(x, y)plt.show()
Note that the above will have effect on every figure generated unless you specify different size for a specific figure. If for any reason you want to set back the default values of this parameter, you can simply use rcParamsDefault as shown below
plt.rcParams['figure.figsize']=plt.rcParamsDefault['figure.figsize']
Now if you wish to resize a figure using a hardcoded factor or ratio in relation say to another figure, then you can do so using the commands below:
figure_size = plt.gcf().get_size_inches()factor = 0.8plt.gcf().set_size_inches(factor * figure_size)
In today’s short guide we discussed how to resize figures generated using matplotlib library. We explore a few possible options but you should make sure to use the one that suits your needs (e.g. depending on whether you want to specify the size for all the figures and plots, or just a specific on).
Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read.
You may also like
spaCy - Train Command

As name implies, this command will train a model. The output will be in spaCy’s JSON format and on every epoch the model will be saved out to the directory.
To package the model using spaCy package command, model details and accuracy scores will be added to meta.json file.
The Train command is as follows:
python -m spacy [lang] [output_path] [train_path] [dev_path]
[--base-model] [--pipeline] [--vectors] [--n-iter] [--n-early-stopping][--n-examples] [--use-gpu] [--version] [--meta-path] [--init-tok2vec][--parser-multitasks] [--entity-multitasks] [--gold-preproc] [--noise-level][--orth-variant-level] [--learn-tokens] [--textcat-arch] [--textcat-multilabel][--textcat-positive-label] [--verbose]

The table below explains its arguments −
 Print
 Add Notes
 Bookmark this page
SortedSet Class in C#

The SortedSet class in C# represents a collection of objects that is maintained in sorted order.
Following are the properties of the SortedSet class −
Following are some of the methods of the SortedSet class −
Let us now see some examples −
To check if the SortedSet contains a specific element, the code is as follows −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      SortedSet<string> set1 = new SortedSet<string>();
      set1.Add("CD");
      set1.Add("CD");
      set1.Add("CD");
      set1.Add("CD");
      Console.WriteLine("Elements in SortedSet1...");
      foreach (string res in set1) {
         Console.WriteLine(res);
      }
      Console.WriteLine("Does the SortedSet1 contains the element DE? = "+set1.Contains("DE"));
      SortedSet<string> set2 = new SortedSet<string>();
      set2.Add("BC");
      set2.Add("CD");
      set2.Add("DE");
      set2.Add("EF");
      set2.Add("AB");
      set2.Add("HI");
      set2.Add("JK");
      Console.WriteLine("Elements in SortedSet2...");
      foreach (string res in set2) {
         Console.WriteLine(res);
      }
      Console.WriteLine("SortedSet2 is a superset of SortedSet1? = "+set2.IsSupersetOf(set1));
   }
}
This will produce the following output −
Elements in SortedSet1...
CD
Does the SortedSet1 contains the element DE? = False
Elements in SortedSet2...
AB
BC
CD
DE
EF
HI
JK
SortedSet2 is a superset of SortedSet1? = True
To get an enumerator that iterates through the SortedSet, the code is as follows −
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      SortedSet<string> set1 = new SortedSet<string>();
      set1.Add("AB");
      set1.Add("BC");
      set1.Add("CD");
      set1.Add("EF");
      Console.WriteLine("Elements in SortedSet1...");
      foreach (string res in set1) {
         Console.WriteLine(res);
      }
      SortedSet<string> set2 = new SortedSet<string>();
      set2.Add("BC");
      set2.Add("CD");
      set2.Add("DE");
      set2.Add("EF");
      set2.Add("AB");
      set2.Add("HI");
      set2.Add("JK");
      Console.WriteLine("Elements in SortedSet2 (Enumerator for SortedSet)...");
      SortedSet<string>.Enumerator demoEnum = set2.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }
   }
}
This will produce the following output −
Elements in SortedSet1...
AB
BC
CD
EF
Elements in SortedSet2 (Enumerator for SortedSet)...
AB
BC
CD
DE
EF
HI
JK
Tryit Editor v3.7

Tryit: HTML link to stylesheet
time.Time.Date() Function in Golang with Examples - GeeksforGeeks

19 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Date() function in Go language is used to check the year, month, and day in which the stated “t” presents itself. 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) Date() (year int, month Month, day int)

Here, “t” is the stated time.
Return Value: It returns year, month and day of the stated “t”.
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 in UTC    t := time.Date(2020, 5, 6, 11, 45, 04, 0, time.UTC)      // Calling Date method    yyyy, mm, dd := t.Date()      // Prints year    fmt.Printf("The stated year is: %v\n", yyyy)      // Prints month    fmt.Printf("The stated month is: %v\n", mm)      // Prints day    fmt.Printf("The stated day is: %v\n", dd)}
Output:
The stated year is: 2020
The stated month is: May
The stated day is: 6

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 in UTC    t := time.Date(2020, 13, 34, 00, 00, 00, 0, time.UTC)      // Calling Date method    yyyy, mm, dd := t.Date()      // Prints year    fmt.Printf("The stated year is: %v\n", yyyy)      // Prints month    fmt.Printf("The stated month is: %v\n", mm)      // Prints day    fmt.Printf("The stated day is: %v\n", dd)}
Output:
The stated year is: 2021
The stated month is: February
The stated day is: 3

Here, the stated month and day are out of usual range but they are normalized while conversion.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Class and Object in Golang
Loops in Go Language
Time Durations in Golang
Structures in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
Sum of squares of binomial coefficients in C++

The binomial coefficient is a quotation found in a binary theorem which can be arranged in a form of pascal triangle it is a combination of numbers which is equal to nCr where r is selected from a set of n items which shows the following formula
nCr=n! / r!(n-r)!
or
nCr=n(n-1)(n-2).....(n-r+1) / r!
The sum of the square of Binomial Coefficient i.e
(nC0)2 + (nC1)2 + (nC2)2 + (nC3)2 + ......... + (nCn-2)2 + (nCn-1)2 + (nCn)2
Input :n=5
Output:252
In this program first we have to find the binomial coefficient of r which is selected from n set then we have to square each coefficient and sum them we can derive a formula from the above equation or use of factorial function of each digit to get a sum so we will fall or factorial function in which we will pass and r for a given equation and then add it then we get the solution
 Live Demo
#include <iostream>
using namespace std;
int fact(int n){
   int fact = 1, i;
   for (i = 2; i <= n; i++){
      fact *= i;
   }
   return fact;
}
int main(){
   int n=5;
   int sum = 0;
   int temp=0;
   for (int r = 0; r <= n; r++){
      temp = fact(n)/(fact(r)*fact(n-r));
      sum +=(temp*temp);
   }
   cout<<sum;
   return 0;
}
252
How to catch IndexError Exception in Python?

An IndexError is raised when a sequence reference is out of range.
The given code is rewritten as follows to catch the exception and find its type
import sys
try:
my_list = [3,7, 9, 4, 6]
print my_list[6]
except IndexError as e:
print e
print sys.exc_type
C:/Users/TutorialsPoint1~.py
list index out of range
<type 'exceptions.IndexError'>
MongoDB query to search for string like “@email” in the field values

Search for email string using MongoDB find(). Let us create a collection with documents −
> db.demo727.insertOne({UserId:"John@email.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab375f43417811278f5898")
}
> db.demo727.insertOne({UserId:"John@yahoo.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab376043417811278f5899")
}
> db.demo727.insertOne({UserId:"Chris@EMAIL.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab376143417811278f589a")
}
Display all documents from a collection with the help of find() method −
> db.demo727.find();
This will produce the following output −
{ "_id" : ObjectId("5eab375f43417811278f5898"), "UserId" : "John@email.com" }
{ "_id" : ObjectId("5eab376043417811278f5899"), "UserId" : "John@yahoo.com" }
{ "_id" : ObjectId("5eab376143417811278f589a"), "UserId" : "Chris@EMAIL.com" }
Following is the query to search for @email like string −
> db.demo727.find({"UserId":/@email/i});
This will produce the following output −
{ "_id" : ObjectId("5eab375f43417811278f5898"), "UserId" : "John@email.com" }
{ "_id" : ObjectId("5eab376143417811278f589a"), "UserId" : "Chris@EMAIL.com" }
Requests - Handling Timeouts

Timeouts can be easily added to the URL you are requesting. It so happens that, you are using a third-party URL and waiting for a response. It is always a good practice to give a timeout on the URL, as we might want the URL to respond within a timespan with a response or an error. Not doing so, can cause to wait on that request indefinitely.
We can give timeout to the URL by using the timeout param and value is passed in seconds as shown in the example below −
import requests
getdata = 
requests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001)
print(getdata.text)    
raise ConnectTimeout(e, request=request)
requests.exceptions.ConnectTimeout:
HTTPSConnectionPool(host='jsonplaceholder.typicode.com', 
port=443): Max retries exceeded with url: /users (Caused 
by Connect
TimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 
0x000000B02AD
E76A0>, 'Connection to jsonplaceholder.typicode.com timed out. (connect 
timeout = 0.001)'))

The timeout given is as follows −
getdata = 
requests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001)

The execution throws connection timeout error as shown in the output. The timeout given is 0.001, which is not possible for the request to get back the response and throws an error. Now, we will increase the timeout and check.
import requests
getdata = 
requests.get('https://jsonplaceholder.typicode.com/users',timeout=1.000)
print(getdata.text)
E:\prequests>python makeRequest.py
[
   {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret",
      "email": "Sincere@april.biz",
      "address": {
         "street": "Kulas Light",
         "suite": "Apt. 556",
         "city": "Gwenborough",
         "zipcode": "92998-3874",
         "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
         }
      },
      "phone": "1-770-736-8031 x56442",
      "website": "hildegard.org",
      "company": {
         "name": "Romaguera-Crona",
         "catchPhrase": "Multi-layered client-server neural-net",
         "bs": "harness real-time e-markets"
      }
   }
] 

With a timeout of 1 second, we can get the response for the URL requested.
 Print
 Add Notes
 Bookmark this page
Python | Raising an Exception to Another Exception - GeeksforGeeks

12 Jun, 2019
Let’s consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback.
To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors.
Code #1 :
def example():    try:        int('N/A')    except ValueError as e:        raise RuntimeError('A parsing error occurred') from e...  example()
Output :
Traceback (most recent call last):
  File "", line 3, in example
ValueError: invalid literal for int() with base 10: 'N/A'

This exception is the direct cause of the following exception –
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 5, in example
RuntimeError: A parsing error occurred

Both exceptions are captured in the traceback. A normal except statement is used to catch such an exception. However, __cause__ attribute of the exception object can be looked to follow the exception chain as explained in the code given below.
Code #2 :
try:    example()except RuntimeError as e:    print("It didn't work:", e)    if e.__cause__:        print('Cause:', e.__cause__)
An implicit form of chained exceptions occurs when another exception gets raised inside an except block.
Code #3 :
def example2():    try:        int('N/A')    except ValueError as e:        print("Couldn't parse:", err)  example2()
Traceback (most recent call last):
    File "", line 3, in example2
ValueError: invalid literal for int() with base 10: 'N / A'

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
    File "", line 1, in 
    File "", line 5, in example2
NameError: global name 'err' is not defined

In the code below, the NameError exception is raised as the result of a programming error, not in direct response to the parsing error. For this case, the __cause__ attribute of an exception is not set. Instead, a __context__ attribute is set to the prior exception.
Code #4 : To suppress chaining, use raise from None
def example3():    try:        int('N / A')    except ValueError:        raise RuntimeError('A parsing error occurred') from None...  example3()
Output :
Traceback (most recent call last):
    File "", line 1, in 
    File "", line 5, in example3
RuntimeError: A parsing error occurred

Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
sum() function in Python
*args and **kwargs in Python
MySQL query to create user and grant permission

To create a user and grant permission, the syntax is as follows −
create database yourDatabaseName DEFAULT CHARACTER SET utf8;
create user `yourUserName` identified by yourPassword;
GRANT SELECT ON yourDatabaseName .* TO `yourUserName`;
GRANT INSERT ON yourDatabaseName .* TO `yourUserName`;
GRANT UPDATE ON yourDatabaseName .* TO `yourUserName`;
GRANT DELETE ON yourDatabaseName .* TO  `yourUserName`;
GRANT EXECUTE ON yourDatabaseName .* TO `yourUserName`;
Here is the query to create user and grant permission −
mysql> create database demo_app DEFAULT CHARACTER SET utf8;
Query OK, 1 row affected, 1 warning (0.00 sec)
mysql> create user `John_123` identified by '123456';
Query OK, 0 rows affected (0.00 sec)
mysql> GRANT SELECT ON demo.* TO `John_123`;
Query OK, 0 rows affected (0.00 sec)
mysql> GRANT INSERT ON demo.* TO `John_123`;
Query OK, 0 rows affected (0.00 sec)
mysql> GRANT UPDATE ON demo.* TO `John_123`;
Query OK, 0 rows affected (0.00 sec)
mysql> GRANT DELETE ON demo.* TO  `John_123`;
Query OK, 0 rows affected (0.00 sec)
mysql> GRANT EXECUTE ON demo.* TO `John_123`;
Query OK, 0 rows affected (0.00 sec)
Let us display all the grants of the above user:
mysql> show grants for `John_123`;
This will produce the following output −
+-----------------------------------------------------------------------------+
| Grants for John_123@%                                                       |
+-----------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `John_123`@`%`                                        |
| GRANT SELECT, INSERT, UPDATE, DELETE, EXECUTE ON `demo`.* TO `John_123`@`%` |
+-----------------------------------------------------------------------------+
2 rows in set (0.00 sec)
Difference between Cost Performance Index (CPI) and Schedule Performance Index (SPI) - GeeksforGeeks

16 May, 2019
Cost Performance Index (CPI):Cost Performance Index (CPI) is the measure of the cost efficiency of project. It is expressed as a ratio of earned value to actual cost.
Schedule Performance Index (SPI):Schedule Performance Index (SPI) is the measure of schedule efficiency of the project. It is expressed as the ratio of earned value to planned value.
Example:A project is going to be completed in 6 months and the budget for the project is 50, 000 dollar. After the 3 months it is found that only 40% of the total work has been done to date and 30, 000 dollar has been spent. Then the Cost Performance Index (CPI) and the Schedule Performance Index (SPI) is calculated as below:
Actual Cost, 
= 30, 000 dollar

Planned Value, 
= 50% of 50, 000 dollar 
= 25, 000 dollar

Earned Value, 
= 40% of 50, 000 dollar 
= 20, 000 dollar

Cost Performance Index, 
= Earned Value / Actual Cost 
= 20, 000 / 30, 000 
= 0.67

Schedule Performance Index (SPI), 
= Earned Value / Planned Value 
= 20, 000 / 25, 000 
= 0.8 
Conclusion: It can be concluded that the project is over budget and behind schedule.
Difference between Cost Performance Index (CPI) and Schedule Performance Index (SPI):
CPI = Earned Value / Actual Cost
SPI = Earned Value / Planned Value
Difference Between
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Stack vs Heap Memory Allocation
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Types of Software Testing
Software Engineering | COCOMO Model
Functional vs Non Functional Requirements
Software Engineering | Spiral Model
Software Engineering | Coupling and Cohesion
How to check if a string starts with a substring using regex in Python? - GeeksforGeeks

29 Dec, 2020
Prerequisite: Regular Expression in Python
Given a string str, the task is to check if a string starts with a given substring or not using regular expression.
Examples:
Input: String: "geeks for geeks makes learning fun" 
       Substring: "geeks" 
Output: True 
Input: String: "geeks for geeks makes learning fun" 
       Substring: "makes" 
Output: False
Approach 1:Here, we first check a given substring present in a string or not if yes then we use search() function of re library along with metacharacter “^”. This metacharacter checks for a given string starts with substring provided or not. 
Below is the implementation of the above approach:
Python3
# import libraryimport re  # define a function def find(string, sample) :      # check substring present   # in a string or not  if (sample in string):        y = "^" + sample        # check if string starts       # with the substring      x = re.search(y, string)        if x :          print("string starts with the given substring")        else :          print("string doesn't start with the given substring")    else :      print("entered string isn't a substring")    # Driver codestring = "geeks for geeks makes learning fun"  sample = "geeks"  # function callfind(string, sample)  sample = "makes"  # function callfind(string, sample)
Output:
string starts with the given substring
string doesn't start with the given substring
Approach 2:Here, we first check a given substring present in a string or not if yes then we use search() function of re library along with metacharacter “\A”. This metacharacter checks for a given string starts with substring provided or not.
 Below is the implementation of the above approach:
Python3
# import libraryimport re  # define a function def find(string, sample) :      # check substring present   # in a string or not  if (sample in string):        y = "\A" + sample        # check if string starts       # with the substring      x = re.search(y, string)        if x :          print("string starts with the given substring")        else :          print("string doesn't start with the given substring")    else :      print("entered string isn't a substring")    # Driver codestring = "geeks for geeks makes learning fun"  sample = "geeks"  # function callfind(string, sample)  sample = "makes"  # function callfind(string, sample)
Output:
string starts with the given substring
string doesn't start with the given substring
Python Regex-programs
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
SLF4J - Environment Setup

In this chapter, we will explain how to set SLF4J environment in Eclipse IDE. Before proceeding with the installation, make sure that you already have Eclipse installed in your system. If not, download and install Eclipse.
For more information on Eclipse, please refer our Eclipse Tutorial
Open the official homepage of the SLF4J website and go to the download page.
Now, download the latest stable version of slf4j-X.X.tar.gz or slf4j-X.X.zip, according to your operating system (if windows .zip file or if Linux tar.gz file).
Within the downloaded folder, you will find slf4j-api-X.X.jar. This is the required Jar file.
Open eclipse and create a sample project. Right-click on the project, select the option Build Path → Configure Build Path... as shown below.
In the Java Build Path frame in the Libraries tab, click Add External JARs...
Select the slf4j-api.x.x.jar file downloaded and click Apply and Close.
In addition to slf4j-api.x.x.jar file, SLF4J provides several other Jar files as shown below. These are called SLF4J bindings.
Where each binding is for its respective logging framework.
The following table lists the SLF4J bindings and their corresponding frameworks.
slf4j-nop-x.x.jar
No operation, discards all loggings.
slf4j-simple-x.x.jar
Simple implementation where messages for info and higher are printed and, remaining all outputs to System.err.
slf4j-jcl-x.x.jar
Jakarta Commons Logging framework.
slf4j-jdk14-x.x.jar
Java.util.logging framework (JUL).
slf4j-log4j12-x.x.jar
Log4J frame work. In addition, you need to have log4j.jar.
To make SLF4J work along with slf4l-api-x.x.jar, you need to add the respective Jar file (binding) of the desired logger framework in the classpath of the project (set build path).
To switch from one framework to other, you need to replace the respective binding. If no bounding is found, it defaults to no-operation mode.
If you are creating the maven project, open the pom.xml and paste the following content in it and refresh the project.
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   
   <modelVersion>4.0.0</modelVersion>
   <groupId>Sample</groupId>
   <artifactId>Sample</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <build>
      <sourceDirectory>src</sourceDirectory>
      <plugins>
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
               <source>1.8</source>
               <target>1.8</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
   <dependencies>
      <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-api</artifactId>
         <version>1.7.25</version>
      </dependency>
   </dependencies>
</project>
 Print
 Add Notes
 Bookmark this page