code-rag-bench/online-tutorials huggingface dataset:
C++ Program to check if a given number is Lucky (all digits are different)

Given with a number and the task is to check whether the input number is a lucky number or not and display the result.
Lucky number is the number whose each and every digit is different and if at least one digit is repeating than the number will not be considered as a lucky number.
Input-: n = 1234
Output-: it is a lucky number
Explanation-: As there is no repeating digit in a number n so it is a lucky number
Input-: n = 3434
Output-: it is not a lucky number
Explanation-: In the given number n, 3 and 4 are repeating twice so it is not a lucky number
Approach we are using in the given program is as follows −
Input the number n from the user to check whether it’s a lucky number or not
Traverse the entire digit till the size of a number
Mark the digit visited on every visit and check whether it is already found or not
Display whether the given number is a lucky number or not
Start
Step1-> declare function to check whether a given number is lucky or not
   bool check_lucky(int size)
   declare bool arr[10]
   Loop For int i=0 and i<10 and i++
      Set arr[i] = false
   End
   Loop While(size > 0)
      declare int digit = size % 10
      IF (arr[digit])
         return false
      End
      set arr[digit] = true
      Set size = size/10
   End
   return true
Step 2-> In main()
   Declare int arr[] = {0,34,2345,1249,1232}
   calculate int size = sizeof(arr)/sizeof(arr[0])
   Loop For int i=0 and i<size and i++
      check_lucky(arr[i])?
      print  is Lucky : print is not Lucky
   End
Stop
#include<iostream>
using namespace std;
//return true if a number if lucky.
bool check_lucky(int size) {
    bool arr[10];
    for (int i=0; i<10; i++)
        arr[i] = false;
    while (size > 0) {
    int digit = size % 10;
      if (arr[digit])
           return false;
        arr[digit] = true;
        size = size/10;
    }
    return true;
}
int main() {
    int arr[] = {0,34,2345,1249,1232};
    int size = sizeof(arr)/sizeof(arr[0]);
    for (int i=0; i<size; i++)
        check_lucky(arr[i])? cout << arr[i] << " is Lucky \n": cout << arr[i] << " is not Lucky \n";
    return 0;
}
19 is Lucky
34 is Lucky
2345 is Lucky
1249 is Lucky
1232 is not Lucky
Python - List Exercises

Now you have learned a lot about lists, and how to use them in Python.
Are you ready for a test?
Try to insert the missing part to make the code work as expected:
Print the second item in the fruits list.
fruits = ["apple", "banana", "cherry"]
print()

Go to the Exercise section and test all of our Python List Exercises:

Python List Exercises

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Interface proximity sensor with Arduino

There are various types of proximity sensors available. Ultrasound sensor, which we discussed in another article for measuring distance, can also be used as a proximity sensor. In this article however, we will consider IR proximity sensor.
A typical IR proximity sensor looks like the one below −
There is an IR Emitter LED and an IR Receiver (photodiode). As you can see, the sensor has 3 pins (VCC, GND and OUT). The OUT pin gives a LOW signal when the there is an obstacle which acts as a reflecting surface, and the light from the LED is reflected back to the received.
Using the property of the OUT pin (LOW when obstacle is detected), we can program our Arduino to determine if an object is nearby.
The Circuit Diagram is shown below −
As you can see, the Vcc pin is connected to 5V on Arduino, GND to GND, and OUT to pin 7.
The code is quite straightforward, as you can see below −
int signalPin = 7;
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   pinMode(signalPin,INPUT);
}
void loop() {
   // put your main code here, to run repeatedly:
   if (digitalRead(signalPin) == HIGH) {
      Serial.println("Obstacle present right now!");
   } else {
      Serial.println("No obstacle!");
   }
   delay(1000);
}
Try placing your hand in front of the IR sensor, and then removing it. And observe the changes in print statement on the Serial monitor.
Python - Stack

In the english dictionary the word stack means arranging objects on over another. It is the same way memory is allocated in this data structure. It stores the data elements in a similar fashion as a bunch of plates are stored one above another in the kitchen. So stack data strcuture allows operations at one end wich can be called top of the stack.We can add elements or remove elements only form this en dof the stack.
In a stack the element insreted last in sequence will come out first as we can remove only from the top of the stack. Such feature is known as Last in First Out(LIFO) feature. The operations of adding and removing the elements is known as PUSH and POP. In the following program we implement it as add and and remove functions. We declare an empty list and use the append() and pop() methods to add and remove the data elements.
Let us understand, how to use PUSH in Stack. Refer the program mentioned program below −
class Stack:
   def __init__(self):
      self.stack = []

   def add(self, dataval):
# Use list append method to add element
      if dataval not in self.stack:
         self.stack.append(dataval)
         return True
      else:
         return False
# Use peek to look at the top of the stack
   def peek(self):     
	   return self.stack[-1]

AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
print(AStack.peek())
When the above code is executed, it produces the following result −
Tue
Thu

As we know we can remove only the top most data element from the stack, we implement a python program which does that. The remove function in the following program returns the top most element. we check the top element by calculating the size of the stack first and then use the in-built pop() method to find out the top most element.
class Stack:
   def __init__(self):
      self.stack = []

   def add(self, dataval):
# Use list append method to add element
      if dataval not in self.stack:
         self.stack.append(dataval)
         return True
      else:
         return False
        
# Use list pop method to remove element
   def remove(self):
      if len(self.stack) <= 0:
         return ("No element in the Stack")
      else:
         return self.stack.pop()

AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())
When the above code is executed, it produces the following result −
Thu
Wed


    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
Read text File with Space as Delimiter in R - GeeksforGeeks

23 Sep, 2021
In this article, we will discuss how to read a text file with spaces as delimiters in R programming language.
Base R allows us to read and access the content within the text files with any number of characters as the delimiter. 
File in use: 
The read.table() method in R can be used to read data from a text file into the data.table or a similar R object. In case the file is located within the same directory, the file-name is specified, else the complete path to the file is given in the workspace. Also, the header is an optional parameter, if TRUE, the header is read into the workspace else, omitted. 
Syntax:
read.table( path-of-the-file, header = T)
Example: Read TXT file with spaces as a delimiter
R
# reading data from the text filefile_path <- "r_content.txt"  data_table <- read.table(file_path,                    header = TRUE)  print("Contents of the text file")print(data_table)
Output:
[1] "Contents of the text file" 
col1 col2 col3 
1    1    3    A 
2    3    5    B 
3    6    8    C 
4    8   12    D
The “sep” argument is used to specify the delimiter of the text file cell values. The “sep” argument of the data.table can also be used to read a text file containing data with single or multiple spaces as delimiters. The sep = “” is used to refer to any length whitespace as being the delimiter.
Syntax:
read.table(filepath, sep, header=T, na.strings, stringAsFactors)
Example: Read TXT file with spaces as a delimiter
R
# reading data from the text filefile_path <- "r_content.txt"  data_table <- read.table(file_path, sep = "" , header = T ,                                  na.strings ="",                          stringsAsFactors= F)  print("Contents of the text file")print(data_table)
Output:
[1] "Contents of the text file" 
col1 col2 col3 
1    1    3    A 
2    3    5    B 
3    6    8    C 
4    8   12    D
Picked
R-FileHandling
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
How to change the order of bars in bar chart in R ?
How to select data in MySQL where a field has a minimum value?

To select data where a field has min value, you can use aggregate function min(). The syntax is as follows.
SELECT *FROM yourTableName WHERE yourColumnName=(SELECT MIN(yourColumnName) FROM yourTableName);
To understand the above syntax, let us create a table. The query to create a table is as follows.
mysql> create table MinValueDemo
-> (
-> ProductId int,
-> ProductName varchar(100),
-> ProductPrice int
-> );
Query OK, 0 rows affected (0.77 sec)
Insert some records in the table using insert command. The query is as follows.
mysql> insert into MinValueDemo values(1,'product-1',4500);
Query OK, 1 row affected (0.14 sec)

mysql> insert into MinValueDemo values(2,'product-2',4340);
Query OK, 1 row affected (0.22 sec)

mysql> insert into MinValueDemo values(3,'product-3',4110);
Query OK, 1 row affected (0.18 sec)

mysql> insert into MinValueDemo values(4,'product-4',4344);
Query OK, 1 row affected (0.16 sec)

mysql> insert into MinValueDemo values(5,'product-5',4103);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement. The query is as follows.
mysql> select *from MinValueDemo;
The following is the output.
+-----------+-------------+--------------+
| ProductId | ProductName | ProductPrice |
+-----------+-------------+--------------+
| 1         | product-1   | 4500         |
| 2         | product-2   | 4340         |
| 3         | product-3   | 4110         |
| 4         | product-4   | 4344         |
| 5         | product-5   | 4103         |
+-----------+-------------+--------------+
5 rows in set (0.00 sec)
Here is the query to select data where the ‘ProductPrice’ has the minimum value using aggregate function MIN() from MySQL.
mysql> select *from MinValueDemo
-> where ProductPrice=(select min(ProductPrice) from MinValueDemo);
The following is the output.
+-----------+-------------+--------------+
| ProductId | ProductName | ProductPrice |
+-----------+-------------+--------------+
| 5         | product-5   | 4103         |
+-----------+-------------+--------------+
1 row in set (0.08 sec)
How to access variables declared in a function, from another function using JavaScript?

