code-rag-bench/online-tutorials huggingface dataset:
HTML DOM Input Password required property

The HTML DOM input password required property is associated with the required attribute of an <input> element. The required property is used for setting and returning if it is necessary to fill some password field or not before the form is submitted to the server. This allows the form to not submit if a password field with required attribute is left empty by the user.
Following is the syntax for −
Setting the required property −
textObject.required = true|false
Here, true represents the text field must be filled while false represents its optional to fill the field before submitting the form.
Let us look at an example for the input password required property −
<!DOCTYPE html>
<html>
<body>
<h1>Input password required property</h1>
<p>Check if the above field is mandatory to be filled or not by clicking the below button</p>
<form action="/Sample_page.php">
Password: <input type="password" id="PASS1" name=”passW” required>
<input type="submit">
</form>
<br>
<button onclick="checkReq()">CHECK</button>
<p id="Sample"></p>
<script>
   function checkReq() {
      var Req=document.getElementById("PASS1").required;
      if(Req==true)
         document.getElementById("Sample").innerHTML="The password field must be filled before submitting";
      else
         document.getElementById("Sample").innerHTML="The password field is optional and can be left blank by the user";
   }
</script>
</body>
</html>
This will produce the following output −
On clicking the CHECK button −
If the required property is set true and you click submit −
In the above example −
We have first created an input password field with id “PASS1”, name “passW” and required attribute set to true.The password field is contained inside a form with action=”Sample_page.php” which specifies where to submit the form data when clicked on the submit button.
<form action="/Sample_page.php">
Password: <input type="password" id="PASS1" name=”passW” required>
<input type="submit">
</form>
We have then created a button CHECK that will execute the checkReq() method when clicked by the user −
<button onclick="checkReq()">CHECK</button>
The checkReq() uses the getElementById() method to get the input element with type password and get its required property which in our case returns true. The returned boolean value is assigned to a variable Req and based on whether the returned value is true or false we display appropriate message in the paragraph with id “Sample” using its innerHTML property −
function checkReq() {
   var Req=document.getElementById("PASS1").required;
   if(Req==true)
      document.getElementById("Sample").innerHTML="The password field must be filled before submitting";
   else
      document.getElementById("Sample").innerHTML="The password field is optional and can be left blank by theuser";
}
MySQL Query to change lower case to upper case?

You can use in-built function UPPER() from MySQL to change a lower case to upper case. The syntax is as follows with select statement.
SELECT UPPER(‘yourStringValue’);
The following is an example showing string in lower case −
mysql> select upper('john');
Here is the output displaying string in upper case −
+---------------+
| upper('john') |
+---------------+
| JOHN          |
+---------------+
1 row in set (0.00 sec)
If you already have a table with a lower case value, then you can use the UPPER() function with update command. The syntax is as follows −
UPDATE yourTableName set yourColumnName = UPPER(yourColumnName);
To understand the above concept, let us first create a table and insert string values in lowercase. The following is the query to create a table −
mysql> create table UpperTableDemo
   −> (
   −> BookName longtext
   −> );
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using INSERT command. The query is as follows −
mysql> insert into UpperTableDemo values('introduction to c');
Query OK, 1 row affected (0.13 sec)

mysql> insert into UpperTableDemo values('introduction to java');
Query OK, 1 row affected (0.18 sec)

mysql> insert into UpperTableDemo values('introduction to python');
Query OK, 1 row affected (0.11 sec)

