code-rag-bench/online-tutorials huggingface dataset:
Assembly - Memory Management

The sys_brk() system call is provided by the kernel, to allocate memory without the need of moving it later. This call allocates memory right behind the application image in the memory. This system function allows you to set the highest available address in the data section.
This system call takes one parameter, which is the highest memory address needed to be set. This value is stored in the EBX register.
In case of any error, sys_brk() returns -1 or returns the negative error code itself. The following example demonstrates dynamic memory allocation.
The following program allocates 16kb of memory using the sys_brk() system call −
section	.text
   global _start         ;must be declared for using gcc
	
_start:	                 ;tell linker entry point

   mov	eax, 45		 ;sys_brk
   xor	ebx, ebx
   int	80h

   add	eax, 16384	 ;number of bytes to be reserved
   mov	ebx, eax
   mov	eax, 45		 ;sys_brk
   int	80h
	
   cmp	eax, 0
   jl	exit	;exit, if error 
   mov	edi, eax	 ;EDI = highest available address
   sub	edi, 4		 ;pointing to the last DWORD  
   mov	ecx, 4096	 ;number of DWORDs allocated
   xor	eax, eax	 ;clear eax
   std			 ;backward
   rep	stosd            ;repete for entire allocated area
   cld			 ;put DF flag to normal state
	
   mov	eax, 4
   mov	ebx, 1
   mov	ecx, msg
   mov	edx, len
   int	80h		 ;print a message

exit:
   mov	eax, 1
   xor	ebx, ebx
   int	80h
	
section	.data
msg    	db	"Allocated 16 kb of memory!", 10
len     equ	$ - msg
When the above code is compiled and executed, it produces the following result −
Allocated 16 kb of memory!


    46 Lectures 
     2 hours 

 Frahaan Hussain

    23 Lectures 
     12 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
strcat() vs strncat() in C++

Both strcat() and strncat() are predefined string functions in C++. Details about these are given as follows.
This function is used for concatenation. It appends a copy of the source string at the end of the destination string and returns a pointer to the destination string. The syntax of strcat() is given as follows.
char *strcat(char *dest, const char *src)
A program that demonstrates strcat() is given as follows.
 Live Demo
#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char str1[20] = "Mangoes are ";
   char str2[20] = "yellow";
   strcat(str1, str2);
   cout << "The concatenated string is "<<str1;
   return 0;
}
The concatenated string is Mangoes are yellow
In the above program, the two strings str1 and str2 are defined. strcat() appends the contents of str2 at the end of str1 and the concatenated string is displayed using cout. This is given as follows.
char str1[20] = "Mangoes are ";
char str2[20] = "yellow";
strcat(str1, str2);
cout << "The concatenated string is "<<str1;
This function is also used for concatenation like strcat(). It appends the specified number of characters from the source string at the end of the destination string and returns a pointer to the destination string. The syntax of strncat() is given as follows.
char * strncat ( char * dest, const char * src, size_t num );
A program that demonstrates strcat() is given as follows.
 Live Demo
#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char str1[20] = "Mangoes are ";
   char str2[20] = "yellow";
   strncat(str1, str2, 4);
   cout <<"The concatenated string is "<<str1;
   return 0;
}
Output
The concatenated string is Mangoes are yell
In the above program, the two strings str1 and str2 are defined. strncat() appends the contents of str2 at the end of str1 till four characters and the concatenated string is displayed using cout. This is given as follows.
char str1[20] = "Mangoes are ";
char str2[20] = "yellow";
strncat(str1, str2, 4);
cout << "The concatenated string is "<<str1;
Function Overloading in C++ - GeeksforGeeks

17 Jun, 2021
Function overloading is a feature of object oriented programming where two or more functions can have the same name but different parameters.
When a function name is overloaded with different jobs it is called Function Overloading.
In Function Overloading “Function” name should be the same and the arguments should be different.
Function overloading can be considered as an example of polymorphism feature in C++.
Following is a simple C++ example to demonstrate function overloading.
CPP
#include <iostream>using namespace std; void print(int i) {  cout << " Here is int " << i << endl;}void print(double  f) {  cout << " Here is float " << f << endl;}void print(char const *c) {  cout << " Here is char* " << c << endl;} int main() {  print(10);  print(10.10);  print("ten");  return 0;}
Output:
Here is int 10 
Here is float 10.1 
Here is char* ten
Exact match:- (Function name and Parameter)
If a not exact match is found:–
               ->Char, Unsigned char, and short are promoted to an int.
               ->Float is promoted to double
