code-rag-bench/online-tutorials huggingface dataset:
How to detect airplane mode is on or off in Android?

This example demonstrates about How to detect airplane mode is on or off in Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:gravity="center" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      checkAirplaneMode();
   }
   private void checkAirplaneMode() {
      if (isAirplaneModeOn(getApplicationContext())) {
         textView.setText("Airplane Mode is Enabled");
      } else {
         textView.setText("Airplane Mode is Disabled");
      }
   }
   private static boolean isAirplaneModeOn(Context context) {
      return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
ios manipulators boolalpha() function in C++ - GeeksforGeeks

28 Aug, 2019
The boolalpha() method of stream manipulators in C++ is used to set the boolalpha format flag for the specified str stream.
Syntax:
ios_base& boolalpha (ios_base& str)

Parameters: This method accepts str as a a parameter which is the stream for which the format flag is affected.
Return Value: This method returns the stream str with boolalpha format flag set.
Example 1:
// C++ code to demonstrate// the working of boolalpha() function  #include <iostream>  using namespace std;  int main(){      // Initializing the boolean flag    bool flag = true;      // Using boolalpha()    cout << "boolalpha flag: "         << boolalpha << flag << endl;      return 0;}
boolalpha flag: true

Example 2:
// C++ code to demonstrate// the working of boolalpha() function  #include <iostream>  using namespace std;  int main(){      // Initializing the boolean flag    bool flag = false;      // Using boolalpha()    cout << "boolalpha flag: "         << boolalpha << flag << endl;      return 0;}
boolalpha flag: false

Reference: http://www.cplusplus.com/reference/ios/boolalpha/
cpp-ios
cpp-manipulators
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Map in C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects
Constructors in C++
Bitwise Operators in C/C++
Socket Programming in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
Virtual Function in C++
iomanip setiosflags() function in C++ with Examples - GeeksforGeeks

10 Jun, 2021
The setiosflags() method of iomanip library in C++ is used to set the ios library format flags specified as the parameter to this method.Syntax:  
setiosflags (ios_base::format_flag)
Parameters: This method accepts format_flag as a parameter which is the ios library format flag to be set by this method.Return Value: This method does not returns anything. It only acts as stream manipulators.Example 1: 
CPP
// C++ code to demonstrate// the working of setiosflags() function #include <iomanip>#include <ios>#include <iostream> using namespace std; int main(){     // Initializing the integer    int num = 50;     // Using setiosflags()    cout << "Setting showbase flag "         << "using setiosflags: \n"         << hex         << setiosflags(ios::showbase)         << num << endl;     return 0;}
Setting showbase flag using setiosflags: 
0x32
 
Example 2: 
CPP
// C++ code to demonstrate// the working of setiosflags() function #include <iomanip>#include <ios>#include <iostream> using namespace std; int main(){     // Initializing the integer    int num = 50;     // Using setiosflags()    cout << "Setting showbase and uppercase"         << " flag using setiosflags: \n"         << hex         << setiosflags(                ios::showbase                | ios::uppercase)         << num << endl;     return 0;}
Setting showbase and uppercase flag using setiosflags: 
0X32
 
Reference: http://www.cplusplus.com/reference/iomanip/setiosflags/ 
kumud544131
CPP-Functions
cpp-input-output
cpp-manipulators
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Classes and Objects
Virtual Function in C++
Constructors in C++
Templates in C++ with Examples
Operator Overloading in C++
Socket Programming in C/C++
vector erase() and clear() in C++
Object Oriented Programming in C++
Substring in C++
Copy Constructor in C++
Scala Map clone() method with example - GeeksforGeeks

13 Aug, 2019
The clone() method is utilized to make a copy of the receivers object. value clone is a member of scala.collection.mutable.Map[String, Int].
Method Definition: def clone(): Map[A, B]
Return Type: It returns the copy of the map used.
Example #1:
// Scala program of clone()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = scala.collection.mutable.Map("geeks" -> 5, "for" -> 3)                  // Applying clone method        val result = m1.clone()                  // Displays output        println(result)          }}
Map(geeks -> 5, for -> 3)

Here, a mutable map is used as clone() is a member of scala.collection.mutable.Map[String, Int].Example #2:
// Scala program of clone()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a map        val m1 = scala.collection.immutable.Map("geeks" -> 5, "for" -> 3)                  // Applying clone method        val result = m1.clone()                  // Displays output        println(result)          }}
prog.scala:16: error: value clone is not a member of scala.collection.immutable.Map[String,Int]val result = m1.clone()^one error found
Here, one error is found as immutable map is utilized but clone method is a member of scala.collection.mutable.Map[String, Int].
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Inheritance in Scala
Scala Constructors
Scala | Arrays
Scala String substring() method with example
Lambda Expression in Scala
Python | Pandas Series.quantile() - GeeksforGeeks

11 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.quantile() function return value at the given quantile for the underlying data in the given Series object.
Syntax: Series.quantile(q=0.5, interpolation=’linear’)
Parameter :q : float or array-like, default 0.5 (50% quantile)interpolation : {‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}
Returns : quantile : float or Series
Example #1: Use Series.quantile() function to return the desired quantile of the underlying data in the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.quantile() function to find the 40% quantile of the underlying data in the given series object.
# return the value of 40 % quantileresult = sr.quantile(q = 0.4)  # Print the resultprint(result)
Output :
As we can see in the output, the Series.quantile() function has successfully returned the desired qunatile value of the underlying data of the given Series object.
Example #2: Use Series.quantile() function to return the desired quantile of the underlying data in the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32])  # Print the seriesprint(sr)
Output :
Now we will use Series.quantile() function to find the 90% quantile of the underlying data in the given series object.
# return the value of 90 % quantileresult = sr.quantile(q = 0.9)  # Print the resultprint(result)
Output :
As we can see in the output, the Series.quantile() function has successfully returned the desired qunatile value of the underlying data of the given Series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists
PyQt5 - Count the number of items in ComboBox - GeeksforGeeks

22 Apr, 2020
In this article we will see how we can find the total number of items present in the combo box. We know we can add items in the combo box with the help of addItem method to add single item and addItems method to add multiple items. In order to get the count of all the items in the combo box we will use count method.
Syntax : combo_box.count()
Argument : It takes no argument
Return : It will return integer i.e number of items in combo box
Steps for implementation:
1. Create a combo box2. Add items to combo box3. Create push button4. Add action to the push button5. Create label to show count5. Inside the action count the items of combo box with the help of count method and store it in variable6. Show the count variable in label with the help of setText method
Below is the implementation –
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 120, 30)          # geek list        geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # creating push button to clear the list        button = QPushButton("Find Count ", self)          print(self.combo_box.count())          # adding action to button        button.pressed.connect(self.find_count)          # creating label to show count        self.label = QLabel(self)          # setting geometry of the label        self.label.setGeometry(200, 200, 200, 30)      def find_count(self):          # finding the number of items in cmbo box        count = self.combo_box.count()          # showing count on the screen though label        self.label.setText("Total number of  items : " + str(count))  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Get the SUM of records between two given dates in MySQL

