code-rag-bench/online-tutorials huggingface dataset:
Count of substrings of a binary string containing K ones in C++

We are given a string of binary numbers i.e. combination of 0’s and 1’s and an integer value k and the task is to calculate the count of substrings formed with the given binary string having given k 1’s.
Input − string str = ‘10000100000’, k = 2
Output − Count of substrings of a binary string containing K ones are − 6
Explanation − Substrings that can be formed from the given string are 1, 10, 100, 1000, 10000, 010, 100001, 10001, 1001, 101, 11, 1000010. So there are 6 substrings having k number of 1’s i.e. exactly 2 ones.
Input − string str = ‘10000100000’, k = 3
Output − Count of substrings of a binary string containing K ones are − 0
Explanation − We are given with an integer value of k as 3 and if we check our string containing binary numbers, it has only 2 ones. So there is no possibility of substring having given k number of ones.
Input a string of binary numbers having combinations of 0’s and 1’s and an integer variable k.
Input a string of binary numbers having combinations of 0’s and 1’s and an integer variable k.
Calculate the length of the string using length() function and pass the data to the function for further processing.
Calculate the length of the string using length() function and pass the data to the function for further processing.
Declare a temporary variable count and total as 0 for storing the substrings with k ones.
Declare a temporary variable count and total as 0 for storing the substrings with k ones.
Declare an array to store the frequency of ones of size as length of string plus one and initialise it with 0 and set the first element of array as 1.
Declare an array to store the frequency of ones of size as length of string plus one and initialise it with 0 and set the first element of array as 1.
Start loop FOR from 0 till the length of an array
Start loop FOR from 0 till the length of an array
Inside the loop, set total as total + str[i] - ‘0’. Check IF total >= k then set count as count + arr[total-k].
Inside the loop, set total as total + str[i] - ‘0’. Check IF total >= k then set count as count + arr[total-k].
Return count
Return count
Print the result.
Print the result.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int sub_k_ones(string str, int length, int k){
   int count = 0;
   int total_1 = 0;
   int arr_fre[length + 1] = {0};
   arr_fre[0] = 1;
   for (int i = 0; i < length; i++){
      total_1 = total_1 + (str[i] - '0');
      if (total_1 >= k){
         count = count + arr_fre[total_1 - k];
      }
      arr_fre[total_1]++;
   }
   return count;
}
int main(){
   string str = "10000100000";
   int length = str.length();
   int k = 2;
   cout<<"Count of substrings of a binary string containing K ones are: "<<sub_k_ones(str, length, k) << endl;
   return 0;
}
If we run the above code it will generate the following output −
Count of substrings of a binary string containing K ones are: 6
How to remove all the elements from a set in javascript?

The Set class in JavaScript provides a clear method to remove all elements from a given set object. This method can be used as follows −
let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1);
mySet.add(3);
mySet.add("a");
console.log(mySet)
mySet.clear();
console.log(mySet)
Set { 1, 2, 3, 'a' }
Set { }
You can also individually remove the elements by iterating over them.
let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1);
mySet.add(3);
mySet.add("a");
console.log(mySet)
for(let i of mySet) {
   console.log(i)
   mySet.delete(i)
}
console.log(mySet)
Set { 1, 2, 3, 'a' }
Set { }
How to handle Null values while working with JDBC?

SQL's use of NULL values and Java's use of null are different concepts. So, to handle SQL NULL values in Java, there are three tactics you can use:
Avoid using getXXX( ) methods that return primitive data types.
Avoid using getXXX( ) methods that return primitive data types.
Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value returned by the getXXX( ) method should be set to null.
Use wrapper classes for primitive data types, and use the ResultSet object's wasNull( ) method to test whether the wrapper class variable that received the value returned by the getXXX( ) method should be set to null.
Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( ) method should be set to an acceptable value that you've chosen to represent a NULL.
Use primitive data types and the ResultSet object's wasNull( ) method to test whether the primitive variable that received the value returned by the getXXX( ) method should be set to an acceptable value that you've chosen to represent a NULL.
Following code snippet demonstrates how to handle null values in Java.
Statement stmt = conn.createStatement( );
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
int id = rs.getInt(1);
if( rs.wasNull( ) ) {
id = 0;
}
Matplotlib.dates.epoch2num() in Python - GeeksforGeeks