If no match found:
               ->C++ tries to find a match through the standard conversion.
ELSE ERROR 
Function overloading and return typeFunctions that cannot be overloaded in C++Function overloading and const keywordFunction Overloading vs Function Overriding in C++
Function overloading and return type
Functions that cannot be overloaded in C++
Function overloading and const keyword
Function Overloading vs Function Overriding in C++
Recent articles on function overloading in C++Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
raHUL GUPTA 23
devilchandra
utkarshgupta04092003
CPP-Functions
cpp-overloading
Functions
C++
School Programming
Functions
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Socket Programming in C/C++
Python Dictionary
Reverse a string in Java
Interfaces in Java
Overriding in Java
Different ways of Reading a text file in Java
Python – Triangular Distribution in Statistics

10 Jan, 2020
scipy.stats.triang () is a triangular continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution.
Parameters :
q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : triangular continuous random variable
Code #1 : Creating triangular continuous random variable
# importing library  from scipy.stats import triang     numargs = triang .numargs a = 0.158rv = triang (a)     print ("RV : \n", rv)  
Output :
RV : 
 scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D843A9C8

Code #2 : triangular continuous variates and probability distribution
import numpy as np quantile = np.arange (0.01, 1, 0.1)   # Random Variates R = triang .rvs(0.158, size = 10) print ("Random Variates : \n", R)   # PDF x = np.linspace(0, 5, 10) R = triang.pdf(x, 1)print ("\nProbability Distribution : \n", R) 
Output :
Random Variates : 
 [0.83667827 0.23988855 0.17637281 0.28973544 0.26458145 0.3554613
 0.09420123 0.20821321 0.3357951  0.1249713 ]

Probability Distribution : 
 [0.         1.11111111 0.         0.         0.         0.
 0.         0.         0.         0.        ]

Code #3 : Graphical Representation.
import numpy as np import matplotlib.pyplot as plt      distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution)      plot = plt.plot(distribution, rv.pdf(distribution)) 
Output :
Distribution : 
 [0.         0.02040816 0.04081633 0.06122449 0.08163265 0.10204082
 0.12244898 0.14285714 0.16326531 0.18367347 0.20408163 0.2244898
 0.24489796 0.26530612 0.28571429 0.30612245 0.32653061 0.34693878
 0.36734694 0.3877551  0.40816327 0.42857143 0.44897959 0.46938776
 0.48979592 0.51020408 0.53061224 0.55102041 0.57142857 0.59183673
 0.6122449  0.63265306 0.65306122 0.67346939 0.69387755 0.71428571
 0.73469388 0.75510204 0.7755102  0.79591837 0.81632653 0.83673469
 0.85714286 0.87755102 0.89795918 0.91836735 0.93877551 0.95918367
 0.97959184 1.        ]
  
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as plt import numpy as np      x = np.linspace(0, 5, 100)      # Varying positional arguments y1 = triang  .pdf(x, 1, 3, 5) y2 = triang  .pdf(x, 1, 4, 4) plt.plot(x, y1, "*", x, y2, "r--") 
Output :
Python scipy-stats-functions
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Enumeration in Java

The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.
This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes such as Vector and Properties, is used by several other API classes, and is currently in widespread use in application code.
The methods declared by Enumeration are summarized in the following table −
Following is an example showing usage of Enumeration.
 Live Demo
import java.util.Vector;
import java.util.Enumeration;

public class EnumerationTester {

   public static void main(String args[]) {
      Enumeration days;
      Vector dayNames = new Vector();

      dayNames.add("Sunday");
      dayNames.add("Monday");
      dayNames.add("Tuesday");
      dayNames.add("Wednesday");
      dayNames.add("Thursday");
      dayNames.add("Friday");
      dayNames.add("Saturday");
      days = dayNames.elements();

      while (days.hasMoreElements()) {
         System.out.println(days.nextElement());
      }
   }
}
This will produce the following result −
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Return type deduction in C++14 with Examples

28 Jan, 2021
In this article, we will discuss Return Type Deduction in C++14. Using an auto return type in C++14, the compiler will attempt to deduce the return type automatically.
Program 1:
C++14
// C++14 program to illustrate the// return type deduction#include <iostream>using namespace std;  // Function to multiply the two// numbers a and bauto multiply(int a, int b){      // Return the product    return a * b;}  // Driver Codeint main(){    int a = 4, b = 5;      // Function Call    cout << multiply(a, b);      return 0;}
20

