code-rag-bench/online-tutorials huggingface dataset:
Converting a List to Vector in R Language – unlist() Function

26 May, 2020
unlist() function in R Language is used to convert a list to vector. It simplifies to produce a vector by preserving all components.
Syntax: unlist(list)
Parameters:list: It is a list or Vectoruse.name: Boolean value to prserve or not the position names
Example 1: Converting list numeric vector into a single vector
# R  program to illustrate# converting list to vector   # Creating a list.my_list <- list(l1 = c(1, 3, 5, 7),                                l2 = c(1, 2, 3),                                    l3 = c(1, 1, 10, 5, 8, 65, 90))      # Apply unlist R functionprint(unlist(my_list))                                    
Output:
l11 l12 l13 l14 l21 l22 l23 l31 l32 l33 l34 l35 l36 l37 
  1   3   5   7   1   2   3   1   1  10   5   8  65  90 

Here in the above code we have unlisted my_list using unlist() and convert it to a single vector.As illustrated above, the list will dissolve and every element will be in the same line as shown above.
Example 2: Unlisting list with dataframe:
# R program to illustrate# Unlisting list with data frame  # Creating a list.my_list <- list(l1 = c(1, 3, 5, 7),                                l2 = c(1, 2, 3),                                    l3 = c(1, 1, 10, 5, 8, 65, 90))        # Create modified listmy_list_2 <- my_list   # Add a data frame to the list                              my_list_2[[4]] <- data.frame(x1 = c(1, 2, 3),                                    x2 = c(4, 5, 6))  # Unlist list with data.frameprint(unlist(my_list_2, use.names = FALSE))                          
Output:
[1]  1  3  5  7  1  2  3  1  1 10  5  8 65 90  1  2  3  4  5  6

Here in the above code we have modified the previous list and added new elements to “my_list_2” and used the function unlist() on it.Also we set the “use.name” parameter to “FALSE” so we will not see the position names of the values in the vector.
R-Functions
Programming Language
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check if a directory or a file exists in system or not using Shell Scripting?

30 Jun, 2019
Shell scripting is really a powerful and dynamic way to automate your tasks. To test if a directory or file already exists in the system or not we can use shell scripting for the same along with test command. To proceed with the test script lets first check the test manual. To open a manual use the man command as follows:
man test
Right now we will be covering these two highlighted arguments in your script, further, you can use and test all of them. First, create a shell script file like test.sh using any editor of your choice like nano, vim or sublime and give it executable permissions(chmod +x).
In the below example we are checking if /usr/games directory is present or not.
#!/bin/bashif [ -d /usr/games ];then     echo "The Directory Exists"else    echo "The Directory is not present"fi
Let’s see another example where we have deleted a file from the directory and let’s check what happens.
#!/bin/bashif [ -e /usr/games/master.txt ];then     echo "The file Exists"else    echo "The file is not present"fi
Now we used -e argument to check for the file and we got the message that file is not present as we had deleted it. Like this, you can play with the shell script, refer to the test manual and test more awesome stuff with this.
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.axis.Axis.set_label_coords() function in Python

05 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.set_label_coords() function in axis module of matplotlib library is used to set the coordinates of the label. 
Syntax: Axis.set_label_coords(self, x, y, transform=None)
Parameters: This method accepts the following parameters. 
x,y: These parameter are the coordinates of the label.
Return value: This method does not returns any value. 
Below examples illustrate the matplotlib.axis.Axis.set_label_coords() function in matplotlib.axis:
Example 1:
Python3
# Implementation of matplotlib function from matplotlib.axis import Axisimport numpy as npimport matplotlib.pyplot as plt  fig, ax2 = plt.subplots(sharex = True)fig.subplots_adjust(left=0.2, wspace=0.6)box = dict(facecolor='green', pad=5, alpha=0.2)  ax2.plot(20*np.random.rand(10))ax2.set_xlabel('X - Label', bbox=box)ax2.set_xlim(0, 10)Axis.set_label_coords(ax2.xaxis, 0.5, 0.95)  fig.suptitle("Matplotlib.axis.Axis.set_label_coords()\Function Example", fontsize = 12, fontweight ='bold')   plt.show()
Output: 
Example 2:
Python3
# Implementation of matplotlib function from matplotlib.axis import Axisimport numpy as npimport matplotlib.pyplot as plt  fig, (ax1, ax2) = plt.subplots(2, 1, sharex = True)fig.subplots_adjust(left=0.2, wspace=0.6)box = dict(facecolor='green', pad=5, alpha=0.2)  np.random.seed(19680801)ax1.plot(2*np.random.rand(10))ax1.set_title('Label is not aligned')ax1.set_ylabel('Default', bbox=box)ax1.set_ylim(0, 20)  ax2.set_title('\nLabel is aligned')ax2.plot(20*np.random.rand(10))ax2.set_ylabel('Adjusted', bbox=box)ax2.set_ylim(0, 20)Axis.set_label_coords(ax2.yaxis,1.1, 0.5)  fig.suptitle("Matplotlib.axis.Axis.set_label_coords()\Function Example", fontsize = 12, fontweight ='bold')   plt.show()
Output: 
 
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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 | Get unique values from a list
Python | datetime.timedelta() function
Loop Optimization Techniques | Set 2

