code-rag-bench/online-tutorials huggingface dataset:
C Program to Reverse Array of Strings - GeeksforGeeks

20 Dec, 2018
Given an array of string literals, reverse the array.
Examples:
Input :  arr[] = {"Coding", "Never",  "Fail",  "Me"} 
Output : arr[] = {"Me", "Fail", "Never", "Coding"}

Input : arr[] = {"welcome", "to", "geeksforgeeks"} 
Output : arr[] = {"geeksforgeeks", "to", "welcome"}  

The idea is to create an array of pointers, store string literals in it. To reverse the array, we start from begin and end, and move both pointers toward each other. While moving, we keep swapping pointers.
// C program to reverse an array of strings#include <stdio.h>#include <string.h>  void PrintArray(char* arr[], int n){    for (int i = 0; i < n; i++) {        printf("%s ", arr[i]);    }}  void ReverseArray(char* arr[], int n){    char* temp;      // Move from begin and end. Keep    // swapping strings.     int j = n - 1;    for (int i = 0; i < j; i++) {        temp = arr[i];        arr[i] = arr[j];        arr[j] = temp;        j--;    }}  int main(){    char* arr[] = { "Coding", "never", "fail", "me" };    int n = sizeof(arr) / sizeof(arr[0]);      PrintArray(arr, n);      printf("\n");      ReverseArray(arr, n);      PrintArray(arr, n);      return 0;}
Coding never fail me 
me fail never Coding

C-String
Reverse
C Programs
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C program to sort an array in ascending order
time() function in C
C Program to Swap two Numbers
Producer Consumer Problem in C
unsigned char in C with Examples
Program to calculate First and Follow sets of given grammar
jQuery | appendTo() with Examples - GeeksforGeeks

13 Feb, 2019
The appendTo() is an inbuilt method in jQuery that is used to insert HTML element at the end of the selected element.Syntax:
$(content).appendTo(selector)

Here the element content specifies the content to be inserted.Parameters: It accepts a parameters “selector” which specifies the elements to which content will be appended.Return Value: It returns the modified selected element.
<html>   <head>      <meta charset="utf-8">      <style>         #hel {         background: lightgreen;         display: block;         border: 2px solid green;         padding: 10px;         width: 300px;         }      </style>      <script src="https://code.jquery.com/jquery-1.10.2.js">      </script>   </head>   <body>      <span>geeks Writer !!!</span>      <div id="hel">Hello-  </div>      <script>         $("span").appendTo("#hel");      </script>   </body></html>
Output:
Code #2:In the below code, we are directly appending a “p” element using this method.
<html>   <head>      <meta charset="utf-8">      <style>         body{         display: block;         width: 250px;         height: 100px;         border: 2px solid green;         padding: 10px;         }      </style>      <script src="https://code.jquery.com/jquery-1.10.2.js">      </script>   </head>   <body>      <h2>Greetings from gfg !</h2>      <div class="container">         <div class="inner">            Hello         </div>      </div>      <script>         $( "<p>Everyone !!!</p>").appendTo( ".inner" );      </script>   </body></html>
Output:
jQuery-HTML/CSS
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to add options to a select element using jQuery?
Chrome input type=“number” CSS styling

To style input type = number, use the following CSS −
input[type=number]::-webkit-inner-spin-button {
   -webkit-appearance: none;
}
The above shows without a spinner.
To show and style a spinner, use
input[type=number]::-webkit-inner-spin-button {
   opacity: 1;
}
The above shows the following output −
Plot the Size of each Group in a Groupby object in Pandas - GeeksforGeeks

31 Aug, 2021
Pandas dataframe.groupby() function is one of the most useful function in the library it splits the data into groups based on columns/conditions and then apply some operations eg. size() which counts the number of entries/rows in each group. The groupby() can also be applied on series.
Syntax: DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)Parameters : by : mapping, function, str, or iterable axis : int, default 0 level : If the axis is a MultiIndex (hierarchical), group by a particular level or levels as_index : For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output sort : Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. groupby preserves the order of rows within each group. group_keys : When calling apply, add group keys to index to identify pieces squeeze : Reduce the dimensionality of the return type if possible, otherwise return a consistent typeReturns : GroupBy object 
In the following example, we are going to make use to two libraries seaborn and pandas where seaborn is used for plotting and pandas for reading data. We are going to use the load_dataset() methods from seaborn to load the penguins.csv data set.
Python3
# import the moduleimport seaborn as snsdataset = sns.load_dataset('penguins')  # displaying the dataprint(dataset.head())
Output :
Top five rows of the dataset
More information about the data set using the info() method
Python3
# display the number of columns and their data typesdataset.info()
Output : 
Info about the dataset
We will be grouping the data using the groupby() method according to ‘island’ and plotting it.
Plotting using Pandas : 
Python3
# apply groupby on the island column# plottingdataset.groupby(['island']).size().plot(kind = "bar")
Plot of groupby() size using Pandas 
Plotting using Seaborn 
Python3
# use the groupby() function to group island column# and apply size() function# size() is equivalent to counting the distinct rowsresult = dataset.groupby(['island']).size() # plot the resultsns.barplot(x = result.index, y = result.values)
Plot of size using Seaborn 
gulshankumarar231
Python pandas-groupby
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
MATLAB - Addition & Subtraction of Matrices

