code-rag-bench/online-tutorials huggingface dataset:
Construct a Turing machine for L = {aibjck | i*j = k; i, j, k ≥ 1} - GeeksforGeeks

18 Oct, 2021
Prerequisite – Turing Machine In a given language, L = {aibjck | i*j = k; i, j, k ≥ 1}, where every string of ‘a’, ‘b’ and ‘c’ has a certain number of a’s, then a certain number of b’s and then a certain number of c’s. The condition is that each of these 3 symbols should occur at least once. ‘a’ and ‘b’ can occur however many times, but the occurrences of ‘c’ must be equal to the product of occurrences of ‘a’ and occurrences of ‘b’. Assume that string is ending with ‘$’. 
Examples –  
Input: a a b b b c c c c c c  
       Here a = 2, b = 3, c = 2 * 3 = 6  
Output: ACCEPTED
          
Input: a a b b c c c
       Here a = 2, b = 2, c = 3 but c should be 4 
Output: NOT ACCEPTED 
Approach used – Scan the input from the left.  
First, replace an ‘a’ with ‘X’ and move 1 step right. Then skip all the a’s and move right. When the pointer reaches the first ‘b’ stop. Replace one ‘b’ with ‘Y’, then move right skipping all intermediate b’s and corresponding to the replaced ‘b’ now replace one ‘c’ with ‘Z’ and move left. Now move towards the left skipping all ‘Z’ and ‘b’ in the way. When the pointer reaches the most recent ‘Y’ move right. If the pointer is pointing at ‘b’ then repeat steps 2 to 4, else if the pointer is pointing at ‘Z’ then move towards left while replacing all ‘Y’ to ‘b’ and skipping all a’s. When the pointer comes to the most recent ‘X’ move one step right. If the pointer is still pointing to ‘a’ then repeat all the above steps, else if the pointer is at ‘b’ then move towards right skipping all ‘b’ and ‘Z’. When $ is reached then move left. The string is ACCEPTED.  
First, replace an ‘a’ with ‘X’ and move 1 step right. Then skip all the a’s and move right. 
When the pointer reaches the first ‘b’ stop. Replace one ‘b’ with ‘Y’, then move right skipping all intermediate b’s and corresponding to the replaced ‘b’ now replace one ‘c’ with ‘Z’ and move left. 
Now move towards the left skipping all ‘Z’ and ‘b’ in the way. 
When the pointer reaches the most recent ‘Y’ move right. 
If the pointer is pointing at ‘b’ then repeat steps 2 to 4, else if the pointer is pointing at ‘Z’ then move towards left while replacing all ‘Y’ to ‘b’ and skipping all a’s. 
When the pointer comes to the most recent ‘X’ move one step right. 
If the pointer is still pointing to ‘a’ then repeat all the above steps, else if the pointer is at ‘b’ then move towards right skipping all ‘b’ and ‘Z’. 
When $ is reached then move left. The string is ACCEPTED.  
 
 
jacushorne
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between DFA and NFA
Design 101 sequence detector (Mealy machine)
Closure properties of Regular languages
Regular expression to ∈-NFA
Boyer-Moore Majority Voting Algorithm
Conversion of Epsilon-NFA to NFA
CYK Algorithm for Context Free Grammar
Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)
Introduction To Grammar in Theory of Computation
Removing Direct and Indirect Left Recursion in a Grammar
sbyte Keyword in C#

22 Jun, 2020
Keywords are the words in a language that are used for some internal process or represent some predefined actions. SByte is a keyword that is used to declare a variable that can store a signed value between the range of -128 to +127. It is an alias of System.SByte.
SByte keyword occupies 1 byte (8 bits) in the memory.
Syntax:
sbyte variable_name = value;
SByte keyword can store the value from the range of -128 to +127.
Example:
Input: -109

Output: num: -109
        Size of a sbyte variable: 1

Input: 110

Output: Type of num: System.SByte
        num: 110
        Size of a sbyte variable: 1

Example 1:
// C# program for sbyte keywordusing System;using System.Text;  class GFG {      static void Main(string[] args)    {        // char variable declaration        sbyte num = -109;          // to print value        Console.WriteLine("num: " + num);          // to print size of a sbyte        Console.WriteLine("Size of a sbyte variable: " + sizeof(sbyte));    }}
Output:
num: -109
Size of a sbyte variable: 1

Example 2:
// C# program for sbyte keywordusing System;using System.Text;  namespace geeks {  class GFG {      static void Main(string[] args)    {        // char variable declaration        sbyte num = 110;          // to print type of variable        Console.WriteLine("Type of num: " + num.GetType());          // to print value        Console.WriteLine("num: " + num);          // to print size of sbyte         Console.WriteLine("Size of a sbyte variable: " + sizeof(sbyte));          // hit ENTER to exit        Console.ReadLine();    }}}
Output:
Type of num: System.SByte
num: 110
Size of a sbyte variable: 1

