code-rag-bench/online-tutorials huggingface dataset:
Get first and last elements from Array and Vector in CPP - GeeksforGeeks

10 Nov, 2018
Given an array, find first and last elements of it.
Input: {4, 5, 7, 13, 25, 65, 98}
Output: First element: 4
Last element: 98

In C++, we can use sizeof operator to find number of elements in an array.
// C++ Program to print first and last element in an array#include <iostream>using namespace std;int main(){    int arr[] = { 4, 5, 7, 13, 25, 65, 98 };    int f, l, n;    n = sizeof(arr) / sizeof(arr[0]);    f = arr[0];    l = arr[n - 1];    cout << "First element: " << f << endl;    cout << "Last element: " << l << endl;    return 0;}
First element: 4
Last element: 98

We should not sizeof when arrays are passed as parameters, there we must pass size and use that size to find first and last elements.
// C++ Program to print first and last element in an array#include <iostream>using namespace std;  int printFirstLast(int arr[], int n){    int f = arr[0];    int l = arr[n - 1];    cout << "First element: " << f << endl;    cout << "Last element: " << l << endl;}  int main(){    int arr[] = { 4, 5, 7, 13, 25, 65, 98 };    int n = sizeof(arr) / sizeof(arr[0]);    printFirstLast(arr, n);    return 0;}
First element: 4
Last element: 98

In case of vectors in C++, there are functions like front and back to find first and last elements.
// C++ Program to find first and last elements in vector#include <iostream>#include <vector>using namespace std;int main(){    vector<int> v;      v.push_back(4);    v.push_back(5);    v.push_back(7);    v.push_back(13);    v.push_back(25);    v.push_back(65);    v.push_back(98);    cout << "v.front() is now " << v.front() << '\n';    cout << "v.back() is now " << v.back() << '\n';    return 0;}
v.front() is now 4
v.back() is now 98

We can use front and back even when vector is passed as a parameter.
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
Convert string to char array in C++
Pair in C++ Standard Template Library (STL)
Iterators in C++ STL
Inline Functions in C++
Multithreading in C++
List in C++ Standard Template Library (STL)
Display auto increment user id sequence number to begin from 001 in MySQL?

For this, use ZEROFILL and alter the table to begin from the same sequence −
alter table yourTableName
   change yourColumnName yourColumnName int(3) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT PRIMARY KEY;
To understand the above syntax, let us first create a table −
mysql> create table DemoTable1958
   (
   UserId int,
   UserName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)
Here is the query to alter generated sequence number to begin from 001:
mysql> alter table DemoTable1958
   change UserId UserId int(3) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT PRIMARY KEY;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0
Let us check the table description:
mysql> desc DemoTable1958;
This will produce the following output −
+----------+--------------------------+------+-----+---------+----------------+
| Field    | Type                     | Null | Key | Default | Extra          |
+----------+--------------------------+------+-----+---------+----------------+
| UserId   | int(3) unsigned zerofill | NO   | PRI | NULL    | auto_increment |
| UserName | varchar(20)              | YES  |     | NULL    |                |
+----------+--------------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1958(UserName) values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1958(UserName) values('David');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1958;
This will produce the following output −
+--------+----------+
| UserId | UserName |
+--------+----------+
|    001 | Chris    |
|    002 | David    |
+--------+----------+
2 rows in set (0.00 sec)
JavaScript string.replace() Method - GeeksforGeeks

06 Oct, 2021
Below is the example of the string.replace() Method.  
Example:  
javascript
<script>    var string = 'GeeksForGeeks';    var newstring = string.replace(/GeeksForGeeks/, 'GfG');     document.write(newstring);</script>
Output:  
GfG
The string.replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged.Syntax:  
str.replace(A, B)
Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string. Return Values: It returns a new string with replaced items.JavaScript code to show the working of this method: Code #1: Here the contents of the string GeeksForGeeks will be replaced with gfg.  
javascript
<script>     // Assigning a string    var string = 'GeeksForGeeks is a CS portal'; // Calling replace() methodvar newstring = string.replace(/GeeksForGeeks/, 'gfg'); // Printing replaced stringdocument.write(newstring); </script>
Output:  
gfg is a CS portal
Code #2:  
javascript
<script>     // Taking a regular expression    var re = /GeeksForGeeks/; // Taking a string as inputvar string = 'GeeksForGeeks is a CS portal'; // Calling replace() method to replace// GeeksForGeeks from string with gfgvar newstring = string.replace(re, 'gfg'); // Printing new string with replaced itemsdocument.write(newstring); </script>
Output:  
gfg is a CS portal
Supported Browsers:  
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 5.5 and above
Opera 4 and above
Safari 1 and above
 
