code-rag-bench/online-tutorials huggingface dataset:
Teradata - Date/Time Functions

This chapter discusses the date/time functions available in Teradata.
Dates are stored as integer internally using the following formula.
((YEAR - 1900) * 10000) + (MONTH * 100) + DAY

You can use the following query to check how the dates are stored.
SELECT CAST(CURRENT_DATE AS INTEGER);

Since the dates are stored as integer, you can perform some arithmetic operations on them. Teradata provides functions to perform these operations.
EXTRACT function extracts portions of day, month and year from a DATE value. This function is also used to extract hour, minute and second from TIME/TIMESTAMP value.
Following examples show how to extract Year, Month, Date, Hour, Minute and second values from Date and Timestamp values.
SELECT EXTRACT(YEAR FROM CURRENT_DATE);  
EXTRACT(YEAR FROM Date) 
----------------------- 
        2016  
SELECT EXTRACT(MONTH FROM CURRENT_DATE);  
EXTRACT(MONTH FROM Date) 
------------------------ 
          1        
SELECT EXTRACT(DAY FROM CURRENT_DATE);  
EXTRACT(DAY FROM Date) 
------------------------ 
          1    
       
SELECT EXTRACT(HOUR FROM CURRENT_TIMESTAMP);  
EXTRACT(HOUR FROM Current TimeStamp(6)) 
--------------------------------------- 
                 4      
SELECT EXTRACT(MINUTE FROM CURRENT_TIMESTAMP);  
EXTRACT(MINUTE FROM Current TimeStamp(6)) 
----------------------------------------- 
                 54  
SELECT EXTRACT(SECOND FROM CURRENT_TIMESTAMP);  
EXTRACT(SECOND FROM Current TimeStamp(6)) 
----------------------------------------- 
              27.140000
Teradata provides INTERVAL function to perform arithmetic operations on DATE and TIME values. There are two types of INTERVAL functions.
YEAR
YEAR TO MONTH
MONTH
DAY
DAY TO HOUR
DAY TO MINUTE
DAY TO SECOND
HOUR
HOUR TO MINUTE
HOUR TO SECOND
MINUTE
MINUTE TO SECOND
SECOND
The following example adds 3 years to current date.
SELECT CURRENT_DATE, CURRENT_DATE + INTERVAL '03' YEAR; 
  Date    (Date+ 3) 
--------  --------- 
16/01/01   19/01/01
The following example adds 3 years and 01 month to current date.
SELECT CURRENT_DATE, CURRENT_DATE + INTERVAL '03-01' YEAR TO MONTH; 
 Date     (Date+ 3-01) 
--------  ------------ 
16/01/01    19/02/01
The following example adds 01 day, 05 hours and 10 minutes to current timestamp.
SELECT CURRENT_TIMESTAMP,CURRENT_TIMESTAMP + INTERVAL '01 05:10' DAY TO MINUTE; 
     Current TimeStamp(6)         (Current TimeStamp(6)+ 1 05:10) 
--------------------------------  -------------------------------- 
2016-01-01 04:57:26.360000+00:00  2016-01-02 10:07:26.360000+00:00
 Print
 Add Notes
 Bookmark this page
fork() to execute processes from bottom to up using wait() in C++

We know that the fork() system call is used to divide the process into two processes. If the function fork() returns 0, then it is child process, and otherwise it is parent process.
In this example we will see how to split processes four times, and use them in bottom up manner. So at first we will use fork() function two times. So it will generate a child process, then from the next fork it will generate another child. After that from the inner fork it will automatically generates a grandchild of them.
We will use wait() function to generate some delay and execute the processes as bottom up manner.
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
int main() {
   pid_t id1 = fork(); //make 4 process using two consecutive fork. The main process, two children and one grand child
   pid_t id2 = fork();
   if (id1 > 0 && id2 > 0) { //when both ids are non zero, then it is parent process
      wait(NULL);
      wait(NULL);
      cout << "Ending of parent process" << endl;
   }else if (id1 == 0 && id2 > 0) { //When first id is 0, then it is first child
      sleep(2); //wait 2 seconds to execute second child first
      wait(NULL);
      cout << "Ending of First Child" << endl;
   }else if (id1 > 0 && id2 == 0) { //When second id is 0, then it is second child
      sleep(1); //wait 2 seconds
      cout << "Ending of Second child process" << endl;
   }else {
      cout << "Ending of grand child" << endl;
   }
   return 0;
}
soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
Ending of grand child
Ending of Second child process
Ending of First Child
Ending of parent process
soumyadeep@soumyadeep-VirtualBox:~$
Make the button size extra small with Bootstrap

Use the .btn-xs class to create a button size extra small than the standard button.
You can try to run the following code to make the size of a button extra small
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p>The following are extra small buttons:</p>
      <button type = "button" class = "btn btn-primary btn-xs">
         Exra Small Primary button
      </button>
      <button type = "button" class = "btn btn-default btn-xs">
         Extra Small button
      </button>
   </body>
</html>
Python - Ways to convert string to json object

Data send and get generally in a string of dictionary(JSON objects) forms in many web API’s to use that data to extract meaningful information we need to convert that data in dictionary form and use for further operations.
 Live Demo