Example 3:
// C# program for sbyte keywordusing System;using System.Text;  class GFG {      static void Main(string[] args)    {        // char variable declaration        sbyte num = -189;          // to print value        Console.WriteLine("num: " + num);          // to print size of a sbyte        Console.WriteLine("Size of a sbyte variable: " + sizeof(sbyte));    }}
Error: When we enter number beyond the range from (-128-127).
Constant value `-189′ cannot be converted to a `sbyte’
CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Lambda Expressions in C#
Partial Classes in C#
Hello World in C#
plotly.express.scatter_3d() function in Python

17 Jul, 2020
Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use.
This function is used to create a 3D scatter plot and can be used with pandas dataframes. Each row of dataframe is represented by a symbol mark in 3D space in a scatter plot.
Syntax: plotly.express.scatter_3d(data_frame=None, x=None, y=None, z=None, color=None, symbol=None, size=None, text=None, hover_name=None, hover_data=None, custom_data=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, error_z=None, error_z_minus=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, size_max=None, color_discrete_sequence=None, color_discrete_map={}, title=None, template=None, width=None, height=None)
Parameters:
data_frame: DataFrame or array-like or dict needs to be passed for column names.
x, y, z: This parameters is either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x, y and z axis in cartesian coordinates respectively.
color: This parameters assign color to marks.
symbol: This parameter is used to assign symbols to marks. It is either a name of a column in data_frame, or a pandas Series or array_like object.
size: This parameter is used to assign mark sizes. It is either a name of a column in data_frame, or a pandas Series or array_like object.
hover_name:  Values from this column or array_like appear in bold in the hover tooltip.
hover_data: This parameter is used to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip.
Example 1:
Python3
# Python program to demonstrate 3D scatter# plot  import plotly.express as px  df = px.data.tips()  plot = px.scatter_3d(df, x = 'day',                      y = 'total_bill',                     z='sex')plot.show()
Output:
Example 2: Using color argument
Python3
# Python program to demonstrate scatter# plot  import plotly.express as px  df = px.data.tips()  plot = px.scatter_3d(df, x = 'day',                      y = 'total_bill',                     z = 'sex',                      color = 'time')plot.show()
Output:
Example 3:
Python3
# Python program to demonstrate scatter# plot  import plotly.express as px  df = px.data.tips()  plot = px.scatter_3d(df, x = 'day',                      y = 'total_bill',                      z = 'sex',                      color = 'time',                     symbol = 'total_bill')plot.show()
Output:
Python Plotly express-class
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js Moment Module

08 Oct, 2021
The moment module is used for parsing, validating, manipulating, and displaying dates and times in JavaScript.
Feature of moment module:
It is easy to get started and easy to use.It is widely used and popular for formatting date and time.
It is easy to get started and easy to use.
It is widely used and popular for formatting date and time.
Installation of moment module:
You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing moment module, you can check your moment version in command prompt using the command.npm ls momentAfter that, you can create a folder and add a file, for example index.js. To run this file, you need to run the following command.node index.js
You can visit the link to Install moment module. You can install this package by using this command.npm install moment
npm install moment
After installing moment module, you can check your moment version in command prompt using the command.npm ls moment
npm ls moment
After that, you can create a folder and add a file, for example index.js. To run this file, you need to run the following command.node index.js
node index.js
Filename: index.js
var moment = require('moment');  // 2020-05-08T22:57:42+05:30console.log(moment().format());  // May 8th 2020, 10:56:31 pmconsole.log(moment().format('MMMM Do YYYY, h:mm:ss a'));  // Fridayconsole.log(moment().format('dddd'));  // May 8th 20console.log(moment().format("MMM Do YY"));  // 2020 escaped 2020 console.log(moment().format('YYYY [escaped] YYYY'));
Steps to run the program:
The project structure will look like this:Make sure you have install moment module using the following commands:npm install momentRun index.js file using below command:node index.js
The project structure will look like this:
Make sure you have install moment module using the following commands:npm install moment
npm install moment
Run index.js file using below command:node index.js
node index.js
So this is how you can use the moment module for parsing, validating, manipulating, and displaying dates and times in JavaScript.
pritishnagpal
NodeJS-Questions
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to measure time with high-precision in Python?

To measure time with high precision, either use time.clock() or time.time() functions. The python docs state that this function should be used for benchmarking purposes.
import time
t0= time.clock()
print("Hello")
t1 = time.clock() - t0
print("Time elapsed: ", t1 - t0) # CPU seconds elapsed (floating point)
This will give the output −
Time elapsed:  0.0009403145040156798
Note that different systems will have different accuracy based on their internal clock setup (ticks per second). but it's generally at least under 20ms. Also note that clock returns different things on different platforms. On Unix, it returns the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.
Write one line functions for strcat() and strcmp()

