code-rag-bench/online-tutorials huggingface dataset:
How do I convert between big-endian and little-endian values in C++?

Here we will see how to convert Little endian value to Big endian or big endian value to little endian in C++. Before going to the actual discussion, we will see what is the big endian and the little endian?
In different architectures, the multi-byte data can be stored in two different ways. Sometimes the higher order bytes are stored first, in that case these are known as big endian, and sometimes the lower order bytes are stored first, then it is called little endian.
For example, if the number is 0x9876543210, then the big endian will be −
The little endian will be like this −
In this section we will see how to convert little endian to big endian and vice versa. To do this we have to interchange the 1st and 4th bytes, and 2nd and 3rd bytes. We can interchange them using logical expressions. Make Copy of the number four times, then for the first copy, shift the 1st byte 24 times to the right, for the second copy, mask it with 00FF0000, then swap 8 bits to the right, for the 3rd copy mask it with 0000FF00, then shift left 8 bits, and for the last copy swap the elements to the left 24 times. Then Logically OR these four copies to get the reversed result.
#include <iostream>
#define SWAP_INT32(x) (((x) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | ((x) << 24)) using namespace std;
void memory_represent(char *value, int n) {
   int i;
   for (i = 0; i < n; i++)
      printf(" %.2x", value[i]);
}
int main() {
   unsigned int x = 0x9876543210;
   int y;
   cout << "The little endian value is: ";
   memory_represent((char*)&x, sizeof(x));
   cout << endl;
   y = SWAP_INT32(x);
   cout << "The Big endian value after conversion is: ";
   memory_represent((char*)&y, sizeof(y));
   cout << endl;
}
The little endian value is: 10 32 54 76
The Big endian value after conversion is: 76 54 32 10
How to override only few methods of interface in Java?

Once you implement an interface from a concrete class you need to provide implementation to all its methods. If you try to skip implementing methods of an interface at compile time an error would be generated.
 Live Demo
interface MyInterface{
   public void sample();
   public void display();
}
public class InterfaceExample implements MyInterface{
   public void sample(){
      System.out.println("Implementation of the sample method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.sample();
   }
}
InterfaceExample.java:5: error: InterfaceExample is not abstract and does not override abstract method display() in MyInterface
public class InterfaceExample implements MyInterface{
       ^
1 error
But, If you still need to skip the implementation.
You can either provide a dummy implementation to the unwanted methods by throwing an exception such as UnsupportedOperationException or, IllegalStateException from them.
 Live Demo
interface MyInterface{
   public void sample();
   public void display();
}
public class InterfaceExample implements MyInterface{
   public void sample(){
      System.out.println("Implementation of the sample method");
   }
   public void display(){
      throw new UnsupportedOperationException();
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.sample();
      obj.display();
   }
}
Implementation of the sample method
Exception in thread "main" java.lang.UnsupportedOperationException
at InterfaceExample.display(InterfaceExample.java:10)
at InterfaceExample.main(InterfaceExample.java:15)
You can make the methods default in the interface itself, Default methods are introduced in interfaces since Java8 and if you have default methods in an interface it is not mandatory to override them in the implementing class.
 Live Demo
interface MyInterface{
   public void sample();
   default public void display(){
      System.out.println("Default implementation of the display method");
   }
}
public class InterfaceExample implements MyInterface{
   public void sample(){
      System.out.println("Implementation of the sample method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.sample();
      obj.display();
   }
}
Implementation of the sample method
Default implementation of the display method
Ansible - Ad hoc Commands

Ad hoc commands are commands which can be run individually to perform quick functions. These commands need not be performed later.
For example, you have to reboot all your company servers. For this, you will run the Adhoc commands from ‘/usr/bin/ansible’.
These ad-hoc commands are not used for configuration management and deployment, because these commands are of one time usage.
ansible-playbook is used for configuration management and deployment.
Reboot your company server in 12 parallel forks at time. For this, we need to set up SSHagent for connection.
$ ssh-agent bash 
$ ssh-add ~/.ssh/id_rsa 

To run reboot for all your company servers in a group, 'abc', in 12 parallel forks −
$ Ansible abc -a "/sbin/reboot" -f 12

By default, Ansible will run the above Ad-hoc commands form current user account. If you want to change this behavior, you will have to pass the username in Ad-hoc commands as follows −
$ Ansible abc -a "/sbin/reboot" -f 12 -u username

You can use the Ad-hoc commands for doing SCP (Secure Copy Protocol) lots of files in parallel on multiple machines.
$ Ansible abc -m copy -a "src = /etc/yum.conf dest = /tmp/yum.conf"

$ Ansible abc -m file -a "dest = /path/user1/new mode = 777 owner = user1 group = user1 state = directory" 

$ Ansible abc -m file -a "dest = /path/user1/new state = absent"

The Ad-hoc commands are available for yum and apt. Following are some Ad-hoc commands using yum.
The following command checks if yum package is installed or not, but does not update it.
$ Ansible abc -m yum -a "name = demo-tomcat-1 state = present"

The following command check the package is not installed.
$ Ansible abc -m yum -a "name = demo-tomcat-1 state = absent" 

The following command checks the latest version of package is installed.
$ Ansible abc -m yum -a "name = demo-tomcat-1 state = latest" 

Facts can be used for implementing conditional statements in playbook. You can find adhoc information of all your facts through the following Ad-hoc command −
$ Ansible all -m setup 