# converting string to json
# using json.loads
import json
# inititialising json object
ini_string = {'vishesh': 1, 'ram' : 5, 'prashant' : 10, 'vishal' : 15}
# printing initial json
ini_string = json.dumps(ini_string)
print ("initial 1st dictionary", ini_string)
print ("type of ini_object", type(ini_string))
# converting string to json
final_dictionary = json.loads(ini_string)
# printing final result
print ("final dictionary", str(final_dictionary))
print ("type of final_dictionary", type(final_dictionary))
('initial 1st dictionary', '{"vishal": 15, "ram": 5, "vishesh": 1, "prashant": 10}')
('type of ini_object', <type 'str'>)
('final dictionary', "{u'vishal': 15, u'ram': 5, u'vishesh': 1, u'prashant': 10}")
('type of final_dictionary', <type 'dict'>)
How to remove an empty string from a list of empty strings in C#?

Firstly, set a list with empty string as elements.
List<string> myList = new List<string>() {
   " ",
   " ",
   " "
};
Now let us remove one empty element using index.
myList.RemoveAt(0);
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      List<string> myList = new List<string>() {
         " ",
         " ",
         " "
      };

      Console.Write("Initial list with empty strings...\n");
      foreach (string list in myList) {
         Console.WriteLine(list);
      }

      Console.Write("Removing an empty element from the list...\n");
      myList.RemoveAt(0);

      foreach (string list in myList) {
         Console.WriteLine(list);
      }
      Console.WriteLine("Empty List after deleting an empty element is shown above...");
   }
}
Initial list with empty strings...

Removing an empty element from the list...

Empty List after deleting an empty element is shown above...
MySQL SELECT IF statement with OR?

You can use SELECT IF statement with OR. To understand select with OR, let us create a table. The query to create a table is as follows −
mysql> create table EmployeeInformation
   -> (
   -> EmployeeId int,
   -> EmployeeName varchar(100),
   -> EmployeeStatus varchar(100)
   -> );
