code-rag-bench/online-tutorials huggingface dataset:
Python Program to Check If Two Numbers are Amicable Numbers

Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. When it is required to check if two numbers are amicable numbers, a method can be defined that iterates over the number, and uses the modulus operator. Another method is defined that calls the previously defined function to determine if two numbers are amicable or not.
Below is the demonstration of the same −
 Live Demo
import math

def divided_sum_val(my_val) :

   res = 0
   for i in range(2, int(math.sqrt(my_val)) + 1) :

      if (my_val % i == 0) :

         if (i == int(my_val / i)) :
            res = res + i
         else :
            res = res + (i + int(my_val / i))
   return (res + 1)

def check_amicable(x, y) :

   if (divided_sum_val(x) != y) :
      return False

   return (divided_sum_val(y) == x)

first_num = 220
second_num = 288
print("The numbers are :")
print(first_num)
print(second_num)
if (check_amicable(first_num, second_num)) :
   print ("The given numbers are amicable in nature")
else :
   print ("The given numbers are not amicable in nature")
The numbers are :
220
288
The given numbers are not amicable in nature
A method named ‘divided_sum_val’ is defined that takes an integer has parameter.
A method named ‘divided_sum_val’ is defined that takes an integer has parameter.
It uses a ‘for’ loop to iterate through the value and checks the divisibility of the number.
It uses a ‘for’ loop to iterate through the value and checks the divisibility of the number.
If the iterator is equal to the value divided by the iterator, it is incremented by the iterator.
If the iterator is equal to the value divided by the iterator, it is incremented by the iterator.
Otherwise, the entire divided number is added.
Otherwise, the entire divided number is added.
Another method named ‘check_amicable’ is defined, that takes two numbers.
Another method named ‘check_amicable’ is defined, that takes two numbers.
It calls the ‘divided_sum_val’ and returns ‘True’ or ‘False’ depending on the computed value.
It calls the ‘divided_sum_val’ and returns ‘True’ or ‘False’ depending on the computed value.
The two numbers are defined, and are displayed on the console.
The two numbers are defined, and are displayed on the console.
The method is called by passing these two numbers.
The method is called by passing these two numbers.
Based on the output, relevant message is displayed on the console.
Based on the output, relevant message is displayed on the console.
Custom Template Filters in Django - GeeksforGeeks

01 Feb, 2021
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. 
Before move to see the how to make custom filters in Django Template Language, let’s  learn what is filters in Django.
Filter is also the important feature of our template language.
Filters are basically used to modify or filter your variables.
You have to use this pipe ( | ) symbol to apply filter in any variables.
For example :-
So this filter will modify this variable value in lowercase
{{ variable_name |  filter_name }}
First of install create the django project using following command :-
django-admin startproject myproj
cd myproj
Then create the new app  inside myproj
For Ubuntu
python3 manage.py startapp main
Add app name in settings.py inside INSTALLED_APPS
Add this view in your views.py
Python3
from django.shortcuts import render  # Create your views here.def home(request):    value="GEEKSFORGEEKS"    return render(request,"home.html",{"value":value})
Now lets make the templatetags directory inside our main folder
and don’t forget to create __init__.py file inside templatetag directory
and then create lower_filter.py file
Python3
from django import template  register = template.Library()  @register.filter()def low(value):    return value.lower()
Create a directory in main directory add name it as templates
Inside the templates directory create a file and name it as home.html
HTML
<!DOCTYPE html><html><head>    <title>Welcome To GFG</title></head><body>    {% load lower_filter %}    <h1>{{value|low}}</h1></body></html>
Create a file in main directory and name it as urls.py
Python3
from django.urls import pathfrom .views import *  urlpatterns = [    path('', home,name="home"),  ]
myproj/urls.py
Python3
from django.contrib import adminfrom django.urls import path,include  urlpatterns = [    path('admin/', admin.site.urls),    path('',include("main.urls"))]
open cmd or terminal
For Ubuntu
python3 manage.py runserver
Output :-
Python Django
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
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?
How to Install Python Pandas on MacOS? - GeeksforGeeks

22 Sep, 2021
In this article, we will learn how to install Pandas in Python on MacOS. Pandas is a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series.
Follow the below steps to install the Pandas package on macOS using pip:
Step 1: Install the latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install Pandas using pip3.
pip3 install pandas
Follow the below steps to install the Pandas package on macOS using the setup.py file:
Step 1: Download the latest source package of Pandas for python3 from here.
curl https://files.pythonhosted.org/packages/71/65/3ab03ef46613e66880dba5b2c2cb5836938f0219389a11c10cfdc617e836/pandas-1.3.3.tar.gz > pandas.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf pandas.tar.gz
Step 3: Go inside the folder and Enter the following command to install the package.
Note: You must have developer tools for XCode MacOS installed in your system
cd pandas-1.3.3
python3 setup.py install
Make the following import in your python terminal to verify if the installation has been done properly:
import pandas
If there is any error while importing the module then is not installed properly.
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install Selenium on MacOS?
How to Import JSON Data into SQL Server?
How to Install PIL on Windows?
Stratified Sampling in Pandas
SQL Query to Convert Datetime to Date
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to Align Text in HTML?
How to install Jupyter Notebook on Windows?
How to Install OpenCV for Python on Windows?
Sass - Nested Rules

Nesting is combining of different logic structures. Using SASS, we can combine multiple CSS rules within one another. If you are using multiple selectors, then you can use one selector inside another to create compound selectors.
The following example describes the use of nested rules in the SCSS file −
<html>
   <head>
      <title>Nested Rules</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css" />
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
   </head>

   <body>
      <div class = "container">
         <h1>My First Heading</h1>
         <p>It is a CSS pre-processor which helps to reduce repetition with CSS and save the time. </p>
         <p>It is more stable and powerful CSS extension language.</p>
         <div class = "box">
            <h1>My Second Heading</h1>
            <p>It is initially designed by Hampton Catlin and developed by Natalie Weizenbaum in 2006.</p>
         </div>
      </div>
   </body>
</html>
Next, create file style.scss. Note the .scss extension.
.container{
   h1{
      font-size: 25px;
      color:#E45456;
   }
   
   p{
      font-size: 25px;
      color:#3C7949;
   }

   .box{
      h1{
         font-size: 25px;
         color:#E45456;
      }
      
      p{
         font-size: 25px;
         color:#3C7949;
      }
   }
}
You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −
sass --watch C:\ruby\lib\sass\style.scss:style.css

Next, execute the above command, it will create the style.css file automatically with the following code −
The generated style.css is as shown below −
.container h1 {
   font-size: 25px;
   color: #E45456;
}

.container p {
   font-size: 25px;
   color: #3C7949;
}

.container .box h1 {
   font-size: 25px;
   color: #E45456;
}

.container .box p {
   font-size: 25px;
   color: #3C7949;
}
Let us carry out the following steps to see how the above given code works −
Save the above given html code in nested_rules.html file.
Save the above given html code in nested_rules.html file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.

    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
How to make a singleton enum in Java?

The singleton pattern restricts the instantiation of a class to one object. INSTANCE is a public static final field that represents the enum instance. We can get the instance of the class with the EnumSingleton.INSTANCE but it is better to encapsulate it in a getter in case if we want to change the implementation.
There are a few reasons why we can use an enum as a singleton in Java
Guaranteed one instance (Cannot instantiate more than one enum even through reflection).
Thread-safe.
Serialization.
public enum Singleton {
   INSTANCE;
   private singleton() {
   }
}
public enum EnumSingleton {
   INSTANCE;
   private String name;
   private int age;
   private void build(SingletonBuilder builder) {
      this.name = builder.name;
      this.age = builder.age;
   }
   public static EnumSingleton getSingleton() { // static getter
      return INSTANCE;
   }
   public void print() {
      System.out.println("Name: "+name + ", age: "+age);
   }
   public static class SingletonBuilder {
      private final String name;
      private int age;
      private SingletonBuilder() {
         name = null;
      }
      public SingletonBuilder(String name) {
         this.name = name;
      }
      public SingletonBuilder age(int age) {
         this.age = age;
         return this;
      }
      public void build() {
         EnumSingleton.INSTANCE.build(this);
      }
   }
   public static void main(String[] args) {
      new SingletonBuilder("Adithya").age(25).build();
      EnumSingleton.getSingleton().print();
   }
}
Name: Adithya, age: 25
PLSQL | LENGTH Function - GeeksforGeeks

23 Sep, 2019
The PLSQL LENGTH function is used for returning the length of the specified string, in other words, it returns the length of char. The char accepted by the LENGTH function in PLSQL can be of any of the datatypes such as CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
The value returned by the LENGTH function is of datatype NUMBER. If char sent in the parameter has datatype CHAR, then the length includes all trailing blanks. If char is null, then this function returns null.
Syntax:
LENGTH( string )
Parameters Used:
string – It is used to specify the string whose length you want to find out.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1:
DECLARE 
   Test_String string(20) := NULL;
   
   
BEGIN 
   dbms_output.put_line(LENGTH(Test_String)); 
   
END;    
Output:
NULL 
Example-2:
DECLARE 
   Test_String string(20) := '';
   
   
BEGIN 
   dbms_output.put_line(LENGTH(Test_String)); 
   
END;    
Output:
NULL 
Example-3:
DECLARE 
   Test_String string(20) := ' ';
   
   
BEGIN 
   dbms_output.put_line(LENGTH(Test_String)); 
   
END;    
Output:
1 
Example-4:
DECLARE 
   Test_String string(20) := 'Geeksforgeeks';
   
   
BEGIN 
   dbms_output.put_line(LENGTH(Test_String)); 
   
END;     
Output:
13 
Example-5:
DECLARE 
   Test_String string(20) := ' Geeksforgeeks ';
   
   
BEGIN 
   dbms_output.put_line(LENGTH(Test_String)); 
   
END;     
Output:
15 
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
SQL | Views
CTE in SQL
Difference between DELETE, DROP and TRUNCATE
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DDL and DML in DBMS
SQL Interview Questions
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
Difference between Where and Having Clause in SQL
JavaScript Array fill() function

The fill() method of JavaScript is used to fill the elements in an array with a static value.
The syntax is as follows −
array.fill(val, start, end)
Above, val is the value to fill the array, start is the index to begin filling the array, whereas end is the index to stop filling the array.
Let us now implement the fill() method in JavaScript −
 Live Demo
<!DOCTYPE html>
<html>
<body>
   <h2>Ranking Points</h2>
   <button onclick="display()">Fill</button>
   <p id="demo"></p>
   <script>
      var pointsArr = [50, 100, 200, 300, 400, 500, 600];
      document.getElementById("demo").innerHTML = pointsArr;
      function display() {
         document.getElementById("demo").innerHTML = pointsArr.fill(1000);
      }
   </script>
</body>
<!DOCTYPE html>
Click “Fill” button to fill the array −
 Live Demo
<!DOCTYPE html>
<html>
<body>
   <h2>Student Name</h2>
   <button onclick="display()">Fill</button>
   <p id="demo"></p>
   <script>
      var stdName = ["John", "Tom", "David"];
      document.getElementById("demo").innerHTML = stdName;
      function display() {
         document.getElementById("demo").innerHTML = stdName.fill("Jacob");
      }
   </script>
</body>
<!DOCTYPE html>
Click “Fill” to fill the array −
HTML onclick Event Attribute

The HTML onclick attribute is triggered when you mouse click on an HTML element in an HTML document.
Following is the syntax −
<tagname onclick=”script”></tagname>
Let us see an example of HTML onclick event Attribute −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
   body {
      color: #000;
      height: 100vh;
      background-color: #FBAB7E;
      background-image: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%);
      text-align: center;
      padding: 20px;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 2px;
      width: 40%;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem auto;
   }
   .show {
      font-size: 1.2rem;
   }
</style>
</head>
<body>
<h1>HTML onclick Event Attribute Demo</h1>
<button class="btn" onclick='clickFn()'>Click me</button>
<div class="show"></div>
<script>
   function clickFn() {
      var msg = document.querySelector('.show');
      msg.innerHTML = "";
      msg.innerHTML = "Hey! you clicked me";
   }
</script>
</body>
</html>
Click on “Click me” button to triggered mouse click event on it.
MongoEngine - Aggregation

The term ‘aggregation’ is used for the operation that processes data and returns computed result. Finding sum, count and average on one or more fields of documents in a collection can be called as aggregation functions.
MongoEngine provides aggregate() function that encapsulates PyMongo’s aggregation framework. Aggregation operation uses a collection as input and returns one or more documents as a result.
MongoDB uses concept of data processing pipelines. A pipeline can have multiple stages. Basic stage provides that provide filter and operate like queries. Others provide tools for grouping and/or sorting by one or more fields, string concatenation tasks, array aggregation tools, etc.
Following stages are defined in MongoDB pipeline creation −
Aggregation expressions use field path to access fields in the input documents. To specify a field path, use a string that prefixes with a dollar sign $$$ the field name. Expression can use one or more Boolean operators ($and, $or, $not) and comparison operators ($eq, $gt, $lt, $gte, $lte and $ne).
Following arithmetic expressions are also used for aggregation −
Following string expression can also be used in aggregation −
To demonstrate how aggregate() function works in MongoEngine, let us first define a Document class called orders.
from mongoengine import *
con=connect('mydata')

class orders(Document):
   custID = StringField()
   amount= IntField()
   status = StringField()

We then add following documents in orders collection −
The aggregate() function is to be used to find sum of amount field for each custID only when status equals ‘A’. Accordingly, the pipeline is constructed as follows.
First stage in pipeline uses $match to filter documents with status=’A’. Second stage uses $group identifier to group documents on CustID and performs sum of amount.
 pipeline = [
{"$match" : {"status" : "A"}},
{"$group": {"_id": "$custID", "total": {"$sum": "$amount"}}}
]

This pipeline is now used as argument to aggregate() function.
docs = orders.objects().aggregate(pipeline)

We can iterate over the document cursor with a for loop. The complete code is given below −
from mongoengine import *
con=connect('mydata')

class orders(Document):
   custID = StringField()
   amount= IntField()
   status = StringField()

pipeline = [
   {"$match" : {"status" : "A"}},
   {"$group": {"_id": "$custID", "total": {"$sum": "$amount"}}}
   ]
docs = orders.objects().aggregate(pipeline)
for doc in docs:
   print (x)
For the given data, the following output is generated −
{'_id': 'B212', 'total': 400}
{'_id': 'A123', 'total': 750}

 Print
 Add Notes
 Bookmark this page
Convert Hexadecimal value String to ASCII value String in C++

In this tutorial, we will be discussing a program to convert hexadecimal value string to ASCII value string.
For this we will be provided with a string with some hexadecimal values. Our task is to get that hexadecimal value and convert it into equivalent ASCII values.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
string convert_ASCII(string hex){
   string ascii = "";
   for (size_t i = 0; i < hex.length(); i += 2){
      //taking two characters from hex string
      string part = hex.substr(i, 2);
      //changing it into base 16
      char ch = stoul(part, nullptr, 16);
      //putting it into the ASCII string
      ascii += ch;
   }
   return ascii;
}
int main(){
   cout << convert_ASCII("6176656e67657273") << endl;
   return 0;
}
avengers
How to select an empty result set in MySQL?

Select an empty result set with the help of dummy table ‘dual’ from MySQL. The query is as follows −
mysql> select 1 from dual where false;
Empty set (0.00 sec)
In the above query, “dual” is a dummy table and the above condition false. Therefore, it returns empty set.
Let us check with true condition. It will return the selected value. The query is as follows −
mysql> select 1 from dual where true;
The following is the output −
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.00 sec)
How to set JavaScript object values dynamically?

Following is the code for setting JavaScript object values dynamically −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Set Javascript object values dynamically</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to set student object values dynamically</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let student = {
      name: "Rohan",
      age: 22,
      displayInfo() {
         return "Name = " + this.name + " : Age = " + this.age + "<br>";
      },
   };
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = student.displayInfo();
      resEle.innerHTML += "<br>After changing properties <br>";
      student.name = "Shawn";
      student.age = 19;
      resEle.innerHTML += student.displayInfo();
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
MongoDB query to skip first 5 records and display only the last 5 of them

To skip records in MongoDB, use skip(). With that, to display only a specific number of records, use limit().
Let us create a collection with documents −
> db.demo275.insertOne({"Number":10});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eac4dd099650a5401a43")
}
> db.demo275.insertOne({"Number":12});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eac7dd099650a5401a44")
}
> db.demo275.insertOne({"Number":6});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eac9dd099650a5401a45")
}
> db.demo275.insertOne({"Number":1});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eacadd099650a5401a46")
}
> db.demo275.insertOne({"Number":5});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eacddd099650a5401a47")
}
> db.demo275.insertOne({"Number":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48ead0dd099650a5401a48")
}
> db.demo275.insertOne({"Number":8});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48ead6dd099650a5401a49")
}
> db.demo275.insertOne({"Number":9});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48ead8dd099650a5401a4a")
}
> db.demo275.insertOne({"Number":19});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eadddd099650a5401a4b")
}
> db.demo275.insertOne({"Number":29});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48eae1dd099650a5401a4c")
}
Display all documents from a collection with the help of find() method −
> db.demo275.find();
This will produce the following output −
{ "_id" : ObjectId("5e48eac4dd099650a5401a43"), "Number" : 10 }
{ "_id" : ObjectId("5e48eac7dd099650a5401a44"), "Number" : 12 }
{ "_id" : ObjectId("5e48eac9dd099650a5401a45"), "Number" : 6 }
{ "_id" : ObjectId("5e48eacadd099650a5401a46"), "Number" : 1 }
{ "_id" : ObjectId("5e48eacddd099650a5401a47"), "Number" : 5 }
{ "_id" : ObjectId("5e48ead0dd099650a5401a48"), "Number" : 24 }
{ "_id" : ObjectId("5e48ead6dd099650a5401a49"), "Number" : 8 }
{ "_id" : ObjectId("5e48ead8dd099650a5401a4a"), "Number" : 9 }
{ "_id" : ObjectId("5e48eadddd099650a5401a4b"), "Number" : 19 }
{ "_id" : ObjectId("5e48eae1dd099650a5401a4c"), "Number" : 29 }
Following is the query to skip first 5 records and display only the last 5 of them −
> db.demo275.find().skip(5).limit(5)
This will produce the following output −
{ "_id" : ObjectId("5e48ead0dd099650a5401a48"), "Number" : 24 }
{ "_id" : ObjectId("5e48ead6dd099650a5401a49"), "Number" : 8 }
{ "_id" : ObjectId("5e48ead8dd099650a5401a4a"), "Number" : 9 }
{ "_id" : ObjectId("5e48eadddd099650a5401a4b"), "Number" : 19 }
{ "_id" : ObjectId("5e48eae1dd099650a5401a4c"), "Number" : 29 }
Cucumber - Debugging

It is very likely that your test may fail due to unknown reasons. Identifying the cause of failure and correcting it is very important. This process is known as debugging. Following are a few tips and tricks, which makes Cucumber debugging a bit easy.
Debugging option is available with Eclipse. Place the break point. Click the file and debug using the following steps −
Step 1 − Place the manual break points in the Ruby step definition file.
require 'ruby-debug' 
Then /^the process should exit cleanly$/ do 
breakpoint 
assert @exited_cleanly, "Process did not exit cleanly: #{@stdout}" 
end
Step 2 − We can also define a separate debug step like the following in the step definition file.
Then /^I debug$/ do 
breakpoint 
0 
end
Step 3 − Webrat is the default tool for cucumber testing with Rails. It lets you do things like click links, type and submit forms, and so on.
There will be times where you try to click on something, for example, and it’s not there. You’ll get a big blob of HTML thrown back, and figuring out what that exactly means can be a real drag.
save_and_open_page

Webrat provides a method save_and_open_page which captures the current HTML, saves it, and then will open it in a browser for you. Extremely useful.
When /^I follow "(.*)"$/ do |link| 
save_and_open_page 
click_link(link) 
end
 Print
 Add Notes
 Bookmark this page
How to remove special characters from a database field in MySQL?

You can remove special characters from a database field using REPLACE() function. The special characters are double quotes (“ “), Number sign (#), dollar sign($), percent (%) etc.
The syntax is as follows to remove special characters from a database field.
UPDATE yourTableName
SET yourColumnName=REPLACE(yourColumnName,’yourSpecialCharacters’,’’);
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table RemoveSpecialCharacterDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> PRIMARY Key(Id)
   -> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into RemoveSpecialCharacterDemo(Name) values('$John');
Query OK, 1 row affected (0.29 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('$Carol');
Query OK, 1 row affected (0.16 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('$Mike');
Query OK, 1 row affected (0.17 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('$Sam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('$Dav$id$');
Query OK, 1 row affected (0.17 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('Robert$');
Query OK, 1 row affected (0.30 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('J$ames$');
Query OK, 1 row affected (0.13 sec)
mysql> insert into RemoveSpecialCharacterDemo(Name) values('Max$well$');
Query OK, 1 row affected (0.27 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from RemoveSpecialCharacterDemo;
The following is the output:
+----+-----------+
| Id | Name      |
+----+-----------+
|  1 | $John     |
|  2 | $Carol    |
|  3 | $Mike     | 
|  4 | $Sam      |
|  5 | $Dav$id$  |
|  6 | Robert$   |
|  7 | J$ames$   |
|  8 | Max$well$ |
+----+-----------+
8 rows in set (0.00 sec)
Here is the query to remove special characters from a database field using REPLACE():
mysql> update RemoveSpecialCharacterDemo
   -> set Name=replace(Name,'$','');
Query OK, 8 rows affected (0.22 sec)
Rows matched: 8 Changed: 8 Warnings: 0
Check the table records once again. The query to display all records is as follows:
mysql> select *from RemoveSpecialCharacterDemo;
The following is the output:
+----+---------+
| Id | Name    |
+----+---------+
|  1 | John    |
|  2 | Carol   |
|  3 | Mike    |
|  4 | Sam     |
|  5 | David   |
|  6 | Robert  |
|  7 | James   |
|  8 | Maxwell |
+----+---------+
8 rows in set (0.00 sec)
Look at the sample output, the special character $ has been removed completely from the table.
Socket.IO - Error Handling

We have worked on local servers until now, which will almost never give us errors related to connections, timeouts, etc. However, in real life production environments, handling such errors are of utmost importance. Therefore, we will now discuss how we can handle connection errors on the client side.
The client API provides us with following built in events −
Connect − When the client successfully connects.
Connect − When the client successfully connects.
Connecting − When the client is in the process of connecting.
Connecting − When the client is in the process of connecting.
Disconnect − When the client is disconnected.
Disconnect − When the client is disconnected.
Connect_failed − When the connection to the server fails.
Connect_failed − When the connection to the server fails.
Error − An error event is sent from the server.
Error − An error event is sent from the server.
Message − When the server sends a message using the send function.
Message − When the server sends a message using the send function.
Reconnect − When reconnection to the server is successful.
Reconnect − When reconnection to the server is successful.
Reconnecting − When the client is in the process of connecting.
Reconnecting − When the client is in the process of connecting.
Reconnect_failed − When the reconnection attempt fails.
Reconnect_failed − When the reconnection attempt fails.
To handle errors, we can handle these events using the out-socket object that we created on our client.
For example – If we have a connection that fails, we can use the following code to connect to the server again −
socket.on('connect_failed', function() {
   document.write("Sorry, there seems to be an issue with the connection!");
})

    35 Lectures 
     2.5 hours 

 Nicholas Lever
 Print
 Add Notes
 Bookmark this page
MongoDB query to remove item from array?

To remove item from array, you can use $pull operator. Let us create a collection with documents −
> db.removeItemFromArray.insertOne(
   { "_id":101, "StudentName":"Larry", "StudentSubjects":["C","MongoDB","Java","MySQL"] } );
{ "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.removeItemFromArray.find().pretty();
This will produce the following output −
{
   "_id" : 101,
   "StudentName" : "Larry",
   "StudentSubjects" : [
      "C",
      "MongoDB",
      "Java",
      "MySQL"
   ]
}
Following is the query to remove item from an array −
> db.removeItemFromArray.update(
...    { },
...    { $pull: {StudentSubjects:"Java" } },
...    { multi: true }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
In the above query, we have removed “Java”. Let us now display the documents from the collection −
> db.removeItemFromArray.find().pretty();
This will produce the following output −
{
   "_id" : 101,
   "StudentName" : "Larry",
   "StudentSubjects" : [
      "C",
      "MongoDB",
      "MySQL"
   ]
}
Cast to ObjectId failed for value in MongoDB?

To cast to ObjectId correctly, use aggregate() in MongoDB. Let us create a collection with documents −
> db.demo460.insertOne({"_id":"5ab9cbfa31c2ab715d42129e"});
{ "acknowledged" : true, "insertedId" : "5ab9cbfa31c2ab715d42129e" }
Display all documents from a collection with the help of find() method −
> db.demo460.find();
This will produce the following output −
{ "_id" : "5ab9cbfa31c2ab715d42129e" }
Following is the query to cast to objectId −
> db.demo460.aggregate( [ idConvert ])
This will produce the following output −
{ "_id" : "5ab9cbfa31c2ab715d42129e", "value" : ObjectId("5ab9cbfa31c2ab715d42129e") }
Compute the Correlation Coefficient Value between Two Vectors in R Programming - cor() Function - GeeksforGeeks

10 Jun, 2020
cor() function in R Language is used to measure the correlation coefficient value between two vectors.
Syntax: cor(x, y, method)
Parameters:x, y: Data vectorsmethod: Type of method to be used
Example 1:
# Data vectors x <- c(1, 3, 5, 10)     y <- c(2, 4, 6, 20)     # Print covariance using Pearson methodprint(cor(x, y, method = "pearson")) 
Output:
[1] 0.9724702

Example 2:
# Data vectors x <- c(1, 3, 5, 10)     y <- c(2, 4, 6, 20)     # Print covariance using Pearson methodprint(cor(x, y, method = "kendall")) 
Output:
[1] 1

Example 3:
# Data vectors x <- c(1, 3, 5, 10)     y <- c(2, 4, 6, 20)     # Print covariance using Pearson methodprint(cor(x, y, method = "spearman")) 
Output:
[1] 1

R Math-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Loops in R (for, while, repeat)
Filter data by multiple conditions in R using Dplyr
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Printing Output of an R Program
Remove rows with NA in one column of R DataFrame
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
CountDownLatch in Java

public class CountDownLatch
   extends Object
CountDownLatch class is a synchronization aid which allows one or more thread to wait until the mandatory operations are performed by other threads.
CountDownLatch is initialized with a given count of threads which are required to be completed before the main thread.
CountDownLatch is initialized with a given count of threads which are required to be completed before the main thread.
CountDownLatch.await() method block the main thread execution until the current count reaches to zero. the count is decremented using countDown() method by executing threads when their task is completed. Any call to await returns immediately once the count is 0.
CountDownLatch.await() method block the main thread execution until the current count reaches to zero. the count is decremented using countDown() method by executing threads when their task is completed. Any call to await returns immediately once the count is 0.
Following is the list of important methods available in the CountDownLatch class.
Following is an example to explain CountDownLatch functionality −
Live Demo
import java.util.concurrent.CountDownLatch;

public class Tester {
   public static void main(String args[]) {
      //Set the counter to 2 being two applications  
      CountDownLatch countDownLatch = new CountDownLatch(4);

      Thread app1 = new Thread(new Application("App1",  countDownLatch));
      Thread app2 = new Thread(new Application("App2",  countDownLatch));          
      Thread app3 = new Thread(new Application("App3",  countDownLatch));
      Thread app4 = new Thread(new Application("App4",  countDownLatch));  
 
      // initialize applications
      app1.start();
      app2.start();
      app3.start();
      app4.start();

      try {
         //wait until countDownLatch reduces to 0.
         countDownLatch.await();            
         //As all applications are up, print the message
         System.out.println("All applications are up and running.");
      } catch(InterruptedException e) {
         System.out.println(e.getMessage());
      }        
   }
}

class Application implements Runnable {
   private String name;
   private CountDownLatch countDownLatch;

   public Application(String name, CountDownLatch countDownLatch) {
      this.name = name;
      this.countDownLatch = countDownLatch;
   }

   public void run() {
      try {
         System.out.println(name + " started. ");
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         System.out.println(e.getMessage());
      }
      System.out.println( name + " is Up and running.");
      //reduce the count by 1
      countDownLatch.countDown();    
   }
}
This will produce the following result −
App2 started.  
App3 started.  
App1 started.  
App4 started.  
App1 is Up and running.
App3 is Up and running.
App4 is Up and running.
App2 is Up and running.
All applications are up and running.
C# Queryable Take() Method

Get specified number of elements from the beginning using the Take() method.
The following is our array.
int[] marks = { 35, 72, 50, 90, 95, 85, 52, 67 };
Now, use OrderByDescending to order the elements in Descending order. Then use the Take() method to get the elements.
marks.AsQueryable().OrderByDescending(s => s).Take(5);
Let us see the complete example.
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      int[] marks = { 35, 72, 50, 90, 95, 85, 52, 67 };
      // top 5 student marks
      IEnumerable<int> selMarks = marks.AsQueryable().OrderByDescending(s => s).Take(5);
      foreach (int res in selMarks) {
         Console.WriteLine(res);
      }
   }
}
95
90
85
72
67
How can we ignore the fields during JSON serialization in Java?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
public @interface JsonIgnore
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;
public class JsonIgnoreAnnotationTest {
   public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {
      Employee emp = new Employee();
      emp.setFirstName("Raja");
      emp.setLastName("Ramesh");
      emp.setEmpId(120);
      emp.getTechnologies().add("Java");
      emp.getTechnologies().add("Scala");
      emp.getTechnologies().add("Python");
      ObjectMapper mapper = new ObjectMapper();
      mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, emp);
   }
}
// Employee class
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
   "firstName",
   "lastName",
   "technologies",
   "empId"
})
class Employee {
   @JsonProperty("EMPLOYEE_ID")
   private int empId;
   @JsonProperty("EMPLOYEE_FIRST_NAME")
   private String firstName;
   @JsonProperty("EMPLOYEE_LAST_NAME")
   private String lastName;
   @JsonIgnore 
   private List<String> technologies = new ArrayList<>();
   public int getEmpId() {
      return empId;
   }
   public void setEmpId(int empId) {
      this.empId = empId;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public List<String> getTechnologies() {
      return technologies;
   }
   public void setTechnologies(List<String> technologies) {
      this.technologies = technologies;
   }
}
{
   "EMPLOYEE_FIRST_NAME" : "Raja",
   "EMPLOYEE_LAST_NAME" : "Ramesh",
   "EMPLOYEE_ID" : 120
}
Monitors vs Semaphores

Monitors and semaphores are used for process synchronization and allow processes to access the shared resources using mutual exclusion. However, monitors and semaphores contain many differences. Details about both of these are given as follows −
Monitors are a synchronization construct that were created to overcome the problems caused by semaphores such as timing errors.
Monitors are abstract data types and contain shared data variables and procedures. The shared data variables cannot be directly accessed by a process and procedures are required to allow a single process to access the shared data variables at a time.
This is demonstrated as follows:
monitor monitorName
{
   data variables;

   Procedure P1(....)
   {

   }

   Procedure P2(....)
   {

   }

   Procedure Pn(....)
   {

   }

   Initialization Code(....)
   {

   }
}
Only one process can be active in a monitor at a time. Other processes that need to access the shared variables in a monitor have to line up in a queue and are only provided access when the previous process release the shared variables.
A semaphore is a signalling mechanism and a thread that is waiting on a semaphore can be signalled by another thread. This is different than a mutex as the mutex can be signalled only by the thread that called the wait function.
A semaphore uses two atomic operations, wait and signal for process synchronization.
The wait operation decrements the value of its argument S, if it is positive. If S is negative or zero, then no operation is performed.
wait(S)
{
   while (S<=0);

   S--;
}
The signal operation increments the value of its argument S.
signal(S)
{
   S++;
}
There are mainly two types of semaphores i.e. counting semaphores and binary semaphores.
Counting Semaphores are integer value semaphores and have an unrestricted value domain. These semaphores are used to coordinate the resource access, where the semaphore count is the number of available resources.
The binary semaphores are like counting semaphores but their value is restricted to 0 and 1. The wait operation only works when the semaphore is 1 and the signal operation succeeds when semaphore is 0.
Hashtable vs. Dictionary in C#

A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.
The members in a Hashtable are thread safe. It returns null if we try to find a key that does not exist. Hashtable is not a generic type.
The Hashtable collection is slower than dictionary because it requires boxing and unboxing.
To declare a Hashtable −
Hashtable ht = new Hashtable();
Dictionary is a collection of keys and values in C#. Dictionary is included in the System.Collection.Generics namespace. Dictionary is a generic type and returns an error if you try to find a key which is not there.
The Dictionary collection is faster than Hashtable because there is no boxing and unboxing.
To declare a Dictionary −
IDictionary<int, string> d = new Dictionary<int, string>();
Perl local Function

This function sets the variables in LIST to be local to the current execution block. If more than one value is specified, you must use parentheses to define the list.
Note that local creates a local copy of a variable, which then goes out of scope when the enclosing block terminates. The localized value is then used whenever it is accessed, including any subroutines and formats used during that block.
Following is the simple syntax for this function −
local LIST

This function does not return any value.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

local $foo;			      # make $foo dynamically local
local (@wid, %get);		# make list of variables local
local $foo = "flurp";	  # make $foo dynamic, and init it
local @oof = @bar;		# make @oof dynamic, and init it

    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Python – Sort grouped Pandas dataframe by group size?

To group Pandas dataframe, we use groupby(). To sort grouped dataframe in ascending or descending order, use sort_values(). The size() method is used to get the dataframe size.
For ascending order sort, use the following in sort_values() −
ascending=True
For descending order sort, use the following in sort_values() −
ascending=False
At first, create a pandas dataframe −
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],
      "Reg_Price": [1000, 1400, 1000, 900, 1700, 900]
   }
)
Next, group according to Reg_Price column and sort in descending order −
dataFrame.groupby('Reg_Price').size().sort_values(ascending=False)
Next, group according to Reg_Price column and sort in ascending order −
dataFrame.groupby('Reg_Price').size().sort_values(ascending=True)
Following is the code −
import pandas as pd

# dataframe with one of the columns as Reg_Price
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],

      "Reg_Price": [1000, 1400, 1000, 900, 1700, 900]
   }
)