We have to write a function, that does some simple task, say adding two numbers or something like that. We are required to demonstrate the way we can access the variables declared inside that function in some other function or globally.
Following is the code −
const num = 5;
const addRandomToNumber = function(num){
   // a random number between [0, 10)
   const random = Math.floor(Math.random() * 10);
   // assigning the random to this object of function
   // so that we can access it outside
   this.random = random;
   this.res = num + random;
};
const addRandomInstance = new addRandomToNumber(num);
const scopedRandom = addRandomInstance.random;
const result = addRandomInstance.res;
// must be equal to the original value of num i.e., 5
console.log(result - scopedRandom);
Following is the output in the console −
5
Drop rows containing specific value in PySpark dataframe - GeeksforGeeks

30 Jun, 2021

In this article, we are going to drop the rows with a specific value in pyspark dataframe.
Creating dataframe for demonstration:
Python3
 

 
 










# importing module 
import pyspark 
  
# importing sparksession from pyspark.sql module 
from pyspark.sql import SparkSession 
  
# creating sparksession and giving an app name 
spark = SparkSession.builder.appName('sparkdf').getOrCreate() 
  
# list  of students  data 
data = [["1", "sravan", "vignan"], 
        ["2", "ojaswi", "vvit"], 
        ["3", "rohith", "vvit"], 
        ["4", "sridevi", "vignan"], 
        ["6", "ravi", "vrs"], 
        ["5", "gnanesh", "iit"]] 
  
# specify column names 
columns = ['ID', 'NAME', 'college'] 
  
# creating a dataframe from the lists of data 
dataframe = spark.createDataFrame(data, columns) 
  
print('Actual data in dataframe') 
dataframe.show() 






Output:
Method 1: Using where() function
This function is used to check the condition and give the results. That means it drops the rows based on the values in the dataframe column
Syntax: dataframe.where(condition)
Example 1: Python program to drop rows with college = vrs.
Python3
 

 
 










# drop rows with college vrs 
dataframe.where(dataframe.college!='vrs').show() 






Output:
Example 2: Python program to drop rows with ID=1
Python3
 

 
 










# drop rows with id=1  
dataframe.where(dataframe.ID !='1').show() 






Output:
Method 2: Using filter() function
This function is used to check the condition and give the results, Which means it drops the rows based on the values in the dataframe column. Both are similar.
Syntax: dataframe.filter(condition)
Example: Python code to drop row with name = ravi.
Python3
 

 
 










# drop rows with name = ravi  
dataframe.filter(dataframe.NAME !='ravi').show() 






Output:

Picked


Python-Pyspark


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 drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to update MySQL column with random value?

To update column with random value, you can use the below syntax−
update yourTableName set yourColumnName =round(1+rand()*100);
The above syntax will generate a value between 1 to 100. Let us see an example and create a table−
mysql> create table DemoTable
   (
   Number int
   );