Query OK, 0 rows affected (0.68 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into EmployeeInformation values(1,'Sam','FullTime');
Query OK, 1 row affected (0.23 sec)

mysql> insert into EmployeeInformation values(2,'Mike','PartTime');
Query OK, 1 row affected (0.14 sec)

mysql> insert into EmployeeInformation values(3,'Bob','Intern');
Query OK, 1 row affected (0.14 sec)

mysql> insert into EmployeeInformation values(4,'Carol','FullTime');
Query OK, 1 row affected (0.16 sec)

mysql> insert into EmployeeInformation values(5,'John','FullTime');
Query OK, 1 row affected (0.19 sec)

mysql> insert into EmployeeInformation values(6,'Johnson','PartTime');
Query OK, 1 row affected (0.19 sec)

mysql> insert into EmployeeInformation values(7,'Maria','Intern');
Query OK, 1 row affected (0.12 sec)
Let us now display all records from the table using select command. The query is as follows −
mysql> select *from EmployeeInformation;
+------------+--------------+----------------+
| EmployeeId | EmployeeName | EmployeeStatus |
+------------+--------------+----------------+
|          1 | Sam          | FullTime       |
|          2 | Mike         | PartTime       |
|          3 | Bob          | Intern         |
|          4 | Carol        | FullTime       |
|          5 | John         | FullTime       |
|          6 | Johnson      | PartTime       |
|          7 | Maria        | Intern         |
+------------+--------------+----------------+
7 rows in set (0.00 sec)
Here is the query to perform SELECT IF statement with OR. In the below query, you will get only EmployeeName which has EmployeeStatus FullTime and Intern, else you will get status of the employee.
The query is as follows −
mysql> select if(EmployeeStatus='FullTime' or
EmployeeStatus='Intern',EmployeeName,EmployeeStatus) as Status from
EmployeeInformation;
+----------+
| Status   |
+----------+
| Sam      |
| PartTime |
| Bob      |
| Carol    |
| John     |
| PartTime |
| Maria    |
+----------+
7 rows in set (0.00 sec)
SAS - Linear Regression

Linear Regression is used to identify the relationship between a dependent variable and one or more independent variables.  A model of the relationship is proposed, and estimates of the parameter values are used to develop an estimated regression equation.
Various tests are then used to determine if the model is satisfactory. If it is then, the estimated regression equation can be used to predict the value of the dependent variable given values for the independent variables.  In SAS the procedure PROC REG is used to find the linear regression model between two variables.
The basic syntax for applying PROC REG in SAS is −
PROC REG DATA = dataset;
MODEL variable_1 = variable_2;

Following is the description of the parameters used −
Dataset is the name of the dataset.
Dataset is the name of the dataset.
variable_1 and variable_2  are the variable names of the dataset used in finding the correlation.
variable_1 and variable_2  are the variable names of the dataset used in finding the correlation.
The below example shows the process to find the correlation between the two variables horsepower and weight of a car by using PROC REG. In the result we see the intercept values which can be used to form the regression equation.
PROC SQL;
create table CARS1 as
SELECT invoice, horsepower, length, weight
   FROM 
   SASHELP.CARS
   WHERE make in ('Audi','BMW')
;
RUN;
proc reg data = cars1;
model horsepower = weight ;
run;

When the above code is executed, we get the following result −
The above code also gives the graphical view of various estimates of the model as shown below. Being an advanced SAS procedure it simply does not stop at giving the intercept values as the output.

    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    35 Lectures 
     2.5 hours 

 Ermin Dedic

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
Puppet - Installation

Puppet works on the client server architecture, wherein we call the server as the Puppet master and the client as the Puppet node. This setup is achieved by installing Puppet on both the client and well as on all the server machines.
For most of the platforms, Puppet can be installed via the package manager of choice. However, for few platforms it can be done by installing the tarball or RubyGems.
Factor is the only pre-requisite that does not come along with Ohai which is present in Chef.
We need to have standard set of library of any underlying OS. Remaining all the system comes along with Ruby 1.8.2 + versions. Following is the list of library items, which an OS should consist of.
base64
cgi
digest/md5
etc
fileutils
ipaddr
openssl
strscan
syslog
uri
webrick
webrick/https
xmlrpc
As discussed, the facter does not come along with the standard edition of Ruby. So, in order to get the facter in the target system one needs to install it manually from the source as the facter library is a pre-requisite of Puppet.
This package is available for multiple platforms however just to be on the safer side it can be installed using tarball, which helps in getting the latest version.
First, download the tarball from the official site of Puppet using the wget utility.
$ wget http://puppetlabs.com/downloads/facter/facter-latest.tgz  ------: 1 

Next, un-tar the tar file. Get inside the untarred directory using the CD command. Finally, install the facter using install.rb file present inside the facter directory.
$ gzip -d -c facter-latest.tgz | tar xf - -----: 2 
$ cd facter-* ------: 3 
$ sudo ruby install.rb # or become root and run install.rb -----:4 

First, install the Puppet tarball from the Puppet site using wget. Then, extract the tarball to a target location. Move inside the created directory using the CD command. Using install.rb file, install Puppet on the underlying server.
# get the latest tarball 
$ wget http://puppetlabs.com/downloads/puppet/puppet-latest.tgz -----: 1

# untar and install it 
$ gzip -d -c puppet-latest.tgz | tar xf - ----: 2 
$ cd puppet-* ------: 3 
$ sudo ruby install.rb # or become root and run install.rb -------: 4 

# Installing Facter 
$ wget http://puppetlabs.com/downloads/gems/facter-1.5.7.gem 
$ sudo gem install facter-1.5.7.gem

# Installing Puppet 
$ wget http://puppetlabs.com/downloads/gems/puppet-0.25.1.gem 
$ sudo gem install puppet-0.25.1.gem 

 Print
 Add Notes
 Bookmark this page
Constructors in Dart Programming

Constructors are methods that are used to initialize an object when it gets created. Constructors are mainly used to set the initial values for instance variables. The name of the constructor is the same as the name of the class.
Constructors are similar to instance methods but they do not have a return type.
All classes in Dart have their own default constructor, if you don't create any constructor for a class, the compiler will implicitly create a default constructor for every class by assigning the default values to the member variables.
We can create a constructor in Dart something like this −
class SomeClass {
   SomeClass(){
      // constructor body
   }
}
There are two important rules that we should keep in mind when creating a constructor in Dart, these are −
The name of the constructor should be the same name as the class name.
The name of the constructor should be the same name as the class name.
The constructor cannot have an explicit return type.
The constructor cannot have an explicit return type.
In total there are three types of constructors present in Dart, these mainly are −
Default Constructor
Default Constructor
Parameterized Constructor
Parameterized Constructor
Named Constructor
Named Constructor
A constructor with no parameter is known as the default constructor. If you don't create a constructor explicitly, the compiler will create one implicitly.
 Live Demo
class Student {
   Student(){
      print("Inside Student Constructor");
   }
}

void main(){
   Student st = new Student();
}
Inside Student Constructor
We can also have constructors that take parameters, that can later be used to initialize instance variables.
 Live Demo
class Student {
   Student(String name){
      print("Student name : ${name}");
   }
}

void main(){
   Student st = new Student("Tuts!");
}
Student name : Tuts!
In Dart, named constructors are mainly used to define multiple constructors.
 Live Demo
void main() {

   Student emp1 = new Student();
   Student emp2 = new Student.namedConst('ST001');
}

class Student{
   Student() {
      print("Inside Student Constructor");
   }

   Student.namedConst(String stCode) {
      print(stCode);
   }
}
Inside Student Constructor
ST001
How to create Dialog Box in ReactJS? - GeeksforGeeks

22 Jan, 2021
Dialogs inform users about a task and can contain critical information, require decisions, or involve multiple tasks. Material UI for React has this component available for us and it is very easy to integrate. We can create the dialog box in ReactJS using the following approach:
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';import DialogActions from '@material-ui/core/DialogActions';import DialogContent from '@material-ui/core/DialogContent';import DialogTitle from '@material-ui/core/DialogTitle';import DialogContentText from '@material-ui/core/DialogContentText';import Dialog from '@material-ui/core/Dialog';import Button from '@material-ui/core/Button';  const App = () => {  const [open, setOpen] = React.useState(false);    const handleClickOpen = () => {    setOpen(true);  };    const handleClose = () => {    setOpen(false);  };    return (    <div>      <Button variant="outlined"               color="primary" onClick={handleClickOpen}>        Open My Custom Dialog      </Button>      <Dialog open={open} onClose={handleClose}>        <DialogTitle>           Greetings from GeeksforGeeks        </DialogTitle>        <DialogContent>          <DialogContentText>            Do you do coding ?          </DialogContentText>        </DialogContent>        <DialogActions>          <Button onClick={handleClose} color="primary">           Close          </Button>          <Button onClick={handleClose} color="primary" autoFocus>           Yes          </Button>        </DialogActions>      </Dialog>    </div>  );}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
Create a Responsive Navbar using ReactJS
How to retrieve the MSI package product code using PowerShell?

You can retrieve the MSI installed packaged product code on the windows OS using PowerShell with Get-Package or Get-WmiObject command.
In this example, we will retrieve the product code of 7-zip.
Get-Package -Name '7-Zip 19.00 (x64 edition)' | fl *
You can use the tagid or mentioned properties to filter the product code.
To retrieve the package from the remote computer using the Get-Package method, use InvokeCommand.
Invoke-Command -ComputerName TestMachine -ScriptBlock{
   (Get-Package -Name '7-Zip 19.00 (x64 edition)').TagID
}
Another way to retrieve the product code is by using the WMI method as shown below.
PS C:\> $product = Get-WmiObject win32_product | where{$_.name -
eq "7-Zip 19.00 (x64 edition)"}
PS C:\> $product.IdentifyingNumber
To get the output from the remote computer, just specify the -ComputerName parameter.
$product = Get-WmiObject win32_product -ComputerName
TestMachine1, Testmachine2 | where{$_.name -eq "7-Zip 19.00 (x64 edition)"}
$product.IdentifyingNumber
Import Files and Images in ReactJS

In this article, we are going to see how to import CSS Files, images and functions defined in other folder to the main App.js file.
In React, we need to dynamically import the images from their folder.
In this example, we will define a project structure with the images and components already defined in the assets and components folder and then we are going to dynamically import them in our main App.js file.
Project Structure
App.js
import React from 'react';
import MyComponent from './components/my -component.js';
import TutorialsPoint from './assets/img.png';

const App = () => {
   return (
      <div>
      <img src={TutorialsPoint} />
      <MyComponent />
      </div>
   );
};
export default App;
my-component.js
import React from 'react';

const MyComponent = () => {
   return <div>Hii! This is the custom MyComponent</div>;
};

export default MyComponent;
This will produce the following result.
R Factors

Factors are used to categorize data. Examples of factors are:
Demography: Male/Female
Music: Rock, Pop, Classic, Jazz
Training: Strength, Stamina
To create a factor, use the factor() function 
and add a vector as argument:
Result:
[1] Jazz    Rock    Classic Classic Pop     Jazz    Rock    Jazz
Levels: Classic Jazz Pop Rock

You can see from the example above that that the factor has four levels (categories): Classic, Jazz, Pop and Rock.
To only print the levels, use the levels() function:
Result:
[1] "Classic" "Jazz"    "Pop"     "Rock"   

You can also set the levels, by adding the levels argument inside the 
factor() function:
Result:
[1] "Classic" "Jazz"    "Pop"     "Rock"    "Other"

Use the length() function to find out how many items there are in the factor:
Result:
[1] 8

To access the items in a factor, refer to the index number, using [] brackets:
Access the third item:
Result:
[1] Classic
Levels: Classic Jazz Pop Rock

To change the value of a specific item, refer to the index number:
Change the value of the third item:
Result:
[1] Pop
Levels: Classic Jazz Pop Rock

Note that you cannot change the value of a specific item if it is not already 
specified in the factor. The following example will produce an error:
Trying to change the value of the third item ("Classic") to an item that does 
not exist/not predefined ("Opera"):
Result:
Warning message:
In `[<-.factor`(`*tmp*`, 3, value = "Opera") :
  invalid factor level, NA generated

However, if you have already specified it inside the levels argument, it will work:
Change the value of the third item:
Result:
[1] Opera
Levels: Classic Jazz Pop Rock Opera

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to plot the outline of the outer edges on a Matplotlib line in Python?

To plot the outline of the outer edges on a Matplotlib in Python, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Plot x and y data points with linewidth set to 10 and 5, to get the visible outline edges.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-10, 10, 100)
y = np.sin(x)