ysachin2314
JavaScript-Methods
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Scala List size() method with example - GeeksforGeeks

26 Jul, 2019
The size() method is utilized to find the number of elements in the stated list.
Method Definition: def size(): Int
Return Type: It returns the number of elements in the stated list.
Example #1:
// Scala program of size()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(1, 2, 3, 4, 5)                  // Applying size method        val result = m1.size                  // Displays output        println(result)          }}
5

Example #2:
// Scala program of size()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating a list        val m1 = List(1, 0)                  // Applying size method        val result = m1.size                  // Displays output        println(result)          }}
2

Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Inheritance in Scala
Operators in Scala
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
How to get the first element of List in Scala
Break statement in Scala
How to Install Katoolin on Linux Mint? - GeeksforGeeks

06 Jun, 2019
When the question comes which Linux Distro is best for ethical hacking then this becomes typical to choose with. Everyone likes the different environment, looks and feel. At last, they find that there is no perfect Distro. There is one way that we can add all Kali Linux Hacking tools in any other Linux Debian based Distro using Katoolin. Katoolin is a script which helps to install all Kali Linux Hacking tools in any other Linux Debian based Distribution.
Step 1: To install Katoolin we need to clone a git hub repository using git command. In some OS (Linux based) Git is not pre-installed so we can install it by using the following command:
sudo apt-get install git
Step 2: After installing git we need to clone the git hub repository, copy the link from below
git clone https://github.com/LionSec/katoolin.git && cp katoolin/katoolin.py /usr/bin/katoolin
Step 3: After cloning the repository we need to give it executable permissions using the following command:
chmod +x /usr/bin/katoolin
Step 4: After completing all the steps just below command to confirm the installation.
katoolin
Using katoolin is very simple. You can enjoy all kali Linux repositories and install all hacking tools you need. Please note that before installing anything from katoolin you should remove previously added manual repositories from other sources to avoid errors.
Linux-Unix
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Top Programming Languages for Android App Development
How to Run a Python Script using Docker?
Setting up the environment in Java
Hello World in R Programming - GeeksforGeeks

22 Jul, 2021
When we start to learn any programming languages we do follow a tradition to begin HelloWorld as our first basic program. Here we are going to learn that tradition. An interesting thing about R programming is that we can get our things done with very little code.
Before we start to learn to code, let’s see the process of where to download the needed Softwares and programs.
Go to the official site of R programming and download R for windows(or Mac).
Install IDE like Rstudio, RTVS, StatET for running programs(you can download Rstudio here).We can write and run programs in IDE, but you have to download R before installing IDE.
For the HelloWorld program, we just need a print function. No need of any packages or main functions, just a simple print function is enough.
print("HelloWorld")
Output:
"HelloWorld" 

print() is a function which is used to print the values on to the output screen. It also has arguments, we can use it if needed. For example, in the above program, the output is printed with quotes by default we can remove it if needed.
print("HelloWorld", quote=FALSE)
Output:
HelloWorld  

We passed the argument named quote in print function which value is set to be false to remove the quotes.
There are many ways to run an R program:
Method 1: Using command prompt or terminalWrite your code in notepad or any text editor, save it as “helloworld.r”, Run it in command prompt or terminal using the command “Rscript helloworld.r”.
Write your code in notepad or any text editor, save it as “helloworld.r”,
 Run it in command prompt or terminal using the command “Rscript helloworld.r”.
Method 2: Using an online IDEThere are many online IDEs(click here) available. We can use that without the need of installing or downloading anything.
Method 3: Using IDE like Rstudio, RTVS, StatETYou can download and install these IDE in your system and can write and run the program there. Rstudio & statET(Eclipse software)is available for Windows, Mac, and Linux. RTVS presently available only on windows.
Picked
R-basics
R-Input/Output
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Convert Factor to Numeric and Numeric to Factor in R Programming
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
What is the RemoveAt method in C# lists?

The RemoveAt() method in C# is used to remove an element in a list at a position you set.
Firstly, set elements in the list −
var subjects = new List();
subjects.Add("Physics");
subjects.Add("Chemistry");
subjects.Add("Biology");
subjects.Add("Science");
To remove an element, set the index from where you want to eliminate the element. The following is to remove an element from the 3rd position −
subjects.RemoveAt(2);
Let us see the complete code −
 Live Demo