31 Jul, 2018
Recursion can be used to do both tasks in one line. Below are one line implementations for stracat() and strcmp().
/* my_strcat(dest, src) copies data of src to dest.  To do so, it first reaches end of the string dest using recursive calls my_strcat(++dest, src).  Once end of dest is reached, data is copied using (*dest++ = *src++)?  my_strcat(dest, src). */void my_strcat(char *dest, char *src){  (*dest)? my_strcat(++dest, src): (*dest++ = *src++)? my_strcat(dest, src): 0 ;}  /* driver function to test above function */int main(){  char dest[100] = "geeksfor";  char *src = "geeks";  my_strcat(dest, src);  printf(" %s ", dest);  getchar();}    
The function my_strcmp() is simple compared to my_strcmp().
/* my_strcmp(a, b) returns 0 if strings a and b are same, otherwise 1.   It recursively increases a and b pointers. At any point if *a is not equal to *b then 1 is returned.  If we reach end of both strings at the same time then 0 is returned. */int my_strcmp(char *a, char *b){  return (*a == *b && *b == '\0')? 0 : (*a == *b)? my_strcmp(++a, ++b): 1;}   /* driver function to test above function */int main(){  char *a = "geeksforgeeks";  char *b = "geeksforgeeks";  if(my_strcmp(a, b) == 0)     printf(" String are same ");  else       printf(" String are not same ");      getchar();  return 0;}    
The above functions do very basic string concatenation and string comparison. These functions do not provide same functionality as standard library functions.
Please write comments if you find the above code incorrect, or find better ways to solve the same problem.
C Array and String
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
'this' pointer in C++
Storage Classes in C
Ways to copy a vector in C++
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)
Program to split two strings to make palindrome using Python

Suppose we have two strings a and b whose length are same. We have to select an index and split both strings at that selected index, splitting a into two strings: a_pref and a_suff where a = a_pref | a_suff, and splitting b into two strings: b_pref | b_suff (| is concatenation operator) where b = b_pref + b_suff. Check if a_pref + b_suff or b_pref + a_suff forms a palindrome or not. (Any split may be an empty string)
So, if the input is like a = "pqrst" b = "turqp", then the output will be True because we can split a like ["pq", "rst"] and b like ["tu", "rqp"], so if we join a_pref with b_suff, we will get "pqrqp" which is a palindrome.
To solve this, we will follow these steps −
for each pair (x, y) from list of pairs [(a, b), (b, a)], doi := 0, j := size of x - 1while x[i] is same as y[j] and i < size of x and j > 0, doi := i + 1j := j - 1midx := substring of x from index i to jmidy := substring of y from index i to jif midx is palindrome or midy is palindrome, thenreturn True
for each pair (x, y) from list of pairs [(a, b), (b, a)], do
i := 0, j := size of x - 1
i := 0, j := size of x - 1
while x[i] is same as y[j] and i < size of x and j > 0, doi := i + 1j := j - 1
while x[i] is same as y[j] and i < size of x and j > 0, do
i := i + 1
i := i + 1
j := j - 1
j := j - 1
midx := substring of x from index i to j
midx := substring of x from index i to j
midy := substring of y from index i to j
midy := substring of y from index i to j
if midx is palindrome or midy is palindrome, thenreturn True
if midx is palindrome or midy is palindrome, then
return True
return True
return False
return False
Let us see the following implementation to get better understanding −
def solve(a, b):
   for x, y in [[a, b], [b, a]]:
      i, j = 0, len(x) - 1
      while x[i] == y[j] and i<len(x) and j>0:
         i += 1
         j -= 1
      midx = x[i:j+1]
      midy = y[i:j+1]
      if (midx == midx[::-1] or midy== midy[::-1]):
         return True
   return False

a = "pqrst"
b = "turqp"
print(solve(a, b))
"pqrst", "turqp"
True
Thread functions in C/C++