plt.plot(x, y, lw=10, color='red')
plt.plot(x, y, lw=5, color='yellow')

plt.show()
How to create boxplot in base R without axes labels?

The boxplot can be created by using boxplot function in base R but the Y−axis labels are generated based on the vector we pass through the function. If we want to remove the axis labels then axes = FALSE argument can be used. For example, if we have a vector x then the boxplot for x without axes labels can be created by using boxplot(x,axes=FALSE).
 Live Demo
Consider the below vector x and creating boxplot −
set.seed(777)
x<−rnorm(50000,41.5,3.7)
boxplot(x)
Creating the boxplot without Y−axis labels −
boxplot(x,axes=FALSE)
Let’s have a look at another example −
 Live Demo
y<−rnorm(10,1,0.5)
boxplot(y)
Removing Y−axis labels −
boxplot(y,axes=FALSE)
We can do the same for multiple boxplots if the data is contained in a data frame.
Transactions and concurrency control - GeeksforGeeks

09 Oct, 2019
T1: read (P) ;
    read (Q) ;
    if P = 0 then Q : = Q + 1 ;
    write (Q) ;
T2: read (Q) ;
    read (P) ;
    if Q = 0 then P : = P + 1 ;
    write (P) ;
See http://www.geeksforgeeks.org/database-management-system-set-3/
2 Phase Locking (2PL) is a concurrency control method that guarantees serializability. The protocol utilizes locks, applied by a transaction to data, which may block (interpreted as signals to stop) other transactions from accessing the same data during the transaction’s life. 2PL may be lead to deadlocks that result from the mutual blocking of two or more transactions. See the following situation, neither T3 nor T4 can make progress.Timestamp-based concurrency control algorithm is a non-lock concurrency control method. In Timestamp based method, deadlock cannot occur as no transaction ever waits.
T1 can complete before T2 and T3 as there is no conflict between Write(X) of T1 and the operations in T2 and T3 which occur before Write(X) of T1 in the above diagram.T3 should can complete before T2 as the Read(Y) of T3 doesn’t conflict with Read(Y) of T2. Similarly, Write(X) of T3 doesn’t conflict with Read(Y) and Write(Y) operations of T2.Another way to solve this question is to create a dependency graph and topologically sort the dependency graph. After topologically sorting, we can see the sequence T1, T3, T2.
T1: r1(X); r1(Z); w1(X); w1(Z)
T2: r2(Y); r2(Z); w2(Z)
T3: r3(Y); r3(X); w3(Y)
S1: r1(X); r3(Y); r3(X); r2(Y); r2(Z);
    w3(Y); w2(Z); r1(Z); w1(X); w1(Z)