You can add or subtract matrices. Both the operand matrices must have the same number of rows and columns.
Create a script file with the following code −
a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c = a + b
d = a - b
When you run the file, it displays the following result −
c =
      8     7     9
      6     5    14
      12    15    10
d =
      -6    -3    -3
      2     5    -2
      2     1     8


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
Java Program to write int array to a file

Here’s our file −
FileWriter writer = new FileWriter("E:/demo.txt");
Now, consider an Integer array −
Integer arr[] = { 10, 20, 30, 40, 50 };
Write the above array to the file “demo.txt” −
int len = arr.length;
for (int i = 0; i < len; i++) {
   writer.write(arr[i] + "\t" + "");
}
The following is an example. Here, our file is “E:/input.txt” −
import java.io.FileWriter;
public class Demo {
   public static void main(String[] argv) throws Exception {
      FileWriter writer = new FileWriter("E:/input.txt");
      Integer arr[] = { 10, 20, 30, 40, 50 };
      int len = arr.length;
      for (int i = 0; i < len; i++) {
         writer.write(arr[i] + "\t"+ "");
      }
      writer.close();
   }
}
The output is as follows i.e. the text in the file is −
1020304050
filepath.Join() Function in Golang With Examples

10 May, 2020
In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Join() function in Go language used to join any number of the specified path elements into a single path, adding a Separator if necessary. This function calls Clean on the result and all empty strings are ignored. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions.
Syntax:
func Join(elem ...string) string

Here, ‘elem’ is the specified path elements.
Return Value: It returns the joined single path.
Example 1:
// Golang program to illustrate the usage of// filepath.Join() function  // Including the main packagepackage main  // Importing fmt and path/filepathimport (    "fmt"    "path/filepath")  // Calling mainfunc main() {      // Calling the Join() function    fmt.Println(filepath.Join("G", "F", "G"))    fmt.Println(filepath.Join("G/F", "G"))    fmt.Println(filepath.Join("gfg", "GFG"))    fmt.Println(filepath.Join("Geeks", "for", "Geeks"))}
Output:
G/F/G
G/F/G
gfg/GFG
Geeks/for/Geeks

Example 2:
// Golang program to illustrate the usage of// filepath.Join() function  // Including the main packagepackage main  // Importing fmt and path/filepathimport (    "fmt"    "path/filepath")  // Calling mainfunc main() {      // Calling the Join() function    fmt.Println(filepath.Join("/", "/"))    fmt.Println(filepath.Join(""))    fmt.Println(filepath.Join("a/b", "/c"))    fmt.Println(filepath.Join("5", "10"))    fmt.Println(filepath.Join("."))  }
Output:
/

a/b/c
5/10
.

Golang-filepath
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to convert a string in lower case in Golang?
How to Trim a String in Golang?
How to compare times in Golang?
How to display animated GIF images in Android using Kotlin?

This example demonstrates how to display animated GIF images in Android using Kotlin.
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 dependency in build.gradle (module:app)
implementation 'com.github.bumptech.glide:glide:4.9.0'
Step 3 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="8dp"
   tools:context=".MainActivity">
   <ImageView
      android:id="@+id/imageView"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
   <Button
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignParentBottom="true"
      android:onClick="showGif"
      android:text="SHOW GIF"
      android:textAlignment="center" />
</RelativeLayout>
Step 4 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
   }
   fun showGif(view: View) {
      val imageView: ImageView = findViewById(R.id.imageView)
      Glide.with(this).load(R.drawable.giphy).into(imageView)
   }
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.kotlipapp">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
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 android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
How to repeat column values of a data.table object in R by number of values in another column?

To repeat column values of a data.table object by values in another column, we can follow the below steps −
First of all, create a data.table object.
First of all, create a data.table object.
Then, use rep function along with cbind function to repeat column values in the matrix by values in another column.
Then, use rep function along with cbind function to repeat column values in the matrix by values in another column.
Let’s create a data.table object as shown below −
library(data.table)
x<-1:10
y<-sample(1:5,10,replace=TRUE)
DT<-data.table(x,y)
DT
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
     x y
1:   1 2
2:   2 4
3:   3 1
4:   4 5
5:   5 3
6:   6 4
7:   7 2
8:   8 5
9:   9 1
10: 10 1
Repeat a column values by values in another column
Using rep function along with cbind function to repeat column x values in the data.table object DT by values in column y −
library(data.table)
x<-1:10
y<-sample(1:5,10,replace=TRUE)
DT<-data.table(x,y)
cbind(rep(DT$x,times=DT$y),rep(DT$y,times=DT$y))
     [,1] [,2]
[1,]   1   2
[2,]   1   2
[3,]   2   4
[4,]   2   4
[5,]   2   4
[6,]   2   4
[7,]   3   1
[8,]   4   5
[9,]   4   5
[10,]  4   5
[11,]  4   5
[12,]  4   5
[13,]  5   3
[14,]  5   3
[15,]  5   3
[16,]  6   4
[17,]  6   4
[18,]  6   4
[19,]  6   4
[20,]  7   2
[21,]  7   2
[22,]  8   5
[23,]  8   5
[24,]  8   5
[25,]  8   5
[26,]  8   5
[27,]  9   1
[28,] 10   1
JavaScript - Array splice() Method

Javascript array splice() method changes the content of an array, adding new elements while removing old elements.
Its syntax is as follows −
array.splice(index, howMany, [element1][, ..., elementN]);

index − Index at which to start changing the array.
index − Index at which to start changing the array.
howMany − An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.
howMany − An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.
element1, ..., elementN − The elements to add to the array. If you don't specify any elements, splice simply removes the elements from the array.
element1, ..., elementN − The elements to add to the array. If you don't specify any elements, splice simply removes the elements from the array.
Returns the extracted array based on the passed parameters.
Try the following example.
<html>
   <head>
      <title>JavaScript Array splice Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var arr = ["orange", "mango", "banana", "sugar", "tea"];         
         var removed = arr.splice(2, 0, "water");
         document.write("After adding 1: " + arr );
         document.write("<br />removed is: " + removed);
         
         removed = arr.splice(3, 1);
         document.write("<br />After adding 1: " + arr );
         document.write("<br />removed is: " + removed);
      </script>      
   </body>
</html>
After adding 1: orange,mango,water,banana,sugar,tea
removed is: 
After adding 1: orange,mango,water,sugar,tea
removed is: banana 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
KnockoutJS - Disable Binding

This binding is the negation of enable binding. This binding disables the associated DOM element when the parameter evaluates to true.
disable: <binding-value>

Parameter consists of Boolean like value, which decides whether the element should be disabled or not. If the parameter is true or true-like value, then the element is disabled.
Parameter consists of Boolean like value, which decides whether the element should be disabled or not. If the parameter is true or true-like value, then the element is disabled.
Non-Boolean values are considered as loosely Boolean values. Meaning 0 and null are considered as false-like value and Integer and non-null objects are considered as true-like value.
Non-Boolean values are considered as loosely Boolean values. Meaning 0 and null are considered as false-like value and Integer and non-null objects are considered as true-like value.
If the condition in parameter contains an observable value, then the condition is re-evaluated whenever the observable value changes. Correspondingly, related markup will be disabled based on the condition result.
If the condition in parameter contains an observable value, then the condition is re-evaluated whenever the observable value changes. Correspondingly, related markup will be disabled based on the condition result.
Let us take a look at the following example which demonstrates the use of disable binding.
<!DOCTYPE html>
   <head>
      <title>KnockoutJS Disable Binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p> Enter your feedback here:<br><br>
         <textarea rows = 5 data-bind = "value: hasFeedback, 
            valueUpdate: 'afterkeydown'" ></textarea>
      </p>
      
      <p><button data-bind = "disable: !(hasFeedback())">Save Feedback</button></p>

      <script type = "text/javascript">
         function ViewModel () {
            hasFeedback = ko.observable('');
         };

         var vm = new ViewModel();
         ko.applyBindings(vm);
      </script>
      
   </body>
</html>
Let's carry out the following steps to see how the above code works −
Save the above code in disable-bind.htm file.
Save the above code in disable-bind.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
The save button is disabled when the user has not entered any feedback.
The save button is disabled when the user has not entered any feedback.
 Enter your feedback here:

Save Feedback
You can also use a random expression to decide whether element should be disabled or not.

    38 Lectures 
     2 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