mysql> insert into UpperTableDemo values('introduction to c#');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from UpperTableDemo;
The following is the output −
+------------------------+
| BookName               |
+------------------------+
| introduction to c      |
| introduction to java   |
| introduction to python |
| introduction to c#     |
+------------------------+
4 rows in set (0.00 sec)
The following is the query to change the lower case to upper case −
mysql> update UpperTableDemo set BookName = upper(BookName);
Query OK, 4 rows affected (0.16 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Display all records again with updated value. The query is as follows −
mysql> select *from UpperTableDemo;
The following is the output −
+------------------------+
| BookName               |
+------------------------+
| INTRODUCTION TO C      |
| INTRODUCTION TO JAVA   |
| INTRODUCTION TO PYTHON |
| INTRODUCTION TO C#     |
+------------------------+
4 rows in set (0.00 sec)
How to use enums in Python classes?

There is a module name "enum" in python with the hep of which enum is used in python.
#import enum
import enum
# use enum in class
class Car(enum.Enum):
   suzuki = 1
   Hyundai = 2
   Dezire = 3
print ("All the enum values are : ")
for c in (Car):
   print(c)
How to convert an Image to blob using JavaScript?

Following is the code to convert an image to blob using JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Convert an Image to blob using JavaScript</h1>
<div class="sample">
<img src="https://picsum.photos/id/222/300/300.jpg" />
</div>
<button class="Btn">Convert</button>
<div class="result"></div>
<h3>Click on the above button to convert the above image to blob</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = gdocument.querySelector(".result");
   BtnEle.addEventListener("click", () => {
      fetch("https://i.picsum.photos/id/222/300/300.jpg")
      .then(function (response) {
         return response.blob();
      })
      .then(function (blob) {
         resEle.innerHTML = "blob.size = " + blob.size + "<br>";
         resEle.innerHTML += "blob.type = " + blob.type + "<br>";
      });
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘Convert’ button −
How do I write a function that takes an array of values and returns an object JavaScript?

Let’s say, we are required to write a function classifyArray() that takes in an array which
contains mixed data types and returns a Map() with the elements grouped by their data types.
For example −
// if the input array is:
const arr = ['class', 2, [7, 8, 9], {"name": "Michael"}, Symbol('foo'),
true, false, 'name', 6];
// then the output Map should be:
Map(5) {
   'string' => [ 'class', 'name' ],
   'number' => [ 2, 6 ],
   'object' => [ [ 7, 8, 9 ], { name: 'Michael' } ],
   'symbol' => [ Symbol(foo) ],
   'boolean' => [ true, false ]
}
Now let’s write the code for this function −
const arr = ['class', 2, [7, 8, 9], {"name": "Michael"}, Symbol('foo'),
true, false, 'name', 6];
const classifyArray = arr => {
   return arr.reduce((acc, val) => {
      const previousData = acc.get(typeof val);
      if(previousData){
         acc.set(typeof val, [...previousData, val]);
      }else{
         acc.set(typeof val, [val]);
      };
      return acc;
   }, new Map());
};
console.log(classifyArray(arr));
The output in the console will be −
Map(5) {
   'string' => [ 'class', 'name' ],
   'number' => [ 2, 6 ],
   'object' => [ [ 7, 8, 9 ], { name: 'Michael' } ],
   'symbol' => [ Symbol(foo) ],
   'boolean' => [ true, false ]
}
What is run time polymorphism in C#?

Runtime polymorphism has method overriding that is also known as dynamic binding or late binding. It is implemented by abstract classes and virtual functions.
Abstract classes contain abstract methods, which are implemented by the derived class.
Let us see an example of abstract classes that implements run time polymorphism −
 Live Demo
using System;

namespace PolymorphismApplication {
   abstract class Shape {
      public abstract int area();
   }

   class Rectangle: Shape {
      private int length;
      private int width;

      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }

      public override int area () {
         Console.WriteLine("Rectangle class area :");
            return (width * length);
      }
   }

   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(10, 7);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}
Rectangle class area :
Area: 70
When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.
Perl int Function

This function returns the integer element of EXPR, or $_ if omitted. The int function does not do rounding. If you need to round a value up to an integer, you should use sprintf.
Following is the simple syntax for this function −
int EXPR

int

This function returns the integer part of EXPR.
Following is the example code showing its basic usage −
#!/usr/bin/perl

$int_val = int( 6.23930 );
print"Integer value is $int_val\n";

$int_val = int( -6.23930 );
print"Integer value is $int_val\n";

$int_val = int( 10 / 3 );
print"Integer value is $int_val\n";
When above code is executed, it produces the following result −
Integer value is 6
Integer value is -6
Integer value is 3


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Python - AnchorLayout in Kivy

Kivy is an open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. It is used to develop the Android application, as well as Desktops applications. In this article we will see how to use the anchor layout positioning.
Using AnchorLayouts we place the widgets at one of the borders. The class kivy.uix.anchorlayout.AnchorLayout implements the anchor layout. Both the anchor_x parameter and anchor_y parameter can be passed the values ‘left’, ‘right’ and ‘center’. In the below program we create two buttons, attach them to two anchors and keep them in a BoxLayout.
from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
class AnchorLayoutApp(App):
   def build(self):
      # Anchor Layout1
      anchor1 = AnchorLayout(anchor_x='left', anchor_y='bottom')
      button1 = Button(text='Bottom-Left', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0))
      anchor1.add_widget(button1)
      # Anchor Layout2
      anchor2 = AnchorLayout(anchor_x='right', anchor_y='top')
      # Add anchor layouts to a box layout
      button2 = Button(text='Top-Right', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0))
      anchor2.add_widget(button2)
      # Create a box layout
      BL = BoxLayout()
      # Add both the anchor layouts to the box layout
      BL.add_widget(anchor1)
      BL.add_widget(anchor2)
      # Return the boxlayout widget
      return BL