For this, use BETWEEN keyword. Let us first create a −
mysql> create table DemoTable1444
   -> (
   -> Value int,
   -> PurchaseDate datetime
   -> );
Query OK, 0 rows affected (0.45 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1444 values(40,'2019-01-10');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1444 values(100,'2019-10-03');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1444 values(170,'2019-11-21');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1444 values(70,'2018-12-05');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select −
mysql> select * from DemoTable1444;
This will produce the following output −
+-------+---------------------+
| Value | PurchaseDate        |
+-------+---------------------+
|    40 | 2019-01-10 00:00:00 |
|   100 | 2019-10-03 00:00:00 |
|   170 | 2019-11-21 00:00:00 |
|    70 | 2018-12-05 00:00:00 |
+-------+---------------------+
4 rows in set (0.00 sec)
Following is the query to get the sum between two given dates −
mysql> select sum(Value) from DemoTable1444 where PurchaseDate between '2019-10-02' and '2019-12-31';
This will produce the following output −
+------------+
| sum(Value) |
+------------+
|        270 |
+------------+
1 row in set (0.02 sec)
Combining two sorted lists in Python

Lists are one of the most extensively used python data structures. In this article we will see how to combine the elements of two lists and produce the final output in a sorted manner.
The + operator can join the elements of two lists into one. Then we apply the sorted function which will sort the elements of the final list created with this combination.
 Live Demo
listA = ['Mon', 'Tue', 'Fri']
listB = ['Thu','Fri','Sat']
# Given lists
print("Given list A is : ",listA)
print("Given list B is : ",listB)
# Add and sort
res = sorted(listA + listB)
# Result
print("The combined sorted list is : \n" ,res)
Running the above code gives us the following result −
Given list A is : ['Mon', 'Tue', 'Fri']
Given list B is : ['Thu', 'Fri', 'Sat']
The combined sorted list is :
['Fri', 'Fri', 'Mon', 'Sat', 'Thu', 'Tue']
The merge function from heapq module can combine the elements of two lists. Then we apply the sorted function to get the final output.
 Live Demo
from heapq import merge
listA = ['Mon', 'Tue', 'Fri']
listB = ['Thu','Fri','Sat']
# Given lists
print("Given list A is : ",listA)
print("Given list B is : ",listB)
# Merge
res = list(merge(listA,listB))
# Result
print("The combined sorted list is : \n" ,sorted(res))
Running the above code gives us the following result −
Given list A is : ['Mon', 'Tue', 'Fri']
Given list B is : ['Thu', 'Fri', 'Sat']
The combined sorted list is :
['Fri', 'Fri', 'Mon', 'Sat', 'Thu', 'Tue']
Math class methods in C#

The System.Math class in C# provides methods are properties to perform mathematical operations, trigonometric, logarithmic calculations, etc.
Some of its methods include −
For all the methods, refer MSDN
Let us see an example to get the absolute value −
using System;

class Program {
   static void Main() {
      int val1 = 50;
      int val2 = -150;

      Console.WriteLine("Before...");
      Console.WriteLine(val1);
      Console.WriteLine(val2);

      int abs1 = Math.Abs(val1);
      int abs2 = Math.Abs(val2);

      Console.WriteLine("After...");
      Console.WriteLine(abs1);
      Console.WriteLine(abs2);
   }
}
Type.GetProperties() Method in C#

The Type.GetProperties() method in C# is used to get the properties of the current Type.
Following is the syntax −
public System.Reflection.PropertyInfo[] GetProperties ();
public abstract System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags bindingAttr);
Above, bindingAttr is a bitwise combination of the enumeration values that specify how the search is performed.
using System;
using System.Reflection;
public class Demo {
   public static void Main(){
      Type type = typeof(System.Type);
      PropertyInfo[] info = type.GetProperties();
      Console.WriteLine("Properties... ");
      for (int i = 0; i < info.Length; i++)
         Console.WriteLine(" {0}", info[i].ToString());
   }
}
This will produce the following output −
Properties...
System.Reflection.MemberTypes MemberType
System.Type DeclaringType
System.Reflection.MethodBase DeclaringMethod
System.Type ReflectedType
System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute
System.Guid GUID
System.Reflection.Binder DefaultBinder
System.Reflection.Module Module
System.Reflection.Assembly Assembly
System.RuntimeTypeHandle TypeHandle
System.String FullName
System.String Namespace
System.String AssemblyQualifiedName
System.Type BaseType
System.Reflection.ConstructorInfo TypeInitializer
Boolean IsNested
System.Reflection.TypeAttributes Attributes
System.Reflection.GenericParameterAttributes GenericParameterAttributes
Boolean IsVisible
Boolean IsNotPublic
Boolean IsPublic
Boolean IsNestedPublic
Boolean IsNestedPrivate
Boolean IsNestedFamily
Boolean IsNestedAssembly
Boolean IsNestedFamANDAssem
Boolean IsNestedFamORAssem
Boolean IsAutoLayout
Boolean IsLayoutSequential
Boolean IsExplicitLayout
Boolean IsClass
Boolean IsInterface
Boolean IsValueType
Boolean IsAbstract
Boolean IsSealed
Boolean IsEnum
Boolean IsSpecialName
Boolean IsImport
Boolean IsSerializable
Boolean IsAnsiClass
Boolean IsUnicodeClass
Boolean IsAutoClass
Boolean IsArray
Boolean IsGenericType
Boolean IsGenericTypeDefinition
Boolean IsConstructedGenericType
Boolean IsGenericParameter
Int32 GenericParameterPosition
Boolean ContainsGenericParameters
Boolean IsByRef
Boolean IsPointer
Boolean IsPrimitive
Boolean IsCOMObject
Boolean HasElementType
Boolean IsContextful
Boolean IsMarshalByRef
System.Type[] GenericTypeArguments
Boolean IsSecurityCritical
Boolean IsSecuritySafeCritical
Boolean IsSecurityTransparent
System.Type UnderlyingSystemType
System.String Name
System.Collections.Generic.IEnumerable`1[System.Reflection.CustomAttributeData] CustomAttributes
Int32 MetadataToken
Let us now see another example to implement the Type.GetProperties() method −
using System;
using System.Reflection;
public class Demo {
   public static void Main(){
      Type type = typeof(string);
      PropertyInfo[] info = type.GetProperties();
      Console.WriteLine("Count of Properties = "+info.Length);
      Console.WriteLine("Properties... ");
      for (int i = 0; i < info.Length; i++)
         Console.WriteLine(" {0}", info[i].ToString());
   }
}
This will produce the following output −
Count of Properties = 2
Properties...
Char Chars [Int32]
Int32 Length
SQL Tryit Editor v1.6

SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Node.js console.table() Method - GeeksforGeeks

09 Jul, 2020
The console.table() method is an inbuilt application programming interface of the console module which is used to print the table constructed from it’s parameters into the console.
Syntax:
console.table(data, properties);
Parameters: This method accept two parameters as mentioned above and described below:
data: Tabular data. An array of each row data that contains values for each column of that specific row.properties: It specifies the properties for constructing the table.
data: Tabular data. An array of each row data that contains values for each column of that specific row.
properties: It specifies the properties for constructing the table.
Return Value: This method doesn’t return anything but print the constructed table and log it. If it fails to parse the arguments into the table then it simply logs the arguments.
Below examples illustrate the use of console.table() method in Node.js.
Example 1: Filename: app.js
// Node.js program to demonstrate the   // console.table() method  // Accessing console moduleconst console = require('console');  // Calling console.table() // without construction ruleconsole.table([    { a: 1, b: 2 },     { a: 3, b: 7, c: 'y' }]);  // With construction ruleconsole.table([    { a: 1, b: 2 },     { a: 3, b: 7, c: 'y' }],    ["a", "b"]);
Run the app.js file using the following command:
node app.js
Output:
┌─────────┬───┬───┬─────┐
│ (index) │ a │ b │ c   │
├─────────┼───┼───┼─────┤
│    0    │ 1 │ 2 │     │
│    1    │ 3 │ 7 │ 'y' │
└─────────┴───┴───┴─────┘

┌─────────┬───┬───┐
│ (index) │ a │ b │
├─────────┼───┼───┤
│    0    │ 1 │ 2 │
│    1    │ 3 │ 7 │
└─────────┴───┴───┘

Example 2: Filename: app.js
// Node.js program to demonstrate the   // console.table() method  // Accessing console moduleconst console = require('console');  // Calling console.table() // fails to parse, so simply // print the argumentconsole.table("arg");  // Blank tableconsole.table([]);
Run the app.js file using the following command:
node app.js
Output:
arg
┌─────────┐
│ (index) │
├─────────┤
└─────────┘

Note: The above program will compile and run by using the node filename.js command.
Reference: https://nodejs.org/api/console.html#console_console_table_tabulardata_properties
Node.js-console-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js crypto.createCipheriv() Method
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
Explain the working of Node.js
How to make Mongoose multiple collections using Node.js ?
Disabling Sessions in Passport.js
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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
HTML | <frame> src Attribute

28 May, 2019
The HTML <frame> src Attribute is used to specifies the document URL which is used to display in the frame.
Syntax:
<frame src="URL">
Attribute Values: It contains single value URL which specifies the source of the document. The possible value of the URL is:
absolute URL: It points to another website.
relative URL: It points to a file within a website.
Note: The <frame> src Attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html>  <head>    <title>HTML frame src Attribute</title></head>  <frameset cols="30%, 40%, 30%">    <frame name="top"           src="attr1.png" />    <frame name="main"            src="gradient3.png" />    <frame name="bottom"            src="col_last.png" /></frameset>  </html>
Output:
Supported Browsers: The browser supported by HTML <frame> src Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
Design a Tribute Page using HTML & CSS
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
How do you run JavaScript script through the Terminal?
Node.js | fs.writeFileSync() Method
Difference between var, let and const keywords in JavaScript
p5.js | fill() Function

04 Sep, 2019
The fill() function is used to fill the color to the shapes. This function supports all types of color object. For example RGB, RGBA, Hex CSS color, and all named color strings. The color object can also be set as string in terms of RGB, RGBA, Hex CSS color or named color string.
Syntax:
fill( v1, v2, v3, alpha )
or
fill( value )
or
fill( gray, alpha )
or
fill( values )
or
fill( color )
Parameters:
v1: It is used to set the red or hue value relative to current color range.
v2: It is used to set the green or saturation value relative to current color range.
v3: It is used to set the blue or brightness value relative to current color range.
alpha: It is used to set the transparency of the drawing.
value: It is used to set the value of color string.
gray: It is used to set the gray value.
values: It is an array containing the red, green, blue and alpha value.
color: It is used to set the stroke color.
Below examples illustrate the fill() function in p5.js:
Example 1:
function setup() {           // Create Canvas of given size     createCanvas(400, 300); }   function draw() {           // Set the background color     background(220);           // Use fill() function to fill color    fill('green')    // Draw a line     rect(50, 50, 150, 150);           // Use noFill() function    noFill();        // Draw a line     rect(100, 100, 150, 150); } 
Output:
Example 2:
function setup() {           // Create Canvas of given size     createCanvas(400, 300); }   function draw() {           // Set the background color     background(220);           // Use noFill() function    noFill();          // Draw a circle     circle(140, 100, 150);          // Use fill() function to fill color    fill('green');          // Draw a crrcle     circle(240, 100, 150); } 
Output:
Reference: https://p5js.org/reference/#/p5/fill
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
YAML - Indentation and Separation

Indentation and separation are two main concepts when you are learning any programming language. This chapter talks about these two concepts related to YAML in detail.
YAML does not include any mandatory spaces. Further, there is no need to be consistent. The valid YAML indentation is shown below −
a:
   b:
      - c
      -  d
      - e
f:
      "ghi"
You should remember the following rules while working with indentation in YAML:Flow blocks must be intended with at least some spaces with surrounding current block level.
You should remember the following rules while working with indentation in YAML:Flow blocks must be intended with at least some spaces with surrounding current block level.
Flow content of YAML spans multiple lines. The beginning of flow content begins with { or [.
Flow content of YAML spans multiple lines. The beginning of flow content begins with { or [.
Block list items include same indentation as the surrounding block level because - is considered as a part of indentation.
Block list items include same indentation as the surrounding block level because - is considered as a part of indentation.
Observe the following code that shows indentation with examples −
--- !clarkevans.com/^invoice
invoice: 34843
date   : 2001-01-23
bill-to: &id001
   given  : Chris
   family : Dumars
   address:
      lines: |
            458 Walkman Dr.
            Suite #292
      city    : Royal Oak
      state   : MI
      postal  : 48046
ship-to: *id001
product:
    - sku         : BL394D
      quantity    : 4
      description : Basketball
      price       : 450.00
   - sku         : BL4438H
      quantity    : 1
      description : Super Hoop
      price       : 2392.00
tax  : 251.42
total: 4443.52
comments: >
    Late afternoon is best.
    Backup contact is Nancy
    Billsmer @ 338-4338.
Strings are separated using double-quoted string. If you escape the newline characters in a given string, it is completely removed and translated into space value.
In this example we have focused listing of animals listed as an array structure with data type of string. Every new element is listed with a prefix of hyphen as mentioned as prefix.
-
 - Cat
 - Dog
 - Goldfish
-
 - Python
 - Lion
 - Tiger

Another example to explain string representation in YAML is mentioned below.
 errors:
      messages:
         already_confirmed: "was already confirmed, please try signing in"
         confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one"
         expired: "has expired, please request a new one"
         not_found: "not found"
         not_locked: "was not locked"
         not_saved:
            one: "1 error prohibited this %{resource} from being saved:"
            other: "%{count} errors prohibited this %{resource} from being saved:"

This example refers to the set of error messages which a user can use just by mentioning the key aspect and to fetch the values accordingly. This pattern of YAML follows the structure of JSON which can be understood by user who is new to YAML.
How to do Templating using ExpressJS in Node.js ?

08 Apr, 2021
Template Engine : A template engine basically helps us to use the static template files with minimal code. At runtime, the template engine replaces all the variables with actual values at the client-side.
Templating Engine Examples:
EJS (Embedded JavaScript Templating)
Pug
Mustache
In this article we are going to use EJS engine.
Setting up NPM packages:npm init -y
Setting up NPM packages:
npm init -y
Installing Dependencies npm install ejs express --save
npm install ejs express --save
Basic ExpressJS Server:
Javascript
const express = require('express');const app = express();    app.get('/' , (req , res)=>{    res.send("GeeksforGeeks");})  app.listen(4000 , ()=>{    console.log("server is running on port 4000");})
Output:
Adding of EJS Engine: Here we need to set ejs as our view engine.
Javascript
const express = require('express');const app = express();  app.set('view engine', 'ejs');  app.get('/' , (req , res)=>{    res.send("GeeksforGeeks");})  app.listen(4000 , ()=>{    console.log("server is running on port 4000");})
index.ejs
<!--Ejs File--><!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport"           content="width=device-width, initial-scale=1.0"></head><body>    <h1>GeeksforGeeks</h1></body></html>
Output:
output
Rendering of EJS file:
Javascript
const express = require('express');const app = express();  app.set('view engine', 'ejs');  app.get('/:name' , (req , res)=>{    res.render("index" , {        data : req.params.name    });})  app.listen(4000 , ()=>{    console.log("server is running on port 4000");})
Storing of data :  Here we have to store the data var name = "<%= data %>".
Javascript
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport"           content="width=device-width, initial-scale=1.0">    <script type="text/javascript">        var name = "<%= data %>"        setTimeout(()=>{        document.getElementById('hello').innerHTML = name;        },1000);    </script></head><body>    <h1 id="hello"></h1></body></html>
Output:
EJS-Templating Language
Express.js
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
How does jQuery Datepicker onchange event work?

To work with jQuery Datepicker onchange(), use the datepicker onSelect event. This will show which date we added currently and changed to.
You can try to run the following code to learn how to work jQuery Datepicker onchange:
Live Demo
<!Doctype html>
<html>
<head>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
   
  $(".date").datepicker({
    onSelect: function(dateText) {
      display("Selected date: " + dateText + ", Current Selected Value= " + this.value);
      $(this).change();
    }
  }).on("change", function() {
    display("Change event");
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
  });
 
  </script>
</head>
<body>
 
Date: <input type='text' class='date' id="datepicker">

</body>
</html>
turtle.down() method in Python

16 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The turtle.down() method is used to pull back the pen down on the screen. It gives drawing on moving to another position or direction. 
turtle.down() or turtle.pd() or turtle.pendown()

Here, this method can be called with three names as written above i.e; it has Aliases: pendown | pd | down. There is no argument required for this method.
Below is the implementation of the above method with some examples :
Example 1:
Python3
# import packageimport turtle    # forward the turtle (drawing)turtle.forward(50)  # up the turtleturtle.up()  # forward the turtle (no drawing)turtle.forward(50)  # down the turtleturtle.down()  # forward the turtle (drawing)turtle.forward(50)
Output :
Example 2:
Python3
# import packageimport turtle    # forward the turtle (drawing)turtle.forward(50)  # turn right 90 degreesturtle.right(90)  # up the turtleturtle.up()  # forward the turtle (no drawing)turtle.forward(50)  # down the turtleturtle.down()  # turn right 90 degreesturtle.right(90)  # forward the turtle (drawing)turtle.forward(50)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Static vs. Non-Static method in C#

Declare a member function as static. Such functions can access only static variables. The static functions exist even before the object is created.
A static class cannot be instantiated and can only contain static members.
Static methods is set using static keyword −
public static int getNum() {
   return num;
}
The following example demonstrates the use of static and non-static methods −
using System;

namespace StaticVarApplication {
   class StaticVar {
      public static int num;

      public void count() {
         num++;
      }

      public static int getNum() {
         return num;
      }
   }

   class StaticTester {
      static void Main(string[] args) {
         StaticVar s = new StaticVar();

         s.count();
         s.count();
         s.count();
         s.count();
         s.count();
         s.count();

         Console.WriteLine("Variable num: {0}", StaticVar.getNum());
         Console.ReadKey();
      }
   }
}
Tryit Editor v3.7

Tryit: The outline property
Character class \p{javaWhitespace} Java regex in java.

This character class \p{javaWhitespace} matches spaces. This class matches the characters which returns true when passed as a parameter to the isWhitespace() method of the java.lang.Character class.
 Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a string");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Regular expression
      String regex = "[\\p{javaWhitespace}]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Number of upper case characters: "+count);
   }
}
Enter a string
hello welcome to tutorialspoint
Number of upper case characters: 3
 Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main( String args[] ) {
      //Regular expression to match lower case letters
      String regex = "^\\p{javaWhitespace}+$";
      //Getting the input data
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      System.out.println("Strings with only upper case characters: ");
      for(int i=0; i<5;i++) {
         //Creating a Matcher object
         Matcher m = p.matcher(input[i]);
         if(m.matches()) {
            System.out.println(m.group());
         }
      }
   }
}
Enter 5 input strings:
Raju
RAMU
rahman
radha
SUnDar*
Strings with only upper case characters:
RAMU
Change Font Size in Matplotlib - GeeksforGeeks

03 Jan, 2021
Matplotlib library mainly used to create 2-dimensional graphs and plots. It has a module named pyplot which makes things easy for plotting. To change the font size in Matplotlib, the two methods given below can be used with appropriate parameters: 
Method 1: matplotlib.rcParams.update() 
rcParams is an instance of matplotlib library for handling default matplotlib values hence to change default the font size we just have to pass value to the key font.size
Approach:
Import module
Create data
Set rcParams.update() with value to the font.size key.
Normally plot the data
Display plot
Example:
Python3
import matplotlib.pyplot as plt  # setting font sizeto 30plt.rcParams.update({'font.size': 30})  x = [1, 2, 3, 4, 5, 6]y = [0, 2, 4, 6, 8, 10]  # plotting a plotplt.plot(x, y)  # setting title nameplt.title("Title")  # setting x axis labelplt.xlabel("x axis")  # setting y axis labelplt.ylabel("y axis")  plt.show()
Output:
Method 2: matplotlib.rc(group, **kwargs):
This function sets the current rc params. The group is the grouping for the rc like line, font, axes etc and kwargs is a dictionary attribute name and value pairs. 
Approach:
Import module
Create data
Create a font dictionary to pass value of the font
Supply this font value to rc()
Normally plot the data
Display data
Example:
Python3
import matplotlib.pyplot as plt    # creating a dictionaryfont = {'size': 10}  # using rc functionplt.rc('font', **font)  x = [1, 2, 3, 4, 5, 6]y = [0, 2, 4, 6, 8, 10]  # plotting a plotplt.plot(x, y)  # setting title nameplt.title("Title")  # setting x axis labelplt.xlabel("x axis")  # setting y axis labelplt.ylabel("y axis")  plt.show()
Output:
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
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 ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects
Instruction type DCR R in 8085 Microprocessor

In 8085 Instruction set, DCR is a mnemonic, which stands for ‘DeCRement’ and ‘R’ stands for any of the following registers, or memory location M pointed by HL pair.
R = A, B, C, D, E, H, L, or M

This instruction is used to decrease the content of register R. Also we can say it will subtract 1 from the register R content. And the decremented value will be stored on to the register R itself. As it is an arithmetic instruction, so all flags, except Cy flag, are affected depending on the result. In those assembly language code where we require down counter, there we can use this instruction. So by design as mentioned, Cy flag is not affected by the execution of this instruction.
As R can have any of the eight register values, so eight opcodes for this type of instruction are possible. It occupies only 1-Byte in memory.
Let us consider DCR M is an example instruction of this type. It is a 1-Byte instruction. Let us consider HL register pair is having initial content of 16-bit address as 4050H. And at memory location 4050H the content is ABH. So the result of execution of this instruction has been depicted in the following tracing table
(HL)
(4050H)
(F)
Actually, internally, 8085 performs this decrement operation by adding the 2's complement of 01H to ABH. So if the 4050H initial memory location content is 00H, then after execution of the instruction DCR M, the content would be FFH.
Summary − So this instruction DCR M requires 1-Bytes, 3-Machine Cycles (Opcode Fetch, Memory Read, Memory Write) and 10 T-States for execution as shown in the timing diagram.
Instant toString() method in Java

The range of values for a field can be obtained using the range() method in the Instant class in Java. This method requires a single parameter i.e. the ChronoField for which the range of values are required and it returns the range of valid values for the ChronoField.
A program that demonstrates this is given as follows −
 Live Demo
import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ValueRange;
public class Demo {
   public static void main(String[] args) {
      Instant i = Instant.now();
      ValueRange range1 = i.range(ChronoField.MILLI_OF_SECOND);
      ValueRange range2 = i.range(ChronoField.MICRO_OF_SECOND);
      ValueRange range3 = i.range(ChronoField.NANO_OF_SECOND);
      System.out.println("The current Instant is: " + i);
      System.out.println("\nThe Range of MILLI_OF_SECOND is: " + range1);
      System.out.println("The Range of MICRO_OF_SECOND is: " + range2);
      System.out.println("The Range of NANO_OF_SECOND is: " + range3);
}
}
The current Instant is: 2019-02-13T09:09:31.210Z
The Range of MILLI_OF_SECOND is: 0 - 999
The Range of MICRO_OF_SECOND is: 0 - 999999
The Range of NANO_OF_SECOND is: 0 - 999999999
Now let us understand the above program.
First, the current instant is displayed. Then the range of MILLI_OF_SECOND, MICRO_OF_SECOND and NANO_OF_SECOND is printed using the range() method. A code snippet that demonstrates this is as follows −
Instant i = Instant.now();
ValueRange range1 = i.range(ChronoField.MILLI_OF_SECOND);
ValueRange range2 = i.range(ChronoField.MICRO_OF_SECOND);
ValueRange range3 = i.range(ChronoField.NANO_OF_SECOND);
System.out.println("The current Instant is: " + i);
System.out.println("\nThe Range of MILLI_OF_SECOND is: " + range1);
System.out.println("The Range of MICRO_OF_SECOND is: " + range2);
System.out.println("The Range of NANO_OF_SECOND is: " + range3);
Jackson Annotations - @JsonUnwrapped

@JsonUnwrapped is used to unwrap values of objects during serialization or de-serialization.
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException, ParseException{
      ObjectMapper mapper = new ObjectMapper();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
      Date date = simpleDateFormat.parse("20-12-1984");
      Student.Name name = new Student.Name();
      name.first = "Jane";
      name.last = "Doe";
      Student student = new Student(1, name);
      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(student);
      System.out.println(jsonString);
   }
}
class Student {
   public int id;   
   @JsonUnwrapped
   public Name name;
   Student(int id, Name name){
      this.id = id;
      this.name = name;
   }
   static class Name {
      public String first;
      public String last;
   }
}
{
   "id" : 1,
   "first" : "Jane",
   "last" : "Doe"
}

 Print
 Add Notes
 Bookmark this page