19 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.dates.epoch2num() function is used to convert an epoch or a sequence of epochs to a new date format from the day since 0001.
Syntax: matplotlib.dates.epoch2num(e)
Parameters:
e: It can be an epoch or a sequence of epochs.
Returns: A new date format since day 0001.
Example 1:
import randomimport matplotlib.pyplot as pltimport matplotlib.dates as mdates  # generate some random data# for approx 5 yrsrandom_data = [float(random.randint(1487517521,                                    14213254713))               for _ in range(1000)]  # convert the epoch format to# matplotlib date format mpl_data = mdates.epoch2num(random_data)  # plotting the graphfig, axes = plt.subplots(1, 1)axes.hist(mpl_data, bins = 51, color ='green')locator = mdates.AutoDateLocator()  axes.xaxis.set_major_locator(locator)axes.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))  plt.show()
Output:
Example 2:
from tkinter import *from tkinter import ttkimport time import matplotlibimport queuefrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tkfrom matplotlib.figure import Figureimport matplotlib.animation as animationimport matplotlib.dates as mdate    root = Tk()  graphXData = queue.Queue()graphYData = queue.Queue()  def animate(objData):          line.set_data(list(graphXData.queue),                   list(graphYData.queue))          axes.relim()    axes.autoscale_view()  figure = Figure(figsize =(5, 5), dpi = 100)axes = figure.add_subplot(111)axes.xaxis_date()  line, = axes.plot([], [])axes.xaxis.set_major_formatter(mdate.DateFormatter('%H:%M'))  canvas = FigureCanvasTkAgg(figure, root)canvas.get_tk_widget().pack(side = BOTTOM,                             fill = BOTH,                             expand = True)  for cnt in range (600):          graphXData.put(matplotlib.dates.epoch2num(time.time()-(600-cnt)))    graphYData.put(0)  ani = animation.FuncAnimation(figure, animate, interval = 1000)  root.mainloop()
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
GATE | GATE-CS-2000 | Question 49 - GeeksforGeeks

28 Jun, 2021
Let m[0]...m[4] be mutexes (binary semaphores) and P[0] .... P[4] be processes.Suppose each process P[i] executes the following:
  wait (m[i]); wait(m[(i+1) mode 4]);

  ------

  release (m[i]); release (m[(i+1)mod 4]); 
This could cause:(A) Thrashing(B) Deadlock(C) Starvation, but not deadlock(D) None of the aboveAnswer: (B)Explanation: See question 2 of https://www.geeksforgeeks.org/operating-systems-set-1/Quiz of this Question
GATE-CS-2000
GATE-GATE-CS-2000
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE CS 1997 | Question 25
GATE | GATE CS 2019 | Question 37
GATE | GATE-CS-2014-(Set-3) | Question 65
Python - Find the number of prime numbers within a given range of numbers

When it is required to find the prime numbers within a given range of numbers, the range is entered and it is iterated over. The ‘%’ modulus operator is used to find the prime numbers.
Below is a demonstration of the same
lower_range = 670
upper_range = 699
print("The lower and upper range are :")
print(lower_range, upper_range)
print("The prime numbers between", lower_range, "and", upper_range, "are:")
for num in range(lower_range, upper_range + 1):
   if num > 1:
      for i in range(2, num):
         if (num % i) == 0:
            break
      else:
         print(num)
The lower and upper range are :
670 699
The prime numbers between 670 and 699 are:
673
677
683
691
The upper range and lower range values are entered and displayed on the console.
The upper range and lower range values are entered and displayed on the console.
The numbers are iterated over.
The numbers are iterated over.
It is checked to see if they are greater than 1 since 1 is neither a prime number nor a composite number.
It is checked to see if they are greater than 1 since 1 is neither a prime number nor a composite number.
The numbers are iterated, and ‘%’ with 2.
The numbers are iterated, and ‘%’ with 2.
This way the prime number is found, and displayed on console.
This way the prime number is found, and displayed on console.
Else it breaks out of the loop.
Else it breaks out of the loop.
Create a directory in Java

A directory can be created with the required abstract path name using the method java.io.File.mkdir(). This method requires no parameters and it returns true on the success of the directory creation or false otherwise.
A program that demonstrates this is given as follows −
 Live Demo
import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("c:\\demo1\\");
         file.createNewFile();
         boolean flag = file.mkdir();
         System.out.print("Directory created? " + flag);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
The output of the above program is as follows −
Directory created? false
Note − The output may vary on Online Compilers.
Now let us understand the above program.
The method java.io.File.mkdir() is used to create a directory in Java. Then the boolean value returned by this method is printed. A code snippet that demonstrates this is given as follows −
try {
   File file = new File("c:\\demo1\\");
   file.createNewFile();
   boolean flag = file.mkdir();
   System.out.print("Directory created? " + flag);
} catch(Exception e) {
   e.printStackTrace();
}
GATE | GATE CS 2010 | Question 65 - GeeksforGeeks

28 Jun, 2021
In a binary tree with n nodes, every node has an odd number of descendants. Every node is considered to be its own descendant. What is the number of nodes in the tree that have exactly one child?(A) 0(B) 1(C) (n-1)/2(D) n-1Answer: (A)Explanation: It is mentioned that each node has odd number of descendants including node itself, so all nodes must have even number of descendants 0, 2, 4 so on. Which means each node should have either 0 or 2 children. So there will be no node with 1 child. Hence 0 is answer.
Following are few examples.
       a
    /    \
   b      c


      a
    /   \
   b     c  
  /  \
 d    e