using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(string[] args) {
      var subjects = new List();
      subjects.Add("Physics");
      subjects.Add("Chemistry");
      subjects.Add("Biology");
      subjects.Add("Science");

      Console.WriteLine("ELEMENTS:");
      foreach (var sub in subjects) {
         Console.WriteLine(sub);
      }

      // remove element at 3rd position
      subjects.RemoveAt(2);
      Console.WriteLine("After removing an element:");

      foreach (var sub in subjects) {
         Console.WriteLine(sub);
      }
   }
}
ELEMENTS:
Physics
Chemistry
Biology
Science
After removing an element:
Physics
Chemistry
Science
XQuery - distinct-values Function

The distinct-values function is used to get the sequence containing unique items present in a given sequence.
distinct-values($seq as item()*)
$seq − provided sequence. A sequence can contain 0 or more items.
$seq − provided sequence. A sequence can contain 0 or more items.
let $items := (1,2,4,4,5,5)
let $unique-items := distinct-values($items)
return
   <result>   
   
      <items>
      {
         for $item in $unique-items
         return <item>{$item}</item>
      }
      </items>
   
   </result>
<result>
   <items>
      <item>1</item>
      <item>2</item>
      <item>4</item>
      <item>5</item>
   </items>
</result>

In order to test the above-mentioned functionality, replace the contents of books.xqy (mentioned in Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program to verify the result.
 Print
 Add Notes
 Bookmark this page
Weight sum of a nested array in JavaScript

We are required to write a JavaScript function that takes in a nested array, arr (nested up to any
level) as the only argument.
The function should calculate the weighted sum of the nested array and return that sum.
For calculating nested sum, we multiply a specific element with its level of nesting and add
throughout the array.
For example, if the input to the function is −
const arr = [4, 7, [6, 1, [5, 2]]];
Then the output should be −
const output = 46;
The sum will be calculated like this −
(4 * 1) + ( 7 * 1) + (6 * 2) + (1 * 2) + (5 * 3) + (2 * 3) = 46
The code for this will be −
const arr = [4, 7, [6, 1, [5, 2]]];
const findWeightedSum = (arr = [], level = 1, res = 0) => {
   for(let i = 0; i < arr.length; i++){
      if(typeof arr[i] === 'number'){
         res += (level * arr[i]);
      }else if(Array.isArray(arr[i])){
         return findWeightedSum(arr[i], level + 1, res);
      };
   };
   return res;
};
console.log(findWeightedSum(arr));
And the output in the console will be −
46
How to implement a Singleton design pattern in C#?

Singleton Pattern belongs to Creational type pattern
Singleton design pattern is used when we need to ensure that only one object of a particular class is Instantiated. That single instance created is responsible to coordinate actions across the application.
As part of the Implementation guidelines we need to ensure that only one instance of the class exists by declaring all constructors of the class to be private. Also, to control the singleton access we need to provide a static property that returns a single instance of the object.
Sealed ensures the class being inherited and
object instantiation is restricted in the derived class
Private property initialized with null
ensures that only one instance of the object is created
based on the null condition
Private constructor ensures that object is not
instantiated other than with in the class itself
Public method which can be invoked through the singleton instance
 Live Demo
public sealed class Singleton {
   private static int counter = 0;
   private static Singleton instance = null;
   public static Singleton GetInstance {
      get {
         if (instance == null)
         instance = new Singleton();
         return instance;
      }
   }
   private Singleton() {
      counter++;
      Console.WriteLine("Counter Value " + counter.ToString());
   }
   public void PrintDetails(string message) {
      Console.WriteLine(message);
   }
}
class Program {
   static void Main() {
      Singleton fromFacebook = Singleton.GetInstance;
      fromFacebook.PrintDetails("From Facebook");
      Singleton fromTwitter = Singleton.GetInstance;
      fromTwitter.PrintDetails("From Twitter");
      Console.ReadLine();
   }
}
Counter Value 1
From Facebook
From Twitter
Python 3 - os.popen() Method

The method popen() opens a pipe to or from command.The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.The bufsize argument has the same meaning as in open() function.
Following is the syntax for popen() method −
os.popen(command[, mode[, bufsize]])

command − This is command used.
command − This is command used.
mode − This is the Mode can be 'r'(default) or 'w'.
mode − This is the Mode can be 'r'(default) or 'w'.
bufsize − If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior). 
bufsize − If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior). 
This method returns an open file object connected to the pipe.
The following example shows the usage of popen() method.
# !/usr/bin/python3
import os, sys