# Run the Kivy app
if __name__ == '__main__':
   AnchorLayoutApp().run()
Running the above code gives us the following result −
C++ program to overload extraction operator

Suppose we have a Person class with two attributes first_name and the last_name. It also has two methods called get_first_name() and get_last_name() to retrieve or set first name and last name respectively. We shall have to overload the extraction operator (<<) to print the first name and the last name to print them using cout statement.
So, if the input is like a person object with first name and last name ("Sumit", "Ray"), then the output will be First name − Sumit, Last name − Ray.
To solve this, we will follow these steps −
To overload extraction operator, it should be defined outside the class
To overload extraction operator, it should be defined outside the class
The return type will be an ostream reference
The return type will be an ostream reference
The input parameters are an ostream reference variable os, and object reference variable
The input parameters are an ostream reference variable os, and object reference variable
using os extract all parts of the object in proper order
using os extract all parts of the object in proper order
return os object reference.
return os object reference.
Let us see the following implementation to get better understanding −
#include <iostream>
using namespace std;
class Person {
    private:
        string f_name;
        string l_name;
    public:
        Person(string first_name, string last_name) : f_name(first_name), l_name(last_name) {}
        string& get_first_name() {
          return f_name;
        }
        string& get_last_name() {
          return l_name;
        }
};
ostream& operator<<(ostream& os, Person& p) {
    os << "First name: " << p.get_first_name() << ", Last name: " << p.get_last_name();
    return os;
}
int main(){
   Person p("Sumit", "Ray");
   
   cout << p << ", he is our member.";
}

p("Sumit", "Ray")
First name: Sumit, Last name: Ray, he is our member.
DateSerial() and DateValue() Function in MS Access - GeeksforGeeks

25 Sep, 2020
In this article, we are going to cover DateSerial() and DateValue() Function in MS Access with examples and will cover DateSerial and DateValue query with output.
DateSerial() Function :The format of the DateSerial functions contains three parts year, month, and day values. And it returns date in a specified format. There are three parameters first one is year second one is month and the third one is the day.
Syntax :
DateSerial(year, month, day)

Parameter Values :
Example-1 :
SELECT DateSerial(2020-10, 10-1, 20-5);

Output :
9/15/2010 

Example-2 :
SELECT DateSerial(2020, 4, 20);

Output :
4/20/2020 

DateValue() Function :In MS Access, DateValue() function returns a date based on a string.In this function, a string that contains day, month, and year will be passed and it will return the date based on the string.
Note :If the year part of the string is not given then it will take the current year.
Syntax :
DateValue(string_date)

Parameter Values :
Example-1 :
SELECT DateValue("May 12, 2010");

Output :
5/12/2010

Example-2 :
SELECT DateValue("July 10");

Output :
7/10/2020 

DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Alter Multiple Columns at Once in SQL Server?
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL | Subquery
SQL | Date functions
SQL Query for Matching Multiple Values in the Same Column
SQL Query to Convert VARCHAR to INT
SQL | DROP, TRUNCATE
Probability - GeeksforGeeks

21 Jan, 2014
Solution set: { 6, (1,5), (1,6) ......}
                  i.e. P(6 appeared on first throw) +
                       P(1 appeared on first throw and 5 appeared on second throw) +
                        P(1 appeared on first throw and 6 appeared on second throw) + ....................
                      = 1/6 + (1/6)(1/6) + (1/6)(1/6) + .....
                      = 1/6 + 9/36
                      = 5/12.Viewpoint 2:
P(......) =   P(6 came on first throw) +  P(sum>= 6 and 1,2,3 appeared in first throw)
          =      1/6                                +                 ????
P(1,2,3 appeared in first throw) = 1/2                                                   //P(E1)
P(sum >= 6 | 1,2,3 appeared in first throw) = 9/18                             //P(E2 | E1)
// Our new sample space is:  { (1,1), (1,2), (1,3), (1,4), (1,5), (1,6)
                                                 (2,1), (2,2), (2,3), (2,4), (2,5), (2,6)
                                                (3,1), (3,2), (3,3), (3,4), (3,5), (3,6) }
// 9 favorable cases: {(1,5), (1,6), (2,4), (2,5), (2,6), (3,3), (3,4), (3,5), (3,6) }
P(sum>= 6 and 1,2,3 appeared in first throw) = (1/2)(9/18)              //P(E2 ∩ E1) = P(E1)P(E2|E1)
P(what we are looking for) = 1/6 + 9/36     = 5/12
Correct Answer: B
A computer can be declared faulty in two cases 
1) It is actually faulty and correctly declared so (p*q)
2) Not faulty and incorrectly declared (1-p)*(1-q). 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments

Old Comments

