code-rag-bench/online-tutorials huggingface dataset:
Draw Heart Using Turtle Graphics in Python

08 Jul, 2020
Turtle is an inbuilt module in Python. It provides: 
Drawing using a screen (cardboard).Turtle (pen).
Drawing using a screen (cardboard).
Turtle (pen).
To draw something on the screen, we need to move the turtle (pen) and to move the turtle, there are some functions like the forward(), backward(), etc
Prerequisite: Turtle Programming Basics
In this section, we will discuss how to draw Heart using Turtle Graphics.
Approach:
Import TurtleMake Turtle ObjectDefine a method to draw a curve with simple forward and left movesDefine a method to draw the full heart and fill the red color in itDefine a method to display some text by setting positionCall all the methods in main section.
Import Turtle
Make Turtle Object
Define a method to draw a curve with simple forward and left moves
Define a method to draw the full heart and fill the red color in it
Define a method to display some text by setting position
Call all the methods in main section.
Code:
python3
# Import turtle packageimport turtle  # Creating a turtle object(pen)pen = turtle.Turtle()  # Defining a method to draw curvedef curve():    for i in range(200):          # Defining step by step curve motion        pen.right(1)        pen.forward(1)  # Defining method to draw a full heartdef heart():      # Set the fill color to red    pen.fillcolor('red')      # Start filling the color    pen.begin_fill()      # Draw the left line    pen.left(140)    pen.forward(113)      # Draw the left curve    curve()    pen.left(120)      # Draw the right curve    curve()      # Draw the right line    pen.forward(112)      # Ending the filling of the color    pen.end_fill()  # Defining method to write textdef txt():      # Move turtle to air    pen.up()      # Move turtle to a given position    pen.setpos(-68, 95)      # Move the turtle to the ground    pen.down()      # Set the text color to lightgreen    pen.color('lightgreen')      # Write the specified text in     # specified font style and size    pen.write("GeeksForGeeks", font=(      "Verdana", 12, "bold"))    # Draw a heartheart()  # Write texttxt()  # To hide turtlepen.ht()
Output:
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTTP Non-Persistent & Persistent Connection | Set 2 (Practice Question)

21 Sep, 2017
Prerequisite: HTTP Non-Persistent & Persistent Connection – Set 1
For question point of view you need to know that Non-persistent connection is known as HTTP 1.0 and Persistent connection is known as HTTP 1.1.
Non-Persistent Connection: It requires connection setup again and again for each object to send.
Persistent connection: It does not require connection setup again and again. Multiple objects can use connection.
Questions : Assume that you have base HTML file with 30 embedded images, images & base file are small enough to fit in one TCP segment. How many RTT are required to retrieve base file & images under-following condition :(i) Non-Persistent connection without parallel connection(ii) Non-persistent connection with 10 parallel connection(iii) Persistent connection without pipe-lining(iv) Persistent connection with pipe-lining(Assume RTT dominates all other time)
Explanation :2RTT is the initial required connection one for TCP connection and one for HTML base file.
Total time = 2RTT + transmit time
(i) Non-Persistent connection with no parallel connection :Here for each image 2 RTT are required one for TCP connection and one for image to send.So transmit time for 30 images = 2*(30 RTT) = 60 RTTTotal time = 2 RTT+60 RTT = 62RTT
(ii) Non-persistent connection with 10 parallel connection :Here 10 images can be send simultaneously.So for 30 images it required -> 2*(30/10) = 6RTTTotal time = 2 RTT + 6 RTT = 8RTT
(iii) Persistent connection without pipelining :Here TCP connection is required again and again.So for 30 images it requires -> 30 RTTsTotal time = 2 RTT + 30 RTT = 32RTT
(iv) Persistent connection with pipe-lining :Since it is Persistent connection TCP connection is not required again and again.Pipe-lining means in one packet only images which can fit, can be send.In Pipe-lining connection we can send all images in 1RTT.Total time = 2 RTT + 1 RTT = 3RTT
This article is contributed by SHAURYA UPPAL. 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.
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Socket Programming in Python
GSM in Wireless Communication
Wireless Application Protocol
Secure Socket Layer (SSL)
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
How to delete a getter using the delete operator in JavaScript?

To delete a getter using the delete operator, use the delete keyword. Here’s how you can delete −
delete obj.name
You can try to run the following code to learn how to delete a getter
Live Demo
<html>
   <body>
      <script>
         var department = {
            deptName: "Marketing",
            deptZone: "North",
            deptID: 101,
            get details() {
               return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID;
            },
            set details(info) {
               var res = info.toString().split(' ');
               this.deptName = res[0] || '';
               this.deptZone = res[1] || '';
               this.deptID = res[2] || '';
            }
         }
         department.details = 'Marketing North 001';
         document.write("<br>Department Name: " + department.deptName);
         document.write("<br>Departmet Zone: " + department.deptZone);
         document.write("<br>Department ID: " + department.deptID);
         delete department.deptName;
         document.write("<br>Department Name (after deletion): " + department.deptName);
      </script>
   </body>
</html>
How to sort an array of dates in C/C++?

10 May, 2019
Given an array of dates, how to sort them.
Example:
Input:
       Date arr[] = {{20,  1, 2014},
                    {25,  3, 2010},
                    { 3, 12, 1676},
                    {18, 11, 1982},
                    {19,  4, 2015},
                    { 9,  7, 2015}}

Output:
      Date arr[] = {{ 3, 12, 1676},
                    {18, 11, 1982},
                    {25,  3, 2010},
                    {20,  1, 2014},
                    {19,  4, 2015},
                    { 9,  7, 2015}}

We strongly recommend you to minimize your browser and try this yourself firstThe idea is to use in-built function to sort function in C++. We can write our own compare function that first compares years, then months, then days.
Below is a complete C++ program.
// C++ program to sort an array of dates#include<bits/stdc++.h>using namespace std;  // Structure for datestruct Date{    int day, month, year;};  // This is the compare function used by the in-built sort// function to sort the array of dates.// It takes two Dates as parameters (const is// given to tell the compiler that the value won't be// changed during the compare - this is for optimization..)  // Returns true if dates have to be swapped and returns// false if not. Since we want ascending order, we return// true if the first Date is less than the second datebool compare(const Date &d1, const Date &d2){    // All cases when true should be returned    if (d1.year < d2.year)        return true;    if (d1.year == d2.year && d1.month < d2.month)        return true;    if (d1.year == d2.year && d1.month == d2.month &&                              d1.day < d2.day)        return true;      // If none of the above cases satisfy, return false    return false;}  // Function to sort array arr[0..n-1] of datesvoid sortDates(Date arr[], int n){    // Calling in-built sort function.    // First parameter array beginning,    // Second parameter - array ending,    // Third is the custom compare function    sort(arr, arr+n, compare);}  // Driver Programint main(){    Date arr[] = {{20,  1, 2014},                  {25,  3, 2010},                  { 3, 12, 1676},                  {18, 11, 1982},                  {19,  4, 2015},                  { 9,  7, 2015}};    int n = sizeof(arr)/sizeof(arr[0]);      sortDates(arr, n);      cout << "Sorted dates are\n";    for (int i=0; i<n; i++)    {        cout << arr[i].day << " " << arr[i].month             << " " << arr[i].year;        cout << endl;    }}
Output:
Sorted dates are
3 12 1676
18 11 1982
25 3 2010
20 1 2014
19 4 2015
9 7 2015
Similarly in C, we can use qsort() function.
Related Problem:How to efficiently sort a big list dates in 20’s
This article is contributed by Dinesh T.P.D. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Akanksha_Rai
date-time-program
C Language
C++
Sorting
Sorting
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# program to check if a string is palindrome or not

To check if a string is palindrome or not, you need to first find the reverse of the string using −
Array.reverse()
After that use the equals() method to match the original string with the reversed. If the result is true, that would mean the string is Palindrome.
Let us try the complete example. Here, our string is “Malayalam”, which is when reversed gives the same result.
Live Demo
using System;
namespace palindromecheck {
   class Program {
      static void Main(string[] args) {
         string string1, rev;
         string1 = "Malayalam";
         char[] ch = string1.ToCharArray();
         Array.Reverse(ch);
         rev = new string(ch);
         bool b = string1.Equals(rev, StringComparison.OrdinalIgnoreCase);
         if (b == true) {
            Console.WriteLine("" + string1 + " is a Palindrome!");
         } else {
            Console.WriteLine(" " + string1 + " is not a Palindrome!");
         }
         Console.Read();
      }
   }
}
Malayalam is a Palindrome!
How to manipulate CSS pseudo-elements ::before and ::after using jQuery?

To manipulate CSS pseudo elements using the hover() function. You can try to run the following code to learn how to manipulate CSS pseudo-elements −
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(){
    $('span').hover(function(){
    $(this).addClass('change').attr('data-content','bar');
});
});
</script>
<style>
span.change:after {
    content: attr(data-content) ' This is demo text.';
}
</style>
</head>
<body>
<p>Place cursor below...</p>
<span>foo</span>

</body>
</html>
cos() function for complex number in C++ - GeeksforGeeks

10 Oct, 2018
The cos() function for complex number is defined in the complex header file.This function is the complex version of the cos() function. This function is used to calculate the complex cosine of complex number z. This function returns the cos of complex number z.
Syntax:
cos (z);