C++ Program to Perform Complex Number Multiplication

Complex numbers are numbers that are expressed as a+bi where i is an imaginary number and a and b are real numbers. Some examples on complex numbers are −
2+3i
5+9i
4+2i
A program to perform complex number multiplication is as follows −
 Live Demo
#include<iostream>
using namespace std;
int main(){
   int x1, y1, x2, y2, x3, y3;
   cout<<"Enter the first complex number : "<<endl;
   cin>> x1 >> y1;

   cout<<"\nEnter second complex number : "<<endl;
   cin>> x2 >> y2;
   x3 = x1 * x2 - y1 * y2;
   y3 = x1 * y2 + y1 * x2;
   cout<<"The value after multiplication is: "<<x3<<" + "<<y3<<" i ";
   return 0;
}
The output of the above program is as follows
Enter the first complex number : 2 1
Enter second complex number : 3 4
The value after multiplication is: 2 + 11 i
In the above program, the user inputs both the complex numbers. This is given as follows −
cout<<"Enter the first complex number : "<<endl;
cin>> x1 >> y1;

cout<<"\nEnter second complex number : "<<endl;
cin>> x2 >> y2;
The product of the two complex numbers is found by the required formula. This is given as follows −
x3 = x1 * x2 - y1 * y2;
y3 = x1 * y2 + y1 * x2;
Finally, the product is displayed. This is given below −
cout<<"The value after multiplication is: "<<x3<<" + "<<y3<<" i ";
SciPy Tutorial

SciPy is a scientific computation library that uses NumPy underneath.
SciPy stands for Scientific Python. 
We have created 10 tutorial pages for you to learn the fundamentals of SciPy:
Test your SciPy skills with a quiz test.
Start SciPy Quiz
Insert the correct syntax for printing the kilometer unit (in meters):
print(constants.);

Start the Exercise
In our "Try it Yourself" editor, you can use the SciPy module, and modify the code to see the result.
How many cubic meters are in one liter:
Click on the "Try it Yourself" button to see how it works.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to Convert a String value to Short value in Java with Examples - GeeksforGeeks

29 Jan, 2020
Given a String “str” in Java, the task is to convert this string to short type.
Examples:
Input: str = "1"
Output: 1

Input: str = "3"
Output: 3

Approach 1: (Naive Method)One method is to traverse the string and add the numbers one by one to the short type. This method is not an efficient approach.
Approach 2: (Using Short.parseShort() method)The simplest way to do so is using parseShort() method of Short class in java.lang package. This method takes the string to be parsed and returns the short type from it. If not convertible, this method throws error.
Syntax:
Short.parseShort(str);

Below is the implementation of the above approach:
Example 1: To show successful conversion
// Java Program to convert string to short  class GFG {      // Function to convert String to Short    public static short convertStringToShort(String str)    {          // Convert string to short        // using parseShort() method        return Short.parseShort(str);    }      // Driver code    public static void main(String[] args)    {          // The string value        String stringValue = "1";          // The expected short value        short shortValue;          // Convert string to short        shortValue = convertStringToShort(stringValue);          // Print the expected short value        System.out.println(            stringValue            + " after converting into short = "            + shortValue);    }}
1 after converting into short = 1

Approach 3: (Using Short.valueOf() method)The valueOf() method of Short class converts data from its internal form into human-readable form.
Syntax:
Short.valueOf(str);

Below is the implementation of the above approach:
Example 1: To show successful conversion
// Java Program to convert string to short  class GFG {      // Function to convert String to Short    public static short convertStringToShort(String str)    {          // Convert string to short        // using valueOf() method        return Short.valueOf(str);    }      // Driver code    public static void main(String[] args)    {          // The string value        String stringValue = "1";          // The expected short value        short shortValue;          // Convert string to short        shortValue = convertStringToShort(stringValue);          // Print the expected short value        System.out.println(            stringValue            + " after converting into short = "            + shortValue);    }}
1 after converting into short = 1

Java-Data Types
Java-Short
Java-String-Programs
Java-Strings
Java
Java Programs
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
cosh() function for complex number working with C++

Given the task is to show the working of cosh() function for complex numbers in C++.
The cosh() function is a part of the C++ standard template library. It is a little different from the standard cosh() function. Instead of calculating the hyperbolic cosines of angles that are in radians, it calculates the complex hyperbolic cosine values of complex numbers.
The mathematical formula for calculating complex hyperbolic cosine is −
cosh(z) = (e^(z) + e^(-z))/z
Where, “z” represents the complex number and “i” represents the iota.
The complex number should be declared as follows −
complex<double> name(a,b)
Here, <double> that is attached to the “complex” data type describes an object that stores ordered pair of objects, both of type “double’. Here the two objects are the real part and the imaginary part of the complex number that we want to enter. <complex> header file should be included to call the function for complex numbers.
The syntax is as follows −
cosh(complexnumber)
Input: complexnumber(5,5)
Output: <-27.0349,-3.85115>
Explanation − The following example shows how we use the cosh() function for calculating the complex hyperbolic cosine values of a complex number. Here 5 is the real part and another 5 is the imaginary part of the complex number as shown in the input, and the we get the hyperbolic cosine values in the output as we pass the complex number into the cosh() function.
Approach used in the below program as follows −
First declare a complex number, let’s say complexnumber(a,b)and then assign it a complex value.
Two values should be assigned to the variable complexnumber(a,b). The first value will be the real part of the complex number and the second value will be the imaginary part of the complex number.Let us say complexnumber(1, 3) so this will represent the complex number 1+3i.
Two values should be assigned to the variable complexnumber(a,b). The first value will be the real part of the complex number and the second value will be the imaginary part of the complex number.
Let us say complexnumber(1, 3) so this will represent the complex number 1+3i.
Now pass the complexnumber(1, 3)we created into the cosh() function
 Live Demo
#include<iostream>
#include<complex>
using namespace std;
int main() {
   complex<double> cno(1,3);
   cout<<cosh(cno);
   return 0;
}
If we run the above code it will generate the following output −
<-1.52764,0.165844>
Here 1 is the real part and 3 is the imaginary part of the complex number, as we pass our complex number into the cosh() function, we get the hyperbolic cosine values in the output as shown.
Diameter of Binary Tree in Python

Suppose we have a binary tree; we have to compute the length of the diameter of the tree. The diameter of a binary tree is actually the length of the longest path between any two nodes in a tree. This path not necessarily pass through the root. So if the tree is like below, then the diameter will be 3.as the length of the path [4,2,1,3] or [5,2,1,3] is 3
To solve this, we will follow these steps −
We will use the dfs to find the diameter, set answer := 0
call the dfs function with the root dfs(root)
dfs will work like below dfs(node)
if node is not present, then return 0
left := dfs(left subtree of root), and right := dfs(right subtree of root)
answer := max of answer and left + right
return max of left + 1 and right + 1
Let us see the following implementation to get better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def insert(temp,data):
   que = []
   que.append(temp)
   while (len(que)):
      temp = que[0]
      que.pop(0)
      if (not temp.left):
         temp.left = TreeNode(data)
         break
      else:
         que.append(temp.left)
      if (not temp.right):
         temp.right = TreeNode(data)
         break
      else:
         que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
class Solution(object):
   def diameterOfBinaryTree(self, root):
      """
      :type root: TreeNode
      :rtype: int
      """
      self.ans = 0
      self.dfs(root)
      return self.ans
   def dfs(self, node):
      if not node:
         return 0
      left = self.dfs(node.left)
      right = self.dfs(node.right)
      self.ans =max(self.ans,right+left)
      return max(left+1,right+1)
root = make_tree([1,2,3,4,5])
ob1 = Solution()
print(ob1.diameterOfBinaryTree(root))
[1,2,3,4,5]
3
Getting MIN and MAX dates in table in SAP Web Intelligence while using a Break

This can be achieved by creating an Indicator as per condition you are looking for- minimum drawn date time for POST-Test and Maximum drawn date time for PRE-Test.
 Once you create this indicator, it will show “Y” for the rows highlighted in yellow as per condition and “N” for other rows.
=If ([Drawn date] = Min([Drawn date]) In ([Patient ABO/RN])  Where ([PrePost] = "POST") )
 Or ([Drawn date] = Max([Drawn date]) In ([Patient ABO/RN])  Where ([PrePost] = "PRE")  )
 Then "Y" Else "N"
You need to apply a filter for rows with indicator value- “Y”.
Other option is you can create 3 variables as below −
Max Accession: =Max([Accession]) Where ([Variables].[Pre/Post] = "PRE") In ([Patient Birth Date])
Min Accession: =Min([Accession]) Where ([Variables].[Pre/Post] = "POST") In ([Patient Birth Date])
Accession Min/Max= If ([Accession]=[Min accession])Then 1 ElseIf ([Accession] = [Max accession]) Then 2 Else 0 (By using these, you will get 1 to the min accession, 2 to maximum and 0 to the rest of values in the report)
Then apply a filter with a condition to select values which are greater than 0.
How to create a password entry field using Tkinter?