S2: r1(X); r3(Y); r2(Y); r3(X); r1(Z);
    r2(Z); w3(Y); w1(X); w2(Z); w1(Z) 
  1. T1 start
  2. T1 B old=12000 new=10000
  3. T1 M old=0 new=2000
  4. T1 commit
  5. T2 start
  6. T2 B old=10000 new=10500
  7. T2 commit 
read(x);  x := x – 50;  write(x);  read(y);  y := y + 50;  write(y) 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
PHP | hexdec( ) Function

07 Mar, 2018
Hexadecimal is a positional numeral system with a base of 16. It has sixteen distinct symbols, where the first nine symbols are 0–9 which represent values zero to nine, and the rest 6 symbols are A, B, C, D, E, F which represent values from ten to fifteen respectively. Since hexadecimal digit represents four binary digits, it allows a more human-friendly representation of binary-coded values and hence it is preferred over other number systems like binary and octal.
The hexdec() function in PHP converts a hexadecimal number to a decimal number.The hexdec() function converts numbers that are too large to fit into the integer type, larger values are returned as a float in that case. If hexdec() encounters any non-hexadecimal characters, it ignores them.
Syntax:
hexdec($value)
Parameters: The hexdec() function accepts a single parameter $value. It is the hexadecimal number whose decimal equivalent you want to calculate.
Return Value: The hexdec() function in PHP returns the decimal equivalent of a hexadecimal number.
Examples:
Input : hexdec("5e")
Output : 94

Input : hexdec("a")
Output : 10

Input : hexdec("f1f1")
Output : 61937

Input : hexdec("abc451")
Output : 11256913

Below program illustrate the working of hexdec() in PHP:
<?php  echo hexdec("5e") . "\n";echo hexdec("a") . "\n";echo hexdec("f1f1") . "\n";echo hexdec("abc451") . "\n";  ?>
Output:
94
10
61937
11256913

Important points to note :
It converts a hexadecimal number to its decimal equivalent.
It returns the values as float if the numbers are too large to be returned as integer type .
The hexadecimal number system is one of the most popular and widely used number system these days.
Reference:http://php.net/manual/en/function.hexdec.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
NLP | Wordlist Corpus

20 Feb, 2019
What is a corpus?A corpus can be defined as a collection of text documents. It can be thought as just a bunch of text files in a directory, often alongside many other directories of text files.
How to create wordlist corpus?
WordListCorpusReader – It is one of the simplest CorpusReader classes.
This class provides access to the files that contain list of words or one word per line
Wordlist file can be a CSV file or a txt file having one word in each line. In our wordlist filewe have added : 
geeks
for
geeks
welcomes
you
to
nlp
articles
we have added : 
geeks
for
geeks
welcomes
you
to
nlp
articles
Two arguments to give
directory path containing the files
list of filenames
Code #1 : Creating a wordlist corpus
from nltk.corpus.reader import WordListCorpusReaderx = WordListCorpusReader('.', ['C:\\Users\\dell\\Desktop\\wordlist.txt'])x.words()  x.fileids()
Output :
['geeks', 'for', 'geeks', 'welcomes', 'you', 'to', 'nlp', 'articles']

