code-rag-bench/online-tutorials huggingface dataset:
Perl | defined() Function

21 Feb, 2019
Defined() in Perl returns true if the provided variable ‘VAR’ has a value other than the undef value, or it checks the value of $_ if VAR is not specified. This can be used with many functions to detect for the failure of operation since they return undef if there was a problem.
If VAR is a function or reference of a function, then it returns true if the function has been defined else it will return false if the function doesn’t exist. If a hash element is specified, it returns true if the corresponding value has been defined, but it doesn’t check for the existence of the key in the hash
Syntax: defined(VAR)
Parameters:VAR which is to be checked
Returns:Returns 0 if VAR is undef and 1 if VAR contains a value
Example 1:
#!/usr/bin/perl  # Defining a variable$X = "X is defined";  # Checking for existence of $X # with defined() functionif(defined($X)) {    print "$X\n";}  # Checking for existence of $Y # with defined() functionif(defined($Y)) {    print "Y is also defined\n";} else{    print "Y is not defined\n";}
Output:
X is defined
Y is not defined
 Example 2:
#!/usr/bin/perl  # Defining a functionsub X{          # Defining a variable    $VAR = 20;}  # Checking for existence of $X # with defined() functionif(defined(X)) {    print "Function Exists\n";}  # Checking for existence of $Y # with defined() functionif(defined($Y)) {    print "Y is also defined\n";} else{    print "Y is not defined\n";}
Output:
Function Exists
Y is not defined

Perl-function
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays (push, pop, shift, unshift)
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Perl | length() Function
Perl | Boolean Values
Perl | Subroutines or Functions
Use of print() and say() in Perl
Perl | Basic Syntax of a Perl Program
Hello World Program in Perl
Introduction to Perl
Get length of a string in Julia – length() Method

26 Mar, 2020
The length() is an inbuilt function in julia which is used to return the length of the specified string with desired starting and end position.
Syntax:length(S::AbstractString)orlength(S::AbstractString, i::Integer, j::Integer)
Parameters:
S::AbstractString: Specified string
i::Integer: Inclusive starting position.
i::Integer: Inclusive ending position.
Returns: It returns the length of the specified string with desired starting and end position.
Example 1:
# Julia program to illustrate # the use of String length() method  # Finding the length of the string# "Geeks"println(length("Geeks"))  # Finding the length of the string# "Geeks" from 2nd to 4th positionprintln(length("Geeks", 2, 4))  # Finding the length of the string# "Geeks" from 2nd to 5th positionprintln(length("Geeks", 2, 5))  # Finding the length of the string# "GeeksforGeeks" println(length("GeeksforGeeks"))  # Finding the length of the string# "GeeksforGeeks" from 2nd to 2nd positionprintln(length("GeeksforGeeks", 2, 2))  # Finding the length of the string# "GeeksforGeeks" from 4th to 10th positionprintln(length("GeeksforGeeks", 4, 10))
Output:Example 2:
# Julia program to illustrate # the use of String length() method   # Finding the length of the string# "12345"println(length("12345"))   # Finding the length of the string# "12345" from 2nd to 4th positionprintln(length("12345", 2, 4))   # Finding the length of the string# "2468" from 1st to 3rd positionprintln(length("2468", 2, 3))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use the foreach loop parallelly in PowerShell?

There are two ways to use the foreach loop parallelly in PowerShell.
Using Foreach-Object -Parallel command (Supports in PowerShell 7.0 or above)
Using Foreach-Object -Parallel command (Supports in PowerShell 7.0 or above)
Using Foreach -Parallel in Workflow (Supports PowerShell 5.1 or below)
Using Foreach -Parallel in Workflow (Supports PowerShell 5.1 or below)
Suppose we have Servers.txt and which contains 10 Servers. When we use the Parallel for loop, it isn’t guaranteed which server loop will pick first as shown below with two examples.
Using Foreach-Object-Parallel command. (not Foreach -Parallel)
Using Foreach-Object-Parallel command. (not Foreach -Parallel)
This Foreach-Object -Parallel command feature is newly added to the PowerShell version 7.0 or above.
$servers = Get-Content C:\Temp\Servers.txt

$servers | foreach-Object -parallel{
   Write-output "Working on $_"
}
PS C:\> C:\Temp\Test1.ps1
Working on IndiaServer003
Working on IndiaServer002
Working on IndiaServer001
Working on USServer001
Working on IndiaServer005
Working on USServer002
Working on IndiaServer006
Working on NZServer001
Working on NZServer002
If you have more servers, you can also set the -Throttlelimit parameter but need to make sure that the system should not get exhausted due to the throttle limit because it will create more runspaces.
Using PowerShell Workflow.
Using PowerShell Workflow.
If you are working with PowerShell 5.1, we can use Workflow feature Foreach -Parallel to run the loop parallelly. For example,
Workflow TestParallel{
   Foreach -parallel($server in (Get-Content C:\Temp\Servers.txt)){
      Write-Output "Working on $Server"
   }
}

