code-rag-bench/online-tutorials huggingface dataset:
PySpark - StorageLevel

StorageLevel decides how RDD should be stored. In Apache Spark, StorageLevel decides whether RDD should be stored in the memory or should it be stored over the disk, or both. It also decides whether to serialize RDD and whether to replicate RDD partitions.
The following code block has the class definition of a StorageLevel −
class pyspark.StorageLevel(useDisk, useMemory, useOffHeap, deserialized, replication = 1)

Now, to decide the storage of RDD, there are different storage levels, which are given below −
DISK_ONLY = StorageLevel(True, False, False, False, 1)
DISK_ONLY = StorageLevel(True, False, False, False, 1)
DISK_ONLY_2 = StorageLevel(True, False, False, False, 2)
DISK_ONLY_2 = StorageLevel(True, False, False, False, 2)
MEMORY_AND_DISK = StorageLevel(True, True, False, False, 1)
MEMORY_AND_DISK = StorageLevel(True, True, False, False, 1)
MEMORY_AND_DISK_2 = StorageLevel(True, True, False, False, 2)
MEMORY_AND_DISK_2 = StorageLevel(True, True, False, False, 2)
MEMORY_AND_DISK_SER = StorageLevel(True, True, False, False, 1)
MEMORY_AND_DISK_SER = StorageLevel(True, True, False, False, 1)
MEMORY_AND_DISK_SER_2 = StorageLevel(True, True, False, False, 2)
MEMORY_AND_DISK_SER_2 = StorageLevel(True, True, False, False, 2)
MEMORY_ONLY = StorageLevel(False, True, False, False, 1)
MEMORY_ONLY = StorageLevel(False, True, False, False, 1)
MEMORY_ONLY_2 = StorageLevel(False, True, False, False, 2)
MEMORY_ONLY_2 = StorageLevel(False, True, False, False, 2)
MEMORY_ONLY_SER = StorageLevel(False, True, False, False, 1)
MEMORY_ONLY_SER = StorageLevel(False, True, False, False, 1)
MEMORY_ONLY_SER_2 = StorageLevel(False, True, False, False, 2)
MEMORY_ONLY_SER_2 = StorageLevel(False, True, False, False, 2)
OFF_HEAP = StorageLevel(True, True, True, False, 1)
OFF_HEAP = StorageLevel(True, True, True, False, 1)
Let us consider the following example of StorageLevel, where we use the storage level MEMORY_AND_DISK_2, which means RDD partitions will have replication of 2.
------------------------------------storagelevel.py-------------------------------------
from pyspark import SparkContext
import pyspark
sc = SparkContext (
   "local", 
   "storagelevel app"
)
rdd1 = sc.parallelize([1,2])
rdd1.persist( pyspark.StorageLevel.MEMORY_AND_DISK_2 )
rdd1.getStorageLevel()
print(rdd1.getStorageLevel())
------------------------------------storagelevel.py-------------------------------------

Command − The command is as follows −
$SPARK_HOME/bin/spark-submit storagelevel.py

Output − The output for the above command is given below −
Disk Memory Serialized 2x Replicated

 Print
 Add Notes
 Bookmark this page
How to delete multiple files in a directory in Python?

You can delete a single file or a single empty folder with functions in the os module.
For example, if you want to delete a file my_file.txt,
>>> import os
>>> os.remove('my_file.txt')
The argument to os.remove must be absolute or relative path.
To delete multiple files, just loop over your list of files and use the above function. If you want to delete a folder containing all files you want to remove, you can remove the folder as follows:
>>> import shutil
>>> shutil.rmtree('my_folder')
You can also use regex to delete the files matching a pattern. For example,
import os, re, os.path
pattern = "^your_regex_here$"
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
    for file in filter(lambda x: re.match(pattern, x), files):
        os.remove(os.path.join(root, file))
Convert VARCHAR data to MySQL date format?

To convert VARCHAR data to date format, you can use STR_TO_DATE() −
mysql> create table DemoTable1989
   (
   DueDate varchar(20)
   );