    41 Lectures 
     5 hours 

 AR Shankar

    11 Lectures 
     58 mins

 Musab Zayadneh

    59 Lectures 
     15.5 hours 

 Narendra P

    11 Lectures 
     1 hours 

 Sagar Mehta

    39 Lectures 
     4 hours 

 Vikas Yadav

    4 Lectures 
     3.5 hours 

 GreyCampus Inc.
 Print
 Add Notes
 Bookmark this page
MySQL query to extract first word from a field?

To extract first word from a field, use in-built SUBSTRING_INDEX() function. The syntax is as follows −
SELECT SUBSTRING_INDEX(yourColumnName,’ ‘,1) as anyVariableName from yourTableName;
In the above query, if you use -1 in place of 1 then you will get the last word. To understand the above concept, let us create a table. The following is the query to create a table.
mysql> create table FirstWordDemo
   −> (
   −> AllWords longtext
   −> );
Query OK, 0 rows affected (0.83 sec)
Now insert some words in the table using insert command. The query is as follows −
mysql> insert into FirstWordDemo values('This is the first MySQL Query');
Query OK, 1 row affected (0.11 sec)

mysql> insert into FirstWordDemo values('MySQL is a Relational Database');
Query OK, 1 row affected (0.17 sec)

mysql> insert into FirstWordDemo values('FirstWord is not correct');
Query OK, 1 row affected (0.21 sec)
Now display all records from the table using select statement. The query is as follows −
mysql> select *from FirstWordDemo;
The following is the output −
+--------------------------------+
| AllWords                       |
+--------------------------------+
| This is the first MySQL Query  |
| MySQL is a Relational Database |
| FirstWord is not correct       |
+--------------------------------+
3 rows in set (0.00 sec)
Here is the query to get first word from a field. We discussed the same syntax in the beginning.
The following is the query −
mysql> select SUBSTRING_INDEX(AllWords, ' ', 1) as MyFirstWordResult from FirstWordDemo;
The following is the output −
+-------------------+
| MyFirstWordResult |
+-------------------+
| This              |
| MySQL             |
| FirstWord         |
+-------------------+
3 rows in set (0.00 sec)
Convert a 1D array to a 2D Numpy array

13 Jan, 2021
Numpy is a Python package that consists of multidimensional array objects and a collection of operations or routines to perform various operations on the array and processing of the array. This package consists of a function called numpy.reshape which is used to convert a 1-D array into a 2-D array of required dimensions (n x m).  This function gives a new required shape without changing the data of the 1-D array.
Syntax: numpy.reshape(array, new_shape, order) 
Parameters:
 array: is the given 1-D array that will be given a new shape or converted into 2-D array
new_shape: is the required shape or 2-D array having int or tuple of int
order: ‘C’ for C style, ‘F’ for Fortran style, ‘A’ if data is in Fortran style then Fortran like order else C style.
Examples 1:
Python3
import numpy as np# 1-D array having elements [1 2 3 4 5 6 7 8]arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])  # Print the 1-D arrayprint ('Before reshaping:')print (arr)print ('\n')  # Now we can convert this 1-D array into 2-D in two ways  # 1. having dimension 4 x 2arr1 = arr.reshape(4, 2)print ('After reshaping having dimension 4x2:')print (arr1)print ('\n')  # 2. having dimension 2 x 4arr2 = arr.reshape(2, 4)print ('After reshaping having dimension 2x4:')print (arr2)print ('\n')
Output:
Before reshaping:
[1 2 3 4 5 6 7 8]
After reshaping having dimension 4x2:
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
After reshaping having dimension 2x4:
[[1 2 3 4]
 [5 6 7 8]]
Example 2: Let us see an important observation that whether we can reshape a 1-D array into any 2-D array.
Python3
import numpy as np# 1-D array having elements [1 2 3 4 5 6 7 8]arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])  # Print the 1-D arrayprint('Before reshaping:')print(arr)print('\n')  # let us try to convert into 2-D array having dimension 3x3arr1 = arr.reshape(3, 3)print('After reshaping having dimension 3x3:')print(arr1)print('\n')
Output:
This concludes that the number of elements should be equal to the product of dimension i.e. 3×3=9 but total elements = 8;
Example 3: Another example is that we can use the reshape method without specifying the exact number for one of the dimensions. Just pass -1 as the value and NumPy will calculate the number.
Python3
import numpy as np# 1-D array having elements [1 2 3 4 5 6 7 8]arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])  # Print the 1-D arrayprint('Before reshaping:')print(arr)print('\n')    arr1 = arr.reshape(2, 2, -1)print('After reshaping:')print(arr1)print('\n')
Output:
Before reshaping:
[1 2 3 4 5 6 7 8]
After reshaping:
[[[1 2]
 [3 4]]
[[5 6]
 [7 8]]]
Picked
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove portion of a string after a certain character in PHP?

21 Feb, 2019
The substr() and strpos() function is used to remove portion of string after certain character.strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string. Function treats upper-case and lower-case characters differently.
Syntax:
strpos( original_string, search_string, start_pos )
Return Value: This function returns an integer value which represents the index of original_str where the string search_str first occurs.
substr() function: The substr() function is an inbuilt function in PHP is used to extract a specific part of string.
Syntax:
substr( string_name, start_position, string_length_to_cut )
Return Value: Returns the extracted part of the string if successful otherwise FALSE or an empty string on failure.Here are few examples.
Below examples use substr() and strpos() function to remove portion of string after certain character.
Example 1:
<?php  // Declare a variable and initialize it$variable = "GeeksForGeeks is the best platform.";  // Display value of variableecho $variable;echo "\n";  // Use substr() and strpos() function to remove// portion of string after certain character$variable = substr($variable, 0, strpos($variable, "is"));  // Display value of variableecho $variable;  ?>
GeeksForGeeks is the best platform.
GeeksForGeeks

Example 2:
<?php  // Declare a variable and initialize it$variable = "computer science portal for geeks";  // Display value of variableecho $variable;echo "\n";  // Use substr() and strpos() function to remove// portion of string after certain character// and display itecho substr($variable, 0, strpos($variable, "for"));  ?>
computer science portal for geeks
computer science portal

Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2011 | Question 7

28 Jun, 2021
A company needs to develop digital signal processing software for one of its newest inventions. The software is expected to have 40000 lines of code. The company needs to determine the effort in person-months needed to develop this software using the basic COCOMO model. The multiplicative factor for this model is given as 2.8 for the software development on embedded systems, while the exponentiation factor is given as 1.20. What is the estimated effort in person-months?(A) 234.25(B) 932.50(C) 287.80(D) 122.40Answer: (A)Explanation: In the Constructive Cost Model (COCOMO), following is formula for effort applied
Effort Applied (E) = ab(KLOC)bb [ person-months ]
                   = 2.8 x(40)1.20 
                   = 2.8 x 83.65 
                   = 234.25 
Quiz of this Question
GATE-CS-2011
GATE-GATE CS 2011
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | Gate IT 2005 | Question 52
GATE | GATE-CS-2001 | Question 50
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2016 (Set 2) | Question 48
STRCMP() Function in MySQL

11 Jan, 2021
STRCMP() function in MySQL is used to compare two strings. If both of the strings are same then it returns 0, if the first argument is smaller than the second according to the defined order it returns -1 and it returns 1 when the second one is smaller the first one.
Syntax : STRCMP(Str1, Str2)
Parameter : This method accepts two-parameter as described below :
str1 : It is the first string used for comparison.
str2 : It is the second string used for comparison.
Returns : It can give four kinds of value –
If string1 = string2, this function returns 0
If string1 < string2, this function returns -1
If string1 > string2, this function returns 1
If any one or both string is NULL, this function returns NULL .
Example-1 : STRCMP() function to compare two equal string. As both given strings are equal it will return 0.
Select STRCMP('Geeks', 'Geeks') As 'Cmp_Value'
Output :
Example-2 : STRCMP() function to compare two string when second string is smaller than the first string. Here, the return value will be 1.
Select STRCMP('Geeks', 'Geek') As 'Cmp_Value'
Output :
Example-3 : STRCMP() function to compare two string when second string is bigger than the first string. As the second string is greater than the first one the result will be -1.
Select STRCMP('Geek', 'Geeks') As 'Cmp_Value'
Output :
Example-4 : STRCMP() function to compare two string when at least one string is NULL.
Select STRCMP('Geek', NULL) As 'Cmp_Value'
Output :
Example-5 : STRCMP() function can also be used on column data. To demonstrate create a table named StudentDetails.
CREATE TABLE StudentDetails(

    Student_id INT AUTO_INCREMENT,  
    First_name VARCHAR(100) NOT NULL,
    Last_name VARCHAR(100) NOT NULL,
    Student_Class VARCHAR(20) NOT NULL,
    TotalExamGiven INT   NOT NULL,
    PRIMARY KEY(Student_id )
Inserting data into the Table :
INSERT INTO  
    StudentDetails(First_name, Last_name, Class, TotalExamGiven )

VALUES
    ('Sayan', 'Jana', 'IX', 8 ),
    ('Nitin', 'Sharma', 'X',  5 ),
    ('Aniket', 'Srivastava', 'XI', 6 ),
    ('Abdur', 'Ali', 'X',  7 ),
    ('Riya', 'Malakar', 'IX', 4 ),
    ('Jony', 'Patel', 'X', 10 ),
    ('Deepak', 'Saini',  'X',  7 ),
    ('Ankana', 'Biswas',  'XII', 5 ),
    ('Shreya', 'Majhi', 'X',  8 ) ;
To verify used the following command as follows.
SELECT * FROM StudentDetails;
Output :
Now, we are going to compare between First_Name and Last_Name column using STRCMP Function.
SELECT First_Name, Last_Name,
STRCMP(First_Name, Last_Name) AS Cmp_Value 
FROM StudentDetails;
Output :
mysql
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tellg() function in C++ with example

05 Jun, 2018
The tellg() function is used with input streams, and returns the current “get” position of the pointer in the stream. It has no parameters and returns a value of the member type pos_type, which is an integer data type representing the current position of the get stream pointer.
Syntax:-
pos_type tellg(); 

Returns: The current position of the get pointer on success, pos_type(-1) on failure.
Example 1
// C++ program to demonstrate // example of tellg() function.#include <bits/stdc++.h>using namespace std;  int main(){    string str = "geeksforgeeks";    istringstream in(str);      string word;    in >> word;    cout << "After reading the word \"" << word        << "\" tellg() returns " << in.tellg() << '\n';}
After reading the word "geeksforgeeks" tellg() returns -1

Example 2 :
// C++ program to demonstrate // example of tellg() function.#include <bits/stdc++.h>using namespace std;  int main(){    string str = "Hello, GFG";    istringstream in(str);      string word;        in >> word;          cout << "After reading the word \"" << word        << "\" tellg() returns " << in.tellg() << '\n';}
After reading the word "Hello," tellg() returns 6

Properties:-tellg() does not report the size of the file, nor the offset from the beginning in bytes. It reports a token value which can later be used to seek to the same place, and nothing more. (It’s not even guaranteed that you can convert the type to an integral type)
cpp-stringstream
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Generating random number in a range in C

Here we will see how to generate random number in given range using C. To solve this problem, we will use the srand() function. The current time will be used to seed the srad() function.
This function cannot generate random number in any range, it can generate number between 0 to some value. So for it, we have to follow one trick. We will generate random number in between 0 to (upper – lower + 1), then add the lower limit for offsetting.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate_random(int l, int r, int count) { //this will generate random number in range l and r
   int i;
   for (i = 0; i < count; i++) {
      int rand_num = (rand() % (r - l + 1)) + l;
      printf("%d ", rand_num);
   }
}
main() {
   int lower = 10, upper = 15, count = 15;
   srand(time(0)); //current time as seed of random number generator
   generate_random(lower, upper, count);
   printf("\n");
}
15 11 13 10 13 10 15 11 14 12 12 13 12 13 14
ExpressJS - Form data

Forms are an integral part of the web. Almost every website we visit offers us forms that submit or fetch some information for us. To get started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware.
To install the body-parser and multer, go to your terminal and use −
npm install --save body-parser multer

Replace your index.js file contents with the following code −
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var app = express();

app.get('/', function(req, res){
   res.render('form');
});

app.set('view engine', 'pug');
app.set('views', './views');

// for parsing application/json
app.use(bodyParser.json()); 

// for parsing application/xwww-
app.use(bodyParser.urlencoded({ extended: true })); 
//form-urlencoded

// for parsing multipart/form-data
app.use(upload.array()); 
app.use(express.static('public'));

app.post('/', function(req, res){
   console.log(req.body);
   res.send("recieved your request!");
});
app.listen(3000);
After importing the body parser and multer, we will use the body-parser for parsing json and x-www-form-urlencoded header requests, while we will use multer for parsing multipart/form-data.
Let us create an html form to test this out. Create a new view called form.pug with the following code −
html
html
   head
      title Form Tester
   body
      form(action = "/", method = "POST")
         div
            label(for = "say") Say:
            input(name = "say" value = "Hi")
         br
         div
            label(for = "to") To:
            input(name = "to" value = "Express forms")
         br
         button(type = "submit") Send my greetings

Run your server using the following.
nodemon index.js

Now go to localhost:3000/ and fill the form as you like, and submit it. The following response will be displayed −
Have a look at your console; it will show you the body of your request as a JavaScript object as in the following screenshot −
The req.body object contains your parsed request body. To use fields from that object, just use them like normal JS objects.
This is the most recommended way to send a request. There are many other ways, but those are irrelevant to cover here, because our Express app will handle all those requests in the same way. To read more about different ways to make a request, have a look at this page.

    16 Lectures 
     1 hours 

 Anadi Sharma
 Print
 Add Notes
 Bookmark this page
DOM - Element Object Method - setAttributeNS

The method setAttributeNS adds a new attribute. If an attribute with the same local name and namespace URI is already present on the element, its prefix is changed to be the prefix part of the qualifiedName, and its value is changed to be the value parameter.
Following is the syntax for the usage of the setAttributeNS method.
elementObj.setAttributeNS(namespace,name,value)

namespace
It is a string specifying the namespace of the attribute.
name
It is a string identifying the attribute to be set.
value
It is the desired string value of the new attribute.
node_ns.xml contents are as below −
<?xml version = "1.0"?>
<Company>
   <Employee xmlns:e = "http://www.tutorials.com/technical/" category = "technical">
      <e:FirstName e:lang = "en">Tanmay</e:FirstName>
      <e:LastName>Patil</e:LastName>
      <e:ContactNo>1234567890</e:ContactNo>
      <e:Email>tanmaypatil@xyz.com</e:Email>
   </Employee>
   
   <Employee xmlns:n = "http://www.tutorials.com/non-technical/" category = "non-technical">
      <n:FirstName n:lang = "en">Taniya</n:FirstName>
      <n:LastName>Mishra</n:LastName>
      <n:ContactNo>1234667898</n:ContactNo>
      <n:Email>taniyamishra@xyz.com</n:Email>
   </Employee>
</Company>
Following example demonstrates the usage of the setAttributeNS method −
<!DOCTYPE html>
   <head>
      <script>
         function loadXMLDoc(filename) {
            if (window.XMLHttpRequest) {
               xhttp = new XMLHttpRequest();
            } else // code for IE5 and IE6 {
               xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xhttp.open("GET",filename,false);
            xhttp.send();
            return xhttp.responseXML;
         }
      </script>
   </head>
   <body>
      <script>
         xmlDoc = loadXMLDoc("/dom/node_ns.xml");
         x = xmlDoc.getElementsByTagName('FirstName')[0];
         ns="http://www.tutorials.com/technical/";
         document.write("<b>Before using setattributeNS method: </b> ");
         document.write(x.getAttributeNS(ns,"lang"));
         x.setAttributeNS(ns,"lang","DE");
         document.write("<br><b>After using setattributeNS method: </b> ");
         document.write(x.getAttributeNS(ns,"lang"));
      </script>
   </body>
</html>
Save this file as elementattribute_setAttributeNS.htm on the server path (this file and node_ns.xml should be on the same path in your server). We will get the output as shown below −
Before using setattributeNS method: en
After using setattributeNS method: DE


    41 Lectures 
     5 hours 

 Abhishek And Pukhraj

    33 Lectures 
     3.5 hours 

 Abhishek And Pukhraj

    15 Lectures 
     1 hours 

 Zach Miller

    15 Lectures 
     4 hours 

 Prof. Paul Cline, Ed.D

    13 Lectures 
     4 hours 

 Prof. Paul Cline, Ed.D

    17 Lectures 
     2 hours 

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
floor() and ceil() function Python - GeeksforGeeks

28 Oct, 2021
floor() method in Python returns the floor of x i.e., the largest integer not greater than x. 
Syntax:
import math
math.floor(x)

Parameter: 
x-numeric expression. 

Returns: 
largest integer not greater than x.
Below is the Python implementation of floor() method: 
Python
# Python program to demonstrate the use of floor() method  # This will import math moduleimport math     # prints the ceil using floor() methodprint "math.floor(-23.11) : ", math.floor(-23.11)print "math.floor(300.16) : ", math.floor(300.16)print "math.floor(300.72) : ", math.floor(300.72)
Output: 
math.floor(-23.11) :  -24.0
math.floor(300.16) :  300.0
math.floor(300.72) :  300.0
The method ceil(x) in Python returns a ceiling value of x i.e., the smallest integer greater than or equal to x.
Syntax: 
import math
math.ceil(x)

Parameter:
x:This is a numeric expression.

Returns: 
Smallest integer not less than x.
Below is the Python implementation of ceil() method: 
Python
# Python program to demonstrate the use of ceil() method  # This will import math moduleimport math     # prints the ceil using ceil() methodprint "math.ceil(-23.11) : ", math.ceil(-23.11)print "math.ceil(300.16) : ", math.ceil(300.16)print "math.ceil(300.72) : ", math.ceil(300.72)
Output: 
math.ceil(-23.11) :  -23.0
math.ceil(300.16) :  301.0
math.ceil(300.72) :  301.0
reachtoshasidhar07
atulyatib
Python-Built-in-functions
Python-Library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Progression - Solved Examples

Q 1 - Locate the ninth term and sixteenth term of the A.P. 5,8,11, 14, 17...
A - 40
B - 50
C - 60
D - 70
Answer - B
Explanation
In the given A.P. we have a=5, d= (8-5) = 3 
∴ Tn= a+ (n-1) d= 5+ (n-1)3 = 3n+2 
T16= (3*16+2) = 50

Q 2 - Which term of the A.P. 4,9,14, 19 ... is 109?
A - 22nd 
B - 23rd 
C - 24th 
D - 25th 
Answer - A
Explanation
We have a =4 and d= (9-4) = 5 
Let the nth term 109. At that point 
(a+ (n-1) d= 109 ⇒ 4+ (n-1)*5 =109 
(n-1)*5= 105 ⇒ (n-1) = 21 ⇒ n= 22 
∴ 22nd term is 109.

Q 3 - What numbers of term arrive in the A.P. 7, 13, 19, 25... 205? 
A - 34
B - 35
C - 36
D - 37
Answer - A
Explanation
Let the given A.P contain A.P. contain n terms. At that point, 
A=7, d = (13-7)= 6 and Tn = 205 
∴ a+ (n-1) d =205 ⇒ 7+ (n-1)*6 = 198 ⇒ (n-1) =33 ⇒ n = 34 
Given A.P contains 34 terms. 

Q 4 - The sixth term of an A.P. is 12 and its eighth term is 22. Locate its first term, normal contrast and sixteenth term.
A - 61
B - 62
C - 63
D - 64
Answer - B
Explanation
Let, first term = a and normal contrast =d. 
T6 = 12 ⇒ a+5d= 12 .... (i) 
T8= 22 ⇒ a+7d = 22 ... (ii) 
On subtracting (i) from (ii), we get 2d = 10 ⇒ d = 5 
Putting d= 5 in (i), we get a+5*5 = 12 ⇒ a= (12-25) =-13 
∴ First term = - 13, normal distinction = 5. 
T16= a+ 15d = - 13+15*5 = (75-13) = 62

Q 5 - Discover the whole of initial 17 terms of the A.P. 5, 9, 13, 17...
A - 627
B - 628
C - 629
D - 630
Answer - C
Explanation
Here a =5, d= (9-5) = 4 and n = 17 
Sn = n/2[2a+ (n-1) d] 
S17 = 17/2 [2*5+ (17-1)*4] = (17/2*74) = 629

Q 6 - Discover the sum of the arrangement = 2+5+8+...+182. 
A - 5612
B - 5712
C - 5812
D - 5912
Answer - A
Explanation
Here a = 2, d = (5-2) = 3 and Tn = 182. 
Tn = 182 ⇒ a+ (n-1) d = 182 ⇒ 2+ (n-1)*3 = 182 ⇒ 3n = 183 ⇒ n= 61. 
Sn = n/2[2a+ (n-1) d] 
=61/2 {2*2+(61-1)*3} = (61/2* 184) = (61*92) = 5612. 

Q 7 - Discover three numbers in A.P. whose sum is 15 and item is 80.
A - 1,4 and 9 or 9,4, and 1
B - 3,5 and 9 or 9,5, and 3
C - 3,6 and 9 or 9,6, and 3
D - 2,5 and 8 or 8,5, and 2
Answer - D
Explanation
Let the numbers be (a-d), an and (a+d). At that point, 
(a-d) +a+ (a+d) = 15 ⇒ 3a = 15 ⇒ a = 5 
(a-d)*a*(a+d) = 80 ⇒ (5-d)*5 * (5+d) = 80 
⇒ (25-d2) = 16 = d2 =9 ⇒ d = 3 
Numbers are 2, 5, 8 or 8, 5, 2. 

Q 8 - Locate the ninth term and the nth term of the G.P. 3,6,12, 24 ...
A - 738, 4n-1
B - 748, 5n-1
C - 758, 6n-1
D - 768, 6n-1
Answer - D
Explanation
Given numbers are in G.P in which a= 3 and r =6/3 = 2. 
∴ Tn = arn-1 ⇒ T9= 3*28 = (3*256) = 768 
Tn = 3*2n-1 = 6n-1

Q 9 - On the off chance that the fourth and ninth terms of A G.P. are 54 and 13122 individually, locate the first term, regular proportion and its sixth term.
A - 476
B - 486
C - 496
D - 506
Answer - B
Explanation
Let A be the first term and r be the basic proportion. At that point, 
T4 = 54 ⇒ ar3 =54 ... (i) 
T4 = 13122 ⇒ ar8 = 13122 ...(ii) 
On isolating (ii) by (i) , we get r5 = 13122/54 = 243 =(3)5 ⇒ r =3 
Putting r =3 in (i), we get a*27 =54 ⇒ a = 2 
∴ First term =2 and common ratio =3.
T6= ar5 = 2*35= 486. Hence, 6th term = 486.


    87 Lectures 
     22.5 hours 

 Programming Line
 Print
 Add Notes
 Bookmark this page
string.char() function in Lua programming

There are so many scenarios where you might want to convert a decimal value into a character representation. The character representation of a decimal or integer value is nothing but the character value, which one can interpret using the ASCII table.
In Lua, to convert a decimal value to its internal character value we make use of the string.char() function.
string.char(I)
In the above syntax, the identifier I represents the decimal value which we want to convert into a character.
Let’s consider a very simple example, where you are given different decimal values, and you want to convert them to a character value.
Consider the example shown below −
 Live Demo
s = string.char(97)
print(s)
s = string.char(122)
print(s)
s = string.char(125)
print(s)
In the above example, the values passed as argument to the string.char() function are decimal values that correspond to a character.
a
z
}
The string.char() function can take multiple arguments as well.
Consider the example shown below −
 Live Demo
i = 97
s = string.char(i,i+1,i+2,i+3)
print(s)
abcd
Java program for Multiplication of Array elements.

To find the product of elements of an array.
create an empty variable. (product)
Initialize it with 1.
In a loop traverse through each element (or get each element from user) multiply each element to product.
Print the product.
 Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class ProductOfArrayOfElements {
   public static void main(String args[]){
      System.out.println("Enter the required size of the array :: ");
      Scanner s = new Scanner(System.in);
      int size = s.nextInt();
      int myArray[] = new int [size];
      int product = 1;
      System.out.println("Enter the elements of the array one by one ");
      for(int i=0; i<size; i++){
         myArray[i] = s.nextInt();
         product = product * myArray[i];
      }
      System.out.println("Elements of the array are: "+Arrays.toString(myArray));
      System.out.println("Sum of the elements of the array ::"+product);
   }
}
Enter the required size of the array:
5
Enter the elements of the array one by one
11
65
22
18
47
Elements of the array are: [11, 65, 22, 18, 47]
Sum of the elements of the array:13307580
How to create EditText with rounded corners in Android?

This example demonstrates how to create EditText with rounded corners in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:padding="16dp"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/editText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:background="@drawable/et_style"
      android:hint="Your name"
      android:padding="10dp" />
</LinearLayout>
Step 3 − Create a drawable resource file and Add the following code to drawable/et_style.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
   <stroke
      android:width="2dp"
      android:color="#0274be" />
   <corners android:radius="8dp"/>
</shape>
Step 4   − Add the following code to src/MainActivity.java
package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 5 − Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sample">
   <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 Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code
JavaScript - Check if value is a percentage?

Let’s say the following is our value −
var value="97%";
To check the value for percentage, use regular expression.
Following is the code −
var value="97%";
var result=/^\d+(\.\d+)?%$/.test(value);
if (result==true) {
   console.log("The percent is="+value);  
}
else
{
   console.log("This is not percentage");  
}
var value1="percent";
var result1=/^\d+(\.\d+)?%$/.test(value1);
if (result1==true) {
   console.log("The percent is="+value1);  
}
else
{
   console.log("This is not percentage");  
}
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo214.js.
The output is as follows on console −
PS C:\Users\Amit\JavaScript-code> node demo214.js
The percent is=97%
This is not percentage
How to add a new row to JTable with insertRow() in Java Swing

Let us first create a table with DefaulTabelMode −
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
Now, add a column to the table −
tableModel.addColumn("Languages");
The insertRow() method will now add a row −
tableModel.insertRow(0, new Object[] { "CSS" });
tableModel.insertRow(0, new Object[] { "HTML5" });
tableModel.insertRow(0, new Object[] { "JavaScript" });
tableModel.insertRow(0, new Object[] { "jQuery" });
The following is an example to add a new row to JTable −
package my;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      DefaultTableModel tableModel = new DefaultTableModel();
      JTable table = new JTable(tableModel);
      tableModel.addColumn("Languages");
      tableModel.insertRow(0, new Object[] { "CSS" });
      tableModel.insertRow(0, new Object[] { "HTML5" });
      tableModel.insertRow(0, new Object[] { "JavaScript" });
      tableModel.insertRow(0, new Object[] { "jQuery" });
      tableModel.insertRow(0, new Object[] { "AngularJS" });
      // adding a new row
      tableModel.insertRow(tableModel.getRowCount(), new Object[] { "ExpressJS" });
      JFrame f = new JFrame();
      f.setSize(550, 350);
      f.add(new JScrollPane(table));
      f.setVisible(true);
   }
}
This will produce the following output −
What is the use of -Force parameter in Get-ChildItem in PowerShell?

To display files along with hidden files, you need to use –Force parameter.
Get-ChildItem D:\Temp\ -Force
If you see the above output, hiddenfile.xlsx is the hidden file and same can be identified with the mode where –a-h—attribute of the file.
You can also use this parameter with –Recurse or –Depth.
Get-ChildItem D:\Temp\ -Recurse -Force
Display array structure and values in PHP 7

An array in PHP is a type of data structure that can store multiple elements of similar data type under a single variable.
To display array structure and values in PHP, we can use two functions. We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array.
print_r: It is used to display the variable information in a human-readable format. Array values will be present in a format so that keys and elements can show. print_r also shows protected and private properties of objects but it will not show the static class and members.
Live Demo
<?php
   $x = array ('x' => 'Dept', 'y' => 'Employee', 'z' => array ('a', 'b', 'c'));
   print_r ($x);
?>
Output for the above print_r program will be:
Array
(
   [x] => Dept
   [y] => Employee
   [z] => Array
      (
         [0] => a
         [1] => b
         [2] => c
      )
)
var_dump: It is used to display the structure information of one or more variables and expressions including its type and value. Arrays and objects are explored recursively with their values indented to show the structure.
Live Demo
<?php
   $x = array(1, 2,3, array("x", "y", "z","a"));
   var_dump($x);
?>
Output for the above var_dump program will be −
array(4) {
   [0]=>
   int(1)
   [1]=>
   int(2)
   [2]=>
   int(3)
   [3]=>
   array(4) {
      [0]=>
      string(1) "x"
      [1]=>
      string(1) "y"
      [2]=>
      string(1) "z"
      [3]=>
      string(1) "a"
   }
}
Live Demo
<?php
   $students = array("Rohan", "Mohan", "Thomas"); // it will print the students
   print_r($students);
   //echo "<hr>";
   var_dump($students);
?>
The output for the above program will be −
Array
(
   [0] => Rohan
   [1] => Mohan
   [2] => Thomas
)
array(3) {
   [0]=>
   string(5) "Rohan"
   [1]=>
   string(5) "Mohan"
   [2]=>
   string(6) "Thomas"
}
Aurelia - Custom Elements

Aurelia offers a way to add components dynamically. You can reuse a single component on different parts of your app without the need to include HTML multiple times. In this chapter, you will learn how to achieve this.
Let's create new components directory inside src folder.
C:\Users\username\Desktop\aureliaApp\src>mkdir components

Inside this directory, we will create custom-component.html. This component will be inserted later in the HTML page.
<template>
   <p>This is some text from dynamic component...</p>
</template>
We will create simple component in app.js. It will be used to render header and footer text on screen.
export class MyComponent {
   header = "This is Header";
   content = "This is content";
}
Inside our app.html file, we need to require the custom-component.html to be able to insert it dynamically. Once we do that, we can add a new element custom-component.
<template>
   <require from = "./components/custom-component.html"></require>