['C:\\Users\\dell\\Desktop\\wordlist.txt']

Code #2 : Accessing raw.
x.raw()  from nltk.tokenize import line_tokenizeprint ("Wordlist : ", line_tokenize(x.raw()))
Output :
'geeks\r\nfor\r\ngeeks\r\nwelcomes\r\nyou\r\nto\r\nnlp\r\narticles'

Wordlist : ['geeks', 'for', 'geeks', 'welcomes', 'you', 'to', 'nlp', 'articles']
Code #3 : Accessing Name Wordlist corpus
# Accessing pre-defined wordlistfrom nltk.corpus import names  print ("Path : ", names.fileids())  print ("\nNo. of female names : ", len(names.words('female.txt')))  print ("\nNo. of male names : ", len(names.words('male.txt')))
Output :
Path :  ['female.txt', 'male.txt']

No. of female names :  5001

No. of male names :  2943
Code #4 : Accessing English Wordlist corpus
# Accessing pre-defined wordlistfrom nltk.corpus import words  print ("File : ", words.fileids())  print ("\nNo. of female names : ", len(words.words('en-basic')))  print ("\nNo. of male names : ", len(words.words('en')))
Output :
File :  ['en', 'en-basic']

No. of female names :  850

No. of male names :  235886
Natural-language-processing
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a specific bit of a number with Arduino

Each number has a specific binary representation. For example, 8 can be represented as 0b1000, 15 can be represented as 0b1111, and so on. If you wish to read a specific bit of a number, Arduino has an inbuilt method for it.
bitRead(x, index)
where, x is the number whose bits you are reading, index is the bit to read. 0 corresponds to least significant (right-most) bit, and so on.
This function returns either 0 or 1 depending on the value of that bit in that number.
The following example will illustrate the use of this function −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   int x = 8;

   Serial.println(bitRead(x,0));
   Serial.println(bitRead(x,1));
   Serial.println(bitRead(x,2));
   Serial.println(bitRead(x,3));
   Serial.println(bitRead(x,4));
   Serial.println(bitRead(x,5));
   Serial.println(bitRead(x,6));
   Serial.println(bitRead(x,7));
}

void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
As you can see, only the bit in position 3 is 1, while all others are 0, which corresponds to the binary representation of 8: 0b00001000
How to implement GROUP by range in MySQL?

To group by range in MySQL, let us first create a table. The query to create a table is as follows
mysql> create table GroupByRangeDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > YourRangeValue int
   - > );
