code-rag-bench/online-tutorials huggingface dataset:
for loop in C

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax of a for loop in C programming language is −
for ( init; condition; increment ) {
   statement(s);
}

Here is the flow of control in a 'for' loop −
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.
After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.
#include <stdio.h>
 
int main () {

   int a;
	
   /* for loop execution */
   for( a = 10; a < 20; a = a + 1 ){
      printf("value of a: %d\n", a);
   }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

 Print
 Add Notes
 Bookmark this page
Java program to cyclically rotate an array by one.

To rotate the contents of an array cyclically −
create an empty variable. (temp)
save the last element of the array in it.
Now, starting from the nth element of the array, replace the current element with the previous element.
Store the element in temp in the 1st position.
 Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class CyclicallyRotateanArray {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the required size of the array ::");
      int size = sc.nextInt();
      int [] myArray = new int[size];
      System.out.println("Enter elements of the array");
      for(int i=0; i< size; i++){
         myArray[i] = sc.nextInt();
      }
      System.out.println("Contents of the array: "+Arrays.toString(myArray));
      int temp = myArray[size-1];
      for(int i = size-1; i>0; i--){
         myArray[i] = myArray[i-1];
      }
      myArray[0] = temp;
      System.out.println("Contents of the cycled array: "+Arrays.toString(myArray));
   }
}
Enter the required size of the array ::
5
Enter elements of the array
14
15
16
17
18
Contents of the array: [14, 15, 16, 17, 18]
Contents of the cycled array: [18, 14, 15, 16, 17]
Start Coding - Java | Practice | GeeksforGeeks

When learning a new language, we first learn to output some message. Here, we'll start with the famous Hello World message. Now, here you are given a function to complete. Don't worry about the ins and outs of functions, just add the command (System.out.print("Hello World")) to print Hello World.
Example:
Input:
No input

Output:
Hello World

Explanation:
Hello World is printed.
User Task:
Your task is to complete the function below to print hello world.
0
habdulhannan204 days ago
System.out.print("Hello World");
0
kopparapupranav5 days ago
class Geeks {
 static void printHello () {
   System.out.println("Hello World");
}
}
0
nivruttidahake301 week ago
// { Driver Code Starts//Initial Template for Java
// } Driver Code Ends//User function Template for Java
class Geeks{      // Function to print hello   static void printHello(){              // Your code here       System.out.println("Hello World");   }   }
// { Driver Code Starts.
class GfG{      public static void main(String args[]){            //Creating an Object of Class Geeks       Geeks g = new Geeks();              //Calling printHello() function of the Class Geeks       g.printHello();   }   }  // } Driver Code Ends
0
maquickstop2 weeks ago
class hello{
public void m1(){
System.out.println("Hello World");
}
}
0
vadaliyaravi22 weeks ago
class Geeks{      // Function to print hello   static void printHello(){             System.out.println("Hello World")          }   }
0
roxsonu93 weeks ago
class Geeks{      // Function to print hello   static void printHello(){              System.out.print("Hello World");          }   }
0
priyanshukumar235653 weeks ago
class Geeks{      // Function to print hello   static void printHello(){       System.out.println("Hello World");              // Your code here          }   }
0
shubhamkumar0285s3 weeks ago
class Geeks{      // Function to print hello   static void printHello(){              // Your code here       System.out.println("Hello World");   }   }
0
arpandutta5034 weeks ago
System.out.println(hello world)
0
arpandutta5034 weeks ago
System.out.println(Hello world);
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Path methods in C#

To handle File Paths in C#, use the Path methods. These methods come under System.IO Namespace.
Some of them are −
Retrieve the extension of the file using the GetExtension() method.
For example, .txt, .dat, etc.
Retrieve the name of the file using the GetFileName() method.
For example, new.txt, details.dat, etc.
Retrieve the name of the file without extension using the GetFileNameWithoutExtension() method.
For example, new, details, etc.
Let us see an example −
 Live Demo
using System.IO;
using System;
class Program {
   static void Main() {
      string myPath = "D:\\one.txt";
      string fileExtension = Path.GetExtension(myPath);
      string fileName = Path.GetFileName(myPath);
      string noExtension = Path.GetFileNameWithoutExtension(myPath);

      Console.WriteLine("File Extension: "+fileExtension);
      Console.WriteLine("Fine Name: "+fileName);
      Console.WriteLine("File Name without extension: "+noExtension);
   }
}
File Extension: .txt
Fine Name: D:\one.txt
File Name without extension: D:\one
How to use MongoDB Aggregate to sort?

Use aggregate() and within that to sort, use $sort in MongoDB. Let us create a collection with documents −
> db.demo164.insertOne({"StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e36883d9e4f06af551997c8")
}
> db.demo164.insertOne({"StudentAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3688409e4f06af551997c9")
}
> db.demo164.insertOne({"StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3688429e4f06af551997ca")
}
> db.demo164.insertOne({"StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3688439e4f06af551997cb")
}
Display all documents from a collection with the help of find() method −
> db.demo164.find();
This will produce the following output −
{ "_id" : ObjectId("5e36883d9e4f06af551997c8"), "StudentAge" : 24 }
{ "_id" : ObjectId("5e3688409e4f06af551997c9"), "StudentAge" : 25 }
{ "_id" : ObjectId("5e3688429e4f06af551997ca"), "StudentAge" : 22 }
{ "_id" : ObjectId("5e3688439e4f06af551997cb"), "StudentAge" : 21 }
Here is the query to use MongoDB aggregate() −
> db.demo164.aggregate([{ $sort : { StudentAge : -1 } }]);
This will produce the following output −
{ "_id" : ObjectId("5e3688409e4f06af551997c9"), "StudentAge" : 25 }
{ "_id" : ObjectId("5e36883d9e4f06af551997c8"), "StudentAge" : 24 }
{ "_id" : ObjectId("5e3688429e4f06af551997ca"), "StudentAge" : 22 }
{ "_id" : ObjectId("5e3688439e4f06af551997cb"), "StudentAge" : 21 }
Java if-then-else statement

In Java, if-then-else is represented by the if-else statement.
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Following is the syntax of an if...else statement −
if(Boolean_expression) {
   // Executes when the Boolean expression is true
}else {
   // Executes when the Boolean expression is false
}
If the boolean expression evaluates to true, then the if a block of code will be executed, otherwise else block of code will be executed.
Live Demo
public class Test {