Query OK, 0 rows affected (0.91 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1989 values('31/01/2015');
Query OK, 1 row affected (0.52 sec)
mysql> insert into DemoTable1989 values('01/12/2018');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1989 values('25/10/2019');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1989;
This will produce the following output −
+------------+
| DueDate    |
+------------+
| 31/01/2015 |
| 01/12/2018 |
| 25/10/2019 |
+------------+
3 rows in set (0.00 sec)
Here is the query to convert date data into MySQL date format:
mysql> select str_to_date(DueDate,'%d/%m/%Y') as MySQLDateFormat from DemoTable1989;
This will produce the following output −
+-----------------+
| MySQLDateFormat |
+-----------------+
| 2015-01-31      |
| 2018-12-01      |
| 2019-10-25      |
+-----------------+
3 rows in set (0.05 sec)
MomentJS - Day of year

This method will take care of getting and setting the day of year. The range given is 0-366. If the input to set is greater than the range, it will show up the next year.
moment().dayOfYear(Number);
moment().dayOfYear();

var m = moment().dayOfYear();
var d = moment().dayOfYear(320);
var a = moment().dayOfYear(400);
 Print
 Add Notes
 Bookmark this page
How to declare constant in react class ? - GeeksforGeeks

14 Dec, 2020
To declare a constant that can be accessed in a React class component, there are multiple approaches that could be efficiently implemented such that that constant is accessible class-wide. Constants can be declared in the following two ways:
Create a getter method in the class for getting the constant when required.Assign the class constant after the declaration of the class. 
Create a getter method in the class for getting the constant when required.
Assign the class constant after the declaration of the class. 
Create a sample project with the following command:
// constantDemo is the name of our folder
npx create-react-app constantDemo
Now move to the constantDemo folder using the following command:
cd constantDemo
The Project Structure will look like the following:
Filename: App.js Now open the App.js file and paste the following code in it:
Javascript
import React, { Component } from "react";  class App extends Component {      static get myConstant() {        return {            name : "GFG",            id : 1        }    }      render() {        return (            <div>My constant is : {JSON.stringify(this.constructor.myConstant)}</div>        );    }}  export default App
Now run the project using the following command:
npm start
Output : 
Another way of declaring the constants is shown below. Paste down the following code in the App.js file.
Filename: App.js
Javascript
import React, { Component } from "react";  class App extends Component {  render() {    return (       <div>My constant is : {JSON.stringify(this.constructor.myConstant)}</div>    );  }}  GFG.myConstant = {    name : "GeeksForGeeks",    id : 2}  export default App
Now run the project using the following command:
npm start
Output:
Picked
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to filter object array based on attributes?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to handle chrome notification in Selenium?

We can handle Chrome notification in Selenium webdriver. These are generally known as the web push notifications and can be handled with the help of the ChromeOptions class. The below image shows a notification from the browser Chrome −
We have to create an object of this ChromeOptions class and apply the addArguments method on it. The parameter --disable-notifications is passed as a parameter to this method. Finally, this information is sent to the ChromeDriver.
ChromeOptions o = new ChromeOptions();
o.addArguments("--disable-notifications");
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.WebDriver;
public class NotificationChrome {
   public static void main(String[] args) throws IOException {
      //object of ChromeOptions
      ChromeOptions o = new ChromeOptions();

      //set browser options o.addArguments("--disable-notifications");
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      // pass browser option to webdriver
      WebDriver driver = new ChromeDriver(o);
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.justdial.com/Bangalore/Bakeries");
   }
}
Tryit Editor v3.7

Tryit: Using media queries
In MongoDB how do you use $set to update a nested value/embedded document?

The syntax is as follows for this −
db.yourCollectionName.update({ }, { $set: { "yourOuterFieldName.yourInnerFieldName": "yourValue" } });
To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.updateNestedValueDemo.insertOne({"CustomerName":"Chris",
   ... "CustomerDetails":{"CustomerAge":25,"CustomerCompanyName":"Google","CustomerCityName":"US"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8fccc4d3c9d04998abf015")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.updateNestedValueDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c8fccc4d3c9d04998abf015"),
   "CustomerName" : "Chris",
   "CustomerDetails" : {
      "CustomerAge" : 25,
      "CustomerCompanyName" : "Google",
      "CustomerCityName" : "US"
   }
}
Here is the query to use $set to update a nested value/embedded document −
> db.updateNestedValueDemo.update({ }, { $set: { "CustomerDetails.CustomerCompanyName": "Dell" } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the documents from a collection using find() method −
> db.updateNestedValueDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c8fccc4d3c9d04998abf015"),
   "CustomerName" : "Chris",
   "CustomerDetails" : {
      "CustomerAge" : 25,
      "CustomerCompanyName" : "Dell",
      "CustomerCityName" : "US"
   }
}
Look at the above sample output, the nested field “CustomerCompanyName” has been changed from “Google” to “Dell”.
Go - Operators Precedence

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Try the following example to understand the operator precedence available in Go programming language −
package main

import "fmt"

func main() {
   var a int = 20
   var b int = 10
   var c int = 15
   var d int = 5
   var e int;

   e = (a + b) * c / d;      // ( 30 * 15 ) / 5
   fmt.Printf("Value of (a + b) * c / d is : %d\n",  e );

   e = ((a + b) * c) / d;    // (30 * 15 ) / 5
   fmt.Printf("Value of ((a + b) * c) / d is  : %d\n" ,  e );

   e = (a + b) * (c / d);   // (30) * (15/5)
   fmt.Printf("Value of (a + b) * (c / d) is  : %d\n",  e );

   e = a + (b * c) / d;     //  20 + (150/5)
   fmt.Printf("Value of a + (b * c) / d is  : %d\n" ,  e );  
}
When you compile and execute the above program it produces the following result −
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is  : 90
Value of (a + b) * (c / d) is  : 90
Value of a + (b * c) / d is  : 50


    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to capture and print Python exception message?

Python exception messages can be captured and printed in different ways as shown in two code examples below. In the first one, we use the message attribute of the exception object.
try:
a = 7/0
print float(a)
except BaseException as e:
print e.message
integer division or modulo by zero
In case of given code, we import the sys module and use the sys.exc_value attribute to capture and print the exception message.
import sys
def catchEverything():
try:
a = 'sequel'
b = 0.8
print a + b
except Exception as e:
print sys.exc_value
catchEverything()
cannot concatenate 'str' and 'float' objects
SQLite - LIMIT Clause

SQLite LIMIT clause is used to limit the data amount returned by the SELECT statement.
Following is the basic syntax of SELECT statement with LIMIT clause.
SELECT column1, column2, columnN 
FROM table_name
LIMIT [no of rows]

Following is the syntax of LIMIT clause when it is used along with OFFSET clause.
SELECT column1, column2, columnN 
FROM table_name
LIMIT [no of rows] OFFSET [row num]

SQLite engine will return rows starting from the next row to the given OFFSET as shown below in the last example.
Consider COMPANY table with the following records −
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0
Following is an example, which limits the row in the table according to the number of rows you want to fetch from table.
sqlite> SELECT * FROM COMPANY LIMIT 6;
This will produce the following result.
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0

However in certain situations, you may need to pick up a set of records from a particular offset. Here is an example, which picks up 3 records starting from the 3rd position.
sqlite> SELECT * FROM COMPANY LIMIT 3 OFFSET 2;
This will produce the following result.
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0


    25 Lectures 
     4.5 hours 

 Sandip Bhattacharya

    17 Lectures 
     1 hours 

 Laurence Svekis

    5 Lectures 
     51 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
Spring WS - Writing Client

In this chapter, we will learn how to create a client for the web application server created in the Spring WS - Writing Server using Spring WS.
package com.tutorialspoint.client;

import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import com.tutorialspoint.GetCountryRequest;
import com.tutorialspoint.GetCountryResponse;

public class CountryServiceClient extends WebServiceGatewaySupport {
   public GetCountryResponse getCountryDetails(String country){
      String uri = "http://localhost:8080/countryService/";
      GetCountryRequest request = new GetCountryRequest();
      request.setName(country);

      GetCountryResponse response =(GetCountryResponse) getWebServiceTemplate()
         .marshalSendAndReceive(uri, request);
      return response;
   }
}
package com.tutorialspoint;

import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import com.tutorialspoint.client.CountryServiceClient;

public class MainApp {
   public static void main(String[] args) {
      CountryServiceClient client = new CountryServiceClient();
      Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
      marshaller.setContextPath("com.tutorialspoint");
      client.setMarshaller(marshaller);
      client.setUnmarshaller(marshaller);
      GetCountryResponse response = client.getCountryDetails("United States");

      System.out.println("Country : " + response.getCountry().getName());
      System.out.println("Capital : " + response.getCountry().getCapital());
      System.out.println("Population : " + response.getCountry().getPopulation());
      System.out.println("Currency : " + response.getCountry().getCurrency());
   }
}
Start the Tomcat server and ensure that we can access other webpages from the webapps folder using a standard browser.
Right click on the MainApp.java in your application under Eclipse and use run as Java Application command. If everything is ok with the application, it will print the following message.
Country : United States
Capital : Washington
Population : 46704314
Currency : USD

Here, we have created a Client – CountryServiceClient.java for the SOAP based web service. MainApp uses CountryServiceClient to make a hit to the web service, makes a post request and gets the data.
 Print
 Add Notes
 Bookmark this page
How to check if field is null or empty in MySQL?

To check whether a field is null or empty in MySQL, use the IF() function in MySQL. The syntax is as follows −
SELECT IF(yourColumnName IS NULL or yourColumnName = '', 'NULLId', yourColumnName) as anyVariableName from yourTableName;
To understand the above syntax, let us create a table. The following is the query to create a table −
mysql> create table NullAndEmptyDemo
-1> (
-> Id varchar(200)
-> );
Query OK, 0 rows affected (0.66 sec)
Let us now insert records into the table with the help of insert command. The query to insert records in the table is as follows. We have added null and empty values as well −
mysql> insert into NullAndEmptyDemo values(NULL);
Query OK, 1 row affected (0.22 sec)
mysql> insert into NullAndEmptyDemo values('Smith123');
Query OK, 1 row affected (0.17 sec)
mysql> insert into NullAndEmptyDemo values(' ');
Query OK, 1 row affected (0.35 sec)
mysql> insert into NullAndEmptyDemo values('98765');
Query OK, 1 row affected (0.15 sec)
mysql> insert into NullAndEmptyDemo values(NULL);
Query OK, 1 row affected (0.10 sec)
mysql> insert into NullAndEmptyDemo values('Carol567');
Query OK, 1 row affected (0.14 sec)
mysql> insert into NullAndEmptyDemo values('');
Query OK, 1 row affected (0.13 sec)
Displaying all records with the help of select statement. The query is as follows −
mysql> select *from NullAndEmptyDemo;
The following is the output −
+----------+
| Id       |
+----------+
| NULL     |
| Smith123 |
|          |
| 98765    |
| NULL     |
| Carol567 |
|          |
+----------+
7 rows in set (0.00 sec)
Now you can apply the above syntax we discussed in the beginning to check whether the field is null or empty. The query is as follows −
mysql> SELECT IF(Id IS NULL or Id = '', 'NULLId', Id) as UpdatedColumnValue from NullAndEmptyDemo;
The following is the output that replace the values, if NULL or empty (“”) is found at first −
+--------------------+
| UpdatedColumnValue |
+--------------------+
| NULLId             |
| Smith123           |
| NULLId             |
| 98765              |
| NULLId             |
| Carol567           |
| NULLId             |
+--------------------+
7 rows in set (0.00 sec)
How to create a signup form with HTML and CSS?

Following is the code to create a signup form using HTML and CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body{
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
* {box-sizing: border-box}
input[type=text], input[type=password] {
   width: 100%;
   font-size: 28px;
   padding: 15px;
   margin: 5px 0 22px 0;
   display: inline-block;
   border: none;
   background: #f1f1f1;
}
label{
   font-size: 15px;
}
input[type=text]:focus, input[type=password]:focus {
   background-color: #ddd;
   outline: none;
}
hr {
   border: 1px solid #f1f1f1;
   margin-bottom: 25px;
}
button {
   font-size: 18px;
   font-weight: bold;
   background-color: rgb(10, 119, 13);
   color: white;
   padding: 14px 20px;
   margin: 8px 0;
   border: none;
   cursor: pointer;
   width: 100%;
   opacity: 0.9;
}
button:hover {
   opacity:1;
}
.cancel {
   padding: 14px 20px;
   background-color: #ff3d2f;
}
.formContainer {
   padding: 16px;
}
.formContainer p{
   font-size: 28px;
}
</style>
<body>
<form>
<div class="formContainer">
<h1>Sign Up Form</h1>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<label for="repeatPassword"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="repeatPassword"
required>
<label>
<input type="checkbox" checked="checked" name="remember" style="marginbottom: 15px"> Remember me
</label>
<p>By creating an account you agree to our <a href="#"
style="color:dodgerblue">Terms & Privacy</a><p>
<div>
<button type="button" class="cancel">Cancel</button>
<button type="submit" class="signup">Sign Up</button>
</div>
</div>
</form>
</body>
</html>
This will produce the following output −
How to cast and update a numeric value from string column only where applicable in MySQL?

You can use the CEIL() function from MySQL. Let us first create a table. Here, we have taken the first column as VARCHAR −
mysql> create table DemoTable
   -> (
   -> Value varchar(20),
   -> UpdateValue int
   -> );
Query OK, 0 rows affected (1.08 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Value) values('100');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Value) values('false');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Value) values('true');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(Value) values('1');
Query OK, 1 row affected (0.07 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+-------------+
| Value | UpdateValue |
+-------+-------------+
|   100 |        NULL |
| false |        NULL |
|  true |        NULL |
|     1 |        NULL |
+-------+-------------+
4 rows in set (0.00 sec)
Following is the query to cast and update a numeric value from string column only where applicable −
mysql> update DemoTable
   -> set UpdateValue=ceil(cast(Value AS char(7)));
Query OK, 4 rows affected (0.18 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-------+-------------+
| Value | UpdateValue |
+-------+-------------+
|   100 |         100 |
| false |           0 |
|  true |           0 |
|     1 |           1 |
+-------+-------------+
4 rows in set (0.00 sec)
bitset test() in C++ STL - GeeksforGeeks

19 Jun, 2018
bitset::test() is an inbuilt function in C++ STL which tests whether the bit at a given index is set or not.
Syntax:
bitset_name.test(index) 
Parameters: The function accepts only a single mandatory parameter index which specifies the index at which the bit is set or not.
Return Value: The function returns a boolean value. It returns true if the bit at the given index is set else it returns false.
Below programs illustrate the above function:
Program 1:
// CPP program to illustrate the// bitset::test() function// when bitset is a string#include <bits/stdc++.h>using namespace std;  int main(){    // Initialization of bitset    bitset<4> b1(string("1100"));    bitset<6> b2(string("010010"));      // Function to check if 2nd index bit    // is set or not in b1    if (b1.test(2))        cout << "Bit at index 2 of 1100 is set\n";    else        cout << "Bit at index 2 is not set\n";      // Function to check if 3nd index bit    // is set or not in b2    if (b2.test(3))        cout << "Bit at index 3 of 010010 is set\n";    else        cout << "Bit at index 3 of 010010 is not set\n";      return 0;}
Bit at index 2 of 1100 is set
Bit at index 3 of 010010 is not set

Program 2:
// CPP program to illustrate the// bitset::test() function// when the bitset is a number#include <bits/stdc++.h>using namespace std;  int main(){    // Initialization of bitset    bitset<4> b1(5);    bitset<6> b2(16);      // Function to check if 2nd index bit    // is set or not in b1    if (b1.test(2))        cout << "Bit at index 2 of 5 is set\n";    else        cout << "Bit at index 2 of 5 is not set\n";      // Function to check if 3nd index bit    // is set or not in b2    if (b2.test(3))        cout << "Bit at index 3 of 16 is set\n";    else        cout << "Bit at index 3 of 16 is not set\n";      return 0;}
Bit at index 2 of 5 is set
Bit at index 3 of 16 is not set

CPP-bitset
CPP-Functions
STL
C++ Programs
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Const keyword in C++
Handling the Divide by Zero Exception in C++
Why it is important to write "using namespace std" in C++ program?
Dynamic _Cast in C++
isdigit() function in C/C++ with Examples
Setting up Sublime Text for C++ Competitive Programming Environment
Different ways to print elements of vector
Bootstrap alert-dismissable class

The .alert-dismissable class in Bootstrap is used to close the alert.
You can try to run the following code to implement the alert-dismissable class in Bootstrap
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "alert alert-warning alert-dismissable">
         <button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
            ×
         </button>
         Warning ! Don’t submit this.
      </div>
      <div class = "alert alert-danger alert-dismissable">
         <button type = "button" class = "close" data-dismiss = "alert" aria-hidden = "true">
            ×
         </button>
         Error ! Change few things.
      </div>
   </body>
</html>
C++ Program for BogoSort or Permutation Sort - GeeksforGeeks

08 Jun, 2021
BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted.(Wiki) For example, if bogosort is used to sort a deck of cards, it would consist of checking if the deck were in order, and if it were not, one would throw the deck into the air, pick the cards up at random, and repeat the process until the deck is sorted. 
PseudoCode:  
while not Sorted(list) do
    shuffle (list)
done
 
CPP
// C++ implementation of Bogo Sort#include <bits/stdc++.h>using namespace std; // To check if array is sorted or notbool isSorted(int a[], int n){    while (--n > 1)        if (a[n] < a[n - 1])            return false;    return true;} // To generate permutation of the arrayvoid shuffle(int a[], int n){    for (int i = 0; i < n; i++)        swap(a[i], a[rand() % n]);} // Sorts array a[0..n-1] using Bogo sortvoid bogosort(int a[], int n){    // if array is not sorted then shuffle    // the array again    while (!isSorted(a, n))        shuffle(a, n);} // prints the arrayvoid printArray(int a[], int n){    for (int i = 0; i < n; i++)        printf("%d ", a[i]);    printf("\n");} // Driver codeint main(){    int a[] = { 3, 2, 5, 1, 0, 4 };    int n = sizeof a / sizeof a[0];    bogosort(a, n);    printf("Sorted array :\n");    printArray(a, n);    return 0;}
Sorted array :
0 1 2 3 4 5
 
Please refer complete article on BogoSort or Permutation Sort for more details! 
anikaseth98
C++ Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Const keyword in C++
Handling the Divide by Zero Exception in C++
Python time ctime() Method

Python time method ctime() converts a time expressed in seconds since the epoch to a string representing local time. If secs is not provided or None, the current time as returned by time() is used. This function is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().
Following is the syntax for ctime() method −
time.ctime([ sec ])

sec − These are the number of seconds to be converted into string representation.
sec − These are the number of seconds to be converted into string representation.
This method does not return any value.
The following example shows the usage of ctime() method.
#!/usr/bin/python
import time

print "time.ctime() : %s" % time.ctime()
When we run above program, it produces following result −
time.ctime() : Tue Feb 17 10:00:18 2009


    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
Rexx - interpret

Interprets or executes the defined instruction.
Interpret command 

command − The command sent to the interpret instruction.
command − The command sent to the interpret instruction.
Returns the output of the command sent to the interpret instruction.
/* Main program */ 
options arexx_bifs interpret 
say 'Hello'
When we run the above program we will get the following result.
Hello

 Print
 Add Notes
 Bookmark this page
Python Functools - total_ordering() - GeeksforGeeks

26 Mar, 2020
Functools module in python helps in implementing higher-order functions. Higher-order functions are dependent functions that call other functions. Total_ordering provides rich class comparison methods that help in comparing classes without explicitly defining a function for it. So, It helps in the redundancy of code.
The six rich class comparison methods are:
object.__lt__(self, other)
object.__le__(self, other)
object.__eq__(self, other)
object.__ne__(self, other)
object.__gt__(self, other)
object.__ge__(self, other)
There are 2 essential conditions to implement these comparison methods:
At least one of the comparison methods must be defined from lt(less than), le(less than or equal to), gt(greater than) or ge(greater than or equal to).
The eq function must also be defined.
Example:
from functools import total_ordering    @total_orderingclass Students:    def __init__(self, cgpa):        self.cgpa = cgpa      def __lt__(self, other):        return self.cgpa<other.cgpa      def __eq__(self, other):        return self.cgpa == other.cgpa      def __le__(self, other):        return self.cgpa<= other.cgpa          def __ge__(self, other):        return self.cgpa>= other.cgpa              def __ne__(self, other):        return self.cgpa != other.cgpa  Arjun = Students(8.6)  Ram = Students(7.5)  print(Arjun.__lt__(Ram))print(Arjun.__le__(Ram))print(Arjun.__gt__(Ram))print(Arjun.__ge__(Ram))print(Arjun.__eq__(Ram))print(Arjun.__ne__(Ram))
Output
False
False
True
True
False
True

Note: Since the __gt__ method is not implemented, it shows “Not
Example 2:
from functools import total_ordering  @total_orderingclass num:          def __init__(self, value):        self.value = value              def __lt__(self, other):        return self.value < other.value            def __eq__(self, other):                  # Changing the functionality        # of equality operator        return self.value != other.value          # Driver codeprint(num(2) < num(3))print(num(2) > num(3))print(num(3) == num(3))print(num(3) == num(5))
Output:
True
False
False
True
Python Decorators
Python functools-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to Sort object of objects by its key value JavaScript

Let’s say, we have an object with keys as string literals and their values as objects as well like
this −
const companies = {
   'landwaves ltd': {employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal'},
   'colin & co': {employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},
   'motilal biscuits': {employees: 975, worth: '1m', CEO: 'Rahul Gupta'},
   'numbtree': {employees: 1500, worth: '1.5m', CEO: 'Jay Kumar'},
   'solace pvt ltd': {employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'},
   'ambicure': {employees: 170, worth: '0.1m', CEO: 'Preetam Chawla'},
   'dis n dat': {employees: 540, worth: '1m', CEO: 'Mohit Sharma'},
}
We are required to write a function that sorts the object according to its keys and returns it.
const companies = {
   'landwaves ltd': {employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal'},
   'colin & co': {employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},
   'motilal biscuits': {employees: 975, worth: '1m', CEO: 'Rahul Gupta'},
   'numbtree': {employees: 1500, worth: '1.5m', CEO: 'Jay Kumar'},
   'solace pvt ltd': {employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'},
   'ambicure': {employees: 170, worth: '0.1m', CEO: 'Preetam Chawla'},
   'dis n dat': {employees: 540, worth: '1m', CEO: 'Mohit Sharma'},
};
const sortKeys = (obj) => {
   return Object.assign(...Object.entries(obj).sort().map(([key, value])
   => {
      return {
         [key]: value
      }
   }));
};
console.log(sortKeys(companies));
The output in the console will be −
{
   ambicure: { employees: 170, worth: '0.1m', CEO: 'Preetam Chawla' },
   'colin & co': { employees: 200, worth: '0.2m', CEO: 'Sukesh Maheshwari'},
   'dis n dat': { employees: 540, worth: '1m', CEO: 'Mohit Sharma' },
   'landwaves ltd': { employees: 1200, worth: '1.2m', CEO: 'Rajiv Bansal' },
   'motilal biscuits': { employees: 975, worth: '1m', CEO: 'Rahul Gupta' },
   numbtree: { employees: 1500, worth: '1.5m', CEO: 'Jay Kumar' },
   'solace pvt ltd': { employees: 1800, worth: '1.65m', CEO: 'Arvind Sangal'
   }
}
Check for NULL or empty variable in a MySQL stored procedure

To check for NULL or empty variable, use the IF condition. Let us create a stored procedure −
mysql> delimiter //
mysql> create procedure checkingForNullDemo(Name varchar(20))
     begin
     if Name is NULL OR Name='' then
     select 'Adam Smith';
     else
     select Name;
     end if ;
     end
     //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
Case 1
When NULL is passed. Call the stored procedure using call command
mysql> call checkingForNullDemo(NULL);
This will produce the following output −
+------------+
| Adam Smith |
+------------+
| Adam Smith |
+------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)
Case 2
When a value is passed. Call the stored procedure using the call command
mysql> call checkingForNullDemo('John Doe');
This will produce the following output −
+----------+
| Name     |
+----------+
| John Doe |
+----------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Graphics.Clear() Method in C# with Examples - GeeksforGeeks

04 Apr, 2019
Graphics.Clear(color) Method is used to clear the canvas and paints it up with the specified background color.
Syntax: public void Clear (System.Drawing.Color color);Parameter:color: Color identifier which contains RGB values, to colour the background of canvas.
Example 1:
// C# snippet to print GeeksForGeeksusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms;namespace GFG {  class PrintableForm : Form {      // Main Method    public static void Main()    {        Application.Run(new PrintableForm());    }    public PrintableForm()    {        ResizeRedraw = true;    }      protected override void OnPaint(PaintEventArgs e)    {        Font font = new Font("Arial", 16);        SolidBrush brush = new SolidBrush(Color.Black);        PointF point = new PointF(10.0F, 10.0F);        e.Graphics.DrawString("GeeksForGeeks", font, brush, point);    }}}
Output:
Example 2:
// C# program to illustrate the Clear Method// C# snippet to print GeeksForGeeksusing System;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms;namespace GFG {  class PrintableForm : Form {      // Main Method    public static void Main()    {        Application.Run(new PrintableForm());    }    public PrintableForm()    {        ResizeRedraw = true;    }      protected override void    OnPaint(PaintEventArgs e)    {        e.Graphics.Clear(Color.Coral);    }}}
Output:
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.drawing.graphics.clear?view=netframework-4.7.2
CSharp-Drawing-Namespace
CSharp-Graphics-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Lambda Expressions in C#
IIF() Function in SQL Server - GeeksforGeeks

16 Oct, 2020
The SQL Server IIF() function has three parameters. IIF() function judges or evaluates the first parameter and returns the second parameters if the first parameters is true; otherwise, it returns the third parameters. IIF() function used in SQL Server to add if-else logic to queries.>
Syntax :
IIF(boolean_value, true_value, false_value)

Parameters used in Syntax:
boolean_value –It is a value to be judged. It must be a valid boolean value, or the function will raise an error.
true_value –It is the value to be resulted if the boolean_value to true.
false_value –It is the value to be resulted if the boolean_value to false.
Fact to know: The IIF() function is similar to a CASE expression – 
CASE  
   WHEN boolean_expression  
       THEN true_value
   ELSE
       false_value
END

Example-1 :To use the IIF() function to check if 40 < 60 :
SELECT  IIF(40 < 60, 'True', 'False') AS Result ; 
Output :ResultTrue
Let us assume we have below sample table named “Geektable“:
Example-2 :To use IIF() function with table column.Below example uses IIF()function within IIF() functions:
SELECT    
   IIF(G_status = 1, ‘Waiting’,  
       IIF(G_status=2, ‘InProgress’,
           IIF(G_status=3, ‘Rejected’,
               IIF(G_status=4, ‘Completed’)
           )
       )
   ) AS Status,

   COUNT(G_id) AS Count
FROM Geektable
GROUP BY G_status ; 
Output :
Example-3 :To use IIF() function with aggregate functions.Below example uses IIF()function with the SUM() function:
SELECT    
   SUM(IIF(G_status = 1, 1, 0)) AS ‘Waiting’,  
   SUM(IIF(G_status = 2, 1, 0)) AS ‘InProgress’,  
   SUM(IIF(G_status = 3, 1, 0)) AS ‘Rejected’,  
   SUM(IIF(G_status = 4, 1, 0)) AS ‘Completed’,  
   COUNT(*) AS Total

FROM  Geektable;

Output :Here, the IIF() function results 1 or 0 if the status is matched. The SUM() function results the number of each status.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Convert VARCHAR to INT
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Select Data Between Two Dates and Times in SQL Server?
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Compare Two Dates
How to install MSI file using batch file in PowerShell?

Let say we have one MSI file and we need to install the MSI file on the remote computers using PowerShell but that MSI file should be deployed with the Batch file and should be executed using PowerShell.
In this example, we have a 7-zip MSI file and batch file we will first write the installation instructions as shown below.
msiexec /i "C:\temp\7z1900-x64.msi" /quiet
We have the installation MSI package located at the C:\temp location. We will save the above instruction inside the 7ZipInstaller.bat file.
Now we need to call the batch file as shown below. −Wait will wait for the batch file to execute first and then moves to the next instruction if any and −NoNewWindow will
Start-Process C:\Temp\7zipInstaller.bat -Wait -NoNewWindow
Once you run the above command, it will install 7zip at the location specified. You can directly pass these instructions inside the Start-Process to execute MSI but if we need to execute the batch file then this is a good way because we can call this batch file remotely as well. The below command is for the remote computer.
Invoke-Command -ComputerName TestMachine1, TestMachine2 -ScriptBlock{
   Start-Process C:\Temp\7zipInstaller.bat -Wait -NoNewWindow
}
This command will run on the computers Testmachine1 and Testmachine2. Make sure you copy the MSI package to the remote location before running this command.
How to Replace null with “-”  JavaScript

We have to write a function that takes in an object with many keys and replaces all false values
with a dash (‘ - ’). We will simply iterate over the original object, checking for the keys that
contain false values, and we will replace those false values with ‘-’ without consuming any extra
space (i.e., in place)
const obj = {
   key1: 'Hello',
   key2: 'World',
   key3: '',
   key4: 45,
   key5: 'can i use arrays',
   key6: null,
   key7: 'fast n furious',
   key8: undefined,
   key9: '',
   key10: NaN,
};
const swapValue = (obj) => {
   Object.keys(obj).forEach(key => {
      if(!obj[key]){
         obj[key] = '-';
      }
   });
};
swapValue(obj);
console.log(obj);
The output in the console will be −
{
   key1: 'Hello',
   key2: 'World',
   key3: '-',
   key4: 45,
   key5: 'can i use arrays',
   key6: '-',
   key7: 'fast n furious',
   key8: '-',
   key9: '-',
   key10: '-'
}
Advanced JavaScript Backend Basics

JavaScript programming language that is usually used for web scripting. It is a lightweight, interpreted programming language. JavaScript is one of the most programming languages for web development. For running JavaScript
each browser has its own engine which enables the proper functioning of JavaScript in the browser. Some common Browsers and their JavaScript engines are −
Spider Monkey for firefox
V8 for Google Chrome
JavaScript code for Safari
Chakra for Microsoft Internet Explorer/ edge
To make JavaScript universe and stop a browser from describing their own scripts. There is a standard set for JavaScript which will be used throughout the browser. there is an Association named ECMA ( European computer manufacturers Association) which sets standards for JavaScript.
For proper running of JavaScript code, the JavaScript engine works in two different phases to make sure the script created work properly irrespective of the browser.
Creation phase − In the creation phase, the JavaScript engine well goes through the entire code and check the syntax of the program and throw a synthetic error if it occurs. the engine will declare and provide some memory chunks to variables as well as to the functions that are declared in the JavaScript code.
Creation phase − In the creation phase, the JavaScript engine well goes through the entire code and check the syntax of the program and throw a synthetic error if it occurs. the engine will declare and provide some memory chunks to variables as well as to the functions that are declared in the JavaScript code.
Execution phase − in the execution phase, the engine will run the code. Also, the variables are declared and throw any other error that may occur.
Execution phase − in the execution phase, the engine will run the code. Also, the variables are declared and throw any other error that may occur.
In JavaScript, there are two types of equality operators.
== operator is used to test for checking abstract equality of two values. This means in this comparison the equality of values is checked, the type of data is not checked for equality.
=== operator is used to check for strict equality of two values. This means in this comparison both types and equality of the data are checked.
<script>
document.write(34 == "34");
document.write('<br>')
document.write(98 === "98");
</script>
true
false
Boolean variables are those variables in programming languages that have only two types of values. The valid boolean values in Javascript programming language are TRUE and FALSE.
The TRUE value in programming corresponds to the values other than 0, which triggers the conditional statements in Javascript.
Some values that convert back to TRUE boolean value are −
{} - empty object
[] - empty array
!False values are TRUE
FALSE values in programming correspond to 0 values, that does not ignore conditional statements in Javascript.
Some values that convert back to FALSE boolean value are −
0 - numerical value of FALSE
undefined - value that is undefined is false
null - null value is always false
Create a large button with Bootstrap

To create a large button, use the .btn-lg class in Bootstrap.
You can try to run the following code to implement the .btn-lg class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p>The following are FMCG companies:</p>
      <div class = "btn-default">
         <button type = "button" class="btn btn-primary">ITC Limited</button>
         <button type = "button" class="btn btn-sm">Nestle</button>
         <button type = "button" class="btn btn-lg">Britannia Industries Limited</button>
      </div>
   </body>
</html>