Such a binary tree is full binary tree (a binary tree where every node has 0 or 2 children).Quiz of this Question
GATE-CS-2010
GATE-GATE CS 2010
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE CS 2019 | Question 37
GATE | GATE-CS-2014-(Set-3) | Question 65
C Program to find transpose of a matrix - GeeksforGeeks

07 Nov, 2018
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i].
For Square Matrix :
The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension.
#include <stdio.h>#define N 4  // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][N]){    int i, j;    for (i = 0; i < N; i++)        for (j = 0; j < N; j++)            B[i][j] = A[j][i];}  int main(){    int A[N][N] = { {1, 1, 1, 1},                    {2, 2, 2, 2},                    {3, 3, 3, 3},                    {4, 4, 4, 4}};      int B[N][N], i, j;      transpose(A, B);      printf("Result matrix is \n");    for (i = 0; i < N; i++)    {        for (j = 0; j < N; j++)           printf("%d ", B[i][j]);        printf("\n");    }      return 0;}
Result matrix is 
1 2 3 4 
1 2 3 4 
1 2 3 4 
1 2 3 4

For Rectangular Matrix :
The below program finds transpose of A[][] and stores the result in B[][].
#include <stdio.h>#define M 3#define N 4  // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][M]){    int i, j;    for (i = 0; i < N; i++)        for (j = 0; j < M; j++)            B[i][j] = A[j][i];}  int main(){    int A[M][N] = { {1, 1, 1, 1},                    {2, 2, 2, 2},                    {3, 3, 3, 3}};      // Note dimensions of B[][]    int B[N][M], i, j;      transpose(A, B);      printf("Result matrix is \n");    for (i = 0; i < N; i++)    {        for (j = 0; j < M; j++)        printf("%d ", B[i][j]);        printf("\n");    }      return 0;}
Result matrix is 
1 2 3 
1 2 3 
1 2 3 
1 2 3

In-Place for Square Matrix:
#include <bits/stdc++.h>using namespace std;  #define N 4  // Converts A[][] to its transposevoid transpose(int A[][N]){    for (int i = 0; i < N; i++)        for (int j = i+1; j < N; j++)            swap(A[i][j], A[j][i]);}  int main(){    int A[N][N] = { {1, 1, 1, 1},                    {2, 2, 2, 2},                    {3, 3, 3, 3},                    {4, 4, 4, 4}};      transpose(A);      printf("Modified matrix is \n");    for (int i = 0; i < N; i++)    {        for (int j = 0; j < N; j++)           printf("%d ", A[i][j]);        printf("\n");    }      return 0;}
Modified matrix is 
1 2 3 4 
1 2 3 4 
1 2 3 4 
1 2 3 4

Please refer complete article on Program to find transpose of a matrix for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Header files in C/C++ and its uses
C Program to read contents of Whole File
C program to sort an array in ascending order
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
Program to find Prime Numbers Between given Interval
Producer Consumer Problem in C
How to Append a Character to a String in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
C Program to Swap two Numbers
Batch Script - RD

This batch command removes directories, but the directories need to be empty before they can be removed.
rd [directoryname]

The following example shows the different variants of the rd command.
@echo off
Rem removes the directory called newdir
rd C:\newdir

Rem removes 2 directories
rd Dir1 Dir2

Rem Removes directory with spaces
rd "Application A"

Rem Removes the directory Dir1 including all the files and subdirectories in it rd /s Dir1
Rem Removes the directory Dir1 including all the files and subdirectories in it but
asks for a user confirmation first.
rd /q /s Dir1
All actions are performed as per the remarks in the batch file.
 Print
 Add Notes
 Bookmark this page
Jackson Annotations - @JsonCreator

@JsonCreator is used to fine tune the constructor or factory method used in deserialization. We'll be using @JsonProperty as well to achieve the same. In the example below, we are matching an json with different format to our class by defining the required property names.
import java.io.IOException; 
import java.text.ParseException; 

import com.fasterxml.jackson.annotation.JsonCreator; 
import com.fasterxml.jackson.annotation.JsonProperty; 
import com.fasterxml.jackson.databind.ObjectMapper; 

public class JacksonTester {
   public static void main(String args[]) throws ParseException{ 
      String json = "{\"id\":1,\"theName\":\"Mark\"}"; 
      ObjectMapper mapper = new ObjectMapper();    
      try {
         Student student = mapper 
            .readerFor(Student.class) 
            .readValue(json); 
         System.out.println(student.rollNo +", " + student.name); 
      }
      catch (IOException e) { 
         e.printStackTrace(); 
      }
   }
}
class Student {
   public String name; 
   public int rollNo; 

