code-rag-bench/online-tutorials huggingface dataset:
Logical AND and OR in Arduino

The logical AND is denoted by the && operator, while the logical OR is denoted by the || operator.
Expression1 && Expression2
OR
Expression1 || Expression2
Where expression1 and expression2 evaluate to Boolean values (true or false). The output of these statements is determined by the truth tables of logical AND and OR.
The truth table for AND is given below −
As you can see, both the expressions have to be true for the AND statement to output true.
The truth table for OR is given below −
As you can see, even if one of the expressions is true, the OR statement will output true.
The following example demonstrates the use of these operators −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   int x1 = 1;
   int x2 = 2;
   int x3 = 3;
   int x4 = 4;

   if((x1 > 2) && (x2 < 2)){
      Serial.println("x1 is greater than 2 and x2 is less than 2");
   }

   if((x1 == 2) || (x2 == 2)){
      Serial.println("Either or both of x1 and x2 are equal to 2");
   }

   if((x3 > 2) && (x4 > 2)){
      Serial.println("x3 and x4 are both greater than 2");
   }

   if((x3 < 2) || (x4 < 2)){
      Serial.println("Either or both of x3 and x4 are less than 2");
   }
}

void loop() {
   // put your main code here, to run repeatedly:
}
The Serial Monitor output is −
In the first case, both expressions were false, so the AND output was false, and nothing was printed.
In the first case, both expressions were false, so the AND output was false, and nothing was printed.
In the second case, one expression was true, so the OR expression was true, and the statement was printed.
In the second case, one expression was true, so the OR expression was true, and the statement was printed.
In the third case, both the expressions were true, so the AND output was true and the statement was printed.
In the third case, both the expressions were true, so the AND output was true and the statement was printed.
In the fourth case, both the expressions were false, so the OR output was false, and nothing was printed.
In the fourth case, both the expressions were false, so the OR output was false, and nothing was printed.
Find all prime factors of a number - JavaScript

We are required to write a JavaScript function that takes in a number and returns an array of all the prime numbers that exactly divide the input number.
For example, if the input number is 18.
Then the output should be −
const output = [2, 3];
Let’s write the code for this function −
const num = 18;
const isPrime = (n) => {
   for(let i = 2; i <= n/2; i++){
      if(n % i === 0){
         return false;
      }
   };
   return true;
};
const findPrimeFactors = num => {
   const res = num % 2 === 0 ? [2] : [];
   let start = 3;
   while(start <= num){
      if(num % start === 0){
         if(isPrime(start)){
            res.push(start);
         };
      };
      start++;
   };
   return res;
};
console.log(findPrimeFactors(18));
The output in the console: −
[2, 3]
How to setup a Web server like Tomcat to test JSP pages?

Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies and can act as a standalone server for testing JSP and Servlets, and can be integrated with the Apache Web Server. Here are the steps to set up Tomcat on your machine −
Download the latest version of Tomcat from https://tomcat.apache.org/.
Download the latest version of Tomcat from https://tomcat.apache.org/.
Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations.
Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations.
Tomcat can be started by executing the following commands on the Windows machine −
%CATALINA_HOME%\bin\startup.bat

or

C:\apache-tomcat-5.5.29\bin\startup.bat
Tomcat can be started by executing the following commands on the Unix (Solaris, Linux, etc.) machine −
$CATALINA_HOME/bin/startup.sh

or

/usr/local/apache-tomcat-5.5.29/bin/startup.sh
After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/.
Upon execution, you will receive the following output −
Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − https://tomcat.apache.org/.
Tomcat can be stopped by executing the following commands on the Windows machine −
%CATALINA_HOME%\bin\shutdown
or

C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$CATALINA_HOME/bin/shutdown.sh

or

/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
How to create a list of object in Python class - GeeksforGeeks

29 Dec, 2020
We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C. Let’s try to understand it better with the help of examples.
Example #1:
# Python3 code here creating classclass geeks:     def __init__(self, name, roll):         self.name = name         self.roll = roll   # creating list       list = []   # appending instances to list list.append( geeks('Akash', 2) )list.append( geeks('Deependra', 40) )list.append( geeks('Reaper', 44) )  for obj in list:    print( obj.name, obj.roll, sep =' ' )  # We can also access instances attributes# as list[0].name, list[0].roll and so on.
Akash 2
Deependra 40
Reaper 44

 
Example #2:
# Python3 code here for creating classclass geeks:     def __init__(self, x, y):         self.x = x         self.y = y              def Sum(self):        print( self.x + self.y )   # creating list       list = []   # appending instances to list list.append( geeks(2, 3) )list.append( geeks(12, 13) )list.append( geeks(22, 33) )  for obj in list:    # calling method     obj.Sum()  # We can also access instances method# as list[0].Sum() , list[1].Sum() and so on.
5
25
55

bagamramyasri
Python Oops-programs
Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Check if element exists in list in Python
Convert integer to string in Python
Dictionary Methods in C#