# using command mkdir
a = 'mkdir nwdir'
b = os.popen(a,'r',1)

print (b)
When we run the above program, it produces the following result −
<os._wrap_close object at 0x7fb599240b70>


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Apache Flink - Table API and SQL

Table API is a relational API with SQL like expression language. This API can do both batch and stream processing. It can be embedded with Java and Scala Dataset and Datastream APIs. You can create tables from existing Datasets and Datastreams or from external data sources. Through this relational API, you can perform operations like join, aggregate, select and filter. Whether the input is batch or stream, the semantics of the query remains the same.
Here is a sample Table API program −
// for batch programs use ExecutionEnvironment instead of StreamExecutionEnvironment
val env = StreamExecutionEnvironment.getExecutionEnvironment

// create a TableEnvironment
val tableEnv = TableEnvironment.getTableEnvironment(env)

// register a Table
tableEnv.registerTable("table1", ...) // or
tableEnv.registerTableSource("table2", ...) // or
tableEnv.registerExternalCatalog("extCat", ...)

// register an output Table
tableEnv.registerTableSink("outputTable", ...);
// create a Table from a Table API query
val tapiResult = tableEnv.scan("table1").select(...)
// Create a Table from a SQL query
val sqlResult = tableEnv.sqlQuery("SELECT ... FROM table2 ...")

// emit a Table API result Table to a TableSink, same for SQL result
tapiResult.insertInto("outputTable")

// execute
env.execute()

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Bootstrap .tooltip("destroy") method

Use the tooltip(“destroy”) method in Bootstrap to detroy the tooltip −
$(".btn-default").click(function(){
  $("[data-toggle='tooltip']").tooltip('destroy');
});
The following example has two buttons, one for “Show Tooltip” and another for “Destroy Tooltip” −
$(".btn-primary").click(function(){
  $("[data-toggle='tooltip']").tooltip('show');
});
$(".btn-default").click(function(){
  $("[data-toggle='tooltip']").tooltip('destroy');
});
Here is the complete code to implement the tooltip(“destroy”) method −
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/3.3.7/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/3.3.7/js/bootstrap.min.js"></script>
  </head>

<body>
  <div class="container">
    <h3>Demo</h3>
    <a href="#" data-toggle="tooltip" title="Tooltip is visible!">Tooltip will be visible here</a>
    <div>
      <button type="button" class="btn btn-primary">Show Tooltip</button>
      <button type="button" class="btn btn-default">Destroy Tooltip</button>
    </div>  
  </div>

<script>
  $(document).ready(function(){
   $(".btn-primary").click(function(){
     $("[data-toggle='tooltip']").tooltip('show');
   });
   $(".btn-default").click(function(){
     $("[data-toggle='tooltip']").tooltip('destroy');
   });
  });
</script>

</body>
</html>
How can we use MySQL SELECT without FROM clause?

FROM clause after SELECT shows the references to a table. But if there is no reference to any table then we can use SELECT without the FROM clause. In other words, we can say that SELECT can be used to retrieve rows computed without reference to any table. Consider the following statements −
mysql> Select concat_ws(" ","Hello", "World");
+---------------------------------+
| concat_ws(" ","Hello", "World") |
+---------------------------------+
| Hello World                     |
+---------------------------------+
1 row in set (0.00 sec)

mysql> Set @var1=100;
Query OK, 0 rows affected (0.00 sec)

mysql> Select @var1;
+-------+
| @var1 |
+-------+
|   100 |
+-------+
1 row in set (0.00 sec)
Relative Positioning with CSS

Relative positioning changes the position of the HTML element relative to where it normally appears. So "left:20" adds 20 pixels to the element's LEFT position.
You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document.
 Move Left - Use a negative value for left.
 Move Right - Use a positive value for left.
 Move Up - Use a negative value for top.
 Move Down - Use a positive value for top.
You can try to run the following code to implement relative positioning −
<html>
   <head>
   </head>
      <body>
         <div style = "position:relative;left:80px;top:2px;background-color:yellow;">
            This div has relative positioning.
         </div>
      </body>
</html>
Create a new user with password in MySQL 8?

You need to use CREATE command to create a new user with password in MySQL 8. Let us check the version
mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.12    |
+-----------+
1 row in set (0.14 sec)
The syntax is as follows to create a new user with password
CREATE USER 'yourUserName'@'localhost' IDENTIFIED BY 'yourPassword';
The following is the syntax to grant all privileges to the created user
GRANT ALL ON *.* TO 'yourUserName'@'localhost';
Now flush the privileges using flush command
flush privileges;