   public static void main(String args[]) {
      int x = 30;

      if( x < 20 ) {
         System.out.print("This is if statement");
      }else {
         System.out.print("This is else statement");
      }
   }
}
This will produce the following result −
This is else statement
Groovy - Maps get()

Look up the key in this Map and return the corresponding value. If there is no entry in this Map for the key, then return null.
Object get(Object key)

Key − Key to search for retrieval.
The key-value pair or NULL if it does not exist.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"] 
      println(mp.get("TopicName")); 
      println(mp.get("Topic")); 
   } 
}
When we run the above program, we will get the following result −
Maps 
Null


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
How to align objects vertically when working with grids in CSS ? - GeeksforGeeks

07 Jan, 2020
CSS grid layout is one of the strongest layout of CSS. The grid layout is 2-D which means it can handle both rows and columns, unlike flexbox which is 1-D. To align objects apply CSS to the parent element which becomes the grid container and the element’s child which becomes the items in the grid.
Approach:Use the align-content property of CSS grids to vertically align objects.
Syntax:
align-content: center;

Example 1:
<!DOCTYPE html><html>  <head>    <style>        .gfg {            display: grid;            /* display is set to grid layout */            height: 400px;            align-content: center;            /* vertically aligns objects to the center */            grid-template-columns: auto auto auto;            grid-gap: 10px;            background-color: #4dd599;            /* background colour is set */            padding: 10px;        }                  .gfg > div {            background-color: rgba(255, 255, 255, 0.8);            text-align: center;            /* text inside the container is set to center */            padding: 20px 0;            font-size: 30px;        }    </style></head>  <body>      <div class="gfg">        <div>Welcome</div>        <div>to</div>        <div>Geeks</div>        <div>for</div>        <div>Geeks</div>        <div>Start</div>    </div>  </body>  </html>
Output:
Example 2:
<!DOCTYPE html><html>  <head>    <style>        .gfg {            display: grid;            /* display is set to grid layout */            height: 400px;            align-content: center;            /* vertically aligns objects to the center */            grid-template-columns: auto auto auto;            grid-gap: 10px;            background-color: #f67280;            /* background colour is set */            padding: 10px;        }                  .gfg > div {            background-color: rgba(255, 255, 255, 0.8);            text-align: center;            /* text inside the container is set to center */            padding: 20px 0;            font-size: 30px;        }    </style></head>  <body>      <div class="gfg">        <div>Explore</div>        <div>the</div>        <div>world</div>        <div>travel</div>        <div>and</div>        <div>eat</div>    </div>  </body>  </html>
Output:
CSS-Properties
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
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
How to do a batch insert in MySQL?

To do a batch insert, we need to use all column names with parenthesis, separated by ‘,’.
Let us see an example. First, we will create a table. The following is the CREATE command to create a table.
mysql> CREATE table MultipleRecordWithValues
   - > (
   - > id int,
   - > name varchar(100)
   - > );
Query OK, 0 rows affected (0.88 sec)
The following is the syntax of batch insert.
INSERT into yourTableName values(column1,column2,....N),(column1,column2,....N),(column1,column2,....N),...........N;

Applying the above syntax to insert batch records.
mysql> insert into MultipleRecordWithValues values(1,'John'),(2,'Carol'),(3,'Bob'),(4,'Smith');
Query OK, 4 rows affected (0.16 sec)
Records: 4  Duplicates: 0  Warnings: 0
Since 4 rows are affected, it implies that we have inserted records successfully. To check if all records are present in the table, use the SELECT command.
mysql> select *from MultipleRecordWithValues;
The following is the output.
+------+-------+
| id   | name  |
+------+-------+
|    1 | John  |
|    2 | Carol |
|    3 | Bob   |
|    4 | Smith |
+------+-------+
4 rows in set (0.00 sec)
How to convert JSON to Ordereddict?

24 Jan, 2021
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python.
An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict() and OrderedDict() is that: OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order and iterating it gives the values in an arbitrary order.
In this article we are going to discuss various methods to convert JSON to Ordereddict.
Method #1
By specifying the object_pairs_hook argument to JSONDecoder.
Python
# import required modulesimport jsonfrom collections import OrderedDict  # assign json filejsonFile = '{"Geeks":1, "for": 2, "geeks":3}'print(jsonFile)  # convert to Ordereddictdata = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(jsonFile)print(data)
Output:
{"Geeks":1, "for": 2, "geeks":3}
OrderedDict([(u'Geeks', 1), (u'for', 2), (u'geeks', 3)])
Method #2
By passing the JSON data as a parameter to json.loads().
Python
# import required modulesimport jsonfrom collections import OrderedDict  # assign json filejsonFile = '{"Geeks":1, "for": 2, "geeks":3}'print(jsonFile)  # convert to Ordereddictdata = json.loads(jsonFile,                   object_pairs_hook=OrderedDict)print(data)
Output:
{"Geeks":1, "for": 2, "geeks":3}
OrderedDict([(u'Geeks', 1), (u'for', 2), (u'geeks', 3)])
Picked
Python collections-module
Python-json
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python - Pandas dataframe.append()
Create a directory in Python
C++ Utility Library - make_pair Function

It constructs a pair object with its first element set to x and its second element set to y.
Following is the declaration for std::make_pair function.
template <class T1, class T2>
   pair<T1,T2> make_pair (T1 x, T2 y);
template <class T1, class T2>
   pair<V1,V2> make_pair (T1&& x, T2&& y); 
x, y − These are two values.
It returns a pair object whose elements first and second are set to x and y respectivelly.
Basic guarantee − if the construction or assignment of type T throws.
If either (or both) T1 or T2 is an rvalue reference type of a type supporting move semantics, its corresponding argument is modified.
In below example explains about std::make_pair function.
#include <utility>
#include <iostream>

int main () {
   std::pair <int,char> foo;
   std::pair <int,int> bar;

   foo = std::make_pair (1,'A');
   bar = std::make_pair (100,3);

   std::cout << "foo: " << foo.first << ", " << foo.second << '\n';
   std::cout << "bar: " << bar.first << ", " << bar.second << '\n';

   return 0;
}
Let us compile and run the above program, this will produce the following result −
foo: 1, A
bar: 100, 3

 Print
 Add Notes
 Bookmark this page
Why is indentation important in Python?

Many a times it is required to treat more than one statements in a program as a block. Different programming languages use different techniques to define scope and extent of block of statements in constructs like class, function, conditional and loop. In C and C++ for example, statements inside curly brackets are treated as a block. Python uses uniform indentation to mark block of statements.
Before beginning of block symbol : is used. First and subsequent statements in block are written by leaving additional (but uniform) whitespace (called indent) . In order to signal end of block, the whitespace is dedented. Following example illustrates the use of indents in Python:
num = int(input("enter number"))
if num%2 == 0:
   if num%3 == 0:
      print ("Divisible by 3 and 2")
   else:
      print ("divisible by 2 not divisible by 3")
else:
   if num%3 == 0:
      print ("divisible by 3 not divisible by 2")
   else:
      print  ("not Divisible by 2 not divisible by 3")
Note: It is important to ensure that all statements in a block at particular level should have same indentation.
HBase - Scan

The scan command is used to view the data in HTable. Using the scan command, you can get the table data. Its syntax is as follows:
scan ‘<table name>’ 

The following example shows how to read data from a table using the scan command. Here we are reading the emp table.
hbase(main):010:0> scan 'emp'

ROW                           COLUMN + CELL

1 column = personal data:city, timestamp = 1417521848375, value = hyderabad
 
1 column = personal data:name, timestamp = 1417521785385, value = ramu

1 column = professional data:designation, timestamp = 1417585277,value = manager

1 column = professional data:salary, timestamp = 1417521903862, value = 50000

1 row(s) in 0.0370 seconds
The complete program to scan the entire table data using java API is as follows.
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.util.Bytes;

import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;


public class ScanTable{

   public static void main(String args[]) throws IOException{

      // Instantiating Configuration class
      Configuration config = HBaseConfiguration.create();

      // Instantiating HTable class
      HTable table = new HTable(config, "emp");

      // Instantiating the Scan class
      Scan scan = new Scan();

      // Scanning the required columns
      scan.addColumn(Bytes.toBytes("personal"), Bytes.toBytes("name"));
      scan.addColumn(Bytes.toBytes("personal"), Bytes.toBytes("city"));

      // Getting the scan result
      ResultScanner scanner = table.getScanner(scan);

      // Reading values from scan result
      for (Result result = scanner.next(); result != null; result = scanner.next())

      System.out.println("Found row : " + result);
      //closing the scanner
      scanner.close();
   }
}
Compile and execute the above program as shown below.
$javac ScanTable.java
$java ScanTable 

The following should be the output:
Found row :
keyvalues={row1/personal:city/1418275612888/Put/vlen=5/mvcc=0,
row1/personal:name/1418035791555/Put/vlen=4/mvcc=0}

 Print
 Add Notes
 Bookmark this page
Single level inheritance in Java

Single Level inheritance - A class inherits properties from a single class. For example, Class B inherits Class A.
 Live Demo
class Shape {
   public void display() {
      System.out.println("Inside display");
   }
}
class Rectangle extends Shape {
   public void area() {
      System.out.println("Inside area");
   }
}
public class Tester {
   public static void main(String[] arguments) {
      Rectangle rect = new Rectangle();
      rect.display();
      rect.area();
   }
}
Inside display
Inside area
Here Rectangle class inherits Shape class and can execute two methods, display() and area() as shown.
PHP $_FILES

The global predefined variable $_FILES is an associative array containing items uploaded via HTTP POST method. Uploading a file requires HTTP POST method form with enctype attribute set to multipart/form-data.
$HTTP_POST_FILES also contains the same information, but is not a superglobal, and now been deprecated
The _FILES array contains following properties −
$_FILES['file']['name'] - The original name of the file to be uploaded.
$_FILES['file']['type'] - The mime type of the file.
$_FILES['file']['size'] - The size, in bytes, of the uploaded file.
$_FILES['file']['tmp_name'] - The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['file']['error'] - The error code associated with this file upload.
Following test.html contains a HTML form whose enctype is set to multiform/form-data. It also has an input file element which presents a button on the form for the user to select file to be uploaded.
<form action="testscript.php" method="POST" enctype="multipart/form-data">
   <input type="file" name="file">
   <input type ="submit" value="submit">
</form>
The PHP script is as follows:
<?php
echo "Filename: " . $_FILES['file']['name']."<br>";
echo "Type : " . $_FILES['file']['type'] ."<br>";
echo "Size : " . $_FILES['file']['size'] ."<br>";
echo "Temp name: " . $_FILES['file']['tmp_name'] ."<br>";
echo "Error : " . $_FILES['file']['error'] . "<br>";
?>
This will produce following result −
Filename: hello.html
Type : text/html
Size : 56
Temp name: C:\xampp\tmp\php32CE.tmp
Error : 0
How to detect integer overflow in C/C++?

The only safe way is to check for overflow before it occurs. There are some hacky ways of checking for integer overflow though. So if you're aiming for detecting overflow in unsigned int addition, you can check if the result is actually lesser than either values added. So for example,
unsigned int x, y;
unsigned int value = x + y;
bool overflow = value < x; // Alternatively "value < y" should also work
This is because if x and y are both unsigned ints, if added and they overflow, their values can't be greater than either of them as it would need to be greater than max possible unsigned int to be able to wrap around and get ahead of these values.
Another way is to try and access the Overflow flag in your CPU. Some compilers provide access to it which you could then test but this isn't standard.
AsEnumerable() in C#

To cast a specific type to its IEnumerable equivalent, use the AsEnumerable() method. It is an extension method.
The following is our array −
int[] arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Now, get the IEnumerable equivalent.
arr.AsEnumerable();
 Live Demo
using System;
using System.Linq;
class Demo {
   static void Main() {
      int[] arr = new int[5];
      arr[0] = 10;
      arr[1] = 20;
      arr[2] = 30;
      arr[3] = 40;
      arr[4] = 50;
      var res = arr.AsEnumerable();
      foreach (var ele in res) {
         Console.WriteLine(ele);
      }
   }
}
10
20
30
40
50
What is use of fluent Validation in C# and how to use in C#?

FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic
To make use of fluent validation we have to install the below package
<PackageReference Include="FluentValidation" Version="9.2.2" />
static class Program {
   static void Main (string[] args) {
      List errors = new List();

      PersonModel person = new PersonModel();
      person.FirstName = "";
      person.LastName = "S";
      person.AccountBalance = 100;
      person.DateOfBirth = DateTime.Now.Date;

      PersonValidator validator = new PersonValidator();
      ValidationResult results = validator.Validate(person);

      if (results.IsValid == false) {
         foreach (ValidationFailure failure in results.Errors) {
            errors.Add(failure.ErrorMessage);
         }
      }
      foreach (var item in errors) {
         Console.WriteLine(item);
      }
      Console.ReadLine ();
   }
}

public class PersonModel {
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public decimal AccountBalance { get; set; }
   public DateTime DateOfBirth { get; set; }
}

public class PersonValidator : AbstractValidator {
   public PersonValidator(){
      RuleFor(p => p.FirstName)
      .Cascade(CascadeMode.StopOnFirstFailure)
      .NotEmpty().WithMessage("{PropertyName} is Empty")
      .Length(2, 50).WithMessage("Length ({TotalLength}) of {PropertyName} Invalid")
      .Must(BeAValidName).WithMessage("{PropertyName} Contains Invalid Characters");

      RuleFor(p => p.LastName)
      .Cascade(CascadeMode.StopOnFirstFailure)
      .NotEmpty().WithMessage("{PropertyName} is Empty")
      .Length(2, 50).WithMessage("Length ({TotalLength}) of {PropertyName} Invalid")
      .Must(BeAValidName).WithMessage("{PropertyName} Contains Invalid Characters");

   }

   protected bool BeAValidName(string name) {
      name = name.Replace(" ", "");
      name = name.Replace("-", "");
      return name.All(Char.IsLetter);
   }
}

First Name is Empty
Length (1) of Last Name Invalid
Julia Programming - Plotting

Julia has various packages for plotting and before starting making plots, we need to first download and install some of them as follows −
(@v1.5) pkg> add Plots PyPlot GR UnicodePlots
The package Plots is a high-level plotting package, also referred to as ‘back-ends’ interfaces with other plotting packages. To start using the Plots package, type the following command −
julia> using Plots
[ Info: Precompiling Plots [91a5bcdd-55d7-5caf-9e0b-520d859cae80]
For plotting a function, we need to switch back to PyPlot back-end as follows −
  julia> pyplot()
Plots.PyPlotBackend()
Here we will be plotting the equation of Time graph which can be modeled by the following function −
julia> eq(d) = -7.65 * sind(d) + 9.87 * sind(2d + 206);
julia> plot(eq, 1:365)
sys:1: MatplotlibDeprecationWarning: Passing the fontdict parameter of _set_ticklabels() positionally is deprecated since Matplotlib 3.3; the parameter will become keyword-only two minor releases later.
sys:1: UserWarning: FixedFormatter should only be used together with FixedLocator
Everyone wants a package that helps them to draw quick plots by text rather than graphics.
Julia provides one such package called UnicodePlots which can produce the following −
scatter plots
scatter plots
line plots
line plots
bar plots
bar plots
staircase plots
staircase plots
histograms
histograms
sparsity patterns
sparsity patterns
density plots
density plots
We can add it to our Julia installation by the following command −
(@v1.5) pkg> add UnicodePlots

Once added, we can use this to plot a graph as follows:
julia> using UnicodePlots

Following Julia example generates a line chart using UnicodePlots.
julia> FirstLinePlot = lineplot([1, 2, 3, 7], [1, 2, -5, 7], title="First Line Plot", border=:dotted) First Line Plot

Following Julia example generates a density chart using UnicodePlots.
Julia> using UnicodePlots
Julia> FirstDensityPlot = densityplot(collect(1:100), randn(100), border=:dotted)
This Julia package is a visualization grammar which allows us to create visualization in a web browser window. With this package, we can −
describe data visualization in a JSON format
describe data visualization in a JSON format
generate interactive views using HTML5 Canvas or SVG
generate interactive views using HTML5 Canvas or SVG
It can produce the following −
Area plots
Area plots
Bar plots/Histograms
Bar plots/Histograms
Line plots
Line plots
Scatter plots
Scatter plots
Pie/Donut charts
Pie/Donut charts
Waterfall charts
Waterfall charts
Worldclouds
Worldclouds
We can add it to our Julia installation by following command −
(@v1.5) pkg> add VegaLite

Once added we can use this to plot a graph as follows −
julia> using VegaLite

Following Julia example generates a Pie chart using VegaLite.
julia> X = ["Monday", "Tuesday", "Wednesday", "Thrusday", "Friday","Saturday","Sunday"];

julia> Y = [11, 11, 15, 13, 12, 13, 10]
7-element Array{Int64,1}:
 11
 11
 15
 13
 12
 13
 10
 
 
julia> P = pie(X,Y)

    73 Lectures 
     4 hours 

 Lemuel Ogbunude

    24 Lectures 
     3 hours 

 Mohammad Nauman

    29 Lectures 
     2.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
isupper() function in C Language

The function isupper() is used to check that the character is uppercase or not. It returns non-zero value if successful otherwise, return zero. It is declared in “ctype.h” header file.
Here is the syntax of isupper() in C language,
int isupper(int character);
Here,
character − The character which is to be checked.
Here is an example of isupper() in C language,
 Live Demo
#include<stdio.h>
#include<ctype.h>
int main() {
   char val1 = 's';
   char val2 = 'S';
   if(isupper(val1))
   printf("The character is uppercase\n");
   else
   printf("The character is not uppercase\n");
   if(isupper(val2))
   printf("The character is uppercase\n");
   else
   printf("The character is not uppercase");
   return 0;
}
The character is not uppercase
The character is uppercase
In the above program, two variables val1 and val2 are initialized with random alphabets and by using isupper() function, these variables are checked that they are uppercase letter or not.
char val1 = 's';
char val2 = 'S';
if(isupper(val1))
printf("The character is uppercase\n");
else
printf("The character is not uppercase\n");
Python - Convert Index Dictionary to List - GeeksforGeeks

03 Jul, 2020
Sometimes, while working with Python dictionaries, we can have a problem in which we have keys mapped with values, where keys represent list index where value has to be placed. This kind of problem can have application in all data domains such as web development. Let’s discuss certain ways in which this task can be performed.
Input : test_dict = { 1 : ‘Gfg’, 3 : ‘is’, 5 : ‘Best’ }Output : [0, ‘Gfg’, 0, ‘is’, 0, ‘Best’, 0, 0, 0, 0, 0]
Input : test_dict = { 2 : ‘Gfg’, 6 : ‘Best’ }Output : [0, 0, ‘Gfg’, 0, 0, 0, ‘Best’, 0, 0, 0, 0]
Method #1 : Using list comprehension + keys()The combination of above functions can be used to solve this problem. In this, we perform the task of assigning values to list checking for index, by extracting keys of dictionary for lookup.
# Python3 code to demonstrate working of # Convert Index Dictionary to List# Using list comprehension + keys()  # initializing dictionarytest_dict = { 2 : 'Gfg', 4 : 'is', 6 : 'Best' }   # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Convert Index Dictionary to List# Using list comprehension + keys()res = [test_dict[key] if key in test_dict.keys() else 0 for key in range(10)]  # printing result print("The converted list : " + str(res)) 
The original dictionary is : {2: 'Gfg', 4: 'is', 6: 'Best'}
The converted list : [0, 0, 'Gfg', 0, 'is', 0, 'Best', 0, 0, 0]

 
Method #2 : Using list comprehension + get()The combination of above functions can be used to solve this problem. In this, we extract element using get(), so as to assign the default values harnessing default value initializing property of get().
# Python3 code to demonstrate working of # Convert Index Dictionary to List# Using list comprehension + get()  # initializing dictionarytest_dict = { 2 : 'Gfg', 4 : 'is', 6 : 'Best' }   # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Convert Index Dictionary to List# Using list comprehension + get()res = [test_dict.get(ele, 0) for ele in range(10)]  # printing result print("The converted list : " + str(res)) 
The original dictionary is : {2: 'Gfg', 4: 'is', 6: 'Best'}
The converted list : [0, 0, 'Gfg', 0, 'is', 0, 'Best', 0, 0, 0]

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Risk

Risk can be defined as the probability of an event, hazard, accident, threat or situation occurring and its undesirable consequences. It is a factor that could result in negative consequences and usually expressed as the product of impact and likelihood.
Risk = Probability of the event occurring x Impact if it did happen 
In software terminology, the risk is broadly divided into two main categories:
Supplier issues
Supplier issues
Organizational factors
Organizational factors
Technical issues
Technical issues
Below are some of the product risks occurring in a LIVE environment:
Defect Prone Software delivered
Defect Prone Software delivered
The Critical defects in the product that could cause harm to an individual (injury or death) or company
The Critical defects in the product that could cause harm to an individual (injury or death) or company
Poor software Features
Poor software Features
Inconsistent Software Features
Inconsistent Software Features

    80 Lectures 
     7.5 hours 

 Arnab Chakraborty

    10 Lectures 
     1 hours 

 Zach Miller

    17 Lectures 
     1.5 hours 

 Zach Miller

    60 Lectures 
     5 hours 

 John Shea

    99 Lectures 
     10 hours 

 Daniel IT

    62 Lectures 
     5 hours 

 GlobalETraining
 Print
 Add Notes
 Bookmark this page
Program to convert given number of days in terms of Years, Weeks and Days in C

You are given with number of days, and the task is to convert the given number of days in terms of years, weeks and days.
Let us assume the number of days in a year =365
Number of year = (number of days) / 365
Explanation-: number of years will be the quotient obtained by dividing the given number of days with 365
Number of weeks = (number of days % 365) / 7
Explanation-: number of weeks will be obtained by collecting the remainder from dividing the number of days with 365 and further dividing the result with number of days in a week which is 7.
Number of days = (number of days % 365) % 7
Explanation-: number of days will be obtained by collecting the remainder from dividing the number of days with 365 and further acquiring the remainder by dividing the partial remainder with number of days in a week which is 7.
Input-:days = 209
Output-: years = 0
   weeks = 29
   days = 6
Input-: days = 1000
Output-: years = 2
   weeks = 38
   days = 4
Start
Step 1-> declare macro for number of days as const int n=7
Step 2-> Declare function to convert number of days in terms of Years, Weeks and Days
   void find(int total_days)
      declare variables as int year, weeks, days
      Set year = total_days / 365
      Set weeks = (total_days % 365) / n
      Set days = (total_days % 365) % n
      Print year, weeks and days
Step 3-> in main()
   Declare int Total_days = 209
   Call find(Total_days)
Stop
 Live Demo
#include <stdio.h>
const int n=7 ;
//find year, week, days
void find(int total_days) {
   int year, weeks, days;
   // assuming its not a leap year
   year = total_days / 365;
   weeks = (total_days % 365) / n;
   days = (total_days % 365) % n;
   printf("years = %d",year);
   printf("\nweeks = %d", weeks);
   printf("\ndays = %d ",days);
}
int main() {
   int Total_days = 209;
   find(Total_days);
   return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
years = 0
weeks = 29
days = 6
AIML - <star> Tag

<star> Tag is used to match wild card * character(s) in <pattern> Tag.
<star index = "n"/>

n signifies the position of * within the user input in  <pattern> Tag.
Consider the following example −
<category>
   <pattern> A * is a *. </pattern>
   
   <template>
      When a <star index = "1"/> is not a <star index = "2"/>?
   </template>
   
</category>
If the user enters "A mango is a fruit." then bot will respond as "When a mango is not a fruit?"
Create star.aiml inside C > ab > bots > test > aiml and star.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding = "UTF-8"?>
   
   <category>
      <pattern>I LIKE *</pattern>
      <template>
         I too like <star/>.
      </template>
   </category>
   
   <category>
      <pattern>A * IS A *</pattern>
      <template>
         How <star index = "1"/> can not be a <star index = "2"/>?
      </template>
   </category>
   
</aiml>
0,I LIKE *,*,*,I too like <star/>.,star.aiml
0,A * IS A *,*,*,How <star index = "1"/> can not be a <star index = "2"/>?,star.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false

You will see the following output −
Human: I like mango
Robot: I too like mango.
Human: A mango is a fruit
Robot: How mango can not be a fruit? 

<star index = "1"/> is often used as <star />
 Print
 Add Notes
 Bookmark this page
Difference between Instance Variable and Class Variable - GeeksforGeeks

28 Apr, 2021
Instance Variable: It is basically a class variable without a static modifier and is usually shared by all class instances. Across different objects, these variables can have different values. They are tied to a particular object instance of the class, therefore, the contents of an instance variable are totally independent of one object instance to others.
Example:
class Taxes  
{  
   int count;  
   /*...*/  
}  
Class Variable: It is basically a static variable that can be declared anywhere at class level with static. Across different objects, these variables can have only one value. These variables are not tied to any particular object of the class, therefore, can share across all objects of the class.  
Example:
class Taxes  
{  
   static int count;  
   /*...*/  
}  
Tabular difference between Instance and Class variable:
Instance Variable
Class Variable
C-Variable Declaration and Scope
Analysis
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
3-coloring is NP Complete
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Proof that Dominant Set of a Graph is NP-Complete
Proof that SAT is NP Complete
Proof that Independent Set in Graph theory is NP Complete
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Non-Negative Matrix Factorization - GeeksforGeeks

18 Jul, 2021
Prerequisite : Low Rank Approximation</p>
Non-Negative Matrix Factorization: For a matrix A of dimensions m x n, where each element is ≥ 0, NMF can factorize it into two matrices W and H having dimensions m x k and k x n respectively and these two matrices only contain non-negative elements. Here, matrix A is defined as:
where,
A -> Original Input Matrix (Linear combination of W & H)
W -> Feature Matrix
H -> Coefficient Matrix (Weights associated with W)
k -> Low rank approximation of A (k ≤ min(m,n))
This method is widely used in performing tasks such as feature reduction in Facial Recognition and for various NLP tasks. 
Intuition:
Fig 1 : NMF Intuition 
The objective of NMF is dimensionality reduction and feature extraction. So, when we set lower dimension as k, the goal of NMF is to find two matrices W ∈ Rm×k and H ∈ Rn×k having only nonnegative elements. (As shown in Fig 1)
Therefore, by using NMF we are able to obtain factorized matrices having significantly lower dimensions than those of the product matrix. Intuitively, NMF assumes that the original input is made of a set of hidden features, represented by each column of W matrix and each column in H matrix represents the ‘coordinates of a data point’ in the matrix W. In simple terms, it contains the weights associated with matrix W.
In this, each data point that is represented as a column in A, can be approximated by an additive combination of the non-negative vectors, which are represented as columns in W.
Real-life example: 
Let us consider some real-life examples to understand the working of the NMF algorithm. Let’s take a case of image processing. 
Suppose, we have an input image, having pixels that form matrix A. Using NMF, we factorize it into two matrices, one containing the facial feature set [Matrix W] and the other containing the importance of each facial feature in the input image, i.e. the weights [Matrix H]. (As shown in Fig 2.)
Fig 2 : NMF in Image Processing
NMF is used in major applications such as image processing, text mining, spectral data analysis and many more. Currently, there is an ongoing research on NMF to increase its efficiency and robustness. Other research is being done on collective factorization, efficient update of matrices etc as well. For any doubt/query, comment below.
Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready.
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Stochastic Gradient Descent (SGD)
Support Vector Machine Algorithm
CNN | Introduction to Pooling Layer
Difference between Informed and Uninformed Search in AI
ML | Logistic Regression using Python
Singular Value Decomposition (SVD)
Principal Component Analysis with Python
Normalization vs Standardization
ML | Linear Discriminant Analysis
Difference between ANN, CNN and RNN
Java Internalization - Formatting Patterns

Followings is the use of characters in formatting patterns.
0
To display 0 if less digits are present.
#
To display digit ommitting leading zeroes.
.
Decimal separator.
,
Grouping separator.
E
Mantissa and Exponent separator for exponential formats.
;
Format separator.
-
Negative number prefix.
%
Shows number as percentage after multiplying with 100.
?
Shows number as mille after multiplying with 1000.
X
To mark character as number prefix/suffix.
'
To mark quote around special characters.
In this example, we're formatting numbers based on different patterns.
IOTester.java
import java.text.DecimalFormat;

public class I18NTester {
   public static void main(String[] args) {
      String pattern = "###.###";
      double number = 123456789.123;

      DecimalFormat numberFormat = new DecimalFormat(pattern);

      System.out.println(number);

      //pattern ###.###
      System.out.println(numberFormat.format(number));

      //pattern ###.#
      numberFormat.applyPattern("###.#");
      System.out.println(numberFormat.format(number));

      //pattern ###,###.##
      numberFormat.applyPattern("###,###.##");
      System.out.println(numberFormat.format(number));

      number = 9.34;

      //pattern 000.###
      numberFormat.applyPattern("000.##");
      System.out.println(numberFormat.format(number));           
   }
}
It will print the following result.
1.23456789123E8
1,2345,6789.12


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
PostgreSQL - COMMIT - GeeksforGeeks

01 Feb, 2021
PostgreSQL COMMIT command is used to save changes and reflect it database whenever we display the required data. For suppose we updated data in the database but we didn’t give COMMIT then the changes are not reflected in the database. To save the changes done in a transaction, we should COMMIT that transaction for sure.
Syntax :
COMMIT TRANSACTION;

(or)

COMMIT;

(or)

END TRANSACTION;
Unlike other database languages in PostgreSQL, we commit the transaction in 3 different forms which are mentioned above. Now for getting good command in the use of COMMIT command we will first create a table for examples.
CREATE TABLE BankStatements (
    customer_id serial PRIMARY KEY,
    full_name VARCHAR NOT NULL,
    balance INT
);
Now we will insert data of some customers
INSERT INTO BankStatements (
    customer_id ,
    full_name,
    balance
)
VALUES
    (1, 'Sekhar rao', 1000),
    (2, 'Abishek Yadav', 500),
    (3, 'Srinivas Goud', 1000);
Now as  the table is ready we will understand about commit
Example 1: 
We will add the data to the table in the transaction using the commit
BEGIN;

 INSERT INTO BankStatements (
     customer_id,
    full_name,
        balance

)
    VALUES(
       4, 'Priya chetri', 500
        )
;
        
COMMIT;
Output:
Example 2:
We will update the balance and display the data without committing the transaction thereafter committing it.
BEGIN;


    UPDATE BankStatements
      SET balance = balance - 500
      WHERE 
      customer_id = 1;
      
      // displaying data before
      // commmiting the transaction
      SELECT customer_id, full_name, balance
      FROM BankStatements;
      
      UPDATE BankStatements
      SET balance = balance + 500
      WHERE 
      customer_id = 2;
 



       
COMMIT;

// displaying data after
// commmiting the transaction
SELECT customer_id, full_name, balance
FROM BankStatements;
Output:
NOTE: When we try to display data from another session before committing the changes then we will get the same output that we got in the first example. 
Picked
postgreSQL-managing-database
Technical Scripter 2020
PostgreSQL
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - ROW_NUMBER Function
How to use PostgreSQL Database in Django?
PostgreSQL - Copy Table