Explanation: In the above program, the multiply(int a, int b) function the compiler will perform the multiplication. As the passed parameters 4 and 5, the compiler will return 20 and since its data type is an integer, the compiler will deduce the type as integer automatically and will return 20 as an integer.
Program 2:
C++14
// C++ 14 program to illustrate the// return type deduction#include <iostream>using namespace std;  // Function to increment the// value of aauto increase(int& a){    // Increment a    a++;      // Return the updated value    return a;}  // Driver Codeint main(){    int b = 10;      // Function Call    int& c = increase(b);      // Print the value b and c    cout << b << c;    return 0;}
Output:
Explanation: As it can be seen that in the above program compiler is showing an error. This is because in the function increase(int &a), the compiler will return 11 and since its type is an integer, the compiler will deduce its type as integer and return it, but in main, we are assigning an integer value to an integer reference variable c, that’s why it was showing error.
Now, the above problem can be fixed in two ways:
C++14
// C++14 program to illustrate return// type deduction using auto&#include <iostream>using namespace std;  // Function to increment the value// of a and return the updated valueauto& increase(int& a){    a++;    return a;}  // Driver Codeint main(){    int b = 10;      // Function Call    int& c = increase(b);    cout << b << '\n'         << c;      return 0;}
11
11

C++14
// C++14 program to illustrate return// type deduction using decltype()#include <iostream>using namespace std;  // Function that increments the value// of a and return the updated valuedecltype(auto) increase(int& a){    a++;    return a;}  // Driver Codeint main(){    int b = 10;      // Function Call    int& c = increase(b);      cout << b << '\n'         << c;      return 0;}
11
11

Technical Scripter 2020
C++
C++ Programs
Technical Scripter
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++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
PHP | foreach Loop

25 Sep, 2019
The foreach construct provides the easiest way to iterate the array elements. It works on array and objects both. The foreach loop though iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively. It allocates temporary memory for index iterations which makes the overall system to redundant its performance in terms of memory allocation.
Syntax:
foreach( $array as $element ) {
    // PHP Code to be executed
}
or
foreach( $array as $key => $element) {
    // PHP Code to be executed
}
Below programs illustrate the foreach loop in PHP:
Program 1: PHP program to print the array elements using foreach loop.
<?php  // Declare an array$arr = array("green", "blue", "pink", "white");   // Loop through the array elementsforeach ($arr as $element) {    echo "$element ";}  ?>
green blue pink white

Program 2: PHP program to print the associative array elements using foreach loop.
<?php $employee = array(     "name" => "Robert",     "email" => "robert112233@mail.com",     "age" => 18,     "gender" => "male"  );   // Loop through employee array foreach($employee as $key => $element) {     echo $key . ": " . $element . "<br>"; }   ?> 
name: Robertemail: robert112233@mail.comage: 18gender: male

Picked
PHP
PHP Programs
Technical Scripter
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Microsoft Codess Interview Experience

07 Sep, 2020
In the month of March, I gave an online competition called Codess.  It had some basic questions on DSA(linked list, queues, stacks, heaps). These were MCQs so you should be clear with basic concepts in DSA.
Engage-2020: When I cleared the Codess, I got into Engage 2020 which is a mentoring program organized by Microsoft. It had two projects from which we had to complete one project.
I had Tic-Tac-Toe with AI agents. In this, we used JavaScript to use the recursive functions. You can refer to the code from the link given below.
https://github.com/nitya2602/tic-tac-toe. 
We had a great experience doing the project under our mentor allotted by Microsoft.
Interview: Then, we got our interview scheduled.
It was a half an hour interview. He first asked me to introduce myself, so I told him about my few projects so we discussed one of them for 10 min. Then rest of 20 min he asked a coding question:
Write to Rearrange characters in a string such that no two adjacents are the same.
Write to Rearrange characters in a string such that no two adjacents are the same.
Tips: Try to solve as many questions as possible for the interview and be interactive with the interviewer.
Microsoft
Interview Experiences
Microsoft
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1
Amazon Interview Experience SDE-2 (3 Years Experienced)
TCS Ninja Interview Experience (2020 batch)
Samsung RnD Coding Round Questions
Write It Up: Share Your Interview Experiences
Tiger Analytics Interview Experience for Data Analyst (On-Campus)
Nagarro Interview Experience
Amazon Interview Experience for SDE-1
Python – assertGreater() function in unittest

24 Oct, 2020
assertGreater() in Python is an unittest library function that is used in unit testing to check whether the first given value is greater than the second value or not. This function will take three parameters as input and return a boolean value depending upon the assert condition.
This function check that if the first given value is greater than the second value and returns true if it is so, else returns false if the first value is not greater than the second value.
Syntax: assertGreater(first, second, message=None)
Parameters: assertGreater() accept three parameters which are listed below with explanation:
first: first input value (integer)
second:  second input value (integer)
message: a string sentence as a message which got displayed when the test case got failed.
Listed below is an example illustrating the positive and negative test case for a given assert function:
Example 1:
Python3
# test suiteimport unittest  class TestStringMethods(unittest.TestCase):        # negative test function to test if values1     # is greater than value2    def test_negativeForGreater(self):        first = 4        second = 5                  # error message in case if test case got failed        message = "first value is not greater that second value."                  # assert function() to check if values1 is         # greater than value2        self.assertGreater(first, second, message)  if __name__ == '__main__':    unittest.main()
Output:
F======================================================================FAIL: test_negativeForGreater (__main__.TestStringMethods)———————————————————————-Traceback (most recent call last): File “p1.py”, line 13, in test_negativeForGreater   self.assertGreater(first, second, message)AssertionError: 4 not greater than 5 : first value is not greater that second value.
———————————————————————-Ran 1 test in 0.000s
FAILED (failures=1)
Example 2:
Python
# test suiteimport unittest  class TestStringMethods(unittest.TestCase):        # positive test function to test if values    # are almost equal with place    def test_positiveForGreater(self):        first = 4        second = 3                  # error message in case if test case got failed        message = "first value is not greater that second value."                  # assert function() to check if values1 is        # greater than value2        self.assertGreater(first, second, message)    if __name__ == '__main__':    unittest.main()
Output:
.———————————————————————-Ran 1 test in 0.000s
OK
Python unittest-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
p5.js | stop() Function

21 Nov, 2021
The stop() function is an inbuilt function in p5.js library. This function is used to stop the audio on the web which is playing or gonna played. After just play function if you use this function without parameter then the output will be NULL you can not hear any audio.Syntax:  
stop( startTime )
Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file.Parameter: This function accept a single parameter as mentioned above and described below.  
startTime: This parameter holds an integer number as seconds that defines the scheduled playback and it is an optional parameter.
Below example illustrates the p5.stop() function in JavaScript: Example: 
javascript
var sound; function preload() {     // Initialize sound    sound = loadSound("pfivesound.mp3");} function setup() {     // Playing the preloaded sound    sound.play();    //stopping the played sound after 5 seconds    sound.stop(5);}
Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Supported Browsers: The browsers are supported by p5.js stop() function are listed below: 
Google Chrome
Internet Explorer
Firefox
Safari
Opera
rs1686740
JavaScript-p5.js
JavaScript
Web Technologies
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
C# program to reverse a string

Our sample string is −
myStr = "Tom";
To reverse the string, firstly find the length of the string −
// find string length
int len;
len = myStr.Length - 1;
Now, use a while loop until the length is greater than 0 −
while (len >= 0) {
   rev = rev + myStr[len];
   len--;
}
You can try to run the following code to reverse a string in C#.
Live Demo
using System;
class Demo {
   static void Main() {
      string myStr, rev;
      myStr = "Tom";
      rev ="";
      Console.WriteLine("String is {0}", myStr);
      // find string length
      int len;
      len = myStr.Length - 1;
      while (len >= 0) {
         rev = rev + myStr[len];
         len--;
      }
      Console.WriteLine("Reversed String is {0}", rev);
      Console.ReadLine();
   }
}
String is Tom
Reversed String is moT
Convert matrix to list in R - GeeksforGeeks

09 May, 2021
In this article, we will discuss how to convert a given matrix to a List in R Programming Language.
The as.list() is an inbuilt function that takes an R language object as an argument and converts the object into a list. We have used this function to convert our matrix to a list. These objects can be Vectors, Matrices, Factors, and data frames. By default, as.list() converts the matrix to a list of lists in column-major order. 
Therefore, we have to use unlist() function to convert the list of lists to a single list. unlist() function in R Language is used to convert a list of lists to a single list, by preserving all the components.
Syntax: 
unlist(as.list(matrix))
Example:
R
mat = matrix(1:12,nrow=3, ncol=4)  print("Sample matrix:")print(mat)  print("Matrix into a single list")unlist(as.list(mat))
Output:
[1] “Sample matrix:”
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
[1] “Matrix into a single list”
 [1]  1  2  3  4  5  6  7  8  9 10 11 12
For this approach we first have to find the transpose of the matrix In the code below, we have used t() function to calculate the transpose of our sample matrix. Due to which our matrix gets converted to a list in a Row-Major order.
The rest of the process is the same as above.
Syntax: 
unlist( as.list( t(mat) ))
Example:
R
mat = matrix(1:12,nrow=3, ncol=4)  print("Sample matrix:")print(mat)  print("Result after conversion")unlist(as.list(t(mat)))
Output:
[1] “Sample matrix:”
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
[1] “Result after conversion”
 [1]  1  4  7 10  2  5  8 11  3  6  9 12
Picked
R List-Programs
R Matrix-Programs
R-List
R-Matrix
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
HTTP headers | Origin - GeeksforGeeks

31 Oct, 2019
The Origin HTTP Header is a response HTTP header that indicates the security contexts that initiates an HTTP request without indicating the path information. The Origin header is added by the browser and can not be controlled by the user.
Syntax:
Origin: <scheme> "://" <hostname> ":" <port> 
Directives:
<scheme>:This is usually the HTTP or HTTPS protocol that is used.
This is usually the HTTP or HTTPS protocol that is used.
<hostname>:This is the IP or domain name of the server.
This is the IP or domain name of the server.
<port>:This is an optional directive that tells Transmission Control Protocol port number of the server. The default port is implied if it is not specified.
This is an optional directive that tells Transmission Control Protocol port number of the server. The default port is implied if it is not specified.
Examples:
Origin: null
This means that there is no origin for the service requested.
Origin: https://www.geeksforgeeks.org
This means that the origin if the service requested exists and has https as the scheme and www.geeksforgeeks.org as the hostname.
Supported Browsers The following browsers are compatible with HTTP Origin:
Google Chrome
Internet Explorer
Opera
Firefox
Safari
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Insert Form Data into Database using PHP ?
How to redirect to another page in ReactJS ?
Set the value of an input field in JavaScript
How to execute PHP code using command line ?
Get the last index of a particular element in an ArrayList in Java

The last index of a particular element in an ArrayList can be obtained by using the method java.util.ArrayList.lastIndexOf(). This method returns the index of the last occurance of the element that is specified. If the element is not available in the ArrayList, then this method returns -1.
A program that demonstrates this is given as follows.
 Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List aList = new ArrayList();
      aList.add("Orange");
      aList.add("Apple");
      aList.add("Peach");
      aList.add("Orange");
      aList.add("Mango");
      aList.add("Peach");
      System.out.println("The last index of the element Orange in ArrayList is: " +
      aList.lastIndexOf("Orange"));
   }
}
The output of the above program is as follows
The last index of the element Orange in ArrayList is: 3
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. The method ArrayList.lastIndexOf() is used to find the last index of element “Orange” and that is displayed. A code snippet which demonstrates this is as follows
List aList = new ArrayList();
aList.add("Orange");
aList.add("Apple");
aList.add("Peach");
aList.add("Orange");
aList.add("Mango");
aList.add("Peach");
System.out.println("The last index of the element Orange in ArrayList is: " + aList.lastIndexOf("Orange"));
WCF - Self Hosting

Here, the WCF service is hosted in a console application. Given below is the process with suitable steps in a sequential manner that explains the entire process.
Step 1 − First, let's create the Service contract and its implementation. Create a console application and name it as MyCalculatorService. This is a simple service to return the addition of two numbers.
Step 2 − Now, right click on the References in the Solution Explorer and click Add References. The following window opens; add System.ServiceModel reference to the project.
Step 3 − Create an ISimpleCalculator interface, Add ServiceContract and OperationContract attribute to the class and function as shown below. You will know more about these contracts in the later session. These contracts will expose the method to the outside world for using this service.
Step 4 − The code behind this file is as follows −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace MyCalculatorWCFService {
   [ServiceContract()]
   Public interface ISimpleCalculator {
      [OperationContract()]
      int Add(int num1, int num2);
   }
}
Step 5 − MyCalculatorService is the implementation class for IMyCalculatorService interface as shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyCalculatorWCFService {
   Class SimpleCalculator : ISimpleCalculator {
      Public int Add(int num1, int num2) {
         return num1 + num2;
      }
   }
}
Step 6 − Now, we are ready with the service. Let's go for implementing the hosting process. Create a new console application and name it as 'MyCalculatorWCFServiceHost'.
Step 7 − Add the reference of system.servicemodel and the project MyCalculatorWCFService.
The code behind this is as follows −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyCalculatorWCFService;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace MyCalculatorWCFServiceHost {
   class Program {
      static void Main(string[] args) {
         //Create a URI to serve as the base address
         UrihttpUrl = newUri("http://localhost:8090/MyCalculatorWCFService/SimpleCalculator");
         
         //Create ServiceHost
         ServiceHost host = newServiceHost(typeof(MyCalculatorWCFService.ISimpleCalculator), httpUrl);
         
         //Add a service endpoint
         host.AddServiceEndpoint(typeof(MyCalculatorWCFService.ISimpleCal culator), newWSHttpBinding(), "");
         
         //Enable metadata exchange
         ServiceMetadataBehaviorsmb = newServiceMetadataBehavior();
         smb.HttpGetEnabled = true;
         host.Description.Behaviors.Add(smb);

         //Start the Service
         host.Open();
         Console.WriteLine("Service is host at " + DateTime.Now.ToString());
         Console.WriteLine("Host is running... Press  key to stop");
         Console.ReadLine();
      }
   }
}

    23 Lectures 
     1.5 hours 

 Anadi Sharma

    9 Lectures 
     48 mins

 TELCOMA Global
 Print
 Add Notes
 Bookmark this page