Dictionary is a collection of keys and values in C#. Dictionary<TKey, TValue> is included in the System.Collection.Generics namespace.
The following are the methods −
Let us see how to add elements into a Dictionary and display the count.
 Live Demo
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      IDictionary<int, int> d = new Dictionary<int, int>();
      d.Add(1,97);
      d.Add(2,89);
      d.Add(3,77);
      d.Add(4,88);
      d.Add(5,78);
      d.Add(6,98);
      Console.WriteLine(d.Count);
   }
}
6
Count Binary Substrings in C++

Suppose we have a string s, we have to find the count of contiguous substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. If substrings occur multiple times are counted the number of times they occur.
So, if the input is like "11001100", then the output will be 6, as the substrings are "1100", "10","0011", "01", "1100", "10".
To solve this, we will follow these steps −
Define an array cnt of size 2 and fill this with 0
res := 0
for initialize i := 0, when i < length of s, update (increase i by 1), do −num := s[i] - ASCII of '0'if i is same as 0 or s[i] is not equal to s[i - 1], then −cnt[num] := 0(increase cnt[num] by 1)if cnt[num] <= cnt[1 - num], then −(increase res by 1)
num := s[i] - ASCII of '0'
if i is same as 0 or s[i] is not equal to s[i - 1], then −cnt[num] := 0
cnt[num] := 0
(increase cnt[num] by 1)
if cnt[num] <= cnt[1 - num], then −(increase res by 1)
(increase res by 1)
return res
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int countBinarySubstrings(string s) {
      int cnt[2] = { 0 };
      int res = 0;
      for (int i = 0; i < s.length(); ++i) {
         int num = s[i] - '0';
         if (i == 0 || s[i] != s[i - 1])
            cnt[num] = 0;
         ++cnt[num];
         if (cnt[num] <= cnt[1 - num])
            ++res;
      }
      return res;
   }
};
main(){
   Solution ob;
   cout << (ob.countBinarySubstrings("11001100"));
}
"11001100"
6
Bash program to check if the Number is a Prime or not

Bash also known as GNU bash is a command language and unix shell script is a command line interpreter for operating system. It was designed by Brian Fox and was a free software which replaced Bourne shell. It first released in 1989 and some became go to for login shell for linux based operating systems like macOS, Linux based softwares, etc.
Prime number is a number that has only two factors i.e. the number itself and 1. For example, 2 , 3 , 5, 7 , 11 , 13 , 17 , 19 , 23 , 29....
Here we are given a number, and we need to find whether the given number is prime or not.
Input : A number
Output : “The number is prime ” OR “The number is not prime” based on the number.
Example −
Input : 23
Output : The number is prime
Step 1 − Loop from 2 to n/2, i as loop variable
Step 1 − Loop from 2 to n/2, i as loop variable
Step 2 − if number is divisible, print “The number is not prime” and flag = 1;
Step 2 − if number is divisible, print “The number is not prime” and flag = 1;
Step 3 − if flag != 1, then print “The number is prime”.
Step 3 − if flag != 1, then print “The number is prime”.
Step 4 − Exit.
Step 4 − Exit.
number=53
i=2
flag=0
while test $i -le `expr $number / 2`
do
if test `expr $number % $i` -eq 0
then
flag=1
fi

i=`expr $i + 1`
done if test $flag -eq 1
then
echo "The number is Not Prime"
else
echo "The number is Prime"
Fi
The number is Prime
Python | Get sum of tuples having same first value - GeeksforGeeks

14 Feb, 2019
Given a list of tuple, the task is to sum the tuples having same first value.
Examples:
Input: [(1, 13), (2, 190), (3, 82), (1, 12)]
Output: [(1, 25), (2, 190), (3, 82)]

Input: [(1, 13), (1, 190), (3, 25), (1, 12)]
Output: [(1, 215), (3, 25)]

 Let’s discuss the different ways we can do this task.
Method #1: Using map()
# Python code to get sum of tuples having same first value  # Initialisation of list of tupleInput = [(1, 13), (1, 190), (3, 25), (1, 12)]  d = {x:0 for x, _ in Input}  for name, num in Input: d[name] += num  # using mapOutput = list(map(tuple, d.items()))  # printing outputprint(Output)
[(1, 215), (3, 25)]

 Method #2: Using defaultdict
# Python code to sum list of tuples having same first value  # Importingfrom collections import defaultdict  # Initialisation of list of tupleInput = [(2, 190), (1, 13), (1, 12),          (2, 14), (3, 82), (1, 70)]  # Initialisation of defaultdictoutput = defaultdict(int)  for k, v in Input:    output[k] += v  # Printing outputprint(list(output.items()))
[(1, 95), (2, 204), (3, 82)]

Python tuple-programs
python-tuple
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 ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib
Python | Pandas Index.shape - GeeksforGeeks

20 Feb, 2019
Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects.
Pandas Index.shape attribute return a tuple of the shape of the underlying data in the given Index object.
Syntax: Index.shape
Parameter : None
Returns : tuple
Example #1: Use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index(['Melbourne', 'Sanghai', 'Lisbon', 'Doha', 'Moscow', 'Rio'])  # Print the indexprint(idx)
Output :
Now we will use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object.
# return a tuple of the shape# of data in idx objectresult = idx.shape  # Print the resultprint(result)
Output :
As we can see in the output, the Index.shape attribute has returned a tuple based on the size of the underlying data in the given Index object. Example #2 : Use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index([900 + 3j, 700 + 25j, 620 + 10j, 388 + 44j, 900])  # Print the indexprint(idx)
Output :
Now we will use Index.shape attribute to return a tuple of the shape of the underlying data in the given Index object.
# return a tuple of the shape# of data in idx objectresult = idx.shape  # Print the resultprint(result)
Output :As we can see in the output, the Index.shape attribute has returned a tuple based on the size of the underlying data in the given Index object.
Python pandas-indexing
Python-pandas
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 ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib
Python - How to convert this while loop to for loop?

Usin count() function in itertools module gives an iterator of evenly spaced values. The function takes two parameters. start is by default 0 and step is by default 1. Using defaults will generate infinite iterator. Use break to terminate loop.
import itertools
percentNumbers = [ ]
finish = "n"
num = "0"
for x in itertools.count() :
    num = input("enter the mark : ")
    num = float(num)
    percentNumbers.append(num)
    finish = input("stop? (y/n) ")
    if finish=='y':break
print(percentNumbers)
Sample output of the above script
enter the mark : 11
stop? (y/n)
enter the mark : 22
stop? (y/n)
enter the mark : 33
stop? (y/n) y
[11.0, 22.0, 33.0]
VBA - Programming Charts

Using VBA, you can generate charts based on certain criteria. Let us take a look at it using an example.
Step 1 − Enter the data against which the graph has to be generated.
Step 2 − Create 3 buttons - one to generate a bar graph, another to generate a pie chart, and another to generate a column chart.
Step 3 − Develop a Macro to generate each one of these type of charts.
' Procedure to Generate Pie Chart
Private Sub fn_generate_pie_graph_Click()
   Dim cht As ChartObject
   For Each cht In Worksheets(1).ChartObjects
      cht.Chart.Type = xlPie
   Next cht
End Sub

' Procedure to Generate Bar Graph
Private Sub fn_Generate_Bar_Graph_Click()
   Dim cht As ChartObject
   For Each cht In Worksheets(1).ChartObjects
      cht.Chart.Type = xlBar
   Next cht
End Sub

' Procedure to Generate Column Graph
Private Sub fn_generate_column_graph_Click()
   Dim cht As ChartObject
   For Each cht In Worksheets(1).ChartObjects
      cht.Chart.Type = xlColumn
   Next cht
End Sub
Step 4 − Upon clicking the corresponding button, the chart is created. In the following output, click on generate Pie Chart button.

    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How to search for element in a List in Java?

Let us first create a String array:
String arr[] = { "One", "Two", "Three", "Four", "Five" };
Now convert the above array to List:
ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(arr));
Sort the collection:
Collections.sort(arrList);
Now, find the elements “Four” in the list. We will get the index at which the specified element is found:
int index = Collections.binarySearch(arrList, "Four");
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Demo {
   public static void main(String args[]) {
      String arr[] = { "One", "Two", "Three", "Four", "Five" };
      ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(arr));
      Collections.sort(arrList);
      System.out.println(arrList);
      int index = Collections.binarySearch(arrList, "Four");
      System.out.println("The element exists at index = " + index);
   }
}
[Five, Four, One, Three, Two]
The element exists at index = 1
JavaScript Array.isArray()

The Array.isArray() method of JavaScript is used to determine whether an object is an array or not.
The syntax is as follows −
Array.isArray(ob)
Above, the ob parameter is the object to be tested.
Let us now implement the Array.isArray() method in JavaScript −
 Live Demo
<!DOCTYPE html>
<html>
<body>
   <h2>Ranking Points</h2>
   <p>Is this an array? Click the below button to get the answer...</p>
   <button onclick="display()">Result</button>
   <p id="test"></p>
   <script>
      var pointsArr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 1000];
      var res = pointsArr.entries();
      for (val of res) {
         document.getElementById("test").innerHTML += val + "<br>";
      }
      function display() {
         var res = document.getElementById("test");
         res.innerHTML = Array.isArray(pointsArr);
      }
   </script>
</body>
</html>
Click the “Result” button above −
 Live Demo
<!DOCTYPE html>
<html>
<body>
   <h2>Demo Heading</h2>
   <p>Is this is an array?</p>
   <p id="test"></p>
   <script>
      var arr = ["Accessories", "Electronics", "Books", "Pet Supplies"];
      var res = document.getElementById("test");
      res.innerHTML = Array.isArray(arr);
   </script>
</body>
</html>
How to hide legend with Plotly Express and Plotly in Python? - GeeksforGeeks

19 Dec, 2021
In this article, we will learn How to hide legend with Plotly Express and Plotly. Here we will discuss two different methods for hiding legend in plotly and plotly express, using two different examples for each to make it more clear.
Syntax: For legend:
fig.update_traces(showlegend=False)
fig.update(layout_showlegend=False)
Example 1:
In this example, we are hiding legend in Plotly Express with the help of method fig.update_traces(showlegend=False), bypassing the show legend parameter as False.
Python3
# importing packagesimport plotly.express as px  # using the gapminder datasetdf = px.data.tips()fig = px.scatter(df, x="total_bill", y="tip", color="sex",                  symbol="smoker", facet_col="time",                 labels={"sex": "Gender", "smoker": "Smokes"})  # hiding legend in pyplot express.fig.update_traces(showlegend=False)  fig.show()
Output:
Example 2:
In this example, we are hiding legend in Plotly with the help of method fig.update(layout_showlegend=False), by passing the showlegend parameter as False.
Python3
import plotly.graph_objects as go  # using the Figure datasetfig = go.Figure()  fig.add_trace(go.Line(name="first", x=["a", "b"], y=[1,3]))fig.add_trace(go.Line(name="second", x=["a", "b"], y=[2,1]))fig.add_trace(go.Line(name="third", x=["a", "b"], y=[1,2]))fig.add_trace(go.Line(name="fourth", x=["a", "b"], y=[2,3]))    # hiding legend in pyplot express.fig.update(layout_showlegend=False)  fig.show()
Output:
Example 3:
In this example, we are hiding legend in Plotly Express with the help of method fig.update_traces(showlegend=False), by passing the layout_showlegend parameter as False.
Python3
import plotly.express as px  # using the iris datasetdf = px.data.iris()  # plotting the line chartfig = px.line(df, y="sepal_width", line_dash='species',            color='species')  # hiding legend in pyplot express.fig.update_traces(showlegend=False)  # showing the plotfig.show()
Output:
Picked
Python Plotly express-class
Python-Plotly
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()
Data pretty printer (pprint) in Python

