code-rag-bench/online-tutorials huggingface dataset:
Arranging words in Ascending order in a string - JavaScript

Let’s say, we are required to write a JavaScript function that takes in a string and returns a new string with words rearranged according to their increasing length.
Following is the code −
const str = 'This is a sample string only';
const arrangeByLength = str => {
   const strArr = str.split(' ');
   const sorted = strArr.sort((a, b) => {
      return a.length - b.length;
   });
   return sorted.join(' ');
};
console.log(arrangeByLength(str));
Following is the output in the console −
a is This only sample string
How to use setInterval function call in JavaScript?

The setInterval() method is JavaScript is used to evaluate an expression at intervals. Here’s the syntax:
setInterval(function, interval_in_milliseconds, param1, param2, param3...)
Here, interval_in_milliseconds sets the intervals in milliseconds, after the code will execute.
param are the optional parameters, which is passend to the function.
You can try to run the following code to use setInterval() function call
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <p id="test"></p>
      <script>
         var myVar = setInterval(function(){ displayTimer() }, 500);
         function displayTimer() {
            var date = new Date();
            var time = date.toLocaleTimeString();
            document.getElementById("test").innerHTML = "Time: "+time;
         }
      </script>
    </body>
</html>
Draw a line in C++ graphics

In this tutorial, we will be discussing a program to draw a line in C++ graphics.
To implement different shapes and sizes, animations, graphics.h library is used in C++.
#include <graphics.h>
int main(){
   int gd = DETECT, gm;
   initgraph(&gd, &gm, "");
   line(150, 150, 450, 150);
   line(150, 200, 450, 200);
   line(150, 250, 450, 250);
   getch();
   closegraph();
   return 0;
}
do...while loop in C

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.
The syntax of a do...while loop in C programming language is −
do {
   statement(s);
} while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the  given condition becomes false.
#include <stdio.h>
 
int main () {

   /* local variable definition */
   int a = 10;

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

 Print
 Add Notes
 Bookmark this page
C Library - <time.h>

The time.h header defines four variable types, two macro and various functions for manipulating date and time.
Following are the variable types defined in the header time.h −
size_t
This is the unsigned integral type and is the result of the sizeof keyword.
clock_t
This is a type suitable for storing the processor time.
time_t is
This is a type suitable for storing the calendar time.
struct tm
This is a structure used to hold the time and date.
The tm structure has the following definition −
struct tm {
   int tm_sec;         /* seconds,  range 0 to 59          */
   int tm_min;         /* minutes, range 0 to 59           */
   int tm_hour;        /* hours, range 0 to 23             */
   int tm_mday;        /* day of the month, range 1 to 31  */
   int tm_mon;         /* month, range 0 to 11             */
   int tm_year;        /* The number of years since 1900   */
   int tm_wday;        /* day of the week, range 0 to 6    */
   int tm_yday;        /* day in the year, range 0 to 365  */
   int tm_isdst;       /* daylight saving time             */
};
Following are the macros defined in the header time.h −
NULL
This macro is the value of a null pointer constant.
CLOCKS_PER_SEC
This macro represents the number of processor clocks per second.
Following are the functions defined in the header time.h −
Returns a pointer to a string which represents the day and time of the structure timeptr.
Returns the processor clock time used since the beginning of an implementation defined era (normally the beginning of the program).
Returns a string representing the localtime based on the argument timer.
Returns the difference of seconds between time1 and time2 (time1-time2).
The value of timer is broken up into the structure tm and expressed in Coordinated Universal Time (UTC) also known as Greenwich Mean Time (GMT).
The value of timer is broken up into the structure tm and expressed in the local time zone.
Converts the structure pointed to by timeptr into a time_t value according to the local time zone.
Formats the time represented in the structure timeptr according to the formatting rules defined in format and stored into str.
Calculates the current calender time and encodes it into time_t format.

    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How can I set the content of an iframe without src using jQuery?

To set the content of an iframe without src, use the jQuery html() method. You can try to run the following code to learn how to set the content of an iframe without src attribute −
Live Demo
<html>
  <head>
   <title>jQuery Selector</title>
   <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">  
   </script>
   <script>
   $(document).ready(function() {
    var context = $('iframe')[0].contentWindow.document;
    var $body = $('body', context);
    $body.html('Hello World!');
  });
  </script>
  </head>
<body>
  <iframe style="border-style: dotted;"></iframe>  
</body>
</html>
Display Month of Year using Java Calendar

For using Calendar class, import the following package.
import java.util.Calendar;
Using the Calendar class, create an object.
Calendar calendar = Calendar.getInstance();
Now, create a string array of the month names.
String[] month = new String[] {"January", "February", "March", "April", "May", "June", "July", "August","September", "October", "November", "December" };
Display the month name.
month[calendar.get(Calendar.MONTH)]
The following is an example.
 Live Demo
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance();
      String[] month = new String[] {"January", "February", "March", "April", "May", "June", "July", "August","September", "October", "November", "December" };
      System.out.println("Current Month = " + month[calendar.get(Calendar.MONTH)]);
   }
}
The following is the output −
Current Month = Dec
Python Program to calculate the Round Trip Time (RTT)

Here we will see how Python can be used to get the Round Trip Time (RTT). The RTT is the time which is taken by the entire trip of a signal. It means the time between the starting time when a signal is sent and the receiving time of the acknowledge signal.
The RTT results varies on different parameters like.
The data transfer rate of the sender’s side.
The nature of the transmission media.
The actual distance between the sender and receiver.
The number of nodes between sender and receiver.
The amount of traffic on LAN.
Number of requests handled by intermediate points.
import time
import requests
import sys
   deffind_roundtriptime(url):
      initial_time = time.time() #Store the time when request is sent
      request = requests.get(url)
      ending_time = time.time() #Time when acknowledged the request
      elapsed_time = str(ending_time - initial_time)
   print('The Round Trip Time for {} is {}'.format(url, elapsed_time))
      find_roundtriptime(sys.argv[1])
$ python3 319.RoundTripTime.py https://www.tutorialspoint.com/
The Round Trip Time for https://www.tutorialspoint.com/ is 0.8301455974578857

$ python3 319.RoundTripTime.py https://www.google.com
The Round Trip Time for https://www.google.com is 0.5217089653015137
$
Update a column A if null, else update column B, else if both columns are not null do nothing with MySQL

For this, use IF() with IS NULL property. Let us first create a table −
mysql> create table DemoTable1976
   (
   FirstName varchar(20),
   LastName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1976 values('John','Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1976 values('John',NULL);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1976 values(NULL,'Miller');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1976 values('Chris','Brown');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1976;
This will produce the following output −
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| John      |      Doe |
| John      |     NULL |
| NULL      |   Miller |
| Chris     |    Brown |
+-----------+----------+
4 rows in set (0.00 sec)
Here is the query to update a column if null else update anther column, else if both columns are not null do nothing −
mysql> update DemoTable1976
   set FirstName=if(FirstName IS NULL,'David',FirstName),
   LastName=if(LastName IS NULL,'Brown',LastName);
Query OK, 2 rows affected (0.00 sec)
Rows matched: 4  Changed: 2 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1976;
This will produce the following output −
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| John      |      Doe |
| John      |    Brown |
| David     |   Miller |
| Chris     |    Brown |
+-----------+----------+
4 rows in set (0.00 sec)
Teradata - Create Tables

CREATE TABLE command is used to create tables in Teradata.
Following is the generic syntax of CREATE TABLE statement.
CREATE <SET/MULTISET> TABLE <Tablename> 
<Table Options> 
<Column Definitions> 
<Index Definitions>;

Table Options − Specifies the physical attributes of the table such as Journal and Fallback.
Table Options − Specifies the physical attributes of the table such as Journal and Fallback.
Column Definition − Specifies the list of columns, data types and their attributes.
Column Definition − Specifies the list of columns, data types and their attributes.
Index Definition − Additional indexing options such as Primary Index, Secondary Index and Partitioned Primary Index.
Index Definition − Additional indexing options such as Primary Index, Secondary Index and Partitioned Primary Index.
The following example creates a table called employee with FALLBACK option. The table contains 5 columns with EmployeeNo as the Unique Primary Index.
CREATE SET TABLE EMPLOYEE,FALLBACK ( 
   EmployeeNo INTEGER, 
   FirstName VARCHAR(30), 
   LastName VARCHAR(30), 
   DOB DATE FORMAT 'YYYY-MM-DD', 
   JoinedDate DATE FORMAT 'YYYY-MM-DD', 
   DepartmentNo BYTEINT 
) 
UNIQUE PRIMARY INDEX ( EmployeeNo );
Once the table is created, you can use SHOW TABLE command to view the Definition of the table.
SHOW TABLE Employee; 
*** Text of DDL statement returned. 
*** Total elapsed time was 1 second. 
------------------------------------------------------------------------  
CREATE SET TABLE EMPLOYEE ,FALLBACK , 
   NO BEFORE JOURNAL, 
   NO AFTER JOURNAL, 
   CHECKSUM = DEFAULT, 
   
   DEFAULT MERGEBLOCKRATIO (
      EmployeeNo INTEGER, 
      FirstName VARCHAR(30) CHARACTER SET LATIN NOT CASESPECIFIC, 
      LastName VARCHAR(30) CHARACTER SET LATIN NOT CASESPECIFIC, 
      DOB DATE FORMAT 'YYYY-MM-DD', 
      JoinedDate DATE FORMAT 'YYYY-MM-DD', 
      DepartmentNo BYTEINT
   ) 
UNIQUE PRIMARY INDEX ( EmployeeNo );

 Print
 Add Notes
 Bookmark this page
What is a singleton class in Java?

A singleton class in Java is the one which can have only one object.
The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
 The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance −
public class Singleton {
   private static Singleton singleton = new Singleton(); private Singleton() { }
   
   public static Singleton getInstance() {
      return singleton;
   }

   protected static void demoMethod() {
      System.out.println("demoMethod for singleton");
   }
}
Here is the main program file where we will create a singleton object −
public class SingletonDemo {
   public static void main(String[] args) {
      Singleton tmp = Singleton.getInstance();
      tmp.demoMethod();
   }
}
How to load and display an image on iOS App using Swift?

To load and display an image in iOS app we’ll first need to get an image.
Then we’ll drag that image to our project and select copy if required option and our application target.
Let’s see the rest with help of an example.
Now, we’ll create an UIImageView and assign the image to its image property, for that we’ll create a function.
func addImage(imageName img: String) {
   let imageView = UIImageView()
   imageView.frame = self.view.frame
   imageView.contentMode = .scaleAspectFit
   if let newImage = UIImage(named: img) {
      imageView.image = newImage
   }
   self.view.addSubview(imageView)
}
Now, we’ll call this code in our viewDidLoad or any other place where we need.
override func viewDidLoad() {
   super.viewDidLoad()
   self.addImage(imageName: "1.png")
}
When we run the above code on our application it produces the following result.
Bootstrap 4 Button .btn-outline-danger class

To set an outline on a button that indicates danger, you need to use the btn-outline-danger class in Bootstrap.
Set the outline in the <button> element −
<button type="button" class="btn btn-outline-danger">
  Danger Ahead
</button>
You can try to run the following code to implement the btn-outline-danger class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/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.0/js/bootstrap.min.js"></script>
  </head>
  <body>
    <h2>Danger Button</h2>
    <button type="button" class="btn btn-outline-danger">Danger Ahead</button>
  </body>
</html>
How to find through list of ids in MongoDB?

You can use $in operator to find through the list of ids in MongoDB. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.findListOfIdsDemo.insertOne({"StudentName":"Carol","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ecadd2f684a30fbdfd575")
}
> db.findListOfIdsDemo.insertOne({"StudentName":"Bob","StudentAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ecae42f684a30fbdfd576")
}
> db.findListOfIdsDemo.insertOne({"StudentName":"David","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ecaed2f684a30fbdfd577")
}
> db.findListOfIdsDemo.insertOne({"StudentName":"John","StudentAge":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ecaf82f684a30fbdfd578")
}
> db.findListOfIdsDemo.insertOne({"StudentName":"Mike","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ecb092f684a30fbdfd579")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.findListOfIdsDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c8ecadd2f684a30fbdfd575"),
   "StudentName" : "Carol",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c8ecae42f684a30fbdfd576"),
   "StudentName" : "Bob",
   "StudentAge" : 25
}
{
   "_id" : ObjectId("5c8ecaed2f684a30fbdfd577"),
   "StudentName" : "David",
   "StudentAge" : 22
}
{
   "_id" : ObjectId("5c8ecaf82f684a30fbdfd578"),
   "StudentName" : "John",
   "StudentAge" : 20
}
{
"_id" : ObjectId("5c8ecb092f684a30fbdfd579"),
"StudentName" : "Mike",
"StudentAge" : 23
}
Here is the query to find through the list of ids −
> var listOfIds = ['5c8ecae42f684a30fbdfd576', '5c8ecaf82f684a30fbdfd578'];
> var documentIds = listOfIds.map(function(myId) { return ObjectId(myId); });
> db.findListOfIdsDemo.find({_id: {$in: documentIds }}).pretty();
The following is the output −
{
   "_id" : ObjectId("5c8ecae42f684a30fbdfd576"),
   "StudentName" : "Bob",
   "StudentAge" : 25
}
{
   "_id" : ObjectId("5c8ecaf82f684a30fbdfd578"),
   "StudentName" : "John",
   "StudentAge" : 20
}
Python PostgreSQL - Create Database - GeeksforGeeks

23 Aug, 2021
In this article, we will discuss how to create database in PsotgreSQL using pysopg2 in Python.
CREATE DATABASE is one of the Data Definition Language ( DDL ) statements supported by the PostgreSQL Database Management System. It is used to create database in PostgreSQL. Database name should be always unique. If it already exists then it shows that the particular database already exists. 
Syntax: CREATE DATABASE database_name;
Python3
import psycopg2  # connection establishmentconn = psycopg2.connect(   database="postgres",    user='postgres',    password='password',    host='localhost',    port= '5432')  conn.autocommit = True  # Creating a cursor objectcursor = conn.cursor()  # query to create a database sql = ''' CREATE database products ''';  # executing above querycursor.execute(sql)print("Database has been created successfully !!");  # Closing the connectionconn.close()
Output
Database has been created successfully !!
Picked
Python PostgreSQL
Python Pyscopg2
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Python | Get dictionary keys as a list
Bar Plot in Matplotlib
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
loops in python
Python - Call function from another file
Ways to filter Pandas DataFrame by column values
Python | Convert set into a list
Python program to find number of days between two given dates
Node.js fs.unlinkSync() Method

08 Oct, 2021
The fs.unlinkSync() method is used to synchronously remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.rmdir() to remove a directory.Syntax:  
fs.unlinkSync( path )
Parameters: This method accepts one parameter as mentioned above and described below:  
path: It is a string, Buffer or URL which represents the file or symbolic link which has to be removed.
Below examples illustrate the fs.unlinkSync() method in Node.js:Example 1: This example removes a file from the filesystem.
javascript
// Node.js program to demonstrate the// fs.unlinkSync() method  // Import the filesystem moduleconst fs = require('fs');  // Get the files in current directory// before deletiongetFilesInDirectory();  // Delete readme.mdfs.unlinkSync("readme.md");console.log("\nFile readme.md is deleted");  // Get the files in current directory// after deletiongetFilesInDirectory();  // Function to get current filenames// in directory with specific extensionfunction getFilesInDirectory() {  console.log("\nFiles present in directory:");  let files = fs.readdirSync(__dirname);  files.forEach(file => {    console.log(file);  });}
Output: 
Files present in directory:
index.html
index.js
package.json
readme.md

File readme.md is deleted

Files present in directory:
index.html
index.js
package.json
Example 2: This example removes a symbolic link from the filesystem. 
javascript
// Node.js program to demonstrate the// fs.unlinkSync() method  // Import the filesystem moduleconst fs = require('fs');  // Creating symlink to filefs.symlinkSync(__dirname + "\\readme.md", "symlinkToReadme");console.log("\nSymbolic link to readme.md created");  // Function to get current filenames// in directory with specific extensiongetFilesInDirectory();  // Deleting symbolic link to readme.mdfs.unlinkSync("symlinkToReadme");console.log("\nSymbolic link to readme.md deleted")  getFilesInDirectory();  // Function to get current filenames// in directory with specific extensionfunction getFilesInDirectory() {  console.log("\nFiles present in directory:");  let files = fs.readdirSync(__dirname);  files.forEach(file => {    console.log(file);  });}
Output: 
Symbolic link to readme.md created

Files present in directory:
index.html
index.js
package.json
readme.md
symlinkToReadme

Symbolic link to readme.md deleted

Files present in directory:
index.html
index.js
package.json
readme.md
Reference: https://nodejs.org/api/fs.html#fs_fs_unlinksync_path
rajeev0719singh
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python String replace() Method

Python string  method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.
Following is the syntax for replace() method −
str.replace(old, new[, max])

old − This is old substring to be replaced.
old − This is old substring to be replaced.
new − This is new substring, which would replace old substring.
new − This is new substring, which would replace old substring.
max − If this optional argument max is given, only the first count occurrences are replaced.
max − If this optional argument max is given, only the first count occurrences are replaced.
This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument max is given, only the first count occurrences are replaced.
The following example shows the usage of replace() method.
#!/usr/bin/python

str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
print str.replace("is", "was", 3)
When we run above program, it produces following result −
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
Export List to CSV or text File in R

16 May, 2021
In this article, we will discuss how to export a list to CSV and text file using R Programming language. Exporting to both of these types of files can be done using capture.output() function. This function is mainly used to evaluate its arguments with the output being returned as a character string or sent to a file. By just changing the file name in the parameter user and change the format of the file in which he/she want to export the list.
Syntax: capture.output(..., file = NULL, append = FALSE, type = c(“output”, “message”), split = FALSE)
Parameter:
...: Expressions to be evaluated.
file: A file name or a connection, or NULL to return the output as a character vector.
append: logical. If file a file name or unopened connection, append or overwrite?
type, split: are passed to sink(), see there.
Returns: This function will be return the file to user which is specified to the function as the parameter.
In this approach user first need to create the list of any datatype and then need to call capture.output() function with the created list by the user and name of the file into which the user has to export the created list as the parameter of the function.
For this simply pass the destination of the file to created along with its name. It will create a CSV file and add a list to it.
Program:
R
gfg_list <- list(c("geeks"),c("for"), c("geeks"))  capture.output(gfg_list, file = "gfg_list.csv")
Output:
For this simply pass the destination of the file to created along with its name. It will create a text file and add a list to it.
Program:
R
gfg_list <- list(c("geeks"),c("for"), c("geeks"))  capture.output(gfg_list, file = "gfg_list_txt.txt")
Output:
Picked
R-CSV
R-FileHandling
R-List
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Print all the prime numbers between ‘m’ and ‘n’ in PL/SQL

10 May, 2020
Prerequisite – PL/SQL Introduction
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Problem :Write a script in PL/SQL to display all the prime numbers between any two positive whole numbers.
Explanation :Here, all the prime numbers between any two numbers taken as input as the upper limit and the lower limit are returned.A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
In this implementation, the number of divisors of a number that occurs between the two limits is counted which should be 2 (1 and the number itself). If the number of divisors is 2, then that number is returned.
For example, consider the number 5. It has only two divisors: 1 and the number 5 itself.Hence, it is a prime number.
Examples :
Input: 10  20
Output: 11 13 17 19

Input: 20  30
Output: 23 29  
Below is the implementation :
   DECLARE--the upper limit and the lower limit are taken as user inputs.   low number(2);   high number(2);   n number(2);   m number(2);   c number(20);BEGIN   dbms_output.put_line('Enter the lower and higher limit:');   low:=&low;   high:=&high;--The main operation happens in this loop  for n IN low.. high     loop       c:=0;       for m IN 1.. n         loop             if mod(n, m)=0 then             c:=c+1;            end if;            end loop;--the number of divisors for each number in the range is counted and then checked.            if c<=2 then                dbms_output.put_line(n||'\n');            end if;         end loop;           END;
Output :
Input: 
Enter the lower and higher limit:1  10
Output: 2
        3
        5
        7 
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
EmberJS - Classes and Instances

Class is a template or blue print, that has a collection of variables and functions, where as instances are related to the object of that class. Creating and extending the Ember class on Ember.Object is the main property of the Ember object model.
You can create new Ember class by using the Ember.Object's extend() method −
const Demo = Ember.Object.extend ({
   //code here
});
The above code creates new Ember class called "Demo" which inherits the properties from initializers, computed properties, etc. After creating the class, you need to create instance of it by using the create() method as shown below −
const state = Demo.create();

Using the above instance "state", access the properties by using the set and get accessor methods.
console.log(state.get('stateOn'));

You can change the "stateon" property by using the set method as shown below −
state.set('stateOn', true);

You can initialize the new instance by invoking the init() method. When declaring objects in the class, you need to initialize each instance with the init() method.
The following example uses the above mentioned properties and displays an alert message when an Ember object is initialized −
import Ember from 'ember';   //import ember module
export default function() {
   
   //new ember object
   const Demo = Ember.Object.extend ({
      init() {
         alert('The default property of stateOn is : ' + this.get('stateOn'));
      },
      stateOn: false
   });

   const state = Demo.create();   //new instance from object with create() method
   state.set('stateOn', true);
   console.log(state.get('stateOn'));
}
Now open the app.js file and add the following line on top of the file −
import classinstance from './classinstance';

Where, classinstance is a name of the file specified as "classinstance.js" and created under the "app" folder. Now, call the inherited "classinstance" at the bottom, before the export. This executes the classinstance function which is created in the classinstance.js file −
classinstance();

Run the ember server and you will receive the following output −
How to make text input non-editable using CSS?

26 Feb, 2019
The read-only attribute in HTML is used to create a text input non-editable. But in case of CSS, the pointer-events property is used to stop the pointer events.
Syntax:
pointer-events: none;
Example 1: This example shows two input text, in which one is non-editable.
<!DOCTYPE html> <html>     <head>         <title>             Disable Text Input field        </title>                   <style>        .inputClass {            pointer-events: none;         }        </style>    </head>           <body style = "text-align:center;">           <h1 style = "color:green;" >             GeeksForGeeks         </h1>                   Non-editable:<input class="inputClass"            name="input" value="GeeksForGeeks">                  <br><br>                  Editable:<input class="inputClass2"            name="input" value="GeeksForGeeks">    </body> </html>                    
Output:
Example 2: This example creates two input text, both of them are non-editable.
<!DOCTYPE html> <html>   <head>      <title>          Disable Text Input field      </title>              <style>         .inputClass {            pointer-events: none;          }      </style>   </head>        <body style = "text-align:center;">               <h1 style = "color:green;" >          GeeksForGeeks       </h1>              Non-editable:<input class="inputClass"        name="input" value="GeeksForGeeks">              <br><br>              Non-Editable:<input class="inputClass"        name="input" value="GeeksForGeeks">   </body></html>
Output:
CSS-Misc
Picked
Web-Programs
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
printf() function in PHP

The printf() function output a formatted string. It returns the length of the outputted string.
printf (format, argument1, argument2, ... )
format − Specifies the string and how to format the variables in it.
format − Specifies the string and how to format the variables in it.
The following are the possible format values −%% - Returns a percent sign%b - Binary number%c - The character according to the ASCII value%d - Signed decimal number (negative, zero or positive)%e - Scientific notation using a lowercase (e.g. 1.2e+2)%E - Scientific notation using a uppercase (e.g. 1.2E+2)%u - Unsigned decimal number (equal to or greather than zero)%f - Floating-point number (local settings aware)%F - Floating-point number (not local settings aware)%g - shorter of %e and %f%G - shorter of %E and %f%o - Octal number%s - String%x - Hexadecimal number (lowercase letters)%X - Hexadecimal number (uppercase letters)
The following are the possible format values −
%% - Returns a percent sign
%% - Returns a percent sign
%b - Binary number
%b - Binary number
%c - The character according to the ASCII value
%c - The character according to the ASCII value
%d - Signed decimal number (negative, zero or positive)
%d - Signed decimal number (negative, zero or positive)
%e - Scientific notation using a lowercase (e.g. 1.2e+2)
%e - Scientific notation using a lowercase (e.g. 1.2e+2)
%E - Scientific notation using a uppercase (e.g. 1.2E+2)
%E - Scientific notation using a uppercase (e.g. 1.2E+2)
%u - Unsigned decimal number (equal to or greather than zero)
%u - Unsigned decimal number (equal to or greather than zero)
%f - Floating-point number (local settings aware)
%f - Floating-point number (local settings aware)
%F - Floating-point number (not local settings aware)
%F - Floating-point number (not local settings aware)
%g - shorter of %e and %f
%g - shorter of %e and %f
%G - shorter of %E and %f
%G - shorter of %E and %f
%o - Octal number
%o - Octal number
%s - String
%s - String
%x - Hexadecimal number (lowercase letters)
%x - Hexadecimal number (lowercase letters)
%X - Hexadecimal number (uppercase letters)
%X - Hexadecimal number (uppercase letters)
argument1 − The argument to be inserted at the first %-sign in the format string.
argument1 − The argument to be inserted at the first %-sign in the format string.
argument2 − The argument to be inserted at the second %-sign in the format string.
argument2 − The argument to be inserted at the second %-sign in the format string.
The printf() function returns the length of the outputted string.
The following is an example −
 Live Demo
<?php
   $val = 2976;
   printf("%f",$val);
?>
The following is the output −
2976.000000
Let us see another example −
 Live Demo
<?php
   $s = "Welcome";
   printf("[%s]<b>",$s);
?>
The following is the output −
[Welcome]<br>
Sets union() function | Guava | Java

15 Nov, 2018
Guava’s Sets.union() returns an unmodifiable view of the union of two sets. The returned set contains all elements that are contained in either backing set. Iterating over the returned set iterates first over all the elements of set1, then over each element of set2, in order, that is not contained in set1.
Syntax:
public static <E> 
  Sets.SetView<E> 
    union(Set<? extends E> set1, 
          Set<? extends E> set2)

Return Value: This method returns an unmodifiable view of the union of two sets.
Example 1:
// Java code to show implementation// of Guava's Sets.union() method  import com.google.common.collect.Sets;import java.util.Set;  class GFG {      // Driver's code    public static void main(String[] args)    {        // Creating first set        Set<Integer>            set1 = Sets.newHashSet(1, 2, 3, 4, 5);          // Creating second set        Set<Integer>            set2 = Sets.newHashSet(3, 5, 7, 9);          // Using Guava's Sets.union() method        Set<Integer>            answer = Sets.union(set1, set2);          // Displaying the union of set set1 and set2        System.out.println("Set 1: "                           + set1);        System.out.println("Set 2: "                           + set2);        System.out.println("Set 1 union Set 2: "                           + answer);    }}
Set 1: [1, 2, 3, 4, 5]
Set 2: [9, 3, 5, 7]
Set 1 union Set 2: [1, 2, 3, 4, 5, 9, 7]

Example 2:
// Java code to show implementation// of Guava's Sets.union() method  import com.google.common.collect.Sets;import java.util.Set;  class GFG {      // Driver's code    public static void main(String[] args)    {        // Creating first set        Set<String>            set1 = Sets.newHashSet("G", "e", "e", "k", "s");          // Creating second set        Set<String>            set2 = Sets.newHashSet("g", "f", "G", "e");          // Using Guava's Sets.union() method        Set<String>            answer = Sets.union(set1, set2);          // Displaying the union of set set1 and set2        System.out.println("Set 1: "                           + set1);        System.out.println("Set 2: "                           + set2);        System.out.println("Set 1 union Set 2: "                           + answer);    }}
Set 1: [k, s, e, G]
Set 2: [e, f, g, G]
Set 1 union Set 2: [k, s, e, G, f, g]

java-guava
java-set
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Objects

In real life, a car is an object. 
A car has properties like weight and color, and methods like start and stop:
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed 
at different times.
You have already learned that JavaScript variables are 
containers for data values.
This code assigns a simple value (Fiat) to 
a variable named car: 
Objects are variables too. But objects can contain many 
values. 
This code assigns many values (Fiat, 500, white) to a
variable 
named car:
The values are written as name:value pairs (name and value separated by a 
colon).
It is a common practice to declare objects with the const keyword.
Learn more about using const with objects in the chapter: JS Const.
You define (and create) a JavaScript object with an object literal:
Spaces and line breaks are not important. An object definition can span multiple lines: 
The name:values pairs in JavaScript objects are called properties:
You can access object properties in two ways: 
or
JavaScript objects are containers for named values called properties.
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function 
definitions.
A method is a function stored as a property.
In the example above, this refers to the person object.
I.E. this.firstName means the firstName property of this.
I.E. this.firstName means the firstName property of person.
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
The JavaScript this Tutorial
In a function definition, this refers to the "owner" of the function.
In the example above, this is the person object that "owns" the 
fullName function.
In other words, this.firstName means the firstName property of this object.
Learn more about this in The JavaScript this Tutorial.
You access an object method with the following syntax:
If you access a method without the () parentheses, it 
will return the function definition:
When a JavaScript variable is declared with the keyword "new", the variable is 
created as 
an object: 
Avoid String, Number, and Boolean objects. They complicate your code and slow down  
execution speed.
You will learn more about objects later in this tutorial.
Alert "John" by extracting information from the person object.
const person = {
  firstName: "John",
  lastName: "Doe"
};

alert();

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to delete specific cache data in ReactJS ?

26 Apr, 2021
We can use the following approach in ReactJS to delete specific cache data in ReactJS. We can delete specific cache data from the browser as per the user requirement. Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested.
Approach: Follow these simple steps in order to delete specific cache data in ReactJS. We have created our deleteSpecificCache function which takes the cache name and deletes it from the browser cache. When we click on the button, the function is triggered, and the given cache gets deleted from the browser and, and we see an alert popup.
Creating React Application:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import * as React from 'react';  export default function App() {    // Function to delete our give cache  const deleteSpecificCache = (cacheName) => {    if ("caches" in window) {        caches.delete(cacheName).then(function (res) {            alert(cacheName)            return res;        });    }};    return (    <div style={{ height: 500, width: '80%' }}>      <h4>How to delete specific cache data in ReactJS?</h4>      <button onClick={()=>deleteSpecificCache('MyCache')} >        Delete Specific Cache</button>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Installation of Node.js on Linux
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?
Differences between Functional Components and Class Components in React
How to Get Coordinate Of Screen in Python Turtle ?

21 Jun, 2022
Turtle is a special feature in python which contains a graphical library. In this article we will learn how to Get Coordinate Of Screen in Python Turtle. 
Turtle has many built in function to create this program we use following.
import turtle –> This is the python library which allow us to access turtle library.
Turtle()–> This Method is used to make object.
onscreenclick(functionname,1) –> This is turtle function which sends the coordinate  to function; 1 is for left click and 3 is for Right click
speed()–> This is used to increase or decrease the speed of turtle pointer.
listen()–> This allows the server to listen to incoming connections.
done()–> This is used to hold the screen.   
 
Python3
# turtle libraryimport turtle #This to make turtle objecttess=turtle.Turtle()  # self defined function to print coordinatedef buttonclick(x,y):    print("You clicked at this coordinate({0},{1})".format(x,y))  #onscreen function to send coordinateturtle.onscreenclick(buttonclick,1)turtle.listen()  # listen to incoming connectionsturtle.speed(10) # set the speedturtle.done()    # hold the screen
Above Output shows that coordinates are print where pointer clicks on the Screen
varshagumber28
simmytarika5
Python-turtle
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
How to show and hide widgets in Tkinter?

Tkinter is a Python library which is used to create and develop GUI-based applications.Let us suppose that we have to create an application such that we can show or hide the widgets.
In order to display/show the widget, use pack() geometry manager
To hide any widget from the application, use pack_forget() method.
Let us take this example to understand how to show/hide widgets −
# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Define the style for combobox widget
style = ttk.Style()
style.theme_use('xpnative')

# Define a function to show/hide widget
def show_widget():
   label.pack()
def hide_widget():
   label.pack_forget()
   b1.configure(text="Show", command=show_widget)

# Add a label widget
label = ttk.Label(win, text="Eat, Sleep, Code and Repeat", font=('Aerial 11'))
label.pack(pady=30)

# Add a Button widget
b1 = ttk.Button(win, text="Hide", command=hide_widget)
b1.pack(pady=20)

win.mainloop()
Running the above code will open a window that will have a Button to show/hide the widgets from the application.
Now, click the button to display/hide the label text from the window.
Arduino - micros () function

The micros() function returns the number of microseconds from the time, the Arduino board begins running the current program. This number overflows i.e. goes back to zero after approximately 70 minutes. On 16 MHz Arduino boards (e.g. Duemilanove and Nano), this function has a resolution of four microseconds (i.e. the value returned is always a multiple of four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has a resolution of eight microseconds.
micros () ;

This function returns number of microseconds since the program started (unsigned long)
unsigned long time; void setup() { 
   Serial.begin(9600); 
} 

void loop() { 
   Serial.print("Time:");
   time = micros(); //prints time since program started
   Serial.println(time); // wait a second so as not to send massive amounts of data
   delay(1000); 
}

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
What are runtime errors in JavaScript?

There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors. Runtime errors, also called exceptions, occur during execution (after compilation/interpretation). For example, the following line causes a runtime error because here the syntax is correct, but at runtime, it is trying to call a method that does not exist.
<script>
   <!--
      window.printme();
   //-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution.