code-rag-bench/online-tutorials huggingface dataset:
Difference Between System.out.print() and System.out.println() Function in Java - GeeksforGeeks

07 Oct, 2021

In Java, we have the following functions to print anything in the console.
System.out.print() and
System.out.println()
But there is a slight difference between both of them, i.e. 
System.out.println() prints the content and switch to the next line after execution of the statement whereas 
System.out.print() only prints the content without switching to the next line after executing this statement.
The following examples will help you in understanding the difference between them more prominently.
Example 1:
Java
 

 
 










import java.io.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
        System.out.println("Welcome to JAVA (1st line)");  
        
          // this print statement will be printed in a new line. 
        System.out.print("Welcome to GeeksforGeeks (2nd line) ");  
        
          // this print statement will be printed in the same line. 
        System.out.print("Hello Geeks (2nd line)"); 
    } 
}






Welcome to JAVA (1st line)
Welcome to GeeksforGeeks (2nd line) Hello Geeks (2nd line)
Example 2:
Java
 

 
 










import java.io.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
        System.out.print("Welcome to JAVA (1st line) ");  
        
          // this print statement will be printed in the same line. 
        System.out.println("Welcome to GeeksforGeeks (1st line)");  
        
          // this print statement will be printed in a new line. 
        System.out.print("Hello Geeks (2nd line)"); 
    } 
}






Welcome to JAVA (1st line) Welcome to GeeksforGeeks (1st line)
Hello Geeks (2nd line)

Difference Between


Java

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Ubuntu - Command Line

Ubuntu is a Linux based operating system and most Linux users are more familiar with the command line interface. In this chapter, we will go through some of the popular command line’s used in Ubuntu.
To invoke the command line, go to the search option and enter the command keyword in the search box.
The search result will give the Terminal option. Double-lick to get the command line as shown in the following screenshot.
The easiest command to start with, is the directory listing command which is used to list the directory contents.
ls –option directoryname

Option − These are the options to be specified with the ls command.
Option − These are the options to be specified with the ls command.
Directoryname − This is the optional directory name that can be specified along with the ls command.
Directoryname − This is the optional directory name that can be specified along with the ls command.
The output will be the listing of the directory contents.
In the following example, we just issue the ls command to list the directory contents.
The directory listing of the current directory will be shown as the output.
Another variant of the ls command is to list the directory, but with more details on each line item. This is shown in the following screenshot with the ls –l command.
To clear the screen, we can use the clear command.
clear

None
The command line screen will be cleared.
To get more information on a command, we can use the ‘man’ command.
man commandname

Commandname − This is the name of the command for which more information is required.
The information on the command will be displayed.
Following is an example of the ‘man’ command. If we issue the ‘man ls’ command, we will get the following output. The output will contain information on the ls command.
We can use the find command to find for files.
find filepattern

Filepattern − This is the pattern used to find for files.
The files based on the file pattern will be displayed.
In this example, we will issue the following command.
find Sample.*

This command will list all the files which start with the word ‘Sample’.
This command is used to display who is the current logged on user.
whoami

None
The name of the current logged on user will be displayed.
In this example, we will issue the following command.
whoami

This command will display the current working directory.
pwd

None
The current working directory will be displayed.
In this example, we will issue the following command.
Pwd


    8 Lectures 
     31 mins

 Musab Zayadneh

    14 Lectures 
     1.5 hours 

 Satish

    26 Lectures 
     1.5 hours 

 YouAccel
 Print
 Add Notes
 Bookmark this page
Simple Machine Learning Model in Python in 5 lines of code | by Raman Sah | Towards Data Science

In this blog, we will train a Linear Regression Model and expect to perform correct on a fresh input.
The basic idea of any machine learning model is that it is exposed to a large number of inputs and also supplied the output applicable for them. On analysing more and more data, it tries to figure out the relationship between input and the result.
Consider a very primitive example when you have to decide whether to wear a jacket or not depending on the weather. You have access to the training data as we call it -
+---------------------+---------------+| Outside Temperature | Wear a Jacket |+---------------------+---------------+| 30°C                | No            || 25°C                | No            || 20°C                | No            || 15°C                | Yes           || 10°C                | Yes           |+---------------------+---------------+
Somehow, your mind finds a connection between the input (temperature) and the output (decision to wear a jacket).
So, if the temperature is 12°C, you would still wear a jacket although you were never told the outcome for that particular temperature.
Now, lets move on to a slightly better algebraic problem which the computer will solve for us.
Before we begin, don’t forget to install scikit-learn, it provides easy to use functions and predefined models which saves a lot of time
pip install scikit-learn
Here, X is the input and y is the output.
Given the training set you could easily guess that the output (y) is nothing but (x1 + 2*x2 + 3*x3).
Working with linear regression model is simple. Create a model, train it and then use it :)
We have the training set ready, so create a Linear Regression Model and pass it the training data.
X = [[10, 20, 30]]
The outcome should be 10 + 20*2 + 30*3 = 140. Let’s see what we got...
Outcome : [ 140.]Coefficients : [ 1. 2. 3.]
Did you notice what just happened? The model had access to the training data, through which it calculated the weights to assign to the inputs to arrive at the desired output. On giving test data, it successfully managed to get the right answer!
If you want to dive deeper into Machine Learning and use Python; I would prefer this book to start with.
shop.oreilly.com
I also experiment a lot and tinker with code. Feel free to fork ML Prototype where I have tried to expose the functions of scikit-learn through API. And don’t forget to clap if you find this article interesting.
Python | bytearray() function - GeeksforGeeks

30 Jul, 2018
bytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256.
Syntax:
bytearray(source, encoding, errors)
Parameters:
source[optional]: Initializes the array of bytes
encoding[optional]: Encoding of the string
errors[optional]: Takes action when encoding fails

Returns: Returns an array of bytes of the given size.
source parameter can be used to initialize the array in few different ways. Let’s discuss each one by one with help of examples.
Code #1: If a string, must provided encoding and errors parameters, bytearray() converts the string to bytes using str.encode()
str = "Geeksforgeeks"  # encoding the string with unicode 8 and 16array1 = bytearray(str, 'utf-8')array2 = bytearray(str, 'utf-16')  print(array1)print(array2)
Output:
bytearray(b'Geeksforgeeks')
bytearray(b'\xff\xfeG\x00e\x00e\x00k\x00s\x00f\x00o\x00r\x00g\x00e\x00e\x00k\x00s\x00')
 Code #2: If an integer, creates an array of that size and initialized with null bytes.
# size of arraysize = 3  # will create an array of given size # and initialize with null bytesarray1 = bytearray(size)  print(array1)
Output:
bytearray(b'\x00\x00\x00')
 Code #3: If an Object, read-only buffer will be used to initialize the bytes array.
# Creates bytearray from byte literalarr1 = bytearray(b"abcd")  # iterating the valuefor value in arr1:    print(value)      # Create a bytearray objectarr2 = bytearray(b"aaaacccc")  # count bytes from the bufferprint("Count of c is:", arr2.count(b"c"))
Output:
97
98
99
100
Count of c is: 4
 Code #4: If an Iterable(range 0<= x < 256), used as the initial contents of an array.
# simple list of integerslist = [1, 2, 3, 4]  # iterable as sourcearray = bytearray(list)  print(array)print("Count of bytes:", len(array))
Output:
bytearray(b'\x01\x02\x03\x04')
Count of bytes: 4
Code #5: If No source, an array of size 0 is created.
# array of size o will be created  # iterable as sourcearray = bytearray()  print(array)
Output:
bytearray(b'')
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Python Conditions

Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
An "if statement" is written by using the if keyword.
If statement:
In this example we use two variables, a and b,
which are used as part of the if statement to test whether b is greater than a.
As a is 33, and b is 200,
we know that 200 is greater than 33, and so we print to screen that "b is greater than a".
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.


If statement, without indentation (will raise an error):
The elif keyword is pythons way of saying "if the previous conditions were not true, then 
try this condition".
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that "a and b are equal".
The else keyword catches anything which isn't caught by the preceding conditions.
In this example a is greater than b,
so the first condition is not true, also the elif condition is not true,
so we go to the else condition and print to screen that "a is greater than b".
You can also have an else without the
elif:
If you have only one statement to execute, you can put it on the same line as the if statement.
One line if statement:
If you have only one statement to execute, one for if, and one for else, you can put it 
all on the same line:
One line if else statement:
This technique is known as Ternary Operators, or Conditional 
  Expressions.
You can also have multiple else statements on the same line:
One line if else statement, with 3 conditions:
The and keyword is a logical operator, and 
is used to combine conditional statements:
Test if a is greater than
  b, AND if c 
  is greater than a:
The or keyword is a logical operator, and 
is used to combine conditional statements:
Test if a is greater than
  b, OR if a 
  is greater than c:
You can have if statements inside 
if statements, this is called nested
if statements.
if statements cannot be empty, but if you 
for some reason have an if statement with no content, put in the pass statement to avoid getting an error.
Print "Hello World" if a is greater than b.
a = 50
b = 10
 a  b
  print("Hello World")

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Check if it is possible to make two matrices strictly increasing by swapping corresponding values only in Python

Suppose we have two matrices of size n x m named mat1 and mat2. We have to check where these two matrices are strictly increasing or not by swapping only two elements in different matrices only when they are at position (i, j) in both matrices.
So, if the input is like
then the output will be True as we can swap (7, 14) and (10, 17) pairs to make them strictly increasing.
To solve this, we will follow these steps −
row := row count of mat1
col := column count of mat1
for i in range 0 to row - 1, dofor j in range 0 to col - 1, doif mat1[i,j] > mat2[i,j], thenswap mat1[i, j] and mat2[i, j]for i in range 0 to row - 1, dofor j in range 0 to col-2, doif mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn Falsefor i in range 0 to row-2, dofor j in range 0 to col - 1, doif mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False
for j in range 0 to col - 1, doif mat1[i,j] > mat2[i,j], thenswap mat1[i, j] and mat2[i, j]
if mat1[i,j] > mat2[i,j], thenswap mat1[i, j] and mat2[i, j]
swap mat1[i, j] and mat2[i, j]
for i in range 0 to row - 1, dofor j in range 0 to col-2, doif mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn False
for j in range 0 to col-2, doif mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn False
if mat1[i, j] >= mat1[i, j + 1] or mat2[i, j] >= mat2[i, j + 1], thenreturn False
return False
for i in range 0 to row-2, dofor j in range 0 to col - 1, doif mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False
for j in range 0 to col - 1, doif mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False
if mat1[i, j] >= mat1[i + 1, j] or mat2[i, j] >= mat2[i + 1, j], thenreturn False
return False
return True
Let us see the following implementation to get better understanding −
 Live Demo
def solve(mat1, mat2):
   row = len(mat1)
   col = len(mat1[0])
   for i in range(row):
      for j in range(col):
         if mat1[i][j] > mat2[i][j]:
            mat1[i][j], mat2[i][j]= mat2[i][j], mat1[i][j]
   for i in range(row):
      for j in range(col-1):
         if mat1[i][j]>= mat1[i][j + 1] or mat2[i][j]>= mat2[i][j + 1]:
            return False
   for i in range(row-1):
      for j in range(col):
         if mat1[i][j]>= mat1[i + 1][j] or mat2[i][j]>= mat2[i + 1][j]:
            return False
   return True
mat1 = [[7, 15],
         [16, 10]]
mat2 = [[14, 9],
         [8, 17]]
print(solve(mat1, mat2))
[[7, 15],
[16, 10]],
[[14, 9],
[8, 17]]
True
How to get last 2 characters from string in C# using Regex?

Set the string −
string str = "Cookie and Session";
Use the following Regex to get the last 2 characters from string −
Regex.Match(str,@"(.{2})\s*$")
The following is the code −
 Live Demo
using System;
using System.Text.RegularExpressions;
public class Demo {
   public static void Main() {
      string str = "Cookie and Session";
      Console.WriteLine(Regex.Match(str,@"(.{2})\s*$"));
   }
}
on
JSTL - fn:startsWith() Function

The fn:startsWith() function determines if an input string starts with a specified substring.
The fn:startsWith() function has the following syntax −
boolean startsWith(java.lang.String, java.lang.String)

Following example explains the functionality of the fn:startsWith() function −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>

<html>
   <head>
      <title>Using JSTL Functions</title>
   </head>

   <body>
      <c:set var = "string" value = "Second: This is first String."/>
      
      <c:if test = "${fn:startsWith(string, 'First')}">
         <p>String starts with First</p>
      </c:if>
      
      <br />
      <c:if test = "${fn:startsWith(string, 'Second')}">
         <p>String starts with Second</p>
      </c:if>
   
   </body>
</html>
You will receive the following result −
String starts with Second


    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to use SVG images in HTML5?

To use SVG images in HTML5, use <img> element or <svg>. To add SVG files, you can use <img> <object>, or <embed> element in HTML. Choose any one of them according to your requirement.
Here’s how you can add SVG images. If the SVG is saved as a file, it can be directly used as an SVG image:
You can try to run the following code to use SVG Images
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         #svgelem {
            position: relative;
            left: 50%;
            -webkit-transform: translateX(-20%);
            -ms-transform: translateX(-20%);
            transform: translateX(-20%);
         }
      </style>
      <title>HTML5 SVG Image</title>
   </head>
   <body>
      <h2 align="center">HTML5 SVG Image</h2>
      <img src="https://www.tutorialspoint.com/html5/src/svg/extensions/imagelib/smiley.svg" alt="smile" height="100px" width="100px" />
   </body>
</html>
C# Tutorial (C Sharp)

C# (C-Sharp) is a programming language developed by Microsoft that runs on the .NET 
Framework.
C# is used to develop web apps, desktop apps, mobile apps, games and much 
more.
Our "Try it Yourself" tool makes it easy to learn C#. You can edit C# code and view the result in your browser.
using System;

namespace HelloWorld
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World!");    
    }
  }
}

Try it Yourself »

Click on the "Run example" button to see how it works.
We recommend reading this tutorial, in the sequence listed in the left menu.
Insert the missing part of the code below to output "Hello World!".
static void (string[] args)
{
  .("Hello World!");    
}

Start the Exercise
Learn by examples! This tutorial supplements all explanations with clarifying examples.
See All C# Examples
Learn by taking a quiz! The quiz will give you a signal of how much you know, or do not know, about C#.
Start C# Quiz
Get certified by completing the C# course
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Return type of getchar(), fgetc() and getc() in C

Details about getchar(), fgetc() and getc() functions in C programming are given as follows −
The getchar() function obtains a character from stdin. It returns the character that was read in the form of an integer or EOF if an error occurs.
A program that demonstrates this is as follows −
 Live Demo
#include <stdio.h>

int main (){
   int i;

   printf("Enter a character: ");
   i = getchar();

   printf("\nThe character entered is: ");
   putchar(i);

   return(0);
}
The output of the above program is as follows −
Enter a character: G
The character entered is: G
Now let us understand the above program.
The value obtained using the getchar() function is stored in i which is an integer variable. Then the character value is displayed using putchar(). The code snippet that shows this is as follows −
int i;

printf("Enter a character: ");
i = getchar();

printf("\nThe character entered is: ");
putchar(i);
The fgetc() function obtains a character from a file stream which is a pointer to a FILE object. This function returns the character that was read in the form of an integer or EOF if an error occurs.
A program that demonstrates this is as follows −
 Live Demo
#include <stdio.h>

int main (){
   FILE *fp;
   fp = fopen("file.txt", "w");
   fprintf(fp, "Apple");
   fclose(fp);

   int i;

   fp = fopen("file.txt","r");
   
   if(fp == NULL){
      perror("Error in opening file");
      return(-1);
   }

   while((i=fgetc(fp))!=EOF){
      printf("%c",i);
   }

   fclose(fp);
   return(0);
}
The output of the above program is as follows −
Apple
Now let us understand the above program.
First, the file is created and the data "Apple" is stored inside it. Then the file is closed. The code snippet that shows this is as follows −
FILE *fp;
fp = fopen("file.txt", "w");
fprintf(fp, "Apple");
fclose(fp);
The file is opened again in reading mode. If fp is NULL then error message is displayed. Otherwise the contents of the file are displayed using the fgetc() function. The code snippet that shows this is as follows −
fp = fopen("file.txt","r");

if(fp == NULL){
   perror("Error in opening file");
   return(-1);
}

while((i=fgetc(fp))!=EOF){
   printf("%c",i);
}

fclose(fp);
The getc() function obtains a character from the stream that is specified. It returns the character that was read in the form of an integer or EOF if an error occurs.
A program that demonstrates this is as follows −
 Live Demo
#include <stdio.h>

int main (){
   int i;

   printf("Enter a character: ");
   i = getc(stdin);

   printf("\nThe character entered is: ");
   putchar(i);

   return(0);
}
The output of the above program is as follows −
Enter a character: K
The character entered is: K
Now let us understand the above program.
The getc() function obtains a character from the stream stdin as specified. This value is stored in int variable i. Then the character value is displayed using putchar(). The code snippet that shows this is as follows −
int i;

printf("Enter a character: ");
i = getc(stdin);

printf("\nThe character entered is: ");
putchar(i);
How to declare variables in JavaScript?

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows.
<script>
   <!--
      var money;
      var name;
   //-->
</script>
You can also declare multiple variables with the same var keyword as follows −
<script>
   <!--
      var money, name;
   //-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.
Fetch records from interval of past 3 days from current date in MySQL and add the corresponding records

Let us first create a table −
mysql> create table DemoTable
(
   ProductAmount int,
   PurchaseDate datetime
);
Query OK, 0 rows affected (0.94 sec)
Note − Let’s say the current date is 2010-09-15.
Insert some records in the table using insert command −
mysql> insert into DemoTable values(567,'2019-09-10');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(1347,'2019-09-14');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(2033,'2019-09-13');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(1256,'2019-09-11');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(1000,'2019-09-16');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------+---------------------+
| ProductAmount | PurchaseDate        |
+---------------+---------------------+
|           567 | 2019-09-10 00 :00 :00 |
|          1347 | 2019-09-14 00:00 :00 |
|          2033 | 2019-09-13 00:00 :00 |
|          1256 | 2019-09-11 00:00 :00 |
|          1000 | 2019-09-16 00:00 :00 |
+---------------+---------------------+
5 rows in set (0.00 sec)
Following is the query to use now() function in MySQL query −
mysql> select sum(ProductAmount) from DemoTable
   where PurchaseDate > NOW()- interval 3 day;