Let us create a new user with the help of the above syntax. The query is as follows
mysql> use MySQL;
Database changed
mysql> CREATE USER 'James'@'localhost' IDENTIFIED BY 'James123456';
Query OK, 0 rows affected (0.21 sec)
The following is the query to grant all privileges to the newly created user
mysql> GRANT ALL ON *.* TO 'James'@'localhost';
Query OK, 0 rows affected (0.18 sec)
Let us check the user has been created or not
mysql> select user from MySQL.user;
The following is the output displaying the new user we created above
+------------------+
| user             |
+------------------+
| Bob              |
| Manish           |
| User2            |
| mysql.infoschema |
| mysql.session    |
| mysql.sys        |
| root             |
| @UserName@       |
| Adam Smith       |
| James            |
| John             |
| John Doe         |
| User1            |
| am               |
| hbstudent        |
| mysql.infoschema |
| mysql.session    |
+------------------+
17 rows in set (0.00 sec)
Look at the sample output, the user James has been created successfully. Now flush the privileges using a flush command. The query is as follows
mysql> flush privileges;
Query OK, 0 rows affected (0.04 sec)
CSS - Layers

CSS gives you opportunity to create layers of various divisions. The CSS layers refer to applying the z-index property to elements that overlap with each other.
The z-index property is used along with the position property to create an effect of layers. You can specify which element should come on top and which element should come at bottom.
A z-index property can help you to create more complex webpage layouts. Following is the example which shows how to create layers in CSS.
<html>
   <head>
   </head>

   <body>
      <div style = "background-color:red; 
         width:300px; 
         height:100px; 
         position:relative; 
         top:10px; 
         left:80px; 
         z-index:2">
      </div>
      
      <div style = "background-color:yellow; 
         width:300px; 
         height:100px; 
         position:relative; 
         top:-60px; 
         left:35px; 
         z-index:1;">
      </div>
      
      <div style = "background-color:green; 
         width:300px; 
         height:100px; 
         position:relative; 
         top:-220px; 
         left:120px; 
         z-index:3;">
      </div>
   </body>
</html> 
It will produce the following result −

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
How to replace rows in a MySQL table with conditions?

To set conditions and replace rows, use MySQL CASE statement. Let us first create a table −
mysql> create table DemoTable1481
   -> (
   -> PlayerScore int
   -> );
