code-rag-bench/online-tutorials huggingface dataset:
Clojure - Vectors get

Returns the element at the index position in the vector.
Following is the syntax.
(get vec index)

Parameters − ‘vec’ is the set of elements in the vector. ‘index’ is the element at the index position which needs to be returned.
Return Value − The value of the element at the index position.
Following is an example of get in Clojure.
(ns clojure.examples.example
   (:gen-class))
(defn example []
   (println (get (vector 3 2 1) 2))
   (println (get (vector 3 2 1) 1)))
(example)
The above code produces the following output.
1
2

 Print
 Add Notes
 Bookmark this page
Comparison of double and float primitive types in Java


If we compare a float and a double value with .5 or .0 or .1235 (ending with 5 or 0), then == operator returns true, otherwise it will return false. See the below example.
Live Demo
public class Tester {
   public static void main(String[] args) {
      double d1 = 2.5;
      float f1 = 2.5f;
      System.out.println(d1 == f1);

      double d2 = 2.4;
      float f2 = 2.4f;
      System.out.println(d2 == f2);
   }
}
true
false
The reason behind this logic is the approximation of float and decimal. Float data type is a single-precision 32-bit IEEE 754 floating point and double data type is a double-precision 64-bit IEEE 754 floating point. A number ending with 5 or 0 can be represented exactly in both double and float.
In case of other numbers, it is similar to comparing 0.3333 to 0.33333333 where precision of later is high.
In order to compare double and float, check the difference of two to be greater than or less than a particular margin. See the example below.
Live Demo
public class Tester {
   public static void main(String[] args) {
      double d1 = 2.5;
      float f1 = 2.5f;

      System.out.println(d1 == f1);

      double d2 = 2.4;
      float f2 = 2.4f;
      double margin = 0.0000001;

      System.out.println(compareNumbers(d2, f2, margin));
   }  

   private static boolean compareNumbers(double d, float f, double margin) {
      if(Math.abs(d - f) < margin) {
         return true;
      }        
      return false;
   }
}
true
true
C++ Program to convert Decimal Numbers to Octal

In a computer system, the octal number is expressed in the octal numeral system while the decimal number is in the decimal numeral system. The octal number is in base 8 while the decimal number is in base 10.
Examples of decimal numbers and their corresponding octal numbers are as follows.
A program that converts the decimal numbers into octal is as follows.
 Live Demo
#include <iostream>
using namespace std;
void DecimalToOctal(int decimalNum) {
   int octalNum = 0, placeValue = 1;
   int dNo = decimalNum;
   while (decimalNum != 0) {
      octalNum += (decimalNum % 8) * placeValue;
      decimalNum /= 8;
      placeValue *= 10;
   }
   cout<<"Octal form of decimal number "<<dNo<<" is "<<octalNum<<endl;
}
int main() {
   DecimalToOctal(70);
   return 0;
}
Octal form of decimal number 70 is 106
In the above program, the function DecimalToOctal convert the decimal numbers into octal.In the function DecimalToOctal, initially the variable octalNum is initialized to zero. The variable placeValue denotes the location of the digit in the number. The value of octalNum is found using a while loop.
For each iteration of the while loop, the decimalNum is divided by 8 and the remainder is multiplied by placeValue. This is added to the previous value of octalNum. Also decimalNum is divided by 8 and the quotient is stored back. placeValue is multiplied by 10.
A code snippet that demonstrates this is as follows.
while (decimalNum != 0) {
   octalNum += (decimalNum % 8) * placeValue;
   decimalNum /= 8;
   placeValue *= 10;
}
After the Octal value i.e. octalNum is ovbtained, it is displayed. This is given below −
cout<<"Octal form of decimal number "<<dNo<<" is "<<octalNum<<endl;
The main() function only contains the function call to DecimalToOctal() with the required values. This is demonstrated by the following code snippet.
DecimalToOctal(70);
C++ Program to Perform Baillie-PSW Primality Test

The Baillie-PSW Primality Test, this test named after Robert Baillie, Carl Pomerance, John Selfridge, and Samuel Wagstaff. It is a test which tests whether a number is a composite number or possibly prime.
Begin
   Declare a function MillerTest of Boolean type.
   Declare MT_dt and MT_num of integer datatype and pass as the parameter.
   Declare MT_a and MT_x of integer datatype.
      Initialize MT_a = 2 + rand( ) % (MT_num - 4).
      Initialize MT_x = pow(MT_a, MT_dt, MT_num).
   if (MT_x == 1 || MT_x == MT_num - 1) then
      return true.
   while (MT_dt != MT_num - 1) do
      MT_x = (MT_x * MT_x) % MT_num.
      MT_dt *= 2.
      if (MT_x == 1) then
         return false;
      if (MT_x == MT_num - 1) then
         return true.
      return false.
End.
#include <iostream>
#include<stdlib.h>
using namespace std;
int pow(int pow_a, unsigned int pow_b, int pow_c) {
   int result = 1;
   pow_a = pow_a % pow_c;
   while (pow_b > 0) {
      if (pow_b & 1)
      result = (result * pow_a) % pow_c;
      pow_b = pow_b >> 1;
      pow_a = (pow_a * pow_a) % pow_c;
   }
   return result;
}
bool MiillerTest(int MT_dt, int MT_num) {
   int MT_a = 2 + rand( ) % (MT_num - 4);
   int MT_x = pow(MT_a, MT_dt, MT_num);
   if (MT_x == 1 || MT_x == MT_num - 1)
      return true;
   while (MT_dt != MT_num - 1) {
      MT_x = (MT_x * MT_x) % MT_num;
      MT_dt *= 2;
      if (MT_x == 1)
         return false;
      if (MT_x == MT_num - 1)
         return true;
   }
   return false;
}
bool prime(int P_N, int P_K) {
   if (P_N <= 1 || P_N == 4)
      return false;
   if (P_N <= 3)
      return true;
   int P_D = P_N - 1;
   while (P_D % 2 == 0)
      P_D /= 2;
   for (int i = 0; i < P_K; i++)
      if (MiillerTest(P_D, P_N) == false)
         return false;
      return true;
}
int main() {
   int iter = 50;
   long num1;
   long num2;
   cout<< "Enter the first number: ";
   cin>>num1;
   cout<<endl;
   if (prime(num1, iter))
      cout<<num1<<" is a prime number\n"<<endl;
   else
      cout<<num1<<" is a composite number\n"<<endl;
   cout<<"Enter another number: ";
   cin>>num2;
   cout<<endl;
   if (prime(num2, iter))
      cout<<num2<<" is a prime number\n"<<endl;
   else
      cout<<num2<<" is a composite number\n"<<endl;
   return 0;
}
Enter the first number: 23
23 is a prime number
Enter another number: 45
45 is a composite number
How to set a default colormap in Matplotlib?

To set a default colormap in matplotlib, we can take the following steps −
Create random data using numpy, array dimension 4×4.
Create random data using numpy, array dimension 4×4.
Create two axes and one figure using subplots() method.
Create two axes and one figure using subplots() method.
Display the data as an image with the default colormap.
Display the data as an image with the default colormap.
Set the title of the image, for the default colormap.
Set the title of the image, for the default colormap.
Set the default colormap using matplotlib rcParams.
Set the default colormap using matplotlib rcParams.
Display the data as an image, with set default colormap.
Display the data as an image, with set default colormap.
Set the title of the image, for the default colormap.
Set the title of the image, for the default colormap.
Adjust the padding between and around the subplots.
Adjust the padding between and around the subplots.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(4, 4)
fig, (ax1, ax2) = plt.subplots(2)
ax1.imshow(data)
ax1.set_title("Default colormap")
mpl.rc('image', cmap='RdYlBu_r')
ax2.imshow(data)
ax2.set_title("Set default colormap")
plt.show()
MySQL Tryit Editor v1.0

SELECT DATE_FORMAT("2017-06-15", "%Y");  
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
SOAP - Header

The optional Header element offers a flexible framework for specifying additional application-level requirements. For example, the Header element can be used to specify a digital signature for password-protected services. Likewise, it can be used to specify an account number for pay-per-use SOAP services.
It is an optional part of a SOAP message.
It is an optional part of a SOAP message.
Header elements can occur multiple times.
Header elements can occur multiple times.
Headers are intended to add new features and functionality.
Headers are intended to add new features and functionality.
The SOAP header contains header entries defined in a namespace.
The SOAP header contains header entries defined in a namespace.
The header is encoded as the first immediate child element of the SOAP envelope.
The header is encoded as the first immediate child element of the SOAP envelope.
When multiple headers are defined, all immediate child elements of the SOAP header are interpreted as SOAP header blocks.
When multiple headers are defined, all immediate child elements of the SOAP header are interpreted as SOAP header blocks.
A SOAP Header can have the following two attributes −
The SOAP protocol defines a message path as a list of SOAP service nodes. Each of these intermediate nodes can perform some processing and then forward the message to the next node in the chain. By setting the Actor attribute, the client can specify the recipient of the SOAP header.
It indicates whether a Header element is optional or mandatory. If set to true, the recipient must understand and process the Header attribute according to its defined semantics, or return a fault.
The following example shows how to use a Header in a SOAP message.
<?xml version = "1.0"?>
<SOAP-ENV:Envelope 
   xmlns:SOAP-ENV = " http://www.w3.org/2001/12/soap-envelope"   
   SOAP-ENV:encodingStyle = " http://www.w3.org/2001/12/soap-encoding">

   <SOAP-ENV:Header>
      <t:Transaction 
         xmlns:t = "http://www.tutorialspoint.com/transaction/" 
         SOAP-ENV:mustUnderstand = "true">5
      </t:Transaction>
   </SOAP-ENV:Header>
   ...
   ...
</SOAP-ENV:Envelope>

    8 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
MySQL-Connector-Python module in Python - GeeksforGeeks

09 Mar, 2020
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command.
In this article, we will be discussing the MySQL Connector module of Python, how to install this module and a piece of code on how to connect this with the MySQL database. For any application, it is very important to store the database on a server for easy data access.
MySQL Connector/Python enables Python programs to access MySQL databases, using an API that is compliant with the Python Database API Specification v2.0 (PEP 249). It is written in pure Python and does not have any dependencies except for the Python Standard Library.
There are various versions of MySQL Connector/Python available:
This module does not come built-in with Python. To install it type the below command in the terminal.
pip install mysql-connector-python

If any issue is there while installing, one can explicitly specify the module version as follows:
pip install mysql-connector-python==8.0.17
Also, to uninstall current MySQL Connector/Python, you use the following command:
pip uninstall mysql-connector-python
After installing the MySQL Python connector, we need to test it to make sure that it is working correctly and we are able to connect to the MySQL database server without any issues.
To verify the installation, we can use the following steps:
Open Python command line
Type the following code
import mysql.connector    mysql.connector.connect(host='localhost',                        database='database',                        user='root',                        password='your password')
Output:
If you see the following output, it means that you have been successfully installing the MySQL Connector/Python on your system.
Python-mySQL
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
C program to copy string without using strcpy() function

28 Nov, 2017
We can use inbuilt strcpy() function to copy one string to other but here, this program copies the content of one string to another manually without using strcpy() function.
Approach : Here we are giving one string in input and then with the help of for loop we transfer the content of first array to the second array.
Error : If destination string length is less than source string, entire string value won’t be copied into destination string.For example, consider destination string length is 20 and source string length is 30. Then, only 20 characters from source string will be copied into destination and remaining 10 characters will be truncated.
// CPP program to copy one string to other// without using in-built function  #include <stdio.h>int main(){    // s1 is the source( input) string and s2 is the destination string    char s1[] = "GeeksforGeeks", s2[100], i;      // Print the string s1    printf("string s1 : %s\n", s1);      // Execute loop till null found    for (i = 0; s1[i] != '\0'; ++i) {        // copying the characters by        // character to str2 from str1        s2[i] = s1[i];    }      s2[i] = '\0';      // printing the destination string    printf("String s2 : %s", s2);      return 0;}
Output:
string s1 : GeeksforGeeks
String s2 : GeeksforGeeks

C-String
cpp-string
C Language
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Python Dictionary
Reverse a string in Java
Introduction To PYTHON
Interfaces in Java
Object Oriented Programming in C++
PHP | Ds\Collection isEmpty() Function

21 Jan, 2019
The Ds\Collection::isEmpty() function is an inbuilt function in PHP which is used to returns whether collection is empty.
Syntax:
Ds\Collection::isEmpty ( void ) : bool
Parameters: This function does not accepts any parameters.
Return Value: It returns True if collection is empty or False otherwise.
Below programs illustrate the Ds\Collection::isEmpty() function in PHP:
Example 1:
<?php  // Create a collection$collection = new \Ds\Vector([10, 15, 21, 13, 16, 18]);  // Use isEmpty function$res = $collection->isEmpty();  // Display the resultvar_dump($res);  // Create a collection$collection = new \Ds\Vector();  // Use isEmpty function$res = $collection->isEmpty();  // Display the resultvar_dump($res);?>
Output:
bool(false) 
bool(true) 
Example 2:
<?php  // Create a collection$collection = new \Ds\Vector();  // display outputvar_dump($collection->isEmpty());  // Create a collection$collection = new \Ds\Vector([1, 3, 5, 2, 6]);  // Display outputvar_dump($collection->isEmpty());  ?>
Output:
bool(true) 
bool(false) 
Reference: http://php.net/manual/en/ds-collection.isempty.php
PHP-DS\Collection
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to use jQuery.closest() method with class selector?

The closest() method begins with the current element and returns only the first ancestors matching the passed expression. This returned jQuery object has zero or one element. Using the class selector is easy and let us see how to use it below.
You can try to run the following code to learn how to use jQuery.closest() method with class selector:
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.myclass * {
    display: block;
    border: 2px solid blue;
    color: red;
    padding: 5px;
    margin:10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
    $("span").closest(".one").css({"color": "maroon", "border": "5px solid maroon"});
  });
</script>
</head>