   @JsonCreator 
   public Student(@JsonProperty("theName") String name, @JsonProperty("id") int rollNo){
      this.name = name; 
      this.rollNo = rollNo; 
   }
}
1, Mark 

 Print
 Add Notes
 Bookmark this page
Python program for addition and subtraction of complex numbers - GeeksforGeeks

13 Dec, 2021
Given two complex numbers z1 and z2. The task is to add and subtract the given complex numbers.Addition of complex number: In Python, complex numbers can be added using + operator.Examples:  
Input:  2+3i, 4+5i
Output: Addition is : 6+8i

Input: 2+3i, 1+2i
Output: Addition is : 3+5i
 Example :
Python3
# Python program to add# two complex numbers  # function that returns# a complex number after# addingdef addComplex( z1, z2):    return z1 + z2 # Driver's codez1 = complex(2, 3)z2 = complex(1, 2)print( "Addition is : ", addComplex(z1, z2))
Output: 
Addition is :  (3+5j)
Subtraction of complex numbers: Complex numbers in Python can be subtracted using – operator.Examples:  
Input: 2+3i, 4+5i
Output: Subtraction is : -2-2i

Input: 2+3i, 1+2i
Output: Subtraction is : 1+1i
Example : 
Python3
# Python program to subtract# two complex numbers  # function that returns# a complex number after# subtractingdef subComplex( z1, z2):    return z1-z2 # driver programz1 = complex(2, 3)z2 = complex(1, 2)print( "Subtraction is : ", subComplex(z1, z2))
Output: 
Subtraction is :  (1+1j)
 
simmytarika5
sweetyty
python-utility
Technical Scripter 2019
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Difference between Abstract Class and Interface in Java

Following are the notable differences between interface and abstract class in Java.
public class Tester {
   public static void main(String[] args) {

      Car car = new Car();
      car.setFuel();
      car.run();
      Truck truck = new Truck();
      truck.setFuel();
      truck.run();
   }
}
interface Vehicle {
   public void setFuel();
   public void run();
}
class Car implements Vehicle {
   public void setFuel() {
      System.out.println("Car: Tank is full.");
   }
   public void run() {
      System.out.println("Car: Running.");
   }
}
abstract class MotorVehicle {
   public void setFuel() {
      System.out.println("MotorVehicle: Tank is full.");
   }
   abstract public void run();
}
class Truck extends MotorVehicle {
   public void run() {
      System.out.println("Truck: Running.");
   }
}
Car: Tank is full.
Car: Running.
MotorVehicle: Tank is full.
Truck: Running.
Python | Remove last element from each row in Matrix - GeeksforGeeks

30 Dec, 2020
Sometimes, while working with Matrix data, we can have a stray element attached at rear end of each row of matrix. This can be undesired at times and wished to be removed. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + del + list slicingThe combination of above functionalities can be used to perform this task. In this, we run a loop for each row in matrix and remove the rear element using del.
# Python3 code to demonstrate working of# Remove last element from each row in Matrix# Using loop + del + list slicing  # initialize listtest_list = [[1, 3, 4], [2, 4, 6], [3, 8, 1]]  # printing original list print("The original list : " + str(test_list))  # Remove last element from each row in Matrix# Using loop + del + list slicingfor ele in test_list: del ele[-1]   # printing resultprint("Matrix after removal of rear element from rows : " + str(test_list))
The original list : [[1, 3, 4], [2, 4, 6], [3, 8, 1]]
Matrix after removal of rear element from rows : [[1, 3], [2, 4], [3, 8]]

 
Method #2 : Using list comprehension + list slicingThe combination of above functions can also be used to perform this task. In this, we just iterate for each row and delete the rear element using list slicing.
# Python3 code to demonstrate working of# Remove last element from each row in Matrix# Using list comprehension + list slicing  # initialize listtest_list = [[1, 3, 4], [2, 4, 6], [3, 8, 1]]  # printing original list print("The original list : " + str(test_list))  # Remove last element from each row in Matrix# Using list comprehension + list slicingres = [ele[:-1] for ele in test_list]  # printing resultprint("Matrix after removal of rear element from rows : " + str(res))
The original list : [[1, 3, 4], [2, 4, 6], [3, 8, 1]]
Matrix after removal of rear element from rows : [[1, 3], [2, 4], [3, 8]]

Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to convert data.table object into a matrix in R?