Query OK, 0 rows affected (0.42 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1481 values(454);
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable1481 values(765);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1481 values(890);
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1481;
This will produce the following output −
+-------------+
| PlayerScore |
+-------------+
|         454 |
|         765 |
|         890 |
+-------------+
3 rows in set (0.00 sec)
Following is the query to replace rows in a MySQL table −
mysql> update DemoTable1481
   -> set PlayerScore= case when PlayerScore=454 then 1256
   -> when PlayerScore=765 then 1865
   -> when PlayerScore=890 then 3990
   -> end
   -> ;
Query OK, 3 rows affected (0.17 sec)
Rows matched: 3  Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1481;
This will produce the following output −
+-------------+
| PlayerScore |
+-------------+
|        1256 |
|        1865 |
|        3990 |
+-------------+
3 rows in set (0.00 sec)
How to get synonyms/antonyms from NLTK WordNet in Python

The WordNet is a part of Python's Natural Language Toolkit. It is a large word database of English Nouns, Adjectives, Adverbs and Verbs. These are grouped into some set of cognitive synonyms, which are called synsets.
To use the Wordnet, at first we have to install the NLTK module, then download the WordNet package.
$ sudo pip3 install nltk
$ python3
>>> import nltk
>>>nltk.download('wordnet')

In the wordnet, there are some groups of words, whose meaning are same.
In the first example, we will see how wordnet returns meaning and other details of a word. Sometimes, if some examples are available, it may also provide that.
from nltk.corpus import wordnet   #Import wordnet from the NLTK
synset = wordnet.synsets("Travel")
print('Word and Type : ' + synset[0].name())
print('Synonym of Travel is: ' + synset[0].lemmas()[0].name())
print('The meaning of the word : ' + synset[0].definition())
print('Example of Travel : ' + str(synset[0].examples()))
$ python3 322a.word_info.py
Word and Type : travel.n.01
Synonym of Travel is: travel
The meaning of the word : the act of going from one place to another
Example of Travel : ['he enjoyed selling but he hated the travel']
$

In the previous example, we are getting detail information about some words. Here we will see how wordnet can send the synonyms and antonyms of a given word.
import nltk
from nltk.corpus import wordnet   #Import wordnet from the NLTK
syn = list()
ant = list()
for synset in wordnet.synsets("Worse"):
   for lemma in synset.lemmas():
      syn.append(lemma.name())    #add the synonyms
      if lemma.antonyms():    #When antonyms are available, add them into the list
      ant.append(lemma.antonyms()[0].name())
print('Synonyms: ' + str(syn))
print('Antonyms: ' + str(ant))
$ python3 322b.syn_ant.py
Synonyms: ['worse', 'worse', 'worse', 'worsened', 'bad', 'bad', 'big', 'bad', 'tough', 'bad', 'spoiled', 'spoilt', 'regretful', 'sorry', 'bad', 'bad', 'uncollectible', 'bad', 'bad', 'bad', 'risky', 'high-risk', 'speculative', 'bad', 'unfit', 'unsound', 'bad', 'bad', 'bad', 'forged', 'bad', 'defective', 'worse']
Antonyms: ['better', 'better', 'good', 'unregretful']
$

The NLTK wordnet has another great feature, by using it we can check whether two words are nearly equal or not. It will return the similarity ratio from a pair of words.
import nltk
from nltk.corpus import wordnet     #Import wordnet from the NLTK
first_word = wordnet.synset("Travel.v.01")
second_word = wordnet.synset("Walk.v.01")
print('Similarity: ' + str(first_word.wup_similarity(second_word)))
first_word = wordnet.synset("Good.n.01")
second_word = wordnet.synset("zebra.n.01")
print('Similarity: ' + str(first_word.wup_similarity(second_word)))
$ python3 322c.compare.py
Similarity: 0.6666666666666666
Similarity: 0.09090909090909091
$
How to make longer subplot tick marks in Matplotlib?

To make longer subplot tick marks in matplotlib, we can use tick_params() method for minor and major ticks length and width.
Add a subplot to the current figure using subplot() method.
Add a subplot to the current figure using subplot() method.
Plot a range(2) value
Plot a range(2) value
s for x and y data points.
s for x and y data points.
Turn the minor ticks of the colorbar ON without extruding into the "extend regions".
Turn the minor ticks of the colorbar ON without extruding into the "extend regions".
Use tick_params for changing the appearance of ticks and tick labels.
Use tick_params for changing the appearance of ticks and tick labels.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
ax1 = plt.subplot()
ax1.plot(range(2), range(2), linewidth=2)
ax1.minorticks_on()
ax1.tick_params('both', length=20, width=2, which='major')
ax1.tick_params('both', length=10, width=1, which='minor')
plt.show()
PHP mktime() Function

The mktime function accepts hours, minutes, seconds, month, day, year as parameters (representing a date) and returns the Unix timestamp for the given date. if you haven't passed any parameters to this method, it returns the current timestamp. 
mktime($hour, $minute, $second, $month, $day,$ year, $is_dst)

hours(Mandatory)
This is an integer value representing the number of hours of the day, from its start.
minute(Mandatory)
This is an integer value representing the number of minutes of an hours, from its start.
seconds(Optional)
This is an integer value representing the number seconds of a minute, from its start.
month(Mandatory)
This is an integer value representing the month of an year, which should be between 1 and 12.
day(Mandatory)
This is an integer value representing the day of a date, it should be below the allowed number of days in the given month.
year(Mandatory)
This is an integer value representing the year of a date, it should be between 1 and 32767.
is_dst(Mandatory)
This parameter can be set to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default) 
PHP mktime() function returns an Unix timestamp representing the given date. In case of a failure this function returns the boolean value false. 
This function was first introduced in PHP Version 4.0 and, works with all the later versions.
Following example demonstrates the usage of the mktime() function −
<?php
   $timestamp = mktime();   
   print($timestamp);
?>
This will produce following result −
1589308340

Now, letus invoke the above method by passing all the required parameters −
<?php
   $timestamp = mktime(7, 36, 45, 06, 25, 2017);   
   print($timestamp);
?>
This will produce following result −
1498376205

<?php
   $lastday = mktime(0, 0, 0, 3, 0, 2010);
   echo strftime("Last day in Feb 2010 is: %dn", $lastday);   
   $lastday = mktime(0, 0, 0, 4, -31, 2010);
   echo strftime("Last day in Feb 2010 is: %d", $lastday);