In this tutorial, we will be discussing a program to understand thread functions in C/C++.
Thread functions allow users to implement concurrent functions at the same time, which can either be dependent on each other for execution or independent.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* func(void* arg){
   //detaching the current thread
   pthread_detach(pthread_self());
   printf("Inside the thread\n");
   pthread_exit(NULL);
}
void fun(){
   pthread_t ptid;
   //creating a new thread
   pthread_create(&ptid, NULL, &func, NULL);
   printf("This line may be printed before thread terminates\n");
   if(pthread_equal(ptid, pthread_self())
      printf("Threads are equal\n");
   else
      printf("Threads are not equal\n");
   //waiting for the created thread to terminate
   pthread_join(ptid, NULL);
   printf("This line will be printed" " after thread ends\n");
   pthread_exit(NULL);
}
int main(){
   fun();
   return 0;
}
This line may be printed before thread terminates
Threads are not equal
Inside the thread
This line will be printed after thread ends
Pure Virtual Functions and Abstract Classes in C++

A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in the declaration.
An abstract class is a class in C++ which have at least one pure virtual function.
Abstract class can have normal functions and variables along with a pure virtual function.
Abstract class can have normal functions and variables along with a pure virtual function.
Abstract class cannot be instantiated, but pointers and references of Abstract class type can be created.
Abstract class cannot be instantiated, but pointers and references of Abstract class type can be created.
Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
If an Abstract Class has derived class, they must implement all pure virtual functions, or else they will become Abstract too.
If an Abstract Class has derived class, they must implement all pure virtual functions, or else they will become Abstract too.
We can’t create object of abstract class as we reserve a slot for a pure virtual function in Vtable, but we don’t put any address, so Vtable will remain incomplete.
We can’t create object of abstract class as we reserve a slot for a pure virtual function in Vtable, but we don’t put any address, so Vtable will remain incomplete.
 Live Demo
#include<iostream>
using namespace std;
class B {
   public:
      virtual void s() = 0; // Pure Virtual Function
};

class D:public B {
   public:
      void s() {
         cout << "Virtual Function in Derived class\n";
      }
};

int main() {
   B *b;
   D dobj;
   b = &dobj;
   b->s();
}
Virtual Function in Derived class
Ruby | Numeric round() function

06 Jan, 2020
The round() is an inbuilt method in Ruby returns a number rounded to a number nearest to the given number with a precision of the given number of digits after the decimal point. In case the number of digits is not given, the default value is taken to be zero.
Syntax: num.round(ndigits)
Parameters: The function needs a number and ndigits which specifies the number of digits to be rounded off. If ndigits is not given then, default value is taken to be zero.
Return Value: It returns the rounded value.
Example 1:
# Ruby program for round()# method in Numeric  # Initialize a number num1 = -16.7834num2 = -16.78324num3 = 16.873  # Prints roundputs num1.round(1)puts num2.round()puts num3.round()
Output:
-16.8
-17
17

Example 2:
# Ruby program for round()# method in Numeric  # Initialize a number num1 = 12.32num2 = -1321.998321num3 = -12.2321  # Prints roundputs num1.round(1)puts num2.round(2)puts num3.round(3)
Output:
12.3
-1322.0
-12.232
Ruby Numeric-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

When we transfer files between Windows and Unix systems, often we come across with issue relating to the end of line character. This is because the EOL character in windows is not recognized as a EOL character in Unix. SO to fix this issue when a file is transferred from Windows to Unix we need to follow one of the below methods.
The dos2unix command is used to convert the EOL character of windows platform to Unix platform. Most of the Unix system comes with this command pre-installed. Below we see how we can convert the file itself or save a copy of the file, when using this command.
# change the file itself.
dos2unix file_name.txt
# Save a copy of the file.
dos2unix -n file_name.txt new_file_name.txt
When we transfer the file from windows to Unix platform and open to read it, the end of line character appears as ^M (called control-M). So we use sed command to replace the ^M characters. Here also we can save the edited file as a new file.
sed 's/^M$//' file_name.txt > new_file_name.txt
The tr command is used in translating or deleting the characters. In this case we will use it to delete the end of the line character in the file from Windows system, if it appears as â\râ in the unix system when opened.
tr -d '\r' file_name.txt > new_file_name.txt
After the above command executes successfully, we can successfully open the file in Unix system without showing the EO L values from Windows system.
How can we create a login form in Java?


We can develop a login form in Java using Java Swing technology. In this example, we can create two labels username and password, two text fields for the user to enter valid credentials and finally one submit button. Once the user is able to enter the valid credentials in the two text fields, we can able to see Hello admin in the login form.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LoginDemo extends JFrame implements ActionListener {
   JPanel panel;
   JLabel user_label, password_label, message;
   JTextField userName_text;
   JPasswordField password_text;
   JButton submit, cancel;
   LoginDemo() {
      // Username Label
      user_label = new JLabel();
      user_label.setText("User Name :");
      userName_text = new JTextField();
      // Password Label
      password_label = new JLabel();
      password_label.setText("Password :");
      password_text = new JPasswordField();
      // Submit
      submit = new JButton("SUBMIT");
      panel = new JPanel(new GridLayout(3, 1));
      panel.add(user_label);
      panel.add(userName_text);
      panel.add(password_label);
      panel.add(password_text);
      message = new JLabel();
      panel.add(message);
      panel.add(submit);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      // Adding the listeners to components..
      submit.addActionListener(this);
      add(panel, BorderLayout.CENTER);
      setTitle("Please Login Here !");
      setSize(450,350);
      setVisible(true);
   }
   public static void main(String[] args) {
      new LoginDemo();
   }
   @Override
   public void actionPerformed(ActionEvent ae) {
      String userName = userName_text.getText();
      String password = password_text.getText();
      if (userName.trim().equals("admin") && password.trim().equals("admin")) {
         message.setText(" Hello " + userName + "");
      } else {
         message.setText(" Invalid user.. ");
      }
   }
}
Python 3 - List max() Method

The max() method returns the elements from the list with maximum value.
Following is the syntax for max() method −
max(list)

list − This is a list from which max valued element to be returned.
This method returns the elements from the list with maximum value.
The following example shows the usage of max() method.
#!/usr/bin/python3

list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))
When we run above program, it produces the following result −
Max value element :  Python
Max value element :  700


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
ReactJS componentDidCatch method