TestParallel
PS C:\WINDOWS\system32> C:\Temp\Test1.ps1
Working on NZServer002
Working on NZServer001
Working on USServer002
Working on USServer001
Working on IndiaServer006
Working on IndiaServer005
Working on IndiaServer003
Working on IndiaServer002
Working on IndiaServer001
How to align multiple plots in a grid using GridSpec Class in Matplotlib

Aligning the multiple plots in a grid can be very messy and it can create multiple issues like higher width and height or minimal width to align all the plots. In order to align all the plots in a grid, we use GridSpec class.
Let us suppose that we have a bar graph plot and we want to align the symmetry of the plot in this sample.
First Import all the necessary libraries and plot some graphs in two grids. Then, we will plot a constant error bar and a symmetric and asymmetric error bar on the first grid. In the second grid, we will plot the sample error bar.
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

#Define the figure size and layout
fig = plt.figure(figsize=(8,8))
plt.style.use('seaborn-deep')

#Define the function to plot the graph
def plot_errorbar(axs, x, y, xerr=None, yerr=None, errevery=1,
   title=None, xlabel=None, ylabel=None, fmt=None):
      ax = fig.add_subplot(axs)
ax.errorbar(x, y, xerr=xerr, yerr=yerr, errorevery=errevery, fmt=fmt)
ax.set(title=title, xlabel=xlabel, ylabel=ylabel)

#First grid with size (3,1)
gs1 = GridSpec(3, 1)

#Data for exponential curve
x = np.arange(0.1, 5, 0.5)
y = np.exp(-x)

#Plot the errorbar with constant axis x and y
plot_errorbar(gs1[0], x, y, xerr=0.8, yerr=0.3, title='Constant
   Errors', xlabel='X', ylabel='Y', fmt='-o')
#Define the varying error with as a function of x
error = 0.1 + 0.25 * x
plot_errorbar(gs1[1], x, y, yerr=error, title='Variable Symmetric
   Error', xlabel='X', ylabel='Y', fmt='-o')

#Define the bounded and unbounded error
lower_error = 0.5 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
plot_errorbar(gs1[2], x, y, xerr=asymmetric_error, title='Variable
   Asymmetric Error', xlabel='X', ylabel='Y', fmt='o')

#Plot the Grid 2 with the same step as in Grid 1
gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])

#Define the data with a smaller interval for exponential curve
x = np.arange(0.1, 5, 0.1)
y = np.exp(-x)
gs2 = GridSpec(2, 1)
'yerr = 0.1 + 0.1 * np.sqrt(x)
plot_errorbar(gs2[0], x, y, yerr=yerr, title='All Errorbars', xlabel='X', ylabel='Y', fmt='-')
plot_errorbar(gs2[1], x, y, yerr=yerr, errevery=5, title='5th errorbar', xlabel='X', ylabel='Y', fmt='-')
gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.5)
top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)
gs1.update(top=top, bottom=bottom)
gs2.update(top=top, bottom=bottom)

#Display the plot
plt.show()
How many ways are there to initialize the instance variables of a class in java?

You can initialize the instance variables of a class using final methods, constructors or, Instance initialization blocks.
Whenever you make a method final, you cannot override it. i.e. you cannot provide implementation to the superclass’s final method from the subclass.
i.e. The purpose of making a method final is to prevent modification of a method from outside (child class). You can also use these final methods to initialize the instance variables.
 Live Demo
import java.util.Scanner;
public class FinalMethods {
   int age = getAge();
   String name = getName();
   static Scanner sc = new Scanner(System.in);
   public static final int getAge() {
      System.out.println("Enter age value");
      return sc.nextInt();
   }
   public static final String getName() {
      System.out.println("Enter name value");
      return sc.next();
   }
   public void display(){
      System.out.println("Name and age values: ");
      System.out.println(this.name);
      System.out.println(this.age);
   }
   public static void main(String args[]){
      FinalMethods obj = new FinalMethods();
      obj.display();
   }
}
Enter age value
25
Enter name value
Krishna
Name and age values:
Krishna
25
A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have the same name as their class and, have no return type.
There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.
 Live Demo
public class Test {
   String name;
   int age;
   public Test(String name, int age){
      this.name = name;
      this.age = age;
   }
   public static void main(String args[]) {
      Test obj = new Test("Krishna", 25);
      System.out.println("Name: "+obj.name);
      System.out.println("Age: "+obj.age);
   }
}
Name: Krishna
Age: 25
Similar to static blocks, Java also provides instance initialization blocks which are used to initialize instance variables, as an alternative to constructors.
Whenever you define an initialization block Java copies its code to the constructors. Therefore, you can also use these to share code between the constructors of a class.
 Live Demo