<body class="myclass">body
  <div style="width:500px;">div
    <ol>ol - This is the third ancestor
    <ol>ol - This is the second ancestor
      <li>li - This is the direct parent element
        <span>demo</span>
        <span class="one">demo - using class selector with closest() method</span>
      </li>
    </ol>
    </ol>  
  </div>
</body>
DAX Filter - EARLIEST function

Returns the current value of the specified column in an outer evaluation pass of the specified column.
EARLIEST (<column>) 

column
A reference to a column.
The current value of row, from column, at the outer evaluation pass.
The EARLIEST function is similar to EARLIER, in which you can also specify the level of recursion.
The Results of Earliest and Earlier functions will be the same, if the parameter number of Earlier function is omitted or is set to 1.
If you have a table Sales with sales data, you can create a calculated column with the ranks of the Sales Amount values as follows −
= COUNTROWS ( 
   FILTER (Sales, EARLIEST (Sales[Sales Amount])>Sales[Sales Amount])
)+1 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Create a caret arrow icon that represents dropdown button with Bootstrap

Use the .caret class in Bootstrap to create a caret arrow icon representing dropdown button.
You can try to run the following code to create a carot arrow icon −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
         <h2>Brands</h2>
         <p>The car brands:</p>
         <div class = "btn-group">
            <button type = "button" class = "btn dropdown-toggle" data-toggle = "dropdown">Car <span class="caret"></span></button>
            <ul class = "dropdown-menu" role = "menu">
               <li><a href = "#">BMW</a></li>
               <li><a href = "#">Toyota</a></li>
               <li><a href = "#">Audi</a></li>
               <li><a href = "#">Mahindra</a></li>
               <li><a href = "#">Volvo</a></li>
            </ul>
         </div>
      </div>
   </body>
</html>
Tryit Editor v3.7

Tryit: Text shadow on white text
Can we select row by DATEPART() in MySQL? Is it possible?

There is no DATEPART() function in MySQL, you need to use MONTH() function to extract the month name from date column. The syntax is as follows:
SELECT *FROM yourTableName WHERE MONTH(yourDateColumnName)=yourValue;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table SelectRowFromDatePart
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,  
   -> LoginDate date,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (2.42 sec)