This will produce the following output −
+--------------------+
| sum(ProductAmount) |
+--------------------+
|             4380   |
+--------------------+
1 row in set (0.00 sec)
Python - Searching Algorithms

Searching is a very basic necessity when you store data in different data structures. The simplest approach is to go across every element in the data structure and match it with the value you are searching for.This is known as Linear search. It is inefficient and rarely used, but creating a program for it gives an idea about how we can implement some advanced search algorithms.
In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data structure.
def linear_search(values, search_for):
   search_at = 0
   search_res = False
# Match the value with each data element	
   while search_at < len(values) and search_res is False:
      if values[search_at] == search_for:
         search_res = True
      else:
         search_at = search_at + 1
   return search_res
l = [64, 34, 25, 12, 22, 11, 90]
print(linear_search(l, 12))
print(linear_search(l, 91))
When the above code is executed, it produces the following result −
True
False

This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in a sorted form and equally distributed.Initially, the probe position is the position of the middle most item of the collection.If a match occurs, then the index of the item is returned.If the middle item is greater than the item, then the probe position is again calculated in the sub-array to the right of the middle item. Otherwise, the item is searched in the subarray to the left of the middle item. This process continues on the sub-array as well until the size of subarray reduces to zero.
There is a specific formula to calculate the middle position which is indicated in the program below −
def intpolsearch(values,x ):
   idx0 = 0
   idxn = (len(values) - 1)
   while idx0 <= idxn and x >= values[idx0] and x <= values[idxn]:
# Find the mid point
	mid = idx0 +\
      int(((float(idxn - idx0)/( values[idxn] - values[idx0]))
      * ( x - values[idx0])))
# Compare the value at mid point with search value 
   if values[mid] == x:
      return "Found "+str(x)+" at index "+str(mid)
   if values[mid] < x:
      idx0 = mid + 1
   return "Searched element not in the list"

l = [2, 6, 11, 19, 27, 31, 45, 121]
print(intpolsearch(l, 2))
When the above code is executed, it produces the following result −
Found 2 at index 0


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^n in C++

In this problem, we are given a number n which defines the n-th term of the series 2^0, 2^1, 2^2, ..., 2^n. Our task is to create a program to find the sum of the series 2^0 + 2^1 + 2^2 +...+ 2^n.
Input
n=6
Output 
Explanation 
sum = 2^0 + 2^1 + 2^2 + 2^3 + 2^4 + 2^5 + 2^6
sum = 1 + 2 + 4 + 8 + 16 + 32 + 64 = 127
A simple solution to the problem is by using the loop. Finding the 2^i, for each value from 0 to n and add it to the sum variable.
Initialize sum = 0
Step 1: Iterate from i = 0 to n. And follow :
Step 1.1: Update sum, sum += 2^i.
Step 2: Print sum.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
#include <math.h>
using namespace std;
int calcSeriesSum(int n) {
   int sum = 0;
   for (int i = 0; i <= n; i++)
   sum += pow(2, i);
   return sum;
}
int main() {
   int n = 11;
   cout<<"Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^"<<n<<" is "<<calcSeriesSum(n);
   return 0;
}
Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^11 is 4095
This is not the most effective method to solve this problem as it uses a loop that makes its time complexity of the order O(n).
A more effective solution, we will use the mathematical formula for the sum. It is given by
 2^(n+1) - 1
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
#include <math.h>
using namespace std;
int calcSeriesSum(int n) {
   return ( (pow(2, (n+1)) - 1) );
}
int main() {
   int n = 11;
   cout<<"Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^"<<n<<" is "<<calcSeriesSum(n);
   return 0;
}
Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^11 is 4095
BabylonJS - Box

In this section, we will learn how to add box to the scene we created.
To create box, following is the syntax.
var box = BABYLON.Mesh.CreateBox("box", 6.0, scene, false, BABYLON.Mesh.DEFAULTSIDE);

The following are the different parameters to add box −
Name − The Name to be given to the box; for example, “box”.
Name − The Name to be given to the box; for example, “box”.
Size of the box − The size of the box.
Size of the box − The size of the box.
Scene − The scene is where the box will be attached.
Scene − The scene is where the box will be attached.
Boolean value − False is the default value.
Boolean value − False is the default value.
BABYLON.Mesh.DEFAULTSIDE − This is used for orientation.
BABYLON.Mesh.DEFAULTSIDE − This is used for orientation.
The last 2 parameters are optional.
<!doctype html>
<html>
   <head>
      <meta charset = "utf-8">
      <title>BabylonJs - Basic Element-Creating Scene</title>
      <script src = "babylon.js"></script>
      <style>
         canvas {width: 100%; height: 100%;}
      </style>
   </head>

   <body>
      <canvas id = "renderCanvas"></canvas>
      <script type = "text/javascript">
         var canvas = document.getElementById("renderCanvas");
         var engine = new BABYLON.Engine(canvas, true);
         var createScene  = function() {
            var scene = new BABYLON.Scene(engine);
            scene.clearColor = new BABYLON.Color3(0, 1, 0);
         
            var camera = new BABYLON.ArcRotateCamera("Camera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);
            camera.attachControl(canvas, true);
         
            var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);
            light.intensity = 0.7;	
         
            var pl = new BABYLON.PointLight("pl", BABYLON.Vector3.Zero(), scene);
            pl.diffuse = new BABYLON.Color3(1, 1, 1);
            pl.specular = new BABYLON.Color3(1, 1, 1);
            pl.intensity = 0.8;
         
            var box = BABYLON.Mesh.CreateBox("box", '3', scene);	
            scene.registerBeforeRender(function() { 
               pl.position = camera.position;
            });

            return scene;
         };
         var scene = createScene();
         engine.runRenderLoop(function() {
            scene.render();
         });
      </script>
   </body>
</html>
Upon execution, the above code will generate the following output −
Size refers to the height of the box on all sides. A size of 100 will basically be a box occupying full screen. The color given to the background scene is green. We are using the camera and light effect to move the screen onmouse cursor. This helps in the light effect too.
 Print
 Add Notes
 Bookmark this page
How to create a left-right split pane in Java?

To create a left-right split pane, let us create two components and split them −
JComponent one = new JLabel("Left Split");
one.setBorder(BorderFactory.createLineBorder(Color.MAGENTA));
JComponent two = new JLabel("Right Split");
two.setBorder(BorderFactory.createLineBorder(Color.ORANGE));
Now, we will split them. The two components will be split one to the left of the other using HORIZONTAL_PANE constant −
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, one, two);
The following is an example to create a left-right split pane in Java −
package my;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSplitPane;
public class SwingDemo {
   public static void main(String[] a) {
      JFrame frame = new JFrame("SplitPane Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JComponent one = new JLabel("Left Split");
      one.setBorder(BorderFactory.createLineBorder(Color.MAGENTA));
      JComponent two = new JLabel("Right Split");
      two.setBorder(BorderFactory.createLineBorder(Color.ORANGE));
      JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, one, two);
      frame.add(splitPane);
      frame.setSize(550, 250);
      frame.setVisible(true);
   }
}
This will produce the following output −
Instant minus() method in Java

An immutable copy of a instant where a time unit is subtracted from it can be obtained using the minus() method in the Instant class in Java. This method requires two parameters i.e. time to be subtracted from the instant and the unit in which it is to be subtracted. It also returns the immutable copy of the instant where the required time unit is subtracted.
A program that demonstrates this is given as follows −
 Live Demo
import java.time.*;
import java.time.temporal.ChronoUnit;
public class Demo {
   public static void main(String[] args) {
      Instant i = Instant.now();
      System.out.println("The current instant is: " + i);
      Instant sub = i.minus(2, ChronoUnit.HOURS);
      System.out.println("The instant with 2 hours subtracted is: " + sub);
   }
}
The current instant is: 2019-02-13T06:40:32.595Z
The instant with 2 hours subtracted is: 2019-02-13T04:40:32.595Z
Now let us understand the above program.
First the current instant is displayed. Then an immutable copy of the instant where 2 hours are subtracted is obtained using the minus() method and this is displayed. A code snippet that demonstrates this is as follows −
Instant i = Instant.now();
System.out.println("The current instant is: " + i);
Instant sub = i.minus(2, ChronoUnit.HOURS);
System.out.println("The instant with 2 hours subtracted is: " + sub);
Batch Script – Remove All Spaces

28 Nov, 2021
In this article, we are going to see how to remove all spaces from any string using Batch String.
Example :
Input: G e e k s     f o r    G e e k s
Output: GeeksforGeeks
By using ‘ set ‘ we are getting input of any string.Example: set str=input string
Example: set str=input string
In the next line using ‘ echo %str% ‘ we are printing our input string.
In the next line of code, we are going to remove all spaces in the input string.
Using ‘ := ‘ operator we are removing spaces in any string.
We have to type any character between and = to remove that character from any given input string.For example: str=%str:e=% (this will remove e from the input string)
For example: str=%str:e=% (this will remove e from the input string)
So for removing spaces we will use ‘ : = ‘ .
‘ pause ‘ is used to hold the screen until any key is pressed.
Code:
@echo off
set str=G e e k s     f o r    G e e k s
echo %str%
set str=%str: =%
echo %str%
pause
Output:
batch script to remove all spaces.
Batch-script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
Perl | index() Function

25 Jun, 2019
This function returns the position of the first occurrence of given substring (or pattern) in a string (or text). We can specify start position. By default, it searches from the beginning(i.e. from index zero).
Syntax:# Searches pat in text from given indexindex(text, pat, index)
# Searches pat in textindex(text, pat)
Parameters:
text: String in which substring is to be searched.
pat: Substring to be searched.
index: Starting index(set by the user or it takes zero by default).
Returns:-1 on failure otherwise Position of the matching string.
Example 1:
#!/usr/bin/perl  # String from which Substring # is to be searched $string = "Geeks are the best";  # Using index() to search for substring$index = index ($string, 'the');  # Printing the position of the substringprint "Position of 'the' in the string: $index\n";
Position of 'the' in the string: 10

Example 2:
#!/usr/bin/perl  # String from which Substring # is to be searched $string = "Geeks are the best";  # Defining the starting Index$pos = 3;  # Using index() to search for substring$index = index ($string, 'Geeks', $pos);  # Printing the position of the substringprint "Position of 'Geeks' in the string: $index\n";
Position of 'Geeks' in the string: -1

Here, in the second example the position is set to ‘3’, i.e. the starting index from where searching is to begin is from 3rd position. Hence, the substring is not found in the String.
Perl-function
Perl-String
Perl-String-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays (push, pop, shift, unshift)
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Perl | Polymorphism in OOPs
Perl | Boolean Values
Perl | Subroutines or Functions
Use of print() and say() in Perl
Perl | Basic Syntax of a Perl Program
Hello World Program in Perl
Introduction to Perl
map::operator[] in C++ STL

06 Oct, 2021
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values. 
This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of map, while this operator causes undefined behavior.Syntax :  
mapname[key]
Parameters :
Key value mapped to the element to be fetched.
Returns :
Direct reference to the element at the given key value.
Examples:  
Input  :  map mymap;
          mymap['a'] = 1;
          mymap['a'];
Output :  1

Input  :  map mymap;
          mymap["abcd"] = 7;
          mymap["abcd"];
Output :  7
Errors and Exceptions1. If the key is not present in the map, it shows undefined behavior. 2. It has a no exception throw guarantee otherwise. 
CPP
// CPP program to illustrate// Implementation of [] operator#include <map>#include <iostream>#include<string>using namespace std; int main(){    // map declaration    map<int,string> mymap;         // mapping integers to strings    mymap[1] = "Hi";    mymap[2] = "This";    mymap[3] = "is";    mymap[4] = "GeeksForGeeks";         // using operator[] to print string    // mapped to integer 4    cout << mymap[4];    return 0;}
Output: 
GeeksForGeeks
Time Complexity: O(logn) 
hritikbhatnagar2182
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
std::find in C++
Inline Functions in C++
NumPy Array Shape

19 Feb, 2022
The shape of an array can be defined as the number of elements in each dimension. Dimension is the number of indices or subscripts, that we require in order to specify an individual element of an array.
In NumPy we will use an attribute called shape which returns a tuple, the elements of the tuple give the lengths of the corresponding array dimensions.
Syntax: numpy.shape(array_name) Parameters: Array is passed as a Parameter. Return: A tuple whose elements give the lengths of the corresponding array dimensions.  
Example 1: (Printing the shape of the multidimensional array)
Python3
import numpy as npy # creating a 2-d arrayarr1 = npy.array([[1, 3, 5, 7], [2, 4, 6, 8]]) # creating a 3-d arrayarr2 = npy.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # printing the shape of arrays# first element of tuple gives# dimension of arrays second# element of tuple gives number# of element of each dimensionprint(arr1.shape)print(arr2.shape)
Output: 
(2, 4)
(2, 2,2)
The example above returns (2, 4) and (2,2,2) which means that the arr1 has 2 dimensions and each dimension has 4 elements. Similarly, arr2 has 3 dimensions and each dimension has 2 rows and 2 columns.
Example 2: (Creating an array using ndmin using a vector with values 2,4,6,8,10 and verifying the value of last dimension) 
python3
import numpy as npy # creating an array of 6 dimension# using ndimarr = npy.array([2, 4, 6, 8, 10], ndmin=6) # printing arrayprint(arr) # verifying the value of last dimension# as 5print('shape of an array :', arr.shape)
Output: 
[[[[[[ 2  4  6  8 10]]]]]]
shape of an array : (1, 1, 1, 1, 1, 5)
In the above example, we verified the last value of dimension as 5.
ashupadhyay99
Python numpy-arrayCreation
Python-numpy
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
How to bind events on dynamically created elements using jQuery?

To bind events on dynamically created elements, you need to load dynamically. You can try to run the following code to learn how to bind events on dynamically created elements. Here, we will generate a new list item on button click.
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
      $("ul").append("<li>new item <a href='javascript:void(0);' class='del'>&times;</a></li>");
      });
 
    $(document).on("click", "a.del" , function() {
        $(this).parent().remove();
    });
});
</script>
</head>
<body>
    <button>Add</button>
    <p>Click the above button to dynamically add new list items. You can remove it later.</p>
    <ul>
        <li>item</li>
    </ul>
</body>
</html>
Find average of each array within an array JavaScript

We are required to write a function getAverage() that accepts an array of arrays of numbers and
we are required to return a new array of numbers that contains the average of corresponding
subarrays.
Let’s write the code for this. We will map over the original array, reducing the subarray to their
averages like this −
const arr = [[1,54,65,432,7,43,43, 54], [2,3], [4,5,6,7]];
const secondArr = [[545,65,5,7], [0,0,0,0], []];
const getAverage = (arr) => {
   const averageArray = arr.map(sub => {
      const { length } = sub;
      return sub.reduce((acc, val) => acc + (val/length), 0);
   });
   return averageArray;
}
console.log(getAverage(arr));
console.log(getAverage(secondArr));
The output in the console will be −
[ 87.375, 2.5, 5.5 ]
[ 155.5, 0, 0 ]
How to define attributes of a class in Python?

Everything, almost everything in Python is an object. Every object has attributes and methods. Thus attributes are very fundamental in Python. A class is a construct which is a collection of similar objects. A class also has attributes. There will be a difference between the class attributes and instance attributes. The class attributes are shared by the instances of the class but it not true vice versa.
We can get a list of the attributes of an object using the built-in “dir” function. For example −
>>> s = 'abc'
>>> len(dir(s))
71
>>> dir(s)[:5]
['__add__', '__class__', '__contains__', '__delattr__', '__doc__']
>>> i = 123
>>> len(dir(i))
64
>>> dir(i)[:5]
['__abs__', '__add__', '__and__', '__class__', '__cmp__']
>>> t = (1,2,3)
>>> len(dir(t))
32
>>> dir(t)[:5]
['__add__', '__class__', '__contains__', '__delattr__', '__doc__']
As we can see, even the basic data types in Python have many attributes. We can see the first five attributes by limiting the output from “dir”;
Java continue Keyword

❮ Java Keywords

Skip the iteration if the variable i is 4, but continue with the next iteration:
for (int i = 0; i < 10; i++) {
  if (i == 4) {
    continue;
  }
  System.out.println(i);
}


Try it Yourself »

The continue keyword is used to end the current iteration in a for loop (or a while loop), and continues to the next iteration.
Use the continue keyword in a while loop
int i = 0;while (i < 10) {
  if (i == 4) {
    i++;
    continue;
  }
  System.out.println(i);
  i++;
}


Try it Yourself »

Use the break 
keyword to break out of a loop.
Read more about for loops in our Java For Loops Tutorial.
Read more about while loops in our Java While Loops Tutorial.
Read more about break and continue in our Java Break Tutorial.

❮ Java Keywords

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

The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.
In this chapter, we will go through the following PHP array sort functions:
sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the value
krsort() - sort associative arrays in descending order, according to the key
The following example sorts the elements of the $cars array in ascending alphabetical order:
The following example sorts the elements of the $numbers array in ascending 
numerical order:
The following example sorts the elements of the $cars array in descending alphabetical order:
The following example sorts the elements of the $numbers array in descending 
numerical order:
The following example sorts an associative array in ascending order, 
according to the value:
The following example sorts an associative array in ascending order, 
according to the key:
The following example sorts an associative array in descending order, 
according to the value:
The following example sorts an associative array in descending order, 
according to the key:
For a complete reference of all array functions, go to our complete PHP Array Reference.
The reference contains a brief description, and examples of use, for each function!
Use the correct array method to sort the $colors array alphabetically.
$colors = array("red", "green", "blue", "yellow"); 
;

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