public class Student {
   String name;
   int age;
   {
      name = "Krishna";
      age = 25;
   }
   public static void main(String args[]){
      Student std = new Student();
      System.out.println(std.age);
      System.out.println(std.name);
   }
}
25
Krishna
Check if the current date falls in a given date range using MySQL query

Let us first create a table −
mysql> create table DemoTable1448
   -> (
   -> StartDate date,
   -> EndDate date
   -> );
Query OK, 0 rows affected (0.46 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1448 values('2019-01-21','2019-03-22');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1448 values('2019-04-05','2019-10-10');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1448 values('2019-10-01','2019-10-29');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1448 values('2018-12-31','2019-12-31');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1448;
This will produce the following output −
+------------+------------+
| StartDate  | EndDate    |
+------------+------------+
| 2019-01-21 | 2019-03-22 |
| 2019-04-05 | 2019-10-10 |
| 2019-10-01 | 2019-10-29 |
| 2018-12-31 | 2019-12-31 |
+------------+------------+
4 rows in set (0.00 sec)
Let’s say the current date is −
2019-10-05
Following is the query to check if the current date falls in a given date range −
mysql> select (curdate() >=StartDate and curdate() <=EndDate) as DateInRange from DemoTable1448;
This will produce the following output −
+-------------+
| DateInRange |
+-------------+
|           0 |
|           1 |
|           1 |
|           1 |
+-------------+
4 rows in set (0.04 sec)
Quiver Plots using Plotly in Python - GeeksforGeeks

05 Sep, 2020
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A quiver plot displays velocity vectors as arrows with the components (u, v) at the points (x, y). The quiver(x, y, u, v) plots vectors as arrows at the coordinates which are specified in each corresponding pair of elements in x and y. The main advantage of using a quiver plot is it can represent a wider range of magnitudes without having the arrows shrink to dots or overlap one another.
Syntax: create_quiver(x, y, u, v, scale=0.1, arrow_scale=0.3, angle=0.3490658503988659, scaleratio=None)
Parameters:
x: x coordinates of the arrow locations
y: y coordinates of the arrow locations
u: x components of the arrow vectors
v: y components of the arrow vectors
arrow_scale: value multiplied to length of barb to get length of arrowhead. Default = .3
angle: angle of arrowhead. Default = pi/9
Example:
Python3
import plotly.figure_factory as ffimport numpy as np  x = np.linspace(-2, 2, 60)y = np.linspace(-1, 1, 60)Y, X = np.meshgrid(x, y)u = 1 - X**2 + Yv = -1 + X - Y**2  # Create quiver plotfig = ff.create_quiver(x, y, u, v, arrow_scale=.1)  fig.show()
Output:
A quiver plot can be shown with the points with the help of the add_trace() method of graph_objects class. The scatter plot is added in such a way that shows the origin of the quivers.
Example:
Python3
import plotly.figure_factory as ffimport plotly.graph_objects as goimport numpy as np  x = np.linspace(-2, 2, 60)y = np.linspace(-1, 1, 60)Y, X = np.meshgrid(x, y)u = np.cos(X)*Yv = np.sin(X)*Y  # Create quiver plotfig = ff.create_quiver(x, y, u, v, arrow_scale=.1)  # Adding scatter as the originfig.add_trace(go.Scatter(x = [0], y = [0],                        mode = 'markers',                         marker_size = 15                        ))  fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Tailwind CSS Box Shadow - GeeksforGeeks

23 Mar, 2022
This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. By using this class we can control the box-shadow of an element. In CSS, we do that by using the CSS Shadow Effect properties of box-shadow. 
Box Shadow classes:
shadow-sm: This class is used to create a faded or small shadow effects on the box.
shadow: This class is used to create normal shadow effects on the box.
shadow-md: This class is used to create md effects on the box.
shadow-lg: This class is used to create lg shadow effects on the box.
shadow-xl: This class is used to create xl shadow effects on the box.
shadow-2xl: This class is used to create 2xl shadow effects on the box.
shadow-inner: This class is used to create shadow effects inside the box.
shadow-none: This class is used to dilute the shadow effects.
Syntax:
<element class="shadow-{shadow-depth}">...</element>
Example:
HTML
<!DOCTYPE html> <head>     <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"        rel="stylesheet"> </head>   <body class="text-center mx-4 space-y-2">     <h1 class="text-green-600 text-5xl font-bold">         GeeksforGeeks     </h1>     <b>Tailwind CSS Box Shadow Class</b>     <div class="grid grid-flow-col text-center p-2">         <div class="shadow-sm w-24 h-24 bg-green-200                     rounded-lg">shadow-sm        </div>        <div class="shadow w-24 h-24 bg-green-200                     rounded-lg">shadow        </div>        <div class="shadow-md w-24 h-24 bg-green-200                     rounded-lg">shadow-md        </div>        <div class="shadow-lg w-24 h-24 bg-green-200                     rounded-lg">shadow-lg        </div>        <div class="shadow-xl w-24 h-24 bg-green-200                     rounded-lg">shadow-xl        </div>        <div class="shadow-2xl w-24 h-24 bg-green-200                     rounded-lg">shadow-2xl        </div>    </div> </body>   </html>
Output:
Tailwind CSS Box shadow class
Tailwind CSS
Tailwind-Effects
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
What is the advantage of collapsing white space ? - GeeksforGeeks

21 Oct, 2021
White space refers to empty or blank values in the code which the browser reads and renders. Html has a special feature of collapsing these white spaces. If you put extra/consecutive white spaces or newlines in the code it will regard it as one white space this is known as collapsing of white spaces. In this article, we will discuss the advantages of collapsing white space in HTML.
Advantages of collapsing white spaces :
While you are writing the HTML for your web page you want the code to be more understandable/readable to the users.  
Collapsing white spaces decreases the transmission time between the server and the client because collapsing features remove unnecessary bytes that are occupied by the white spaces.
By mistake, if you leave extra white space, the browser will ignore it and display the UI perfectly.
Example 1:  The following example shows the basic example for collapsing white space. The h1 tag contains a lot of space between the short form and the full form.  If you run this code in the browser you will see the following output. All the white space in between the two has been converted into a single white space.
HTML
<!DOCTYPE html><html><head>    <title>Page Title</title></head><body>     <h1>Welcome to GFG.              GeeksforGeeks.</h1></body></html>
Output: 
Collapsed_White_Space
Example 2:  The following example shows a 2d array of Integers type in code as a structure with each row in a different line. If you will see the output it will come in one line with all the white spaces collapsed.
HTML
<!DOCTYPE html><html><body>    <h1>Example of a 2 D Array of Integers :             [            [1,2,3,4,5],            [6,7,8,9,10]            ]       </h1></body></html>
Output: 
Collapsed_White_Space
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Questions
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Bash program to check if the Number is a Prime or not - GeeksforGeeks

30 Sep, 2019
Given a number, the task is to find whether the given number is prime or not using Bash Scripting.
Examples:
Input: N = 43
Output: Prime

Input: N = 35
Output: Not Prime

Prime Numbers:A prime number is a whole number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 .....
Approach:We run a loop from 2 to number/2 and check if there is any factor of the number. If we find any factor then the number is composite otherwise prime.
Implementation:
#storing the number to be checkednumber=43i=2  #flag variablef=0  #running a loop from 2 to number/2while test $i -le `expr $number / 2` do  #checking if i is factor of numberif test `expr $number % $i` -eq 0 thenf=1fi  #increment the loop variablei=`expr $i + 1`doneif test $f -eq 1 thenecho "Not Prime"elseecho "Prime"fi
Output:
Prime

shubham_singh
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
'crontab' in Linux with Examples
diff command in Linux with examples
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
How to get current function name in PHP? - GeeksforGeeks

11 Nov, 2018
The function name can be easily obtained by the __FUNCTION__ or the __METHOD__magic constant.
Method 1 (Prints function name):__FUNCTION__ is used to resolve function name or method name (function in class).
Example:
<?phpclass Test {      public function bar() {        var_dump(__FUNCTION__);    }}  function foo() {    var_dump(__FUNCTION__);}  // Must output string(3) 'foo' foo();  $obj = new Test;  // Must output string(3) 'bar'$obj->bar();
string(3) "foo"
string(3) "bar"

Method 2 (Prints function and class name):using __METHOD__.
<?php  class Test {    public function foo() {        var_dump(__METHOD__);    }}    function bar(){    var_dump(__METHOD__);}  // Same As __FUNCTION__bar();  $obj = new Test;  // Output the fully qualified method name "ClassName::MethodName"$obj->foo();
string(3) "bar"
string(9) "Test::foo"

Note: this code is tested with php7.1
PHP-function
Picked
Technical Scripter 2018
PHP
Technical Scripter
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
How to get parameters from a URL string in PHP?
How to declare a global variable in PHP?
How to run JavaScript from PHP?
How to fetch data from localserver database and display on HTML table using PHP ?
Best way to initialize empty array in PHP
Python File fileno() Method

Python file method fileno() returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system.
Following is the syntax for fileno() method −
fileObject.fileno(); 

NA
NA
This method returns the integer file descriptor.
The following example shows the usage of fileno() method.
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name

fid = fo.fileno()
print "File Descriptor: ", fid

# Close opend file
fo.close()
When we run above program, it produces following result −
Name of the file:  foo.txt
File Descriptor:  3


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Isupper() and Islower() and their application in C++

The functions isupper() and islower() in C++ are inbuilt functions present in “ctype.h” header file. It checks whether the given character or string is in uppercase or lowercase.
This function is used to check whether the given string contains any uppercase letter or not and also if we have one character as an input then it checks whether the character is in uppercase or not.
int isupper ( int arg)
This function has return type as int as it returns non zero value when the string contains uppercase letter and 0 otherwise. It has one parameter which will contain the character to be checked.
Input − string s = “HELLo”
Output − It contains uppercase letter
Input − string s = “hello”
Output − It doesn’t contains uppercase letter
The function given below will check the string whether it contains uppercase letter or not and if it contains uppercase letter then it will convert them to a lowercase.
 Live Demo
#include <stdio.h>
#include <ctype.h>
int main (){
   int i=0;
   char str[]="Test String.\n";
   char c;
   while (str[i]){
      c=str[i];
      if (isupper(c)) c=tolower(c);
         putchar (c);
         i++;
   }
   return 0;
}
If we run the above code it will generate the following output −
test string.
This function is used to check whether the given string contains any lowercase letter or not and also if we have one character as an input then it checks whether the character is in lowercase or not.
int islower( int arg)
This function has return type as int as it returns non zero value when the string contains lowercase letter and 0 otherwise. It has one parameter which will contain the character to be checked.
Input − string s = “HELLo”
Output − It contains lowercase letter
Input − string s = “hello”
Output − It doesn’t contains lowercase letter
The function given below will check the string whether it contains lowercase letter or not and if it contains lowercase letter then it will convert them to a uppercase.
 Live Demo
#include <stdio.h>
#include <ctype.h>
int main (){
   int i=0;
   char str[]="Test String.\n";
   char c;
   while (str[i]) {
      c=str[i];
      if (islower(c)) c=toupper(c);
         putchar (c);
         i++;
   }
   return 0;
}
If we run the above code it will generate the following output − 
TEST STRING.
How to create a product card with CSS?

To create a product card with CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .productCard {
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
      max-width: 300px;
      margin: auto;
      text-align: center;
      font-family: arial;
      background-color: rgb(190, 224, 224);
   }
   .productDetails {
      color: rgb(26, 0, 51);
      font-weight: bold;
      font-size: 18px;
   }
   button {
      border: none;
      outline: 0;
      display: inline-block;
      padding: 8px;
      color: white;
      background-color: rgb(23, 31, 102);
      text-align: center;
      cursor: pointer;
      width: 100%;
      font-size: 18px;
   }
   button:hover, a:hover {
      opacity: 0.7;
   }
</style>
</head>
<body>
<h2 style="text-align:center">Product Card Example</h2>
<div class="productCard">
<img src="https://images.pexels.com/photos/1152077/pexels-photo-1152077.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
style="width:100%"/>
<h1>Leather Bag</h1>
<p class="productDetails">Exotic Quality</p>
<p>Price 50$</p>
<p><button>Buy Now</button></p>
</div>
</body>
</html>
The above code will produce the following output −
Count unique sublists within list in Python

A Python list can also contain sublist. A sublist itself is a list nested within a bigger list. In this article we will see how to count the number of unique sublists within a given list.
Counter is a subclass of Dictionary and used to keep track of elements and their count. It is also considered as an unordered collection where elements are stored as Dict keys and their count as dict value. So in the below example we directly take a list which has sublists.
 Live Demo
from collections import Counter
# Given List
Alist = [['Mon'],['Tue','Wed'],['Tue','Wed']]
print(Counter(str(elem) for elem in Alist))
Running the above code gives us the following result −
Counter({"['Tue', 'Wed']": 2, "['Mon']": 1})
We can also iterate through the elements of the list and setting it as tuple and then keep adding 1 for each occurrence of the same element. Finally print the new list showing the sublist as key and their count as values.
 Live Demo
# Given List
Alist = [['Mon'],['Tue','Wed'],['Tue','Wed'], ['Tue','Wed']]

# Initialize list
NewList = {}

# Use Append through Iteration
for elem in Alist:
   NewList.setdefault(tuple(elem), list()).append(1)
for k, v in NewList.items():
   NewList[k] = sum(v)

# Print Result
print(NewList)
Running the above code gives us the following result −
{('Mon',): 1, ('Tue', 'Wed'): 3}
How to take a screenshot of the window using Python?(Tkinter)

Python has a rich library of modules and functions that allows us to build and develop featured applications. Tkinter is a well-known Python library that is used for creating GUIbased applications. If we want to develop an application that takes a screenshot of the window, then we can definitely use Tkinter to build the GUI of the application. The following stages of the application will help to know how our application works,
Required Libraries – Pillow (PIL) for Image Processing, Time Module in Python for Randomizing the Filename and epochs processing.
Required Libraries – Pillow (PIL) for Image Processing, Time Module in Python for Randomizing the Filename and epochs processing.
Create a Label widget in the window and add a Button to take the screenshot.
Create a Label widget in the window and add a Button to take the screenshot.
Define a function, screenshot(), that will take the screenshot of the window and save the file in a local directory.
Define a function, screenshot(), that will take the screenshot of the window and save the file in a local directory.
In order to keep the Tkinter window away from taking screenshots as well as in the image, we can use withdraw() function to withdraw the image.
In order to keep the Tkinter window away from taking screenshots as well as in the image, we can use withdraw() function to withdraw the image.
# Import the required libraries
from tkinter import *
import time
from PIL import ImageTk, Image
import pyautogui as pg

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

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

# Define a function for taking screenshot
def screenshot():
   random = int(time.time())
   filename = "C:/Users/Sairam/Documents/" \ + str(random) + ".jpg"
   ss = pg.screenshot(filename)
   ss.show()
   win.deiconify()

def hide_window():
   # hiding the tkinter window while taking the screenshot
   win.withdraw()
   win.after(1000, screenshot)

# Add a Label widget
   Label(win, text="Click the Button to Take the Screenshot", font=('Times New Roman', 18, 'bold')).pack(pady=10)

# Create a Button to take the screenshots
button = Button(win, text="Take Screenshot", font=('Aerial 11 bold'), background="#aa7bb1", foreground="white", command=hide_window)
button.pack(pady=20)

win.mainloop()
Running the above code will display a window that contains a button and a Label text.
When we click the button, it will take a screenshot of the window and save it in a local directory.
Java program to print a given matrix in Spiral Form.

Following is a Java program to print the spiral form of a given matrix.
 Live Demo
public class PrintMatrixInSpiralForm {
   public static void main(String args[]){
      int a[][]={{1,2,3},{4,5,6},{7,8,9}};
      int w = 0;
      int x = a.length-1;
      int y = 0;
      int z = a[0].length-1;
      while(w <= x && y <= z){
         for (int i = w; i <= z; i++) {
            System.out.print(a[w][i] + " ");
         }
         for (int i = w+1; i <= x; i++) {
            System.out.print(a[i][z] + " ");
         }
         if(w+1 <= x){
            for (int i = z-1; i >= y; i--) {
               System.out.print(a[x][i] + " ");
            }
         }
         if(y+1 <= z){
            for (int i = x-1; i > w; i--) {
               System.out.print(a[i][y] + " ");
            }
         }
         w++;
         x--;
         y++;
         z--;
      }
   }
}
1 2 3 6 9 8 7 4 5
How to Package A Python Application using Anaconda and Docker | Towards Data Science

I rarely use anaconda for my python projects, but recently it happened to me to rely on a python package which is available only via Anaconda. Therefore, I had to set my project using conda environment. However, I encountered a problem packaging my python application using Docker, because of the conda virtual environment and I didn’t find much documentation to solve my problem. I finally found a solution and I share it with you here in this article.
The Source codes for this article are available on GitHub below:
github.com
The project structure for this article is the simple. Four files are necessary :
Create a file with .yaml extension:
environment.yaml
Name your conda environment, for instance app
Add a list of channels where the desired packages are hosted
List packages you want to install such as flask, gunicorn, numpy... under dependencies
You can also install pip packages from the YAML file. One way to it is by adding a pip command to install (pip) packages from a requirements.txt, (-r in the command stands for requirement)
For instance:
requirements.txt
Here we have created a test file main.py for testing the application.
main.py
Create a file named Dockerfile (without extension) from which we build a docker image for our Python application.
Dockerfile
For simplicity we start from the base image of miniconda3 (line1)
Copy the files from the folder to docker (line 6)
Create a conda environment and install the packages defined in YAML file (line 9)
Edit the shell command so we can launch python scripts from within the newly created conda environment (line 11)
Define an entry-point for the docker image such that it execute the main.py python script of the application (line 13)
We build a docker image, named app, with the following commands
docker build --tag myapp .
... then wait for docker to build an image for your app (it might tight a take for downloading and update it the packages list).
Note:
The Dockerfile must be located in the root directory of the applicationMake sure Docker is installed on your machine (www.docker.com).
The Dockerfile must be located in the root directory of the application
Make sure Docker is installed on your machine (www.docker.com).
To run the App from the docker image we created
docker run --rm -ti myapp 
This should outputs:
Hello World !Numpy version is  1.19.4
Done.
In this tutorial I walked you through a quick tutorial on how to package your python application using Docker and leveraging python package from pip and anaconda together. The key solution is in the SHELL command of Dockerfile. Without it Docker can not run the code inside the conda environment.
I hope it will benefit you.
Peace.
github.com
www.python.org
www.anaconda.com
www.docker.com
PS: If you encounter a problem please create an issue on GitHub or comment below.
Why the #1054 - Unknown column error occurs in MySQL and how to fix it?

Let’s see when the #1054 error occurs in MySQL. While inserting a varchar value, if you will forget to add single quotes, then this error will arise.

Following is the error −
mysql> insert into DemoTable798 values(100,Adam);
ERROR 1054 (42S22): Unknown column 'Adam' in 'field list'
You need to use single quotes around the string value to fix this error as shown below −
mysql> insert into DemoTable798 values(100,’Adam’);
Let us first create a table −
mysql> create table DemoTable798 (
   StudentId int,
   StudentName varchar(100)
);
Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable798 values(100,'Adam');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable798 values(101,'Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable798 values(102,'Robert');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable798 values(103,'Carol');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable798;
This will produce the following output -
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 100       | Adam        |
| 101       | Chris       |
| 102       | Robert      |
| 103       | Carol       |
+-----------+-------------+
4 rows in set (0.00 sec)
How to lock Screen Orientation programmatically in iOS?

You might come across a scenario where you need to show the UI in a specific orientation may be Landscape or Portrait.
We will be seeing how to lock orientation programmatically using Swift in iOS.
Open Xcode → New Project → ViewController.swift write the below code.
// Set the shouldAutorotate to False
override open var shouldAutorotate: Bool {
   return false
}

// Specify the orientation.
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
   return .portrait
}
JSF - h:commandButton

The h:commandButton tag renders an HTML input element of the type "submit".
<h:commandButton value = "Click Me!" onclick = "alert('Hello World!');" /> 
<input type = "submit" name = "j_idt10:j_idt13" value = "Click Me!" 
   onclick = "alert('Hello World!');" />

id
Identifier for a component
rendered
A boolean; false suppresses rendering
value
A component’s value, typically a value binding
valueChangeListener
A method binding to a method that responds to value changes
coords
Coordinates for an element whose shape is a rectangle, circle, or polygon
dir
Direction for text. Valid values are ltr (left to right) and rtl (right to left)
disabled
Disabled state of an input element or button
tabindex
Numerical value specifying a tab index
target
The name of a frame in which a document is opened
title
A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value
width
Width of an element
onblur
Element loses focus
onchange
Element’s value changes
onclick
Mouse button is clicked over the element
ondblclick
Mouse button is double-clicked over the element
onfocus
Element receives focus
onkeydown
Key is pressed
onkeypress
Key is pressed and subsequently released
onkeyup
Key is released
onmousedown
Mouse button is pressed over the element
onmousemove
Mouse moves over the element
onmouseout
Mouse leaves the element’s area
onmouseover
Mouse moves onto an element
onmouseup
Mouse button is released
onreset
Form is reset
onselect
Text is selected in an input field 
Let us create a test JSF application to test the above tag.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">
   <head>
      <title>JSF Tutorial!</title>
   </head>
   
   <body>
      <h2>h:commandButton example</h2>
      <hr />
      
      <h:form>
         <h:commandButton value = "Click Me!" onclick = "alert('Hello World!');" />
      </h:form>
   </body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.

    37 Lectures 
     3.5 hours 

 Chaand Sheikh
 Print
 Add Notes
 Bookmark this page
Bootstrap - Badges

This chapter will discuss about Bootstrap badges. Badges are similar to labels; the primary difference is that the corners are more rounded.
Badges are mainly used to highlight new or unread items. To use badges just add <span class = "badge"> to links, Bootstrap navs, and more.
The following example demonstrates this −
<a href = "#">Mailbox <span class = "badge">50</span></a>
When there are no new or unread items, badges will simply collapse via CSS's  :empty selector, provided no content exists within.
You can place badges in active states of pill and list navigations. You can achieve this by placing <span class = "badge"> to active links, as demonstrated in the following example −
<h4>Example for Active State in Pill </h4>

<ul class = "nav nav-pills">
   <li class = "active"><a href = "#">Home <span class ="badge">42</span></a></li>
   <li><a href = "#">Profile</a></li>
   <li><a href = "#">Messages <span class = "badge">3</span></a></li>
</ul>

<br>

<h4>Example for Active State in navigations</h4>

<ul class = "nav nav-pills nav-stacked" style = "max-width: 260px;">
   <li class = "active">
      <a href = "#">
         <span class = "badge pull-right">42</span>
         Home
      </a>
   </li>
	
   <li><a href = "#">Profile</a></li>
	
   <li>
      <a href = "#">
         <span class = "badge pull-right">3</span>
         Messages
      </a>
   </li>
</ul>
Home 42
Profile
Messages 3


42
               Home
            

Profile


3
               Messages
            


    26 Lectures 
     2 hours 

 Anadi Sharma

    54 Lectures 
     4.5 hours 

 Frahaan Hussain

    161 Lectures 
     14.5 hours 

 Eduonix Learning Solutions

    20 Lectures 
     4 hours 

 Azaz Patel

    15 Lectures 
     1.5 hours 

 Muhammad Ismail

    62 Lectures 
     8 hours 

 Yossef Ayman Zedan
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

CSS Rounded Corners
Tryit: Specify each corner
How to extract numbers from text using Python regular expression?

If we want to extract all numbers/digits  individually from given text we use the following regex
import re
s = '12345 abcdf 67'
result=re.findall(r'\d', s)
print result
['1', '2', '3', '4', '5', '6', '7']
If we want to extract groups of numbers/digits from given text we use the following regex
import re
s = '12345 abcdf 67'
result=re.findall(r'\d+', s)
print result
['12345', '67']
How to wait until an element no longer exists in Selenium?

We can wait until an element no longer exists in Selenium webdriver. This can be achieved with synchronization in Selenium. We shall add an explicit wait criteria where we shall stop or wait till the element no longer exists.
Timeout exception is thrown once the explicit wait time has elapsed and the expected behavior of the element is still not available on the page. To check if an element no longer exists on the page, we can take the help of the expected condition invisibilityOfElementLocated.
To implement explicit wait conditions, we have to take help of the WebDriverWait and ExpectedCondition class.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ElementInvisibleWait{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
      // identify element and click()
      driver.findElement(By.xpath("//*[text()='Library']")).click();
      // explicit wait of invisibility condition
      WebDriverWait w = new WebDriverWait(driver,5);
      // invisibilityOfElementLocated condition
      w.until(ExpectedConditions.
      invisibilityOfElementLocated(By.xpath("//*[@class='mui-btn']")));
      // get page title of next page
      System.out.println("Page title after click:" + driver.getTitle());
      driver.close()
   }
}
Next.js - Environment Variables

Next.js, has support for publishing environment variables in node which we can use in connecting to server, database etc. For this, we need to create .env.local file in root directory. We can also create .env.production.
Create .env.local in root directory with the following contents.
DB_HOST=localhost
DB_USER=tutorialspoint
DB_PASS=nextjs

Create a page named env.js with following contents in pages/posts directory where we'll use the environment variables using process.env.
import Head from 'next/head'
import Container from '../../components/container'

export default function FirstPost(props) {
   return (
      <>
         <Container>
            <Head>
               <title>Environment Variables</title>
            </Head>
            <h1>Database Credentials</h1>
               <p>Host: {props.host}</p>
               <p>Username: {props.username}</p>
               <p>Password: {props.password}</p>
         </Container>
      </>	  
   )
}

export async function getStaticProps() {
   // Connect to Database using DB properties
   return {
      props: { 
         host: process.env.DB_HOST,
         username: process.env.DB_USER,
         password: process.env.DB_PASS
      }
   }
}
 Now start the server.
Next.JS will detect .env.local and show follwing message on console.
npm run dev

> nextjs@1.0.0 dev D:\Node\nextjs
> next

ready - started server on http://localhost:3000
info  - Loaded env from D:\Node\nextjs\.env.local
event - compiled successfully
wait  - compiling...
event - compiled successfully
event - build page: /posts/env
wait  - compiling...
event - compiled successfully