Parameter:
z: This method takes a mandatory parameter z which represents the complex number.
Return value: This function returns the cos() of complex number z.
Below programs illustrate the cos() function in C++:
Program 1:-
// C++ program to demonstrate// example of cos() function.#include <iostream>#include <complex>using namespace std;   // driver programint main (){  complex<double> complexnumber (0.0, 1.0);        // use of cos() function for complex number  cout << "The cos of " << complexnumber << " is "                     << cos(complexnumber) <<endl;        return 0;}
The cos of (0,1) is (1.54308,-0)

Program 2:-
// C++ program to demonstrate// example of cos() function.#include <iostream>#include <complex>using namespace std;   // driver programint main (){  complex<double> complexnumber (1.0, 0.0);        // use of cos() function for complex number  cout << "The cos of " << complexnumber << " is "                     << cos(complexnumber) <<endl;        return 0;}
The cos of (1,0) is (0.540302,-0)

CPP-Library
cpp-numerics-library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Pure Virtual Functions and Abstract Classes in C++
turtle.stamp() function in Python - GeeksforGeeks

11 Jun, 2021
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to stamp a copy of the turtleshape onto the canvas and return its id. It doesn’t require any argument. Whatever the shape of the turtle is, it is printed at that point and continues with the next instructions.
turtle.stamp()
Below is the implementation of the above method with some examples :
Example 1:
Python3
# import packageimport turtle # forward turtle by 100turtle.forward(100) # print the turtle shapeturtle.stamp() # and then continue# forward turtle by 100turtle.forward(100)
 
 
Output: 
 
Here the middle one arrow is due to the stamp and next is turtle’s head
 
Example 2:
 
Python3
# import packageimport turtle # loop for printing some stampsfor i in range(15):         # for motion    turtle.forward(100+10*i)         # printing turtle shape    turtle.stamp()         # for pattern    turtle.right(90)
 
 
Output :
 
Printing the turtle’s shape at each movement
 
simranarora5sos
Python-turtle
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
Create a Glowing text shadow using HTML and CSS - GeeksforGeeks

16 Jun, 2020
To create a glowing text-shadow, we will use HTML to create the structure and CSS for the styling of the text. With the help of CSS, we can add shadow to text.
HTML Code: In this section, we will design the basic structure of the code.
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport"           content="width=device-width,                    initial-scale=1.0">    <title>Glowing Text</title>    <link rel="stylesheet" href="style.css"></head><body>    <h1>Hello !</h1>    <h1>GeeksforGeeks</h1></body></html>
CSS Code: In this section, we will use some CSS property to design the Glowing text shadow. The CSS text-shadow property applies shadow to text.The text-shadow CSS property adds shadows to text. It accepts a comma-separated list of shadows to be applied to the text and any of its decorations. Each shadow is described by some combination of X and Y offsets from the element, blur radius, and color.
body{    background: black;}  h1{    margin-top: 150px;    text-align: center;    font-size: 60px;    font-family: 'century gothic';    color: #ffffcc;    text-shadow: 0 0 5px #fff,                 0 0 10px #fff,                  0 0 20px green,                  0 0 30px green,                  0 0 40px green,                  0 0 55px green,                  0 0 70px green;}
Complete Code: It is the combination of above two code section.
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport"           content="width=device-width,                   initial-scale=1.0">    <title>Glowing Text</title>    <style>body{    background: black;}  h1{    margin-top: 150px;    text-align: center;    font-size: 60px;    font-family: 'century gothic';    color: #ffffcc;    text-shadow: 0 0 5px #fff,                 0 0 10px #fff,                  0 0 20px green,                  0 0 30px green,                  0 0 40px green,                  0 0 55px green,                  0 0 70px green;}    </style></head><body>    <h1>Hello !</h1>    <h1>GeeksforGeeks</h1></body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Properties
HTML-DOM
HTML5
CSS
HTML
Web Technologies
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
Form validation using jQuery
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 ?
What is the difference between class variables and instance variables in Java?

Following are the notable differences between Class (static) and instance variables.
 Live Demo
public class VariableExample{
   int myVariable;
   static int data = 30;
   
   public static void main(String args[]){
      VariableExample obj = new VariableExample();
      
      System.out.println("Value of instance variable: "+obj.myVariable);
      System.out.println("Value of static variable: "+VariableExample.data);
   }
}
Value of instance variable: 0
Value of static variable: 30
How to convert a Python date string to a date object?

You can convert a string to date object using the strptime function. Provide the date string and the format in which the date is specified. 
import datetime
date_str = '29122017' # The date - 29 Dec 2017
format_str = '%d%m%Y' # The format
datetime_obj = datetime.datetime.strptime(date_str, format_str)
print(datetime_obj.date())
This will give the output −
2017-12-29
How to create a plot with cross sign in R?

In base R, the plot with different shape of points can be created by using pch argument inside the plot function but if we want to use any sign that is not designed for pch argument by default then we should pass that particular sign. For example, if we want to use cross sign then we can use letter x with pch as pch = "x".
Consider the below vector and create the plot by displaying cross sign using letter x −
 Live Demo
x<-1:10
plot(x,pch="x")
 Live Demo
y<-rnorm(10)
plot(y,pch="x")
 Live Demo
z<-rpois(10,3)
plot(z,pch="x")
sum() function in Python

In this tutorial, we are going to learn about the sum() function.
The function sum() is used to sum all the numbers in an iterable. Let's see some examples.
 Live Demo
# initialinzing a list
numbers = [1, 2, 3, 4, 5]
# printing the sum
print(sum(numbers))
If you run the above code, then you will get the following result.
15
The sum() takes one optional argument i.e., start that will be added to the result. Let's see it.
 Live Demo
# initialinzing a list
numbers = [1, 2, 3, 4, 5]
# printing the sum
print(sum(numbers, 5))
If you run the above code, then you will get the following result.
20
If we place any string or any other data type inside the iterable, then we will get an error. Let's
see it with the following example.
 Live Demo
# initialinzing a list
numbers = [1, 2, 3, [1, 2, 3], '5']
# printing the sum
print(sum(numbers, 5))
If you run the above code, then you will get the following result.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-40c38246060a> in <module>
   3
   4 # printing the sum
----> 5 print(sum(numbers, 5))
TypeError: unsupported operand type(s) for +: 'int' and 'list'
If you have any doubts in the tutorial, mention them in the comment section.
Python - Round number of places after the decimal for column values in a Pandas DataFrame

To round number of places after the decimal, use the display.precision attribute of the Pandas.
At first, import the required Pandas library −
import pandas as pd
Create a DataFrame with 2 columns −
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
      "Reg_Price": [7000.5057, 1500, 5000.9578, 8000, 9000.75768, 6000]

   }
)