?>
This produces the following result −
Last day in Feb 2010 is: 28nLast day in Feb 2010 is: 28


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How to reverse the column order of the Pandas DataFrame?

01 Jun, 2021
Sometimes when working with DataFrames we might want to change or reverse the order of the column of the dataframe. In this article, let’s see how to reverse the order of the columns of a dataframe. This can be achieved in two ways –
Method 1: The sequence of columns appearing in the dataframe can be reversed by using the attribute.columns[::-1] on the corresponding dataframe. It accesses the columns from the end and outer dataframe[...] reindexes the dataframe using this new sequence provided. 
Example:
Python3
# importing required modulesimport pandas as pd  dataframe = pd.DataFrame([[1, 'A', "Student"],                          [2, 'B', "Tutor"],                          [3, 'C', "Instructor"]]) print("Original DataFrame")display(dataframe) # reversing the dataframeprint("Reversed DataFrame")display(dataframe[dataframe.columns[::-1]])
Output:
Method 2: iloc indexer can also be used to reverse the column order of the data frame, using the syntax iloc[:, ::-1] on the specified dataframe. The contents are not preserved in the original dataframe. 
Python3
# importing required modulesimport pandas as pd  dataframe = pd.DataFrame([[1, 'A', "Student"],                          [2, 'B', "Tutor"],                          [3, 'C', "Instructor"]]) print("Original DataFrame")display(dataframe) # reversing the dataframeprint("Reversed DataFrame")display(dataframe.iloc[:, ::-1])
Output:
adnanirshad158
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check if the value is primitive or not in JavaScript ?

31 Mar, 2021
In this article, we will know how to check if a value of primitive or not.
JavaScript provides six types of primitive values that include Number, String, Boolean, Undefined, Symbol, and BigInt. The size of primitive values is fixed, therefore JavaScript stores the primitive value in the call stack (Execution context).
When we access a primitive value, we manipulate the actual value stored in that variable. Thus, variables that are primitive are accessed by value. When we assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable.
To check a value whether it is primitive or not we use the following approaches:
Approach 1: In this approach, we check the type of the value using the typeof operator. If the type of the value is ‘object’ or ‘function’ then the value is not primitive otherwise the value is primitive. But the typeof operator shows the null to be an “object” but actually, the null is a Primitive.
Example:
Javascript
let isPrimitive = (val) => {      if(val === null){      console.log(true);      return;  }      if(typeof val == "object" || typeof val == "function"){    console.log(false)  }else{    console.log(true)  }}    isPrimitive(null)isPrimitive(12)isPrimitive(Number(12))isPrimitive("Hello world")isPrimitive(new String("Hello world"))isPrimitive(true)isPrimitive([])isPrimitive({})
Output:
true
true
true
true
false
true
false
false
Approach 2: In this approach, we pass the value inside Object() and check if the value is equal to Object(value). If the value is equal then the value is primitive otherwise not primitive.
Example:
Javascript
let isPrimitive = (val) => {      if(val === Object(val)){    console.log(false)  }else{    console.log(true)  }}    isPrimitive(null)isPrimitive(12)isPrimitive(Number(12))isPrimitive("Hello world")isPrimitive(new String("Hello world"))isPrimitive(true)isPrimitive([])isPrimitive({})
Output:
true
true
true
true
false
true
false
false
JavaScript-Methods
JavaScript-Questions
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Select an element or sub array by index from a Numpy Array

29 Aug, 2020
The elements of a NumPy array are indexed just like normal arrays. The index of the first element will be 0 and the last element will be indexed n-1, where n is the total number of elements.
Each element of these ndarrays can be accessed using its index number.
Example: The following code shows how to access an element of a NumPy array.
Python3
import numpy as np  # NumPy ArraynumpyArr = np.array([1, 2, 3, 4])print("numpyArr[0] =", numpyArr[0])print("numpyArr[-1] =", numpyArr[-1])
Output:
numpyArr[0] = 1
numpyArr[-1] = 4

In the first case, we accessed the first element of the array using its index number. In the second case we accessed the last element of the array by using negative indexes.
To get a sub-array, we pass a slice in place of the element index.
Syntax:
numpyArr[x:y]

Here x and y are the starting and last index of the required sub-array.
Example:
Python3
import numpy as np  # NumPy ArraynumpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])  # the slice 3:6 is passed instead # of indexprint("Sub-Array=", numpyArr[3:6])
Output:
Sub-Array= [4 5 6]