   <h1>${header}</h1>
   <p>${content}</p>
   <custom-component></custom-component>
</template>
Following is the output. Header and Footer text is rendered from myComponent inside app.js. The additional text is rendered from the custom-component.js.
 Print
 Add Notes
 Bookmark this page
C++ Queue Library - operator== Function

The C++ function std::queue::operator== tests whether two queues are equal or not. Comparison is done by applying corresponding operator to the underlying container.
Following is the declaration for std::queue::operator== function form std::queue header.
template <class T, class Container>
bool operator== (const queue<T,Container>& q1, const queue<T,Container>& q2);

q1 − First queue object.
q1 − First queue object.
q2 − Second queue object.
q2 − Second queue object.
Returns true if both queues are identical otherwise false.
This member function never throws exception.
Linear i.e. O(n)
The following example shows the usage of std::queue::operator== function.
#include <iostream>
#include <queue>

using namespace std;

int main(void) {
   queue<int> q1, q2;

   for (int i = 0; i < 5; ++i) {
      q1.push(i + 1);
      q2.push(i + 1);
   }

   if (q1 == q2)
      cout << "q1 and q2 are identical." << endl;

   q1.push(6);

   if (!(q1 == q2))
      cout << "q1 and q2 are not identical." << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
q1 and q2 are identical.
q1 and q2 are not identical.

 Print
 Add Notes
 Bookmark this page
Tail Recursion in Data Structures

Here we will see what is tail recursion. The tail recursion is basically using the recursive function as the last statement of the function. So when nothing is left to do after coming back from the recursive call, that is called tail recursion. We will see one example of tail recursion.
 Live Demo
#include <iostream>
using namespace std;
void printN(int n){
   if(n < 0){
      return;
   }
   cout << n << " ";
   printN(n - 1);
}
int main() {
   printN(10);
}
10 9 8 7 6 5 4 3 2 1 0
The tail recursion is better than non-tail recursion. As there is no task left after the recursive call, it will be easier for the compiler to optimize the code. When one function is called, its address is stored inside the stack. So if it is tail recursion, then storing addresses into stack is not needed.
We can use factorial using recursion, but the function is not tail recursive. The value of fact(n-1) is used inside the fact(n).
long fact(int n){
   if(n <= 1)
      return 1;
   n * fact(n-1);
}
We can make it tail recursive, by adding some other parameters. This is like below −
long fact(long n, long a){
   if(n == 0)
      return a;
   return fact(n-1, a*n);
}
Program to find lowest sum of pairs greater than given target in Python

Suppose we have a list of numbers called nums and another value target. We have to find the lowest sum of pair of numbers that is larger than target.
So, if the input is like nums = [2, 4, 6, 10, 14] target = 10, then the output will be 12, as we pick 2 and 10
To solve this, we will follow these steps −
sort the list nums
n := size of nums
answer := 10^10
i := 0, j := n - 1
while i < j, doif nums[i] + nums[j] > target, thenanswer := minimum of answer and (nums[i] + nums[j])j := j - 1otherwise,i := i + 1
if nums[i] + nums[j] > target, thenanswer := minimum of answer and (nums[i] + nums[j])j := j - 1
answer := minimum of answer and (nums[i] + nums[j])
j := j - 1
otherwise,i := i + 1
i := i + 1
return answer
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums, target): nums.sort()
      n = len(nums)
      answer = 10 ** 10
      i, j = 0, n - 1
      while i < j:
         if nums[i] + nums[j] > target:
            answer = min(answer, nums[i] + nums[j])
            j -= 1
         else:
            i += 1
      return answer
ob = Solution()
nums = [2, 4, 6, 10, 14]
target = 10
print(ob.solve(nums, target))
[2, 4, 6, 10, 14], 10
12
Matplotlib.ticker.LogLocator Class in Python

21 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.ticker.LogLocator class is used to determine the tick locations for log axes. In this class the ticks are placed on the location as : subs[j]*base**i.
Syntax: class matplotlib.ticker.LogLocator(base=10.0, subs=(1.0, ), numdecs=4, numticks=None)
Parameter:
subs: It is an optional parameter which is either None, or string or a sequence of floats. It defaults to (1.0, ). It provides the multiples of integer powers of the base at which is used to place ticks. Only at integer powers of the base the default places ticks. The auto and all are the only accepted string values here. The ticks are placed exactly between integer powers with ‘auto’ whereas with “all’ the integers power are accepted. Here None value is equivalent to ‘auto’.
Methods of the class:
base(self, base): This method is used for setting the base of the log scale.
nonsingular(self, vmin, vmax): It is used to expand the range as required to avoid singularities.
set_params(self, base=None, subs=None, numdecs=None, numticks=None): It is used to set parameters within the scale.
tick_values(self, vmin, vmax): This method returns the values of the located ticks between the range of vmin and vmax.
subs(self, subs): It is used to set the minor ticks for the log scaling every base**i*subs[j].
view_limit(self, vmin, vmax): This methods comes in handy while intelligently choosing the vie limits.
Example 1:
import matplotlib.pyplot as pltfrom matplotlib.ticker import MultipleLocator, LogLocator  x = [1, 2, 3, 4, 5, 6,     7, 8, 9, 10, 11, 12]  y = [0.32, 0.30, 0.28, 0.26,     0.24, 0.22, 0.20, 0.18,     0.16, 0.14, 0.12, 0.10]  fig = plt.figure()ax1 = fig.add_subplot(111)  x_major = MultipleLocator(4)x_minor = MultipleLocator(1)  ax1.xaxis.set_major_locator(x_major)ax1.xaxis.set_minor_locator(x_minor)ax1.set_yscale("log")  y_major = LogLocator(base = 10)y_minor = LogLocator(base = 10, subs =[1.1, 1.2, 1.3])  ax1.yaxis.set_major_locator(y_major)ax1.yaxis.set_minor_locator(y_minor)  ax1.plot(x, y)  plt.show()
Output:
Example 2:
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import LogLocator    x = np.linspace(0, 10, 10)y = 2**x  f = plt.figure()ax = f.add_subplot(111)plt.yscale('log')  ax.yaxis.set_major_locator(LogLocator(base = 100))  ax.plot(x, y)  plt.show()
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.