A data.table object is very similar to a data frame in R, therefore, converting a data.table object to a matrix is not a difficult job. We just need to use as.matrix function and store the data.table object into a new object that will belong to the matrix, otherwise R will not be able to convert the data.object to a matrix. For example, if we have a data.table object DT then to convert it into a matrix, we should use the below example code −
DT_matrix<-as.matrix(DT)
Loading data.table package −
library(data.table)
Creating a data.table object −
x1<-rnorm(20,1,0.04)
x2<-rnorm(20,5,1.2)
x3<-runif(20,5,10)
x4<-runif(20,1,5)
DT1<-data.table(x1,x2,x3,x4)
DT1
x1 x2 x3 x4
1: 0.9785610 7.345365 8.079572 4.289080
2: 0.9787770 6.684993 6.842196 3.420399
3: 0.9936527 5.076511 6.584490 4.339317
4: 0.9585088 6.348905 5.256956 1.041050
5: 1.0172288 6.076759 6.456343 3.964968
6: 1.0199971 6.384019 6.444665 2.477480
7: 1.0027680 5.189908 6.352739 3.358625
8: 1.0013410 7.480771 6.236253 3.704360
9: 0.9638484 3.173219 6.768095 2.710411
10: 0.9771605 4.072879 5.269356 3.689747
11: 0.9768464 3.898211 8.212824 1.230352
12: 1.0322361 4.964122 8.062670 2.333302
13: 0.9730514 2.746493 7.991256 1.319675
14: 1.0157617 4.032643 7.324038 3.883257
15: 1.0167210 6.994750 5.123840 3.157113
16: 0.9526550 5.292459 8.401666 2.362798
17: 1.0022340 4.753125 6.175266 3.900407
18: 1.0456185 6.001135 8.018412 3.324448
19: 1.1422387 5.121760 5.340800 2.348761
20: 0.9269784 5.893736 5.754917 1.940769
is.matrix(DT1_matrix) 
[1] TRUE
Let’s have a look at another example −
y1<-rpois(20,2)
y2<-rpois(20,5)
y3<-rpois(20,8)
y4<-rpois(20,10)
y5<-sample(0:9,20,replace=TRUE)
DT2<-data.table(y1,y2,y3,y4,y5)
DT2
   y1 y2  y3   y4   y5
1: 2  5   12   12   7
2: 2  7   9    8   1
3: 2  5   3    9   2
4: 0  0   10   12   9
5: 2  3   5    8   8
6: 4  7   6   8    9
7: 2  7   8   9    0
8: 0  7   8   11   1
9: 3  6   7   8    2
10: 0  3   8  9    1
11: 2  7  9   9    2
12: 3  4  8   7   7
13: 0  1  10  14 8
14: 1  6  7   5 9
15: 3  3   12 14 6
16: 0  4   8   8 4
17: 1  7   9  13 2
18: 5  1   14  11 7
19: 1 4   14   9 6
20: 3 5   8   10 1
Converting data.table object into a matrix object −
DT2_matrix<-as.matrix(DT2)
DT2_matrix
     y1  y2  y3   y4 y5
[1,] 2   5   12   12 7
[2,] 2   7   9   8 1
[3,] 2   5   3   9 2
[4,] 0   0   10 12 9
[5,] 2   3   5 8 8
[6,] 4   7   6 8 9
[7,] 2   7   8 9 0
[8,] 0   7   8 11 1
[9,] 3   6   7 8 2
[10,] 0  3   8 9 1
[11,] 2  7   9 9 2
[12,] 3 4 8 7 7
[13,] 0 1 10 14 8
[14,] 1 6 7 5 9
[15,] 3 3 12 14 6
[16,] 0 4 8 8 4
[17,] 1 7 9 13 2
[18,] 5 1 14 11 7
[19,] 1 4 14 9 6
[20,] 3 5 8 10 1
is.matrix(DT2_matrix) 
[1] TRUE
Anonymous classes in C++

Anonymous entity is anything that is defined without a name. A class with no name provided is known as an anonymous class in c++. An anonymous class is a special class with one basic property.
As there is no name given to the class there is no constructor allocated to it, though a destructor is there for deallocating the memory block.
As there is no name given to the class there is no constructor allocated to it, though a destructor is there for deallocating the memory block.
The class cannot be used as an element of a function i.e. you cannot pass it as an argument or cannot accept values return from the function.
The class cannot be used as an element of a function i.e. you cannot pass it as an argument or cannot accept values return from the function.
class {
   //data members
   // member fucntions
}
Some programming to illustrate the working of an anonymous class in c++.
Creating an anonymous class and defining and using its single objects −We will define an anonymous class and declare its objects using which we will use the members of the class.
Creating an anonymous class and defining and using its single objects −
We will define an anonymous class and declare its objects using which we will use the members of the class.
 Live Demo
#include <iostream>
using namespace std;
class{
   int value;
   public:
   void setData(int i){
      this->value = i;
   }
   void printvalues(){
      cout<<"Value : "<<this->value<<endl;
   }
}
 obj1;
int main(){
   obj1.setData(10);
   obj1.printvalues();
   return 0;
}
Value : 10
Creating an anonymous class and defining and using its two objects −We can have multiple objects of an anonymous class and use them in our code. The below program show the working −
Creating an anonymous class and defining and using its two objects −
We can have multiple objects of an anonymous class and use them in our code. The below program show the working −
 Live Demo