What is the difference between literal and constant in C++?

A literal is a value that is expressed as itself. For example, the number 25 or the string "Hello World" are both literals.
A constant is a data type that substitutes a literal. Constants are used when a specific, unchanging value is used various times during the program. For example, if you have a constant named PI that you'll be using at various places in your program to find the area, circumference, etc of a circle, this is a constant as you'll be reusing its value. But when you'll be declaring it as −
const float PI = 3.141;
The 3.141 is a literal that you're using. It doesn't have any memory address of its own and just sits in the source code.
AWK - Arrays

AWK has associative arrays and one of the best thing about it is – the indexes need not to be continuous set of number; you can use either string or number as an array index. Also, there is no need to declare the size of an array in advance – arrays can expand/shrink at runtime.
Its syntax is as follows −
array_name[index] = value

Where array_name is the name of array, index is the array index, and value is any value assigning to the element of the array.
To gain more insight on array, let us create and access the elements of an array.
[jerry]$ awk 'BEGIN {
   fruits["mango"] = "yellow";
   fruits["orange"] = "orange"
   print fruits["orange"] "\n" fruits["mango"]
}'
On executing this code, you get the following result −
orange
yellow

In the above example, we declare the array as fruits whose index is fruit name and the value is the color of the fruit. To access array elements, we use array_name[index] format.
For insertion, we used assignment operator. Similarly, we can use delete statement to remove an element from the array. The syntax of delete statement is as follows −
delete array_name[index]

The following example deletes the element orange. Hence the command does not show any output.
[jerry]$ awk 'BEGIN {
   fruits["mango"] = "yellow";
   fruits["orange"] = "orange";
   delete fruits["orange"];
   print fruits["orange"]
}'
AWK only supports one-dimensional arrays. But you can easily simulate a multi-dimensional array using the one-dimensional array itself.
For instance, given below is a 3x3 two-dimensional array −
100   200   300
400   500   600
700   800   900

In the above example, array[0][0] stores 100, array[0][1] stores 200, and so on. To store 100 at array location [0][0], we can use the following syntax −
array["0,0"] = 100

Though we gave 0,0 as index, these are not two indexes. In reality, it is just one index with the string 0,0.
The following example simulates a 2-D array −
[jerry]$ awk 'BEGIN {
   array["0,0"] = 100;
   array["0,1"] = 200;
   array["0,2"] = 300;
   array["1,0"] = 400;
   array["1,1"] = 500;
   array["1,2"] = 600;

   # print array elements
   print "array[0,0] = " array["0,0"];
   print "array[0,1] = " array["0,1"];
   print "array[0,2] = " array["0,2"];
   print "array[1,0] = " array["1,0"];
   print "array[1,1] = " array["1,1"];
   print "array[1,2] = " array["1,2"];
}'
On executing this code, you get the following result −
array[0,0] = 100
array[0,1] = 200
array[0,2] = 300
array[1,0] = 400
array[1,1] = 500
array[1,2] = 600

You can also perform a variety of operations on an array such as sorting its elements/indexes. For that purpose, you can use assort and asorti functions
 Print
 Add Notes
 Bookmark this page
Python PIL | ImageDraw.Draw.chord() - GeeksforGeeks

02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.chord() Same as arc(), but connects the end points with a straight line.
Syntax: PIL.ImageDraw.Draw.chord(xy, start, end, fill=None, outline=None)
Parameters:xy – Four points to define the bounding box. Sequence of [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].outline – Color to use for the outline.fill – Color to use for the fill.
Returns: An Image.
     # importing image object from PILimport mathfrom PIL import Image, ImageDraw  w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)]  # creating new Image objectimg = Image.new("RGB", (w, h))  # create chord imageimg1 = ImageDraw.Draw(img)  img1.chord(shape, start = 30, end = 200, fill ="# 800080", outline ="red")img.show()
Output:
Another Example: Here we use different colour for filling.
     # importing image object from PILimport mathfrom PIL import Image, ImageDraw  w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)]  # creating new Image objectimg = Image.new("RGB", (w, h))  # create chord imageimg1 = ImageDraw.Draw(img)  img1.chord(shape, start = 30, end = 200, fill ="# ffff33", outline ="blue")img.show()
Output:
Python-pil
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Get closest number out of array JavaScript

Let’s say, we are required to write a function that takes in an array of numbers and a number as
input and returns the closest value that exists in the array to that number.
For example −
closest([45,61,53,98,54,12,69,21], 67); //69
closest([45,61,53,98,54,12,69,21], 64); //61
So, let’s write the code for it.
We will use the Array.prototype.reduce() method to calculate the differences and return the
smallest difference from the reduce function and the sum of that smallest difference and the
number we were searching for will be our required number.
Here is the code for this −
const closest = (arr, num) => {
   return arr.reduce((acc, val) => {
      if(Math.abs(val - num) < Math.abs(acc)){
         return val - num;
      }else{
         return acc;
      }
   }, Infinity) + num;
}
console.log(closest([45,61,53,98,54,12,69,21], 67));
console.log(closest([45,61,53,98,54,12,69,21], 64));
The output of this code in the console will be −
69
61
std::basic_string::at in C++ - GeeksforGeeks

07 Jul, 2017
Returns a reference to the character at the specified location pos. The function automatically checks whether pos is the valid position of a character in the string (i.e., whether pos is less than the string length), throwing an out_of_range exception if it is not.
Syntax:
reference at (size_type pos);
const_reference at (size_type pos) const;
Parameters :
pos - position of the character to return
Return value :
Reference to the requested character
Exceptions :
Throws std::out_of_range if pos >= size().
// CPP program to access a character through// std::basic_string::at #include <stdexcept>#include <iostream>  int main(){    // String with valid indices from 0 to 2    std::string str = "abc";      // Printing size of string    std::cout << "string size = " << str.size() << '\n';      // Accessing out of bounds index    try     {        str.at(4) = 't';    }          // If error is generated, it is caught    catch (std::out_of_range const& error)     {        std::cout << error.what() << '\n';    }}
Output:
string size = 3
basic_string::at: __n (which is 4) >= this->size() (which is 3)

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-strings-library
STL
C++
Misc
Misc
Misc
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Bitwise Operators in C/C++
Virtual Function in C++
Top 10 algorithms in Interview Questions
vector::push_back() and vector::pop_back() in C++ STL
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions?
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
numpy.rate() in Python - GeeksforGeeks

29 Nov, 2018
numpy.pmt(rate, nper, pv, fv, when = ‘end’) : This financial function helps user to compute rate of interest per period.
Parameters :nper : [scalar or (M, )array] total compounding periodspmt : [scalar or (M, )array] Paymentfv : [scalar or (M, )array] Future valuepv : [scalar or (M, )array] present valuewhen : at the beginning (when = {‘begin’, 1}) or the end (when = {‘end’, 0}) of each period. Default is {‘end’, 0}
Return : Rate of interest per period.
Equation being solved :
fv + pv*(1+rate)**nper + pmt*(1 + rate*when)/rate*((1 + rate)**nper – 1) == 0
or when rate == 0fv + pv + pmt * nper == 0
Code:
# Python program explaining # rate() function import numpy as np     #                 nper  pmt   pv   fv Solution = np.rate(6, 10000, 500, 200)   print("Solution= rate ", Solution) 
Output:
Solution= rate  -2.024705182882783
Python numpy-Financial Functions
Python-numpy
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
HTML form Tag - GeeksforGeeks

17 Mar, 2022
Form Tag
Forms are required to take input from the user who visits the website. This form is used basically for the registration process, logging into your profile on a website or to create your profile on a website, etc ... The information that is collected from the form is -1. Name 2.Email Addresses etc. Now the form will take input from the form and post that data in backend applications (like PHP). So the backend application will process the data which is received by them. There are various form elements that we can use like text fields, text area, drop-down list, select, checkboxes, radio, etc.
Syntax: 
<form> Form Content... </form>
Attributes: There are many attributes that are associated with the <form> tag. Some of them are listed below: 
Action Attribute: -This is used to send the data to the server after the submission of the form.
Method: -This is used to upload the data by using two methods that are Get and Post. Get Method: -It has a limited length of characters of URL. -we should not use get to send some sensitive data. -This method is better for non-secure data. Post Method: -1. It has no size limitations 2. The submission of the form with the method post, can not be bookmarked.
Enctype attribute: -This attribute is used to specify that how a browser decodes the data before it sends it to the server .so the values of this attribute are: -1.application/x-www-form-urlencoded − It is the standard method most forms used 2.multipart/form-data -it is used when you have something to upload like files of images, word files, etc.
Example of the form tag:-
HTML
<!DOCTYPE html> <html> <body>    <h1>form tag </h1>    <!--Here we have not used the action attribute    as we are not submitting the data to the server-->    <form>      <label for="fname">FirstName</label><!-- Here i have used label to    define the label for input -->    <input type="text" name="fname" placeholder="enter your name" required><!--It    defines a text field by using input tag  -->        <label for="lname">LastName</label>    <input type="text" name="lname" placeholder="enter your name" required>    </form>    </body> </html>
Output:
Supported Browsers: 
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
codingbeast12
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
How to position a div at the bottom of its container using CSS?
How to use strconv.Quote() Function in Golang? - GeeksforGeeks

05 May, 2020
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides a Quote() function which is used to find a double-quoted Go string literal representing str and the returned string uses Go escape sequences (\t, \n, \xFF, \u0100) to control characters and non-printable characters defined by IsPrint. To access Quote() function you need to import strconv Package in your program.
Syntax:
func Quote(str string) string
Parameter: This function takes one parameter of string type, i.e., str.
Return Value: This function returns a double-quoted Go string literal which represents str.
Example 1:
// Golang program to illustrate strconv.Quote() Functionpackage main  import (    "fmt"    "strconv")  func main() {    // Finding a double-quoted Go    // string literal representing str    // Using Quote() function    str := strconv.Quote(`" Hello      Welcome to GeeksforGeeks "`)    fmt.Println(str)  }
Output:
"\" Hello \n     Welcome to GeeksforGeeks \""
Example 2:
// Golang program to illustrate// strconv.Quote() Functionpackage main  import (    "fmt"    "strconv")  func main() {      // Finding a double-quoted Go string literal    // Using Quote() function    val1 := strconv.Quote(`"Hello! GFG   "`)    fmt.Println("Result 1: ", val1)    fmt.Println("Length 1: ", len(val1))      val2 := strconv.Quote(`"Welcome!        GeeksforGeeks"`)    fmt.Println("Result 2: ", val2)    fmt.Println("Length 2: ", len(val2))  }
Output:
Result 1:  "\"Hello! GFG   \""
Length 1:  19
Result 2:  "\"Welcome!\n        GeeksforGeeks\""
Length 2:  37

Golang-strconv
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
How to Split a String in Golang?
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Slices in Golang
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
How to Trim a String in Golang?
Java | Exception Handling | Question 1 - GeeksforGeeks

08 Jul, 2021
Predict the output of following Java program
class Main {   public static void main(String args[]) {      try {         throw 10;      }      catch(int e) {         System.out.println("Got the  Exception " + e);      }  }}
(A) Got the Exception 10(B) Got the Exception 0(C) Compiler ErrorAnswer: (C)Explanation: In Java only throwable objects (Throwable objects are instances of any subclass of the Throwable class) can be thrown as exception. So basic data type cannot be thrown at all.
Following are errors in the above program
Main.java:4: error: incompatible types
         throw 10;
               ^
  required: Throwable
  found:    int
Main.java:6: error: unexpected type
      catch(int e) {
            ^
  required: class
  found:    int
2 errors
Quiz of this Question
vkshaw1997
Exception Handling
Java-Exception Handling
Java Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java | Constructors | Question 5
Java | Functions | Question 1
Java | final keyword | Question 1
Java | Inheritance | Question 8
Java | Arrays | Question 1
Java | Operators | Question 1
Java | Operators | Question 3
Java | Inheritance | Question 7
Java | Functions | Question 4
Java | Inheritance | Question 5