In this article, we are going to see how to execute a function in the commit phase if some error occurs in the Component.
This method is called when a component or any children component encounters some error during the React Component Lifecycle. This method allows us to handle the error boundaries of the application.
Unlike the getDerivedStateFromError method, this method is called during the commit phase, so side-effects are also allowed in this method.
componentDidCatch(err, data)
err - Error thrown by the component.
err - Error thrown by the component.
data - Stores information about the component which has thrown the error.
data - Stores information about the component which has thrown the error.
In this example, we will build a React application that displays the contained Comp component if no error occurs; otherwise it displays some text.
But here, in Comp component, error is defined to occur as the state is not defined which fires the componentDidCatch method in the parent component.
App.jsx
import React from 'react';

class App extends React.Component {
   constructor() {
      super();
      this.state = {
         err: false,
      };
   }
   componentDidCatch(error) {
      this.setState({
         err: true,
      });
   }
   render() {
      return (
         <div>
            {this.state.err ? (
               <div style={{border: '2px solid red',}}>
                  Error
               </div>
               ) : (
               <Comp/>
            )}
         </div>
      );
   }
}
class Comp extends React.Component {
   render() {
      return <h1>{this.state.name}</h1>;
   }
}
export default App;
This will produce the following result −
Spring Boot - Enabling HTTPS

By default, Spring Boot application uses HTTP 8080 port when the application starts up.
You need to follow the steps given below to configure the HTTPS and the port 443 in Spring Boot application −
Obtain the SSL certificate – Create a self-signed certificate or get one from a Certificate Authority
Obtain the SSL certificate – Create a self-signed certificate or get one from a Certificate Authority
Enable HTTPS and 443 port
Enable HTTPS and 443 port
To create a self-signed certificate, Java Run Time environment comes bundled with certificate management utility key tool. This utility tool is used to create a Self-Signed certificate. It is shown in the code given here −
keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
Enter keystore password:
   Re-enter new password:
   What is your first and last name?
   [Unknown]:
   What is the name of your organizational unit?
   [Unknown]:
   What is the name of your organization?
   [Unknown]:
   What is the name of your City or Locality?
   [Unknown]:
   What is the name of your State or Province?
   [Unknown]:
   What is the two-letter country code for this unit?
   [Unknown]:
   Is CN = Unknown, OU=Unknown, O = Unknown, L = Unknown, ST = Unknown, C = Unknown correct?
   [no]: yes
This code will generate a PKCS12 keystore file named as keystore.p12 and the certificate alias name is tomcat.
We need to provide the server port as 443, key-store file path, key-store-password, key-store-type and key alias name into the application.properties file. Observe the code given here −
server.port: 443
server.ssl.key-store: keystore.p12
server.ssl.key-store-password: springboot
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
You can use the following code if you are using YAML properties use below application.yml −
server:
   port: 443
   ssl:
      key-store: keystore.p12
      key-store-password: springboot
      keyStoreType: PKCS12
      keyAlias: tomcat
You can create an executable JAR file, and run the spring boot application by using the following Maven or Gradle commands.
For Maven, you can use the following command −
mvn clean install

After “BUILD SUCCESS”, you can find the JAR file under the target directory.
For Gradle, you can use the command
gradle clean build

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.
Now, run the JAR file by using the following command −
java –jar <JARFILE>

Now, the application has started on the Tomcat port 443 with https as shown −

    102 Lectures 
     8 hours 

 Karthikeya T

    39 Lectures 
     5 hours 

 Chaand Sheikh

    73 Lectures 
     5.5 hours 

 Senol Atac

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac

    69 Lectures 
     5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Jackson Annotations - @JsonProperty

@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      String json = "{\"id\" : 1}";
      Student student = mapper.readerFor(Student.class).readValue(json);
      System.out.println(student.getTheId());
   }
}
class Student {
   private int id;
   Student(){}
   Student(int id){
      this.id = id;
   }
   @JsonProperty("id")
   public int getTheId() {
      return id;
   }
   @JsonProperty("id")
   public void setTheId(int id) {
      this.id = id;
   }   
}
1

 Print
 Add Notes
 Bookmark this page