C# Program to Check Given Directory Exists or not
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Show all columns of Pandas DataFrame in Jupyter Notebook
How to split a Dataset into Train and Test Sets using Python
How to check if a set contains an element in Python?

Angular Material Toolbar Component
How to write Pandas DataFrame as TSV using Python?
How to Read Text Files with Pandas?
Must Do Coding Questions for Product Based Companies
How to Conditionally Remove Rows in R DataFrame?
How to customize X-axis ticks in Matplotlib?

To customize X-axis ticks in Matplotlib, we can change the ticks length and width.
Set the figure size and adjust the padding between and around the subplots.
Create lists for height, bars and y_pos data points.
Make a bar plot using bar() method.
To customize X-axis ticks, we can use tick_params() method, with color=red, direction=outward, length=7, and width=2.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

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

height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(bars))

plt.bar(y_pos, height, color='yellow')
plt.tick_params(axis='x', colors='red', direction='out', length=7, width=2)

plt.show()
A hidden gem: df.select_dtypes(). A micro-post about a Pandas function... | by Patrick Coffey | Towards Data Science

How many times have you gone to feed a pandas DataFrame into a utility function form another library and it fails due to there being object columns. Maybe it was a graph from seaborn? (we’re looking at you sns.clustermaps()).
>>> sns.clustermap(        df,         method='ward',         cmap="YlGnBu",         standard_scale=1    )TypeError: unsupported operand type(s) for -: 'str' and 'str'
So, I build a list of all the data types of my columns and filter those non numeric columns out, and pass that resulting data frame into the function that only expected numeric columns.
>>> numeric_cols = [        col         for col, dtype         in df.dtypes.items()         if dtype=='float64'    ]>>> print(numeric_cols)['col1', 'col2']>>> sns.clustermap(        df[numeric_cols],         method='ward',         cmap="YlGnBu",         standard_scale=1    )
As I was investigating some data relating to gene expressions in yeasts yesterday, it got me thinking. There has to be a better way. This concept of filtering a DataFrame’s columns by datatype should be common enough to be a one-liner! Well, it turns out it is, and even though I thought I had crawled to documentation enough times to be across the pandas API, it turns out there’s always a new hidden gem!
Pandas DataFrames have a built in method called select_dtypes() which does exactly what I wanted. And rewriting the above code to use this new (to me) function looks like the following (notice select_dtypes() takes a list, you can filter for multiple data types!):
>>> sns.clustermap(        df.select_dtypes(['number']),         method='ward',         cmap="YlGnBu",         standard_scale=1    )
I’m sure most of you are already well across this since (I did a git blame on the pandas git repo to see when it was added: 2014 🤦). Anyway, I hope maybe someone will find this as helpful as I have. Happy coding!
Python - HTTP Response

The http or Hyper Text Transfer Protocol works on client server model. Usually the web browser is the client and the computer hosting the website is the 
server. Upon receiving a request from client the server generates a response and sends it back to the client in certain format.
After receiving and interpreting a request message, a server responds with an HTTP response message:

A Status-line
Zero or more header (General|Response|Entity) fields followed by CRLF
An empty line (i.e., a line with nothing preceding the CRLF) 
indicating the end of the header fields
Optionally a message-body

A Status-line
Zero or more header (General|Response|Entity) fields followed by CRLF
An empty line (i.e., a line with nothing preceding the CRLF) 
indicating the end of the header fields
Optionally a message-body
The following sections explain each of the entities used in an HTTP response message.
A Status-Line consists of the protocol version followed by a numeric status code and its associated textual phrase. The elements are separated by space SP characters.
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

A server supporting HTTP version 1.1 will return the following version information:
HTTP-Version = HTTP/1.1

The Status-Code element is a 3-digit integer where first digit of the Status-Code defines the class of response and the last two digits do not have any categorization role. There are 5 values for the first digit:
 It means the request was received and the process is continuing.
 It means  the action was successfully received, understood, and accepted.
 It means further action must be taken in order to complete the request.
 It means the request contains incorrect syntax or cannot be fulfilled.
 It means the server failed to fulfill an apparently valid request.
HTTP status codes are extensible and HTTP applications are not required to understand the meaning of all registered status codes.
In the below python program we use the urllib3 module to make a http GET request and receive the response containing the data. It also provides the
response code which is also managed by the functions in the module. The PoolManager object handles all of the details of connection pooling and also handles the thread safety.
import urllib3
http = urllib3.PoolManager()

resp = http.request('GET', 'http://tutorialspoint.com/robots.txt')
print resp.data