Open localhost:3000/posts/env in a browser and you will see the following output.
 Print
 Add Notes
 Bookmark this page
java.time.LocalDate.format() Method Example

The java.time.LocalDate.format(DateTimeFormatter formatter) method formats this date using the specified formatter.
Following is the declaration for java.time.LocalDate.format(DateTimeFormatter formatter) method.
public String format(DateTimeFormatter formatter)

formatter − the formatter to use, not null.
the formatted date string, not null.
DateTimeException − if an error occurs during printing.
The following example shows the usage of java.time.LocalDate.format(DateTimeFormatter formatter) method.
package com.tutorialspoint;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateDemo {
   public static void main(String[] args) {

      LocalDate date = LocalDate.parse("2017-02-03");
      System.out.println(date);  
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY");
      System.out.println(formatter.format(date));  
   }
}
Let us compile and run the above program, this will produce the following result −
2017-02-03
03/02/2017

 Print
 Add Notes
 Bookmark this page
R - While Loop

The While loop executes the same code again and again until a stop condition is met.
The basic syntax for creating a while loop in R is −
while (test_expression) {
   statement
}

Here key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
v <- c("Hello","while loop")
cnt <- 2

while (cnt < 7) {
   print(v)
   cnt = cnt + 1
}
When the above code is compiled and executed, it produces the following result  −
[1] "Hello"  "while loop"
[1] "Hello"  "while loop"
[1] "Hello"  "while loop"
[1] "Hello"  "while loop"
[1] "Hello"  "while loop"


    12 Lectures 
     2 hours 

 Nishant Malik

    10 Lectures 
     1.5 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    20 Lectures 
     2 hours 

 Asif Hussain

    10 Lectures 
     1.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain
 Print
 Add Notes
 Bookmark this page
Program to find the sum of all digits of given number in Python

Suppose we have a number num, we have to find the sum of its digits. We have to solve it without using strings.
So, if the input is like num = 512, then the output will be 8, as 8 = 5 + 1 + 2.
tput will be 8, as 8 = 5 + 1 + 2.
To solve this, we will follow these steps −
sum:= 0
while num is not same as 0, dosum := sum + (num mod 10)num:= quotient of num/10
sum := sum + (num mod 10)
num:= quotient of num/10
return sum
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, num):
      sum=0
      while(num!=0):
         sum = sum+int(num%10)
         num=int(num/10)
      return sum
ob = Solution()
print(ob.solve(512))
512
8