ReactJS – createRef() method

In this article, we are going to see how to create a reference to any DOM element in the functional component.
This method is used to access any DOM element in a component and it returns a mutable ref object which will be persisted as long as the component is placed in the DOM. If we pass a ref object to any DOM element, then the. current property to the corresponding DOM node elements will be added whenever the node changes.
React.createRef()
In this example, we will build a React application that will pass the ref object to two input fields and when clicked on the button, it will automatically fetch the data of these input fields.
App.jsx
import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      this.fetchUsername = this.fetchUsername.bind(this);
      this.fetchEmail = this.fetchEmail.bind(this);
   }
   fetchUsername() {
      this.refs.username.value = 'RahulBansal123';
   }
   fetchEmail() {
      this.refs.email.value = 'rahul@gmail.com';
   }
   render() {
      return (
         <div>
            <input type="text" ref="username" />
            <input type="text" ref="email" />
            <button type="button" onClick={this.fetchUsername}>
               Username
            </button>
            <button type="button" onClick={this.fetchEmail}>
               Email
            </button>
         </div>
      );
   }
}
export default App;
In the above example, when the Username or Email button is clicked, then the fetchUsername and fetchEmail function is called respectively which pass the ref object to the input fields and change its value from null to some text.
This will produce the following result.
Passing parameters by references in C++

We have discussed how we implement call by reference concept using pointers. Here is another example of call by reference which makes use of C++ reference −
#include <iostream>
using namespace std;
 
// function declaration
void swap(int& x, int& y);
 
int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
 
   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;
 
   /* calling a function to swap the values.*/
   swap(a, b);
 
   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;
 
   return 0;
}
 
// function definition to swap the values.
void swap(int& x, int& y) {

   int temp;
   temp = x; /* save the value at address x */
   x = y;    /* put y into x */
   y = temp; /* put x into y */
  
   return;
}
When the above code is compiled and executed, it produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Iterate through Java Pair Tuple

The iteration through Pair in JavaTuples is the same as you may have seen in Java Arrays collection.
Let us first see what we need to work with JavaTuples. To work with Pair class in JavaTuples, you need to import the following package −
import org.javatuples.Pair;
Note − Steps to download and run JavaTuples program If you are using Eclipse IDE to run Pair Class in JavaTuples, then Right Click Project → Properties → Java Build Path → Add External Jars and upload the downloaded JavaTuples jar file.
The following is an example −
import org.javatuples.Pair;
public class Demo {
   public static void main(String[] args) {
      Pair < String, String > p = Pair.with("Mobile", "Desktop");
      for (Object ob: p)
         System.out.println(ob);
   }
}
Mobile
Desktop
How to see request logs in Postman console?

We can see request logs in the Postman console. Once a request has been sent, the Postman console records the header of request, variables, Response header and body, certificates, proxy settings, errors, scripts, output obtained from console.log, and so on.
The Console is obtained from the Postman application by following the navigation − View menu Show Postman Console. Or using the shortcut Ctrl+Alt+C.
Let us send a GET request for an endpoint. Add a Pre-request and Tests scripts.
console.log("Tutorialspoint - Postman")
console.warn("Warning message in console")
console.log("Logging message in console")
console.info("Info message in console")
console.error("Error message in console")
Postman Console Output shows the message from the Pre-Request and Test scripts. Also, we find the Response code and the Response time obtained from the request.
We can expand the panel of the Request, to get more details −
In the Postman Console, we can filter the Console Output messages by Log, Info, Warning and Error. We can also delete the previous logs with the Clear button.
DAX Date & Time - NOW function

Returns the current date and time in datetime format.
NOW () 

No parameters for this function.
A date in datetime format.
DAX NOW function is useful when you need to display the current date and time on a worksheet or calculate a value based on the current date and time, and have that value updated each time you open the workbook.
DAX uses datetime format when working with dates. Dates stored in other formats are converted implicitly.
The result of NOW function changes only when the column that contains the DAX formula is refreshed. It is not updated continuously.
DAX TODAY function also returns the current date but is not precise with regard to time. The time returned is always 12:00:00 AM and only the date is updated.
= NOW () 
= HOUR (NOW ()) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How to print results of script in MongoDB?