# get the status of the response
print resp.status
When we run the above program, we get the following output −
User-agent: *
Disallow: /tmp
Disallow: /logs
Disallow: /rate/*
Disallow: /cgi-bin/*
Disallow: /videotutorials/video_course_view.php?*
Disallow: /videotutorials/course_view.php?*
Disallow: /videos/*
Disallow: /*/*_question_bank/*
Disallow: //*/*/*/*/src/*

200


    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
Node.js console.timeStamp() Method - GeeksforGeeks

06 Sep, 2020
The console module provides a simple debugging console that is provided by web browsers which export two specific components:
A Console class that can be used to write to any Node.js stream. Example: console.log(), console.error(), etc.
A global console that can be used without importing console. Example: process.stdout, process.stderr, etc.
The console.timeStamp() (Added in v8.0.0) method is an inbuilt application programming interface of the ‘console‘ module which does not display anything unless used in the inspector. This method adds an event with the label ‘label‘ to the Timeline panel of the inspector.
Note: The global console methods are neither consistently synchronous nor consistently asynchronous.
Syntax:
console.timeStamp([label])
Parameters: This function accepts a single parameter as mentioned above and described below:
label <string>: It accepts the label name that is further to be used in the inspector.
Return Value: It doesn’t print anything in console instead, prints timestamp at the call in Inspector.
The Below examples illustrate the use of console.timeStamp() method in Node.js.
Example 1:   Filename: index.js
// Node.js program to demonstrate the // console.timeStamp() Method  // Starting newProfile() console profileconsole.profile("Hello()");  // Printing timestampconsole.timeStamp("Hello()");  // Finishing profileconsole.profileEnd("Hello()");
Run index.js file using the following command:
node index.js
Output in Console:
*Doesn’t print anything in Console...
Output in Inspector(edge):
Example 2:   Filename: index.js
// Node.js program to demonstrate the // console.timeStamp() Method  // Starting Hello() console profileconsole.profile("Hello()");  // Printing timeStampconsole.timeStamp("Hello()");  // Performing some actionfor(var i=0; i<1; i++) {  console.log("doing some task...");}  // Finishing profileconsole.profileEnd("Hello()");  // Printing timeStamp againconsole.timeStamp("Hello()");
Run index.js file using the following command:
node index.js
Output in Console:
Doing some task...
Output in Inspector (edge):
Reference: https://nodejs.org/api/console.html#console_console_timestamp_label
Node.js-console-module
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Node.js Event Loop
Mongoose Populate() Method
Mongoose find() Function
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
MySQL increment a database field by 1?

You can increment a database using update command. The syntax is as follows −
UPDATE yourTableName
set yourColumnName=yourColumnName+1
where condition;
To understand the above syntax, let us first create a table. The query to create a table is as follows −
mysql> create table IncrementBy1
   -> (
   -> Id int,
   -> Name varchar(100),
   -> CounterLogin int
   -> );
Query OK, 0 rows affected (0.63 sec)
Insert some records using insert command. The query to insert records in the table is as follows −
mysql> insert into IncrementBy1 values(100,'John',30);
Query OK, 1 row affected (0.17 sec)

mysql> insert into IncrementBy1 values(101,'Carol',50);
Query OK, 1 row affected (0.15 sec)

mysql> insert into IncrementBy1 values(102,'Bob',89);
Query OK, 1 row affected (0.25 sec)

mysql> insert into IncrementBy1 values(103,'Mike',99);
Query OK, 1 row affected (0.18 sec)

mysql> insert into IncrementBy1 values(104,'Sam',199);
Query OK, 1 row affected (0.36 sec)

mysql> insert into IncrementBy1 values(105,'Tom',999);
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from IncrementBy1;
+------+-------+--------------+
| Id   | Name  | CounterLogin |
+------+-------+--------------+
|  100 | John  |           30 |
|  101 | Carol |           50 |
|  102 | Bob   |           89 |
|  103 | Mike  |           99 |
|  104 | Sam   |          199 |
|  105 | Tom   |          999 |
+------+-------+--------------+
6 rows in set (0.00 sec)
Here is the query that increments the database field by 1 −
mysql> update IncrementBy1
   -> set CounterLogin=CounterLogin+1
   -> where Id=105;
Query OK, 1 row affected (0.45 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Now you can check the particular record is incremented or not. The value 999 has been incremented with 1 since we are incrementing the value where Id=105 as shown above.
The following is the query to check the record −
mysql> select *from IncrementBy1 where Id=105;
+------+------+--------------+
| Id   | Name | CounterLogin |
+------+------+--------------+
|  105 | Tom  | 1        000 |
+------+------+--------------+
1 row in set (0.00 sec)
VBA - While Wend Loops

In a While...Wend loop, if the condition is True, all the statements are executed until the Wend keyword is encountered.
If the condition is false, the loop is exited and the control jumps to the very next statement after the Wend keyword.
Following is the syntax of a While..Wend loop in VBA.
While condition(s)
   [statements 1]
   [statements 2]
   ...
   [statements n]
Wend

Private Sub Constant_demo_Click()
   Dim Counter :  Counter = 10   
   
   While Counter < 15     ' Test value of Counter.
      Counter = Counter + 1   ' Increment Counter.
      msgbox "The Current Value of the Counter is : " & Counter
   Wend   ' While loop exits if Counter Value becomes 15.
End Sub   
When the above code is executed, it prints the following in a message box.
The Current Value of the Counter is : 11 

The Current Value of the Counter is : 12 

The Current Value of the Counter is : 13 

The Current Value of the Counter is : 14 

The Current Value of the Counter is : 15


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Check if a file exists in Java


The java.io.File class provides useful methods on file. This example shows how to check a file existence by using the file.exists() method of File class.
import java.io.File;

public class Main {
   public static void main(String[] args) {
      File file = new File("C:/java.txt");
      System.out.println(file.exists());
   }
}
The above code sample will produce the following result (if the file "java.txt" exists in 'C' drive).
true
The following is another simple example of the file exist or not in java.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintpWriter;

import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class fileexist {
   public static void main(String[] args) throws IOException {
      File f = new File(System.getProperty("user.dir")+"/folder/file.txt");
      System.out.println(f.exists());

      if(!f.getParentFile().exists()) {
          f.getParentFile().mkdirs();
      }        

      if(!f.exists()) {
         try {
            f.createNewFile();
         } catch (Exception e) {
            e.printStackTrace();
         }        
      }

      try {
         File dir = new File(f.getParentFile(), f.getName());
         PrintpWriter pWriter = new PrintpWriter(dir);
         pWriter.print("writing anything...");
         pWriter.close();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      }    
   }
}
The above code sample will produce the following result (if the file "java.txt" exists in 'C' drive).
true
Finding the length of string in R programming - nchar() method - GeeksforGeeks

25 Oct, 2021
nchar() method in R Programming Language is used to get the length of a character in a string object.
Syntax: nchar(string)
Where: String is object.
Return: Returns the length of a string. 
In this example, we are going to see how to get the length of a string object using nchar() method.
R
# R program to calculate length of string # Given Stringgfg < - "Geeks For Geeks" # Using nchar() methodanswer < - nchar(gfg) print(answer)
Output:
[1] 15
In this example, we will get the length of the vector using nchar() method.
R
# R program to get length of Character Vectors # by default numeric values# are converted into charactersv1 <- c('geeks', '2', 'hello', 57) # Displaying type of vectortypeof(v1) nchar(v1)
Output:
'character'
5 1 5 2
The nchar() function provides an optional argument called keepNA, it can help when dealing with NA values.
R
# R program to create Character Vectors # by default numeric values# are converted into charactersv1 <- c(NULL, '2', 'hello', NA) nchar(v1, keepNA = FALSE)
Output:
1 5 2
In the above example, the first element is NULL then it returns nothing and the last element NA returns 2 because we keep keepNA = FALSE. If we pass keepNA = TRUE, then see the following output:
R
# R program to create Character Vectors # by default numeric values# are converted into charactersv1 <- c('', NULL, 'hello', NA) nchar(v1, keepNA = TRUE)
Output:
0 5 <NA>
kumar_satyam
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
What are reference data types in C#?

The reference data type in C# does not have the actual data stored in a variable, but they contain a reference to the variables.
In C#, the following are the built-in reference types −
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types.
object ob;
ob = 250; // boxing
Store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time.
dynamic d = 100;

The String Type allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type.
String val = "Welcome!";
What is header() function in PHP?

The header() function is an predefined PHP native function.With header() HTTP functions we can control data sent to the client or browser by the Web server before some other output has been sent.
The header function sets the headers for an HTTP Response given by the server. We can do all sorts of things using the header function in PHP like Change page location, set timezone, set caching control, etc...
Some of the important uses of the header() in PHP are listed below:
It is used to redirect a from one web page to another web page in PHP.
header('Location:give your url here');
PHP defaults to sending Content-Type:text/html.If we want to change the Content-Type, we can achieve that with the header() function.
Generated PDF file :header('Content-Type: application/pdf');
Return response in json format:header('Content-Type: application/pdf');.
header("HTTP/1.0 404 Not Found");
The below example helps to prevent caching by sending header information which overrides browser setting to not-cache.
header("Cache-Control: no-cache, must-revalidate");
How to ignore the null and empty fields using the Jackson library in Java?


The Jackson is a library for Java and it has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. The Jackson library provides @JsonInclude annotation that controls the serialization of a class as a whole or its individual fields based on their values during serialization.
The @JsonInclude annotation contains below two values
Include.NON_NULL: Indicates that only properties with not null values will be included in JSON.
Include.NON_EMPTY: Indicates that only properties that are not empty will be included in JSON
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
public class IgnoreNullAndEmptyFieldTest {
   public static void main(String[] args) throws JsonProcessingException {
      ObjectMapper mapper = new ObjectMapper();
      mapper.enable(SerializationFeature.INDENT_OUTPUT);
      Employee employee = new Employee(115, null, ""); // passing null and empty fields
      String result = mapper.writeValueAsString(employee);
      System.out.println(result);
   }
}
// Employee class
class Employee {
   private int id;
   @JsonInclude(Include.NON_NULL)
   private String firstName;
   @JsonInclude(Include.NON_EMPTY)
   private String lastName;
   public Employee(int id, String firstName, String lastName) {
      super();
      this.id = id;
      this.firstName = firstName;
      this.lastName = lastName;
   }
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
   return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
}
{
 "id" : 115
}
Add the slug field inside Django Model

In this tutorial, we are going to learn about the SlugField in Django.
SlugField is a way to generate a URL using the data which we already have. You can generate URL using your title of the post or page. Let's see one detailed example.
Let's say we have an article with name This is from Tutorialspoint with id = 5. Then we can have URL as www.tutorialspoint.com/posts/5/. It's difficult for the content writers to recognize the article with the previous URL. But, if you have a URL like www.tutorialspoint.com/this-isfrom-tutorialspoint, then it's easy for us to identify the piece. So, SlugField is used to generate those types of URLs'.
Let's see the code of our post model. Compare your model with the following model.
CHOICES = (
   ('draft', 'Draft'),
   ('published', 'Published'),
)
class Article(models.Model):
   title = models.CharField(max_length = 250)
   slug = models.SlugField(max_length = 250, null = True, blank = True)
   text = models.TextField()
   published_on = models.DateTimeField(auto_now_add = True)
   updated_time = models.DateTimeField(auto_now = True)
   status = models.CharField(max_length = 10, choices = CHOICES, default ='draft')
class Meta:
   ordering = ('_Published_At', )
   def __str__(self):
return self.title
Now, we will add SlugField to our project. So, it automatically generates the URLs according the title.
Create a file called util.py in the project level directory. We have to generate URL every time invoke the Post model. To achieve that, we need signals.
import string
   from django.utils.text import slugify
   def get_random_string(size = 10, chars = string.ascii_lowercase + string.digits
   return ''.join(random.choice(chars) for _ in range(size))
def get_slug(instance, slug = None):
   if slug is not None:
      slug_two = slug
   else:
      slug_two = slugify(instance.title)
   Klass = instance.__class__
   is_exists = Klass.objects.filter(slug_two = slug_two).exists()
   if is_exists:
      slug_two = "{slug_two}-{random_string}".format(slug_two = slug_two, ran
      string = get_random_string(size = 5))
   return get_slug(instance, slug = slug)
return slug_two
Add the following code at the end of the file models.py.
def pre_save_receiver(sender, instance, *args, **kwargs):
if not instance.slug_two:
instance.slug_two = get_slug(instance)
pre_save.connect(pre_save_receiver, sender = Article)
In the urls.py edit the path like path('posts/', post). Edit the views.py according to the code.
def article(request, slug):
obj = Article.objects.filter(slug__iexact = slug)
   if obj.exists():
      obj = obj.first()
   else:
      return HttpResponse('Article Not Found')
context = {
   'article': obj
}
return render(request, 'posts/post.html', context)
Matrix creation of n*n in Python

When it is required to create a matrix of dimension n * n, a list comprehension is used.
Below is a demonstration of the same −
 Live Demo
N = 4
print("The value of N is ")
print(N)

my_result = [list(range(1 + N * i, 1 + N * (i + 1)))
   for i in range(N)]

print("The matrix of dimension N * 0 is :")
print(my_result)
The value of N is
4
The matrix of dimension N * 0 is :
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
The value of N is predefined.
The value of N is predefined.
It is displayed on the console.
It is displayed on the console.
It tells about the dimensions of the matrix.
It tells about the dimensions of the matrix.
The number is iterated over, and is converted into a list.
The number is iterated over, and is converted into a list.
This is assigned to a variable.
This is assigned to a variable.
It is displayed on the console.
It is displayed on the console.
map equal_range() in C++ STL - GeeksforGeeks

05 Mar, 2021
The map::equal_range() is a built-in function in C++ STL which returns a pair of iterators. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. Since the map container only contains unique key, hence the first iterator in the pair returned thus points to the element and the second iterator in the pair points to the next key which comes after key K. If there are no matches with key K and the key K is greater than largest key , the range returned is of length 1 with both iterators pointing to the an element which has a key denoting the size of map and elements as 0. Otherwise the lower bound and the upper bound points to the element just greater than the key K.Syntax: 
iterator map_name.equal_range(key)
Parameters: This function accepts a single mandatory parameter key which specifies the element whose range in the container is to be returned. Return Value: The function returns a pair of iterators as explained above.Below programs illustrate the above method: Program 1: 
CPP
// C++ program to illustrate the// map::equal_range() function#include <bits/stdc++.h>using namespace std; int main(){     // initialize container    map<int, int> mp;     // insert elements in random order    mp.insert({ 4, 30 });    mp.insert({ 1, 40 });    mp.insert({ 6, 60 });     pair<map<int, int>::iterator,         map<int, int>::iterator>        it;     // iterator of pairs    it = mp.equal_range(1);    cout << "The lower bound is "         << it.first->first         << ":" << it.first->second;     cout << "\nThe upper bound is "         << it.second->first         << ":" << it.second->second;     return 0;}
The lower bound is 1:40
The upper bound is 4:30
 
Program 2:  
CPP
// C++ program to illustrate the// map::equal_range() function#include <bits/stdc++.h>using namespace std; int main(){     // initialize container    map<int, int> mp;     // insert elements in random order    mp.insert({ 4, 30 });    mp.insert({ 1, 40 });    mp.insert({ 6, 60 });     pair<map<int, int>::iterator,         map<int, int>::iterator>        it;     // iterator of pairs    it = mp.equal_range(10);    cout << "The lower bound is "         << it.first->first << ":"         << it.first->second;     cout << "\nThe upper bound is "         << it.second->first         << ":" << it.second->second;     return 0;}
The lower bound is 3:0
The upper bound is 3:0
 
aryanrawlani007
gorangshrm3
CPP-Functions
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Friend class and function in C++
Polymorphism in C++
List in C++ Standard Template Library (STL)
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
Queue in C++ Standard Template Library (STL)
new and delete operators in C++ for dynamic memory
Destructors in C++
How to deserialize a JSON string using @JsonCreator annotation in Java?

The @JsonProperty annotation can be used to indicate the property name in JSON. This annotation can be used for a constructor or factory method. The @JsonCreator annotation is useful in situations where the @JsonSetter annotation cannot be used. For instance, immutable objects do not have any setter methods, so they need their initial values injected into the constructor.
import com.fasterxml.jackson.annotation.*;
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
public class JsonCreatorTest1 {
   public static void main(String[] args) throws IOException {
      ObjectMapper om = new ObjectMapper();
      String jsonString = "{\"id\":\"101\", \"fullname\":\"Ravi Chandra\", \"location\":\"Pune\"}";
      System.out.println("JSON: " + jsonString);
      Customer customer = om.readValue(jsonString, Customer.class);
      System.out.println(customer);
   }
}
// Customer class
class Customer {
   private String id;
   private String name;
   private String address;
   public Customer() {
   }
   @JsonCreator
   public Customer(
      @JsonProperty("id") String id,
      @JsonProperty("fullname") String name,  
      @JsonProperty("location") String address) {
      this.id = id;
      this.name = name;
      this.address = address;
   }
   @Override
   public String toString() {
      return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
   }
}
JSON: {"id":"101", "fullname":"Ravi Chandra", "location":"Pune"}
Customer [id=101, name=Ravi Chandra, address=Pune]
import com.fasterxml.jackson.annotation.*;
import java.io.IOException;
import com.fasterxml.jackson.databind.*;
public class JsonCreatorTest2 {
   public static void main(String[] args) throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = "{\"id\":\"102\", \"fullname\":\"Raja Ramesh\",          \"location\":\"Hyderabad\"}";
      System.out.println("JSON: " + jsonString);
      Customer customer = mapper.readValue(jsonString, Customer.class);
      System.out.println(customer);
   }
}
// Customer class
class Customer {
   private String id;
   private String name;
   private String address;
   public Customer() {
   }
   @JsonCreator
   public static Customer createCustomer(
      @JsonProperty("id") String id,
      @JsonProperty("fullname") String name,
   @JsonProperty("location") String address) {
      Customer customer = new Customer();
      customer.id = id;
      customer.name = name;
      customer.address = address;
      return customer;
   }
   @Override
   public String toString() {
         return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
   }
}
JSON: {"id":"101", "fullname":"Raja Ramesh", "location":"Hyderabad"}
Customer [id=102, name=Raja Ramesh, address=Hyderabad]