02 Jun, 2020
Prerequisite – Loop Optimization | Set 1
1. Loop Fission: improves locality of reference –In this, a loop is broken into multiple loops over the same index range, but each new loop contains only a specific part of the original loop’s body. This can improve locality of reference.
Before optimization:
for(i=0;i<100;i++)                          
{a[i]=...
b[i]=...
}
After optimization:
for(i=0;i<100;i++)
a[i]=...
for(i=0;i<100;i++)
b[i]=...
2. Loop Interchange: improves locality of reference –In these optimizations exchange inner loops with outer loops. When the loop variables index into an array, such a transformation can improve the locality of reference, depending on the array’s layout.
Before optimization:
for(i=0;i<100;i++)
for(j=0;j<100;j++)
a[j][i]=...
After optimization:
for(j=0;j<100;j++)
for(i=0;i<100;i++)
a[j][i]=...
3. Loop Reversal –Reverses the order in which values are assigned to the index variable. This can help eliminate dependencies and thus enable other optimizations.
Before optimization:
for(i=0;i<100;i++)
a[99-i]=...  
After optimization:
for(i=99;i>=0;i--)
a[i]=...
4. Loop Unrolling: minimizes tests and jumps but increases code size –The objective of loop unrolling is to increase a program’s speed by reducing instructions that control the loop, such as pointer arithmetic and “end of loop” test condition on each iteration. To eliminate or reduce this computational overhead, loops can be re-written as a repeated sequence of similar independent statements.
Before optimization:
for(i=0;i<100;i++)
a[i]=...  
After optimization:
for(i=0;i<100;i+=2)
{a[i]=...
a[i+1]=...
}
5. Loop Splitting –This attempts to simplify a loop or eliminate dependencies by breaking it into multiple loops that have the same bodies but iterate over different portions of the index range.
Before optimization:
for(i=0;i<100;i++)
if(i<50)
a[i]=...
else
b[i]=...
After optimization:
for(i=0;i<50;i++)
a[i]=...
for(;i<100;i++)
b[i]=...
6. Loop Peeling: special case of loop splitting –A special case of loop splitting is loop peeling, which can simplify a loop with a problematic first iteration by performing that iteration separately before entering the loop.
Before optimization:
for(i=0;i<100;i++)
if(i==0)
a[i]=...
else
b[i]=...
After optimization:
a[0]=...
for(i=1;i<100;i++)
b[i]=...
7. Unswitching –Moves a conditional from inside a loop to outside of it by duplicating the loop’s body, and placing   a version of it inside each of the if and else clauses of the conditional.
Before optimization:
for(i=0;i<100;i++)
if(x>y)
a[i]=...
else
b[i]=...
After optimization:
if(x>y)
for(i=0;i<100;i++)
a[i]=...
else
for(i=0;i<100;i++)
b[i]=...  
8. Loop Test Replacement: increases possibility of dead code elimination –
Before optimization:
i=0;
val=0;
while(i<100)
{val+=5;
i++;
}
After optimization:
i=0;
val=0;
while(val<500)
{val+=5;
i++;
}
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Element in Java ArrayList? - GeeksforGeeks

09 Jul, 2021
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array.
Element can be added in Java ArrayList using add() method of java.util.ArrayList class.
1. boolean add(Object element):
The element passed as a parameter gets inserted at the end of the list.
Declaration:
public boolean add(Object element)
Parameter: 
The element will get added to the end of the list.
Return Value: 
This method returns a boolean value true
Example:
Input:
list.add("A");
list.add("B");
list.add("C");
Output:
list=[A,B,C]

Input:
list.add(1);
list.add(2);
list.add(3);
list.add(4);
Output:
list=[1,2,3,4]
Implementation of the given method:
Java
// Java program to add elements in// Array List using add() method import java.io.*;import java.util.ArrayList; class GFG {    public static void main(String[] args)    {        ArrayList<Integer> list = new ArrayList<>();         // add method for integer ArrayList        list.add(1);        list.add(2);        list.add(3);        list.add(4);        System.out.println(list);    }}
[1, 2, 3, 4]
2. void add(int index, Object element)
The specified element gets inserted into the specified index.
Declaration:
public void add(int index, Object element)
Parameter: 
index – the position at which the element has to be inserted
element – the element to be inserted.
Exception: It throws IndexOutOfBoundsException if index<0||index>size()
Example:
Input:
list.add("A");
list.add("B");
list.add(1,"C");
Output:
list=["A","C","B"]


Input:
list.add(1);
list.add(2);
list.add(1,3);
list.add(2,4);
Output:
list=[1,3,4,2]
Implementation of the given method:
Java
// Java program to add elements// at the specified index in the list// using add(index,element) method import java.io.*;import java.util.ArrayList; class GFG {    public static void main(String[] args)    {        ArrayList<Integer> list = new ArrayList<>();         // add method for integer ArrayList        list.add(1);        list.add(2);         // index is zero based        // 3 gets added to the 1st        // position(zero-based)        list.add(1, 3);         // 4 gets added to the 2nd        // position(zero-based)        list.add(2, 4);         System.out.println(list);    }}
[1, 3, 4, 2]
rupaksai
sagartomar9927
Java-ArrayList
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Python program to print all Prime numbers in an Interval

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given an interval we need to compute all the prime numbers in a given range
Here we will be discussing a brute-force approach to get the solution i.e. the basic definition of
a prime number. Prime numbers are the number which has 1 and itself as a factor and rests all the numbers are not its factors.
Each time the condition of a prime number is evaluated to be true computation is performed.
Now let’s observe the concept in the implementation below−
 Live Demo
start = 1
end = 37
for val in range(start, end + 1):
   # If num is divisible by any number
   # between 2 and val, it is not prime
   if val > 1:
      for n in range(2, val):
         if (val % n) == 0:
            break
      else:
         print(val)
2
3
5
7
11
13
17
19
23
29
31
37
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can print all the prime numbers in an interval
Can a class in Java be both final and abstract?

An abstract cannot be instantiated. Therefore to use an abstract class you need to create another class and extend the abstract class and use it.
If a class is final you can’t extend it further.
So, you cannot declare a class both final and abstract.
Still if you try to do so you will get a compile time error saying “illegal combination of modifiers:”
final abstract class Demo{
   public final void display(){
      System.out.println("Hello welcome to tutorialspoint");
   }
}
C:\Sample>javac Demo.java
Demo.java:1: error: illegal combination of modifiers: abstract and final
final abstract class Demo{
               ^
1 error
How to add a new element in the XML using PowerShell?

Suppose we have a XML file as shown below.
<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications with XML.</description>
   </book>
</catalog>
We need to add a new node. So we will first load the XML file and then operate on it as shown below.
The below command will save the XML file to the variable.
$xmlfile = [XML](Get-Content C:\Temp\SampleXML.xml)
The below command will create a new XML element
$newelement = $xmlfile.CreateElement("book")
Once the element is created we need to append it to the specific node. Here we need to append a new element underneath the Catalog.
$xmlfile.catalog.AppendChild($newelement)
And the last part is to save the XML file using the below command.
$xmlfile.save('C:\Temp\SampleXML.xml')
You can check the new book element is created.
How to set the shadow effect of a text with JavaScript?

To set the shadow effect, use the textShadow property in JavaScript.
You can try to run the following code to return the shadow effect of a text with JavaScript −
<!DOCTYPE html>
<html>
   <body>
      <button onclick = "display()">Set Text Shadow</button>

      <div id = "myID">
         This is Demo Text! This is Demo Text! This is <br>This is Demo Text! This is Demo Text! This is Demo Text! This is Demo Text!<br> This is Demo Text!<br> This is Demo Text! This is Demo Text! This is Demo Text! This is Demo Text!
      </div>

      <script>
         function display() {
            document.getElementById("myID").style.textShadow = "2px 2px 2px #ff0000,20px 5px 2px #F1F1F1";
         }
      </script>
   </body>
</html>
MySQL update multiple rows in one query

Theory of Computation
In this exercise, we will learn to update multiple rows with different values in one query. Suppose we have the following employee records and we want to update the phone number of some employees -
CREATE TABLE IF NOT EXISTS `empdata` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(25) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `empdata` (`id`, `name`, `email`, `phone`) VALUES
(1, 'Anjali', 'anjali@example.com', 878433948),
(2, 'Priska', 'priska@example.com', 493905490),
(3, 'Abhi', 'abhi@example.com', 403022139),
(4, 'Joya', 'joya@example.com', 342345329),
(5, 'Ammy', 'ammy@example.com', 239848342),
(6, 'Lussi', 'lussi@example.com', 490290331);
The best way to update multiple rows in just one statement is use CASE WHEN ELSE statement. In this, the statement will update the matched case and end otherwise, like-
UPDATE 'table_name' 
SET 'field_name' = CASE 'id'
WHEN '1' THEN 'value 1'
WHEN '2' THEN 'value 2'
WHEN '3' THEN 'value 3'
ELSE 'field_name'
END
Here, 'table_name' is the MySQL table name, 'field_name' is the column name.
The update query to update the phone number of some employees are as follows -
UPDATE empdata SET phone = CASE 
WHEN id=1 THEN '840932345'
WHEN id=2 THEN '890040908'
WHEN id=3 THEN '675748389'
WHEN id=6 THEN '909030309'
ELSE phone
END;
let's check the updated data -
SELECT * FROM 'empdata';
+----+--------+--------------------+-----------+
| id | name   | email              | phone     |
+----+--------+--------------------+-----------+
|  6 | Lussi  | lussi@example.com  | 909030309 |
|  4 | Joya   | joya@example.com   | 342345329 |
|  5 | Ammy   | ammy@example.com   | 239848342 |
|  2 | Priska | priska@example.com | 890040908 |
|  3 | Abhi   | abhi@example.com   | 675748389 |
|  1 | Anjali | anjali@example.com | 840932345 |
C Program to check if an array is palindrome or not using Recursion

Given an array arr[n] where n is some size of an array, the task is to find out that the array is palindrome or not using recursion. Palindrome is a sequence which can be read backwards and forward as same, like: MADAM, NAMAN, etc.
So to check an array is palindrome or not so we can traverse an array from back and forward like −
In recursion also we have to change the start and end value till they are equal or when the values as start and end are not equal then exit and return false that the given array is not palindrome.
Input: arr[] = { 2, 3, 4, 3, 2}
Output: Yes, the array is Palindrome
Explanation: the array is identical from start (2, 3, 4, 3, 2) and end (2, 3, 4, 3, 2).
Input: arr[] = {1, 2, 3, 4}
Output: No, the array is not Palindrome
Explanation: The array is not identical from start (1, 2, 3, 4) and end (4, 3, 2, 1).
Approach used below is as follows −
We will recursively do the following steps −
Check arr[start] is equal to arr[end] and start < end
Increment start with 1 and decrement end with 1.
Goto step 1.
Start
In function int palindrome(int arr[], int start, int end)
   Step 1-> If start >= end then,
      Return 1
   Step 2-> If arr[start] == arr[end] then,
      Return palindrome(arr, start + 1, end - 1)
   Step 3-> Else {
      Return 0
In fucntion int main()
      Step 1-> Declare and initialize an array arr[]
      Step 2-> Declare and initialize n = sizeof(arr) / sizeof(arr[0]
      Step 3-> If palindrome(arr, 0, n - 1) == 1 then,
         Print "Yes, the array is Palindrome”
      Step 4-> Else
         Print "No, the array is not Palindrome”
Stop
#include <stdio.h>
// Recursive pallindrome function that returns 1 if
// palindrome, 0 if it is not
int palindrome(int arr[], int start, int end) {
   // base case
   if (start >= end) {
      return 1;
   }
   if (arr[start] == arr[end]) {
      return palindrome(arr, start + 1, end - 1);
   } else {
      return 0;
   }
   // Driver code
   int main() {
   int arr[] = { 1, 2, 0, 2, 1 };
   int n = sizeof(arr) / sizeof(arr[0]);
   if (palindrome(arr, 0, n - 1) == 1)
      printf("Yes, the array is Palindrome\n");
   else
      printf("No, the array is not Palindrome\n");
   return 0;
}
If run the above code it will generate the following output −
Yes, the array is Palindrome
What is the purpose of using Optional.ifPresentOrElse() method in Java 9?

The improvement of ifPresentOrElse() method in Optional class is that accepts two parameters, Consumer and Runnable. The purpose of of using ifPresentOrElse() method is that if an Optional contains a value, the function action is called on the contained value, i.e. action.accept (value), which is consistent with ifPresent() method. The difference from the ifPresent() method is that ifPresentOrElse() has a second parameter, emptyAction. If Optional contains no value, then ifPresentOrElse() method calls emptyAction, i.e. emptyAction.run().
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
import java.util.Optional;

public class IfPresentOrElseMethodTest {
   public static void main(String args[]) {
      Optional<Integer> optional = Optional.of(1);

      optional.ifPresentOrElse(x -> System.out.println("Value: " + x), () ->
                                    System.out.println("Not Present"));

      optional = Optional.empty();

      optional.ifPresentOrElse(x -> System.out.println("Value: " + x), () ->
                                    System.out.println("Not Present"));
   }
}
Value: 1
Not Present
Restart instructions (RSTn) in 8085 Microprocessor

In 8085 Instruction set, RSTn is actually standing for “Restart n”. And in this case, n has a value from 0 to 7 only. Thus the eight possible RST instructions are there, e.g. RST 0, RST 1, ..., RST 7. They are 1-Byte call instructions. Functionally RST n instruction is similar with:
RST n = CALL n*8
For example, let us consider RST 4 is functionally equivalent to CALL 4*8, i.e. CALL 32 = CALL 0020H. The advantage of RST 2 is that it is only 1 Byte, whereas CALL 0010H is 3-Byte long. Thus RST instructions are useful for branching to frequently used subroutines.
In the above table, it has been shown that if we analyze the RSTn Hex Codes than we are finding that middle most 3-bits are denoting the value for n (As highlighted in the table). And the other5 bits in the Byte provide the code for RST.
Let us consider, RST 4 is an example instruction of this type. It is a 1-Byte instruction. It is functionally same as CALL 0020H = PUSH PC + JMP  0010H. It causes a branch to subroutine starting from memory address 0020H. Similarly, RST 5 causes a branch to a subroutine at 5*8 = 0028H. Thus, the subroutine, which starts at location 0020H should not go beyond memory location 0027H. So at the most only eight locations are available for the subroutine, which is too small in general to keep the sub-routine bodies. This limitation is overcome by branching to a subroutine at some other memory location, like 4050H. It is achieved by the combination of RST 4 instruction, and JMP 4050H instruction at memory location 0020H, as shown in the following Fig. 
The way in which the stack contents get affected due to the execution of RST 4 is shown below.
The way in which the stack contents get affected due to an execution of RST 4 is shown below.
In the Fig. the main program is starting from address 2000H with instruction LXI SP, 5000H to initialize SP with that memory address. The main program is having the terminating instruction HLT at address 2050H. In the main program at address 2020H the instruction is RST 4. So the computed target address will be 4*8 = 32 = 0020H. So the return address 2021H will be pushed at the top of the stack. So 20H will be pushed at stack location 4FFFH and 21H at address 4FFEH. So the updated SP address will be 4FFEH. And the control will be transferred to the address 0020H. At that address, we are having instruction JMP 4050H. So the program control will branch to that address 4050H. This subroutine is having the last instruction at address 4080H with the instruction RET. So return 2-Byte address will be popped out from the top of the stack. So the16-bit return address will be 2021H and SP will get initialized with 5000H again. So the main program will resume its execution and will terminate at 4080H address with instruction HLT as usual.
The timing diagram against this instruction RST 4 execution is as follows –
Summary − So this instruction RST 4 requires 1-Byte, 3-Machine Cycles (Opcode Fetch, Memory Write, Memory Write) and 12 T-States for execution as shown in the timing diagram.
How do I create dynamic variable names inside a JavaScript loop?

To achieve this, you need to add properties to the current scope. Achieve this using this, which is for the current scope in the program −
for (var i = 0; i < coords.length; ++i) {
   this["marker"+i] = "add here";
}
The above will get what you want and retrieve it like the following −
var a = this.marker0;
alert(a);
It will give you the text “add here” as shown above.
Java program to calculate Body Mass Index (BMI)

The Body Mass Index is the body mass in kilogram divided by the square of body height in meters. This is expressed as kg/m^2.
A program that calculates the Body Mass Index (BMI) is given as follows.
import java.util.Scanner;
public class Example {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.print("Input weight in kilogram: ");
      double weight = sc.nextDouble();
      System.out.print("\nInput height in meters: ");
      double height = sc.nextDouble();
      double BMI = weight / (height * height);
      System.out.print("\nThe Body Mass Index (BMI) is " + BMI + " kg/m2");
   }
}
Input weight in kilogram: 55
Input height in meters: 1.5
The Body Mass Index (BMI) is 24.444444444444443 kg/m2
Now let us understand the above program.
The values of the weight and height are obtained from the user in kilogram and meters respectively. The code snippet that demonstrates this is given as follows −
Scanner sc = new Scanner(System.in);
System.out.print("Input weight in kilogram: ");
double weight = sc.nextDouble();
System.out.print("\nInput height in meters: ");
double height = sc.nextDouble();
Then the Body Mass Index is calculated using the formula BMI = weight / (height * height). Finally the values of the Body Mass Index is displayed. The code snippet that demonstrates this is given as follows −
double BMI = weight / (height * height);
System.out.print("\nThe Body Mass Index (BMI) is " + BMI + " kg/m2");
Find all elements count in list in Python

Many times we need to count the elements present in a list for some data processing. But there may be cases of nested lists and counting may not be straight forward. In this article we will see how to handle these complexities of counting number of elements in a list.
In this approach we use two for loops to go through the nesting structure of list. In the below program we have nested list where inner elements have different number of elements inside them. We also apply the len() function to calculate the length of the flattened list.
 Live Demo
listA = [[2,9, 6], [5, 'a'], [0], [12,'c', 9, 3]]

# Given list
print("Given list : ",listA)

res = len([x for y in listA for x in y])

# print result
print("Total count of elements : " ,res)
Running the above code gives us the following result −
Given list : [[2, 9, 6], [5, 'a'], [0], [12, 'c', 9, 3]]
Total count of elements : 10
In this approach we apply the chain method which brings out all the inner elements from the list by flattening them and then convert it to a list. Finally apply the len() function so that the count of the elements in the list found.
from itertools import chain
listA = [[2,9, 6], [5, 'a'], [0], [12,'c', 9, 3]]

# Given list
print("Given list : ",listA)

res = len(list(chain(*listA)))

# print result
print("Total count of elements : " ,res)
Running the above code gives us the following result −
Given list : [[2, 9, 6], [5, 'a'], [0], [12, 'c', 9, 3]]
Total count of elements : 10
ENDOFQUARTER function

Returns the last date of the quarter in the current context for the specified column of dates.
ENDOFQUARTER (<dates>) 

dates
A column that contains dates.
A table containing a single column and single row with a date value.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
= ENDOFQUARTER (Sales [Date]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
ftell() in C

In C language, ftell() returns the current file position of the specified stream with respect to the starting of the file. This function is used to get the total size of file after moving the file pointer at the end of the file. It returns the current position in long type and file can have more than 32767 bytes of data.
Here is the syntax of ftell() in C language,
long int ftell(FILE *stream)
Here is the parameter used in ftell(),
stream − This is the pointer to a FILE object that identifies the stream.
stream − This is the pointer to a FILE object that identifies the stream.
Here is an example of ftell() in C language.
Let’s say we have a file “one.txt” with the following content.
This is demo text!
This is demo text!
This is demo text!
Now, let us see the example.
#include <stdio.h>
#include<conio.h>
void main () {
   FILE *f;
   int len;
   f = fopen("one.txt", "r");
   if(f == NULL) {
      perror(“Error opening file”);
      return(-1);
   }
   fseek(f, 0, SEEK_END);
   len = ftell(f);
   fclose(f);
   printf("Size of file: %d bytes", len);
   getch();
}
Size of file: 78 bytes
jQuery Examples - keyup(  )

The keyup() method triggers the keyup event of each matched element.
Here is the simple syntax to use this method −
selector.keyup()

None
Following is a simple example showing the usage of this method. Here it triggers the keyup event of each matched element −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
   </head>	

   <body>			
      <form name = "sampleForm">
         <label>Enter Name: </label><input type = "text" id = "result1" title="Enter Name" value = "" ></input><br/><br/>         
         <input type = "button" value = "Trigger KeyUp" onclick="triggerKeyUp();"/>
      </form>		
      <script type = "text/javascript" language = "javascript">
         function triggerKeyUp(){		   
            $("#result1").keyup();
         }

         $("#result1").keyup(function( event ) {
            alert("Handler for keyup() called!");
         });
      </script>
   </body>	
</html>
This will produce following result −
 Print
 Add Notes
 Bookmark this page
How to create a Tkinter toggle button?

Python has a rich set of libraries and modules that can be used to build various components of an application. Tkinter is another well-known Python library for creating and developing GUI-based applications. Tkinter offers many widgets, functions, and modules that are used to bring life to the application visuals. We can create button widgets to perform certain tasks in an application.
In this application, we will create a toggle button that will turn the On/ Off Night and Day mode of the application. To create a toggle button, we have to first render the image in a Label.
We define buttons and functions to change the background color of the window. Since the buttons need to be changed repeatedly, we have to declare a global variable is_on=True which helps to control the function.
# Import tkinter in the notebook
from tkinter import *

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

# set Title
win.title('Toggle Button Demonstration')

# Set the Geometry
win.geometry("700x400")
win.resizable(0, 0)

# Create a variable to turn on the button initially
is_on = True

# Create Label to display the message
label = Label(win, text="Night Mode is On", bg="white", fg="black", font=("Poppins bold", 22))
label.pack(pady=20)

# Define our switch function
def button_mode():
   global is_on

   # Determine it is on or off
   if is_on:
      on_.config(image=off)
      label.config(text="Day Mode is On", bg="white", fg="black")
      is_on = False
   else:
      on_.config(image=on)
      label.config(text="Night Mode is On", fg="black")
      is_on = True

# Define Our Images
on = PhotoImage(file="on.png")
off = PhotoImage(file="off.png")

# Create A Button
on_ = Button(win, image=on, bd=0, command=button_mode)
on_.pack(pady=50)

# Keep Running the window
win.mainloop()
If we execute the above code, it will display a window that contains a toggle button.
If we click the button, it will change the color of the window.
Bootstrap - Breadcrumb

Breadcrumbs are a great way to show hierarchy-based information for a site. In the case of blogs, breadcrumbs can show the dates of publishing, categories, or tags. They indicate the current page's location within a navigational hierarchy.
A breadcrumb in Bootstrap is simply an unordered list with a class of .breadcrumb. The separator is automatically added by CSS (bootstrap.min.css) through the following class −
.breadcrumb > li + li:before {
   color: #CCCCCC;
   content: "/ ";
   padding: 0 5px;
}
The following example demonstrates breadcrumbs −
<ol class = "breadcrumb">
   <li><a href = "#">Home</a></li>
   <li><a href = "#">2013</a></li>
   <li class = "active">November</li>
</ol>

Home
2013
November

Home
2013
November

    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
klist - Unix, Linux Command

klist allows the user to view entries in the local credentials cache and
key table.



klist -k -t -K FILE:/temp/mykrb5cc


List entries in the credentials cache
specified including credentials flag
and address list:



klist -c -f FILE:/temp/mykrb5cc













Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to put the title at the bottom of a figure in Matplotlib?

To put the line title at the bottom of a figure in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Initialize a variable, N, to get the number of sample data.
Initialize a variable, N, to get the number of sample data.
Plot the x and y data points using scatter() method.
Plot the x and y data points using scatter() method.
Set the title at the bottom of the figure in matplotlib, with y=-0.01.
Set the title at the bottom of the figure in matplotlib, with y=-0.01.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

N = 100
x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y, c=x, s=x*100+1, cmap="plasma")

plt.title('Scatter plot', y=-0.01)

plt.show()
What are the differences between a JTextPane and a JEditorPane in Java?

A JTextPane is an extension of JEditorPane which provides word processing features like fonts, text styles, colors and etc. If we need to do heavy-duty text processing we can use this class whereas a JEditorPane supports display/editing of HTML and RTF content and can be extended by creating our own EditorKit.
A JTextPane is a subclass of JEditorPane.
A JTextPane is used for a styled document with embedded images and components.
A JTextPane is a text component that can be marked up with the attributes that are represented graphically and it can use a DefaultStyledDocument as the default model.
The important methods of JTextPane are addStyle(), getCharacterAttributes(), getStyledDocument(), setDocument(), setEditorKit(), setStyledDocument() and etc.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JTextPaneTest {
   public static void main(String args[]) throws BadLocationException {
      JFrame frame = new JFrame("JTextPane Test");
      Container cp = frame.getContentPane();
      JTextPane pane = new JTextPane();
      SimpleAttributeSet set = new SimpleAttributeSet();
      StyleConstants.setBold(set, true);
      pane.setCharacterAttributes(set, true);
      pane.setText("Welcome to");
      set = new SimpleAttributeSet();
      StyleConstants.setItalic(set, true);
      StyleConstants.setForeground(set, Color.blue);
      Document doc = pane.getStyledDocument();
      doc.insertString(doc.getLength(), " Tutorials ", set);
      set = new SimpleAttributeSet();
      StyleConstants.setFontSize(set, 20);
      doc.insertString(doc.getLength(), " Point", set);
      JScrollPane scrollPane = new JScrollPane(pane);
      cp.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(375, 250);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}
A JEditorPane is a kind of text area which can display various text formats
By default, JEditorPane supports HTML and RTF (Rich Text Format), we can build our own editor kits to handle a specific content type.
We can use setContentType() method to choose the document we want to display and setEditorKit() method to set custom editor for JEditorPane explicitly.
import javax.swing.*;
public class JEditorPaneTest extends JFrame {
   public JEditorPaneTest() {
      setTitle("JEditorPane Test");
      JEditorPane editorPane = new JEditorPane();
      editorPane.setContentType("text/html");
      editorPane.setText("<h1>Java</h1><p>is a general-purpose computer programming language that is       concurrent, class-based, object-oriented, and specifically designed to have as few          implementation dependencies as possible.</p>");
      setSize(350, 275);
      setContentPane(editorPane);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] a) {
      new JEditorPaneTest();
   }
}
Golang program that uses fallthrough keyword - GeeksforGeeks

04 May, 2020
With the help of fallthrough statement, we can use to transfer the program control just after the statement is executed in the switch cases even if the expression does not match. Normally, control will come out of the statement of switch just after the execution of first line after match. Don’t put the fallthrough in the last statement of switch case.
Example 1: In this example we can see that by using switch cases with fallthrough and assuming variable as a string type we can make use of switch cases.
// Golang program to show the// uses of fallthrough keywordpackage main  // Here "fmt" is formatted IO which// is same as C’s printf and scanf.import "fmt"  // Main functionfunc main() {    day := "Tue"      // Use switch on the day variable.    switch {    case day == "Mon":        fmt.Println("Monday")        fallthrough    case day == "Tue":        fmt.Println("Tuesday")        fallthrough    case day == "Wed":        fmt.Println("Wednesday")    }}
Output :
Tuesday
Wednesday

Example 2:
// Golang program to show the// uses of fallthrough keywordpackage main  // Here "fmt" is formatted IO which// is same as C’s printf and scanf.import "fmt"  // Main functionfunc main() {    gfg := "Geek"      // Use switch on the day variable.    switch {    case gfg == "Geek":        fmt.Println("Geek")        fallthrough    case gfg == "For":        fmt.Println("For")        fallthrough    case gfg == "Geeks":        fmt.Println("Geeks")    }}
Output :
Geek
For
Geeks

Go-Keywords
Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Formatting in Golang
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
How to convert a string in lower case in Golang?
How to compare times in Golang?
How to Trim a String in Golang?
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to display the first element in a JComboBox in Java

To display the first element in a JComboBox, use the getSelectedIndex():
comboBox.setSelectedIndex(0);
The following is an example to display the first element in a JComboBox in Java:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel(new BorderLayout());
      String[] strArr = new String[] { "Laptop", "Mobile", "Desktop", "Tablet" };
      JComboBox<String> comboBox = new JComboBox<>(strArr);
      panel.add(comboBox, BorderLayout.NORTH);
      JTextArea text = new JTextArea(5, 5);
      panel.add(text, BorderLayout.CENTER);
      JButton btn = new JButton("Click");
      btn.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            text.setText((String) comboBox.getSelectedItem());
            comboBox.setSelectedIndex(0);
         }
      });
      panel.add(btn, BorderLayout.SOUTH);
      JFrame frame = new JFrame();
      frame.add(panel);
      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}
The output is as follows displaying the first item:
How to change the size of plots arranged using grid.arrange in R?

To change the size of plots arranged using grid.arrange, we can use heights argument. The heights argument will have a vector equal to the number of plots that we want to arrange inside grid.arrange. The size of the plots will vary depending on the values in this vector.
Consider the below data frame −
 Live Demo
x<-rnorm(20)
y<-rpois(20,2)
df<-data.frame(x,y)
df
          x      y
1 2.44725895     4
2 -1.30716203    2
3 -0.98084721    6
4 0.31704022     3
5 1.09460383     2
6 0.76611276     1
7 0.93073818     1
8 -0.84915028    2
9 1.27882442     0
10 0.77428764    1
11 0.48511829    0
12 -1.20333353   0
13 -0.66665709   0
14 -0.12132914   4
15 0.46865269    1
16 0.71771117    1
17 0.76447810    2
18 0.01445573    1
19 -0.75449056   3
20 1.18946339    3
Loading ggplot2 package and creating two plots −
library(ggplot2)
p1<-ggplot(df,aes(x))+geom_histogram(bins=2)
p2<-ggplot(df,aes(x,y))+geom_point()
Loading gridExtra package and arranging above plots using grid.arrange −
library(gridExtra)
grid.arrange(p1,p2)
Arranging plots using grid.arrange with varying heights −
grid.arrange(p1,p2,heights=c(2,1))
Solidity - Error Handling

Solidity provides various functions for error handling. Generally when an error occurs, the state is reverted back to its original state. Other checks are to prevent unauthorized code access. Following are some of the important methods used in error handling −
assert(bool condition) − In case condition is not met, this method call causes an invalid opcode and any changes done to state got reverted. This method is to be used for internal errors.
assert(bool condition) − In case condition is not met, this method call causes an invalid opcode and any changes done to state got reverted. This method is to be used for internal errors.
require(bool condition) − In case condition is not met, this method call reverts to original state. - This method is to be used for errors in inputs or external components.
require(bool condition) − In case condition is not met, this method call reverts to original state. - This method is to be used for errors in inputs or external components.
require(bool condition, string memory message) − In case condition is not met, this method call reverts to original state. - This method is to be used for errors in inputs or external components. It provides an option to provide a custom message.
require(bool condition, string memory message) − In case condition is not met, this method call reverts to original state. - This method is to be used for errors in inputs or external components. It provides an option to provide a custom message.
revert() − This method aborts the execution and revert any changes done to the state.
revert() − This method aborts the execution and revert any changes done to the state.
revert(string memory reason) − This method aborts the execution and revert any changes done to the state. It provides an option to provide a custom message.
revert(string memory reason) − This method aborts the execution and revert any changes done to the state. It provides an option to provide a custom message.
Try the following code to understand how error handling works in Solidity.
pragma solidity ^0.5.0;

contract Vendor {
   address public seller;
   modifier onlySeller() {
      require(
         msg.sender == seller,
         "Only seller can call this."
      );
      _;
   }
   function sell(uint amount) public payable onlySeller { 
      if (amount > msg.value / 2 ether)
         revert("Not enough Ether provided.");
      // Perform the sell operation.
   }
}

When revert is called, it will return the hexadecimal data as followed.
0x08c379a0                     // Function selector for Error(string)
0x0000000000000000000000000000000000000000000000000000000000000020 // Data offset
0x000000000000000000000000000000000000000000000000000000000000001a // String length
0x4e6f7420656e6f7567682045746865722070726f76696465642e000000000000 // String data


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page