Python has the ability to properly format the content of a print method using a special method called pretty print or pprint. For example when we read a content of an url which is in the form of json, the content will be printed as single line which is hard to read or comprehend. But if we apply pretty print, python gives it a ice structure as per the json tags.
In the below program we are printing the json content of a web page using the traditional print method. The entire result comes as a single line.
import requests
json_url_link = "https://pypi.org/pypi/sampleproject/json"
result = requests.get(json_url_link )
print(result.json())
Running the above code gives us the following result −
{'info': {'author': 'The Python Packaging Authority', 'author_email': 'pypa-dev@googlegroups.com', . . .
Next we take the same content as above but apply the pprint now. As you can see the output format is very organized.
import requests
from pprint import pprint
json_url_link = "https://pypi.org/pypi/sampleproject/json"
result = requests.get(json_url_link )
pprint(result.json())
Running the above code gives us the following result −
{'info': {'author': 'The Python Packaging Authority',
         'author_email': 'pypa-dev@googlegroups.com',
         'bugtrack_url': None,
         'classifiers': ['Development Status :: 3 - Alpha',
                        'Intended Audience :: Developers',
                        'License :: OSI Approved :: MIT License',
                        'Programming Language :: Python :: 2',
                        'Programming Language :: Python :: 2.7',
Difference between Compile Time Errors and Runtime Errors in C Program

Error or exception is something that refers to the interruption of code execution due to which the expected outcome could not be attained to the end-user.On the basis of the event when an error is generated or identified we can classify them as Compile time error and runtime error.
The following are the important differences between Compile Time Errors and Runtime Errors.
CompileDemo.c
#include<stdio.h>
public class CompileDemo{
   void main(){
      int x = 100;
      int y = 155;
      // semicolon missed
      printf("%d", (x, y))
   }
}
error: expected ';' before '}' token
RuntimeDemo.c
include<stdio.h>
public class RuntimeDemo{
   void main(){
      int n = 9;
      div = 0;
      div = n/0;
      printf("resut = %d", div);
   }
}
warning: division by zero [-Wdiv-by-zero]
div = n/0;
How to inverse a matrix using NumPy - GeeksforGeeks

18 Aug, 2020
The inverse of a matrix is just a reciprocal of the matrix as we do in normal arithmetic for a single number which is used to solve the equations to find the value of unknown variables. The inverse of a matrix is that matrix which when multiplied with the original matrix will give as an identity matrix. The inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. Using determinant and adjoint, we can easily find the inverse of a square matrix using below formula,
if det(A) != 0
    A-1 = adj(A)/det(A)
else
    "Inverse doesn't exist"  
where,
A-1: The inverse of matrix A
x: The unknown variable column
B: The solution matrix
Python provides a very easy method to calculate the inverse of a matrix. The function numpy.linalg.inv() which is available in the python NumPy module is used to compute the inverse of a matrix. 
Syntax:
numpy.linalg.inv(a)
Parameters:
a: Matrix to be inverted
Returns: 
Inverse of the matrix a.
Example 1:
Python
# Python program to inverse# a matrix using numpy  # Import required packageimport numpy as np  # Taking a 3 * 3 matrixA = np.array([[6, 1, 1],              [4, -2, 5],              [2, 8, 7]])  # Calculating the inverse of the matrixprint(np.linalg.inv(A))
Output:
[[ 0.17647059 -0.00326797 -0.02287582]
 [ 0.05882353 -0.13071895  0.08496732]
 [-0.11764706  0.1503268   0.05228758]]
Example 2:
Python
# Python program to inverse# a matrix using numpy  # Import required packageimport numpy as np  # Taking a 4 * 4 matrixA = np.array([[6, 1, 1, 3],              [4, -2, 5, 1],              [2, 8, 7, 6],              [3, 1, 9, 7]])  # Calculating the inverse of the matrixprint(np.linalg.inv(A))
Output:
[[ 0.13368984  0.10695187  0.02139037 -0.09090909]
 [-0.00229183  0.02673797  0.14820474 -0.12987013]
 [-0.12987013  0.18181818  0.06493506 -0.02597403]
 [ 0.11000764 -0.28342246 -0.11382735  0.23376623]]

Example 3:
Python
# Python program to inverse# a matrix using numpy  # Import required packageimport numpy as np  # Inverses of several matrices can# be computed at onceA = np.array([[[1., 2.], [3., 4.]],              [[1, 3], [3, 5]]])  # Calculating the inverse of the matrixprint(np.linalg.inv(A))
Output:
[[[-2.    1.  ]
  [ 1.5  -0.5 ]]

 [[-1.25  0.75]
  [ 0.75 -0.25]]]

Picked
Python-numpy
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to replace an element of an ArrayList in Java?

You can replace an element of an ArrayList using the set() method of the Collections class. This method accepts two parameters an integer parameter indicating the index of the element to be replaced and an element to replace with.
 Live Demo
import java.util.ArrayList;

public class ArrayListSample {
   public static void main(String[] args) {
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFx");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      System.out.println(list);
      list.set(2, "HBase");
      System.out.println(list);
   }
}
[JavaFx, Java, WebGL, OpenCV]
[JavaFx, Java, HBase, OpenCV]
Bootstrap - Wells

A well is a container in <div> that causes the content to appear sunken or an inset effect on the page. To create a well, simply wrap the content that you would like to appear in the well with a <div> containing the class of .well. The following example shows a default well −
<div class = "well">Hi, am in well !!</div>
You can change the size of well using the optional classes such as, well-lg or well-lg. These classes are used in conjunction with .well class. These affect the padding, making the well larger or smaller depending on the class.
<div class = "well well-lg">Hi, am in large well !!</div>
<div class = "well well-sm">Hi, am in small well !!</div>

    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
Nested collection filter with JavaScript

Suppose, we have an array of nested objects like this −
const arr = [{
   id: 1,
   legs:[{
      carrierName:'Pegasus'
   }]
},
{
   id: 2,
   legs:[{
      carrierName: 'SunExpress'
   },
   {
      carrierName: 'SunExpress'
   }]
},
{
   id: 3,
   legs:[{
      carrierName: 'Pegasus'
   },
   {
      carrierName: 'SunExpress'
   }]
}];
We are required to write a JavaScript function that takes one such array as the first argument and a search query string as the second argument.
Our function should filter the array to contain only those objects whose "carrier name" property value is the same value specified by the second argument.
If for the above array, the second argument is "Pegasus". Then the output should look like −
const output = [{
   id: 1,
   legs:[{
      carrierName:'Pegasus'
   }]
},
{
   id: 3,
   legs:[{
      carrierName: 'Pegasus'
   },
   {
      carrierName: 'SunExpress'
   }]
}];
The code for this will be −
const arr = [{
   id: 1,
   legs:[{
      carrierName:'Pegasus'
   }]
},
{
   id: 2,
   legs:[{
      carrierName: 'SunExpress'
   },
   {
      carrierName: 'SunExpress'
   }]
},
{
   id: 3,
   legs:[{
      carrierName: 'Pegasus'
   },
   {
      carrierName: 'SunExpress'
   }]
}];
const keys = ['Pegasus'];
const filterByKeys = (arr = [], keys = []) => {
   const res = arr.filter(function(item) {
      const thisObj = this;
      return item.legs.some(leg => {
         return thisObj[leg.carrierName];
      });
   }, keys.reduce((acc, val) => {
      acc[val] = true;
      return acc;
   }, Object.create(null)));
   return res;
}
console.log(JSON.stringify(filterByKeys(arr, keys), undefined, 4));
And the output in the console will be −
[
   {
      "id": 1,
      "legs": [
         {
            "carrierName": "Pegasus"
         }
      ]
   },
   {
      "id": 3,
      "legs": [
         {
            "carrierName": "Pegasus"
         },
         {
            "carrierName": "SunExpress"
         }
      ]
   }
]
Assembly program to transfer the status of switches - GeeksforGeeks

30 Sep, 2019
Problem – Write an assembly language program in 8085 of interfacing between 8085 and 8255. 8 switches are connected at port A. Transfer the status of these switches into port B where LEDs are connected.
Example –
Input port is A and output port is B.
Algorithm –
Construct the control word registerInput the data from port ADisplay the result in port B
Construct the control word register
Input the data from port A
Display the result in port B
Program –
Explanation –
MVI A, 92 means that the value of control register is 92.D7=1 as it is in I/O mode
D6=0 & D5=0 as Poet A is in m0 mode
D4=1 as Port A is taking input
D3=0 & D0=0 as Port C is not taking part
D2=0 as mode of Port B is m0
D1=0as Port B is displaying the resultOUT 83 putting the value of A in 83H which is the port number of port control register.IN 80 taking input from 80H which is the port number of port A.OUT 81 displaying the result in 81H which is the port number of port B.RET return
MVI A, 92 means that the value of control register is 92.D7=1 as it is in I/O mode
D6=0 & D5=0 as Poet A is in m0 mode
D4=1 as Port A is taking input
D3=0 & D0=0 as Port C is not taking part
D2=0 as mode of Port B is m0
D1=0as Port B is displaying the result
D7=1 as it is in I/O mode
D6=0 & D5=0 as Poet A is in m0 mode
D4=1 as Port A is taking input
D3=0 & D0=0 as Port C is not taking part
D2=0 as mode of Port B is m0
D1=0as Port B is displaying the result
OUT 83 putting the value of A in 83H which is the port number of port control register.
IN 80 taking input from 80H which is the port number of port A.
OUT 81 displaying the result in 81H which is the port number of port B.
RET return
Akanksha_Rai
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Architecture of 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Direct Access Media (DMA) Controller in Computer Architecture
Pin diagram of 8086 microprocessor
Computer Organization | Different Instruction Cycles
Difference between SRAM and DRAM
General purpose registers in 8086 microprocessor
I2C Communication Protocol
Memory mapped I/O and Isolated I/O
Shift Micro-Operations in Computer Architecture
How to remove all objects except one or few in R?

We can use rm remove all or few objects.
< x>-rnorm(100,0.5)
< y>-1:100
< z>-rpois(100,5)
< a>-rep(1:5,20)
To remove all objects
> rm(list=ls())
ls()
character(0)
To remove all except a
> rm(list=setdiff(ls(), "a"))
> ls()
[1] "a"
To remove all except x and a
> rm(list=ls()[! ls() %in% c("x","a")])
ls()
[1] "a" "x"
Calculate the Floor and Ceiling values in R Programming - floor() and ceiling() Function - GeeksforGeeks

03 Jun, 2020
floor() function in R Language returns the largest integer that is smaller than or equal to value passed to it as argument(i.e : rounds downs to the nearest integer).
Syntax: floor(x)
Parameter:x: Value to be rounded off
Example 1:
# R program to calculate floor value     # Using floor() method answer1 <- floor(1.2) answer2 <- floor(1.5) answer3 <- floor(2.6) answer4 <- floor(-2.6)     print(answer1) print(answer2) print(answer3) print(answer4) 
Output:
1
1
2
-3

ceiling() function in R Language returns the smallest integer that is greater than or equal to the value passed to it as argument(i.e : rounds up to the nearest integer).
Syntax: ceiling(x)
Parameter:x: Value to be rounded off
Example 1:
# R program to calculate ceiling value     # Using ceiling() method answer1 <- ceiling(1.2) answer2 <- ceiling(1.5) answer3 <- ceiling(2.6) answer4 <- ceiling(-2.6)     print(answer1) print(answer2) print(answer3) print(answer4) 
Output:
2
2
3
-2

R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
How to Split Column Into Multiple Columns in R DataFrame?
How to pass a 2D array as a parameter in C?

A 2-D array can be easily passed as a parameter to a function in C. A program that demonstrates this when both the array dimensions are specified globally is given as follows.
 Live Demo
#include <stdio.h>
const int R = 4;
const int C = 3;
void func(int a[R][C]) {
   int i, j;
   for (i = 0; i < R; i++)
   for (j = 0; j < C; j++)
   a[i][j] += 5; ;
}
int main() {
   int a[R][C];
   int i, j;
   for (i = 0; i < R; i++)
   for (j = 0; j < C; j++)
   a[i][j] = i+j;
   printf("Initial 2-D array is:\n");
   for (i = 0; i < R; i++) {
      for (j = 0; j < C; j++) {
         printf("%d ", a[i][j]);
      }
      printf("\n");
   }
   func(a);
   printf("Modified 2-D array is:\n");
   for (i = 0; i < R; i++) {
      for (j = 0; j < C; j++) {
         printf("%d ", a[i][j]);
      }
      printf("\n");
   }
   return 0;
}
The output of the above program is as follows.
Initial 2-D array is:
0 1 2
1 2 3
2 3 4
3 4 5
Modified 2-D array is:
5 6 7
6 7 8
7 8 9
8 9 10
Prototype - escapeHTML() Method

This method converts HTML special characters to their entity equivalents.
string.escapeHTML();

Returns a string.
<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showResult() {
            var str = '<div class = "article">This is an article</div>';
            alert( str.escapeHTML() );
         }
      </script>
   </head>

   <body>
      <p>Click the button to see the result.</p>
      <br />
      <br />
      <input type = "button" value = "Result" onclick = "showResult();"/>
   </body>
</html>
Click the button to see the result.

    127 Lectures 
     11.5 hours 

 Aleksandar Cucukovic
 Print
 Add Notes
 Bookmark this page
Create a Horizontal Navigation Bar with CSS

To create a horizontal navigation bar, set the <li> elements as inline.
You can try to run the following code to create horizontal navigation bar
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
         }
         .active {
            background-color: #4CAF50;
            color: white;
         }
         li {
            border-bottom: 1px solid #555;
            display: inline;
         }
      </style>
   </head>
   <body>
      <ul>
         <li><a href = "#home">Home</a></li>
         <li><a href = "#company" class = "active">Company</a></li>
         <li><a href = "#product">Product</a></li>
         <li><a href = "#services">Services</a></li>
         <li><a href = "#contact">Contact</a></li>
      </ul>
   </body>
</html>
PyQt5 - QFormLayout Class

QFormLayout is a convenient way to create two column form, where each row consists of an input field associated with a label. As a convention, the left column contains the label and the right column contains an input field. Mainly three overloads of addRow() method addLayout() are commonly used.
addRow(QLabel, QWidget)
Adds a row containing label and input field
addRow(QLabel, QLayout)
Adds a child layout in the second column
addRow(QWidget)
Adds a widget spanning both columns
This code adds a LineEdit field to input name in the first row. Then it adds a vertical box layout for two address fields in the second column of the next row. Next, a horizontal box layout object containing two Radio button fields is added in the second column of the third row. The fourth row shows two buttons ‘Submit’ and ‘Cancel’.
import sys 
from PyQt5.QtCore import * 
from PyQt5.QtGui import * 
from PyQt5.QtWidgets import *

def window():
   app = QApplication(sys.argv)
   win = QWidget()

   l1 = QLabel("Name")
   nm = QLineEdit()

   l2 = QLabel("Address")
   add1 = QLineEdit()
   add2 = QLineEdit()
   fbox = QFormLayout()
   fbox.addRow(l1,nm)
   vbox = QVBoxLayout()

   vbox.addWidget(add1)
   vbox.addWidget(add2)
   fbox.addRow(l2,vbox)
   hbox = QHBoxLayout()

   r1 = QRadioButton("Male")
   r2 = QRadioButton("Female")
   hbox.addWidget(r1)
   hbox.addWidget(r2)
   hbox.addStretch()
   fbox.addRow(QLabel("sex"),hbox)
   fbox.addRow(QPushButton("Submit"),QPushButton("Cancel"))

   win.setLayout(fbox)
   
   win.setWindowTitle("PyQt")
   win.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   window()
The above code produces the following output −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
ConvertDecimal to equivalent 32-bit unsigned integer in C#

To convert the value of the specified Decimal to the equivalent 32-bit unsigned integer, the code is as follows −
 Live Demo
using System;
public class Demo {
   public static void Main() {
      Decimal val = 0.001m;
      Console.WriteLine("Decimal value = "+val);
      uint res = Decimal.ToUInt32(val);
      Console.WriteLine("32-bit unsigned integer = "+res);
   }
}
This will produce the following output −
Decimal value = 0.001
32-bit unsigned integer = 0
Let us see another example −
 Live Demo
using System;
public class Demo {
   public static void Main() {
      Decimal val = 67.487m;
      Console.WriteLine("Decimal value = "+val);
      uint res = Decimal.ToUInt32(val);
      Console.WriteLine("32-bit unsigned integer = "+res);
   }
}
This will produce the following output −
Decimal value = 67.487
32-bit unsigned integer = 67
Import module in Python

In this article, we will learn about all the methods by which we can import modules in Python 3.x. Or earlier. The import statement is used to include all the dependencies/modules needed to execute the code.
import < module name >
import math
print(math.log10(100))
2.0
from <module name> import <function name>
from math import pi
print(math.pi)
3.14159265358979
from math import *
from math import *
print(math.log10(100))
2.0
import <module name> as <alias name>
import math as m
print(m.log10(100))


2.0
In this article, we learned about importing external modules and libraries in Python 3.x. Or earlier.
Array Copy in Java

Array in java can be copied to another array using the following ways.
Using variable assignment. This method has side effects as changes to the element of an array reflects on both the places. To prevent this side effect following are the better ways to copy the array elements.
Using variable assignment. This method has side effects as changes to the element of an array reflects on both the places. To prevent this side effect following are the better ways to copy the array elements.
Create a new array of the same length and copy each element.
Create a new array of the same length and copy each element.
Use the clone method of the array. Clone methods create a new array of the same size.
Use the clone method of the array. Clone methods create a new array of the same size.
Use System.arraycopy() method. arraycopy can be used to copy a subset of an array.
Use System.arraycopy() method. arraycopy can be used to copy a subset of an array.
Create a java class named Tester.
Tester.java
Live Demo
public class Tester {
   public static void main(String args[]) {      
      //Scenario 1: Copy array using assignment
      int[] a = {1, 2, 3};      
      int[] b = a;

      //test side effect
      b[0]++;

      System.out.println("Scenario 1: ");
      System.out.print("Array a: ");
      printArray(a);
      System.out.print("Array b: ");
      printArray(b);

      //Scenario 2: Copy array by iterating
      int[] c = {1, 2, 3};       int[] d = new int[c.length];
      for (int i = 0; i < d.length; i++) {
         d[i] = c[i];
      }

      //test side effect
      d[0]++;

      System.out.println("Scenario 2: ");
      System.out.print("Array c: ");
      printArray(c);
      System.out.print("Array d: ");
      printArray(d);

      //Scenario 3: Copy array using clone
      int[] e = {1, 2, 3};      
      int[] f = e.clone();

      //test side effect
      f[0]++;

      System.out.println("Scenario 3: ");
      System.out.print("Array e: ");
      printArray(e);
      System.out.print("Array f: ");
      printArray(f);

      //Scenario 4: Copy array using arraycopy
      int[] g = {1, 2, 3};      
      int[] h = new int[g.length];
      System.arraycopy(g, 0, h, 0, h.length);

      //test side effect
      h[0]++;

      System.out.println("Scenario 4: ");
      System.out.print("Array g: ");
      printArray(g);
      System.out.print("Array h: ");
      printArray(h);    
   }

   public static void printArray(int[] a) {
      System.out.print("[ ");
      for (int i = 0; i < a.length; i++) {
         System.out.print(a[i] + " ");
      }
      System.out.println("]");
   }
}
Compile and Run the file to verify the result.
Scenario 1:  
Array a: [ 2 2 3 ]
Array b: [ 2 2 3 ]
Scenario 2:  
Array c: [ 1 2 3 ]
Array d: [ 2 2 3 ]
Scenario 3:  
Array e: [ 1 2 3 ]
Array f: [ 2 2 3 ]
Scenario 4:  
Array g: [ 1 2 3 ]
Array h: [ 2 2 3 ]
Apache Presto - contains(x,element)

presto:default> select contains(array[1,2],5) as array_contains; 
 array_contains 
---------------- 
    false 


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Read and Write to an excel file using Python openpyxl module

Python provides openpyxl module for operating with Excel files.
How to create Excel files, how to write, read etc. can be implemented by this module.
For installing openpyxl module, we can write this command in command prompt
pip install openpyxl

import openpyxl
my_wb = openpyxl.Workbook()
my_sheet = my_wb.active
my_sheet_title = my_sheet.title
print("My sheet title: " + my_sheet_title)
My sheet title:Sheet

import openpyxl
my_wb = openpyxl.Workbook()
my_sheet = my_wb.active
my_sheet.title = "My New Sheet"
print("sheet name is : " + sheet.title)
sheet name is : My New Sheet

import openpyxl
my_wb = openpyxl.Workbook()
my_sheet = my_wb.active
c1 = my_sheet.cell(row = 1, column = 1)
c1.value = "Aadrika"
c2 = my_sheet.cell(row= 1 , column = 2)
c2.value = "Adwaita"
c3 = my_sheet['A2']
c3.value = "Satyajit"
# B2 = column = 2 & row = 2.
c4 = my_sheet['B2']
c4.value = "Bivas"
my_wb.save("C:\Users\TP\Desktop\Book1.xlsx")
import openpyxl
my_wb = openpyxl.Workbook()
my_sheet = my_wb.active
my_wb.create_sheet(index = 1 , title = "new sheet")
my_wb.save("C:\Users\TP\Desktop\Book1.xlsx")
import openpyxl
my_path = "C:\Users\TP\Desktop\Book1.xlsx"
my_wb_obj = openpyxl.load_workbook(my_path)
my_sheet_obj = my_wb_obj.active
print(my_sheet_obj.max_row)
2

import openpyxl
# Give the location of the file
My_path = "C:\Users\TP\Desktop\Book1.xlsx"
wb_obj = openpyxl.load_workbook(my_path)
my_sheet_obj = my_wb_obj.active
my_cell_obj = my_sheet_obj.cell(row = 1, column = 1)
print(my_cell_obj.value)
Aadrika

import openpyxl
# Give the location of the file
My_path = "C:\Users\TP\Desktop\Book1.xlsx"
My_wb_obj = openpyxl.load_workbook(path)
my_sheet_obj = my_wb_obj.active
print(sheet_obj.max_column)
2

import openpyxl
# Give the location of the file
my_path = "C:\Users\TP\Desktop\Book1.xlsx"
# workbook object is created
my_wb_obj = openpyxl.load_workbook(my_path)
my_sheet_obj = my_wb_obj.active
my_max_col = my_sheet_obj.max_column
for i in range(1, my_max_col + 1):
   my_cell_obj = my_sheet_obj.cell(row = 1, column = i)
   print(my_cell_obj.value) 
Aadrika Adwaita

import openpyxl
# Give the location of the file
my_path = "C:\Users\TP\Desktop\Book1.xlsx"
my_wb_obj = openpyxl.load_workbook(my_path)
my_sheet_obj = my_wb_obj.active
my_row = my_sheet_obj.max_row
for i in range(1, my_row + 1):
   cell_obj = my_sheet_obj.cell(row = i, column = 1)
   print(cell_obj.value)
Aadrika
Satyajit

import openpyxl
# Give the location of the file
my_path = "C:\Users\TP\Desktop\Book1.xlsx"
my_wb_obj = openpyxl.load_workbook(my_path)
my_sheet_obj = my_wb_obj.active
my_max_col = my_sheet_obj.max_column
for i in range(1, my_max_col + 1):
   cell_obj = my_sheet_obj.cell(row = 2, column = i)
   print(cell_obj.value, end = " ")
Satyajit Bivas