We will use printjson() for this. Let us first create a collection with documents −
> dbprintResultScriptDemoinsertOne({"StudentName":"John","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cf22c02b64a577be5a2bc0b")
}
> dbprintResultScriptDemoinsertOne({"StudentName":"Carol","StudentAge":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cf22c09b64a577be5a2bc0c")
}
> dbprintResultScriptDemoinsertOne({"StudentName":"David","StudentAge":19});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cf22c11b64a577be5a2bc0d")
}
Following is the query to display all documents from a collection with the help of find() method −
> dbprintResultScriptDemofind();
This will produce the following document −
{ "_id" : ObjectId("5cf22c02b64a577be5a2bc0b"), "StudentName" : "John", "StudentAge" : 21 }
{ "_id" : ObjectId("5cf22c09b64a577be5a2bc0c"), "StudentName" : "Carol", "StudentAge" : 20 }
{ "_id" : ObjectId("5cf22c11b64a577be5a2bc0d"), "StudentName" : "David", "StudentAge" : 19 }
Following is the query to print results of script −
> var document=dbprintResultScriptDemofind();
> while (documenthasNext()) {
   printjson(documentnext());
}
This will produce the following document −
{
   "_id" : ObjectId("5cf22c02b64a577be5a2bc0b"),
   "StudentName" : "John",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5cf22c09b64a577be5a2bc0c"),
   "StudentName" : "Carol",
   "StudentAge" : 20
}
{
   "_id" : ObjectId("5cf22c11b64a577be5a2bc0d"),
   "StudentName" : "David",
   "StudentAge" : 19
}
Set filtering conditions for nested array in MongoDB