Use the set_option() method to set precision. We have set precision value 2 −
pd.set_option('display.precision', 2)
Following is the complete code −
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
      "Reg_Price": [7000.5057, 1500, 5000.9578, 8000, 9000.75768, 6000]

   }
)

print"DataFrame ...\n",dataFrame

pd.set_option('display.precision', 2)
print"\nUpdated dataframe with rounding decimal values...\n", dataFrame
This will produce the following output −
DataFrame ...
        Car    Reg_Price
0       BMW  7000.50570
1     Lexus  1500.00000
2     Tesla  5000.95780
3   Mustang  8000.00000
4  Mercedes  9000.75768
5    Jaguar  6000.00000

Updated dataframe with rounding decimal values...
        Car   Reg_Price
0       BMW    7000.51
1     Lexus    1500.00
2     Tesla    5000.96
3   Mustang    8000.00
4  Mercedes    9000.76
5    Jaguar    6000.00
Algorithms | Searching | Question 2 - GeeksforGeeks

28 Jun, 2021
Which of the following is correct recurrence for worst case of Binary Search?(A) T(n) = 2T(n/2) + O(1) and T(1) = T(0) = O(1)(B) T(n) = T(n-1) + O(1) and T(1) = T(0) = O(1)(C) T(n) = T(n/2) + O(1) and T(1) = T(0) = O(1)(D) T(n) = T(n-2) + O(1) and T(1) = T(0) = O(1)Answer: (C)Explanation: Following is typical implementation of Binary Search.
// Searches x in arr[low..high].  If x is present, then returns its index, else -1int binarySearch(int arr[], int low, int high, int x){    if(high >= low)    {        int mid = low + (high - low)/2;        if (x == arr[mid])            return mid;        if (x> arr[mid])            return binarySearch(arr, (mid + 1), high);        else            return binarySearch(arr, low, (mid -1));    }      return -1;}
In Binary Search, we first compare the given element x with middle of the array. If x matches with middle element, then we return middle index. Otherwise, we either recur for left half of array or right half of array.
So recurrence is T(n) = T(n/2) + O(1)Quiz of this Question
Algorithms-Searching
Searching Quiz
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithms | Backtracking | Question 1
Algorithms | Dynamic Programming | Question 2
Algorithms | Greedy Algorithms | Question 1
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Dynamic Programming | Question 3
Algorithms | Dynamic Programming | Question 7
Algorithms | Graph Traversals | Question 12
Algorithms | Graph Traversals | Question 8
Algorithms | Dynamic Programming | Question 7
Algorithms | Analysis of Algorithms | Question 17
What is the importance of 'for await...of' statement in JavaScript?

The 'for await...of' statement creates a loop iterating over async objects and sync objects such as arrays, array-like objects, maps sets, etc.
for await (variable of iterable) {
   statement
}
In the following example "for await...of" statement is used to loop over a normal array in an async format and integers were displayed from 1 to 5 as shown in the output.
Live Demo
<html>
<body>
<script>
   var txt = "";
   const array = [1,2,3,4,5];
   async function test() {
      for await (const p of array) {
         var txt = p + "</br>";
         document.write(txt);
      }
   }
   test();
</script>
</body>
</html>
1
2
3
4
5
To call an async function in a loop, a new Symbol "Symbol.asyncIterator" and "for-await...of" construct are used. Most importantly "for-await...of" has played an important role to loop over async iterable object.   
In the following example using "for await...of", which iterates over an async iterable, integers from 1 to 5 were displayed.
Live Demo
<html>
<body>
<script>
   var txt = "";
   var async = {
      [Symbol.asyncIterator]() {
         return {
            i: 1,
            next() {
               if (this.i < 6) {
                  return Promise.resolve({ value: this.i++, done : false});
               }
            }
         };
      }
   };
   async function test() {
      for await (let p of async) {
         txt = p + "</br>"
         document.write(txt);
      }
   }
   test();
</script>
</body>
</html>
1
2
3
4
5
Koa.js - Form Data

Forms are an integral part of the web. Almost every website we visit offers us forms that submit or fetch some information for us. To get started with forms, we will first install the koa-body. To install this, go to your terminal and use −
$ npm install --save koa-body

Replace your app.js file contents with the following code.
var koa = require('koa');
var router = require('koa-router');
var bodyParser = require('koa-body');
var app = koa();

//Set up Pug
var Pug = require('koa-pug');
var pug = new Pug({
   viewPath: './views',
   basedir: './views',
   app: app //Equivalent to app.use(pug)
});

//Set up body parsing middleware
app.use(bodyParser({
   formidable:{uploadDir: './uploads'},
   multipart: true,
   urlencoded: true
}));

_.get('/', renderForm);
_.post('/', handleForm);

function * renderForm(){
   this.render('form');
}
function *handleForm(){
   console.log(this.request.body);
   console.log(this.req.body);
   this.body = this.request.body; //This is where the parsed request is stored
}

app.use(_.routes()); 
app.listen(3000);
The new things we are doing here are importing the body parser and multer. We are using the body parser for parsing json and x-www-form-urlencoded header requests, while we use multer for parsing multipart/form-data.
Let us create a html form to test this out! Create a new view named form.pug with the following code.
html
   head
      title Form Tester
   body
      form(action = "/", method = "POST")
         div
            label(for = "say") Say: 
            input(name = "say" value = "Hi")
         br
         div
            label(for = "to") To: 
            input(name = "to" value = "Koa form")
         br
         button(type = "submit") Send my greetings
Run your server using −
nodemon index.js

Now go to localhost:3000/ and fill the form as you like, and submit it. You'll receive the response as −
Take a look at your console, it'll show you the body of your request as a JavaScript object. For example −
The this.request.body object contains your parsed request body. To use fields from that object, just use them as normal JS objects.
This is just one way to send a request. There are many other ways, but those are irrelevant to cover here, because our Koa app will handle all those requests in the same way. To read more about different ways to make a request, have a look at this page.
 Print
 Add Notes
 Bookmark this page
C# program to merge two sorted arrays into one

Set two arrays that you wish to merge −
int[] arr1 = new int[5] {
   5,
   15,
   25,
   30,
   47
};
int[] arr2 = new int[5] {
   55,
   60,
   76,
   83,
   95
};
Now take a third array that would merge both the above arrays −
int[] merged = new int[10];
The following is the code that merges two arrays into the third array in C# −
 Live Demo
using System;
using System.Collections.Generic;

class Program {
   static void Main() {
      int i = 0;
      int j = 0;

      int[] arr1 = new int[5] {
         5,
         15,
         25,
         30,
         47
      };
      int[] arr2 = new int[5] {
         55,
         60,
         76,
         83,
         95
      };
      int[] merged = new int[10];
   
      for (i = 0, j = 0; i < 5; i++) {
         merged[j++] = arr1[i];
      }
      for (i = 0; i < 5; i++) {
         merged[j++] = arr2[i];
      }
      Console.WriteLine("Elements of merged array = ");
      for (i = 0; i < 10; i++) {
         Console.WriteLine("merged[" + (i) + "]: " + merged[i]);
      }
      Console.WriteLine();
   }
}
Elements of merged array =
merged[0]: 5
merged[1]: 15
merged[2]: 25
merged[3]: 30
merged[4]: 47
merged[5]: 55
merged[6]: 60
merged[7]: 76
merged[8]: 83
merged[9]: 95
How to use multiple submit buttons in an HTML form ?