Query OK, 0 rows affected (0.78 sec)
Now you can insert some records in the table using insert command.
The query is as follows
mysql> insert into GroupByRangeDemo(YourRangeValue) values(1);
Query OK, 1 row affected (0.14 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(7);
Query OK, 1 row affected (0.15 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(9);
Query OK, 1 row affected (0.14 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(23);
Query OK, 1 row affected (0.13 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(33);
Query OK, 1 row affected (0.15 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(35);
Query OK, 1 row affected (0.16 sec)
mysql> insert into GroupByRangeDemo(YourRangeValue) values(1017);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from GroupByRangeDemo;
The following is the output
+----+----------------+
| Id | YourRangeValue |
+----+----------------+
|  1 |              1 |
|  2 |              7 |
|  3 |              9 |
|  4 |             23 |
|  5 |             33 |
|  6 |             35 |
|  7 |           1017 |
+----+----------------+
7 rows in set (0.04 sec)
Here is the query to group by range
mysql> select round(YourRangeValue / 10), count(YourRangeValue) from GroupByRangeDemo where YourRangeValue < 40 group by round(YourRangeValue / 10)
   - > union
   - > select '40+', count(YourRangeValue) from GroupByRangeDemo where YourRangeValue >= 40;
The following is the output
+----------------------------+-----------------------+
| round(YourRangeValue / 10) | count(YourRangeValue) |
+----------------------------+-----------------------+
| 0                          |                     1 |
| 1                          |                     2 |
| 2                          |                     1 |
| 3                          |                     1 |
| 4                          |                     1 |
| 40+                        |                     1 |
+----------------------------+-----------------------+
6 rows in set (0.08 sec)
How to change date time format in HTML5?

The date-time format can be changed by using custom HTML5 elements. If we wish to change or override existing Html tags then we can do so with the help of shadow DOM.
We can make customizable tags like −
<date-timeformatchange ></ date-timeformatchange>
Here is an example −
<date-timeformatchange format=”dd/mm/yyyy ></ date-timeformatchange>
However, E10 and older versions do not support customizable tags; however, all newer versions support customizable tags.
Demonstrating variable-length arguments in Java

A method with variable length arguments(Varargs) in Java can have zero or multiple arguments. Variable length arguments are most useful when the number of arguments to be passed to the method is not known beforehand. They also reduce the code as overloaded methods are not required.
A program that demonstrates this is given as follows:
 Live Demo
public class Demo {
   public static void Varargs(String... str) {
      System.out.println("\nNumber of arguments are: " + str.length);
      System.out.println("The argument values are: ");
      for (String s : str)
         System.out.println(s);
   }
   public static void main(String args[]) {
      Varargs("Apple", "Mango", "Pear");
      Varargs();
      Varargs("Magic");
   }
}
Number of arguments are: 3
The argument values are:
Apple
Mango
Pear

Number of arguments are: 0
The argument values are:

Number of arguments are: 1
The argument values are:
Magic
Now let us understand the above program.
The method Varargs() in class Demo has variable-length arguments of type String. This method prints the number of arguments as well as their values. A code snippet which demonstrates this is as follows:
public static void Varargs(String... str) {
   System.out.println("\nNumber of arguments are: " + str.length );
   System.out.println("The argument values are: ");
   for (String s : str)
      System.out.println(s);
}
In main() method, the method Varargs() is called with different argument lists. A code snippet which demonstrates this is as follows:
public static void main(String args[]) {
   Varargs("Apple", "MAngo", "Pear");
   Varargs();
   Varargs("Magic");
}
C# Program to implement Sleep Method Of Thread

The sleep method of the thread is used to pause the thread for a specific period.
If you want to set sleep for some seconds, then use it like the following code snippet −
int sleepfor = 2000;
Thread.Sleep(sleepfor);
You can try to run the following code to implement the sleep method of the thread.
Live Demo
using System;
using System.Threading;
namespace MyApplication {
   class ThreadCreationProgram {
      public static void CallToChildThread() {
         Console.WriteLine("Child thread starts");
         int sleepfor = 2000;
         Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);
         Thread.Sleep(sleepfor);
         Console.WriteLine("Child thread resumes");
      }
      static void Main(string[] args) {
         ThreadStart childref = new ThreadStart(CallToChildThread);
         Console.WriteLine("In Main: Creating the Child thread");
         Thread childThread = new Thread(childref);
         childThread.Start();
         Console.ReadKey();
      }
   }
}
In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 2 seconds
Child thread resumes
Compression of IPv6 address - GeeksforGeeks

28 Jun, 2021
IPv6 address is short form of IP address version 6. It is basically a 128 bit address. In IPv6 address, hexadecimal notation is preferred. There are total 8 fields in IPv6 hexadecimal notation and each field consists of 16 bits. Hence, total bits are 8 x 16 = 128 
Rules for compression: There are basically three rules for compression:  
Rule-1: When only 0 (zero) is available in a field then it is removed from the IPv6 address notation.  
 
IPv6 = FE82:1234:0:1235:1416:1A12:1B12:1C1F

After compression,
IPv6 = FE82:1234::1235:1416:1A12:1B12:1C1F 
 
 
Rule-2: When continuous 0s (zeros) are available in IPv6 address notation then all zeros are replaced by ::.  
 
IPv6 = FE82:0:0:0:0:1A12:1234:1A12

After compression,
IPv6 = FE82::1A12:1234:1A12 
 
 
Rule-3: When zeros are present in discontinuous places then at only one junction, 0s (zeros) are replaced by ::.  
 
IPv6 = 2001:1234:0:0:1A12:0:0:1A13

After compression,
IPv6 = 2001:1234::1A12:0:0:1A13
          or
     = 2001:1234:0:0:1A12::1A13 
 
 
Unspecified Address: When in hexadecimal notation of IPv6 all fields are 0. It is denoted by ::.  
:: = 0:0:0:0:0:0:0:0
Loop Back Address: When in hexadecimal notation of IPv6 all fields are 0 except the last field and last field value is 1. It is denoted by ::1.  
::1 = 0:0:0:0:0:0:0:1
 
clintra
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Data encryption standard (DES) | Set 1
Types of Network Topology
Types of Transmission Media
ACID Properties in DBMS
Normal Forms in DBMS
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Data encryption standard (DES) | Set 1
Matplotlib savefig with a legend outside the plot

To save a file with legend outside the plot, we can take the following steps −
Create x data points using numpy.
Create x data points using numpy.
Plot y=sin(x) curve using plot() method, with color=red, marker="v" and label y=sin(x).
Plot y=sin(x) curve using plot() method, with color=red, marker="v" and label y=sin(x).
Plot y=cos(x), curve using plot() method, with color=green, marker="x" and label y=cos(x).
Plot y=cos(x), curve using plot() method, with color=green, marker="x" and label y=cos(x).
To place the legend outside the plot, use bbox_to_anchor(.45, 1.15) and location="upper center".
To place the legend outside the plot, use bbox_to_anchor(.45, 1.15) and location="upper center".
To save the figure, use savefig() method.
To save the figure, use savefig() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 100)
plt.plot(x, np.sin(x), c="red", marker="v", label="y=sin(x)")
plt.plot(x, np.cos(x), c="green", marker="x", label="y=cos(x)")
plt.legend(bbox_to_anchor=(.45, 1.15), loc="upper center")
plt.savefig("legend_outside.png")
When we execute this code, it will save the following plot with the name "legend_outside.png" in the current directory.
CSS | margin-block-start Property - GeeksforGeeks

17 Feb, 2021
The margin-block-start property is used to define the logical block start margin of element. This property helps to place margin depending on the element’s writing mode, directionality, and text orientation.Syntax:  
margin-block-start: length | auto | initial | inherit;
Property values:  
length: It sets the fixed value defined in px, cm, pt. Negative values as mentioned earlier are allowed. 0px is the default value.
auto: It is used when it is desired that the browser determines the width of the left margin.
initial: It is used to set the value of the margin-left property to its default value.
inherit: It is used when it is desired that the element inherit the margin-left property of its parent as its own.
Below examples illustrate the margin-block-start property in CSS:Example 1:  
html
<!DOCTYPE html><html> <head>    <title>CSS | margin-block-start Property</title>    <style>        h1 {            color: green;        }                 div {            background-color: yellow;            width: 110px;            height: 80px;        }        .two {              margin-block-start: 20px;              background-color: purple;        }    </style></head> <body>    <center>        <h1>Geeksforgeeks</h1>        <b>CSS | margin-block-start Property</b>        <br><br>        <div class="one">GeeksforGeeks</div>        <div class="two">GFG</div>        <div class="three">GeeksforGeeks</div>    </center></body> </html>
Output:  
Example 2:  
html
<!DOCTYPE html><html> <head>    <title>CSS | margin-block-start Property</title>    <style>        h1 {            color: green;        }                 div {            background-color: yellow;            width: 110px;            height: 80px;        }        .two {            margin-block-start: auto;            writing-mode: vertical-lr;            background-color: purple;        }    </style></head> <body>    <center>        <h1>Geeksforgeeks</h1>        <b>CSS | margin-block-start Property</b>        <br><br>        <div class="one">GeeksforGeeks</div>        <div class="two">GFG</div>        <div class="three">GeeksforGeeks</div>    </center></body> </html>                   
Output:  
Supported Browsers: The browser supported by margin-block-start property are listed below:  
Google Chrome
Internet Explorer
Mozilla Firefox
 
arorakashish0911
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Technical Challenges of Mobile Computing - GeeksforGeeks

06 Jan, 2020
Mobile Computing is defined as a computing environment which is mobile and moves along with the user. There are various number of challenges that affected mobile computing and it has to overcome them. Some of the major technical challenges faced by mobile computing are:
1. Mobility
2. Wireless Medium
3. Portability 
These are explained as following below:
1. Mobility:It is the most important aspect of mobile computing, but it has to face the certain challenges which are :
Auto configuration of the system, as the environment of the system is developing continuously. Hence for every change, it has to configure itself to the new situation.
Location management is also a big objection in mobility. To manage the location, following tasks are to be performed regularly over a fixed period of time.Track user’s call.Update user’s position and data.
Track user’s call.
Update user’s position and data.
To maintain the heterogenity is also a big task as the system is keep moving in a large variation of situations
Range of spectrum.
Verification of security.
2. Wireless Medium:The transmission medium in mobile computing is wireless, therefore the following points are considered:
Various interferences occurs in the mobile computing by the different elements in the environment.
Accuracy and quantity of bandwidth should be sufficient.
Network cost is feasible.
3. Portability:This means that the communication device moves, for eg. mobile phones. The following mobile constraints are to be considered as the devices are also mobile:
Minimum number of resources are used.
Security is very less, as security risks include the processing of fake transactions, unauthorized access of data and program files, and the physical theft or damage of the device.
Restrictions of the battery.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
Multiple Access Protocols in Computer Network
Congestion Control in Computer Networks
Routing Information Protocol (RIP)
Wireless Sensor Network (WSN)
Architecture of Internet of Things (IoT)
JavaScript String replaceAll() Method - GeeksforGeeks

07 Oct, 2021
Below is an example of the String replaceAll() Method.
Javascript
<script>function gfg() {    let string = "Geeks or Geeks";    newString = string.replaceAll("or", "for");    document.write(newString);}gfg();</script>
Output:
Geeks for Geeks
The replaceAll() method returns a new string after replacing all the matches of a string with a specified string or a regular expression.
The original string is left unchanged after this operation.
Syntax:
const newString = originalString.replaceAll(regexp | substr , newSubstr | function)
 
Parameters: This method accepts certain parameters defined below:
 
regexp: It is the regular expression whose matches are replaced with the newSubstr or the value returned by the specified function.
substr: It defines the sub strings which are to replace with newSubstr or the value returned by the specified function.
newSubstr: It is the sub string that replaces all the matches of the string specified by the substr or the regular expression.
function: It is the function that is invoked to replace the matches with the regexp or substr.
 
Javascript
<script>function GFG() {    let string = "Hello, what are you doing?";    newString = string.replaceAll("Hello", "Hi");    document.write(newString);}GFG();</script>
  
Hi, what are you doing?
 
Javascript
<script>function GFG() {    const regexp = /coffee/ig;    let string = "Lets, have coffee today!";    newString = string.replaceAll(regexp, "tea");    document.write(newString);}GFG();</script>
 Output:
Lets, have tea today!
 
Supported Browser:
Chrome 85 and above
Edge 85 and above
Firefox 77 and above
Opera 71 and above
Safari 13.1 and above
ysachin2314
JavaScript-Methods
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript