code-rag-bench/online-tutorials huggingface dataset:
How to create a read-only list in Java?

Let us first create a List in Java −
List<String>list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
Now to convert the above list to read-only, use Collections −
list = Collections.unmodifiableList(list);
We have converted the above list to read-only. Now, if you will try to add more elements to the list, then the following error would be visible −
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
 Live Demo
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String args[]) throws Exception {
      List<String>list = new ArrayList<String>();
      list.add("A");
      list.add("B");
      list.add("C");
      list = Collections.unmodifiableList(list);
      // An exception is thrown since its a read-only list now
      list.add("D");
      list.add("E");
      list.add("F");
      System.out.println(list);
   }
}
The output is as follows. Since it’s a read-only list, an error would be visible −
Exception in thread "main" java.lang.Error:Unresolved compilation problem:
String literal is not properly closed by a double-quote
at Amit/my.Demo.main(Demo.java:18)
What is the difference between dynamic type variables and object type variables?

You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time.
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). The object is an alias for System. Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types.
Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at runtime.
Example of Dynamic Type −
dynamic z = 100;
Example of Object Type −
object obj = 100;
Check for NULL or NOT NULL values in a column in MySQL

For this, use IS NOT NULL in MySQL. Let us see the syntax−
select yourColumnName IS NOT NULL from yourTableName;
The above query returns 1 if the column does not have NULL value otherwise 0. Let us first create a −
mysql> create table DemoTable1408
   -> (
   -> FirstName varchar(30)
   -> );
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert −
mysql> insert into DemoTable1408 values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1408 values('');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1408 values(NULL);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1408 values('David');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select −
mysql> select * from DemoTable1408;
This will produce the following output −
+-----------+
| FirstName |
+-----------+
| Chris     |
|           |
| NULL      |
| David     |
+-----------+
4 rows in set (0.00 sec)
Following is the query to check for NULL or NOT NULL −
mysql> select FirstName IS NOT NULL from DemoTable1408;
This will produce the following output −
+-----------------------+
| FirstName IS NOT NULL |
+-----------------------+
|                     1 |
|                     1 |
|                     0 |
|                     1 |
+-----------------------+
4 rows in set (0.00 sec)
Generating password in Java

Generate temporary password is now a requirement on almost every website now-a-days. In case a user forgets the password, system generates a random password adhering to password policy of the company. Following example generates a random password adhering to following conditions −
It should contain at least one capital case letter.
It should contain at least one capital case letter.
It should contain at least one lower-case letter.
It should contain at least one lower-case letter.
It should contain at least one number.
It should contain at least one number.
Length should be 8 characters.
Length should be 8 characters.
It should contain one of the following special characters: @, $, #, !.
It should contain one of the following special characters: @, $, #, !.
import java.util.Random;

public class Tester{
   public static void main(String[] args) {
      System.out.println(generatePassword(8));
   }

   private static char[] generatePassword(int length) {
      String capitalCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      String lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
      String specialCharacters = "!@#$";
      String numbers = "1234567890";
      String combinedChars = capitalCaseLetters + lowerCaseLetters + specialCharacters + numbers;
      Random random = new Random();
      char[] password = new char[length];

      password[0] = lowerCaseLetters.charAt(random.nextInt(lowerCaseLetters.length()));
      password[1] = capitalCaseLetters.charAt(random.nextInt(capitalCaseLetters.length()));
      password[2] = specialCharacters.charAt(random.nextInt(specialCharacters.length()));
      password[3] = numbers.charAt(random.nextInt(numbers.length()));
   
      for(int i = 4; i< length ; i++) {
         password[i] = combinedChars.charAt(random.nextInt(combinedChars.length()));
      }
      return password;
   }
}
cF#0KYbY
Installing MySQL on Unix/Linux Using Generic Binaries

Oracle comes with a set of binary distributions of MySQL. This includes generic binary distributions in the form of compressed tar files (files that have a .tar.xz extension) for many platforms, and binaries in platform-specific package formats for specific platforms.
MySQL compressed tar file binary distributions have names in the format ‘mysql−VERSION−OS.tar.xz’, where VERSION refers to a number and OS indicates the type of operating system on which the distribution is required to be used.
To install a compressed tar file binary distribution, the installation needs to be unpacked into a location that is chosen by user. Debug versions of the mysqld binary are available as mysqld−debug.
If the user’s own debug version needs to be used to compile MySQL from a source distribution, appropriate configuration options need to be used.
To install and use a MySQL binary distribution, the below shown command sequence needs to be used −
shell> groupadd mysql
shell> useradd −r −g mysql −s /bin/false mysql
shell> cd /usr/local
shell> tar xvf /path/to/mysql−VERSION−OS.tar.xz
shell> ln −s full−path−to−mysql−VERSION−OS mysql
shell> cd mysql
shell> mkdir mysql−files
shell> chown mysql:mysql mysql−files
shell> chmod 750 mysql−files
shell> bin/mysqld −−initialize −−user=mysql
shell> bin/mysql_ssl_rsa_setup
shell> bin/mysqld_safe −−user=mysql &
# Below command is optional
shell> cp support−files/mysql.server /etc/init.d/mysql.server
The above assumes that the user has root (administrator) access to their system.
The mysql-files directory provides an easy location to use as the value for the secure_file_priv system variable. This limits the import and export operations to a specific directory only. See Section 5.1.8, “Server System Variables”.
The steps are briefed as shown below −
Create a mysql User and Group. It can be done using below commands −
shell> groupadd mysql
shell> useradd −r −g mysql −s /bin/false mysql
Obtain and unpack the distribution. It can be done using below commands −
shell> cd /usr/local
Unpack the distribution, that will create the installation directory. The ‘tar’ can uncompress and unpack the distribution if it has ’z’ option support. It can be done using below commands −
shell> tar xvf /path/to/mysql−VERSION−OS.tar.xz
The tar command creates a directory named mysql−VERSION−OS
The tar command can be replaced with below command to uncompress and extract the distribution −
shell> xz −dc /path/to/mysql−VERSION−OS.tar.xz | tar x

A symbolic link can be created to the installation directory that has been created by tar −
shell> ln −s full−path−to−mysql−VERSION−OS mysql
The ‘ln’ command creates a symbolic link to the installation directory. This enables the user to refer more easily to the poth as /usr/local/mysql. The /usr/local/mysql/bin directory can be added to the user’s PATH variable using the below commad −
shell> export PATH=$PATH:/usr/local/mysql/bin
Find the difference between two datetime values with MySQL?

To find the difference between two datetime values, you can use TIMESTAMPDIFF(). Let us first create a table −
mysql> create table DemoTable
   -> (
   -> DueDatetime1 datetime,
   -> DueDatetime2 datetime
   -> );
Query OK, 0 rows affected (0.86 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-10-26 19:49:00','2019-10-26 17:49:00');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('2019-10-26 08:00:00','2019-10-26 13:00:00');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2019-10-26 06:50:00','2019-10-26 12:50:00');
Query OK, 1 row affected (0.68 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------------+---------------------+
| DueDatetime1        | DueDatetime2        |
+---------------------+---------------------+
| 2019-10-26 19:49:00 | 2019-10-26 17:49:00 |
| 2019-10-26 08:00:00 | 2019-10-26 13:00:00 |
| 2019-10-26 06:50:00 | 2019-10-26 12:50:00 |
+---------------------+---------------------+
3 rows in set (0.00 sec)
Here is the query to implement timestampdiff() and find the difference between two dates −
mysql> select abs(timestampdiff(minute,DueDatetime1,DueDatetime2)) from DemoTable;
This will produce the following output −
+------------------------------------------------------+
| abs(timestampdiff(minute,DueDatetime1,DueDatetime2)) |
+------------------------------------------------------+
|                                                  120 |
|                                                  300 |
|                                                  360 |
+------------------------------------------------------+
3 rows in set (0.00 sec)
Explain the role of HttpContext class in ASP.NET Core

The HttpContext encapsulates all the HTTP-specific information about a single HTTP request.
When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.
The HttpContext object constructed by the ASP.NET Core web server acts as a container for a single request. It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any.
ASP.NET Core applications access the HTTPContext through the IHttpContextAccessor interface. The HttpContextAccessor class implements it. You can use this class when you need to access HttpContext inside a service.
Here are different ways to access HttpContext from various types of applications.
public class HomeController : Controller{
   public IActionResult About(){
      var pathBase = HttpContext.Request.PathBase;

      ...

      return View();
   }
}
public class AboutModel : PageModel{
   public string Message { get; set; }

   public void OnGet(){
      Message = HttpContext.Request.PathBase;
   }
}
@{
   var username = Context.User.Identity.Name;

   ...
}
From middleware
public class MyCustomMiddleware{
   public Task InvokeAsync(HttpContext context){
      ...
   }
}
Here are some of the useful properties and methods on the HttpContext object.
Connection: Gets the information about the underlying network connection for this request.
Request: Gets the HttpRequest object for this request
Response: Gets the HttpResponse object for this request
Session: Gets or sets the object used to manage the user session data for this request
Abort(): Aborts the connection underlying the request.
In ASP.NET Core, the Kestrel web server receives the HTTP request and constructs a C# representation of the request, the HttpContext object. However, Kestrel doesn't generate the response itself but forwards the HttpContext object to the middleware pipeline in the ASP.NET Core application. Middleware is a series of components that process the incoming request and perform various operations such as authentication, caching, logging, etc.
DAX Other - EXCEPT function

Returns the rows of one table which do not appear in another table. DAX EXCEPT function is new in Excel 2016.
EXCEPT (<table_expression1>, <table_expression2>) 

A table that contains the rows of one table minus all the rows of another table.
If a row appears in both tables, that row and its duplicates are not present in the result table.
If a row appears in both tables, that row and its duplicates are not present in the result table.
If a row appears in only table_expression1, that row and its duplicates will appear in the result table.
If a row appears in only table_expression1, that row and its duplicates will appear in the result table.
The two tables must have the same number of columns.
The two tables must have the same number of columns.
The column names in the result table will match the column names in table_expression1.
The column names in the result table will match the column names in table_expression1.
Columns are compared based on positioning, and data comparison with no type coercion.
Columns are compared based on positioning, and data comparison with no type coercion.
The set of rows returned depends on the order of the two expressions.
The set of rows returned depends on the order of the two expressions.
The returned table has lineage based on the columns in table_expression1, regardless of the lineage of the columns in the second table. For example, if the first column of first table_expression has lineage to the base column C1 in the Data Model, DAX Except function will reduce the rows based on the availability of values in the first column of table_expression2 and keep the lineage on base column C1 intact.
The returned table has lineage based on the columns in table_expression1, regardless of the lineage of the columns in the second table. For example, if the first column of first table_expression has lineage to the base column C1 in the Data Model, DAX Except function will reduce the rows based on the availability of values in the first column of table_expression2 and keep the lineage on base column C1 intact.
The returned table does not include columns from the tables related to table_expression1.
The returned table does not include columns from the tables related to table_expression1.
= SUMX (EXCEPT (SalesNewData,SalesOldData),[Sales Amount]) 
This DAX formula returns the sum of Sales Amount for those transactions that appear in the table SalesNewData but do not appear in the table SalesOldData.

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
4 Different Ways to Center an Element using CSS - GeeksforGeeks

22 Feb, 2021
When we create a web page, we most probably have come across the issue to center an element. So let us take a look at 4 different ways to center an element using CSS:
Using FlexMargin PropertyGrid PropertyAbsolute Property
Using Flex
Margin Property
Grid Property
Absolute Property
Now let’s have a look at how these respective properties work using example.
HTML Code:
Filename: index.html
HTML
<!DOCTYPE html><html>  <head>    <title>Page Title</title>    <link rel="stylesheet" href="styles.css" /></head>  <body>    <div class="parent">        <div class="child">            This element is centered        </div>    </div></body>  </html>
In the above code, we have created a parent div and a child div. We will take a look on how to center the child div inside the parent div. A stylesheet titled styles.css has been linked to the file where we have defined the styles of the parent and child div.
CSS
.parent {  height: 400px;  width: 400px;  background-color: red;}.child {  height: 100px;  width: 100px;  background-color: blue;}
Method 1: Using Flex We can use Flexbox in order to center the element. We can set the display property of parent div as flex and can easily center the children div using justify-context : center (horizontally) and align-items : center (vertically) properties.
CSS
.parent {  display: flex;  justify-content: center;  align-items: center;}
Method 2: Margin Property Another simple way to center a child div is to set it’s margin to auto and make the parent div display as grid.
CSS
.parent {  display: grid;}.child {  margin: auto;}
Method 3: Grid Property A quite easy way to center elements is to use the grid property on the parent div and set the place-items: center.
CSS
.parent {  display: grid;  place-items: center;}
Method 4: Absolute Property We can also use the position property to center the elements.
CSS
.parent {  position: relative;}.child {  position: absolute;  top: 50%;  left: 50%;  transform: translate(-50%, -50%);}
Output:
The output of all these ways will be the same which is shown below:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Questions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
atomic.CompareAndSwapInt32() Function in Golang With Examples - GeeksforGeeks

01 Apr, 2020
In Go language, atomic packages supply lower level atomic memory that is helpful is implementing synchronization algorithms. The CompareAndSwapInt32() function in Go language is used to perform the compare and swap operation for an int32 value. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions.
Syntax:
func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)

Here, addr indicates address, old indicates int32 value that is the old swapped value which is returned from the swapped operation, and new is the int32 new value that will swap itself from the old swapped value.
Note: (*int32) is the pointer to a int32 value. And int32 is integer type of bit size 32. Moreover, int32 contains the set of all signed 32-bit integers from -2147483648 to 2147483647.
Return Value: It returns true if swapping is accomplished else it returns false.
Example 1:
// Golang Program to illustrate the usage of// CompareAndSwapInt32 function  // Including main packagepackage main  // importing fmt and sync/atomicimport (    "fmt"    "sync/atomic")  // Main functionfunc main() {      // Assigning variable values to the int32    var (        i int32 = 111    )      // Swapping    var old_value = atomic.SwapInt32(&i, 498)      // Printing old value and swapped value    fmt.Println("Swapped:", i, ", old value:", old_value)      // Calling CompareAndSwapInt32 method with its parameters    Swap := atomic.CompareAndSwapInt32(&i, 498, 675)      // Displays true if swapped else false    fmt.Println(Swap)    fmt.Println("The Value of i is: ",i)}
Output:
Swapped: 498 , old value: 111
true
The Value of i is:  675

Example 2:
// Golang Program to illustrate the usage of// CompareAndSwapInt32 function  // Including main packagepackage main  // importing fmt and sync/atomicimport (    "fmt"    "sync/atomic")  // Main functionfunc main() {      // Assigning variable values to the int32    var (        i int32 = 111    )      // Swapping    var old_value = atomic.SwapInt32(&i, 498)      // Printing old value and swapped value    fmt.Println("Swapped:", i, ", old value:", old_value)      // Calling CompareAndSwapInt32    // method with its parameters    Swap := atomic.CompareAndSwapInt32(&i, 111, 675)      // Displays true if    // swapped else false    fmt.Println(Swap)    fmt.Println("The Value of i is: ",i)}
Output:
Swapped: 498 , old value: 111
false
The Value of i is:  498

Here, the old value in the CompareAndSwapInt32 method must be the swapped value returned from the SwapInt32 method. And here the swapping is not performed so false is returned.
GoLang-atomic
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Loops in Go Language
Class and Object in Golang
Structures in Golang
Time Durations in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
How to Create a Timeline in Jupyter Notebook | by Alon Lekhtman | Towards Data Science

When dealing with temporal data it is always useful to be able to see the data on a timeline in order to understand it better.
There are some built-in python solutions like this and this. However, I found them not flexible enough. I want to propose another solution that is a bit more complex but gives you much more flexibility. Integrate a really great javascript library (vis.js) that deals with timelines on a general-purpose web application into a Jupyter Notebook (don’t worry it is not as complex as it may sound).
Install vis.js timeline:
Install vis.js timeline:
npm install vis-timeline
2. Generate config for your Jupyter Notebook (If you don’t already have one):
jupyter notebook --generate-config
3. Open for editing the config file, located at ~/.jupyter/jupyter_notebook_config.py (Linux and macOS, on windows it is on equivalent location). Uncomment the line with c.NotebookApp.extra_static_path in the file. Put the path to the installed vis-timeline dist folder, it should be something like this:
c.NotebookApp.extra_static_paths = ['~/node_modules/vis-timeline/dist']
(pay attention that on windows you need to use double backslash instead of a single slash in the path).
4. Run (or restart if it was running before):
jupyter notebook
Now your notebook is ready to work with vis.js timelines.
You will need 3 Jupyter Notebook cells for this:
A Python cell, you can create your data here. For this simple example, I created two events, one on December 20, and one on December 25. This code puts our events on the window of the browser, so it can later be used in a javascript cell.
A Python cell, you can create your data here. For this simple example, I created two events, one on December 20, and one on December 25. This code puts our events on the window of the browser, so it can later be used in a javascript cell.
2. A Html cell, with a placeholder for our timeline.
3. A Javascript cell. We import the js and css files of vis.js itself, then get our events from the window, and use the vis.js library to put them in a timeline object.
Now you should see this basic timeline in the HTML cell:
The timeline doesn’t look impressive at this point. However, with the approach introduced here, you can bring all the flexibility there is in the javascript library to your Jupyter Notebook ( Add a functionality when clicking on an event, create a different style for each node, and much much more... )
In order to understand how to create more complex timelines, you can see all the documentation here.
pow() function in C

The function pow() is used to calculate the power raised to the base value. It takes two arguments. It returns the power raised to the base value. It is declared in “math.h” header file.
Here is the syntax of pow() in C language,
double pow(double val1, double val2);
Here,
val1 − The base value whose power is to be calculated.
val2 − The power value.
Here is an example of pow() in C language,
#include<stdio.h>
#include<math.h>
int main() {
   double x = 5.5;
   double y = 4.0;
   double p;
   p = pow(x, y);
   printf("The value : %lf", p);
   return 0;
}
The value : 915.062500
On some online compilers, the following error may occur.
undefined reference to `pow'
error: ld returned 1 exit status
The above error occurs because we have added “math.h” header file, but haven’t linked the program to the following math library.
libm.a
Link the program with the above library, so that the call to function pow() is resolved.
Differentiate the NULL pointer with Void pointer in C language

The difference between Null pointer and Void pointer is that Null pointer is a value and Void pointer is a type.
A null pointer means it is not pointing to anything. If, there is no address that is assigned to a pointer, then set it to null.
A pointer type, i.e., int *, char * each have a null pointer value.
The syntax is as follows −
<data type> *<variable name> = NULL;
For example,
int *p = NULL;
char *p = '\0';
Following is the C program for NULL pointer −
 Live Demo
#include<stdio.h>
int main(){
   printf("TutorialPoint C Programming");
   int *p = NULL; // ptr is a NULL pointer
   printf("\n The value of pointer is: %x ", p);
   return 0;
}
When the above program is executed, it produces the following result −
TutorialPoint C Programming
The value of pointer is: 0
A void pointer is nothing but the one who does not have any data type with it. It is also called as a general purpose pointer. It can hold the addresses of any data type.
Thee syntax is as follows −
void *<data type>;
For example,
void *p;
int a; char c;
p = &a; //p changes to integer pointer as address of integer is assigned to it
p = &c; //p changes to character pointer as address of character is assigned to it
Following is the C program for Void Pointer −
 Live Demo
#include<stdio.h>
int main(){
   int a = 10;
   void *ptr = &a;
   printf("%d", *(int *)ptr);
   return 0;
}
When the above program is executed, it produces the following result −
10
Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted in Python

Suppose we have a given unsorted array A[0..n-1] of size n, we have to find the minimum length subarray A[s..e] so that by sorting this subarray the whole array will be sorted. So, if the array is like [2,6,4,8,10,9,15], then the output will be 5. The subarray will be [6,4,8,10,9].
To solve this, we will follow these steps −
res := sort the nums as an array
res := sort the nums as an array
ans := 0
ans := 0
set r as a linked list
set r as a linked list
for i in range 0 to length of resif nums[i] is not same as res[i], then insert i into the r
for i in range 0 to length of res
if nums[i] is not same as res[i], then insert i into the r
if nums[i] is not same as res[i], then insert i into the r
if length of r is 0, then return 0, if length of r is 1, then return 1
if length of r is 0, then return 0, if length of r is 1, then return 1
return last element of r – first element of r + 1
return last element of r – first element of r + 1
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def findUnsortedSubarray(self, nums):
      res = sorted(nums)
      ans = 0
      r = []
      for i in range(len(res)):
         if nums[i] != res[i]:
            r.append(i)
      if not len(r):
         return 0
      if len(r) == 1:
         return 1
      return r[-1]-r[0]+1
ob1 = Solution()
print(ob1.findUnsortedSubarray([2,6,4,8,10,9,15]))
[2,6,4,8,10,9,15]
5
Sum of Square Numbers in C++

Suppose we have a non-negative integer c, we have to decide whether there're two integers a and b such that it satisfies a^2 + b^2 = c.
So, if the input is like 61, then the output will be True, as 61 = 5^2 + 6^2.
To solve this, we will follow these steps −
Define a function isPerfect(), this will take x,
Define a function isPerfect(), this will take x,
sr := square root of x
sr := square root of x
return true when (sr - floor of sr) is 0
return true when (sr - floor of sr) is 0
From the main method do the following,
From the main method do the following,
if c is same as 0, then −return true
if c is same as 0, then −
return true
return true
for initialize i := 0, when i < the ceiling of square root of c, update (increase i by 1), do −b := c - i * iif isPerfect(b) is true, then −return true
for initialize i := 0, when i < the ceiling of square root of c, update (increase i by 1), do −
b := c - i * i
b := c - i * i
if isPerfect(b) is true, then −return true
if isPerfect(b) is true, then −
return true
return true
return false
return false
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool isPerfect(int x){
      long double sr = sqrt(x);
      return ((sr - floor(sr)) == 0);
   }
   bool judgeSquareSum(int c) {
      if (c == 0)
         return true;
      int b;
      for (int i = 0; i < ceil(sqrt(c)); i++) {
         b = c - i * i;
         if (isPerfect(b))
            return true;
      }
      return false;
   }
};
main(){
   Solution ob;
   cout << (ob.judgeSquareSum(61));
}
61
1
Narrowing Conversion in Java

Narrowing conversion is needed when you convert from a larger size type to a smaller size. This is for incompatible data types, wherein automatic conversions cannot be done.
Let us see an example wherein we are converting long to integer using Narrowing Conversion.
 Live Demo
public class Demo {
    public static void main(String[] args) {
       long longVal = 878;
       int intVal = (int) longVal;
       System.out.println("Long: "+longVal);
       System.out.println("Integer: "+intVal);
    }
}
Long: 878
Integer: 878
Let us see another example, wherein we are converting double to long using Narrowing Conversion.
 Live Demo
public class Demo {
    public static void main(String[] args) {
       double doubleVal = 299.89;
       long longVal = (long)doubleVal;
       System.out.println("Double: "+doubleVal);
       System.out.println("Long: "+longVal);
    }
}
Double: 299.89
Long: 299
Java Program to Find the Surface Area and Volume of a Cone - GeeksforGeeks

01 Dec, 2020
Given the dimensions of the cone, find the Surface area and Volume of a cone. The formula’s to calculate the area and volume are given below.
Cone
Cone is a three-dimensional geometric shape. It consists of a base having the shape of a circle and a curved side (the lateral surface) ending up in a tip called the apex or vertex.
Surface Area of Cone = Area of cone + Area of Circle = pi * r * s + pi * r^2
Volume of Cone = 1/3(pi * r * r * h)
where r is the radius of the circular base, h is the height (the perpendicular distance from the base to the vertex) and s is the slant height of the cone.
Slant height (s) can be calculated using Pythagoras formula sqrt(r * r + h * h)
Input : 
radius = 5
slant_height = 13
height = 12
Output :
Volume Of Cone = 314.159
Surface Area Of Cone = 282.743

Input :
radius = 6
slant_height = 10
height = 8
Output : 
Volume Of Cone = 301.593
Surface Area Of Cone = 301.593
Approach : 
Given the dimensions of the cone, say radius R and height H of cone
Find S = sqrt(R * R + H * H)
Apply the above formulas
Example 1: 
Java
// Java Program to Find the Surface Area and Volume of a// Cone  import java.io.*;  class GFG {    public static void main(String[] args)    {        // specify radius and height of cone        double R = 6, H = 8;          // calculate slant height S        double S = Math.sqrt(R * R + H * H);          // calculate surface area of cone        double SurfaceArea            = (Math.PI * R * R) + (Math.PI * R * S);          // calculate volume of cone        double Volume = (Math.PI * R * R * H) / 3;          System.out.println("Surface area of cone is : "                           + SurfaceArea);          System.out.println("Volume of cone is : " + Volume);    }}
Surface area of cone is : 301.59289474462014
Volume of cone is : 301.59289474462014

Example 2:
Java
// Java Program to Find the Surface Area and Volume of a// Cone  import java.io.*;  class GFG {    public static void main(String[] args)    {        // specify radius and height of cone        double R = 3.42, H = 12;          // calculate slant height S        double S = Math.sqrt(R * R + H * H);          // calculate surface area of cone        double SurfaceArea            = (Math.PI * R * R) + (Math.PI * R * S);          // calculate volume of cone        double Volume = (Math.PI * R * R * H) / 3;          System.out.println("Surface area of cone is : "                           + SurfaceArea);          System.out.println("Volume of cone is : " + Volume);    }}
Surface area of cone is : 170.81027853689216
Volume of cone is : 146.98129725379061

Time Complexity = O(1)
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Tryit Editor v3.7

Tryit: HTML image map - rectangle area
How to install OpenCV in Python?

OpenCV is a Python library that is used to solve computer vision problems. Computer vision include understanding and analyzing digital images by the computer and process the images or provide relevant data after analyzing the image.
OpenCV is an open-source library used in machine learning and image processing.It performs tasks such as recognizing handwritten digits, human faces and objects.
To use OpenCV, we need to install it.
Type the following commands in command prompt to check is python and pip is installed on your system.
python --version
If python is successfully installed, the version of python installed on your system will be displayed.
pip -V
The version of pip will be displayed, if it is successfully installed on your system.
OpenCV can be installed using pip. The following command is run in the command prompt to install OpenCV.
pip install opencv-python
This command will start downloading and installing packages related to the OpenCV library. Once done, the message of successful installation will be displayed.
How to convert a dictionary to a Pandas series? - GeeksforGeeks

08 Oct, 2021
Let’s discuss how to convert a dictionary into pandas series in Python. A series is a one-dimensional labeled array which can contain any type of data i.e. integer, float, string, python objects, etc. while dictionary is an unordered collection of key : value pairs. We use series() function of pandas library to convert a dictionary into series by passing the dictionary as an argument.
Let’s see some examples:
Example 1: We pass the name of dictionary as an argument in series() function. The order of output will be same as of dictionary.
Python3
# Import pandas libraryimport pandas as pd # Create a dictionaryd = {'g' : 100, 'e' : 200,     'k' : 400, 's' : 800,     'n' : 1600} # Convert from dictionary to seriesresult_series = pd.Series(d) # Print seriesresult_series
 Output:
Example 2: We pass the name of dictionary and a different order of index. The order of output will be same as the order we passed in the argument.
Python3
# Import pandas libraryimport pandas as pd # Create a dictionaryd = {'a' : 10, 'b' : 20,     'c' : 40, 'd' :80,     'e' :160}   # Convert from dictionary to seriesresult_series = pd.Series(d, index = ['e', 'b',                                      'd', 'a',                                      'c'])# Print seriesresult_series
Output: 
Example 3: In the above example the length of index list was same as the number of keys in the dictionary. What happens if they are not equal let’s see with the help of an example.
Python3
# Import pandas libraryimport pandas as pd # Create a dictionaryd = {'a' : 10, 'b' : 20,     'c' : 40, 'd':80} # Convert from dictionary to seriesresult_series = pd.Series(d, index = ['b', 'd',                                      'e', 'a',                                      'c'])# Print seriesresult_series
Output: 
So It’s assigning NaN value to that corresponding index.
simmytarika5
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 Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Spiral Matrix II in Python

Suppose we have a positive integer n, we have to generate a square matrix with n2 elements in spiral order. So if n = 5, then the matrix will be −
Let us see the steps −
set (row1, col1) := (0, 0) and (row2, col2) := (n, n), and create one matrix called res, then fill it with 0s, and set num := 1
while num <= n2,for i in range col1 to col2,res[row1, i] = num, incase num by 1if num > n2, then breakfor i in range row1 + 1 to row2,res[i, col2-1] = num, incase num by 1if num > n2, then breakfor i in range col2 – 2 down to col1 – 1,res[row2 – 1, i] = num, incase num by 1if num > n2, then breakfor i in range row2 – 2 down to row1,res[i, col1] = num, incase num by 1increase row1 by 1, decrease row2 by 1, increase col1 by 1 and decrease col2 by 1
for i in range col1 to col2,res[row1, i] = num, incase num by 1if num > n2, then break
res[row1, i] = num, incase num by 1
if num > n2, then break
for i in range row1 + 1 to row2,res[i, col2-1] = num, incase num by 1if num > n2, then break
res[i, col2-1] = num, incase num by 1
if num > n2, then break
for i in range col2 – 2 down to col1 – 1,res[row2 – 1, i] = num, incase num by 1if num > n2, then break
res[row2 – 1, i] = num, incase num by 1
if num > n2, then break
for i in range row2 – 2 down to row1,res[i, col1] = num, incase num by 1
res[i, col1] = num, incase num by 1
increase row1 by 1, decrease row2 by 1, increase col1 by 1 and decrease col2 by 1
return res
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def generateMatrix(self, n):
      row1 = 0
      col1 = 0
      row2 = n
      col2 = n
      result = [ [0 for i in range(n)] for j in range(n)]
      num = 1
      while num<=n**2:
         for i in range(col1,col2):
            result[row1][i] = num
            num+=1
         if num > n**2:
            break
         for i in range(row1+1,row2):
            result[i][col2-1] = num
            num+=1
         if num > n**2:
            break
         for i in range(col2-2,col1-1,-1):
            result[row2-1][i] = num
            num+=1
         if num > n**2:
            break
         for i in range(row2-2,row1,-1):
            result[i][col1] = num
            num+=1
            row1+=1
            row2-=1
            col1+=1
            col2-=1
            #print(result)
      return result
ob1 = Solution()
print(ob1.generateMatrix(4))
4
[[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]
PHP | SplFileInfo getFileInfo() Function - GeeksforGeeks

17 Dec, 2018
The SplFileInfo::getFileInfo() function is an inbuilt function of Standard PHP Library (SPL) in PHP which is used to get the file information of the file.
Syntax:
SplFileInfo::getFileInfo( $class )
Parameters: This function accepts single parameter $class which is optional. It is used to specify the name of splfile derived class.
Return Value: This function returns the SplFileInfo object.
Below programs illustrate the SplFileInfo::getFileInfo() function in PHP:
Program 1:
<?php  // PHP Program to illustrate // Splfileinfo::getFileInfo() function   // Create new SPlFileInfo Object$file = new SplFileInfo("gfg.txt");   // Print resultvar_dump( $file->getFileInfo());   ?>
object(SplFileInfo)#2 (2) {
  ["pathName":"SplFileInfo":private]=>
  string(7) "gfg.txt"
  ["fileName":"SplFileInfo":private]=>
  string(7) "gfg.txt"
}

Program 2:
<?php  // PHP program to use array to check// multiple files$GFG = array (    "/home/rajvir/Desktop/GeeksforGeeks/dummy.php",    "/home/rajvir/Desktop/gfg.txt",    "/var/www/html/gfg.php",    "demo.c");    foreach ($GFG as $file_name) {            // Create new SPlFileInfo Object    $file = new SplFileInfo($file_name);            // Print result    var_dump($file->getFileInfo());    echo "</br>";}?>
object(SplFileInfo)#2 (2) {
  ["pathName":"SplFileInfo":private]=>
  string(44) "/home/rajvir/Desktop/GeeksforGeeks/dummy.php"
  ["fileName":"SplFileInfo":private]=>
  string(9) "dummy.php"
}
object(SplFileInfo)#1 (2) {
  ["pathName":"SplFileInfo":private]=>
  string(28) "/home/rajvir/Desktop/gfg.txt"
  ["fileName":"SplFileInfo":private]=>
  string(7) "gfg.txt"
}
object(SplFileInfo)#2 (2) {
  ["pathName":"SplFileInfo":private]=>
  string(21) "/var/www/html/gfg.php"
  ["fileName":"SplFileInfo":private]=>
  string(7) "gfg.php"
}
object(SplFileInfo)#1 (2) {
  ["pathName":"SplFileInfo":private]=>
  string(6) "demo.c"
  ["fileName":"SplFileInfo":private]=>
  string(6) "demo.c"
}

Reference: http://php.net/manual/en/splfileinfo.getfileinfo.php
PHP-function
PHP-SplFileInfo
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to receive JSON POST with PHP ?
How to Upload Image into Database and Display it using PHP ?
How to fetch data from localserver database and display on HTML table using PHP ?
Express.js express.Router() Function
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers
Complement of Base 10 Integer in Python

Suppose we have a number in decimal number system. We have to get the complement of the number in binary form, then again change it to decimal and return the result. So if the number is 20, then the binary form will be 10100, the complement will be 01011, this is 11 in decimal
To solve this, we will follow these steps −
s := binary string of the number n
sum := 0 and num := 1
for each element i in s in reverse directionif i = ‘b’, then return sumotherwise when i = ‘0’, then sum := sum + numnum := num * 2
if i = ‘b’, then return sum
otherwise when i = ‘0’, then sum := sum + num
num := num * 2
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def bitwiseComplement(self, N):
      s = str(bin(N))
      sum = 0
      num = 1
      for i in s[::-1]:
         if i == "b":
            return sum
         elif i =="0":
            sum+=num
         num*=2
ob1 = Solution()
print(ob1.bitwiseComplement(20))
20
11
How to dynamically update a ListView on Android

This example demonstrates How to dynamically update a ListView on Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:orientation = "vertical"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent">
   <ListView
      android:id = "@+id/list"
      android:layout_width = "fill_parent"
      android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken listview.
Step 3 − Add the following code to src/MainActivity.java
How to dynamically update a ListView on Android
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Now click on any item it will update the value to 100 as shown below –
How can we implement a rounded JTextField in Java?

A JTextField is a subclass of JTextComponent class and it is one of the most important components that allow the user to an input text value in a single-line format. A JTextField class will generate an ActionListener interface when we trying to enter some input inside it. The important methods of a JTextField class are setText(), getText(),
setEnabled() and etc. By default, a JTextfield has a rectangle shape, we can also implement a round-shaped JTextField by using the RoundRectangle2D class and need to override the paintComponent() method.
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class RoundedJTextFieldTest extends JFrame {
   private JTextField tf;
   public RoundedJTextFieldTest() {
      setTitle("RoundedJTextField Test");
      setLayout(new BorderLayout());
      tf = new RoundedJTextField(15);
      add(tf, BorderLayout.NORTH);
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new RoundedJTextFieldTest();
   }
}
// implement a round-shaped JTextField
class RoundedJTextField extends JTextField {
   private Shape shape;
   public RoundedJTextField(int size) {
   super(size);
   setOpaque(false);
}
protected void paintComponent(Graphics g) {
   g.setColor(getBackground());
   g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
   super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
   g.setColor(getForeground());
   g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
}
public boolean contains(int x, int y) {
   if (shape == null || !shape.getBounds().equals(getBounds())) {
      shape = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15);
   }
   return shape.contains(x, y);
   }
}
Find the last element of a list in scala

Suppose we have a list in Scala, this list is defined under scala.collection.immutable package. As we know, a list is a collection of same type elements which contains immutable (cannot be changed) data. We generally apply last function to show last element of a list.
The following Scala code is showing how to print the last element stored in a list of Scala.
import scala.collection.immutable._
object HelloWorld {
   def main(args: Array[String]) {
      val temp_list: List[String] = List("Hello", "World", "SCALA", "is", "awesome")
      println("Elements of temp_list: " + temp_list.last)
   }
}
$scala HelloWorld
Elements of temp_list: awesome
The following Scala code is showing how to print the last element stored in a list of Scala using for loop.
import scala.collection.immutable._
object HelloWorld {
   def main(args: Array[String]) {
      val temp_list: List[String] = List("Hello", "World", "SCALA", "is", "awesome")
      for(element<-temp_list.last) {
         print(element)
      }
   }
}
$scala HelloWorld
awesome
The following Scala code is showing how to print the elements using for-each loop and display the last element.
import scala.collection.immutable._
object HelloWorld {
   def main(args: Array[String]) {
      val temp_list: List[String] = List("Hello", "World", "SCALA", "is", "awesome")
      temp_list.foreach{x:String => print(x + ", ") }
      println("\nLast element is: " + temp_list.last)
   }
}
$scala HelloWorld
Hello, World, SCALA, is, awesome,
Last element is: awesome