Query OK, 0 rows affected (0.46 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(80);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(100000);
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable values(987);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output−
+--------+
| Number |
+--------+
| 10     |
| 100    |
| 80     |
| 100000 |
| 987    |
+--------+
5 rows in set (0.00 sec)
Following is the query to update column with random value−
mysql> update DemoTable set Number=round(1+rand()*100);
Query OK, 5 rows affected (0.46 sec)
Rows matched: 5 Changed: 5 Warnings: 0
Let us display table records once again−
mysql> select *from DemoTable;
This will produce the following output −
+--------+
| Number |
+--------+
| 33     |
| 88     |
| 41     |
| 39     |
| 70     |
+--------+
5 rows in set (0.00 sec)
Process Representation in Linux System

Linux can manage the processes in the system, each process is represented by a task_struct C data structure. It is found in the <linux/sched.h> include file in the kernel source-code directory. The task vector is an array of pointers to every task_struct data structure in the system. As well as the normal type of process, Linux supports real time processes. All the required information i.e; the state of the process, scheduling and memory-management information, list of open files, and pointers to the process’s parent and a list of its children and siblings are contained in this structure.
A process who creates a process is called parent of that created process; its children are any processes that it creates and siblings are children with the same parent process.
Some of these fields include −
long state; /*denote state of the process */
struct sched entity se; /*denote scheduling information */
struct task struct *parent; /*denotes this process’s parent */
struct list head children; /*denotes this process’s children */
struct files struct *files; /* denotes list of open files */
struct mm struct *mm; /* denotes address space of this process */
struct task struct *p_opptr,*p_pptr,*p_cptr,*p_ysptr,*p_osptr
/*denotes, op = original parent, p = parent, c = youngest child, ys = youngest sibling, os = older sibling */
All active processes are represented using a doubly linked list of task struct, within the Linux kernel. A pointer is maintained by Kernel –current-to the process currently executing on the system, as shown below −
E.g. If the system would like to change the state of the process currently running to the value new state. If current is a pointer to the process currently executing, its state is changed with the following: current->state = new state;
PHP | natsort() Function - GeeksforGeeks

08 Mar, 2018
The natsort() function is an inbuilt function in PHP which is used to sort an array by using a “natural order” algorithm. The natural order tells the order to be used as a normal human being would use. That is, it does not check the type of value for comparison. For example, in string representation 30 is less than 7 according to the standard sorting algorithm as 3 comes before 7 lexicographically. But in natural order 30 is greater than 7.
Syntax:
bool natsort(array)
Parameters: This function accepts a single parameter $array. It is the array which natsort() function is going to sort.
Return Value: It returns a boolean value i.e., TRUE on success and FALSE on failure.
Below programs illustrate the natsort() function in PHP:
Program 1:
<?php  // input array$arr1 = array("12.jpeg", "10.jpeg", "2.jpeg", "1.jpeg");$arr2 = $arr1;  // sorting using sort function.sort($arr1);  // printing sorted element.echo "Standard sorting\n";print_r($arr1);  // sorting using natsort() function.natsort($arr2);  // printing sorted element.echo "\nNatural order sorting\n";print_r($arr2);  ?>
Output:
Standard sorting
Array
(
    [3] => 1.jpeg
    [1] => 10.jpeg
    [0] => 12.jpeg
    [2] => 2.jpeg
)

Natural order sorting
Array
(
    [3] => 1.jpeg
    [2] => 2.jpeg
    [1] => 10.jpeg
    [0] => 12.jpeg
)

Program 2:
<?php  // input array$arr = array("gfg15.jpeg", "gfg10.jpeg", "gfg1.jpeg",                           "gfg22.jpeg", "gfg2.jpeg");  // sorting using natsort() function.natsort($arr);  // printing sorted element.echo "\nNatural order sorting\n";print_r($arr);  ?>
Output:
Natural order sorting
Array
(
    [2] => gfg1.jpeg
    [4] => gfg2.jpeg
    [1] => gfg10.jpeg
    [0] => gfg15.jpeg
    [3] => gfg22.jpeg
)

Reference:http://php.net/manual/en/function.natsort.php
PHP-function
PHP-string
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 convert array to string in PHP ?
Comparing two dates in PHP
PHP | Converting string to Date and DateTime
How to fetch data from localserver database and display on HTML table using PHP ?
Download file from URL using PHP
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Explain the quick sort technique in C language.

Sorting is the process of arranging the elements either in ascending (or) descending order.
C language provides five sorting techniques, which are as follows −
Bubble sort (or) Exchange Sort
Selection sort
Insertion sort(or) Linear sort
Quick sort (or) Partition exchange sort
Merge Sort (or) External sort
It is a divide and conquer algorithm.
Step 1 − Pick an element from an array, call it as pivot element.
Step 2 − Divide an unsorted array element into two arrays.
Step 3 − If the value less than pivot element come under first sub array, the remaining elements with value greater than pivot come in second sub array.
Consider an example given below, wherein
P is the pivot element.
L is the left pointer.
R is the right pointer.
The elements are 6, 3, 7, 2, 4, 5.
Now,
The pivot is in fixed position.
All the left elements are less.
The right elements are greater than pivot.
Now, divide the array into 2 sub arrays left part and right part.
Take left partition apply quick sort.
Now,
The pivot is in fixed position.
All the left elements are less and sorted
The right elements are greater and are in sorted order.
The final sorted list is combining two sub arrays is 2, 3, 4, 5, 6, 7
Following is the C program to sort the elements by using the quick sort technique −
 Live Demo
#include<stdio.h>
void quicksort(int number[25],int first,int last){
   int i, j, pivot, temp;
   if(first<last){
      pivot=first;
      i=first;
      j=last;
      while(i<j){
         while(number[i]<=number[pivot]&&i<last)
         i++;
         while(number[j]>number[pivot])
         j--;
         if(i<j){
            temp=number[i];
            number[i]=number[j];
            number[j]=temp;
         }
      }
      temp=number[pivot];
      number[pivot]=number[j];
      number[j]=temp;
      quicksort(number,first,j-1);
      quicksort(number,j+1,last);
   }
}
int main(){
   int i, count, number[25];
   printf("How many elements are u going to enter?: ");
   scanf("%d",&count);
   printf("Enter %d elements: ", count);
   for(i=0;i<count;i++)
   scanf("%d",&number[i]);
   quicksort(number,0,count-1);
   printf("Order of Sorted elements: ");
   for(i=0;i<count;i++)
   printf(" %d",number[i]);
   return 0;
}
When the above program is executed, it produces the following output −
How many elements are u going to enter?: 10
Enter 10 elements: 2 3 5 7 1 9 3 8 0 4
Order of Sorted elements: 0 1 2 3 3 4 5 7 8 9
Draw an ellipse in C#

To draw an ellipse, use the drawEllipse() method in C# that belong to the Graphics object.  It has a pen object as well as a rectangle object.
You need windows form to draw shapes in C#.
Set graphics object.
Graphics g = this.CreateGraphics();

Now, the pen object.
Pen p = new Pen(new SolidBrush(Color.Red), 15);

The following is the rectangle object.
Rectangle r = new Rectangle(120, 60, 180, 180);

Now use the drawEllipse() method with the graphics object and add both the objects in it to draw an ellipse.
s.DrawEllipse(p, r);
How to sort a data frame in R by multiple columns together?

We can sort a data frame by multiple columns using order function.
Consider the below data frame −
> df <- data.frame(x1 = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
x2 = c("A", "B", "D", "C"), x3 = c(4, 7, 5, 3),
x4 = c(9, 5, 7, 4))
> df
x1 x2 x3 x4
1 Hi A 4 9
2 Med B 7 5
3 Hi D 5 7
4 Low C 3 4
Let’s say we want to sort the data frame by column x4 in descending order then by
column x1 in ascending order.
It can be done follows −
> df[with(df, order(-x4, x1)), ]
x1 x2 x3 x4
1 Hi A 4 9
3 Hi D 5 7
2 Med B 7 5
4 Low C 3 4
We can do it by using column index as well −
> df[order(-df[,4], df[,1]), ]
x1 x2 x3 x4
1 Hi A 4 9
3 Hi D 5 7
2 Med B 7 5
4 Low C 3 4
Count dictionaries in a list in Python - GeeksforGeeks

29 Apr, 2020
A list in Python may have items of different types. Sometimes, while working with data, we can have a problem in which we need to find the count of dictionaries in particular list. This can have application in data domains including web development and Machine Learning. Lets discuss certain ways in which this task can be performed.
Input : test_list = [4, 5, ‘gfg’]Output : 0
Input : test_list = [{‘gfg’ : 1}]Output : 1
Input : test_list = [10, {‘gfg’ : 1}, {‘ide’ : 2, ‘code’ : 3}, 20]Output : 2
Input : test_list = [4, 5, ‘gfg’, {‘best’: 32, ‘gfg’: 1}, {‘CS’: 4}, (1, 2)]Output : 2
Method #1 : Using list comprehension + isinstance()The combination of above functionalities can be used to solve this problem. In this, we perform iteration using list comprehension and test for dictionary using isinstance().
# Python3 code to demonstrate working of # Dictionary Count in List# Using list comprehension + isinstance()  # initializing listtest_list = [10, {'gfg' : 1}, {'ide' : 2, 'code' : 3}, 20]  # printing original listprint("The original list is : " + str(test_list))  # Dictionary Count in List# Using list comprehension + isinstance()res = len([ele for ele in test_list if isinstance(ele, dict)])  # printing result print("The Dictionary count : " + str(res)) 
The original list is : [10, {'gfg': 1}, {'code': 3, 'ide': 2}, 20]
The Dictionary count : 2

 
Method #2 : Using recursion + isinstance() ( for nested dictionaries)The combination of above functionalities can be used to solve this problem. In this, we also solve the problem of inner nesting using recursion.
# Python3 code to demonstrate working of # Dictionary Count in List# Using recursion + isinstance()  # helper_funcdef hlper_fnc(test_list):    count = 0    if isinstance(test_list, str):        return 0    if isinstance(test_list, dict):        return hlper_fnc(test_list.values()) + hlper_fnc(test_list.keys()) + 1    try:        for idx in test_list:            count = count + hlper_fnc(idx)    except TypeError:        return 0    return count  # initializing listtest_list = [10, {'gfg': 1}, {'code': 3, 'ide': 2}, 20]  # printing original listprint("The original list is : " + str(test_list))  # Dictionary Count in List# Using recursion + isinstance()res = hlper_fnc(test_list)  # printing result print("The Dictionary count : " + str(res)) 
The original list is : [10, {'gfg': 1}, {'code': 3, 'ide': 2}, 20]
The Dictionary count : 2

Python dictionary-programs
Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
HTML | selected Attribute - GeeksforGeeks

03 Dec, 2021
The selected attribute in HTML is used to specify which option should be by default selected when the page loads. This is a boolean attribute. The option that is having the selected attribute will be displayed by default.Syntax:  
<option selected>value</option>
Note: This attribute can be used only on <option> element.Example: Below HTML program to illustrate selected Attribute  
html
<!DOCTYPE html><html>    <head>        <title>HTML selected Attribute</title>    </head>    <body style = "text-align: center;">        <h1 style = "color: green;">GeeksforGeeks</h1>        <h2>HTML selected Attribute</h2>                 <!-- List of Options -->        <select>            <option value="merge">Merge Sort</option>            <option value="bubble">Bubble Sort</option>            <option value="insertion">Insertion Sort</option>                         <!-- Option element with selected attribute -->            <option value="quick" selected>Quick Sort</option>        </select>    </body></html>                   
Output:  
Supported Browsers: The browser supported by selected attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
simranarora5sos
ManasChhabra2
HTML-Attributes
CSS
HTML
Web Technologies
HTML
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?
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 set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Differences between Functional and Non-functional Testing - GeeksforGeeks

08 May, 2019
Functional Testing:Functional testing is a type of software testing in which the system is tested against the functional requirements and specifications. Functional testing ensures that the requirements or specifications are properly satisfied by the application. This type of testing is particularly concerned with the result of processing. It focuses on simulation of actual system usage but does not develop any system structure assumptions.
It is basically defined as a type of testing which verifies that each function of the software application works in conformance with the requirement and specification. This testing is not concerned about the source code of the application. Each functionality of the software application is tested by providing appropriate test input, expecting the output and comparing the actual output with the expected output.
Non-functional Testing:Non-functional testing is a type of software testing that is performed to verify the non-functional requirements of the application. It verifies whether the behavior of the system is as per the requirement or not. It tests all the aspects which are not tested in functional testing.
Non-functional testing is defined as a type of software testing to check non-functional aspects of a software application. It is designed to test the readiness of a system as per nonfunctional parameters which are never addressed by functional testing. Non-functional testing is as important as functional testing.
Below is the difference between functional and non-functional testing:
1. Unit Testing
2. Smoke Testing
3. Integration Testing
4. Regression Testing 
1. Performance Testing
2. Load Testing
3. Stress Testing
4. Scalability Testing 
Software Testing
Difference Between
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Types of Software Testing
Software Engineering | COCOMO Model
Functional vs Non Functional Requirements
Software Engineering | Coupling and Cohesion
Software Engineering | Spiral Model
PHP | imagestring() Function - GeeksforGeeks

17 Aug, 2018
The imagestring() function is an inbuilt function in PHP which is used to draw the string horizontally. This function draws the string at given position.
Syntax:
bool imagestring( $image, $font, $x, $y, $string, $color )
Parameters: This function accepts six parameters as mentioned above and described below:
$image: The imagecreatetruecolor() function is used to create a blank image in a given size.
$font: This parameter is used to set the font size. Inbuilt font in latin2 encoding can be 1, 2, 3, 4, 5 or other font identifiers registered with imageloadfont() function.
$x: This parameter is used to hold the x-coordinate of the upper left corner.
$y: This parameter is used to hold the y-coordinate of the upper left corner.
$string: This parameter is used to hold the string to be written.
$color: This parameter is used to hold the color of image.
Return Value: This function returns TRUE on success or FALSE on failure.
Below programs illustrate the imagestring() function in PHP.Program 1:
<?php   // Create the size of image or blank image$image = imagecreate(500, 300);   // Set the background color of image$background_color = imagecolorallocate($image, 0, 153, 0);   // Set the text color of image$text_color = imagecolorallocate($image, 255, 255, 255);   // Function to create image which contains string.imagestring($image, 5, 180, 100,  "GeeksforGeeks", $text_color);imagestring($image, 3, 160, 120,  "A computer science portal", $text_color);   header("Content-Type: image/png");   imagepng($image);imagedestroy($image);?>
Output:
Program 2:
<?php  // Create the size of image or blank image$image = imagecreate(500, 300);  // Set the background color of image$background_color = imagecolorallocate($image, 255, 255, 255);  // Set the text color of image$text_color = imagecolorallocate($image, 0, 153, 0);  // Function to create image which contains string.imagestring($image, 5, 50, 100,      "GeeksforGeeks: A computer science portal", $text_color);  header("Content-Type: image/png");  imagepng($image);imagedestroy($image);?>
Output:
Related Articles:
PHP | imagedashedline() Function
PHP | imagecolorat() function
PHP | imagepolygon() Function
Reference: http://php.net/manual/en/function.imagestring.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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?
How to find Definite Integral using Python ? - GeeksforGeeks

15 Mar, 2021
Definite integrals are the extension after indefinite integrals, definite integrals have limits [a, b]. It gives the area of a curve bounded between given limits.
It denotes the area of curve F(x) bounded between a and b, where a is the lower limit and b is the upper limit.
In this article, we will discuss how we can solve definite integrals in python, and would also visualize the area between them using matplotlib. We would also use the NumPy module for defining the range of the variable we are integrating. Let’s Begin with installing the modules.
matplotlib: We would use this to visualize our area under the graph formed by a definite integral.
numpy: Helper library to define ranges of definite integrals.
sympy: Library to calculate the numerical solution of the integral easily.
For calculating area under curve
Import module
Declare function
Integrate.
Syntax : 
sympy.integrate(expression, reference variable)
For plotting 
Import module
Define a function
Define a variable
Draw the curve
Fill the color under it using some condition.
Display plot
Given below is the implementation for the same.
The area between a curve and standard axis
Example 1 :
Python
import matplotlib.pyplot as pltimport numpy as npimport sympy as sy    def f(x):    return x**2  x = sy.Symbol("x")print(sy.integrate(f(x), (x, 0, 2)))
Output:
8/3
Example 2:
Python3
import matplotlib.pyplot as pltimport numpy as np    def f(x):    return x**2  x = np.linspace(0, 2, 1000)plt.plot(x, f(x))plt.axhline(color="black")plt.fill_between(x, f(x), where=[(x > 0) and (x < 2) for x in x])plt.show()
Output:
The area between two curves
Example 1:
Python3
import matplotlib.pyplot as pltimport numpy as npimport sympy as sy    def f(x):    return x**2    def g(x):    return x**(1/2)    x = sy.Symbol("x")print(sy.integrate(f(x)-g(x), (x, 0, 2)))
Output:
0.781048583502540
Example 2:
Python3
import matplotlib.pyplot as pltimport numpy as np    def f(x):    return x**2    def g(x):    return x**(1/2)    x = np.linspace(0, 2, 1000)plt.plot(x, f(x))plt.plot(x, g(x))plt.fill_between(x, f(x), g(x), where=[(x > 0) and (x < 2) for x in x])plt.show()
Output:
Picked
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
How to Rotate Image in HTML ? - GeeksforGeeks

22 Jun, 2021
You can easily rotate images in HTML using the CSS transform property. This property is used to move, rotate, scale, and perform various kinds of transformations of elements.
Approach: You can use rotate() function defined as a transformation that rotates an element around a fixed point on the 2D plane, without deforming it. It takes one parameter which defines the rotation angle. The rotation angle consists of two parts, the value of the rotation followed by the unit of rotation. The unit can be defined in degrees (deg), gradient (grad), radians (rad), and turns. The value with the method rotate() will rotate an element clockwise.
Note: To rotate by 90 degrees any of the units can be used with their corresponding values. 90 degrees would equal 100 gradients or 0.25 turns.
 
Syntax:
transform: rotate(90deg);
It is recommended to add the below code in CSS so that your code is compatible with all major browsers because people using other browsers will see It upside down.
CSS code:
-webkit-transform:rotate(180deg); /* Chrome, Safari, Opera */
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);   /* Standard syntax */
Example:
HTML
<!DOCTYPE html><html>  <head>    <style>        .rotate_image {            -webkit-transform: rotate(45deg);            -moz-transform: rotate(45deg);            -ms-transform: rotate(45deg);            -o-transform: rotate(45deg);            transform: rotate(45deg);        }          h1 {            color: green;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>      <center>        <img class="rotate_image"            src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"            alt="GeeksforGeeks logo">    </center></body>  </html>
Output:
Without using transform: rotate() property:
Using transform: rotate() property:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Properties
CSS-Questions
HTML-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
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 ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Node.js | os.tmpdir() Method - GeeksforGeeks

14 Feb, 2020
The os.tmpdir() method is an inbuilt application programming interface of the os module which is used to get path of default directory for temporary files of the operating system.
Syntax:
os.tmpdir()
Parameters: This method does not accept any parameters.
Return Value: This method returns a string specifies the path to the default directory for temporary files of the operating system.
Below examples illustrate the use of os.tmpdir() method in Node.js:
Example 1:
// Node.js program to demonstrate the    // os.tmpdir() method      // Allocating os moduleconst os = require('os');  // Display os.tmpdir() valueconsole.log(os.tmpdir());
Output:
C:\Users\gekcho\AppData\Local\Temp

Example 2:
// Node.js program to demonstrate the    // os.tmpdir() method      // Allocating os moduleconst os = require('os');  console.log("home directory:" + getUserHome());console.log("temp directory:" + os.tmpdir());  function getUserHome() {          // From process.env    return process.env[(process.platform == 'win32')            ? 'USERPROFILE' : 'HOME'];}
Output:
home directory:C:\Users\gekcho
temp directory:C:\Users\gekcho\AppData\Local\Temp

Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/os.html#os_os_tmpdir
Node.js-os-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Express.js res.render() Function
Express.js res.redirect() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to copy file in Python3? - GeeksforGeeks

02 Dec, 2020
Prerequisites: Shutil
When we require a backup of data, we usually make a copy of that file. Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Here we will learn how to copy a file using Python3.
Method 1 : Using shutil library
shutil library includes a method call copyfile(). The method takes two parameters, one is source path of file and other is destination path of file. The following image includes a file with its path.
Syntax:
copyfile(source_path,destination_path)
Source Path of File
Program:
Python3
# copy a file using shutil.copyfile() methodimport shutil  # path where original file is locatedsourcePath = "c:\\SourceFolder\\gfg.txt"  # path were a copy of file is neededdestinationPath = "c:\\DestinationFolder\\gfgcopy.txt"  # call copyfile() methodshutil.copyfile(sourcePath, destinationPath)
Output:
Destination Folder
Method 2 : copying data of file into another file
Copying data of one file to another file could also create a backup of file. Suppose the data of file is as below:
Data in source file
Program:
Python3
# open source file in read modesource = open("c:\\SourceFolder\\gfg.txt", "r")  # open destination file in write modedest = open("c:\\DestinationFolder\\gfgcopy.txt", "w")  # read first lineline = source.readline()  # read lines until reached EOFwhile line:      # write line into destination file    dest.write(line)    # read another line    line = source.readline()  # close both filessource.close()dest.close()
Output:
Destination File
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to concatenate two arrays in java?

One way of doing it is, create an array of length equals to the sum of lengths of the two arrays and, add elements of both arrays to it one by one.
Live Demo
public class HelloWorld {
   public static void main(String[] args) {
      int[]a = {1,2,3,4};
      int[]b = {4,16,1,2,3,22};
      int[]c = new int[a.length+b.length];
      int count = 0;
      for(int i = 0; i<a.length; i++) {
         c[i] = a[i];
         count++;
      }
      for(int j = 0;j<b.length;j++) {
         c[count++] = b[j];
      }
      for(int i = 0;i<c.length;i++)
      System.out.print(c[i]+" ");
   }
}
1 2 3 4 4 16 1 2 3 22
How to add a TextView to a LinearLayout dynamically in Android?

This example demonstrates about How to add a TextView to a LinearLayout dynamically in 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:id="@+id/rlMain"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="16dp"
   android:orientation="vertical" />
Step 3 − Add the following code to src/MainActivity.java package
package app.com.sample;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      LinearLayout llMain = findViewById(R.id.rlMain);
      TextView textView = new TextView(this);
      textView.setText("I am added dynamically to the view");
      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
         LinearLayout.LayoutParams.MATCH_PARENT,
         LinearLayout.LayoutParams.MATCH_PARENT
      );
      textView.setLayoutParams(params);
      llMain.addView(textView);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
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 −
Click here to download the project code.
Java - sqrt() Method

The method returns the square root of the argument.
double sqrt(double d)

Here is the detail of parameters −
d − Any primitive data type.
d − Any primitive data type.
This method returns the square root of the argument.
public class Test { 

   public static void main(String args[]) {
      double x = 11.635;
      double y = 2.76;

      System.out.printf("The value of e is %.4f%n", Math.E);
      System.out.printf("sqrt(%.3f) is %.3f%n", x, Math.sqrt(x));
   }
}
This will produce the following result −
The value of e is 2.7183
sqrt(11.635) is 3.411


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page