#include <iostream>
using namespace std;
class{
   int value;
   public:
   void setData(int i){
      this->value = i;
   }
   void print(){
      cout<<"Value : "<<this->value<<endl;
   }
}
 obj1,obj2;
int main(){
   cout<<"Object 1 \n";
   obj1.setData(10);
   obj1.print();
   cout<<"Object 2 \n";
   obj1.setData(12);
   obj1.print();
   return 0;
}
Object 1
Value : 10
Object 2
Value : 12
How to use Boto3 to start a crawler in AWS Glue Data Catalog

In this article, we will see how a user can start a crawler in AWS Glue Data Catalog.
Problem Statement: Use boto3 library in Python to start a crawler.
Step 1: Import boto3 and botocore exceptions to handle exceptions
Step 1: Import boto3 and botocore exceptions to handle exceptions
Step 2:
crawler_name is the parameter in this function.
Step 2:
crawler_name is the parameter in this function.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 4: Create an AWS client for glue.
Step 4: Create an AWS client for glue.
Step 5: Now use the start_crawler function and pass the parameter crawler_name as Name.
Step 5: Now use the start_crawler function and pass the parameter crawler_name as Name.
Step 6: It returns the response metadata and starts the crawler irrespective of its schedule. If the status of crawler is running, then it throws CrawlerRunningException.
Step 6: It returns the response metadata and starts the crawler irrespective of its schedule. If the status of crawler is running, then it throws CrawlerRunningException.
Step 7: Handle the generic exception if something went wrong while starting a crawler.
Step 7: Handle the generic exception if something went wrong while starting a crawler.
The following code starts a crawler in AWS Glue Data Catalog −
import boto3
from botocore.exceptions import ClientError

def start_a_crawler(crawler_name)
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      response = glue_client.start_crawler(Name=crawler_name)
      return response
   except ClientError as e:
      raise Exception("boto3 client error in start_a_crawler: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in start_a_crawler: " + e.__str__())

#1st time start the crawler
print(start_a_crawler("Data Dimension"))
#2nd time run, before crawler completes the operation
print(start_a_crawler("Data Dimension"))
#1st time start the crawler
{'ResponseMetadata': {'RequestId': '73e50130-*****************8e', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 28 Mar 2021 07:26:55 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '2', 'connection': 'keep-alive', 'x-amzn-requestid': '73e50130-***************8e'}, 'RetryAttempts': 0}}

#2nd time run, before crawler completes the operation
Exception: boto3 client error in start_a_crawler: An error occurred (CrawlerRunningException) when calling the StartCrawler operation: Crawler with name Data Dimension has already started
How to resize an Entry Box by height in Tkinter?

An Entry widget in a Tkinter application supports singleline user inputs. You can configure the size of an Entry widget such as its width using the width property. However, tkinter has no height property to set the height of an Entry widget. To set the height, you can use the font('font_name', font-size) property. The font size of the text in an Entry widget always works as a height of the Entry widget.
Let us take an example to understand this more clearly. Follow the steps given below −
Import the required libraries
Import the required libraries
Create an Entry widget, set its width and height by specifying the font('font-name', font-size) property.
Create an Entry widget, set its width and height by specifying the font('font-name', font-size) property.
Create a Button to print the name of the user with the help of a Label widget.
Create a Button to print the name of the user with the help of a Label widget.
Define a function to create a Label to display the name of the users.
Define a function to create a Label to display the name of the users.
Use the get() function to return the string input from the Entry widget.
Use the get() function to return the string input from the Entry widget.
# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Define a function
def myClick():
   greet= "Hello " + name.get()
   label=Label(win, text=greet, font=('Arial', 12))
   label.pack(pady=10)

# Create an entry widget
name=Entry(win, width=50, font=('Arial 24'))
name.pack(padx=10, pady=10)

# Create a button
button=Button(win, text="Submit", command=myClick)
button.pack(pady=10)

win.mainloop()
Running the above program will display a window with an Entry widget asking users to enter their name and a Button to submit the name. When you hit "submit", it will display a Label widget on the screen.
Now enter your name in the field and click "Submit" to see the output.
BufferedWriter close() method in Java with Examples - GeeksforGeeks

28 May, 2020
The close() method of BufferedWriter class in Java is used to flush the characters from the buffer stream and then close it. Once the stream is closed further calling the methods like write() and append() will throw the exception.
Syntax:
public void close()

Parameters: This method does not accept any parameter.
Return value: This method does not return any value.
Exceptions: This method throws IOException if an I/O error occurs.
Below programs illustrate close() method in BufferedWriter class in IO package:
Program 1:
// Java program to illustrate// BufferedWriter close() method  import java.io.*;  public class GFG {    public static void main(String[] args)    {        try {              // Create the string Writer            StringWriter stringWriter                = new StringWriter();              // Convert stringWriter to            // bufferedWriter            BufferedWriter buffWriter                = new BufferedWriter(                    stringWriter);              // Write "GEEKS" to buffered writer            buffWriter.write(                "GEEKSFORGEEKS", 0, 5);              // Close the buffered writer            buffWriter.close();              System.out.println(                stringWriter.getBuffer());        }        catch (Exception e) {            System.out.println(                "BufferedWriter is closed");        }    }}
GEEKS