print"DataFrame...\n",dataFrame

# group according to Reg_Price column and sort in descending order
print"Sorted in Descending order...\n";
print(dataFrame.groupby('Reg_Price').size().sort_values(ascending=False))

# group according to Reg_Price column and sort in ascending order
print"Sorted in Ascending order...\n";
print(dataFrame.groupby('Reg_Price').size().sort_values(ascending=True))
This will produce the following output −
DataFrame...
       Car   Reg_Price
0      BMW        1000
1    Lexus        1400
2     Audi        1000
3 Mercedes         900
4   Jaguar        1700
5  Bentley         900
Sorted in Descending order...

Reg_Price
1000    2
900     2
1700    1
1400    1
dtype: int64
Sorted in Ascending order...

Reg_Price
1400    1
1700    1
900     2
1000    2
dtype: int64
Laravel - Insert Records

We can insert the record using the DB facade with insert method. The syntax of insert method is as shown in the following table.
$query(string) − query to execute in database
$bindings(array) − values to bind with queries
Step 1 − Execute the below command to create a controller called StudInsertController
php artisan make:controller StudInsertController --plain

Step 2 − After the successful execution of step 1, you will receive the following output −
Step 3 − Copy the following code to file
app/Http/Controllers/StudInsertController.php
app/Http/Controllers/StudInsertController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class StudInsertController extends Controller {
   public function insertform() {
      return view('stud_create');
   }
	
   public function insert(Request $request) {
      $name = $request->input('stud_name');
      DB::insert('insert into student (name) values(?)',[$name]);
      echo "Record inserted successfully.<br/>";
      echo '<a href = "/insert">Click Here</a> to go back.';
   }
}
Step 4 − Create a view file called resources/views/stud_create.php and copy the following code in that file.
resources/views/stud_create.php
<html>
   <head>
      <title>Student Management | Add</title>
   </head>

   <body>
      <form action = "/create" method = "post">
         <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
         <table>
            <tr>
               <td>Name</td>
               <td><input type='text' name='stud_name' /></td>
            </tr>
            <tr>
               <td colspan = '2'>
                  <input type = 'submit' value = "Add student"/>
               </td>
            </tr>
         </table>
      </form>
      
   </body>
</html>
Step 5 − Add the following lines in app/Http/routes.php.
app/Http/routes.php
Route::get('insert','StudInsertController@insertform');
Route::post('create','StudInsertController@insert');

Step 6 − Visit the following URL to insert record in database.
http://localhost:8000/insert

Step 7 − The output will appear as shown in the following image.

    13 Lectures 
     3 hours 

 Sebastian Sulinski

    35 Lectures 
     3.5 hours 

 Antonio Papa

    7 Lectures 
     1.5 hours 

 Sebastian Sulinski

    42 Lectures 
     1 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    116 Lectures 
     13 hours 

 Hafizullah Masoudi
 Print
 Add Notes
 Bookmark this page