A sub-array starting from the 3rd index up to the 6th index ( excluding the last the 6th index ) was selected. You can slice a sub-array starting from the first element by leaving the starting index blank.
Example: The following code selects a sub-array starting from the first element. 
Python3
import numpy as np  numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])  # works same as 0:6print("Sub-Array=", numpyArr[:6])
Output:
Sub-Array= [1 2 3 4 5 6]

Similarly, leaving the left side of the colon blank will give you an array up to the last element.
Example: The following code selects a sub-array starting from a particular index up to the last index.
Python3
import numpy as np  numpyArr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])  # same as 3:9 or 3:n, where n is# the length of arrayprint("Sub-Array=", numpyArr[3:])
Output:
Sub-Array= [4 5 6 7 8 9]

Python numpy-Indexing
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
get_object_or_404 method in Django Models

29 Jun, 2021
Some functions are hard as well as boring to code each and every time. But Django users don’t have to worry about that because Django has some awesome built-in functions to make our work easy and enjoyable. Let’s discuss get_object_or_404() here.
This function calls the given model and get object from that if that object or model doesn’t exist it raise 404 error.
Suppose we want to fetch 3rd product from the product model then we can use:
Python3
# import get_object_or_404()from django.shortcuts import get_object_or_404  # defining viewdef product_view(request):    #retrieving product (pk is primary key)    product = get_object_or_404(Products, pk=3)
This is the advantage of Django if you hardcode that then you have to write this much line of code:
Python3
# import Http404from django.http import Http404  # defining viewdef product_view(request):      # try except logic    try:        product = Products.objects.get(pk=1)    except Products.DoesNotExist:        raise Http404("Given query not found....")
QuerySet instance is used to filter data while fetching from the database. For example, we want to fetch only shoes then we can write:
queryset = Products.objects.filter(type='shoes')
get_object_or_404(queryset)
We can simplify above example by a single line:
get_object_or_404(Products, type='shoes') 
saurabh1990aror
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the meaning of spread operator (...) in Reactjs?

23 Dec, 2020
The three dots syntax (...) is part of ES6 and not React itself and it’s used by two operators i.e. the Spread and Rest operators. The Spread operator lets you expand an iterable like an object, string, or array into its elements while the Rest operator does the inverse by reducing a set of elements into one array.
The spread operator is very useful when you want to make an exact copy of an existing array, you can use the spread operator to accomplish this quickly.
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. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
App.js:JavascriptJavascriptimport React, { Component } from 'react';  // Details is a component in same folderimport Details from './Details'; class App extends React.Component {    render() {    var person = {      name: 'User',      age: 22    };      return (      <div>        {/* Details component which accepts props */}        <Details {...person} title='Dear' />      </div>    );  }}  export default App;
App.js:
Javascript
import React, { Component } from 'react';  // Details is a component in same folderimport Details from './Details'; class App extends React.Component {    render() {    var person = {      name: 'User',      age: 22    };      return (      <div>        {/* Details component which accepts props */}        <Details {...person} title='Dear' />      </div>    );  }}  export default App;
Details.js (Details Component):JavascriptJavascriptimport React, { Component } from 'react';  class Details extends React.Component {  render() {    // To extract values in variables sent by parent component    const { name, age } = { ...this.props };    return (      <div>        <h3>Person Details: </h3>        <ul>          <li>name={this.props.title} {name}</li>          <li>age={age}</li>        </ul>      </div>    );  }}  export default Details;
Details.js (Details Component):
Javascript
import React, { Component } from 'react';  class Details extends React.Component {  render() {    // To extract values in variables sent by parent component    const { name, age } = { ...this.props };    return (      <div>        <h3>Person Details: </h3>        <ul>          <li>name={this.props.title} {name}</li>          <li>age={age}</li>        </ul>      </div>    );  }}  export default Details;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Picked
react-js
Technical Scripter 2020
JavaScript
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ default constructor

A class constructor is a special member function of a class that is executed whenever we create new objects of that class.
A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables.
Following example explains the concept of constructor −
 Live Demo
#include <iostream>
using namespace std;
class Line {
   public:
      void setLength( double len );
      double getLength( void );
      Line(); // This is the constructor
      private:
      double length;
};
// Member functions definitions including constructor
Line::Line(void) {
   cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
   length = len;
}
double Line::getLength( void ) {
   return length;
}
// Main function for the program
int main() {
   Line line;
   // set line length
   line.setLength(6.0);
   cout << "Length of line : " << line.getLength() <<endl;
   return 0;
}
Object is being created
Length of line : 6