Program 2:
// Java program to illustrate// BufferedWriter close() method  import java.io.*;  public class GFG {    public static void main(String[] args)    {        try {              // Create the string Writer            StringWriter stringWriter                = new StringWriter();              // Convert stringWriter to            // bufferedWriter            BufferedWriter buffWriter                = new BufferedWriter(                    stringWriter);              // Write "GEEKS" to buffered writer            buffWriter.write(                "GEEKSFORGEEKS", 0, 5);              // Close the buffered writer            buffWriter.close();              System.out.println(                stringWriter.getBuffer());              // It will throw exception            buffWriter.write(                "GEEKSFORGEEKS", 5, 8);        }        catch (Exception e) {            System.out.println(                "BufferedWriter is closed");        }    }}
GEEKS
BufferedWriter is closed

Reference: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#close()
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Internal Working of HashMap in Java
Matplotlib - Working With Text

Matplotlib has extensive text support, including support for mathematical expressions, TrueType support for raster and vector outputs, newline separated text with arbitrary rotations, and unicode support. Matplotlib includes its own matplotlib.font_manager which implements a cross platform, W3C compliant font finding algorithm.
The user has a great deal of control over text properties (font size, font weight, text location and color, etc.). Matplotlib implements a large number of TeX math symbols and commands.
The following list of commands are used to create text in the Pyplot interface −
All of these functions create and return a matplotlib.text.Text() instance.
Following scripts demonstrate the use of some of the above functions −
import matplotlib.pyplot as plt
fig = plt.figure()

ax = fig.add_axes([0,0,1,1])

ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
ax.text(3, 8, 'boxed italics text in data coords', style='italic', 
bbox = {'facecolor': 'red'})
ax.text(2, 6, r'an equation: $E = mc^2$', fontsize = 15)
ax.text(4, 0.05, 'colored text in axes coords',
verticalalignment = 'bottom', color = 'green', fontsize = 15)
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy = (2, 1), xytext = (3, 4),
arrowprops = dict(facecolor = 'black', shrink = 0.05))
ax.axis([0, 10, 0, 10])
plt.show()
The above line of code will generate the following output −

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
numpy.char.split()

This function returns a list of words in the input string. By default, a whitespace is used as a separator. Otherwise the specified separator character is used to spilt the string.
import numpy as np 
print np.char.split ('hello how are you?') 
print np.char.split ('TutorialsPoint,Hyderabad,Telangana', sep = ',')
Its output would be −
['hello', 'how', 'are', 'you?']
['TutorialsPoint', 'Hyderabad', 'Telangana']


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
SQL | Query to select NAME from table using different options - GeeksforGeeks

19 Aug, 2020
Let us consider the following table named “Geeks” :
SQL query to write “FIRSTNAME” from Geeks table using the alias name as NAME.
Select FIRSTNAME AS NAME 
from Geeks;
Output –
SQL query to write “FIRSTNAME” from Geeks table in upper case.
Select upper(FIRSTNAME) 
from Geeks;
Output –
SQL query to find the first three characters of FIRSTNAME from Geeks table.
Select substring(FIRSTNAME, 1, 3) 
from Geeks;
Output –
SQL query to write the FIRSTNAME and LASTNAME from Geeks table into a single column COMPLETENAME with a space char should separate them.
Select CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'COMPLETENAME' 
from Geeks;
Output –
Write an SQL query to print all Worker details from the Geeks table order by FIRSTNAME Ascending.
Select * 
from Geeks 
order by FIRSTNAME asc;
Output –
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views
SQL Interview Questions
SQL | GROUP BY
Difference between DDL and DML in DBMS
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
Heterogeneous Arrays in Data Sturcture

As we know the arrays are homogeneous by definition. So we have to put data of same type in an array. But if we want to store data of different type, then what will be the trick? In C like old languages, we can use unions to artificially coalesce the different types into one type. Then we can define an array on this new type. Here the kind of object that an array element actually contains is determined by a tag. Let us see one structure like this −
struct Vehicle{
   int id;
   union {
      Bus b;
      Bike c;
      Car d;
   }
};
Then the programmer would have to establish a convention on how the id tag will be used. Suppose, for example, when the id is 0, it means that the Vehicle which is represented is actually a Bus etc. The union allocates memory for the largest type among Bus, Bike and Car. This is wasteful for memory if there is a great disparity among the sizes of the objects.
In the object oriented languages, we can use the concept of inheritances. Suppose we have a class called Vehicle, and all other types like Bus, Bike and Car are the sub-class of it. So if we define an array for Vehicle, then that can also hold all of its sub-classes. This will help us to store multiple types of data in a single array.
How to identify the difference between Kolmogorov Smirnov test and Chi Square Goodness of fit test in R?