Now you can insert some records in the table using insert command. The query is as follows:
mysql> insert into SelectRowFromDatePart(LoginDate) values(curdate());
Query OK, 1 row affected (0.21 sec)
mysql> insert into SelectRowFromDatePart(LoginDate) values(date_add(curdate(),interval -3 year));
Query OK, 1 row affected (0.19 sec)
mysql> insert into SelectRowFromDatePart(LoginDate) values('2014-05-21');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SelectRowFromDatePart(LoginDate) values('2015-08-25');
Query OK, 1 row affected (0.23 sec)
mysql> insert into SelectRowFromDatePart(LoginDate) values('2018-12-31');
Query OK, 1 row affected (0.18 sec)
mysql> insert into SelectRowFromDatePart(LoginDate) values('2011-12-21');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SelectRowFromDatePart(LoginDate) values('2013-10-02');
Query OK, 1 row affected (0.12 sec)
mysql> insert into SelectRowFromDatePart(LoginDate) values('2006-12-11');
Query OK, 1 row affected (0.17 sec)
mysql> insert into SelectRowFromDatePart(LoginDate) values('2010-03-09');
Query OK, 1 row affected (0.40 sec)
mysql> insert into SelectRowFromDatePart(LoginDate) values('2012-12-12');
Query OK, 1 row affected (0.70 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from SelectRowFromDatePart;
The following is the output:
+----+------------+
| Id | LoginDate  |
+----+------------+
|  1 | 2019-01-31 |
|  2 | 2016-01-31 |
|  3 | 2014-05-21 |
|  4 | 2015-08-25 |
|  5 | 2018-12-31 |
|  6 | 2011-12-21 |
|  7 | 2013-10-02 |
|  8 | 2006-12-11 |
|  9 | 2010-03-09 |
| 10 | 2012-12-12 |
+----+------------+
10 rows in set (0.00 sec)
Here is the query to select row by datepart, which is MONTH():
mysql> select *from SelectRowFromDatePart where MONTH(LoginDate)=12;
The following is the output:
+----+------------+
| Id | LoginDate  |
+----+------------+
|  5 | 2018-12-31 |
|  6 | 2011-12-21 |
|  8 | 2006-12-11 |
| 10 | 2012-12-12 |
+----+------------+
4 rows in set (0.00 sec)
C Program to find largest element in an array - GeeksforGeeks

18 Jul, 2021
Given an array, find the largest element in it.
Input : arr[] = {10, 20, 4}
Output : 20

Input : arr[] = {20, 10, 20, 4, 100}
Output : 100

C
// C program to find maximum in arr[] of size n #include <stdio.h>  // C function to find maximum in arr[] of size nint largest(int arr[], int n){    int i;         // Initialize maximum element    int max = arr[0];      // Traverse array elements from second and    // compare every element with current max      for (i = 1; i < n; i++)        if (arr[i] > max)            max = arr[i];      return max;}  int main(){    int arr[] = {10, 324, 45, 90, 9808};    int n = sizeof(arr)/sizeof(arr[0]);    printf("Largest in given array is %d", largest(arr, n));    return 0;}
Largest in given array is 9808
Please refer complete article on Program to find largest element in an array for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Hamming code Implementation in C/C++
C Hello World Program
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Difference between break and continue statement in C
Tryit Editor v3.7

Table Colspan & Rowspan
Tryit: HTML table - colspan
Sass - Passing Content Blocks to a Mixin

Block of styles is passed to the mixin for the placement inside the styles. In @content directive location, styles gets included into the mixin.
The block of content is evaluated in the scope, which is passed to a mixin where block is defined.
The following example demonstrates the use of passing content blocks to mixin in the SCSS file −
<html>
   <head>
      <title>Mixin example of sass</title>
      <link rel = "stylesheet" type = "text/css" href = "sample.css"/>
   </head>
   
   <body>
      <div class = "block">
         <h1>Example using passing content blocks</h1>
         <p>Different Colors</p>
         <ul>
            <li>Red</li>
            <li>Green</li>
            <li>Blue</li>
         </ul>
      </div>
   </body>
</html>
Next, create file sample.scss.
@mixin element {
   @content;
}

@include element {
   .block {
      color: green;
   }
}
You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −
sass --watch C:\ruby\lib\sass\sample.scss:sample.css

Next, execute the above command; it will create the sample.css file automatically with the following code −
.block {
   color: green;
}
Let us carry out the following steps to see how the above given code works −
Save the above given html code in pass_content.scss file.
Save the above given html code in pass_content.scss file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.

    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
How to return a json object from a Python function?

We return a json object from a python function as follows using given python dictionary.
import json
a = {'name':'Sarah', 'age': 24, 'isEmployed': True }
# a python dictionary
def retjson():
python2json = json.dumps(a)
print python2json
retjson()
{"age": 24, "isEmployed": true, "name": "Sarah"}
Crystal Reports - If Then Else

The if-then-Else statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular condition meets true.
If you see the following If-Then-Else statement with Boolean operators, it has allowed you to pass multiple conditions in the formula and returning the value, if the condition is true.
If({PROJECT.Customer\Customer Name} [1 to 2] = "An" and
ToText({PROJECT.Time\Year}) [1] = "2") or
({Project.Customer\CUSTOMER NAME} [1 to 2] = "Ja" and
ToText({PROJECT.Time\Year}) [1] = "2") Then
"Five star rating CUSTOMER"
Else
"1 star rating CUSTOMER"
This statement says that when any of the condition is true (before and after OR operator), then it will print Five star rating customer otherwise it will print 1 star rating customer.
This formula has been saved and then added to the body of the report under the structure tab as shown in the following images −
A new column in the report has been added with the rating of the customers as mentioned in the TEST formula.

    37 Lectures 
     2 hours 

 Neha Gupta

    61 Lectures 
     4.5 hours 

 Sasha Miller

    31 Lectures 
     32 mins

 Prof Krishna N Sharma

    35 Lectures 
     2 hours 

 Prof Krishna N Sharma

    24 Lectures 
     2 hours 

 Prof Krishna N Sharma
 Print
 Add Notes
 Bookmark this page
Functional Programming - Default Methods

Java 8 introduces a new concept of default method implementation in interfaces. This capability is added for backward compatibility so that old interfaces can be used to leverage the lambda expression capability of Java 8.
For example, 'List' or 'Collection' interfaces do not have 'forEach' method declaration. Thus, adding such method will simply break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same.
public interface vehicle {

   default void print() {
      System.out.println("I am a vehicle!");
   }
}

With default functions in interfaces, there is a possibility that a class is implementing two interfaces with same default methods. The following code explains how this ambiguity can be resolved.
public interface vehicle {

   default void print() {
      System.out.println("I am a vehicle!");
   }
}

public interface fourWheeler {

   default void print() {
      System.out.println("I am a four wheeler!");
   }
}
First solution is to create an own method that overrides the default implementation.
public class car implements vehicle, fourWheeler {

   public void print() {
      System.out.println("I am a four wheeler car vehicle!");
   }
}
Second solution is to call the default method of the specified interface using super.
public class car implements vehicle, fourWheeler {

   default void print() {
      vehicle.super.print();
   }
}
An interface can also have static helper methods from Java 8 onwards.
public interface vehicle {

   default void print() {
      System.out.println("I am a vehicle!");
   }
	
   static void blowHorn() {
      System.out.println("Blowing horn!!!");
   }
}
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
public class Java8Tester {

   public static void main(String args[]) {
      Vehicle vehicle = new Car();
      vehicle.print();
   }
}

interface Vehicle {

   default void print() {
      System.out.println("I am a vehicle!");
   }
	
   static void blowHorn() {
      System.out.println("Blowing horn!!!");
   }
}

interface FourWheeler {

   default void print() {
      System.out.println("I am a four wheeler!");
   }
}

class Car implements Vehicle, FourWheeler {

   public void print() {
      Vehicle.super.print();
      FourWheeler.super.print();
      Vehicle.blowHorn();
      System.out.println("I am a car!");
   }
}
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java

Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester

It should produce the following output −
I am a vehicle!
I am a four wheeler!
Blowing horn!!!
I am a car!


    32 Lectures 
     3.5 hours 

 Pavan Lalwani

    11 Lectures 
     1 hours 

 Prof. Paul Cline, Ed.D

    72 Lectures 
     10.5 hours 

 Arun Ammasai

    51 Lectures 
     2 hours 

 Skillbakerystudios

    43 Lectures 
     4 hours 

 Mohammad Nauman

    8 Lectures 
     1 hours 

 Santharam Sivalenka
 Print
 Add Notes
 Bookmark this page
IntSummaryStatistics getSum() method in Java with Examples - GeeksforGeeks

28 Jun, 2019
The getSum() method of IntSummaryStatistics class in Java is used to get the sum of records in this IntSummaryStatistics.
Syntax:
public long getSum()

Parameter: This method do not accept any value as parameter.
Return Value: This method returns the sum of the records in this IntSummaryStatistics.
Program:
// Java program to demonstrate// the above method  import java.util.*;  public class IntSummaryStatisticsDemo {    public static void main(String[] args)    {          IntSummaryStatistics intSummaryStatistics            = new IntSummaryStatistics();          List<Integer> list            = Arrays.asList(10, 20, 30, 40, 50);          Iterator<Integer> iterator = list.listIterator();        while (iterator.hasNext()) {              // Add the integers to the IntSummaryStatistics object            intSummaryStatistics.accept(iterator.next());        }          System.out.println("The sum of values is "                           + intSummaryStatistics.getSum());    }}
The sum of values is 150

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/IntSummaryStatistics.html#getSum()
Java - util package
Java-Functions
Java-IntSummaryStatistics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
Gii - Generating Controller

Let us see how to generate a Controller.
Step 1 − To generate a controller with several actions, open the controller generator interface fill in the form.
Step 2 − Then, click the “Preview” button and “Generate”. The CustomController.php file with index, hello, and world actions will be generated in the controllers folder.
<?php
   namespace app\controllers;
   class CustomController extends \yii\web\Controller {
      public function actionHello() {
         return $this->render('hello');
      }
      public function actionIndex() {
         return $this->render('index');
      }
      public function actionWorld() {
         return $this->render('world');
      }
   }
?>
Step 1 − To generate a view file from an existing model, open the form generation interface and fill in the form.
Then, click the “Preview” button and “Generate”. The customview view file will be generated in the view folder.
Step 2 − To display it, add a new method to the CustomController.
public function actionView() {
   $model = new MyUser();
   return $this->render('/customview', [
      'model' => $model,
   ]);
}
Step 3 − To see the generated view file, open the URL http://localhost:8080/index.php?r=custom/view.
 Print
 Add Notes
 Bookmark this page
How to copy or clone a Java ArrayList?

The clone() method of the java.util.ArrayList class returns a shallow copy of this ArrayList instance (i.e the elements themselves are not copied). Using this method, you can copy the contents of one array list to other.
import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String args[]) {
      ArrayList<StringBuilder> arrlist1 = new ArrayList<StringBuilder>();
      arrlist1.add(new StringBuilder("Learning-"));
      ArrayList arrlist2 = (ArrayList) arrlist1.clone();
      StringBuilder strbuilder = arrlist1.get(0);
      strbuilder.append("list1, list2-both pointing to the same StringBuilder");
      System.out.println("The 1st list prints: ");
      for (int i = 0; i < arrlist1.size(); i++) {
         System.out.print(arrlist1.get(i) + " ");
      }
      System.out.println("The 2nd list prints the same i.e:");
      for (int i = 0; i < arrlist2.size(); i++) {
         System.out.print(arrlist2.get(i));
      }
   }
}
The 1st list prints:
Learning-list1, list2 - both pointing to the same StringBuilder
The 2nd list prints the same i.e:
Learning-list1, list2 - both pointing to the same StringBuilder
Cypress - Plugins