30 Sep, 2021
Every HTML form deals with the server-side with an action attribute. The HTML action Attribute is used to specify where the form data is to be sent to the server after submission of the form. As the destination of our data is stored in the action attribute each and every button will lead us to the same location. To overcome this difficulty we have to use the formaction attribute of HTML input and buttons.
Approach: The formaction attribute is used to specify where to send the data of the form. After submission of the form, the formaction attribute is called. The form data is to be sent to the server after the submission of the form. It overrides the feature of the action attribute of a <form> element. We are going to  implement our problem using this ‘formaction’ attribute
Let’s learn the steps of performing multiple actions with multiple buttons in a single HTML form:  
Create a form with method ‘post’ and set the value of the action attribute to a default URL where you want to send the form data.
Create the input fields inside the as per your concern.
Create a button with type submit. This button will trigger the default action attribute of the form and send our input data to that URL.
Create another button with type submit. Also add a ‘formaction‘ attribute to this button and give it the value of the secondary URL where you want to send the form-data when this button is clicked.
The formaction attribute will override the action attribute of the form and send the data to your desired location.
<form action="/DEFAULT_URL" method="post">
  <!-- Input fields here -->
  
  <!-- This button will post to the 
  /DEFAULT_URL of the form-->
  <button type="submit">BUTTON 1</button>
  
  <!-- This button will post to the custom 
  URL of the formaction attribute-->
  <button type="submit" formaction="/URL2">
    BUTTON 2
  </button>
</form>
HTML
<!DOCTYPE html><html lang="en">  <body>    <form action="https://gfg.com/" method="post">        Username:<br>        <input type="text" name="username">        <br>        Email id:<br>        <input type="text" name="email_id">        <br><br>          <button type="submit" formaction="#">            Submit 1        </button>                  <button type="submit" formaction="#">            Submit 2        </button>    </form></body>  </html>
HTML-Attributes
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
kbhit in C language

Here we will see the kbhit functionality in C. The kbhit is basically the Keyboard Hit. This function is present at conio.h header file. So for using this, we have to include this header file into our code.
The functionality of kbhit() is that, when a key is pressed it returns nonzero value, otherwise returns zero.
#include <stdio.h>
#include <conio.h>
main() {
   char ch;
   printf("Enter keys (ESC to exit)\n");
   while (1) { //define infinite loop for taking keys
      if (kbhit) {
         ch = getch(); // Get typed character into ch
         if ((int)ch == 27) //when esc button is pressed, then it will comeout from loop
         break;
         printf("You have entered : %c\n", ch);
      }
   }
}
Enter keys (ESC to exit)
You have entered : i
You have entered : t
You have entered : D
You have entered : w
You have entered : 5
You have entered : /
You have entered : *
You have entered : +
You have entered :
You have entered : o
You have entered :
You have entered : &
Note: This kbhit() is not a standard library. So we should avoid this in our code.
Get first element of each sublist in Python

A list in python can also contain lists inside it as elements. These nested lists are called sublists. In this article we will solve the challenge of retrieving only the first element of each sublist in a given list.
It is a very simple approach in which we loop through the sublists fetching the item at index 0 in them. A for loop is used for this purpose as shown below.
 Live Demo
Alist = [['Mon', 1], ['Tue', 'Wed', "Fri"], [12,3,7]]
print("Given List:\n",Alist)
print("First Items from sublists:\n")
for item in Alist:
   print((item[0]))
Running the above code gives us the following result −
Given List:
[['Mon', 1], ['Tue', 'Wed', 'Fri'], [12, 3, 7]]
First Items from sublists:
Mon
Tue
12
The * allows us to unpack the sublists and give access to individual elements of the sublist. So in this case we will use * and access the element at index 0 from each element. Then we finally zip the result to get a list of the first element from the sublists.
 Live Demo
Alist = [['Mon', 1], ['Tue', 'Wed', "Fri"], [12,3,7]]
print("Given List:\n",Alist)
print("\n First Items from sublists:\n")
print(list(list(zip(*Alist))[0]))

Running the above code gives us the following result −
Given List:
[['Mon', 1], ['Tue', 'Wed', 'Fri'], [12, 3, 7]]
First Items from sublists:
['Mon', 'Tue', 12]
The itemgetter(i) constructs a callable that takes an iterable object like dictionary,list, tuple etc. as input, and fetches the i-th element out of it. So we can use this method to get the first items of the list using the map function as follows.
 Live Demo
from operator import itemgetter

Alist = [['Mon', 1], ['Tue', 'Wed', "Fri"], [12,3,7]]
print("Given List:\n",Alist)
print("\n First Items from sublists:\n")
print(list(map(itemgetter(0), Alist)))
Running the above code gives us the following result −
Given List:
[['Mon', 1], ['Tue', 'Wed', 'Fri'], [12, 3, 7]]

First Items from sublists:

['Mon', 'Tue', 12]
How to add shadow Effect for a Text in Android?

This example demonstrates how to add shadow Effect for a Text in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:id = "@+id/parent"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:gravity = "center"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/text"
      android:textSize = "28sp"
      android:textAlignment = "center"
      android:textColor = "#FFF"
      android:layout_width = "match_parent"
      android:shadowColor = "#000"
      android:shadowDx = "-2"
      android:shadowDy = "-2"
      android:shadowRadius = "1"
      android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken a text view with shadow properties as shown below -
android:shadowColor = "#000"
android:shadowDx = "-2"
android:shadowDy = "-2"
android:shadowRadius = "1"
In the above tags indicates about shadow color, Axis's(X, Y) and shadow radius for text view.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   TextView textview;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
      textview = findViewById(R.id.text);
      textview.setText("textview with shadow");
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, it will show a text view with shadow effect.
Click here to download the project code
isfinite() function in C++ - GeeksforGeeks

06 Jul, 2021
The isfinite() function is a builtin function in C++ and is used to determine whether a given value if finite or not. A finite value is a value that is neither infinite nor NAN. If the number is finite then the function returns 1 else returns zero.Syntax:  
bool isfinite(float x);  

or,
bool isfinite(double x);

or,  
bool isfinite(long double x); 
Parameter: This function takes only one parameter . It represents the floating point number.Returns: If the number is infinite or NAN then it returns 0 else if it is finite then it returns 1.Below programs illustrate the isfinite() function in C++: Program 1:  
CPP
// C++ program to illustrate the// isfinite() function. #include <bits/stdc++.h>using namespace std; int main(){    float x = 19.0;         cout<<"The value of x is = "<< x << endl;     // Here function check whether 19 is finite or not    // if yes function returns 1, else 0    cout<<"isfinite(x) = "<<isfinite(x);         return 0;}
The value of x is = 19
isfinite(x) = 1
 
Program 2:  
CPP
// C++ program to illustrate the// isfinite() function #include <bits/stdc++.h>using namespace std; int main(){    float x=9.6/0.0;         cout<<"The value of x is = "<< x << endl;         cout<<"isfinite(x) = "<<isfinite(x);         return 0;}
The value of x is = inf
isfinite(x) = 0
 
Program 3:  
CPP
// C++ program to illustrate the// isfinite() function #include <bits/stdc++.h>using namespace std; int main(){      // Value is NAN    double x=0.0/0.0;         cout<<"Value of x is = "<< x << endl;         cout<<"isfinite(x) = "<<isfinite(x);         return 0;}
Value of x is = -nan
isfinite(x) = 0
 
surinderdawra388
CPP-Functions
CPP-Library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Inline Functions in C++
Exception Handling in C++
Destructors in C++
new and delete operators in C++ for dynamic memory
std::string class in C++
Sorting a vector in C++
MySQL - Between Clause

You can use BETWEEN clause to replace a combination of "greater than equal AND less than equal" conditions.
To understand BETWEEN clause, consider an employee_tbl table, which is having following records −
mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
|  id  | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|   1  | John | 2007-01-24 |        250         |
|   2  | Ram  | 2007-05-27 |        220         |
|   3  | Jack | 2007-05-06 |        170         |
|   3  | Jack | 2007-04-06 |        100         |
|   4  | Jill | 2007-04-06 |        220         |
|   5  | Zara | 2007-06-06 |        300         |
|   5  | Zara | 2007-02-06 |        350         |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now, suppose based on the above table you want to fetch records with conditions daily_typing_pages more than 170 and equal and less than 300 and equal. This can be done using >= and <= conditions as follows −
mysql>SELECT * FROM employee_tbl 
   ->WHERE daily_typing_pages >= 170 AND
   ->daily_typing_pages <= 300;
+------+------+------------+--------------------+
|  id  | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|   1  | John | 2007-01-24 |        250         |
|   2  | Ram  | 2007-05-27 |        220         |
|   3  | Jack | 2007-05-06 |        170         |
|   4  | Jill | 2007-04-06 |        220         |
|   5  | Zara | 2007-06-06 |        300         |
+------+------+------------+--------------------+
5 rows in set (0.03 sec)
Same can be achieved using BETWEEN clause as follows −
mysql> SELECT * FROM employee_tbl 
   -> WHERE daily_typing_pages BETWEEN 170 AND 300; 
+------+------+------------+--------------------+
|  id  | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|   1  | John | 2007-01-24 |        250         |
|   2  | Ram  | 2007-05-27 |        220         |
|   3  | Jack | 2007-05-06 |        170         |
|   4  | Jill | 2007-04-06 |        220         |
|   5  | Zara | 2007-06-06 |        300         |
+------+------+------------+--------------------+
5 rows in set (0.03 sec)

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Permutation in String in C++

Suppose we have two strings s1 and s2, we have to write a function to return true if s2 contains the permutation of s1. So we can say that one of the first string's permutations is the substring of the second string. So if the string s1 = “abc”, and second string s2 is “findcab”, then the result will be true, as the permutation of “abc” is true. That is “cab”.
To solve this, we will follow these steps −
create two vectors cnt1 and cnt2 of size 26
for i in range 0 to s1increase the value of cnt1[s1[i] – ‘a’] by 1
increase the value of cnt1[s1[i] – ‘a’] by 1
j := 0 and required := size of s1
for i in range 0 to size of s2x := s2[i]increase cnt2[x – ‘a’] by 1if cnt1[x – ‘a’] and cnt2[x – ‘a’] <= cnt[x – ‘a’], thendecrease required by 1while j <= i and cnt2[s2[j] – ‘a’] – 1 >= cnt1[s2[j] – ‘a’], dodecrease cnt2[s2[j] – ‘a’] by 1increase j by 1if i – j + 1 = size of s1 and required = 0, then return true
x := s2[i]
increase cnt2[x – ‘a’] by 1
if cnt1[x – ‘a’] and cnt2[x – ‘a’] <= cnt[x – ‘a’], thendecrease required by 1
decrease required by 1
while j <= i and cnt2[s2[j] – ‘a’] – 1 >= cnt1[s2[j] – ‘a’], dodecrease cnt2[s2[j] – ‘a’] by 1increase j by 1
decrease cnt2[s2[j] – ‘a’] by 1
increase j by 1
if i – j + 1 = size of s1 and required = 0, then return true
return false.
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool checkInclusion(string s1, string s2) {
      vector <int> cnt1(26), cnt2(26);
      for(int i = 0; i < s1.size(); i++)cnt1[s1[i] - 'a']++;
      int j = 0;
      int required = s1.size();
      for(int i = 0; i < s2.size(); i++){
         char x = s2[i];
         cnt2[x - 'a']++;
         if(cnt1[x - 'a'] && cnt2[x - 'a'] <= cnt1[x - 'a']) required--;
         while(j <= i && cnt2[s2[j] - 'a'] - 1 >= cnt1[s2[j] - 'a']){
            cnt2[s2[j] - 'a']--;
            j++;
         }
         if(i - j + 1 == s1.size() && required == 0){
            return true;
         }
      }
      return false;
   }
};
main(){
   Solution ob;
   cout << (ob.checkInclusion("abc", "findcab"));
}
"abc"
"findcab"
1
C - Program Structure

Before we study the basic building blocks of the C programming language, let us look at a bare minimum C program structure so that we can take it as a reference in the upcoming chapters.
A C program basically consists of the following parts −
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
Let us look at a simple code that would print the words "Hello World" −
#include <stdio.h>

int main() {
   /* my first program in C */
   printf("Hello, World! \n");
   
   return 0;
}
Let us take a look at the various parts of the above program −
The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation.
The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation.
The next line int main() is the main function where the program execution begins.
The next line int main() is the main function where the program execution begins.
The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program.
The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program.
The next line printf(...) is another function available in C which causes the message "Hello, World!" to be displayed on the screen.
The next line printf(...) is another function available in C which causes the message "Hello, World!" to be displayed on the screen.
The next line return 0; terminates the main() function and returns the value 0.
The next line return 0; terminates the main() function and returns the value 0.
Let us see how to save the source code in a file, and how to compile and run it. Following are the simple steps −
Open a text editor and add the above-mentioned code.
Open a text editor and add the above-mentioned code.
Save the file as hello.c
Save the file as hello.c
Open a command prompt and go to the directory where you have saved the file.
Open a command prompt and go to the directory where you have saved the file.
Type gcc hello.c and press enter to compile your code.
Type gcc hello.c and press enter to compile your code.
If there are no errors in your code, the command prompt will take you to the next line and would generate a.out executable file.
If there are no errors in your code, the command prompt will take you to the next line and would generate a.out executable file.
Now, type a.out to execute your program.
Now, type a.out to execute your program.
You will see the output "Hello World" printed on the screen.
You will see the output "Hello World" printed on the screen.
$ gcc hello.c
$ ./a.out
Hello, World!

Make sure the gcc compiler is in your path and that you are running it in the directory containing the source file hello.c.
 Print
 Add Notes
 Bookmark this page
Adding Navigation Bar programmatically iOS using Swift

To add navigation bar programmatically we’ll go through a series of steps that are mentioned below. We’ll be doing this in ViewWillLayoutSubviews method of our viewController.
Getting the width of the current View.
let width = self.view.frame.width
Creating a navigation bar with the width of our current view and height of 44 px which is the default height of a navigation bar.
let navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: width, height: 44))
Adding the newly created navigation bar to our view.
self.view.addSubview(navigationBar)
We can further extend this example to add a title and a button to our View. The complete result should look something like the class below.
class ViewController: UIViewController {
   override func viewWillLayoutSubviews() {
      let width = self.view.frame.width
      let navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: width, height: 44))
      self.view.addSubview(navigationBar);
      let navigationItem = UINavigationItem(title: "Navigation bar")
      let doneBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: nil, action: #selector(selectorX))
      navigationItem.rightBarButtonItem = doneBtn
      navigationBar.setItems([navigationItem], animated: false)
   }
   override func viewDidLoad() {
      super.viewDidLoad()
   }
   @objc func selectorX() { }
}
When we execute this example our result should look like.