Let us suppose we want to add an Entry widget which accepts user passwords. Generally, the passwords are displayed using “*” which yields to make the user credentials in an encrypted form.
We can create a password field using tkinter Entry widget.
In this example, we have created an application window that will accept the user password and a button to close the window.
#Import the required libraries
from tkinter import *

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

#Set the geometry of frame
win.geometry("600x250")

def close_win():
   win.destroy()

#Create a text label
Label(win,text="Enter the Password", font=('Helvetica',20)).pack(pady=20)

#Create Entry Widget for password
password= Entry(win,show="*",width=20)
password.pack()

#Create a button to close the window
Button(win, text="Quit", font=('Helvetica bold',
10),command=close_win).pack(pady=20)

win.mainloop()
Running the above code will display a window with an entry field that accepts passwords and a button to close the window.
Now, enter the password and click the “Quit” button to close the window.
How to use the <base> tag to define the base URL for an HTML page?

The HTML <base> tag is to display the base URL/target for all relative URLs. The tag comes inside the HTML <head>...</head> tag. You can set the base URL once at the top of your page in header section, and all subsequent relative links will use that URL as a starting point.
The following are the attributes of the HTML <base> tag −
You can try to run the following code to learn about the HTML <base> tag
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML base Tag</title>
      <base href = "http://www.tutorialspoint.com" />
   </head>
   <body>
      HTML: <br><img src = "/images/html.gif" />
   </body>
</html>
How to get the data type of a tensor in PyTorch?

A PyTorch tensor is homogenous, i.e., all the elements of a tensor are of the same data type. We can access the data type of a tensor using the ".dtype" attribute of the tensor. It returns the data type of the tensor.
Import the required library. In all the following Python examples, the required Python library is torch. Make sure you have already
installed it.
Import the required library. In all the following Python examples, the required Python library is torch. Make sure you have already
installed it.
Create a tensor and print it.
Create a tensor and print it.
Compute T.dtype. Here T is the tensor of which we want to get the data type.
Compute T.dtype. Here T is the tensor of which we want to get the data type.
Print the data type of the tensor.
Print the data type of the tensor.
The following Python program shows how to get the data type of a tensor.
# Import the library
import torch

# Create a tensor of random numbers of size 3x4
T = torch.randn(3,4)
print("Original Tensor T:\n", T)

# Get the data type of above tensor
data_type = T.dtype

# Print the data type of the tensor
print("Data type of tensor T:\n", data_type)
Original Tensor T:
tensor([[ 2.1768, -0.1328, 0.8155, -0.7967],
         [ 0.1194, 1.0465, 0.0779, 0.9103],
         [-0.1809, 1.8085, 0.8393, -0.2463]])
Data type of tensor T:
torch.float32
# Python program to get data type of a tensor
# Import the library
import torch

# Create a tensor of random numbers of size 3x4
T = torch.Tensor([1,2,3,4])
print("Original Tensor T:\n", T)

# Get the data type of above tensor
data_type = T.dtype

# Print the data type of the tensor
print("Data type of tensor T:\n", data_type)
Original Tensor T:
   tensor([1., 2., 3., 4.])
Data type of tensor T:
   torch.float32
How to get current foreground activity context in Android?

This example demonstrate about How to get current foreground activity context 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 src/MyApp.java
package app.tutorialspoint.com.sample ;
import android.app.Activity ;
import android.app.Application ;
public class MyApp extends Application {
   private Activity mCurrentActivity = null;
   @Override
   public void onCreate () {
      super .onCreate() ;
   }
   public Activity getCurrentActivity () {
      return mCurrentActivity ;
   }
   public void setCurrentActivity (Activity mCurrentActivity) {
      this . mCurrentActivity = mCurrentActivity ;
   }
}
Step 3 − Add the following code to src/MyBaseActivity.java
package app.tutorialspoint.com.sample ;
import android.app.Activity ;
import android.os.Bundle ;
import android.support.v7.app.AppCompatActivity ;
public class MyBaseActivity extends AppCompatActivity {
   protected MyApp mMyApp ;
   public void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState) ;
      mMyApp = (MyApp) this .getApplicationContext() ;
   }
   protected void onResume () {
      super .onResume() ;
      mMyApp .setCurrentActivity( this ) ;
   }
   protected void onPause () {
      clearReferences() ;
      super .onPause() ;
   }
   protected void onDestroy () {
      clearReferences() ;
      super .onDestroy() ;
   }
   private void clearReferences () {
      Activity currActivity = mMyApp .getCurrentActivity() ;
      if ( this .equals(currActivity))
         mMyApp .setCurrentActivity( null ) ;
   }
}
Step 4 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.app.Activity ;
import android.support.v7.app.AppCompatActivity ;
import android.os.Bundle ;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState) ;
      setContentView(R.layout. activity_main ) ;
      Activity currentActivity = ((MyApp)
      getApplicationContext()).getCurrentActivity() ;
   }
}
Step 5 − Add the following code to androidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
   package= "app.tutorialspoint.com.sample" >
   <uses-permission android :name= "android.permission.CALL_PHONE" />
   <application
      android :name= ".MyApp"
      android :allowBackup= "true"
      android :icon= "@mipmap/ic_launcher"
      android :label= "@string/app_name"
      android :roundIcon= "@mipmap/ic_launcher_round"
      android :supportsRtl= "true"
      android :theme= "@style/AppTheme" >
      <activity android :name= ".MainActivity" >
         <intent-filter>
            <action android :name= "android.intent.action.MAIN" />
            <category android :name= "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <activity android :name= ".MyBaseActivity" />
   </application>