To set filtering conditions, use $filter and $cond in MongoDB aggregate(). The $filter selects a subset of an array to return based on the specified condition. Let us create a collection with documents −
> db.demo725.insertOne(
...    {
...
...       "details": {
...
...          "userMessages": [
...             {
...                "Messages": [
...                   { "Message": "Hello" },
...                   { "Message": "How" },
...                   { "Message": "are" }
...                ]
...
...             },
...             {
...                "Messages": [
...                   { "Message": "Good" },
...                   { "Message": "Bye" }
...
...                ]
...             },
...             {
...                "Messages": [
...                   { "Message": "Hello" },
...                   { "Message": "Bye" }
...
...                ]
...
...             }
...          ]
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eab16cd43417811278f5893")
}
Display all documents from a collection with the help of find() method −
> db.demo725.find();
This will produce the following output −
{ "_id" : ObjectId("5eab16cd43417811278f5893"), "details" : { "userMessages" : [ { "Messages" : [ { "Message" : "Hello" }, { "Message" : "How" }, { "Message" : "are" } ] }, { "Messages" : [ { "Message" : "Good" }, { "Message" : "Bye" } ] }, { "Messages" : [ { "Message" : "Hello" }, { "Message" : "Bye" } ] } ] } }
Following is the query to set filtering conditions for nested array −
> db.demo725.aggregate([
...    {
...       $addFields: {
...          "details.userMessages": {
...             $filter: {
...                input: "$details.userMessages",
...                as: "out",
...                cond: {
...                   $anyElementTrue: {
...                      $map: {
...                         input: "$$out.Messages",
...                         in: { $gte: [ { $indexOfBytes: [ "$$this.Message", "Hello" ] }, 0 ] }
...                      }
...                   }
...                }
...             }
...          }
...       }
...    }
... ]).pretty()
This will produce the following output −
{
   "_id" : ObjectId("5eab16cd43417811278f5893"),
   "details" : {
      "userMessages" : [
         {
            "Messages" : [
               {
                  "Message" : "Hello"
               },
               {
                  "Message" : "How"
               },
               {
                  "Message" : "are"
               }
            ]
         },
         {
            "Messages" : [
               {
                  "Message" : "Hello"
               },
               {
                  "Message" : "Bye"
               }
            ]
         }
      ]
   }
}
Construct the derivation tree for the string aabbabba.

Derive a derivation tree for the string aabbabba for the given context free grammar (CFG) −
S->aB|bA
A->a|aS|bAA
B->b|bS|aBB
Derivation is a sequence of production rules, which is used to get input strings.
It is a graphical representation for derivation of given production rules for a given CFG. It is also called as a parse tree.
The derivation tree contains some properties, which are as follows −
The root node is always a node indicating the start symbol.
The derivation is read from left to right.
The leaf node is always terminal nodes.
The interior nodes are always the non-terminal nodes.
The given CFG is as follows −
S->aB|bA
A->a|aS|bAA
B->b|bS|aBB
To draw a parse tree first try to obtain derivation for the string aabbabba
Let’s take leftmost derivation as shown below −
S-> aB
 ->aaBB
 ->aabSB
 ->aabbAB
 ->aabbaB
 ->aabbabS
 ->aabbabbA
 ->aabbabba which is our final string
Now, construct the derivation tree for the given grammar.
If the grammar is generating more than one type of tree, then we call the given grammar ambiguous grammar.
Check if object contains all keys in JavaScript array

We are required to write a function containsAll() that takes in two arguments, first an object and
second an array of strings. It returns a boolean based on the fact whether or not the object
contains all the properties that are mentioned as strings in the array.
So, let’s write the code for this. We will iterate over the array, checking for the existence of each
element in the object, if we found a string that’s not a key of object, we exit and return false,
otherwise we return true.
Here is the code for doing the same −
const obj = {
   'name': 'Ashish Kumar','dob': '12/07/1991','gen': 'M','isEmployed': true,'jobType': 'full-time'
};
const obj2 = {
   'name': 'Ashish Kumar','dob': '12/07/1991','gen': 'M','jobType': 'full-time'
};
const arr = ['dob', 'name', 'gen', 'isEmployed', 'jobType'];
const containsAll = (obj, arr) => {
   for(const str of arr){
      if(Object.keys(obj).includes(str)){
         continue;
      }else{
         return false;
      }
   }
   return true;
};
console.log(containsAll(obj, arr));
console.log(containsAll(obj2, arr));
The output of the above code in the console will be −
true
false
How to convert DateTime to integer in Python

30 Aug, 2021
Python provides a module called DateTime to perform all the operations related to date and time. It has a rich set of functions used to perform almost all the operations that deal with time. It needs to be imported first to use the functions and it comes along with python, so no need to install it separately.
Here, we deal with a special date object. So to convert the given date to integer, we can follow the following method.
In this method, we will multiply each component, of the date with multiples of 100 and add them all to convert them into integers.
Python3
# importing the datetime moduleimport datetime # Getting todays date and time using now() of# datetime classcurrent_date = datetime.datetime.now() # Printing the current_date as the date object itself.print("Original date and time object:", current_date) # Retrieving each component of the date# i.e year,month,day,hour,minute,second and# Multiplying with multiples of 100# year - 10000000000# month - 100000000# day - 1000000# hour - 10000# minute - 100print("Date and Time in Integer Format:",      current_date.year*10000000000 +      current_date.month * 100000000 +      current_date.day * 1000000 +      current_date.hour*10000 +      current_date.minute*100 +      current_date.second)
Output:
Original date and time object: 2021-08-10 15:51:25.695808
Date and Time in Integer Format: 20210810155125
In this method, we are using strftime() function of datetime class which converts it into the string which can be converted to an integer using the int() function.
Syntax : strftime(format)
Returns : It returns the string representation of the date or time object.
Code:
Python3
# importing the datetime moduleimport datetime # Getting todays date and time using now() of datetime# classcurrent_date = datetime.datetime.now() # Printing the current_date as the date object itself.print("Original date and time object:", current_date) # Using the strftime() of datetime class# which takes the components of date as parameter# %Y - year# %m - month# %d - day# %H - Hours# %M - Minutes# %S - Secondsprint("Date and Time in Integer Format:",      int(current_date.strftime("%Y%m%d%H%M%S")))
Output:
Original date and time object: 2021-08-10 15:55:19.738126
Date and Time in Integer Format: 20210810155519
anikaseth98
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
Specify Row Names when Reading Excel File in R

31 Aug, 2021
In this article, we are going to specify the row names when reading Excel file in the R Programming language.
Specifying row names when reading a file using row.names argument of the read.xlsx2() function.
This is the easiest approach to specify the row names when reading a file in the R programming language as in this approach the user needs to just call the read.xlsx() function which is particularly used for importing the excel type size, and used the row.names argument of this function with the required values into it and this will be reading to the specifying row names as per mentioned as the argument value with reading o file in the R programming language. Also, xlsx package, for this approach the user needs to install and import the xlsx package to the R working console as the function used here is from this package.
To install and import the xlsx package the user needs to follow the below syntax:
install.packages("xlsx")                            
library("xlsx")  
Read.xlsx2() function: This function is used to read data from an Excel file or Workbook object into data.frame
Syntax: read.xlsx(xlsxFile, sheet, startRow = 1, colNames = TRUE, rowNames = FALSE, detectDates = FALSE, skipEmptyRows = TRUE, skipEmptyCols = TRUE, rows = NULL, cols = NULL,check.names = FALSE, sep.names = “.”, namedRegion = NULL, na.strings = “NA”, fillMergedCells = FALSE,row.names)
We will be using the xlsx file of 6 rows and 5 columns and with the use of the row.names argument we will be specifying the row names to 1 while reading this file.
R
library(xlsx)  gfg_file = read.xlsx2("GFG_DATA.xlsx",                       sheetIndex = 1,                      row.names = 1)gfg_file
Output:
We will be using the xlsx file of 6 rows and 5 columns same as used in the previous example and with the use of the row.names argument we will specify the row names to 4 while reading this file.
R
library(xlsx)  gfg_file = read.xlsx2("GFG_DATA.xlsx",                      sheetIndex = 1,                      row.names = 4)gfg_file
Output:
Picked
R-Excel
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
R - if statement
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming