code-rag-bench/online-tutorials huggingface dataset:
Write a Python code to swap last two rows in a given dataframe

Assume you have dataframe and the result for swapping last two rows,
Before swapping
  Name    Age Maths Science English
0 David   13   98      75    79
1 Adam    12   59      96    45
2 Bob     12   66      55    70
3 Alex    13   95      49    60
4 Serina  12   70      78    80
After swapping
   Name  Age Maths Science English
0 David   13   98    75    79
1 Adam    12   59    96    45
2 Bob     12   66    55    70
3 Serina  12   70    78    80
4 Alex    13   95    49    60
To solve this, we will follow the approach given below −
Define a dataframe
Define a dataframe
Create temp data to store last row. It is defined below,
Create temp data to store last row. It is defined below,
temp = df.iloc[-1]
Swap second row values to first row and assign temp data to second row. It is defined below,
Swap second row values to first row and assign temp data to second row. It is defined below,
df.iloc[-1] = df.iloc[-2]
df.iloc[-2] = temp
Let’s see the below implementation to get better understanding −
import pandas as pd
data = {'Name': ['David', 'Adam', 'Bob', 'Alex', 'Serina'],
         'Age' : [13,12,12,13,12],
         'Maths': [98, 59, 66, 95, 70],
         'Science': [75, 96, 55, 49, 78],
         'English': [79, 45, 70, 60, 80]}
df = pd.DataFrame(data)
print("Before swapping\n",df)
temp = df.iloc[-1]
df.iloc[-1] = df.iloc[-2]
df.iloc[-2] = temp
print("After swapping\n",df)
Before swapping
  Name    Age Maths Science English
0 David   13    98    75    79
1 Adam    12    59    96    45
2 Bob     12    66    55    70
3 Alex    13    95    49    60
4 Serina  12    70    78    80
After swapping
   Name   Age Maths Science English
0 David    13   98    75    79
1 Adam     12   59    96    45
2 Bob      12   66    55    70
3 Serina   12   70    78    80
4 Alex    13    95    49    60
YAML - Comments

Now that you are comfortable with the syntax and basics of YAML, let us proceed further into its details. In this chapter, we will see how to use comments in YAML.
YAML supports single line comments. Its structure is explained below with the help of an example −
# this is single line comment.

YAML does not support multi line comments. If you want to provide comments for multiple lines, you can do so as shown in the example below −
# this
# is a multiple
# line comment

The features of comments in YAML are given below −
A commented block is skipped during execution.
A commented block is skipped during execution.
Comments help to add description for specified code block.
Comments help to add description for specified code block.
Comments must not appear inside scalars.
Comments must not appear inside scalars.
YAML does not include any way to escape the hash symbol (#) so within multi-line string so there is no way to divide the comment from the raw string value.
YAML does not include any way to escape the hash symbol (#) so within multi-line string so there is no way to divide the comment from the raw string value.
The comments within a collection are shown below −
key: #comment 1
   - value line 1
   #comment 2
   - value line 2
   #comment 3
   - value line 3

The shortcut key combination for commenting YAML blocks is Ctrl+Q.
If you are using Sublime Text editor, the steps for commenting the block are mentioned below −
Select the block. Use “CTRL + /” on Linux and Windows and “CMD+/” for Mac operating system. Execute the block.
Note that the same steps are applicable if you are using Visual Studio Code Editor. It is always recommended to use Sublime Text Editor for creating YAML files as it supported by most operating systems and includes developer friendly shortcut keys.

    33 Lectures 
     44 mins

 Tarun Telang
 Print
 Add Notes
 Bookmark this page
Check if any interval completely overlaps the other in Python

Suppose, we are given a set of intervals that consists of values (a,b) where a represents the starting time and b represents the ending time of an event. Our task is to check whether any of these intervals completely overlap any other interval in this set. If any of the intervals overlap, we return the result as True, otherwise we return False.
So, if the input is like [(4,6), (10,12), (7,9), (13,16)], then the output will be False. If the input is like [(4,6), (4,9), (7,11), (5,8)], then the output will be True.
To solve this, we will follow these steps −
sort the list intervals
for i in range 1 to size of intervals, doif intervals[i, 1] <= intervals[i- 1, 1], thenreturn Truereturn False
if intervals[i, 1] <= intervals[i- 1, 1], thenreturn True
return True
return False
Let us see the following implementation to get better understanding −
 Live Demo
def solve(intervals):
intervals.sort()
for i in range(1, len(intervals)):
   if intervals[i][1] <= intervals[i- 1][1]:
      return True
   return False
intervals = [(4,6),(10,12),(7,9),(13,16)] 
intervals2 = [(4,6), (4,9), (7,11), (5,8)] 
print(solve(intervals))
print(solve(intervals2))
[(4,6),(10,12),(7,9),(13,16)] [(4,6), (4,9), (7,11), (5,8)]
False
True
JavaScript string.search() Method - GeeksforGeeks

18 Nov, 2021
The string.search() method is the inbuilt method in JavaScript that is used to search for a match in between regular expressions and a given string object.
Syntax:
string.search( A )
Parameters: This method accepts a single parameter A which holds the regular expression as an object.
Return Value: This function returns the index of the first match string in between regular expression and the given string object and returns -1 if no match is found. Indexing starts from zero (0) and in a first attempt, an alphabet is matched, then it does not check further. Simply, it returns the index of that first matched alphabet.
Example 1: The below example illustrate the string.search() method in JavaScript.
Javascript
<script>   // Taking input a string.  var string = "GeeksforGeeks";   // Taking a regular expression.  var re1 = /G/;  var re2 = /e/;  var re3 = /s/;   // Printing the index of matching alphabets  document.write(string.search(re1) + "<br>");  document.write(string.search(re2) + "<br>");  document.write(string.search(re3));< /script>
Output:
0
1
4
Example 2: This example returns -1, because of no match found in between regular expression and the input string.
Javascript
<script>   // Taking input a string.  var string = "GeeksforGeeks";   // Taking a regular expression.  var re1 = /p/;  var re2 = /1/;  var re3 = / /;  var re4 = /, /;   // Printing the index of matching alphabets  document.write(string.search(re1) + "<br>");  document.write(string.search(re2) + "<br>");  document.write(string.search(re3) + "<br>");  document.write(string.search(re4));< /script>
Output:
-1
-1
-1
-1
Supported Browser:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 4 and above
Opera 4 and above
Safari 1 and above
ysachin2314
bhaskargeeksforgeeks
javascript-functions
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Set the value of an input field in JavaScript
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
CSS position: fixed;

The position: fixed; property allows you to position element relative to the viewport. You can try to run the following code to implement CSS position: fixed;
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         div{
            position: fixed;
            bottom: 0;
            right: 0;
            width: 200px;
            border: 3px solid blue;
         }
      </style>
   </head>
   <body>
      <h2>position: fixed;</h2>
      <p>The position: fixed; property allows you to position element relative to the viewport.</p>
      <div>
         div has position: fixed;
      </div>
   </body>
</html>
Encrypting Data in Node.js - GeeksforGeeks

14 Oct, 2021
Encryption and Decryption in Node can be done by installing and implementing the ‘crypto’ library. If you have installed Node.js by manual build, then there is a chance that the crypto library is not shipped with it. You can run the following command to install the crypto dependency. 
npm install crypto --save
But you don’t need to do that if you have installed it using pre-built packages.Example for implementing crypto in Node.  
javascript
// Nodejs encryption with CTRconst crypto = require('crypto');const algorithm = 'aes-256-cbc';const key = crypto.randomBytes(32);const iv = crypto.randomBytes(16);  function encrypt(text) {let cipher = crypto.createCipheriv('aes-256-cbc',Buffer.from(key), iv);let encrypted = cipher.update(text);encrypted = Buffer.concat([encrypted, cipher.final()]);return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };}  function decrypt(text) {let iv = buffer.from(text.iv, 'hex');let encryptedText = Buffer.from(text.encryptedData, 'hex');let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);let decrypted = decipher.update(encryptedText);decrypted = Buffer.concat([decrypted, decipher.final()]);return decrypted.toString();}  var gfg = encrypt("GeeksForGeeks");console.log(gfg);console.log(decrypt(gfg));
Output  
 
sagartomar9927
simranarora5sos
Picked
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 path.resolve() Method
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
Node.js fs.readdir() Method
Express.js res.render() Function
Node.js First Application
Express.js express.Router() Function
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers
How to create footer to stay at the bottom of a Web page?
SELECT last entry without using LIMIT in MySQL?

For this, you can use subquery. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name) values('John Smith');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(Name) values('David Miller');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Name) values('Chris Brown');
Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+----+--------------+
| Id | Name         |
+----+--------------+
| 1  | John Smith   |
| 2  | David Miller |
| 3  | Chris Brown  |
+----+--------------+
3 rows in set (0.00 sec)
Here is the query to get the last entry without using LIMIT in MySQL −
mysql> select *from DemoTable -> where Id=(select max(Id) from DemoTable);
+----+-------------+
| Id | Name        |
+----+-------------+
| 3  | Chris Brown |
+----+-------------+
1 row in set (0.00 sec)
Implicit conversion from Byte to Decimal in C#

Byte represents an 8-bit unsigned integer.
Implicit conversion of an 8-bit unsigned integer (Byte) to a Decimal is possible. Let us see how.
Here’s our Byte value.
byte val = 16;
To implicitly convert, just assign the value as shown below −
decimal dec;
dec = val;
Let us see the complete example.
 Live Demo
using System;
public class Demo {
   public static void Main() {
      byte val = 16;
      decimal dec;
      // implicit
      dec = val;
      Console.WriteLine("Decimal ="+dec);
   }
}
Decimal =16
How can I display only unique record from MongoDB and ignore the duplicates?

To display only unique records, use distinct() in MongoDB. Let us create a collection with documents −
> db.demo613.insertOne({"Name":"Chris"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988bd4f6b89257f5584d88")
}
> db.demo613.insertOne({"Name":"Bob"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988bdbf6b89257f5584d89")
}
> db.demo613.insertOne({"Name":"Bob"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988bddf6b89257f5584d8a")
}
> db.demo613.insertOne({"Name":"David"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988be0f6b89257f5584d8b")
}
> db.demo613.insertOne({"Name":"Chris"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988be2f6b89257f5584d8c")
}
> db.demo613.insertOne({"Name":"Sam"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988be8f6b89257f5584d8d")
}
Display all documents from a collection with the help of find() method −
> db.demo613.find();
This will produce the following output −
{ "_id" : ObjectId("5e988bd4f6b89257f5584d88"), "Name" : "Chris" }
{ "_id" : ObjectId("5e988bdbf6b89257f5584d89"), "Name" : "Bob" }
{ "_id" : ObjectId("5e988bddf6b89257f5584d8a"), "Name" : "Bob" }
{ "_id" : ObjectId("5e988be0f6b89257f5584d8b"), "Name" : "David" }
{ "_id" : ObjectId("5e988be2f6b89257f5584d8c"), "Name" : "Chris" }
{ "_id" : ObjectId("5e988be8f6b89257f5584d8d"), "Name" : "Sam" }
Following is the query to get a unique record −
> db.demo613.distinct("Name");
This will produce the following output −
[ "Chris", "Bob", "David", "Sam" ]
XSLT <for-each>

<xsl:for-each> tag applies a template repeatedly for each node.
Following is the syntax declaration of <xsl:for-each> element
<xsl:for-each
   select = Expression >  
</xsl:for-each>

Select
XPath Expression to be evaluated in current context to determine the set of nodes to be iterated.
Parent elements
xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:foreach, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processinginstruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements.
Child elements
xsl:apply-imports, xsl:apply-templates, xsl:attribute, xsl:call-template, xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:number, xsl:processing-instruction, xsl:sort, xsl:text, xsl:value-of, xsl:variable.
This example creates a table of <student> element with its attribute rollno and its child <firstname>,<lastname><nickname> and <marks> by iterating over each student.
students.xml
<?xml version = "1.0"?> 
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?> 
<class> 
   <student rollno = "393"> 
      <firstname>Dinkar</firstname> 
      <lastname>Kad</lastname> 
      <nickname>Dinkar</nickname> 
      <marks>85</marks> 
   </student> 
   <student rollno = "493"> 
      <firstname>Vaneet</firstname> 
      <lastname>Gupta</lastname> 
      <nickname>Vinni</nickname> 
      <marks>95</marks> 
   </student> 
   <student rollno = "593"> 
      <firstname>Jasvir</firstname> 
      <lastname>Singh</lastname> 
      <nickname>Jazz</nickname> 
      <marks>90</marks> 
   </student> 
</class>
students.xsl
<?xml version = "1.0" encoding = "UTF-8"?> 
   <xsl:stylesheet version = "1.0" 
      xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
   <xsl:template match = "/"> 
      <html> 
         <body> 
            <h2>Students</h2> 
            <table border = "1"> 
               <tr bgcolor = "#9acd32"> 
                  <th>Roll No</th> 
                  <th>First Name</th> 
                  <th>Last Name</th> 
                  <th>Nick Name</th> 
                  <th>Marks</th> 
               </tr> 
					
               <xsl:for-each select = "class/student"> 
					
                  <tr> 
                     <td><xsl:value-of select = "@rollno"/></td> 
                     <td><xsl:value-of select = "firstname"/></td> 
                     <td><xsl:value-of select = "lastname"/></td> 
                     <td><xsl:value-of select = "nickname"/></td> 
                     <td><xsl:value-of select = "marks"/></td> 
                  </tr> 
               </xsl:for-each> 
					
            </table> 
         </body> 
      </html> 
   </xsl:template>  
</xsl:stylesheet>
 Print
 Add Notes
 Bookmark this page
Puppeteer - Type Selector

Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case.
For this, our first job is to identify the element. If a tag is used only one time in a page, we can use it as a type selector. If there are multiple elements with the same tag, only the first matching element on the page shall be identified.
The syntax for type selector is as follows −
const n = await page.$("h4")

In the below example, let us identify the highlighted element having tagname h4 and obtain its text - You are browsing the best resource for Online Education.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which is as follows:
Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).
The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.
Right-click on the folder where the node_modules folder is created, then click on the New file button.
Step 2 − Enter a filename, say testcase1.js.
Step 3 − Add the below code within the testcase1.js file created.
//Puppeteer library
const pt= require('puppeteer')
async function selectorType(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify element with type selector
   const n = await page.$("h4")
   //obtain text
   const text = await (await n.getProperty('textContent')).jsonValue()
   console.log("Text is: " + text)
}
selectorType()
Step 4 − Execute the code with the command given below −
node <filename>

So in our example, we shall run the following command −
node testcase1.js

After the command has been successfully executed, the text on the element - You are browsing the best resource for Online Education gets printed in the console.
 Print
 Add Notes
 Bookmark this page
CakePHP - Extending Views

Many times, while making web pages, we want to repeat certain part of pages in other pages. CakePHP has such facility by which one can extend view in another view and for this, we need not repeat the code again.
The extend() method is used to extend views in View file. This method takes one argument, i.e., the name of the view file with path. Don’t use extension .ctp while providing the name of the View file.
Make changes in the config/routes.php file as shown in the following program.
<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   $builder->connect('extend',['controller'=>'Extends','action'=>'index']);
   $builder->fallbacks();
});
Create an ExtendsController.php file at src/Controller/ExtendsController.php. Copy the following code in the controller file.
<?php
   namespace App\Controller;
   use App\Controller\AppController;
   class ExtendsController extends AppController{
      public function index(){
      }
   }
?>
Create a directory Extends at src/Template and under that folder create a View file called header.php. Copy the following code in that file.
<div align="center">
   <h1>Common Header</h1>
</div>
<?= $this->fetch('content') ?>
Create another View under Extends directory called index.php. Copy the following code in that file. Here, we are extending the above view header.php.
<?php $this->extend('header'); ?>
This is an example of extending view.
Execute the above example by visiting the following URL http://localhost/cakephp4/extend
Upon execution, you will receive the following output.
 Print
 Add Notes
 Bookmark this page
How to test remote computer connectivity using PowerShell?

To test the remote connectivity using PowerShell Test-Connection command is used. PowerShell also supports the Ping command and both the commands are almost produce the same output but Test- Connection cmdlet supports advanced parameters. See how both commands output look.
Ping Command −
PS C:\Temp> ping Test1-Win2k16
Pinging Test1-Win2k16 [192.168.0.108] with 32 bytes of data:
Reply from 192.168.0.108: bytes=32 time<1ms TTL=128
Reply from 192.168.0.108: bytes=32 time=1ms TTL=128
Reply from 192.168.0.108: bytes=32 time=1ms TTL=128
Reply from 192.168.0.108: bytes=32 time=1ms TTL=128
Ping statistics for 192.168.0.108:
   Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
   Minimum = 0ms, Maximum = 1ms, Average = 0ms
Test-Connection command output −
PS C:\Scripts> Test-Connection Test1-win2k16
Source    Destination    IPV4Address    IPV6Address
------    -----------    -----------    -----------
ADDC    Test1-win2k16    192.168.0.108
ADDC    Test1-win2k16    192.168.0.108
ADDC    Test1-win2k16    192.168.0.108
ADDC    Test1-win2k16    192.168.0.108
You can reduce the number of checks using -Count parameter. It is similar to -n in the ping command.
PS C:\Scripts> Test-Connection Test1-win2k16 -Count 2
Source    Destination    IPV4Address    IPV6Address
------    -----------    -----------    -----------
ADDC    Test1-win2k16    192.168.0.108
ADDC    Test1-win2k16    192.168.0.108
If you need to perform the above command quietly then you can use -Quiet parameter which gives a Boolean (True or False) output if the connection is successful or fails respectively.
PS C:\Scripts> Test-Connection Test1-win2k16 -Count 2 -Quiet
True
Test-Connection has the advantage that it supports common parameters like dealing with errors. In the below example, Any-Comp server doesn’t exist. To catch the error when the server is not reachable or server name doesn’t exist then we will use the ErrorAction parameter supported by cmdlet.
try {
   Test-Connection Any-Comp -Count 2 -ErrorAction Stop
}
catch {
   $_.Exception.Message
}
Testing connection to computer 'Any-Comp' failed: Cannot resolve the target name.
getkey - Unix, Linux Command

If there is no time limit specified,
the number of seconds left is reported as 0.

$ getkey
a$

The command waits until any key pressed and comes out immediately once the key is pressed
$ getkey -c 5
$ 

$ getkey -c 5
a$ 

In the first example the command waits for 5 seconds for key press and comes out even if no key is pressed.
In the second example the command comes out immediately after key is pressed.
$ getkey -c 5 -m "Press key within %d seconds"
Press key within 5 seconds

$ getkey -c 5 -m "Press key within %d seconds"
Press key within 4 seconds
...
...
$ getkey -c 5 -m "Press key within %d seconds"
Press key within 1 seconds

$ getkey -c 5 -m "Press key within %d seconds"
Press key within 0 seconds$

In the above example the command displays a message where the number of seconds keep decrementing till it reaches 0 or key is pressed.

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Convert number INT in minutes to TIME in MySQL?

To convert number INT in minutes to TIME in MySQL, you can use SEC_TO_TIME() function.
The syntax is as follows
select SEC_TO_TIME(yourIntColumnName*60) AS `anyAliasName` from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table convertNumberToMinute
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> NumberToMinute int
   -> );
Query OK, 0 rows affected (0.79 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into convertNumberToMinute(NumberToMinute) values(60);
Query OK, 1 row affected (0.12 sec)
mysql> insert into convertNumberToMinute(NumberToMinute) values(70);
Query OK, 1 row affected (0.21 sec)
mysql> insert into convertNumberToMinute(NumberToMinute) values(80);
Query OK, 1 row affected (0.15 sec)
mysql> insert into convertNumberToMinute(NumberToMinute) values(90);
Query OK, 1 row affected (0.13 sec)
mysql> insert into convertNumberToMinute(NumberToMinute) values(100);
Query OK, 1 row affected (0.22 sec)
mysql> insert into convertNumberToMinute(NumberToMinute) values(110);
Query OK, 1 row affected (0.07 sec)
mysql> insert into convertNumberToMinute(NumberToMinute) values(120);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from convertNumberToMinute;
The following is the output
+----+----------------+
| Id | NumberToMinute |
+----+----------------+
| 1  | 60             |
| 2  | 70             |
| 3  | 80             |
| 4  | 90             |
| 5  | 100            |
| 6  | 110            |
| 7  | 120            |
+----+----------------+
7 rows in set (0.00 sec)
Here is the query to convert number INT in minutes to TIME in MySQL
mysql> select SEC_TO_TIME(NumberToMinute*60) AS `MinuteDemo` from convertNumberToMinute;
The following is the output
+------------+
| MinuteDemo |
+------------+
| 01:00:00   |
| 01:10:00   |
| 01:20:00   |
| 01:30:00   |
| 01:40:00   |
| 01:50:00   |
| 02:00:00   |
+------------+
7 rows in set (0.00 sec)
Here is the query to display ‘NumberToMinute’ column
mysql> select NumberToMinute, SEC_TO_TIME(NumberToMinute*60) AS `MinuteDemo` from convertNumberToMinute;
The following is the output
+----------------+------------+
| NumberToMinute | MinuteDemo |
+----------------+------------+
| 60             | 01:00:00   |
| 70             | 01:10:00   |
| 80             | 01:20:00   |
| 90             | 01:30:00   |
| 100            | 01:40:00   |
| 110            | 01:50:00   |
| 120            | 02:00:00   |
+----------------+------------+
7 rows in set (0.00 sec)
Implicit conversion from Char to Decimal in C#

To implicitly convert char to a Decimal, firstly set a char.
char c = 'p';
To convert char to decimal, assign the value.
decimal dec;
dec = c;
Let us see the above example.
 Live Demo
using System;
public class Demo {
   public static void Main() {
      char c = 'p';
      decimal dec;
      Console.WriteLine("Implicit conversion from Char to Decimal");
      dec = c;
      Console.WriteLine("Decimal : "+dec);
   }
}
Implicit conversion from Char to Decimal
Decimal : 112
C++ Program To Convert Decimal Number to Binary

In a computer system, the binary number is expressed in the binary numeral system while the decimal number is in the decimal numeral system. The binary number is in base 2 while the decimal number is in base 10. Examples of decimal numbers and their corresponding binary numbers are as follows −
A program that converts the decimal numbers into binary is as follows −
 Live Demo
#include <iostream>
using namespace std;
void DecimalToBinary(int n) {
   int binaryNumber[100], num=n;
   int i = 0;
   while (n > 0) {
      binaryNumber[i] = n % 2;
      n = n / 2;
      i++;
   }
   cout<<"Binary form of "<<num<<" is ";
   for (int j = i - 1; j >= 0; j--)
   cout << binaryNumber[j];
   cout<<endl;
}
int main() {
   DecimalToBinary(15);
   DecimalToBinary(10);
   DecimalToBinary(18);
   DecimalToBinary(27);
   return 0;
}
Binary form of 15 is 1111
Binary form of 10 is 1010
Binary form of 18 is 10010
Binary form of 27 is 11011
In the above program, the DecimalToBinary function has binary value of the decimal number n and is stored in the array binaryNumber[]. A while loop is used and the result of the n modulus 2 operation is stored in binaryNumber[] for each iteration of the loop.
This is shown using the following code snippet.
while (n > 0) {
   binaryNumber[i] = n % 2;
   n = n / 2;
   i++;
}
After this, the binary number is displayed using a for loop. This is shown as follows −
cout<<"Binary form of "<<num<<" is ";
for (int j = i - 1; j >= 0; j--)
cout << binaryNumber[j];
The main() function contains only the function calls to DecimalToBinary() for various decimal numbers.
This is shown in the following code snippet.
DecimalToBinary(15);
DecimalToBinary(10);
DecimalToBinary(18);
DecimalToBinary(27);
Online SQL Minifier

Editable SQL Code
1234SELECT count(*),`Column1`,`Testing`, `Testing Three` FROM `Table1`WHERE Column1 = 'testing' AND ( (`Column2` = `Column3` OR Column4 >= NOW()) )GROUP BY Column1 ORDER BY Column3 DESC LIMIT 5,10X
Privacy Policy
Cookies Policy
Terms of Use
C# | Get the number of elements contained in the Queue

01 Feb, 2019
Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque. Queue.Count Property is used to get the number of elements contained in the Queue.
Properties:
Enqueue adds an element to the end of the Queue.
Dequeue removes the oldest element from the start of the Queue.
Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue.
The capacity of a Queue is the number of elements the Queue can hold.
As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array.
Queue accepts null as a valid value for reference types and allows duplicate elements.
Syntax:
myQueue.Count 

Here, myQueue is the name of the Queue.
Return Value: This property returns the number of elements contained in the Queue.
Example 1:
// C# code to Get the number of// elements contained in the Queueusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a Queue of strings        Queue<string> myQueue = new Queue<string>();          // Inserting the elements into the Queue        myQueue.Enqueue("Chandigarh");        myQueue.Enqueue("Delhi");        myQueue.Enqueue("Noida");        myQueue.Enqueue("Himachal");        myQueue.Enqueue("Punjab");        myQueue.Enqueue("Jammu");          // Displaying the count of elements        // contained in the Queue        Console.Write("Total number of elements in the Queue are : ");          Console.WriteLine(myQueue.Count);    }}
Total number of elements in the Queue are : 6

Example 2:
// C# code to Get the number of// elements contained in the Queueusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a Queue of Integers        Queue<int> myQueue = new Queue<int>();          // Displaying the count of elements        // contained in the Queue        Console.Write("Total number of elements in the Queue are : ");          // The function should return 0        // as the Queue is empty and it        // doesn't contain any element        Console.WriteLine(myQueue.Count);    }}
Total number of elements in the Queue are : 0

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1.count?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Generic-Namespace
CSharp-Generic-Queue
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Constructors
C# | Class and Object
Extension Method in C#
C# | Replace() Method
Difference between Ref and Out keywords in C#
Java - sin() Method

The method returns the sine of the specified double value.
double sin(double d)

Here is the detail of parameters −
d − A double data type.
d − A double data type.
This method returns the sine of the specified double value.
This method returns the sine of the specified double value.
public class Test {

   public static void main(String args[]) {
      double degrees = 45.0;
      double radians = Math.toRadians(degrees);

      System.out.format("The value of pi is %.4f%n", Math.PI);
      System.out.format("The sine of %.1f degrees is %.4f%n", degrees, Math.sin(radians));
   }
}
This will produce the following result −
The value of pi is 3.1416
The sine of 45.0 degrees is 0.7071
Java Math round() method with Example

11 Apr, 2018
The java.lang.Math.round() is a built-in math function which returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result after adding 1/2, and casting the result to type long.
If the argument is NaN, the result is 0.
If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.
Syntax:
public static int round(float val)
Parameter: 
val - floating-point value to be rounded to an integer. 

Returns:The method returns the value of the argument rounded to the nearest int value.
Example: To show working of java.lang.Math.round() function
// Java program to demonstrate working// of java.lang.Math.round() methodimport java.lang.Math;    class Gfg {        // driver code    public static void main(String args[])    {        // float numbers      float x = 4567.9874f;        // find the closest int for these floats      System.out.println(Math.round(x));              float y = -3421.134f;        // find the closest int for these floats      System.out.println(Math.round(y));                double positiveInfinity = Double.POSITIVE_INFINITY;        // returns the Integer.MAX_VALUE value when       System.out.println(Math.round(positiveInfinity));              }}
Output:
4568
-3421
9223372036854775807

Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
Collections in Java
Singleton Class in Java
Set in Java
Initializing a List in Java
Introduction to Java
Multithreading in Java
Constructors in Java
Exceptions in Java
Difference between std::swap and std::vector::swap

19 Jul, 2021
The std::swap is a general function used to exchange the given values whereas the std::vector::swap is a specialized function that can swap all the contents of two different vector containers.Below are some major key differences between std::swap and std::vector::swap,  
In practice, both the functions will swap the contents of vectors in O(1) time and give the same performance. For consistency, it may be better to use the std::swap.
Program 1: To illustrate swapping of two vectors using std::swap().  
CPP
// CPP program to illustrate swapping// of two vectors using std::swap() #include <bits/stdc++.h>using namespace std; int main(){    vector<int> v1 = { 1, 2, 3 };    vector<int> v2 = { 4, 5, 6 };     // swapping the above two vectors    // by traversing and swapping each element    for (int i = 0; i < 3; i++) {        swap(v1[i], v2[i]);    }     // print vector v1    cout << "Vector v1 = ";    for (int i = 0; i < 3; i++) {        cout << v1[i] << " ";    }     // print vector v2    cout << "\nVector v2 = ";    for (int i = 0; i < 3; i++) {        cout << v2[i] << " ";    }     return 0;}
Vector v1 = 4 5 6 
Vector v2 = 1 2 3
 
Program 2: To illustrate swapping of two vectors using std::vector::swap().  
CPP
// CPP program to illustrate swapping// of two vectors using std::vector::swap() #include <bits/stdc++.h>using namespace std; int main(){    vector<int> v1 = { 1, 2, 3 };    vector<int> v2 = { 4, 5, 6 };     // swapping the above two vectors    // using std::vector::swap    v1.swap(v2);     // print vector v1    cout << "Vector v1 = ";    for (int i = 0; i < 3; i++) {        cout << v1[i] << " ";    }     // print vector v2    cout << "\nVector v2 = ";    for (int i = 0; i < 3; i++) {        cout << v2[i] << " ";    }     return 0;}
Vector v1 = 4 5 6 
Vector v2 = 1 2 3
 
bhagatea
CPP-Functions
cpp-vector
STL
C++
Difference Between
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Substring in C++
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
JavaScript | Passing parameters to a callback function - GeeksforGeeks

29 Jun, 2020
Callback Function:Passing a function to another function or passing a function inside another function is known as a Callback Function.In other words, a callback is an already defined function which is passed as an argument to the other code
Syntax:
function geekOne(z) { alert(z); }
function geekTwo(a, callback) {
    callback(a);        
}
prevfn(2, newfn);
Above is an example of a callback variable in JavaScript function.“geekOne” accepts an argument and generates an alert with z as the argument.“geekTwo” accepts an argument and a function.“geekTwo” moves the argument it accepted to the function to passed it to.“geekOne” is the callback function in this case.
Example:
<script>function GFGexample(fact, callback){   var myFact = "GeeksforGeeks Is Awesome, " + fact;  callback(myFact); // 2}  function logFact(fact){  document.write(fact);}GFGexample("Learning is easy since", logFact);</script>
Output:
GeeksforGeeks Is Awesome, Learning is easy since
Approach:In this, The “GFGexample” is the main function and accepts 2 arguments, the “callback” is the second one. The logFact function is used as the callback function. When we execute the “GFGexample” function, observe that we are not using parentheses to logFact since it is being passed as an argument. This is because we don’t want to run the callback spontaneously, we only need to pass the function to our main function for later execution.Make sure that if the callback function is expecting an argument. Then we supply those arguments while executing.Moreover, you don’t need to use the word “callback” as the argument name, JavaScript only needs to know it’s the correct argument name.
JavaScript callback functions are easy and efficient to use and are of great importance Web applications and code.
sai shiva hari prasad
javascript-functions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Form validation using HTML and JavaScript
JavaScript | console.log() with Examples
Installation of Node.js on Linux
Express.js express.Router() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Sort Python Dictionaries by Key or Value

When it is required to sort the dictionaries in Python using a key or a value, a dictionary can be defined, and key value pairs can be inserted into it. A ‘for’ loop can be used to iterate through the key value pair, and sort it using ‘sort’ method. This method can be called.
Below is the demonstration of the same −
def my_dict():

my_key_value_pair ={}

my_key_value_pair[2] = 56
my_key_value_pair[1] = 2
my_key_value_pair[5] = 12
my_key_value_pair[4] = 24
my_key_value_pair[6] = 18
my_key_value_pair[3] = 323

print ("The keys and values after sorting in alphabetical order based on the key are : ")

for i in sorted (my_key_value_pair) :
   print((i, my_key_value_pair[i]))

my_dict()
The keys and values after sorting in alphabetical order based on the key are :
(1, 2)
(2, 56)
(3, 323)
(4, 24)
(5, 12)
(6, 18)
A method is defined, that initially assigns an empty dictionary to a variable.
A method is defined, that initially assigns an empty dictionary to a variable.
The index of the empty dictionary is accessed and elements are assigned to indices.
The index of the empty dictionary is accessed and elements are assigned to indices.
The ‘sorted’ method is used to iterate through the dictionary, and display it on the console.
The ‘sorted’ method is used to iterate through the dictionary, and display it on the console.
This method is called.
This method is called.
The output is displayed on the console.
The output is displayed on the console.
How do I invoke a Java method when given the method name as a string?

The java.lang.reflect.Method class provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method). A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.
You can invoke the method using the class named method of the package java.lang.reflect. The constructor of this class accepts the method name in the form of a string. And you can invoke this method using the invoke() method.
import java.lang.reflect.Method;

public class DemoTest {
   private void sampleMethod(){
      System.out.println("hello");
   }
}
public class SampleTest {
   public static void main(String args[]) throws Exception{
      Class c = Class.forName("DemoTest");
      Object obj = c.newInstance();
      
      Method method = c.getDeclaredMethod("sampleMethod", null);
      method.setAccessible(true);
      method.invoke(obj, null);
   }
}
Python program to create a sorted merged list of two unsorted list

Here two user input list is given, the elements of two lists are unsorted. Our task is to merged these two unsorted array and after that sort the list.
Input: A [] = {100, 50, 150}
       B [] = {200, 30, 20}
Output: Merge List:{20, 30, 50, 100, 150, 200}

Step 1: first we create two user input list.
Step 2: Final merge list size is (size of the first list + the size of the second list).
Step 3: then sort two list using sort() method.
Step 4: Merge two sorted list and store it into a third list.
Step 5: Merging remaining elements of a[] (if any).Merging remaining elements of b[] (if any).
Step 6: display merged sorted list.

# Python program to merge two unsorted lists 
# in sorted order
# Function to merge array in sorted order
def unsortedarray (a, b, res, n, m):
   # Sorting a[] and b[]
   a.sort()
   b.sort()
   # Merge two sorted arrays into res[]
   i, j, k = 0, 0, 0
   while (i < n and j < m):
      if (a[i] <= b[j]):
         res[k] = a[i]
         i += 1
         k += 1
      else:
         res[k] = b[j]
         j += 1
         k += 1
   while (i < n):  # Merging remaining
      # elements of a[] (if any)
      res[k] = a[i]
      i += 1
      k += 1
   while (j < m):  # Merging remaining
      # elements of b[] (if any)
      res[k] = b[j]
      j += 1
      k += 1
# Driver code
A=list()
n=int(input("Enter the size of the First List ::"))
print("Enter the Element of First List ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k)
B=list()
m=int(input("Enter the size of the Second List ::"))
print("Enter the Element of Second List ::")
for i in range(int(n)):
   k=int(input(""))
   B.append(k)
# Final merge list
res = [0 for i in range(n + m)]
unsortedarray(A, B, res, n, m)
print ("Sorted merged list :")
for i in range(n + m):
   print (res[i],)
Enter the size of the First List: 4
Enter the Element of First List::
8
79
56
3
Enter the size of the Second List: 4
Enter the Element of Second List::
67
1
9
45
Sorted merged list:
1
3
8
9
45
56
67
79
How to detect search engine bots with PHP?

A search engine directory of the spider names can be used as a reference. Next, $_SERVER['HTTP_USER_AGENT']; can be used to check if the agent is a spider (bot).
Below is an example demonstrating the same −
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), "some_bot_name")) {
   //other steps that need to be used
}
Code explanation − The agent, along with the user agent is passed to the strtolower function, whose output in turn is passed to the strstr function. Both the user agent and the bot are compared to see if the spider is a bot or not.
Another option is shown below −
function _bot_detected() {
   return (
      isset($_SERVER['HTTP_USER_AGENT'])
      && preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT']);
}
Code explanation − The preg_match function helps in finding specific patterns in the string. To the preg_match function, the bot name is passed and it is compared with the user agent that detects if the spider is a search engine bot or not.
Reading and Writing Files in Perl

Once you have an open file handle in Perl, you need to be able to read and write information. There are a number of different ways of reading and writing data into the file.
The main method of reading the information from an open filehandle is the <FILEHANDLE> operator. In a scalar context, it returns a single line from the filehandle. For example −
#!/usr/bin/perl
print "What is your name?\n";
$name = <STDIN>;
print "Hello $name\n";
When you use the <FILEHANDLE> operator in a list context, it returns a list of lines from the specified filehandle. For example, to import all the lines from a file into an array −
#!/usr/bin/perl
open(DATA,"<import.txt") or die "Can't open data";
@lines = <DATA>;
close(DATA);
The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified −
getc FILEHANDLE
getc
If there was an error, or the filehandle is at end of file, then undef is returned instead.
The read function reads a block of information from the buffered filehandle: This function is used to read binary data from the file.
read FILEHANDLE, SCALAR, LENGTH, OFFSET
read FILEHANDLE, SCALAR, LENGTH
The length of the data read is defined by LENGTH, and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise data is placed after OFFSET bytes in SCALAR. The function returns the number of bytes read on success, zero at end of file, or undef if there was an error.
For all the different methods used for reading information from filehandles, the main function for writing information back is the print function.
print FILEHANDLE LIST
print LIST
print
The print function prints the evaluated value of LIST to FILEHANDLE, or to the current output filehandle (STDOUT by default). For example −
print "Hello World!\n";
Conversion of ArrayList to Array in C#

To convert an ArrayList to Array, use the ToArray() method in C#.
Firstly, set an ArrayList −
ArrayList arrList = new ArrayList();
arrList.Add("one");
arrList.Add("two");
arrList.Add("three");
Now, to convert, use the ToArray() method −
arrList.ToArray(typeof(string)) as string[];
Let us see the complete code −
 Live Demo
using System;
using System.Collections;

public class Program {
   public static void Main() {
      ArrayList arrList = new ArrayList();
      arrList.Add("one");
      arrList.Add("two");
      arrList.Add("three");

      string[] arr = arrList.ToArray(typeof(string)) as string[];

      foreach (string res in arr) {
         Console.WriteLine(res);
      }
   }
}
one
two
three