Cypress has multiple plugins to add to its features. There are multiple types of plugins like the authentication, component testing, custom commands, development tools and so on.
Some of the prominent plugins include −
To perform file upload task in Cypress, we have to first install a plugin with the command mentioned below −
npm install –dev cypress-file-upload

Once the installation is done, we have to add the statement import 'cypress-file-upload' in the command.js file, which resides inside the support folder within the Cypress project.
To work with frames, first, we have to install the Cypress plugin for frames with the command given below −
npm install –D cypress-iframe

Then, we have to add the statement import 'cypress-iframe' in the code.
To identify elements with xpath locator, run the following command −
npm install cypress-xpath

Once the installation is done, we have to add the statement require ("cypress-xpath") within the index.js file, which resides inside the support folder within the Cypress project.
Also, we have to use the cy.xpath command to identify elements.
To enable themes, we have to install a plugin with the command mentioned below −
npm install --save-dev cypress-dark

Once the installation is done, we have to add the statement require ("cypress-dark") within
the index.js file, which resides inside the support folder within the Cypress project.

    73 Lectures 
     12 hours 

 Rahul Shetty
 Print
 Add Notes
 Bookmark this page
How to remove the icon from the title bar in Tkinter?

To remove the default icon of the Tkinter window, we can use wm_attributes('type', 'value') method by specifying the type of property. In the following example, we will use '-toolwindow', a Boolean value that removes the icon associated with the title bar of the application.
#Import the tkinter library
from tkinter import *

#Create an instance of tkinter frame
win = Tk()
win.geometry("700x350")

#Create a Label to print the Name
label= Label(win, text="This is a New Line Text", font= ('Helvetica 14 bold'), foreground= "red3")
label.pack()

win.wm_attributes('-toolwindow', 'True')
win.mainloop()
When we run the above code, it will display a Tkinter window without its default icon on the title bar.
How can I render 3D histograms in Python using Matplotlib?

To render 3D histograms in Python, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Add an axes to the cureent figure as a subplot arrangement.
Add an axes to the cureent figure as a subplot arrangement.
Create x3, y3 and z3 data points using numpy.
Create x3, y3 and z3 data points using numpy.
Create dx, dy and dz data points using numpy.
Create dx, dy and dz data points using numpy.
Use bar3d() method to plot 3D bars.
Use bar3d() method to plot 3D bars.
To hide the axes use axis('off') class by name.
To hide the axes use axis('off') class by name.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()

ax1 = fig.add_subplot(111, projection='3d')

x3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y3 = [5, 6, 7, 8, 2, 5, 6, 3, 7, 2]
z3 = np.zeros(10)

dx = np.ones(10)
dy = np.ones(10)
dz = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

ax1.bar3d(y3, x3, z3, dx, dy, dz, color="red")
ax1.axis('off')
plt.show()
MoviePy – Concatenating multiple Video Files

31 Oct, 2021
In this article, we will see how we can concatenate multiple video file clips in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of “snow” and “ball” is “snowball”, similarly concatenating multiple videos clips means that they will get played one after another and act as a single video file.Note: The clips do not need to be the same size. If they aren’t of the same size they will all appear centered in a clip large enough to contain the biggest of them. 
In order to do this we will use concatenate_videoclips method Syntax : concatenate_videoclips(clips)Argument : It takes list of video file clips as argument Return : It returns VideoFileClip object  
Below is the implementation 
Python3
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm") # getting subclip as video is largeclip1 = clip.subclip(0, 5) # getting subclip as video is largeclip2 = clip.subclip(60, 65) # concatenating both the clipsfinal = concatenate_videoclips([clip1, clip2])#writing the video into a file / saving the combined videofinal.write_videofile("merged.webm") # showing final clipfinal.ipython_display(width = 480)
Output : 
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Another example:
Python3
# Import everything needed to edit video clipsfrom moviepy.editor import * # loading video dsa gfg intro videoclip = VideoFileClip("dsa_geek.webm") # getting subclip as video is largeclip1 = clip.subclip(0, 5)  # loading video gfgclipx = VideoFileClip("geeks.mp4") # getting subclipclip2 = clipx.subclip(0, 5) # clip listclips = [clip1, clip2] # concatenating both the clipsfinal = concatenate_videoclips(clips) # showing final clipfinal.ipython_display(width = 480)
Output : 
Moviepy - Building video __temp__.mp4.
MoviePy - Writing audio in __temp__TEMP_MPY_wvf_snd.mp3
                                                                                                                       
MoviePy - Done.
Moviepy - Writing video __temp__.mp4

                                                                                                                       
Moviepy - Done !
Moviepy - video ready __temp__.mp4
anikaseth98
shashankkadiwal2000
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ | Operator Overloading | Question 5

16 Apr, 2021
How does C++ compiler differs between overloaded postfix and prefix operators?(A) C++ doesn’t allow both operators to be overloaded in a class(B) A postfix ++ has a dummy parameter(C) A prefix ++ has a dummy parameter(D) By making prefix ++ as a global function and postfix as a member function.Answer: (B)Explanation: See the following example:
class Complex
{
private:
    int real;
    int imag;
public:
    Complex(int r, int i)  {  real = r;   imag = i; }
    Complex operator ++(int);
    Complex & operator ++();
};

Complex &Complex::operator ++()
{
    real++; imag++;
    return *this;
}

Complex Complex::operator ++(int i)
{
    Complex c1(real, imag);
    real++; imag++;
    return c1;
}

int main()
{
    Complex c1(10, 15);
    c1++; 
    ++c1;
    return 0;
}
Quiz of this Question
arorakashish0911
C++-Operator Overloading
Operator Overloading
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Remove Invalid Parentheses from an Expression

Given a parentheses sequence; now, you have to print all the possible parentheses that it can make by removing the invalid brackets, for example
Input : str = “()())()” -
Output : ()()() (())()
There are two possible solutions
"()()()" and "(())()"

Input : str = (v)())()
Output : (v)()() (v())()
In this problem, we are going to use backtracking so that it will print all the valid sequences.
In this approach, we will be trying to remove the opening and closing brackets one by one using BFS. Now for each sequence, we check if it is valid or not. If it is valid, then we print it as our output.
 
#include <bits/stdc++.h>
using namespace std;
bool isParenthesis(char c){
    return ((c == '(') || (c == ')'));
}
bool validString(string str){
    // cout << str << " ";
    int cnt = 0;
    for (int i = 0; i < str.length(); i++){
        if (str[i] == '(')
           cnt++;
        else if (str[i] == ')')
           cnt--;
        if (cnt < 0)
           return false;
    }
    // cout << str << " ";
    return (cnt == 0);
}
void validParenthesesSequences(string str){
    if (str.empty())
        return ;
    set<string> visit; // if we checked that sting so we put it inside visit
                      // so that we will not encounter that string again
    queue<string> q; // queue for performing bfs
    string temp;
    bool level;
    // pushing given string as starting node into queue
    q.push(str);
    visit.insert(str);
    while (!q.empty()){
        str = q.front(); q.pop();
        if (validString(str)){
        //    cout << "s";
            cout << str << "\n"; // we print our string
            level = true; // as we found the sting on the same level so we don't need to apply bfs from it
        }
        if (level)
            continue;
        for (int i = 0; i < str.length(); i++){
            if (!isParenthesis(str[i])) // we won't be removing any other characters than the brackets from our string
                continue;
            temp = str.substr(0, i) + str.substr(i + 1); // removing parentheses from the strings one by one
            if (visit.find(temp) == visit.end()) { // if we check that string so we won't check it again
                q.push(temp);
                visit.insert(temp);
            }
        }
    }
}
int main(){
    string s1;
    s1 = "(v)())()";
    cout << "Input : " << s1 << "\n";
    cout << "Output : ";
    validParenthesesSequences(s1);
    return 0;
}
Input : (v)())()
Output : (v())()
In the above approach, we simply one by one remove our parentheses now as we can the bracket we also keep track of the previous sequences so that we won’t check the same sequence twice now if we find a valid sequence out of these all possibilities, we print all the valid possibilities and that’s how our program proceeds.
In this tutorial, we solve a problem to find Remove Invalid Parentheses. We also learned the C++ program for this problem and the complete approach (Normal) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this tutorial helpful.
get_class() function in PHP

The get_class() function gets the name of the class of an object. It returns FALSE if object is not an object. If object is excluded when inside a class, the name of that class is returned.
get_class(object)
object  − The tested object. You can avoid this parameter inside the cass.
object  − The tested object. You can avoid this parameter inside the cass.
The get_class() function returns the name of the class of an object. It returns FALSE if object is not an object. If object is excluded when inside a class, the name of that class is returned.
The following is an example −
 Live Demo
<?php
class Demo {
   function Demo() {
}
function name() {
   echo "Internal call: " , get_class($this) , "\n";
   }
}
// create an object $two = new Demo();
// external call echo "External call: " , get_class($two) , "\n";
// internal call
$two->name();
?>
External call: Demo
Internal call: Demo
How to append text to a text file in C++?

This is a C++ program to append text to a text file.
Begin
   Open that file a1.txt as output file stream class object to perform
   output operation in append mode using fout file reference.
   If the file exists then
      Appending text to that file.
   Close fout.
   Open the file “a1.txt” for reading the content of the file.
   Extracting the text from file and printing the text.
End.
 Live Demo
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main() {
   fstream f;
   ofstream fout;
   ifstream fin;
      fin.open("a1.txt");
      fout.open ("a1.txt",ios::app);
   if(fin.is_open())
      fout<<" tutorials point";
      cout<<"\n Data has been appended to file"<<endl;
      fin.close();
      fout.close();
      string word;
      f.open("a1.txt");
      while (f >> word) {
         cout << word << " ";
      }
      return 0;
}
Data has been appended to file