</manifest>
Tryit Editor v3.7

CSS Style Images
Tryit: Center an image
queue::empty() and queue::size() in C++ STL

In this article we will be discussing the working, syntax and examples of queue::empty() and queue::size() functions in C++ STL.
Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue.
queue::empty() is an inbuilt function in C++ STL which is declared in  header file. queue::empty() is used to check whether the associated queue container is empty or not. This function returns either true or false, if the queue is empty (size is 0) then the function returns true, else if the queue is having some value then it will return false.
myqueue.empty();
This function accepts no parameter
This function returns true if the size of the associated queue container is 0, else will return false.
Input: queue<int> myqueue = {10, 20, 30, 40};
      myqueue.empty();
Output:
      False
Input: queue<int> myqueue;
      myqueue.empty();
Output:
      True
 Live Demo
#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   Queue.push(10);
   Queue.push(20);
   Queue.push(30);
   Queue.push(40);
   //check is queue is empty or not
   if (Queue.empty()){
      cout<<"Queue is empty";
   }
   else{
      cout <<"Queue is not empty";
   }
   return 0;
}
If we run the above code it will generate the following output −
Queue is not empty
queue::size() is an inbuilt function in C++ STL which is declared in <queue> header file. queue::size() is used to check whether the size of the associated queue container. This function returns an unsigned int value, i.e the size of the queue container, or the number of elements present in a queue container. This function returns 0 if the queue is empty or having no elements in it.
myqueue.size();
This function accepts no parameter
This function returns unsigned int, the size of the queue container associated with the function.
Input: queue<int> myqueue = {10, 20 30, 40};
      myqueue.size();
Output:
      4
Input: queue<int> myqueue;
      myqueue.size();
Output:
      0
 Live Demo
#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   Queue.push(10);
   Queue.push(20);
   Queue.push(30);
   Queue.push(40);
      cout<<"size of Queue is : "<<Queue.size();
   return 0;
}
If we run the above code it will generate the following output −
size of Queue is : 4
StringBuilder.Chars[] Property in C# - GeeksforGeeks

28 Jan, 2019
StringBuilder.Chars[Int32] Property is used to get or set the character at the specified character position in this instance.
Syntax: public char this[int index] { get; set; }Here, the index is the position of the character.
Property Value: This property returns the Unicode character at position index.
Exceptions:
ArgumentOutOfRangeException: If the index is outside the bounds of this instance while setting a character.
IndexOutOfRangeException: If the index is outside the bounds of this instance while getting a character.
Below programs illustrate the use of the above-discussed property:
Example 1:
// C# program demonstrate// the Chars[Int32] Propertyusing System;using System.Text;  class GFG {      // Main Method    public static void Main(String[] args)    {        // create a StringBuilder object        // with a String pass as parameter        StringBuilder str =          new StringBuilder("GeeksforGeeks");          // print string        Console.WriteLine("String is "                     + str.ToString());          // loop through string        // and print every Character        for (int i = 0; i < str.Length; i++) {              // get char at position i            char ch = str[i];              // print char            Console.WriteLine("Char at position "                              + i + " is " + ch);        }    }}
String is GeeksforGeeks
Char at position 0 is G
Char at position 1 is e
Char at position 2 is e
Char at position 3 is k
Char at position 4 is s
Char at position 5 is f
Char at position 6 is o
Char at position 7 is r
Char at position 8 is G
Char at position 9 is e
Char at position 10 is e
Char at position 11 is k
Char at position 12 is s

Example 2:
// C# program demonstrate// the Chars[Int32] Propertyusing System;using System.Text;  class GFG {      // Main Method    public static void Main(String[] args)    {        // create a StringBuilder object        StringBuilder str = new StringBuilder();          // add the String to StringBuilder Object        str.Append("Geek");          // get char at position 1        char ch = str[1];          // print the result        Console.WriteLine("StringBuilder Object"                        + " contains = " + str);          Console.WriteLine("Character at Position 1"                     + " in StringBuilder = " + ch);    }}
StringBuilder Object contains = Geek
Character at Position 1 in StringBuilder = e

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.chars?view=netframework-4.7.2
CSharp-StringBuilder-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
Draw Rectangle in C graphics - GeeksforGeeks

04 Oct, 2018
rectangle() is used to draw a rectangle. Coordinates of left top and right bottom corner are required to draw the rectangle. left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of right bottom corner, bottom specifies the Y-coordinate of right bottom corner.Syntax :
rectangle(int left, int top, int right, int bottom);

Examples:
Input : left = 150, top = 250, right = 450, bottom = 350;
Output : 


Input : left = 150, top = 150, right = 450, bottom = 450;
Output : 


Below is the implementation of the rectangle function :
// C program to draw a rectangle#include <graphics.h>  // Driver codeint main(){    // gm is Graphics mode which is a computer display    // mode that generates image using pixels.    // DETECT is a macro defined in "graphics.h" header file    int gd = DETECT, gm;      // location of left, top, right, bottom    int left = 150, top = 150;    int right = 450, bottom = 450;      // initgraph initializes the graphics system    // by loading a graphics driver from disk    initgraph(&gd, &gm, "");      // rectangle function    rectangle(left, top, right, bottom);      getch();      // closegraph function closes the graphics    // mode and deallocates all memory allocated    // by graphics system .    closegraph();      return 0;}
Output:


computer-graphics
square-rectangle
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fork() in C
Function Pointer in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
Substring in C++
Strings in C
UDP Server-Client implementation in C
C Program to read contents of Whole File
Arrow operator -> in C/C++ with Examples
Header files in C/C++ and its uses
How to retrieve specific file(s) information using Get-ChildItem in PowerShell?

When the item (file) path is provided to the Get-ChildItem cmdlet, it extracts the file information like Name, LastWriteTime, Size, etc.
Get-ChildItem -Path D:\Temp\style.css
Directory: D:\Temp

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       08-12-2017     10:16            393 style.css
To get the full properties of the file then you need to use fl * (Format-List *) pipeline command.
Get-ChildItem -Path D:\Temp\style.css | fl *

PSPath            : Microsoft.PowerShell.Core\FileSystem::D:\Temp\style.css
PSParentPath      : Microsoft.PowerShell.Core\FileSystem::D:\Temp
PSChildName       : style.css
PSDrive           : D
PSProvider        : Microsoft.PowerShell.Core\FileSystem
PSIsContainer     : False
Mode              : -a----
VersionInfo       : File:             D:\Temp\style.css
                    InternalName:
                    OriginalFilename:
                    FileVersion:
                    FileDescription:
                    Product:
                    ProductVersion:
                    Debug:            False
                    Patched:          False
                    PreRelease:       False
                    PrivateBuild:     False
                    SpecialBuild:     False
                    Language:

BaseName          : style
Target            : {}
LinkType          :
Name              : style.css
Length            : 393
DirectoryName     : D:\Temp
Directory         : D:\Temp
IsReadOnly        : False
Exists            : True
FullName          : D:\Temp\style.css
Extension         : .css
CreationTime      : 08-12-2017 10:02:17
CreationTimeUtc   : 08-12-2017 04:32:17
LastAccessTime    : 08-12-2017 10:02:17
LastAccessTimeUtc : 08-12-2017 04:32:17
LastWriteTime     : 08-12-2017 10:16:26
LastWriteTimeUtc  : 08-12-2017 04:46:26
Attributes        : Archive
You can get the specific properties by pipelining the Select-Object parameter. From the above example, we will display the File Name, attributes, extension, creation time, last access time and last write time.
Get-ChildItem D:\Temp\style.css | Select Name, Extension, CreationTime, LastAccessTime, LastWriteTime

Name           : style.css
Extension      : .css
CreationTime   : 08-12-2017 10:02:17
LastAccessTime : 08-12-2017 10:02:17
LastWriteTime  : 08-12-2017 10:16:26
Similarly, you can retrieve multiple files information in the same command. Each filename needs to be separated by comma (,).
PS D:\Temp> Get-ChildItem .\style.css, .\cars.xml