The Chi Square Goodness of fit test is used to test whether the distribution of nominal variables is same or not as well as for other distribution matches and on the other hand the Kolmogorov Smirnov test is only used to test to the goodness of fit for a continuous data. The difference is not about the programming tool, it is a concept of statistics.
Live Demo
> x<-rnorm(20)
> x
[1] 0.078716115 -0.682154062 0.655436957 -1.169616157 -0.688543382
[6] 0.646087104 0.472429834 2.277750805 0.963105637 0.414918478
[11] 0.575005958 -1.286604138 -1.026756390 2.692769261 -0.835433410
[16] 0.007544065 0.925296720 1.058978610 0.906392907 0.973050503
> ks.test(x,pnorm)

One-sample Kolmogorov-Smirnov test

data: x
D = 0.2609, p-value = 0.1089
alternative hypothesis: two-sided

Chi-Square test:

> chisq.test(x,p=rep(1/20,20))
Error in chisq.test(x, p = rep(1/20, 20)) :
all entries of 'x' must be nonnegative and finite
With discrete distribution −
Live Demo
> y<-rpois(200,5)
> y
[1] 6 8 7 3 5 7 6 5 2 6 4 4 3 6 6 6 6 11 7 5 4 8 6 1 3
[26] 10 4 4 9 5 2 6 4 1 5 4 4 5 1 7 8 7 3 6 6 6 2 8 7 6
[51] 7 5 5 4 6 5 3 5 3 4 4 9 3 3 3 8 3 3 2 5 4 6 6 8 4
[76] 6 12 6 1 5 5 5 0 7 4 7 7 3 2 5 5 2 5 5 4 6 4 3 4 4
[101] 4 6 5 1 2 4 4 4 8 5 8 6 3 4 5 2 3 3 3 6 7 4 4 5 3
[126] 5 5 5 8 2 5 8 1 2 3 5 9 4 3 5 6 3 6 3 6 3 7 4 4 1
[151] 3 5 0 7 2 9 6 10 2 6 4 5 1 7 2 8 7 4 2 5 4 2 4 5 6
[176] 3 9 3 9 5 9 7 3 1 3 9 5 6 3 10 7 5 5 6 7 4 2 5 5 1
> chisq.test(y,p=rep(1/200,200))

Chi-squared test for given probabilities

data: y
X-squared = 203.61, df = 199, p-value = 0.3964

Warning message:
In chisq.test(y, p = rep(1/200, 200)) :
Chi-squared approximation may be incorrect
Live Demo
> a<-sample(0:9,100,replace=TRUE)
> a
[1] 4 6 1 8 1 7 3 9 8 5 4 0 7 2 2 4 6 2 1 2 1 9 1 3 1 9 2 9 1 8 4 0 4 7 1 7 1
[38] 0 1 5 9 6 5 4 6 6 9 6 1 0 8 9 4 8 2 8 1 6 9 1 0 4 6 8 8 1 1 0 3 2 6 7 2 1
[75] 7 9 9 8 2 6 4 7 3 4 0 9 5 5 9 4 5 7 8 7 3 0 1 4 8 5
> ks.test(a,pnorm)

One-sample Kolmogorov-Smirnov test

data: a
D = 0.76134, p-value < 2.2e-16
alternative hypothesis: two-sided

Warning message:
In ks.test(a, pnorm) :
ties should not be present for the Kolmogorov-Smirnov test
> chisq.test(a,p=rep(1/100,100))

Chi-squared test for given probabilities

data: a
X-squared = 198.88, df = 99, p-value = 1.096e-08

Warning message:
In chisq.test(a, p = rep(1/100, 100)) :
Chi-squared approximation may be incorrect
How do I put a border around an Android textview?

If you wants to see text view as 3D view as we seen in Microsoft power point 3d texts. This example demonstrate
about how do I put a border around an Android text view.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:background="#dde4dd"
   android:gravity="center"
   android:orientation="vertical">
   <TextView
      android:id="@+id/text"
      android:textSize="18sp"
      android:layout_width="wrap_content"
      android:background="@drawable/ border "
      android:layout_height="wrap_content" />
</LinearLayout>
In the above code we have taken one text view with background as border so we need to create a file in drawable as boarder.xml and add the following content.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
   <solid android:color="@android:color/white" />
   <stroke android:width="1dip" android:color="#4fa5d5"/>
   <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp"/>
</shape>
In the above code we have taken shape as root tag and given shape is rectangle and added width and padding for shape.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView textView=findViewById(R.id.text);
      textView.setText("Tutorialspoint india pvt ltd");
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Runicon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, we have added boarder to text view.
Click here to download the project code