title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Node.js - Net Module | Node.js net module is used to create both servers and clients. This module provides an asynchronous network wrapper and it can be imported using the following syntax.
var net = require("net")
net.createServer([options][, connectionListener])
Creates a new TCP server. The connectionListener argument is automatically set as a listener for the 'connection' event.
net.connect(options[, connectionListener])
A factory method, which returns a new 'net.Socket' and connects to the supplied address and port.
net.createConnection(options[, connectionListener])
A factory method, which returns a new 'net.Socket' and connects to the supplied address and port.
net.connect(port[, host][, connectListener])
Creates a TCP connection to port on host. If host is omitted, 'localhost' will be assumed. The connectListener parameter will be added as a listener for the 'connect' event. It is a factory method which returns a new 'net.Socket'.
net.createConnection(port[, host][, connectListener])
Creates a TCP connection to port on host. If host is omitted, 'localhost' will be assumed. The connectListener parameter will be added as a listener for the 'connect' event. It is a factory method which returns a new 'net.Socket'.
net.connect(path[, connectListener])
Creates Unix socket connection to path. The connectListener parameter will be added as a listener for the 'connect' event. It is a factory method which returns a new 'net.Socket'.
net.createConnection(path[, connectListener])
Creates Unix socket connection to path. The connectListener parameter will be added as a listener for the 'connect' event. It is a factory method which returns a new 'net.Socket'.
net.isIP(input)
Tests if the input is an IP address. Returns 0 for invalid strings, 4 for IP version 4 addresses, and 6 for IP version 6 addresses.
net.isIPv4(input)
Returns true if the input is a version 4 IP address, otherwise returns false.
net.isIPv6(input)
Returns true if the input is a version 6 IP address, otherwise returns false.
This class is used to create a TCP or local server.
server.listen(port[, host][, backlog][, callback])
Begin accepting connections on the specified port and host. If the host is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY). A port value of zero will assign a random port.
server.listen(path[, callback])
Start a local socket server listening for connections on the given path.
server.listen(handle[, callback])
The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object. It will cause the server to accept connections on the specified handle, but it is presumed that the file descriptor or handle has already been bound to a port or domain socket. Listening on a file descriptor is not supported on Windows.
server.listen(options[, callback])
The port, host, and backlog properties of options, as well as the optional callback function, behave as they do on a call to server.listen(port, [host], [backlog], [callback]) . Alternatively, the path option can be used to specify a UNIX socket.
server.close([callback])
Finally closed when all connections are ended and the server emits a 'close' event.
server.address()
Returns the bound address, the address family name and port of the server as reported by the operating system.
server.unref()
Calling unref on a server will allow the program to exit if this is the only active server in the event system. If the server is already unrefd, then calling unref again will have no effect.
server.ref()
Opposite of unref, calling ref on a previously unrefd server will not let the program exit if it's the only server left (the default behavior). If the server is refd, then calling the ref again will have no effect.
server.getConnections(callback)
Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks. Callback should take two arguments err and count.
listening
Emitted when the server has been bound after calling server.listen.
connection
Emitted when a new connection is made. Socket object, the connection object is available to event handler. Socket is an instance of net.Socket.
close
Emitted when the server closes. Note that if connections exist, this event is not emitted until all the connections are ended.
error
Emitted when an error occurs. The 'close' event will be called directly following this event.
This object is an abstraction of a TCP or local socket. net.Socket instances implement a duplex Stream interface. They can be created by the user and used as a client (with connect()) or they can be created by Node and passed to the user through the 'connection' event of a server.
net.Socket is an eventEmitter and it emits the following events.
lookup
Emitted after resolving the hostname but before connecting. Not applicable to UNIX sockets.
connect
Emitted when a socket connection is successfully established.
data
Emitted when data is received. The argument data will be a Buffer or String. Encoding of data is set by socket.setEncoding().
end
Emitted when the other end of the socket sends a FIN packet.
timeout
Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection.
drain
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
error
Emitted when an error occurs. The 'close' event will be called directly following this event.
close
Emitted once the socket is fully closed. The argument had_error is a boolean which indicates if the socket was closed due to a transmission error.
net.Socket provides many useful properties to get better control over socket interactions.
socket.bufferSize
This property shows the number of characters currently buffered to be written.
socket.remoteAddress
The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'.
socket.remoteFamily
The string representation of the remote IP family. 'IPv4' or 'IPv6'.
socket.remotePort
The numeric representation of the remote port. For example, 80 or 21.
socket.localAddress
The string representation of the local IP address the remote client is connecting on. For example, if you are listening on '0.0.0.0' and the client connects on '192.168.1.1', the value would be '192.168.1.1'.
socket.localPort
The numeric representation of the local port. For example, 80 or 21.
socket.bytesRead
The amount of received bytes.
socket.bytesWritten
The amount of bytes sent.
new net.Socket([options])
Construct a new socket object.
socket.connect(port[, host][, connectListener])
Opens the connection for a given socket. If port and host are given, then the socket will be opened as a TCP socket, if host is omitted, localhost will be assumed. If a path is given, the socket will be opened as a Unix socket to that path.
socket.connect(path[, connectListener])
Opens the connection for a given socket. If port and host are given, then the socket will be opened as a TCP socket, if host is omitted, localhost will be assumed. If a path is given, the socket will be opened as a Unix socket to that path.
socket.setEncoding([encoding])
Set the encoding for the socket as a Readable Stream.
socket.write(data[, encoding][, callback])
Sends data on the socket. The second parameter specifies the encoding in the case of a string--it defaults to UTF8 encoding.
socket.end([data][, encoding])
Half-closes the socket, i.e., it sends a FIN packet. It is possible the server will still send some data.
socket.destroy()
Ensures that no more I/O activity happens on this socket. Necessary only in case of errors (parse error or so).
socket.pause()
Pauses the reading of data. That is, 'data' events will not be emitted. Useful to throttle back an upload.
socket.resume()
Resumes reading after a call to pause().
socket.setTimeout(timeout[, callback])
Sets the socket to timeout after timeout milliseconds of inactivity on the socket. By default, net.Socket does not have a timeout.
socket.setNoDelay([noDelay])
Disables the Nagle algorithm. By default, TCP connections use the Nagle algorithm, they buffer data before sending it off. Setting true for noDelay will immediately fire off data each time socket.write() is called. noDelay defaults to true.
socket.setKeepAlive([enable][, initialDelay])
Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket. enable defaults to false.
socket.address()
Returns the bound address, the address family name, and the port of the socket as reported by the operating system. Returns an object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }.
socket.unref()
Calling unref on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already unrefd, then calling unref again will have no effect.
socket.ref()
Opposite of unref, calling ref on a previously unrefd socket will not let the program exit if it's the only socket left (the default behavior). If the socket is refd, then calling ref again will have no effect.
Create a js file named server.js with the following code β
File: server.js
var net = require('net');
var server = net.createServer(function(connection) {
console.log('client connected');
connection.on('end', function() {
console.log('client disconnected');
});
connection.write('Hello World!\r\n');
connection.pipe(connection);
});
server.listen(8080, function() {
console.log('server is listening');
});
Now run the server.js to see the result β
$ node server.js
Verify the Output.
server is listening
Create a js file named client.js with the following code β
File: client.js
var net = require('net');
var client = net.connect({port: 8080}, function() {
console.log('connected to server!');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('disconnected from server');
});
Now run the client.js from another terminal to see the result β
$ node client.js
Verify the Output.
connected to server!
Hello World!
disconnected from server
Verify the Output on the terminal where server.js is running.
server is listening
client connected
client disconnected
44 Lectures
7.5 hours
Eduonix Learning Solutions
88 Lectures
17 hours
Eduonix Learning Solutions
32 Lectures
1.5 hours
Richard Wells
8 Lectures
33 mins
Anant Rungta
9 Lectures
2.5 hours
SHIVPRASAD KOIRALA
97 Lectures
6 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2185,
"s": 2018,
"text": "Node.js net module is used to create both servers and clients. This module provides an asynchronous network wrapper and it can be imported using the following syntax."
},
{
"code": null,
"e": 2211,
"s": 2185,
"text": "var net = require(\"net\")\n"
},
{
"code": null,
"e": 2261,
"s": 2211,
"text": "net.createServer([options][, connectionListener])"
},
{
"code": null,
"e": 2382,
"s": 2261,
"text": "Creates a new TCP server. The connectionListener argument is automatically set as a listener for the 'connection' event."
},
{
"code": null,
"e": 2425,
"s": 2382,
"text": "net.connect(options[, connectionListener])"
},
{
"code": null,
"e": 2523,
"s": 2425,
"text": "A factory method, which returns a new 'net.Socket' and connects to the supplied address and port."
},
{
"code": null,
"e": 2575,
"s": 2523,
"text": "net.createConnection(options[, connectionListener])"
},
{
"code": null,
"e": 2673,
"s": 2575,
"text": "A factory method, which returns a new 'net.Socket' and connects to the supplied address and port."
},
{
"code": null,
"e": 2718,
"s": 2673,
"text": "net.connect(port[, host][, connectListener])"
},
{
"code": null,
"e": 2949,
"s": 2718,
"text": "Creates a TCP connection to port on host. If host is omitted, 'localhost' will be assumed. The connectListener parameter will be added as a listener for the 'connect' event. It is a factory method which returns a new 'net.Socket'."
},
{
"code": null,
"e": 3003,
"s": 2949,
"text": "net.createConnection(port[, host][, connectListener])"
},
{
"code": null,
"e": 3235,
"s": 3003,
"text": "Creates a TCP connection to port on host. If host is omitted, 'localhost' will be assumed. The connectListener parameter will be added as a listener for the 'connect' event. It is a factory method which returns a new 'net.Socket'."
},
{
"code": null,
"e": 3272,
"s": 3235,
"text": "net.connect(path[, connectListener])"
},
{
"code": null,
"e": 3452,
"s": 3272,
"text": "Creates Unix socket connection to path. The connectListener parameter will be added as a listener for the 'connect' event. It is a factory method which returns a new 'net.Socket'."
},
{
"code": null,
"e": 3498,
"s": 3452,
"text": "net.createConnection(path[, connectListener])"
},
{
"code": null,
"e": 3678,
"s": 3498,
"text": "Creates Unix socket connection to path. The connectListener parameter will be added as a listener for the 'connect' event. It is a factory method which returns a new 'net.Socket'."
},
{
"code": null,
"e": 3694,
"s": 3678,
"text": "net.isIP(input)"
},
{
"code": null,
"e": 3826,
"s": 3694,
"text": "Tests if the input is an IP address. Returns 0 for invalid strings, 4 for IP version 4 addresses, and 6 for IP version 6 addresses."
},
{
"code": null,
"e": 3844,
"s": 3826,
"text": "net.isIPv4(input)"
},
{
"code": null,
"e": 3922,
"s": 3844,
"text": "Returns true if the input is a version 4 IP address, otherwise returns false."
},
{
"code": null,
"e": 3940,
"s": 3922,
"text": "net.isIPv6(input)"
},
{
"code": null,
"e": 4018,
"s": 3940,
"text": "Returns true if the input is a version 6 IP address, otherwise returns false."
},
{
"code": null,
"e": 4070,
"s": 4018,
"text": "This class is used to create a TCP or local server."
},
{
"code": null,
"e": 4121,
"s": 4070,
"text": "server.listen(port[, host][, backlog][, callback])"
},
{
"code": null,
"e": 4331,
"s": 4121,
"text": "Begin accepting connections on the specified port and host. If the host is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY). A port value of zero will assign a random port."
},
{
"code": null,
"e": 4363,
"s": 4331,
"text": "server.listen(path[, callback])"
},
{
"code": null,
"e": 4436,
"s": 4363,
"text": "Start a local socket server listening for connections on the given path."
},
{
"code": null,
"e": 4470,
"s": 4436,
"text": "server.listen(handle[, callback])"
},
{
"code": null,
"e": 4834,
"s": 4470,
"text": "The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object. It will cause the server to accept connections on the specified handle, but it is presumed that the file descriptor or handle has already been bound to a port or domain socket. Listening on a file descriptor is not supported on Windows."
},
{
"code": null,
"e": 4869,
"s": 4834,
"text": "server.listen(options[, callback])"
},
{
"code": null,
"e": 5116,
"s": 4869,
"text": "The port, host, and backlog properties of options, as well as the optional callback function, behave as they do on a call to server.listen(port, [host], [backlog], [callback]) . Alternatively, the path option can be used to specify a UNIX socket."
},
{
"code": null,
"e": 5141,
"s": 5116,
"text": "server.close([callback])"
},
{
"code": null,
"e": 5225,
"s": 5141,
"text": "Finally closed when all connections are ended and the server emits a 'close' event."
},
{
"code": null,
"e": 5242,
"s": 5225,
"text": "server.address()"
},
{
"code": null,
"e": 5353,
"s": 5242,
"text": "Returns the bound address, the address family name and port of the server as reported by the operating system."
},
{
"code": null,
"e": 5368,
"s": 5353,
"text": "server.unref()"
},
{
"code": null,
"e": 5559,
"s": 5368,
"text": "Calling unref on a server will allow the program to exit if this is the only active server in the event system. If the server is already unrefd, then calling unref again will have no effect."
},
{
"code": null,
"e": 5572,
"s": 5559,
"text": "server.ref()"
},
{
"code": null,
"e": 5787,
"s": 5572,
"text": "Opposite of unref, calling ref on a previously unrefd server will not let the program exit if it's the only server left (the default behavior). If the server is refd, then calling the ref again will have no effect."
},
{
"code": null,
"e": 5819,
"s": 5787,
"text": "server.getConnections(callback)"
},
{
"code": null,
"e": 5979,
"s": 5819,
"text": "Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks. Callback should take two arguments err and count."
},
{
"code": null,
"e": 5989,
"s": 5979,
"text": "listening"
},
{
"code": null,
"e": 6057,
"s": 5989,
"text": "Emitted when the server has been bound after calling server.listen."
},
{
"code": null,
"e": 6068,
"s": 6057,
"text": "connection"
},
{
"code": null,
"e": 6212,
"s": 6068,
"text": "Emitted when a new connection is made. Socket object, the connection object is available to event handler. Socket is an instance of net.Socket."
},
{
"code": null,
"e": 6218,
"s": 6212,
"text": "close"
},
{
"code": null,
"e": 6345,
"s": 6218,
"text": "Emitted when the server closes. Note that if connections exist, this event is not emitted until all the connections are ended."
},
{
"code": null,
"e": 6351,
"s": 6345,
"text": "error"
},
{
"code": null,
"e": 6445,
"s": 6351,
"text": "Emitted when an error occurs. The 'close' event will be called directly following this event."
},
{
"code": null,
"e": 6727,
"s": 6445,
"text": "This object is an abstraction of a TCP or local socket. net.Socket instances implement a duplex Stream interface. They can be created by the user and used as a client (with connect()) or they can be created by Node and passed to the user through the 'connection' event of a server."
},
{
"code": null,
"e": 6792,
"s": 6727,
"text": "net.Socket is an eventEmitter and it emits the following events."
},
{
"code": null,
"e": 6799,
"s": 6792,
"text": "lookup"
},
{
"code": null,
"e": 6891,
"s": 6799,
"text": "Emitted after resolving the hostname but before connecting. Not applicable to UNIX sockets."
},
{
"code": null,
"e": 6899,
"s": 6891,
"text": "connect"
},
{
"code": null,
"e": 6961,
"s": 6899,
"text": "Emitted when a socket connection is successfully established."
},
{
"code": null,
"e": 6966,
"s": 6961,
"text": "data"
},
{
"code": null,
"e": 7092,
"s": 6966,
"text": "Emitted when data is received. The argument data will be a Buffer or String. Encoding of data is set by socket.setEncoding()."
},
{
"code": null,
"e": 7096,
"s": 7092,
"text": "end"
},
{
"code": null,
"e": 7157,
"s": 7096,
"text": "Emitted when the other end of the socket sends a FIN packet."
},
{
"code": null,
"e": 7165,
"s": 7157,
"text": "timeout"
},
{
"code": null,
"e": 7313,
"s": 7165,
"text": "Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection."
},
{
"code": null,
"e": 7319,
"s": 7313,
"text": "drain"
},
{
"code": null,
"e": 7397,
"s": 7319,
"text": "Emitted when the write buffer becomes empty. Can be used to throttle uploads."
},
{
"code": null,
"e": 7403,
"s": 7397,
"text": "error"
},
{
"code": null,
"e": 7497,
"s": 7403,
"text": "Emitted when an error occurs. The 'close' event will be called directly following this event."
},
{
"code": null,
"e": 7503,
"s": 7497,
"text": "close"
},
{
"code": null,
"e": 7650,
"s": 7503,
"text": "Emitted once the socket is fully closed. The argument had_error is a boolean which indicates if the socket was closed due to a transmission error."
},
{
"code": null,
"e": 7741,
"s": 7650,
"text": "net.Socket provides many useful properties to get better control over socket interactions."
},
{
"code": null,
"e": 7759,
"s": 7741,
"text": "socket.bufferSize"
},
{
"code": null,
"e": 7838,
"s": 7759,
"text": "This property shows the number of characters currently buffered to be written."
},
{
"code": null,
"e": 7859,
"s": 7838,
"text": "socket.remoteAddress"
},
{
"code": null,
"e": 7966,
"s": 7859,
"text": "The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'."
},
{
"code": null,
"e": 7986,
"s": 7966,
"text": "socket.remoteFamily"
},
{
"code": null,
"e": 8055,
"s": 7986,
"text": "The string representation of the remote IP family. 'IPv4' or 'IPv6'."
},
{
"code": null,
"e": 8073,
"s": 8055,
"text": "socket.remotePort"
},
{
"code": null,
"e": 8143,
"s": 8073,
"text": "The numeric representation of the remote port. For example, 80 or 21."
},
{
"code": null,
"e": 8163,
"s": 8143,
"text": "socket.localAddress"
},
{
"code": null,
"e": 8372,
"s": 8163,
"text": "The string representation of the local IP address the remote client is connecting on. For example, if you are listening on '0.0.0.0' and the client connects on '192.168.1.1', the value would be '192.168.1.1'."
},
{
"code": null,
"e": 8389,
"s": 8372,
"text": "socket.localPort"
},
{
"code": null,
"e": 8458,
"s": 8389,
"text": "The numeric representation of the local port. For example, 80 or 21."
},
{
"code": null,
"e": 8475,
"s": 8458,
"text": "socket.bytesRead"
},
{
"code": null,
"e": 8505,
"s": 8475,
"text": "The amount of received bytes."
},
{
"code": null,
"e": 8525,
"s": 8505,
"text": "socket.bytesWritten"
},
{
"code": null,
"e": 8551,
"s": 8525,
"text": "The amount of bytes sent."
},
{
"code": null,
"e": 8577,
"s": 8551,
"text": "new net.Socket([options])"
},
{
"code": null,
"e": 8608,
"s": 8577,
"text": "Construct a new socket object."
},
{
"code": null,
"e": 8656,
"s": 8608,
"text": "socket.connect(port[, host][, connectListener])"
},
{
"code": null,
"e": 8897,
"s": 8656,
"text": "Opens the connection for a given socket. If port and host are given, then the socket will be opened as a TCP socket, if host is omitted, localhost will be assumed. If a path is given, the socket will be opened as a Unix socket to that path."
},
{
"code": null,
"e": 8937,
"s": 8897,
"text": "socket.connect(path[, connectListener])"
},
{
"code": null,
"e": 9178,
"s": 8937,
"text": "Opens the connection for a given socket. If port and host are given, then the socket will be opened as a TCP socket, if host is omitted, localhost will be assumed. If a path is given, the socket will be opened as a Unix socket to that path."
},
{
"code": null,
"e": 9209,
"s": 9178,
"text": "socket.setEncoding([encoding])"
},
{
"code": null,
"e": 9263,
"s": 9209,
"text": "Set the encoding for the socket as a Readable Stream."
},
{
"code": null,
"e": 9306,
"s": 9263,
"text": "socket.write(data[, encoding][, callback])"
},
{
"code": null,
"e": 9431,
"s": 9306,
"text": "Sends data on the socket. The second parameter specifies the encoding in the case of a string--it defaults to UTF8 encoding."
},
{
"code": null,
"e": 9462,
"s": 9431,
"text": "socket.end([data][, encoding])"
},
{
"code": null,
"e": 9568,
"s": 9462,
"text": "Half-closes the socket, i.e., it sends a FIN packet. It is possible the server will still send some data."
},
{
"code": null,
"e": 9585,
"s": 9568,
"text": "socket.destroy()"
},
{
"code": null,
"e": 9697,
"s": 9585,
"text": "Ensures that no more I/O activity happens on this socket. Necessary only in case of errors (parse error or so)."
},
{
"code": null,
"e": 9712,
"s": 9697,
"text": "socket.pause()"
},
{
"code": null,
"e": 9819,
"s": 9712,
"text": "Pauses the reading of data. That is, 'data' events will not be emitted. Useful to throttle back an upload."
},
{
"code": null,
"e": 9835,
"s": 9819,
"text": "socket.resume()"
},
{
"code": null,
"e": 9876,
"s": 9835,
"text": "Resumes reading after a call to pause()."
},
{
"code": null,
"e": 9915,
"s": 9876,
"text": "socket.setTimeout(timeout[, callback])"
},
{
"code": null,
"e": 10046,
"s": 9915,
"text": "Sets the socket to timeout after timeout milliseconds of inactivity on the socket. By default, net.Socket does not have a timeout."
},
{
"code": null,
"e": 10075,
"s": 10046,
"text": "socket.setNoDelay([noDelay])"
},
{
"code": null,
"e": 10316,
"s": 10075,
"text": "Disables the Nagle algorithm. By default, TCP connections use the Nagle algorithm, they buffer data before sending it off. Setting true for noDelay will immediately fire off data each time socket.write() is called. noDelay defaults to true."
},
{
"code": null,
"e": 10362,
"s": 10316,
"text": "socket.setKeepAlive([enable][, initialDelay])"
},
{
"code": null,
"e": 10526,
"s": 10362,
"text": "Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket. enable defaults to false."
},
{
"code": null,
"e": 10543,
"s": 10526,
"text": "socket.address()"
},
{
"code": null,
"e": 10760,
"s": 10543,
"text": "Returns the bound address, the address family name, and the port of the socket as reported by the operating system. Returns an object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }."
},
{
"code": null,
"e": 10775,
"s": 10760,
"text": "socket.unref()"
},
{
"code": null,
"e": 10966,
"s": 10775,
"text": "Calling unref on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already unrefd, then calling unref again will have no effect."
},
{
"code": null,
"e": 10979,
"s": 10966,
"text": "socket.ref()"
},
{
"code": null,
"e": 11190,
"s": 10979,
"text": "Opposite of unref, calling ref on a previously unrefd socket will not let the program exit if it's the only socket left (the default behavior). If the socket is refd, then calling ref again will have no effect."
},
{
"code": null,
"e": 11249,
"s": 11190,
"text": "Create a js file named server.js with the following code β"
},
{
"code": null,
"e": 11265,
"s": 11249,
"text": "File: server.js"
},
{
"code": null,
"e": 11630,
"s": 11265,
"text": "var net = require('net');\nvar server = net.createServer(function(connection) { \n console.log('client connected');\n \n connection.on('end', function() {\n console.log('client disconnected');\n });\n \n connection.write('Hello World!\\r\\n');\n connection.pipe(connection);\n});\n\nserver.listen(8080, function() { \n console.log('server is listening');\n});"
},
{
"code": null,
"e": 11672,
"s": 11630,
"text": "Now run the server.js to see the result β"
},
{
"code": null,
"e": 11690,
"s": 11672,
"text": "$ node server.js\n"
},
{
"code": null,
"e": 11709,
"s": 11690,
"text": "Verify the Output."
},
{
"code": null,
"e": 11730,
"s": 11709,
"text": "server is listening\n"
},
{
"code": null,
"e": 11789,
"s": 11730,
"text": "Create a js file named client.js with the following code β"
},
{
"code": null,
"e": 11805,
"s": 11789,
"text": "File: client.js"
},
{
"code": null,
"e": 12099,
"s": 11805,
"text": "var net = require('net');\nvar client = net.connect({port: 8080}, function() {\n console.log('connected to server!'); \n});\n\nclient.on('data', function(data) {\n console.log(data.toString());\n client.end();\n});\n\nclient.on('end', function() { \n console.log('disconnected from server');\n});"
},
{
"code": null,
"e": 12163,
"s": 12099,
"text": "Now run the client.js from another terminal to see the result β"
},
{
"code": null,
"e": 12181,
"s": 12163,
"text": "$ node client.js\n"
},
{
"code": null,
"e": 12200,
"s": 12181,
"text": "Verify the Output."
},
{
"code": null,
"e": 12261,
"s": 12200,
"text": "connected to server!\nHello World!\n\ndisconnected from server\n"
},
{
"code": null,
"e": 12323,
"s": 12261,
"text": "Verify the Output on the terminal where server.js is running."
},
{
"code": null,
"e": 12381,
"s": 12323,
"text": "server is listening\nclient connected\nclient disconnected\n"
},
{
"code": null,
"e": 12416,
"s": 12381,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 12444,
"s": 12416,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12478,
"s": 12444,
"text": "\n 88 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 12506,
"s": 12478,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12541,
"s": 12506,
"text": "\n 32 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12556,
"s": 12541,
"text": " Richard Wells"
},
{
"code": null,
"e": 12587,
"s": 12556,
"text": "\n 8 Lectures \n 33 mins\n"
},
{
"code": null,
"e": 12601,
"s": 12587,
"text": " Anant Rungta"
},
{
"code": null,
"e": 12635,
"s": 12601,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12655,
"s": 12635,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 12688,
"s": 12655,
"text": "\n 97 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 12708,
"s": 12688,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 12715,
"s": 12708,
"text": " Print"
},
{
"code": null,
"e": 12726,
"s": 12715,
"text": " Add Notes"
}
] |
Explain the variable declaration, initialization and assignment in C language | The main purpose of variables is to store data in memory. Unlike constants, it will not change during the program execution. However, its value may be changed during execution.
The variable declaration indicates that the operating system is going to reserve a piece of memory with that variable name.
The syntax for variable declaration is as follows β
type variable_name;
or
type variable_name, variable_name, variable_name;
For example,
iInt a,b;
float c;
double d;
Here, a, b, c, d are variables. The int, float, double are the data types.
The syntax for variable initialization is as follows β
data type variablename=value;
For example,
int width, height=20;
char letter='R';
float base, area; //variable declaration
double d;
/* actual initialization */
width = 10;
area = 26.5;
A variable assignment is a process of assigning a value to a variable.
For example,
int height = 40;
int base = 31;
A variable may be alphabets, digits, and underscore.
A variable may be alphabets, digits, and underscore.
A variable name can start with an alphabet, and an underscore but, canβt start with a digit.
A variable name can start with an alphabet, and an underscore but, canβt start with a digit.
Whitespace is not allowed in the variable name.
Whitespace is not allowed in the variable name.
A variable name is not a reserved word or keyword. For example, int, goto etc.
A variable name is not a reserved word or keyword. For example, int, goto etc.
Following is the C program for variable assignment β
Live Demo
#include <stdio.h>
int main (){
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 40;
b = 50;
c = a + b;
printf("value of c : %d \n", c);
return 0;
}
When the above program is executed, it produces the following result β
Value of c: 90 | [
{
"code": null,
"e": 1239,
"s": 1062,
"text": "The main purpose of variables is to store data in memory. Unlike constants, it will not change during the program execution. However, its value may be changed during execution."
},
{
"code": null,
"e": 1363,
"s": 1239,
"text": "The variable declaration indicates that the operating system is going to reserve a piece of memory with that variable name."
},
{
"code": null,
"e": 1415,
"s": 1363,
"text": "The syntax for variable declaration is as follows β"
},
{
"code": null,
"e": 1435,
"s": 1415,
"text": "type variable_name;"
},
{
"code": null,
"e": 1438,
"s": 1435,
"text": "or"
},
{
"code": null,
"e": 1488,
"s": 1438,
"text": "type variable_name, variable_name, variable_name;"
},
{
"code": null,
"e": 1501,
"s": 1488,
"text": "For example,"
},
{
"code": null,
"e": 1530,
"s": 1501,
"text": "iInt a,b;\nfloat c;\ndouble d;"
},
{
"code": null,
"e": 1605,
"s": 1530,
"text": "Here, a, b, c, d are variables. The int, float, double are the data types."
},
{
"code": null,
"e": 1660,
"s": 1605,
"text": "The syntax for variable initialization is as follows β"
},
{
"code": null,
"e": 1690,
"s": 1660,
"text": "data type variablename=value;"
},
{
"code": null,
"e": 1703,
"s": 1690,
"text": "For example,"
},
{
"code": null,
"e": 1846,
"s": 1703,
"text": "int width, height=20;\nchar letter='R';\nfloat base, area; //variable declaration\ndouble d;\n/* actual initialization */\nwidth = 10;\narea = 26.5;"
},
{
"code": null,
"e": 1917,
"s": 1846,
"text": "A variable assignment is a process of assigning a value to a variable."
},
{
"code": null,
"e": 1930,
"s": 1917,
"text": "For example,"
},
{
"code": null,
"e": 1962,
"s": 1930,
"text": "int height = 40;\nint base = 31;"
},
{
"code": null,
"e": 2015,
"s": 1962,
"text": "A variable may be alphabets, digits, and underscore."
},
{
"code": null,
"e": 2068,
"s": 2015,
"text": "A variable may be alphabets, digits, and underscore."
},
{
"code": null,
"e": 2161,
"s": 2068,
"text": "A variable name can start with an alphabet, and an underscore but, canβt start with a digit."
},
{
"code": null,
"e": 2254,
"s": 2161,
"text": "A variable name can start with an alphabet, and an underscore but, canβt start with a digit."
},
{
"code": null,
"e": 2302,
"s": 2254,
"text": "Whitespace is not allowed in the variable name."
},
{
"code": null,
"e": 2350,
"s": 2302,
"text": "Whitespace is not allowed in the variable name."
},
{
"code": null,
"e": 2429,
"s": 2350,
"text": "A variable name is not a reserved word or keyword. For example, int, goto etc."
},
{
"code": null,
"e": 2508,
"s": 2429,
"text": "A variable name is not a reserved word or keyword. For example, int, goto etc."
},
{
"code": null,
"e": 2561,
"s": 2508,
"text": "Following is the C program for variable assignment β"
},
{
"code": null,
"e": 2572,
"s": 2561,
"text": " Live Demo"
},
{
"code": null,
"e": 2787,
"s": 2572,
"text": "#include <stdio.h>\nint main (){\n /* variable definition: */\n int a, b;\n int c;\n float f;\n /* actual initialization */\n a = 40;\n b = 50;\n c = a + b;\n printf(\"value of c : %d \\n\", c);\n return 0;\n}"
},
{
"code": null,
"e": 2858,
"s": 2787,
"text": "When the above program is executed, it produces the following result β"
},
{
"code": null,
"e": 2873,
"s": 2858,
"text": "Value of c: 90"
}
] |
Collections min() method in Java with Examples - GeeksforGeeks | 10 Oct, 2018
The min() method of java.util.Collections class is used to return the minimum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements in the collection must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the collection).
This method iterates over the entire collection, hence it requires time proportional to the size of the collection.
Syntax:
public static <T
extends Object & Comparable<? super T>> T
min(Collection<? extends T> coll)
Parameters: This method takes the collection coll as a parameter whose minimum element is to be determined
Return Value: This method returns the minimum element of the given collection, according to the natural ordering of its elements.
Exception: This method throws NoSuchElementException if the collection is empty.
Below are the examples to illustrate the min() method
Example 1:
// Java program to demonstrate// min() method// for <Integer> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create link list object List<Integer> list = new LinkedList<Integer>(); // populate the list list.add(10); list.add(20); list.add(30); list.add(40); // printing the List System.out.println("List: " + list); // getting minimum value // using min() method int min = Collections.min(list); // printing the min value System.out.println("Minimum value is: " + min); } catch (NoSuchElementException e) { System.out.println("Exception thrown : " + e); } }}
List: [10, 20, 30, 40]
Minimum value is: 10
Example 2: To demonstrate NoSuchElementException
// Java program to demonstrate// min() method for NoSuchElementException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create link list object List<Integer> list = new LinkedList<Integer>(); // printing the List System.out.println("List: " + list); // getting minimum value // using min() method System.out.println("Trying to get" + " the minimum value " + "with empty list"); int min = Collections.min(list); // printing the min value System.out.println("Min value is: " + min); } catch (NoSuchElementException e) { System.out.println("Exception thrown : " + e); } }}
List: []
Trying to get the minimum value with empty list
Exception thrown : java.util.NoSuchElementException
The min(Collections, Comparator) method of java.util.Collections class is used to return the minimum element of the given collection, according to the order induced by the specified comparator. All elements in the collection must be mutually comparable by the specified comparator .
This method iterates over the entire collection, hence it requires time proportional to the size of the collection.
Parameters: This method takes the following argument as parameters:
coll- the collection whose minimum element is to be determined.
comp- the comparator with which to determine the minimum element. A null value indicates that the elementsβ natural ordering should be used.
Return Value: This method returns the minimum element of the given collection, according to the specified comparator.
Exception: This method throws NoSuchElementException if the collection is empty.
Below are the examples to illustrate the min() method
Example 1:
// Java program to demonstrate// min() method// for Integer import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create link list object List<Integer> list = new LinkedList<Integer>(); // populate the list list.add(10); list.add(20); list.add(30); list.add(40); // printing the List System.out.println("List: " + list); // getting minimum value // using min() method int min = Collections.min(list, Collections.reverseOrder()); // printing the min value System.out.println("Min value by reverse order is: " + min); } catch (NoSuchElementException e) { System.out.println("Exception thrown : " + e); } }}
List: [10, 20, 30, 40]
Min value by reverse order is: 40
Example 2: To demonstrate NoSuchElementException
// Java program to demonstrate// min() method for NoSuchElementException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create link list object List<Integer> list = new LinkedList<Integer>(); // printing the List System.out.println("List: " + list); // getting minimum value // using min() method System.out.println("Trying to get" + " the minimum value " + "with empty list"); int min = Collections.min(list, Collections.reverseOrder()); // printing the min value System.out.println("Min value is: " + min); } catch (NoSuchElementException e) { System.out.println("Exception thrown : " + e); } }}
List: []
Trying to get the minimum value with empty list
Exception thrown : java.util.NoSuchElementException
Java - util package
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Stream In Java
Set in Java | [
{
"code": null,
"e": 24630,
"s": 24602,
"text": "\n10 Oct, 2018"
},
{
"code": null,
"e": 25046,
"s": 24630,
"text": "The min() method of java.util.Collections class is used to return the minimum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements in the collection must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the collection)."
},
{
"code": null,
"e": 25162,
"s": 25046,
"text": "This method iterates over the entire collection, hence it requires time proportional to the size of the collection."
},
{
"code": null,
"e": 25170,
"s": 25162,
"text": "Syntax:"
},
{
"code": null,
"e": 25271,
"s": 25170,
"text": "public static <T \n extends Object & Comparable<? super T>> T \n min(Collection<? extends T> coll)"
},
{
"code": null,
"e": 25378,
"s": 25271,
"text": "Parameters: This method takes the collection coll as a parameter whose minimum element is to be determined"
},
{
"code": null,
"e": 25508,
"s": 25378,
"text": "Return Value: This method returns the minimum element of the given collection, according to the natural ordering of its elements."
},
{
"code": null,
"e": 25589,
"s": 25508,
"text": "Exception: This method throws NoSuchElementException if the collection is empty."
},
{
"code": null,
"e": 25643,
"s": 25589,
"text": "Below are the examples to illustrate the min() method"
},
{
"code": null,
"e": 25654,
"s": 25643,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// min() method// for <Integer> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create link list object List<Integer> list = new LinkedList<Integer>(); // populate the list list.add(10); list.add(20); list.add(30); list.add(40); // printing the List System.out.println(\"List: \" + list); // getting minimum value // using min() method int min = Collections.min(list); // printing the min value System.out.println(\"Minimum value is: \" + min); } catch (NoSuchElementException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 26504,
"s": 25654,
"text": null
},
{
"code": null,
"e": 26549,
"s": 26504,
"text": "List: [10, 20, 30, 40]\nMinimum value is: 10\n"
},
{
"code": null,
"e": 26598,
"s": 26549,
"text": "Example 2: To demonstrate NoSuchElementException"
},
{
"code": "// Java program to demonstrate// min() method for NoSuchElementException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create link list object List<Integer> list = new LinkedList<Integer>(); // printing the List System.out.println(\"List: \" + list); // getting minimum value // using min() method System.out.println(\"Trying to get\" + \" the minimum value \" + \"with empty list\"); int min = Collections.min(list); // printing the min value System.out.println(\"Min value is: \" + min); } catch (NoSuchElementException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 27471,
"s": 26598,
"text": null
},
{
"code": null,
"e": 27581,
"s": 27471,
"text": "List: []\nTrying to get the minimum value with empty list\nException thrown : java.util.NoSuchElementException\n"
},
{
"code": null,
"e": 27864,
"s": 27581,
"text": "The min(Collections, Comparator) method of java.util.Collections class is used to return the minimum element of the given collection, according to the order induced by the specified comparator. All elements in the collection must be mutually comparable by the specified comparator ."
},
{
"code": null,
"e": 27980,
"s": 27864,
"text": "This method iterates over the entire collection, hence it requires time proportional to the size of the collection."
},
{
"code": null,
"e": 28048,
"s": 27980,
"text": "Parameters: This method takes the following argument as parameters:"
},
{
"code": null,
"e": 28112,
"s": 28048,
"text": "coll- the collection whose minimum element is to be determined."
},
{
"code": null,
"e": 28253,
"s": 28112,
"text": "comp- the comparator with which to determine the minimum element. A null value indicates that the elementsβ natural ordering should be used."
},
{
"code": null,
"e": 28371,
"s": 28253,
"text": "Return Value: This method returns the minimum element of the given collection, according to the specified comparator."
},
{
"code": null,
"e": 28452,
"s": 28371,
"text": "Exception: This method throws NoSuchElementException if the collection is empty."
},
{
"code": null,
"e": 28506,
"s": 28452,
"text": "Below are the examples to illustrate the min() method"
},
{
"code": null,
"e": 28517,
"s": 28506,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// min() method// for Integer import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create link list object List<Integer> list = new LinkedList<Integer>(); // populate the list list.add(10); list.add(20); list.add(30); list.add(40); // printing the List System.out.println(\"List: \" + list); // getting minimum value // using min() method int min = Collections.min(list, Collections.reverseOrder()); // printing the min value System.out.println(\"Min value by reverse order is: \" + min); } catch (NoSuchElementException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 29458,
"s": 28517,
"text": null
},
{
"code": null,
"e": 29516,
"s": 29458,
"text": "List: [10, 20, 30, 40]\nMin value by reverse order is: 40\n"
},
{
"code": null,
"e": 29565,
"s": 29516,
"text": "Example 2: To demonstrate NoSuchElementException"
},
{
"code": "// Java program to demonstrate// min() method for NoSuchElementException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create link list object List<Integer> list = new LinkedList<Integer>(); // printing the List System.out.println(\"List: \" + list); // getting minimum value // using min() method System.out.println(\"Trying to get\" + \" the minimum value \" + \"with empty list\"); int min = Collections.min(list, Collections.reverseOrder()); // printing the min value System.out.println(\"Min value is: \" + min); } catch (NoSuchElementException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 30503,
"s": 29565,
"text": null
},
{
"code": null,
"e": 30613,
"s": 30503,
"text": "List: []\nTrying to get the minimum value with empty list\nException thrown : java.util.NoSuchElementException\n"
},
{
"code": null,
"e": 30633,
"s": 30613,
"text": "Java - util package"
},
{
"code": null,
"e": 30650,
"s": 30633,
"text": "Java-Collections"
},
{
"code": null,
"e": 30665,
"s": 30650,
"text": "Java-Functions"
},
{
"code": null,
"e": 30670,
"s": 30665,
"text": "Java"
},
{
"code": null,
"e": 30675,
"s": 30670,
"text": "Java"
},
{
"code": null,
"e": 30692,
"s": 30675,
"text": "Java-Collections"
},
{
"code": null,
"e": 30790,
"s": 30692,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30822,
"s": 30790,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30873,
"s": 30822,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30892,
"s": 30873,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30910,
"s": 30892,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30941,
"s": 30910,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30973,
"s": 30941,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30993,
"s": 30973,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 31017,
"s": 30993,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 31032,
"s": 31017,
"text": "Stream In Java"
}
] |
Servlets - Debugging | It is always difficult to testing/debugging a servlets. Servlets tend to involve a large amount of client/server interaction, making errors likely but hard to reproduce.
Here are a few hints and suggestions that may aid you in your debugging.
System.out.println() is easy to use as a marker to test whether a certain piece of code is being executed or not. We can print out variable values as well. Additionally β
Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications.
Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications.
Stopping at breakpoints technique stops the normal execution hence takes more time. Whereas writing to System.out doesn't interfere much with the normal execution flow of the application, which makes it very valuable when timing is crucial.
Stopping at breakpoints technique stops the normal execution hence takes more time. Whereas writing to System.out doesn't interfere much with the normal execution flow of the application, which makes it very valuable when timing is crucial.
Following is the syntax to use System.out.println() β
System.out.println("Debugging message");
All the messages generated by above syntax would be logged in web server log file.
It is always great idea to use proper logging method to log all the debug, warning and error messages using a standard logging method. I use log4J to log all the messages.
The Servlet API also provides a simple way of outputting information by using the log() method as follows β
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ContextLog extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
String par = request.getParameter("par1");
//Call the two ServletContext.log methods
ServletContext context = getServletContext( );
if (par == null || par.equals(""))
//log version with Throwable parameter
context.log("No message received:", new IllegalStateException("Missing parameter"));
else
context.log("Here is the visitor's message: " + par);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
String title = "Context Log";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<h2 align = \"center\">Messages sent</h2>\n" +
"</body>
</html>"
);
} //doGet
}
The ServletContext logs its text messages to the servlet container's log file. With Tomcat these logs are found in <Tomcat-installation-directory>/logs.
The log files do give an indication of new emerging bugs or the frequency of problems. For that reason it's good to use the log() function in the catch clause of exceptions which should normally not occur.
You can debug servlets with the same jdb commands you use to debug an applet or an application.
To debug a servlet, we debug sun.servlet.http.HttpServer and carefully watch as HttpServer executes servlets in response to HTTP requests made from browser. This is very similar to how applets are debugged. The difference is that with applets, the actual program being debugged is sun.applet.AppletViewer.
Most debuggers hide this detail by automatically knowing how to debug applets. Until they do the same for servlets, you have to help your debugger by doing the following β
Set your debugger's classpath so that it can find sun.servlet.http.Http-Server and associated classes.
Set your debugger's classpath so that it can find sun.servlet.http.Http-Server and associated classes.
Set your debugger's classpath so that it can also find your servlets and support classes, typically server_root/servlets and server_root/classes.
Set your debugger's classpath so that it can also find your servlets and support classes, typically server_root/servlets and server_root/classes.
You normally wouldn't want server_root/servlets in your classpath because it disables servlet reloading. This inclusion, however, is useful for debugging. It allows your debugger to set breakpoints in a servlet before the custom servlet loader in HttpServer loads the servlet.
Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints in whatever servlet you're interested in debugging, then use a web browser to make a request to the HttpServer for the given servlet (http://localhost:8080/servlet/ServletToDebug). You should see execution being stopped at your breakpoints.
Comments in your code can help the debugging process in various ways. Comments can be used in lots of other ways in the debugging process.
The Servlet uses Java comments and single line (// ...) and multiple line (/* ... */) comments can be used to temporarily remove parts of your Java code. If the bug disappears, take a closer look at the code you just commented and find out the problem.
Sometimes when a servlet doesn't behave as expected, it's useful to look at the raw HTTP request and response. If you're familiar with the structure of HTTP, you can read the request and response and see exactly what exactly is going with those headers.
Here is a list of some more debugging tips on servlet debugging β
Remember that server_root/classes doesn't reload and that server_root/servlets probably does.
Remember that server_root/classes doesn't reload and that server_root/servlets probably does.
Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's usually an option under the View menu.
Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's usually an option under the View menu.
Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh.
Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh.
Verify that your servlet's init() method takes a ServletConfig parameter and calls super.init(config) right away.
Verify that your servlet's init() method takes a ServletConfig parameter and calls super.init(config) right away.
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
31 Lectures
12.5 hours
Uplatz
38 Lectures
4.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2355,
"s": 2185,
"text": "It is always difficult to testing/debugging a servlets. Servlets tend to involve a large amount of client/server interaction, making errors likely but hard to reproduce."
},
{
"code": null,
"e": 2428,
"s": 2355,
"text": "Here are a few hints and suggestions that may aid you in your debugging."
},
{
"code": null,
"e": 2599,
"s": 2428,
"text": "System.out.println() is easy to use as a marker to test whether a certain piece of code is being executed or not. We can print out variable values as well. Additionally β"
},
{
"code": null,
"e": 2828,
"s": 2599,
"text": "Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications."
},
{
"code": null,
"e": 3057,
"s": 2828,
"text": "Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications."
},
{
"code": null,
"e": 3298,
"s": 3057,
"text": "Stopping at breakpoints technique stops the normal execution hence takes more time. Whereas writing to System.out doesn't interfere much with the normal execution flow of the application, which makes it very valuable when timing is crucial."
},
{
"code": null,
"e": 3539,
"s": 3298,
"text": "Stopping at breakpoints technique stops the normal execution hence takes more time. Whereas writing to System.out doesn't interfere much with the normal execution flow of the application, which makes it very valuable when timing is crucial."
},
{
"code": null,
"e": 3593,
"s": 3539,
"text": "Following is the syntax to use System.out.println() β"
},
{
"code": null,
"e": 3634,
"s": 3593,
"text": "System.out.println(\"Debugging message\");"
},
{
"code": null,
"e": 3717,
"s": 3634,
"text": "All the messages generated by above syntax would be logged in web server log file."
},
{
"code": null,
"e": 3889,
"s": 3717,
"text": "It is always great idea to use proper logging method to log all the debug, warning and error messages using a standard logging method. I use log4J to log all the messages."
},
{
"code": null,
"e": 3997,
"s": 3889,
"text": "The Servlet API also provides a simple way of outputting information by using the log() method as follows β"
},
{
"code": null,
"e": 5303,
"s": 3997,
"text": "// Import required java libraries\nimport java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n\npublic class ContextLog extends HttpServlet {\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, java.io.IOException {\n \n String par = request.getParameter(\"par1\");\n \n //Call the two ServletContext.log methods\n ServletContext context = getServletContext( );\n\n if (par == null || par.equals(\"\"))\n //log version with Throwable parameter\n context.log(\"No message received:\", new IllegalStateException(\"Missing parameter\"));\n else\n context.log(\"Here is the visitor's message: \" + par);\n \n response.setContentType(\"text/html\");\n java.io.PrintWriter out = response.getWriter( );\n String title = \"Context Log\";\n String docType =\n \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" + \"transitional//en\\\">\\n\";\n \n out.println(docType +\n \"<html>\\n\" +\n \"<head><title>\" + title + \"</title></head>\\n\" +\n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" +\n \"<h1 align = \\\"center\\\">\" + title + \"</h1>\\n\" +\n \"<h2 align = \\\"center\\\">Messages sent</h2>\\n\" +\n \"</body>\n </html>\"\n );\n } //doGet\n}"
},
{
"code": null,
"e": 5457,
"s": 5303,
"text": "The ServletContext logs its text messages to the servlet container's log file. With Tomcat these logs are found in <Tomcat-installation-directory>/logs. "
},
{
"code": null,
"e": 5663,
"s": 5457,
"text": "The log files do give an indication of new emerging bugs or the frequency of problems. For that reason it's good to use the log() function in the catch clause of exceptions which should normally not occur."
},
{
"code": null,
"e": 5759,
"s": 5663,
"text": "You can debug servlets with the same jdb commands you use to debug an applet or an application."
},
{
"code": null,
"e": 6065,
"s": 5759,
"text": "To debug a servlet, we debug sun.servlet.http.HttpServer and carefully watch as HttpServer executes servlets in response to HTTP requests made from browser. This is very similar to how applets are debugged. The difference is that with applets, the actual program being debugged is sun.applet.AppletViewer."
},
{
"code": null,
"e": 6237,
"s": 6065,
"text": "Most debuggers hide this detail by automatically knowing how to debug applets. Until they do the same for servlets, you have to help your debugger by doing the following β"
},
{
"code": null,
"e": 6340,
"s": 6237,
"text": "Set your debugger's classpath so that it can find sun.servlet.http.Http-Server and associated classes."
},
{
"code": null,
"e": 6443,
"s": 6340,
"text": "Set your debugger's classpath so that it can find sun.servlet.http.Http-Server and associated classes."
},
{
"code": null,
"e": 6589,
"s": 6443,
"text": "Set your debugger's classpath so that it can also find your servlets and support classes, typically server_root/servlets and server_root/classes."
},
{
"code": null,
"e": 6735,
"s": 6589,
"text": "Set your debugger's classpath so that it can also find your servlets and support classes, typically server_root/servlets and server_root/classes."
},
{
"code": null,
"e": 7012,
"s": 6735,
"text": "You normally wouldn't want server_root/servlets in your classpath because it disables servlet reloading. This inclusion, however, is useful for debugging. It allows your debugger to set breakpoints in a servlet before the custom servlet loader in HttpServer loads the servlet."
},
{
"code": null,
"e": 7362,
"s": 7012,
"text": "Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints in whatever servlet you're interested in debugging, then use a web browser to make a request to the HttpServer for the given servlet (http://localhost:8080/servlet/ServletToDebug). You should see execution being stopped at your breakpoints."
},
{
"code": null,
"e": 7501,
"s": 7362,
"text": "Comments in your code can help the debugging process in various ways. Comments can be used in lots of other ways in the debugging process."
},
{
"code": null,
"e": 7754,
"s": 7501,
"text": "The Servlet uses Java comments and single line (// ...) and multiple line (/* ... */) comments can be used to temporarily remove parts of your Java code. If the bug disappears, take a closer look at the code you just commented and find out the problem."
},
{
"code": null,
"e": 8008,
"s": 7754,
"text": "Sometimes when a servlet doesn't behave as expected, it's useful to look at the raw HTTP request and response. If you're familiar with the structure of HTTP, you can read the request and response and see exactly what exactly is going with those headers."
},
{
"code": null,
"e": 8074,
"s": 8008,
"text": "Here is a list of some more debugging tips on servlet debugging β"
},
{
"code": null,
"e": 8168,
"s": 8074,
"text": "Remember that server_root/classes doesn't reload and that server_root/servlets probably does."
},
{
"code": null,
"e": 8262,
"s": 8168,
"text": "Remember that server_root/classes doesn't reload and that server_root/servlets probably does."
},
{
"code": null,
"e": 8418,
"s": 8262,
"text": "Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's usually an option under the View menu."
},
{
"code": null,
"e": 8574,
"s": 8418,
"text": "Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's usually an option under the View menu."
},
{
"code": null,
"e": 8761,
"s": 8574,
"text": "Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh."
},
{
"code": null,
"e": 8948,
"s": 8761,
"text": "Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh."
},
{
"code": null,
"e": 9063,
"s": 8948,
"text": "Verify that your servlet's init() method takes a ServletConfig parameter and calls super.init(config) right away. "
},
{
"code": null,
"e": 9178,
"s": 9063,
"text": "Verify that your servlet's init() method takes a ServletConfig parameter and calls super.init(config) right away. "
},
{
"code": null,
"e": 9213,
"s": 9178,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9227,
"s": 9213,
"text": " Karthikeya T"
},
{
"code": null,
"e": 9262,
"s": 9227,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9278,
"s": 9262,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 9311,
"s": 9278,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 9327,
"s": 9311,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 9363,
"s": 9327,
"text": "\n 31 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 9371,
"s": 9363,
"text": " Uplatz"
},
{
"code": null,
"e": 9406,
"s": 9371,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9424,
"s": 9406,
"text": " Packt Publishing"
},
{
"code": null,
"e": 9431,
"s": 9424,
"text": " Print"
},
{
"code": null,
"e": 9442,
"s": 9431,
"text": " Add Notes"
}
] |
C# - While Loop | A while loop statement in C# repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop in C# is β
while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body is skipped and the first statement after the while loop is executed.
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* while loop execution */
while (a < 20) {
Console.WriteLine("value of a: {0}", a);
a++;
}
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result β
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2376,
"s": 2270,
"text": "A while loop statement in C# repeatedly executes a target statement as long as a given condition is true."
},
{
"code": null,
"e": 2414,
"s": 2376,
"text": "The syntax of a while loop in C# is β"
},
{
"code": null,
"e": 2453,
"s": 2414,
"text": "while(condition) {\n statement(s);\n}\n"
},
{
"code": null,
"e": 2640,
"s": 2453,
"text": "Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true."
},
{
"code": null,
"e": 2741,
"s": 2640,
"text": "When the condition becomes false, program control passes to the line immediately following the loop."
},
{
"code": null,
"e": 2949,
"s": 2741,
"text": "Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body is skipped and the first statement after the while loop is executed."
},
{
"code": null,
"e": 3292,
"s": 2949,
"text": "using System;\n\nnamespace Loops {\n class Program {\n static void Main(string[] args) {\n /* local variable definition */\n int a = 10;\n\n /* while loop execution */\n while (a < 20) {\n Console.WriteLine(\"value of a: {0}\", a);\n a++;\n }\n Console.ReadLine();\n }\n }\n} "
},
{
"code": null,
"e": 3373,
"s": 3292,
"text": "When the above code is compiled and executed, it produces the following result β"
},
{
"code": null,
"e": 3524,
"s": 3373,
"text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n"
},
{
"code": null,
"e": 3561,
"s": 3524,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 3574,
"s": 3561,
"text": " Raja Biswas"
},
{
"code": null,
"e": 3608,
"s": 3574,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3626,
"s": 3608,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 3659,
"s": 3626,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3673,
"s": 3659,
"text": " Peter Jepson"
},
{
"code": null,
"e": 3710,
"s": 3673,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 3725,
"s": 3710,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 3760,
"s": 3725,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3775,
"s": 3760,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3810,
"s": 3775,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3822,
"s": 3810,
"text": " Eric Frick"
},
{
"code": null,
"e": 3829,
"s": 3822,
"text": " Print"
},
{
"code": null,
"e": 3840,
"s": 3829,
"text": " Add Notes"
}
] |
GATE | GATE-CS-2006 | Question 49 | 28 Jun, 2021
An implementation of a queue Q, using two stacks S1 and S2, is given below:
void insert(Q, x) { push (S1, x);} void delete(Q){ if(stack-empty(S2)) then if(stack-empty(S1)) then { print(βQ is emptyβ); return; } else while (!(stack-empty(S1))){ x=pop(S1); push(S2,x); } x=pop(S2);}
Let n insert and m (<=n) delete operations be performed in an arbitrary order on an empty queue Q. Let x and y be the number of push and pop operations performed respectively in the process. Which one of the following is true for all m and n?(A) n+m <= x < 2n and 2m <= y <= n+m(B) n+m <= x < 2n and 2m<= y <= 2n(C) 2m <= x < 2n and 2m <= y <= n+m(D) 2m <= x <2n and 2m <= y <= 2nAnswer: (A)Explanation: Same as https://www.geeksforgeeks.org/data-structures-queue-question-10/Quiz of this Question
GATE-CS-2006
GATE-GATE-CS-2006
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 130,
"s": 54,
"text": "An implementation of a queue Q, using two stacks S1 and S2, is given below:"
},
{
"code": "void insert(Q, x) { push (S1, x);} void delete(Q){ if(stack-empty(S2)) then if(stack-empty(S1)) then { print(βQ is emptyβ); return; } else while (!(stack-empty(S1))){ x=pop(S1); push(S2,x); } x=pop(S2);}",
"e": 399,
"s": 130,
"text": null
},
{
"code": null,
"e": 897,
"s": 399,
"text": "Let n insert and m (<=n) delete operations be performed in an arbitrary order on an empty queue Q. Let x and y be the number of push and pop operations performed respectively in the process. Which one of the following is true for all m and n?(A) n+m <= x < 2n and 2m <= y <= n+m(B) n+m <= x < 2n and 2m<= y <= 2n(C) 2m <= x < 2n and 2m <= y <= n+m(D) 2m <= x <2n and 2m <= y <= 2nAnswer: (A)Explanation: Same as https://www.geeksforgeeks.org/data-structures-queue-question-10/Quiz of this Question"
},
{
"code": null,
"e": 910,
"s": 897,
"text": "GATE-CS-2006"
},
{
"code": null,
"e": 928,
"s": 910,
"text": "GATE-GATE-CS-2006"
},
{
"code": null,
"e": 933,
"s": 928,
"text": "GATE"
}
] |
Highest power of a number that divides other number | 16 Nov, 2021
Given two numbers N and M, the task is to find the highest power of M that divides N. Note: M > 1 Examples:
Input: N = 48, M = 4 Output: 2 48 % (4^2) = 0 Input: N = 32, M = 20 Output: 0 32 % (20^0) = 0
Approach: Initially prime factorize both the numbers N and M and store the count of prime factors in freq1[] and freq2[] respectively for N and M. For every prime factor of M, check if its freq2[num] is greater than freq1[num] or not. If it is for any prime factor of M, then max power will be 0. Else the maximum power will be the minimum of all freq1[num] / freq2[num] for every prime factor of M. For a number N = 24, the prime factors will 2^3 * 3^1. Hence freq1[2] = 3 and freq1[3] = 1. Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to get the prime factors// and its count of times it dividesvoid primeFactors(int n, int freq[]){ int cnt = 0; // Count the number of 2s that divide n while (n % 2 == 0) { cnt++; n = n / 2; } freq[2] = cnt; // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { cnt = 0; // While i divides n, count i and divide n while (n % i == 0) { cnt++; n = n / i; } freq[i] = cnt; } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) freq[n] = 1;} // Function to return the highest powerint getMaximumPower(int n, int m){ // Initialize two arrays int freq1[n + 1], freq2[m + 1]; memset(freq1, 0, sizeof freq1); memset(freq2, 0, sizeof freq2); // Get the prime factors of n and m primeFactors(n, freq1); primeFactors(m, freq2); int maxi = 0; // Iterate and find the maximum power for (int i = 2; i <= m; i++) { // If i not a prime factor of n and m if (freq1[i] == 0 && freq2[i] == 0) continue; // If i is a prime factor of n and m // If count of i dividing m is more // than i dividing n, then power will be 0 if (freq2[i] > freq1[i]) return 0; // If i is a prime factor of M if (freq2[i]) { // get the maximum power maxi = max(maxi, freq1[i] / freq2[i]); } } return maxi;} // Drivers codeint main(){ int n = 48, m = 4; cout << getMaximumPower(n, m); return 0;}
// Java program to implement// the above approach class GFG{ // Function to get the prime factors// and its count of times it dividesstatic void primeFactors(int n, int freq[]){ int cnt = 0; // Count the number of 2s that divide n while (n % 2 == 0) { cnt++; n = n / 2; } freq[2] = cnt; // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i = i + 2) { cnt = 0; // While i divides n, count i and divide n while (n % i == 0) { cnt++; n = n / i; } freq[i] = cnt; } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) freq[n] = 1;} // Function to return the highest powerstatic int getMaximumPower(int n, int m){ // Initialize two arrays int freq1[] = new int[n + 1], freq2[] = new int[m + 1]; // Get the prime factors of n and m primeFactors(n, freq1); primeFactors(m, freq2); int maxi = 0; // Iterate and find the maximum power for (int i = 2; i <= m; i++) { // If i not a prime factor of n and m if (freq1[i] == 0 && freq2[i] == 0) continue; // If i is a prime factor of n and m // If count of i dividing m is more // than i dividing n, then power will be 0 if (freq2[i] > freq1[i]) return 0; // If i is a prime factor of M if (freq2[i] != 0) { // get the maximum power maxi = Math.max(maxi, freq1[i] / freq2[i]); } } return maxi;} // Drivers codepublic static void main(String[] args){ int n = 48, m = 4; System.out.println(getMaximumPower(n, m)); }} // This code contributed by Rajput-Ji
import math # Python program to implement# the above approach # Function to get the prime factors# and its count of times it dividesdef primeFactors(n, freq): cnt = 0 # Count the number of 2s that divide n while n % 2 == 0: cnt = cnt + 1 n = int(n // 2) freq[2] = cnt # n must be odd at this point. So we can skip # one element (Note i = i+2) i=3 while i<=math.sqrt(n): cnt = 0 # While i divides n, count i and divide n while (n % i == 0): cnt = cnt+1 n = int(n // i) freq[int(i)] = cnt i=i + 2 # This condition is to handle the case when n # is a prime number greater than 2 if (n > 2): freq[int(n)] = 1 # Function to return the highest powerdef getMaximumPower(n, m): # Initialize two arrays freq1 = [0] * (n + 1) freq2 = [0] * (m + 1) # Get the prime factors of n and m primeFactors(n, freq1) primeFactors(m, freq2) maxi = 0 # Iterate and find the maximum power i = 2 while i <= m: # If i not a prime factor of n and m if (freq1[i] == 0 and freq2[i] == 0): i = i + 1 continue # If i is a prime factor of n and m # If count of i dividing m is more # than i dividing n, then power will be 0 if (freq2[i] > freq1[i]): return 0 # If i is a prime factor of M if (freq2[i]): # get the maximum power maxi = max(maxi, int(freq1[i] // freq2[i])) i = i + 1 return maxi # Drivers coden = 48m = 4print(getMaximumPower(n, m)) # This code is contributed by Shashank_Sharma
// C# program to implement// the above approachusing System; class GFG{ // Function to get the prime factors// and its count of times it dividesstatic void primeFactors(int n, int []freq){ int cnt = 0; // Count the number of 2s that divide n while (n % 2 == 0) { cnt++; n = n / 2; } freq[2] = cnt; // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i = i + 2) { cnt = 0; // While i divides n, count i and divide n while (n % i == 0) { cnt++; n = n / i; } freq[i] = cnt; } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) freq[n] = 1;} // Function to return the highest powerstatic int getMaximumPower(int n, int m){ // Initialize two arrays int []freq1 = new int[n + 1];int []freq2 = new int[m + 1]; // Get the prime factors of n and m primeFactors(n, freq1); primeFactors(m, freq2); int maxi = 0; // Iterate and find the maximum power for (int i = 2; i <= m; i++) { // If i not a prime factor of n and m if (freq1[i] == 0 && freq2[i] == 0) continue; // If i is a prime factor of n and m // If count of i dividing m is more // than i dividing n, then power will be 0 if (freq2[i] > freq1[i]) return 0; // If i is a prime factor of M if (freq2[i] != 0) { // get the maximum power maxi = Math.Max(maxi, freq1[i] / freq2[i]); } } return maxi;} // Drivers codepublic static void Main(String[] args){ int n = 48, m = 4; Console.WriteLine(getMaximumPower(n, m)); }} // This code has been contributed by 29AjayKumar
<?php// PHP program to implement// the above approach // Function to get the prime factors// and its count of times it dividesfunction primeFactors($n, $freq){ $cnt = 0; // Count the number of 2s that divide n while ($n % 2 == 0) { $cnt++; $n = floor($n / 2); } $freq[2] = $cnt; // n must be odd at this point. So we can skip // one element (Note i = i +2) for ($i = 3; $i <= sqrt($n); $i = $i + 2) { $cnt = 0; // While i divides n, count i and divide n while ($n % $i == 0) { $cnt++; $n = floor($n / $i); } $freq[$i] = $cnt; } // This condition is to handle the case when n // is a prime number greater than 2 if ($n > 2) $freq[$n] = 1; return $freq ;} // Function to return the highest powerfunction getMaximumPower($n, $m){ $freq1 = array_fill(0,$n + 1,0); $freq2 = array_fill(0,$m + 1,0); // Get the prime factors of n and m $freq1 = primeFactors($n, $freq1); $freq2 = primeFactors($m, $freq2); $maxi = 0; // Iterate and find the maximum power for ($i = 2; $i <= $m; $i++) { // If i not a prime factor of n and m if ($freq1[$i] == 0 && $freq2[$i] == 0) continue; // If i is a prime factor of n and m // If count of i dividing m is more // than i dividing n, then power will be 0 if ($freq2[$i] > $freq1[$i]) return 0; // If i is a prime factor of M if ($freq2[$i]) { // get the maximum power $maxi = max($maxi, floor($freq1[$i] / $freq2[$i])); } } return $maxi;} // Drivers code $n = 48; $m = 4; echo getMaximumPower($n, $m); // This code is contributed by Ryuga?>
<script> // Javascript program to implement// the above approach // Function to get the prime factors// and its count of times it dividesfunction primeFactors(n, freq){ var cnt = 0; // Count the number of 2s that divide n while (n % 2 == 0) { cnt++; n = n / 2; } freq[2] = cnt; var i; // n must be odd at this point. So we can skip // one element (Note i = i +2) for (i = 3; i <= Math.sqrt(n); i = i + 2) { cnt = 0; // While i divides n, count i and divide n while (n % i == 0) { cnt++; n = n / i; } freq[i] = cnt; } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) freq[n] = 1;} // Function to return the highest powerfunction getMaximumPower(n, m){ // Initialize two arrays var freq1 = new Array(n+1); var freq2 = new Array(m+1); // Get the prime factors of n and m primeFactors(n, freq1); primeFactors(m, freq2); var maxi = 0; // Iterate and find the maximum power for(i = 2; i <= m; i++) { // If i not a prime factor of n and m if (freq1[i] == 0 && freq2[i] == 0) continue; // If i is a prime factor of n and m // If count of i dividing m is more // than i dividing n, then power will be 0 if (freq2[i] > freq1[i]) return 0; // If i is a prime factor of M if (freq2[i]) { // get the maximum power maxi = Math.max(maxi, freq1[i]/freq2[i]); } } return maxi;} // Drivers code var n = 48, m = 4; document.write(getMaximumPower(n, m)); </script>
2
Time Complexity: O(n log log n)
Auxiliary Space: O(max(m,n))
ankthon
Rajput-Ji
29AjayKumar
Shashank_Sharma
SURENDRA_GANGWAR
rohan07
frequency-counting
Number Divisibility
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "Given two numbers N and M, the task is to find the highest power of M that divides N. Note: M > 1 Examples: "
},
{
"code": null,
"e": 233,
"s": 138,
"text": "Input: N = 48, M = 4 Output: 2 48 % (4^2) = 0 Input: N = 32, M = 20 Output: 0 32 % (20^0) = 0 "
},
{
"code": null,
"e": 778,
"s": 233,
"text": "Approach: Initially prime factorize both the numbers N and M and store the count of prime factors in freq1[] and freq2[] respectively for N and M. For every prime factor of M, check if its freq2[num] is greater than freq1[num] or not. If it is for any prime factor of M, then max power will be 0. Else the maximum power will be the minimum of all freq1[num] / freq2[num] for every prime factor of M. For a number N = 24, the prime factors will 2^3 * 3^1. Hence freq1[2] = 3 and freq1[3] = 1. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 782,
"s": 778,
"text": "C++"
},
{
"code": null,
"e": 787,
"s": 782,
"text": "Java"
},
{
"code": null,
"e": 796,
"s": 787,
"text": "Python 3"
},
{
"code": null,
"e": 799,
"s": 796,
"text": "C#"
},
{
"code": null,
"e": 803,
"s": 799,
"text": "PHP"
},
{
"code": null,
"e": 814,
"s": 803,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to get the prime factors// and its count of times it dividesvoid primeFactors(int n, int freq[]){ int cnt = 0; // Count the number of 2s that divide n while (n % 2 == 0) { cnt++; n = n / 2; } freq[2] = cnt; // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { cnt = 0; // While i divides n, count i and divide n while (n % i == 0) { cnt++; n = n / i; } freq[i] = cnt; } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) freq[n] = 1;} // Function to return the highest powerint getMaximumPower(int n, int m){ // Initialize two arrays int freq1[n + 1], freq2[m + 1]; memset(freq1, 0, sizeof freq1); memset(freq2, 0, sizeof freq2); // Get the prime factors of n and m primeFactors(n, freq1); primeFactors(m, freq2); int maxi = 0; // Iterate and find the maximum power for (int i = 2; i <= m; i++) { // If i not a prime factor of n and m if (freq1[i] == 0 && freq2[i] == 0) continue; // If i is a prime factor of n and m // If count of i dividing m is more // than i dividing n, then power will be 0 if (freq2[i] > freq1[i]) return 0; // If i is a prime factor of M if (freq2[i]) { // get the maximum power maxi = max(maxi, freq1[i] / freq2[i]); } } return maxi;} // Drivers codeint main(){ int n = 48, m = 4; cout << getMaximumPower(n, m); return 0;}",
"e": 2562,
"s": 814,
"text": null
},
{
"code": "// Java program to implement// the above approach class GFG{ // Function to get the prime factors// and its count of times it dividesstatic void primeFactors(int n, int freq[]){ int cnt = 0; // Count the number of 2s that divide n while (n % 2 == 0) { cnt++; n = n / 2; } freq[2] = cnt; // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i = i + 2) { cnt = 0; // While i divides n, count i and divide n while (n % i == 0) { cnt++; n = n / i; } freq[i] = cnt; } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) freq[n] = 1;} // Function to return the highest powerstatic int getMaximumPower(int n, int m){ // Initialize two arrays int freq1[] = new int[n + 1], freq2[] = new int[m + 1]; // Get the prime factors of n and m primeFactors(n, freq1); primeFactors(m, freq2); int maxi = 0; // Iterate and find the maximum power for (int i = 2; i <= m; i++) { // If i not a prime factor of n and m if (freq1[i] == 0 && freq2[i] == 0) continue; // If i is a prime factor of n and m // If count of i dividing m is more // than i dividing n, then power will be 0 if (freq2[i] > freq1[i]) return 0; // If i is a prime factor of M if (freq2[i] != 0) { // get the maximum power maxi = Math.max(maxi, freq1[i] / freq2[i]); } } return maxi;} // Drivers codepublic static void main(String[] args){ int n = 48, m = 4; System.out.println(getMaximumPower(n, m)); }} // This code contributed by Rajput-Ji",
"e": 4350,
"s": 2562,
"text": null
},
{
"code": "import math # Python program to implement# the above approach # Function to get the prime factors# and its count of times it dividesdef primeFactors(n, freq): cnt = 0 # Count the number of 2s that divide n while n % 2 == 0: cnt = cnt + 1 n = int(n // 2) freq[2] = cnt # n must be odd at this point. So we can skip # one element (Note i = i+2) i=3 while i<=math.sqrt(n): cnt = 0 # While i divides n, count i and divide n while (n % i == 0): cnt = cnt+1 n = int(n // i) freq[int(i)] = cnt i=i + 2 # This condition is to handle the case when n # is a prime number greater than 2 if (n > 2): freq[int(n)] = 1 # Function to return the highest powerdef getMaximumPower(n, m): # Initialize two arrays freq1 = [0] * (n + 1) freq2 = [0] * (m + 1) # Get the prime factors of n and m primeFactors(n, freq1) primeFactors(m, freq2) maxi = 0 # Iterate and find the maximum power i = 2 while i <= m: # If i not a prime factor of n and m if (freq1[i] == 0 and freq2[i] == 0): i = i + 1 continue # If i is a prime factor of n and m # If count of i dividing m is more # than i dividing n, then power will be 0 if (freq2[i] > freq1[i]): return 0 # If i is a prime factor of M if (freq2[i]): # get the maximum power maxi = max(maxi, int(freq1[i] // freq2[i])) i = i + 1 return maxi # Drivers coden = 48m = 4print(getMaximumPower(n, m)) # This code is contributed by Shashank_Sharma",
"e": 6026,
"s": 4350,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to get the prime factors// and its count of times it dividesstatic void primeFactors(int n, int []freq){ int cnt = 0; // Count the number of 2s that divide n while (n % 2 == 0) { cnt++; n = n / 2; } freq[2] = cnt; // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= Math.Sqrt(n); i = i + 2) { cnt = 0; // While i divides n, count i and divide n while (n % i == 0) { cnt++; n = n / i; } freq[i] = cnt; } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) freq[n] = 1;} // Function to return the highest powerstatic int getMaximumPower(int n, int m){ // Initialize two arrays int []freq1 = new int[n + 1];int []freq2 = new int[m + 1]; // Get the prime factors of n and m primeFactors(n, freq1); primeFactors(m, freq2); int maxi = 0; // Iterate and find the maximum power for (int i = 2; i <= m; i++) { // If i not a prime factor of n and m if (freq1[i] == 0 && freq2[i] == 0) continue; // If i is a prime factor of n and m // If count of i dividing m is more // than i dividing n, then power will be 0 if (freq2[i] > freq1[i]) return 0; // If i is a prime factor of M if (freq2[i] != 0) { // get the maximum power maxi = Math.Max(maxi, freq1[i] / freq2[i]); } } return maxi;} // Drivers codepublic static void Main(String[] args){ int n = 48, m = 4; Console.WriteLine(getMaximumPower(n, m)); }} // This code has been contributed by 29AjayKumar",
"e": 7838,
"s": 6026,
"text": null
},
{
"code": "<?php// PHP program to implement// the above approach // Function to get the prime factors// and its count of times it dividesfunction primeFactors($n, $freq){ $cnt = 0; // Count the number of 2s that divide n while ($n % 2 == 0) { $cnt++; $n = floor($n / 2); } $freq[2] = $cnt; // n must be odd at this point. So we can skip // one element (Note i = i +2) for ($i = 3; $i <= sqrt($n); $i = $i + 2) { $cnt = 0; // While i divides n, count i and divide n while ($n % $i == 0) { $cnt++; $n = floor($n / $i); } $freq[$i] = $cnt; } // This condition is to handle the case when n // is a prime number greater than 2 if ($n > 2) $freq[$n] = 1; return $freq ;} // Function to return the highest powerfunction getMaximumPower($n, $m){ $freq1 = array_fill(0,$n + 1,0); $freq2 = array_fill(0,$m + 1,0); // Get the prime factors of n and m $freq1 = primeFactors($n, $freq1); $freq2 = primeFactors($m, $freq2); $maxi = 0; // Iterate and find the maximum power for ($i = 2; $i <= $m; $i++) { // If i not a prime factor of n and m if ($freq1[$i] == 0 && $freq2[$i] == 0) continue; // If i is a prime factor of n and m // If count of i dividing m is more // than i dividing n, then power will be 0 if ($freq2[$i] > $freq1[$i]) return 0; // If i is a prime factor of M if ($freq2[$i]) { // get the maximum power $maxi = max($maxi, floor($freq1[$i] / $freq2[$i])); } } return $maxi;} // Drivers code $n = 48; $m = 4; echo getMaximumPower($n, $m); // This code is contributed by Ryuga?>",
"e": 9620,
"s": 7838,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach // Function to get the prime factors// and its count of times it dividesfunction primeFactors(n, freq){ var cnt = 0; // Count the number of 2s that divide n while (n % 2 == 0) { cnt++; n = n / 2; } freq[2] = cnt; var i; // n must be odd at this point. So we can skip // one element (Note i = i +2) for (i = 3; i <= Math.sqrt(n); i = i + 2) { cnt = 0; // While i divides n, count i and divide n while (n % i == 0) { cnt++; n = n / i; } freq[i] = cnt; } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) freq[n] = 1;} // Function to return the highest powerfunction getMaximumPower(n, m){ // Initialize two arrays var freq1 = new Array(n+1); var freq2 = new Array(m+1); // Get the prime factors of n and m primeFactors(n, freq1); primeFactors(m, freq2); var maxi = 0; // Iterate and find the maximum power for(i = 2; i <= m; i++) { // If i not a prime factor of n and m if (freq1[i] == 0 && freq2[i] == 0) continue; // If i is a prime factor of n and m // If count of i dividing m is more // than i dividing n, then power will be 0 if (freq2[i] > freq1[i]) return 0; // If i is a prime factor of M if (freq2[i]) { // get the maximum power maxi = Math.max(maxi, freq1[i]/freq2[i]); } } return maxi;} // Drivers code var n = 48, m = 4; document.write(getMaximumPower(n, m)); </script>",
"e": 11288,
"s": 9620,
"text": null
},
{
"code": null,
"e": 11290,
"s": 11288,
"text": "2"
},
{
"code": null,
"e": 11323,
"s": 11290,
"text": "Time Complexity: O(n log log n) "
},
{
"code": null,
"e": 11352,
"s": 11323,
"text": "Auxiliary Space: O(max(m,n))"
},
{
"code": null,
"e": 11360,
"s": 11352,
"text": "ankthon"
},
{
"code": null,
"e": 11370,
"s": 11360,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 11382,
"s": 11370,
"text": "29AjayKumar"
},
{
"code": null,
"e": 11398,
"s": 11382,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 11415,
"s": 11398,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 11423,
"s": 11415,
"text": "rohan07"
},
{
"code": null,
"e": 11442,
"s": 11423,
"text": "frequency-counting"
},
{
"code": null,
"e": 11462,
"s": 11442,
"text": "Number Divisibility"
},
{
"code": null,
"e": 11475,
"s": 11462,
"text": "Mathematical"
},
{
"code": null,
"e": 11488,
"s": 11475,
"text": "Mathematical"
}
] |
Python program to compute arithmetic operation from String | 01 Oct, 2020
Given a String with the multiplication of elements, convert to the summation of these multiplications.
Input : test_str = β5Γ10, 9Γ10, 7Γ8β Output : 196 Explanation : 50 + 90 + 56 = 196.
Input : test_str = β5Γ10, 9Γ10β Output : 140 Explanation : 50 + 90 = 140.
Method 1 : Using map() + mul + sum() + split()
The combination of the above functions can be used to solve this problem. In this, we perform summation using sum() and multiplication using mul(), split() is used to split elements for creating operands for multiplication. The map() is used to extend the logic to multiplication to each computation.
Python3
# importing modulefrom operator import mul # initializing stringtest_str = '5x6, 9x10, 7x8' # printing original stringprint("The original string is : " + str(test_str)) # sum() is used to sum the product of each computationres = sum(mul(*map(int, ele.split('x'))) for ele in test_str.split(', ')) # printing resultprint("The computed summation of products : " + str(res))
The original string is : 5x6, 9x10, 7x8
The computed summation of products : 176
Method 2 : Using eval() + replace()
In this, we convert multiplication symbol to the operator for multiplication(β*β), similarly, comma symbol is converted to arithmetic β+β symbol. Then eval() performs internal computations and returns the result.
Python3
# initializing stringtest_str = '5x6, 9x10, 7x8' # printing original stringprint("The original string is : " + str(test_str)) # using replace() to create eval friendly stringtemp = test_str.replace(',', '+').replace('x', '*') # using eval() to get the required resultres = eval(temp) # printing resultprint("The computed summation of products : " + str(res))
The original string is : 5x6, 9x10, 7x8
The computed summation of products : 176
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 132,
"s": 28,
"text": "Given a String with the multiplication of elements, convert to the summation of these multiplications. "
},
{
"code": null,
"e": 216,
"s": 132,
"text": "Input : test_str = β5Γ10, 9Γ10, 7Γ8β Output : 196 Explanation : 50 + 90 + 56 = 196."
},
{
"code": null,
"e": 292,
"s": 216,
"text": "Input : test_str = β5Γ10, 9Γ10β Output : 140 Explanation : 50 + 90 = 140. "
},
{
"code": null,
"e": 339,
"s": 292,
"text": "Method 1 : Using map() + mul + sum() + split()"
},
{
"code": null,
"e": 640,
"s": 339,
"text": "The combination of the above functions can be used to solve this problem. In this, we perform summation using sum() and multiplication using mul(), split() is used to split elements for creating operands for multiplication. The map() is used to extend the logic to multiplication to each computation."
},
{
"code": null,
"e": 648,
"s": 640,
"text": "Python3"
},
{
"code": "# importing modulefrom operator import mul # initializing stringtest_str = '5x6, 9x10, 7x8' # printing original stringprint(\"The original string is : \" + str(test_str)) # sum() is used to sum the product of each computationres = sum(mul(*map(int, ele.split('x'))) for ele in test_str.split(', ')) # printing resultprint(\"The computed summation of products : \" + str(res))",
"e": 1024,
"s": 648,
"text": null
},
{
"code": null,
"e": 1107,
"s": 1024,
"text": "The original string is : 5x6, 9x10, 7x8\nThe computed summation of products : 176\n\n"
},
{
"code": null,
"e": 1143,
"s": 1107,
"text": "Method 2 : Using eval() + replace()"
},
{
"code": null,
"e": 1356,
"s": 1143,
"text": "In this, we convert multiplication symbol to the operator for multiplication(β*β), similarly, comma symbol is converted to arithmetic β+β symbol. Then eval() performs internal computations and returns the result."
},
{
"code": null,
"e": 1364,
"s": 1356,
"text": "Python3"
},
{
"code": "# initializing stringtest_str = '5x6, 9x10, 7x8' # printing original stringprint(\"The original string is : \" + str(test_str)) # using replace() to create eval friendly stringtemp = test_str.replace(',', '+').replace('x', '*') # using eval() to get the required resultres = eval(temp) # printing resultprint(\"The computed summation of products : \" + str(res))",
"e": 1727,
"s": 1364,
"text": null
},
{
"code": null,
"e": 1810,
"s": 1727,
"text": "The original string is : 5x6, 9x10, 7x8\nThe computed summation of products : 176\n\n"
},
{
"code": null,
"e": 1833,
"s": 1810,
"text": "Python string-programs"
},
{
"code": null,
"e": 1840,
"s": 1833,
"text": "Python"
},
{
"code": null,
"e": 1856,
"s": 1840,
"text": "Python Programs"
},
{
"code": null,
"e": 1954,
"s": 1856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1986,
"s": 1954,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2013,
"s": 1986,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2044,
"s": 2013,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2065,
"s": 2044,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2121,
"s": 2065,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2143,
"s": 2121,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2182,
"s": 2143,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2220,
"s": 2182,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2269,
"s": 2220,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Reverse a String in JavaScript | 16 Apr, 2019
Given an input string and the task is to reverse the input string.
Examples:
Input: str = "Geeks for Geeks"
Output: "skeeG rof skeeG"
Input: str = "Hello"
Output: "olleH"
There are many methods to reverse a string in JavaScript some of them are discussed below:
Method 1:
Check the input string that if given string is empty or just have one character or it is not of string type then it return βNot Valid stringβ.
If the above condition false create an array where we can store the result. Here revArray[] is the new array.
Loop through the array from the end to the beginning and push each and every item in the array revArray[].
Use join() prebuilt function in JavaScript to join the elements of an array into a string.
Example:
<script>function ReverseString(str) { // Check input if(!str || str.length < 2 || typeof str!== 'string') { return 'Not valid'; } // Take empty array revArray const revArray = []; const length = str.length - 1; // Looping from the end for(let i = length; i >= 0; i--) { revArray.push(str[i]); } // Joining the array elements return revArray.join('');} document.write(ReverseString("Geeks for Geeks"))</script>
Output:
skeeG rof skeeG
Method 2:
Use split() inbuilt function in JavaScript to split string into array of characters i.e. [ βGβ, βeβ, βeβ, βkβ, βsβ, β β, βfβ, βoβ, βrβ, β β, βGβ, βeβ, βeβ, βkβ, βsβ ]
Use reverse() function in JavaScript to reversal the array of characters i.e. [ βsβ, βkβ, βeβ, βeβ, βGβ, β β, βrβ, βoβ, βfβ, β β, βsβ, βkβ, βeβ, βeβ, βGβ ]
Use join() function in JavaScript to join the elements of an array into a string.
Example:
<script> // Function to reverse stringfunction ReverseString(str) { return str.split('').reverse().join('')} // Function call document.write(ReverseString("Geeks for Geeks"))</script>
Output:
skeeG rof skeeG
Method 3:
Use spread operator instead of split() function to convert string into array of characters i.e. [ βGβ, βeβ, βeβ, βkβ, βsβ, β β, βfβ, βoβ, βrβ, β β, βGβ, βeβ, βeβ, βkβ, βsβ ]. Learn more about the spread operator here Spread Operator
Use reverse() function in JavaScript to reversal the array of characters i.e. [ βsβ, βkβ, βeβ, βeβ, βGβ, β β, βrβ, βoβ, βfβ, β β, βsβ, βkβ, βeβ, βeβ, βGβ ]
Use join() function in JavaScript to join the elements of an array into a string.
Example:
<script>const ReverseString = str => [...str].reverse().join(''); document.write(ReverseString("Geeks for Geeks"))</script>
Output:
skeeG rof skeeG
javascript-string
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Apr, 2019"
},
{
"code": null,
"e": 119,
"s": 52,
"text": "Given an input string and the task is to reverse the input string."
},
{
"code": null,
"e": 129,
"s": 119,
"text": "Examples:"
},
{
"code": null,
"e": 226,
"s": 129,
"text": "Input: str = \"Geeks for Geeks\"\nOutput: \"skeeG rof skeeG\"\n\nInput: str = \"Hello\"\nOutput: \"olleH\"\n"
},
{
"code": null,
"e": 317,
"s": 226,
"text": "There are many methods to reverse a string in JavaScript some of them are discussed below:"
},
{
"code": null,
"e": 327,
"s": 317,
"text": "Method 1:"
},
{
"code": null,
"e": 470,
"s": 327,
"text": "Check the input string that if given string is empty or just have one character or it is not of string type then it return βNot Valid stringβ."
},
{
"code": null,
"e": 580,
"s": 470,
"text": "If the above condition false create an array where we can store the result. Here revArray[] is the new array."
},
{
"code": null,
"e": 687,
"s": 580,
"text": "Loop through the array from the end to the beginning and push each and every item in the array revArray[]."
},
{
"code": null,
"e": 778,
"s": 687,
"text": "Use join() prebuilt function in JavaScript to join the elements of an array into a string."
},
{
"code": null,
"e": 787,
"s": 778,
"text": "Example:"
},
{
"code": "<script>function ReverseString(str) { // Check input if(!str || str.length < 2 || typeof str!== 'string') { return 'Not valid'; } // Take empty array revArray const revArray = []; const length = str.length - 1; // Looping from the end for(let i = length; i >= 0; i--) { revArray.push(str[i]); } // Joining the array elements return revArray.join('');} document.write(ReverseString(\"Geeks for Geeks\"))</script>",
"e": 1278,
"s": 787,
"text": null
},
{
"code": null,
"e": 1286,
"s": 1278,
"text": "Output:"
},
{
"code": null,
"e": 1302,
"s": 1286,
"text": "skeeG rof skeeG"
},
{
"code": null,
"e": 1312,
"s": 1302,
"text": "Method 2:"
},
{
"code": null,
"e": 1479,
"s": 1312,
"text": "Use split() inbuilt function in JavaScript to split string into array of characters i.e. [ βGβ, βeβ, βeβ, βkβ, βsβ, β β, βfβ, βoβ, βrβ, β β, βGβ, βeβ, βeβ, βkβ, βsβ ]"
},
{
"code": null,
"e": 1635,
"s": 1479,
"text": "Use reverse() function in JavaScript to reversal the array of characters i.e. [ βsβ, βkβ, βeβ, βeβ, βGβ, β β, βrβ, βoβ, βfβ, β β, βsβ, βkβ, βeβ, βeβ, βGβ ]"
},
{
"code": null,
"e": 1717,
"s": 1635,
"text": "Use join() function in JavaScript to join the elements of an array into a string."
},
{
"code": null,
"e": 1726,
"s": 1717,
"text": "Example:"
},
{
"code": "<script> // Function to reverse stringfunction ReverseString(str) { return str.split('').reverse().join('')} // Function call document.write(ReverseString(\"Geeks for Geeks\"))</script>",
"e": 1914,
"s": 1726,
"text": null
},
{
"code": null,
"e": 1922,
"s": 1914,
"text": "Output:"
},
{
"code": null,
"e": 1938,
"s": 1922,
"text": "skeeG rof skeeG"
},
{
"code": null,
"e": 1948,
"s": 1938,
"text": "Method 3:"
},
{
"code": null,
"e": 2181,
"s": 1948,
"text": "Use spread operator instead of split() function to convert string into array of characters i.e. [ βGβ, βeβ, βeβ, βkβ, βsβ, β β, βfβ, βoβ, βrβ, β β, βGβ, βeβ, βeβ, βkβ, βsβ ]. Learn more about the spread operator here Spread Operator"
},
{
"code": null,
"e": 2337,
"s": 2181,
"text": "Use reverse() function in JavaScript to reversal the array of characters i.e. [ βsβ, βkβ, βeβ, βeβ, βGβ, β β, βrβ, βoβ, βfβ, β β, βsβ, βkβ, βeβ, βeβ, βGβ ]"
},
{
"code": null,
"e": 2419,
"s": 2337,
"text": "Use join() function in JavaScript to join the elements of an array into a string."
},
{
"code": null,
"e": 2428,
"s": 2419,
"text": "Example:"
},
{
"code": "<script>const ReverseString = str => [...str].reverse().join(''); document.write(ReverseString(\"Geeks for Geeks\"))</script>",
"e": 2553,
"s": 2428,
"text": null
},
{
"code": null,
"e": 2561,
"s": 2553,
"text": "Output:"
},
{
"code": null,
"e": 2577,
"s": 2561,
"text": "skeeG rof skeeG"
},
{
"code": null,
"e": 2595,
"s": 2577,
"text": "javascript-string"
},
{
"code": null,
"e": 2606,
"s": 2595,
"text": "JavaScript"
},
{
"code": null,
"e": 2623,
"s": 2606,
"text": "Web Technologies"
},
{
"code": null,
"e": 2650,
"s": 2623,
"text": "Web technologies Questions"
}
] |
Set up virtual environment for Python using Anaconda | 18 Apr, 2022
If you are dealing with the problem of setting up an environment in anaconda and donβt have any idea why do we have to deal with the pain of setting up the environment then this is the right place for you.
Anaconda is an open source software that contains Jupyter, spyder, etc that are used for large data processing, data analytics, heavy scientific computing. Anaconda works for R and Python programming language. Package versions are managed by the package management system conda.
Installing Anaconda :
Head over to anaconda.com and install the latest version of Anaconda. Make sure to download the βPython 3.7 Versionβ for the appropriate architecture. Refer to the below articles for the detailed information on installing anaconda on different platforms.
How to install Anaconda on windows?
How to install Anaconda on Linux?
Like many other languages Python requires a different version for different kind of applications. The application needs to run on a specific version of the language because it requires a certain dependency that is present in older versions but changes in newer versions. Virtual environments makes it easy to ideally separate different applications and avoid problems with different dependencies. Using virtual environment we can switch between both applications easily and get them running.
There are multiple ways of creating an environment using virtualenv, venv and conda. Conda command is preferred interface for managing installations and virtual environments with the Anaconda Python distribution.
Letβs go through the steps of creating a virtual environment using conda interface:
Step 1: Check if conda is installed in your path.
Open up the anaconda command prompt.
Type conda -V and press enter.
If the conda is successfully installed in your system you should see a similar output.
conda -V
Output:
Step 2: Update the conda environment
Enter the following in the anaconda prompt.
conda update conda
Step 3: Set up the virtual environment
Type conda search β^python$β to see the list of available python versions.
Now replace the envname with the name you want to give to your virtual environment and replace x.x with the python version you want to use.
conda create -n envname python=x.x anaconda
Letβs create a virtual environment name Geeks for Python3.6
Step 4: Activating the virtual environment
To see the list of all the available environments use command conda info -e
To activate the virtual environment, enter the given command and replace your given environment name with envname
conda activate envname
When conda environment is activated it modifies the PATH and shell variables points specifically to the isolated Python set- up you created.
Step 5: Installation of required packages to the virtual environment
Type the following command to install the additional packages to the environment and replace envname with the name of your environment.
conda install -n yourenvname package
Step 6: Deactivating the virtual environment
To come out of the particular environment type the following command. The settings of the environment will remain as it is.
conda deactivate
Step 7: Deletion of virtual environment
If you no longer require a virtual environment. Delete it using the following command and replace your environment name with envname
conda remove -n envname -all
varshagumber28
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 259,
"s": 53,
"text": "If you are dealing with the problem of setting up an environment in anaconda and donβt have any idea why do we have to deal with the pain of setting up the environment then this is the right place for you."
},
{
"code": null,
"e": 539,
"s": 259,
"text": "Anaconda is an open source software that contains Jupyter, spyder, etc that are used for large data processing, data analytics, heavy scientific computing. Anaconda works for R and Python programming language. Package versions are managed by the package management system conda. "
},
{
"code": null,
"e": 562,
"s": 539,
"text": "Installing Anaconda : "
},
{
"code": null,
"e": 819,
"s": 562,
"text": "Head over to anaconda.com and install the latest version of Anaconda. Make sure to download the βPython 3.7 Versionβ for the appropriate architecture. Refer to the below articles for the detailed information on installing anaconda on different platforms. "
},
{
"code": null,
"e": 857,
"s": 819,
"text": "How to install Anaconda on windows? "
},
{
"code": null,
"e": 893,
"s": 857,
"text": "How to install Anaconda on Linux? "
},
{
"code": null,
"e": 1385,
"s": 893,
"text": "Like many other languages Python requires a different version for different kind of applications. The application needs to run on a specific version of the language because it requires a certain dependency that is present in older versions but changes in newer versions. Virtual environments makes it easy to ideally separate different applications and avoid problems with different dependencies. Using virtual environment we can switch between both applications easily and get them running."
},
{
"code": null,
"e": 1598,
"s": 1385,
"text": "There are multiple ways of creating an environment using virtualenv, venv and conda. Conda command is preferred interface for managing installations and virtual environments with the Anaconda Python distribution."
},
{
"code": null,
"e": 1684,
"s": 1600,
"text": "Letβs go through the steps of creating a virtual environment using conda interface:"
},
{
"code": null,
"e": 1736,
"s": 1686,
"text": "Step 1: Check if conda is installed in your path."
},
{
"code": null,
"e": 1773,
"s": 1736,
"text": "Open up the anaconda command prompt."
},
{
"code": null,
"e": 1805,
"s": 1773,
"text": "Type conda -V and press enter."
},
{
"code": null,
"e": 1892,
"s": 1805,
"text": "If the conda is successfully installed in your system you should see a similar output."
},
{
"code": null,
"e": 1901,
"s": 1892,
"text": "conda -V"
},
{
"code": null,
"e": 1909,
"s": 1901,
"text": "Output:"
},
{
"code": null,
"e": 1947,
"s": 1909,
"text": "Step 2: Update the conda environment "
},
{
"code": null,
"e": 1991,
"s": 1947,
"text": "Enter the following in the anaconda prompt."
},
{
"code": null,
"e": 2010,
"s": 1991,
"text": "conda update conda"
},
{
"code": null,
"e": 2049,
"s": 2010,
"text": "Step 3: Set up the virtual environment"
},
{
"code": null,
"e": 2125,
"s": 2049,
"text": "Type conda search β^python$β to see the list of available python versions."
},
{
"code": null,
"e": 2265,
"s": 2125,
"text": "Now replace the envname with the name you want to give to your virtual environment and replace x.x with the python version you want to use."
},
{
"code": null,
"e": 2309,
"s": 2265,
"text": "conda create -n envname python=x.x anaconda"
},
{
"code": null,
"e": 2369,
"s": 2309,
"text": "Letβs create a virtual environment name Geeks for Python3.6"
},
{
"code": null,
"e": 2412,
"s": 2369,
"text": "Step 4: Activating the virtual environment"
},
{
"code": null,
"e": 2488,
"s": 2412,
"text": "To see the list of all the available environments use command conda info -e"
},
{
"code": null,
"e": 2602,
"s": 2488,
"text": "To activate the virtual environment, enter the given command and replace your given environment name with envname"
},
{
"code": null,
"e": 2625,
"s": 2602,
"text": "conda activate envname"
},
{
"code": null,
"e": 2774,
"s": 2627,
"text": " When conda environment is activated it modifies the PATH and shell variables points specifically to the isolated Python set- up you created."
},
{
"code": null,
"e": 2845,
"s": 2776,
"text": "Step 5: Installation of required packages to the virtual environment"
},
{
"code": null,
"e": 2981,
"s": 2845,
"text": "Type the following command to install the additional packages to the environment and replace envname with the name of your environment."
},
{
"code": null,
"e": 3018,
"s": 2981,
"text": "conda install -n yourenvname package"
},
{
"code": null,
"e": 3063,
"s": 3018,
"text": "Step 6: Deactivating the virtual environment"
},
{
"code": null,
"e": 3187,
"s": 3063,
"text": "To come out of the particular environment type the following command. The settings of the environment will remain as it is."
},
{
"code": null,
"e": 3204,
"s": 3187,
"text": "conda deactivate"
},
{
"code": null,
"e": 3244,
"s": 3204,
"text": "Step 7: Deletion of virtual environment"
},
{
"code": null,
"e": 3377,
"s": 3244,
"text": "If you no longer require a virtual environment. Delete it using the following command and replace your environment name with envname"
},
{
"code": null,
"e": 3406,
"s": 3377,
"text": "conda remove -n envname -all"
},
{
"code": null,
"e": 3423,
"s": 3408,
"text": "varshagumber28"
},
{
"code": null,
"e": 3437,
"s": 3423,
"text": "python-basics"
},
{
"code": null,
"e": 3444,
"s": 3437,
"text": "Python"
},
{
"code": null,
"e": 3542,
"s": 3444,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3560,
"s": 3542,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3602,
"s": 3560,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3624,
"s": 3602,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3659,
"s": 3624,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3685,
"s": 3659,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3714,
"s": 3685,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3741,
"s": 3714,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3771,
"s": 3741,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3792,
"s": 3771,
"text": "Python OOPs Concepts"
}
] |
StringBuilder charAt() in Java with Examples | 15 Oct, 2018
The charAt(int index) method of StringBuilder Class is used to return the character at the specified index of String contained by StringBuilder Object. The index value should lie between 0 and length()-1.
Syntax:
public char charAt(int index)
Parameters: This method accepts one int type parameter index which represents index of the character to be returned.
Return Value: This method returns character at the specified position.
Exception: This method throws IndexOutOfBoundsException when index is negative or greater than or equal to length().
Below programs demonstrate the charAt() method of StringBuilder Class:
Example 1:
// Java program to demonstrate// the charAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object StringBuilder str = new StringBuilder(); // add the String to StringBuilder Object str.append("Geek"); // get char at position 1 char ch = str.charAt(1); // print the result System.out.println("StringBuilder Object" + " contains = " + str); System.out.println("Character at Position 1" + " in StringBuilder = " + ch); }}
StringBuilder Object contains = Geek
Character at Position 1 in StringBuilder = e
Example 2:
// Java program demonstrate// the charAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("WelcomeGeeks"); // print string System.out.println("String is " + str.toString()); // loop through string and print every Character for (int i = 0; i < str.length(); i++) { // get char at position i char ch = str.charAt(i); // print char System.out.println("Char at position " + i + " is " + ch); } }}
String is WelcomeGeeks
Char at position 0 is W
Char at position 1 is e
Char at position 2 is l
Char at position 3 is c
Char at position 4 is o
Char at position 5 is m
Char at position 6 is e
Char at position 7 is G
Char at position 8 is e
Char at position 9 is e
Char at position 10 is k
Char at position 11 is s
Example 3: To demonstrate IndexOutOfBoundException
// Java program to demonstrate// IndexOutOfBound exception thrown by the charAt() Method. class GFG { public static void main(String[] args) { try { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("WelcomeGeeks"); // get char at position i char ch = str.charAt(str.length()); // print char System.out.println("Char at position " + str.length() + " is " + ch); } catch (Exception e) { System.out.println("Exception: " + e); } }}
Exception: java.lang.StringIndexOutOfBoundsException:
String index out of range: 12
Reference:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#charAt(int)
java-basics
Java-Functions
Java-StringBuilder
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2018"
},
{
"code": null,
"e": 233,
"s": 28,
"text": "The charAt(int index) method of StringBuilder Class is used to return the character at the specified index of String contained by StringBuilder Object. The index value should lie between 0 and length()-1."
},
{
"code": null,
"e": 241,
"s": 233,
"text": "Syntax:"
},
{
"code": null,
"e": 271,
"s": 241,
"text": "public char charAt(int index)"
},
{
"code": null,
"e": 388,
"s": 271,
"text": "Parameters: This method accepts one int type parameter index which represents index of the character to be returned."
},
{
"code": null,
"e": 459,
"s": 388,
"text": "Return Value: This method returns character at the specified position."
},
{
"code": null,
"e": 576,
"s": 459,
"text": "Exception: This method throws IndexOutOfBoundsException when index is negative or greater than or equal to length()."
},
{
"code": null,
"e": 647,
"s": 576,
"text": "Below programs demonstrate the charAt() method of StringBuilder Class:"
},
{
"code": null,
"e": 658,
"s": 647,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// the charAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object StringBuilder str = new StringBuilder(); // add the String to StringBuilder Object str.append(\"Geek\"); // get char at position 1 char ch = str.charAt(1); // print the result System.out.println(\"StringBuilder Object\" + \" contains = \" + str); System.out.println(\"Character at Position 1\" + \" in StringBuilder = \" + ch); }}",
"e": 1252,
"s": 658,
"text": null
},
{
"code": null,
"e": 1335,
"s": 1252,
"text": "StringBuilder Object contains = Geek\nCharacter at Position 1 in StringBuilder = e\n"
},
{
"code": null,
"e": 1346,
"s": 1335,
"text": "Example 2:"
},
{
"code": "// Java program demonstrate// the charAt() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"WelcomeGeeks\"); // print string System.out.println(\"String is \" + str.toString()); // loop through string and print every Character for (int i = 0; i < str.length(); i++) { // get char at position i char ch = str.charAt(i); // print char System.out.println(\"Char at position \" + i + \" is \" + ch); } }}",
"e": 2055,
"s": 1346,
"text": null
},
{
"code": null,
"e": 2369,
"s": 2055,
"text": "String is WelcomeGeeks\nChar at position 0 is W\nChar at position 1 is e\nChar at position 2 is l\nChar at position 3 is c\nChar at position 4 is o\nChar at position 5 is m\nChar at position 6 is e\nChar at position 7 is G\nChar at position 8 is e\nChar at position 9 is e\nChar at position 10 is k\nChar at position 11 is s\n"
},
{
"code": null,
"e": 2420,
"s": 2369,
"text": "Example 3: To demonstrate IndexOutOfBoundException"
},
{
"code": "// Java program to demonstrate// IndexOutOfBound exception thrown by the charAt() Method. class GFG { public static void main(String[] args) { try { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"WelcomeGeeks\"); // get char at position i char ch = str.charAt(str.length()); // print char System.out.println(\"Char at position \" + str.length() + \" is \" + ch); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}",
"e": 3132,
"s": 2420,
"text": null
},
{
"code": null,
"e": 3218,
"s": 3132,
"text": "Exception: java.lang.StringIndexOutOfBoundsException:\n String index out of range: 12\n"
},
{
"code": null,
"e": 3312,
"s": 3218,
"text": "Reference:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#charAt(int)"
},
{
"code": null,
"e": 3324,
"s": 3312,
"text": "java-basics"
},
{
"code": null,
"e": 3339,
"s": 3324,
"text": "Java-Functions"
},
{
"code": null,
"e": 3358,
"s": 3339,
"text": "Java-StringBuilder"
},
{
"code": null,
"e": 3363,
"s": 3358,
"text": "Java"
},
{
"code": null,
"e": 3368,
"s": 3363,
"text": "Java"
}
] |
DynamoDB - Global Secondary Indexes | Applications requiring various query types with different attributes can use a single or multiple global secondary indexes in performing these detailed queries.
For example β A system keeping a track of users, their login status, and their time logged in. The growth of the previous example slows queries on its data.
Global secondary indexes accelerate queries by organizing a selection of attributes from a table. They employ primary keys in sorting data, and require no key table attributes, or key schema identical to the table.
All the global secondary indexes must include a partition key, with the option of a sort key. The index key schema can differ from the table, and index key attributes can use any top-level string, number, or binary table attributes.
In a projection, you can use other table attributes, however, queries do not retrieve from parent tables.
Projections consist of an attribute set copied from table to secondary index. A Projection always occurs with the table partition key and sort key. In queries, projections allow DynamoDB access to any attribute of the projection; they essentially exist as their own table.
In a secondary index creation, you must specify attributes for projection. DynamoDB offers three ways to perform this task β
KEYS_ONLY β All index items consist of table partition and sort key values, and index key values. This creates the smallest index.
KEYS_ONLY β All index items consist of table partition and sort key values, and index key values. This creates the smallest index.
INCLUDE β It includes KEYS_ONLY attributes and specified non-key attributes.
INCLUDE β It includes KEYS_ONLY attributes and specified non-key attributes.
ALL β It includes all source table attributes, creating the largest possible index.
ALL β It includes all source table attributes, creating the largest possible index.
Note the tradeoffs in projecting attributes into a global secondary index, which relate to throughput and storage cost.
Consider the following points β
If you only need access to a few attributes, with low latency, project only those you need. This reduces storage and write costs.
If you only need access to a few attributes, with low latency, project only those you need. This reduces storage and write costs.
If an application frequently accesses certain non-key attributes, project them because the storage costs pale in comparison to scan consumption.
If an application frequently accesses certain non-key attributes, project them because the storage costs pale in comparison to scan consumption.
You can project large sets of attributes frequently accessed, however, this carries a high storage cost.
You can project large sets of attributes frequently accessed, however, this carries a high storage cost.
Use KEYS_ONLY for infrequent table queries and frequent writes/updates. This controls size, but still offers good performance on queries.
Use KEYS_ONLY for infrequent table queries and frequent writes/updates. This controls size, but still offers good performance on queries.
You can utilize queries for accessing a single or multiple items in an index. You must specify index and table name, desired attributes, and conditions; with the option to return results in ascending or descending order.
You can also utilize scans to get all index data. It requires table and index name. You utilize a filter expression to retrieve specific data.
DynamoDB automatically performs synchronization on indexes with their parent table. Each modifying operation on items causes asynchronous updates, however, applications do not write to indexes directly.
You need to understand the impact of DynamoDB maintenance on indices. On creation of an index, you specify key attributes and data types, which means on a write, those data types must match key schema data types.
On item creation or deletion, indexes update in an eventually consistent manner, however, updates to data propagate in a fraction of a second (unless system failure of some type occurs). You must account for this delay in applications.
Throughput Considerations in Global Secondary Indexes β Multiple global secondary indexes impact throughput. Index creation requires capacity unit specifications, which exist separate from the table, resulting in operations consuming index capacity units rather than table units.
This can result in throttling if a query or write exceeds provisioned throughput. View throughput settings by using DescribeTable.
Read Capacity β Global secondary indexes deliver eventual consistency. In queries, DynamoDB performs provision calculations identical to that used for tables, with a lone difference of using index entry size rather than item size. The limit of a query returns remains 1MB, which includes attribute name size and values across every returned item.
When write operations occur, the affected index consumes write units. Write throughput costs are the sum of write capacity units consumed in table writes and units consumed in index updates. A successful write operation requires sufficient capacity, or it results in throttling.
Write costs also remain dependent on certain factors, some of which are as follows β
New items defining indexed attributes or item updates defining undefined indexed attributes use a single write operation to add the item to the index.
New items defining indexed attributes or item updates defining undefined indexed attributes use a single write operation to add the item to the index.
Updates changing indexed key attribute value use two writes to delete an item and write a new one.
Updates changing indexed key attribute value use two writes to delete an item and write a new one.
A table write triggering deletion of an indexed attribute uses a single write to erase the old item projection in the index.
A table write triggering deletion of an indexed attribute uses a single write to erase the old item projection in the index.
Items absent in the index prior to and after an update operation use no writes.
Items absent in the index prior to and after an update operation use no writes.
Updates changing only projected attribute value in the index key schema, and not indexed key attribute value, use one write to update values of projected attributes into the index.
Updates changing only projected attribute value in the index key schema, and not indexed key attribute value, use one write to update values of projected attributes into the index.
All these factors assume an item size of less than or equal to 1KB.
On an item write, DynamoDB automatically copies the right set of attributes to any indices where the attributes must exist. This impacts your account by charging it for table item storage and attribute storage. The space used results from the sum of these quantities β
Byte size of table primary key
Byte size of index key attribute
Byte size of projected attributes
100 byte-overhead per index item
You can estimate storage needs through estimating average item size and multiplying by the quantity of the table items with the global secondary index key attributes.
DynamoDB does not write item data for a table item with an undefined attribute defined as an index partition or sort key.
Create a table with global secondary indexes by using the CreateTable operation paired with the GlobalSecondaryIndexes parameter. You must specify an attribute to serve as the index partition key, or use another for the index sort key. All index key attributes must be string, number, or binary scalars. You must also provide throughput settings, consisting of ReadCapacityUnits and WriteCapacityUnits.
Use UpdateTable to add global secondary indexes to existing tables using the GlobalSecondaryIndexes parameter once again.
In this operation, you must provide the following inputs β
Index name
Key schema
Projected attributes
Throughput settings
By adding a global secondary index, it may take a substantial time with large tables due to item volume, projected attributes volume, write capacity, and write activity. Use CloudWatch metrics to monitor the process.
Use DescribeTable to fetch status information for a global secondary index. It returns one of four IndexStatus for GlobalSecondaryIndexes β
CREATING β It indicates the build stage of the index, and its unavailability.
CREATING β It indicates the build stage of the index, and its unavailability.
ACTIVE β It indicates the readiness of the index for use.
ACTIVE β It indicates the readiness of the index for use.
UPDATING β It indicates the update status of throughput settings.
UPDATING β It indicates the update status of throughput settings.
DELETING β It indicates the delete status of the index, and its permanent unavailability for use.
DELETING β It indicates the delete status of the index, and its permanent unavailability for use.
Update global secondary index provisioned throughput settings during the loading/backfilling stage (DynamoDB writing attributes to an index and tracking added/deleted/updated items). Use UpdateTable to perform this operation.
You should remember that you cannot add/delete other indices during the backfilling stage.
Use UpdateTable to delete global secondary indexes. It permits deletion of only one index per operation, however, you can run multiple operations concurrently, up to five. The deletion process does not affect the read/write activities of the parent table, but you cannot add/delete other indices until the operation completes.
Create a table with an index through CreateTable. Simply create a DynamoDB class instance, a CreateTableRequest class instance for request information, and pass the request object to the CreateTable method.
The following program is a short example β
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient (
new ProfileCredentialsProvider()));
// Attributes
ArrayList<AttributeDefinition> attributeDefinitions = new
ArrayList<AttributeDefinition>();
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("City")
.withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("Date")
.withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("Wind")
.withAttributeType("N"));
// Key schema of the table
ArrayList<KeySchemaElement> tableKeySchema = new ArrayList<KeySchemaElement>();
tableKeySchema.add(new KeySchemaElement()
.withAttributeName("City")
.withKeyType(KeyType.HASH)); //Partition key
tableKeySchema.add(new KeySchemaElement()
.withAttributeName("Date")
.withKeyType(KeyType.RANGE)); //Sort key
// Wind index
GlobalSecondaryIndex windIndex = new GlobalSecondaryIndex()
.withIndexName("WindIndex")
.withProvisionedThroughput(new ProvisionedThroughput()
.withReadCapacityUnits((long) 10)
.withWriteCapacityUnits((long) 1))
.withProjection(new Projection().withProjectionType(ProjectionType.ALL));
ArrayList<KeySchemaElement> indexKeySchema = new ArrayList<KeySchemaElement>();
indexKeySchema.add(new KeySchemaElement()
.withAttributeName("Date")
.withKeyType(KeyType.HASH)); //Partition key
indexKeySchema.add(new KeySchemaElement()
.withAttributeName("Wind")
.withKeyType(KeyType.RANGE)); //Sort key
windIndex.setKeySchema(indexKeySchema);
CreateTableRequest createTableRequest = new CreateTableRequest()
.withTableName("ClimateInfo")
.withProvisionedThroughput(new ProvisionedThroughput()
.withReadCapacityUnits((long) 5)
.withWriteCapacityUnits((long) 1))
.withAttributeDefinitions(attributeDefinitions)
.withKeySchema(tableKeySchema)
.withGlobalSecondaryIndexes(windIndex);
Table table = dynamoDB.createTable(createTableRequest);
System.out.println(table.getDescription());
Retrieve the index information with DescribeTable. First, create a DynamoDB class instance. Then create a Table class instance to target an index. Finally, pass the table to the describe method.
Here is a short example β
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient (
new ProfileCredentialsProvider()));
Table table = dynamoDB.getTable("ClimateInfo");
TableDescription tableDesc = table.describe();
Iterator<GlobalSecondaryIndexDescription> gsiIter =
tableDesc.getGlobalSecondaryIndexes().iterator();
while (gsiIter.hasNext()) {
GlobalSecondaryIndexDescription gsiDesc = gsiIter.next();
System.out.println("Index data " + gsiDesc.getIndexName() + ":");
Iterator<KeySchemaElement> kse7Iter = gsiDesc.getKeySchema().iterator();
while (kseIter.hasNext()) {
KeySchemaElement kse = kseIter.next();
System.out.printf("\t%s: %s\n", kse.getAttributeName(), kse.getKeyType());
}
Projection projection = gsiDesc.getProjection();
System.out.println("\tProjection type: " + projection.getProjectionType());
if (projection.getProjectionType().toString().equals("INCLUDE")) {
System.out.println("\t\tNon-key projected attributes: "
+ projection.getNonKeyAttributes());
}
}
Use Query to perform an index query as with a table query. Simply create a DynamoDB class instance, a Table class instance for the target index, an Index class instance for the specific index, and pass the index and query object to the query method.
Take a look at the following code to understand better β
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient (
new ProfileCredentialsProvider()));
Table table = dynamoDB.getTable("ClimateInfo");
Index index = table.getIndex("WindIndex");
QuerySpec spec = new QuerySpec()
.withKeyConditionExpression("#d = :v_date and Wind = :v_wind")
.withNameMap(new NameMap()
.with("#d", "Date"))
.withValueMap(new ValueMap()
.withString(":v_date","2016-05-15")
.withNumber(":v_wind",0));
ItemCollection<QueryOutcome> items = index.query(spec);
Iterator<Item> iter = items.iterator();
while (iter.hasNext()) {
System.out.println(iter.next().toJSONPretty());
}
The following program is a bigger example for better understanding β
Note β The following program may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources).
This example also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project.
import java.util.ArrayList;
import java.util.Iterator;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Index;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
import com.amazonaws.services.dynamodbv2.document.QueryOutcome;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.Projection;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
public class GlobalSecondaryIndexSample {
static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient (
new ProfileCredentialsProvider()));
public static String tableName = "Bugs";
public static void main(String[] args) throws Exception {
createTable();
queryIndex("CreationDateIndex");
queryIndex("NameIndex");
queryIndex("DueDateIndex");
}
public static void createTable() {
// Attributes
ArrayList<AttributeDefinition> attributeDefinitions = new
ArrayList<AttributeDefinition>();
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("BugID")
.withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("Name")
.withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("CreationDate")
.withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("DueDate")
.withAttributeType("S"));
// Table Key schema
ArrayList<KeySchemaElement> tableKeySchema = new ArrayList<KeySchemaElement>();
tableKeySchema.add (new KeySchemaElement()
.withAttributeName("BugID")
.withKeyType(KeyType.HASH)); //Partition key
tableKeySchema.add (new KeySchemaElement()
.withAttributeName("Name")
.withKeyType(KeyType.RANGE)); //Sort key
// Indexes' initial provisioned throughput
ProvisionedThroughput ptIndex = new ProvisionedThroughput()
.withReadCapacityUnits(1L)
.withWriteCapacityUnits(1L);
// CreationDateIndex
GlobalSecondaryIndex creationDateIndex = new GlobalSecondaryIndex()
.withIndexName("CreationDateIndex")
.withProvisionedThroughput(ptIndex)
.withKeySchema(new KeySchemaElement()
.withAttributeName("CreationDate")
.withKeyType(KeyType.HASH), //Partition key
new KeySchemaElement()
.withAttributeName("BugID")
.withKeyType(KeyType.RANGE)) //Sort key
.withProjection(new Projection()
.withProjectionType("INCLUDE")
.withNonKeyAttributes("Description", "Status"));
// NameIndex
GlobalSecondaryIndex nameIndex = new GlobalSecondaryIndex()
.withIndexName("NameIndex")
.withProvisionedThroughput(ptIndex)
.withKeySchema(new KeySchemaElement()
.withAttributeName("Name")
.withKeyType(KeyType.HASH), //Partition key
new KeySchemaElement()
.withAttributeName("BugID")
.withKeyType(KeyType.RANGE)) //Sort key
.withProjection(new Projection()
.withProjectionType("KEYS_ONLY"));
// DueDateIndex
GlobalSecondaryIndex dueDateIndex = new GlobalSecondaryIndex()
.withIndexName("DueDateIndex")
.withProvisionedThroughput(ptIndex)
.withKeySchema(new KeySchemaElement()
.withAttributeName("DueDate")
.withKeyType(KeyType.HASH)) //Partition key
.withProjection(new Projection()
.withProjectionType("ALL"));
CreateTableRequest createTableRequest = new CreateTableRequest()
.withTableName(tableName)
.withProvisionedThroughput( new ProvisionedThroughput()
.withReadCapacityUnits( (long) 1)
.withWriteCapacityUnits( (long) 1))
.withAttributeDefinitions(attributeDefinitions)
.withKeySchema(tableKeySchema)
.withGlobalSecondaryIndexes(creationDateIndex, nameIndex, dueDateIndex);
System.out.println("Creating " + tableName + "...");
dynamoDB.createTable(createTableRequest);
// Pause for active table state
System.out.println("Waiting for ACTIVE state of " + tableName);
try {
Table table = dynamoDB.getTable(tableName);
table.waitForActive();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void queryIndex(String indexName) {
Table table = dynamoDB.getTable(tableName);
System.out.println
("\n*****************************************************\n");
System.out.print("Querying index " + indexName + "...");
Index index = table.getIndex(indexName);
ItemCollection<QueryOutcome> items = null;
QuerySpec querySpec = new QuerySpec();
if (indexName == "CreationDateIndex") {
System.out.println("Issues filed on 2016-05-22");
querySpec.withKeyConditionExpression("CreationDate = :v_date and begins_with
(BugID, :v_bug)")
.withValueMap(new ValueMap()
.withString(":v_date","2016-05-22")
.withString(":v_bug","A-"));
items = index.query(querySpec);
} else if (indexName == "NameIndex") {
System.out.println("Compile error");
querySpec.withKeyConditionExpression("Name = :v_name and begins_with
(BugID, :v_bug)")
.withValueMap(new ValueMap()
.withString(":v_name","Compile error")
.withString(":v_bug","A-"));
items = index.query(querySpec);
} else if (indexName == "DueDateIndex") {
System.out.println("Items due on 2016-10-15");
querySpec.withKeyConditionExpression("DueDate = :v_date")
.withValueMap(new ValueMap()
.withString(":v_date","2016-10-15"));
items = index.query(querySpec);
} else {
System.out.println("\nInvalid index name");
return;
}
Iterator<Item> iterator = items.iterator();
System.out.println("Query: getting result...");
while (iterator.hasNext()) { | [
{
"code": null,
"e": 2686,
"s": 2525,
"text": "Applications requiring various query types with different attributes can use a single or multiple global secondary indexes in performing these detailed queries."
},
{
"code": null,
"e": 2843,
"s": 2686,
"text": "For example β A system keeping a track of users, their login status, and their time logged in. The growth of the previous example slows queries on its data."
},
{
"code": null,
"e": 3058,
"s": 2843,
"text": "Global secondary indexes accelerate queries by organizing a selection of attributes from a table. They employ primary keys in sorting data, and require no key table attributes, or key schema identical to the table."
},
{
"code": null,
"e": 3291,
"s": 3058,
"text": "All the global secondary indexes must include a partition key, with the option of a sort key. The index key schema can differ from the table, and index key attributes can use any top-level string, number, or binary table attributes."
},
{
"code": null,
"e": 3397,
"s": 3291,
"text": "In a projection, you can use other table attributes, however, queries do not retrieve from parent tables."
},
{
"code": null,
"e": 3670,
"s": 3397,
"text": "Projections consist of an attribute set copied from table to secondary index. A Projection always occurs with the table partition key and sort key. In queries, projections allow DynamoDB access to any attribute of the projection; they essentially exist as their own table."
},
{
"code": null,
"e": 3795,
"s": 3670,
"text": "In a secondary index creation, you must specify attributes for projection. DynamoDB offers three ways to perform this task β"
},
{
"code": null,
"e": 3926,
"s": 3795,
"text": "KEYS_ONLY β All index items consist of table partition and sort key values, and index key values. This creates the smallest index."
},
{
"code": null,
"e": 4057,
"s": 3926,
"text": "KEYS_ONLY β All index items consist of table partition and sort key values, and index key values. This creates the smallest index."
},
{
"code": null,
"e": 4134,
"s": 4057,
"text": "INCLUDE β It includes KEYS_ONLY attributes and specified non-key attributes."
},
{
"code": null,
"e": 4211,
"s": 4134,
"text": "INCLUDE β It includes KEYS_ONLY attributes and specified non-key attributes."
},
{
"code": null,
"e": 4295,
"s": 4211,
"text": "ALL β It includes all source table attributes, creating the largest possible index."
},
{
"code": null,
"e": 4379,
"s": 4295,
"text": "ALL β It includes all source table attributes, creating the largest possible index."
},
{
"code": null,
"e": 4499,
"s": 4379,
"text": "Note the tradeoffs in projecting attributes into a global secondary index, which relate to throughput and storage cost."
},
{
"code": null,
"e": 4531,
"s": 4499,
"text": "Consider the following points β"
},
{
"code": null,
"e": 4661,
"s": 4531,
"text": "If you only need access to a few attributes, with low latency, project only those you need. This reduces storage and write costs."
},
{
"code": null,
"e": 4791,
"s": 4661,
"text": "If you only need access to a few attributes, with low latency, project only those you need. This reduces storage and write costs."
},
{
"code": null,
"e": 4936,
"s": 4791,
"text": "If an application frequently accesses certain non-key attributes, project them because the storage costs pale in comparison to scan consumption."
},
{
"code": null,
"e": 5081,
"s": 4936,
"text": "If an application frequently accesses certain non-key attributes, project them because the storage costs pale in comparison to scan consumption."
},
{
"code": null,
"e": 5186,
"s": 5081,
"text": "You can project large sets of attributes frequently accessed, however, this carries a high storage cost."
},
{
"code": null,
"e": 5291,
"s": 5186,
"text": "You can project large sets of attributes frequently accessed, however, this carries a high storage cost."
},
{
"code": null,
"e": 5429,
"s": 5291,
"text": "Use KEYS_ONLY for infrequent table queries and frequent writes/updates. This controls size, but still offers good performance on queries."
},
{
"code": null,
"e": 5567,
"s": 5429,
"text": "Use KEYS_ONLY for infrequent table queries and frequent writes/updates. This controls size, but still offers good performance on queries."
},
{
"code": null,
"e": 5788,
"s": 5567,
"text": "You can utilize queries for accessing a single or multiple items in an index. You must specify index and table name, desired attributes, and conditions; with the option to return results in ascending or descending order."
},
{
"code": null,
"e": 5931,
"s": 5788,
"text": "You can also utilize scans to get all index data. It requires table and index name. You utilize a filter expression to retrieve specific data."
},
{
"code": null,
"e": 6134,
"s": 5931,
"text": "DynamoDB automatically performs synchronization on indexes with their parent table. Each modifying operation on items causes asynchronous updates, however, applications do not write to indexes directly."
},
{
"code": null,
"e": 6347,
"s": 6134,
"text": "You need to understand the impact of DynamoDB maintenance on indices. On creation of an index, you specify key attributes and data types, which means on a write, those data types must match key schema data types."
},
{
"code": null,
"e": 6583,
"s": 6347,
"text": "On item creation or deletion, indexes update in an eventually consistent manner, however, updates to data propagate in a fraction of a second (unless system failure of some type occurs). You must account for this delay in applications."
},
{
"code": null,
"e": 6863,
"s": 6583,
"text": "Throughput Considerations in Global Secondary Indexes β Multiple global secondary indexes impact throughput. Index creation requires capacity unit specifications, which exist separate from the table, resulting in operations consuming index capacity units rather than table units."
},
{
"code": null,
"e": 6994,
"s": 6863,
"text": "This can result in throttling if a query or write exceeds provisioned throughput. View throughput settings by using DescribeTable."
},
{
"code": null,
"e": 7341,
"s": 6994,
"text": "Read Capacity β Global secondary indexes deliver eventual consistency. In queries, DynamoDB performs provision calculations identical to that used for tables, with a lone difference of using index entry size rather than item size. The limit of a query returns remains 1MB, which includes attribute name size and values across every returned item."
},
{
"code": null,
"e": 7620,
"s": 7341,
"text": "When write operations occur, the affected index consumes write units. Write throughput costs are the sum of write capacity units consumed in table writes and units consumed in index updates. A successful write operation requires sufficient capacity, or it results in throttling."
},
{
"code": null,
"e": 7705,
"s": 7620,
"text": "Write costs also remain dependent on certain factors, some of which are as follows β"
},
{
"code": null,
"e": 7856,
"s": 7705,
"text": "New items defining indexed attributes or item updates defining undefined indexed attributes use a single write operation to add the item to the index."
},
{
"code": null,
"e": 8007,
"s": 7856,
"text": "New items defining indexed attributes or item updates defining undefined indexed attributes use a single write operation to add the item to the index."
},
{
"code": null,
"e": 8106,
"s": 8007,
"text": "Updates changing indexed key attribute value use two writes to delete an item and write a new one."
},
{
"code": null,
"e": 8205,
"s": 8106,
"text": "Updates changing indexed key attribute value use two writes to delete an item and write a new one."
},
{
"code": null,
"e": 8330,
"s": 8205,
"text": "A table write triggering deletion of an indexed attribute uses a single write to erase the old item projection in the index."
},
{
"code": null,
"e": 8455,
"s": 8330,
"text": "A table write triggering deletion of an indexed attribute uses a single write to erase the old item projection in the index."
},
{
"code": null,
"e": 8535,
"s": 8455,
"text": "Items absent in the index prior to and after an update operation use no writes."
},
{
"code": null,
"e": 8615,
"s": 8535,
"text": "Items absent in the index prior to and after an update operation use no writes."
},
{
"code": null,
"e": 8796,
"s": 8615,
"text": "Updates changing only projected attribute value in the index key schema, and not indexed key attribute value, use one write to update values of projected attributes into the index."
},
{
"code": null,
"e": 8977,
"s": 8796,
"text": "Updates changing only projected attribute value in the index key schema, and not indexed key attribute value, use one write to update values of projected attributes into the index."
},
{
"code": null,
"e": 9045,
"s": 8977,
"text": "All these factors assume an item size of less than or equal to 1KB."
},
{
"code": null,
"e": 9314,
"s": 9045,
"text": "On an item write, DynamoDB automatically copies the right set of attributes to any indices where the attributes must exist. This impacts your account by charging it for table item storage and attribute storage. The space used results from the sum of these quantities β"
},
{
"code": null,
"e": 9345,
"s": 9314,
"text": "Byte size of table primary key"
},
{
"code": null,
"e": 9378,
"s": 9345,
"text": "Byte size of index key attribute"
},
{
"code": null,
"e": 9412,
"s": 9378,
"text": "Byte size of projected attributes"
},
{
"code": null,
"e": 9445,
"s": 9412,
"text": "100 byte-overhead per index item"
},
{
"code": null,
"e": 9612,
"s": 9445,
"text": "You can estimate storage needs through estimating average item size and multiplying by the quantity of the table items with the global secondary index key attributes."
},
{
"code": null,
"e": 9734,
"s": 9612,
"text": "DynamoDB does not write item data for a table item with an undefined attribute defined as an index partition or sort key."
},
{
"code": null,
"e": 10137,
"s": 9734,
"text": "Create a table with global secondary indexes by using the CreateTable operation paired with the GlobalSecondaryIndexes parameter. You must specify an attribute to serve as the index partition key, or use another for the index sort key. All index key attributes must be string, number, or binary scalars. You must also provide throughput settings, consisting of ReadCapacityUnits and WriteCapacityUnits."
},
{
"code": null,
"e": 10259,
"s": 10137,
"text": "Use UpdateTable to add global secondary indexes to existing tables using the GlobalSecondaryIndexes parameter once again."
},
{
"code": null,
"e": 10318,
"s": 10259,
"text": "In this operation, you must provide the following inputs β"
},
{
"code": null,
"e": 10329,
"s": 10318,
"text": "Index name"
},
{
"code": null,
"e": 10340,
"s": 10329,
"text": "Key schema"
},
{
"code": null,
"e": 10361,
"s": 10340,
"text": "Projected attributes"
},
{
"code": null,
"e": 10381,
"s": 10361,
"text": "Throughput settings"
},
{
"code": null,
"e": 10598,
"s": 10381,
"text": "By adding a global secondary index, it may take a substantial time with large tables due to item volume, projected attributes volume, write capacity, and write activity. Use CloudWatch metrics to monitor the process."
},
{
"code": null,
"e": 10738,
"s": 10598,
"text": "Use DescribeTable to fetch status information for a global secondary index. It returns one of four IndexStatus for GlobalSecondaryIndexes β"
},
{
"code": null,
"e": 10816,
"s": 10738,
"text": "CREATING β It indicates the build stage of the index, and its unavailability."
},
{
"code": null,
"e": 10894,
"s": 10816,
"text": "CREATING β It indicates the build stage of the index, and its unavailability."
},
{
"code": null,
"e": 10952,
"s": 10894,
"text": "ACTIVE β It indicates the readiness of the index for use."
},
{
"code": null,
"e": 11010,
"s": 10952,
"text": "ACTIVE β It indicates the readiness of the index for use."
},
{
"code": null,
"e": 11076,
"s": 11010,
"text": "UPDATING β It indicates the update status of throughput settings."
},
{
"code": null,
"e": 11142,
"s": 11076,
"text": "UPDATING β It indicates the update status of throughput settings."
},
{
"code": null,
"e": 11240,
"s": 11142,
"text": "DELETING β It indicates the delete status of the index, and its permanent unavailability for use."
},
{
"code": null,
"e": 11338,
"s": 11240,
"text": "DELETING β It indicates the delete status of the index, and its permanent unavailability for use."
},
{
"code": null,
"e": 11564,
"s": 11338,
"text": "Update global secondary index provisioned throughput settings during the loading/backfilling stage (DynamoDB writing attributes to an index and tracking added/deleted/updated items). Use UpdateTable to perform this operation."
},
{
"code": null,
"e": 11655,
"s": 11564,
"text": "You should remember that you cannot add/delete other indices during the backfilling stage."
},
{
"code": null,
"e": 11982,
"s": 11655,
"text": "Use UpdateTable to delete global secondary indexes. It permits deletion of only one index per operation, however, you can run multiple operations concurrently, up to five. The deletion process does not affect the read/write activities of the parent table, but you cannot add/delete other indices until the operation completes."
},
{
"code": null,
"e": 12189,
"s": 11982,
"text": "Create a table with an index through CreateTable. Simply create a DynamoDB class instance, a CreateTableRequest class instance for request information, and pass the request object to the CreateTable method."
},
{
"code": null,
"e": 12232,
"s": 12189,
"text": "The following program is a short example β"
},
{
"code": null,
"e": 14365,
"s": 12232,
"text": "DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient ( \n new ProfileCredentialsProvider()));\n \n// Attributes \nArrayList<AttributeDefinition> attributeDefinitions = new \n ArrayList<AttributeDefinition>(); \nattributeDefinitions.add(new AttributeDefinition() \n .withAttributeName(\"City\") \n .withAttributeType(\"S\"));\n \nattributeDefinitions.add(new AttributeDefinition() \n .withAttributeName(\"Date\") \n .withAttributeType(\"S\"));\n \nattributeDefinitions.add(new AttributeDefinition() \n .withAttributeName(\"Wind\") \n .withAttributeType(\"N\"));\n \n// Key schema of the table \nArrayList<KeySchemaElement> tableKeySchema = new ArrayList<KeySchemaElement>(); \ntableKeySchema.add(new KeySchemaElement()\n .withAttributeName(\"City\") \n .withKeyType(KeyType.HASH)); //Partition key\n \ntableKeySchema.add(new KeySchemaElement() \n .withAttributeName(\"Date\") \n .withKeyType(KeyType.RANGE)); //Sort key\n \n// Wind index \nGlobalSecondaryIndex windIndex = new GlobalSecondaryIndex() \n .withIndexName(\"WindIndex\") \n .withProvisionedThroughput(new ProvisionedThroughput() \n .withReadCapacityUnits((long) 10) \n .withWriteCapacityUnits((long) 1)) \n .withProjection(new Projection().withProjectionType(ProjectionType.ALL));\n \nArrayList<KeySchemaElement> indexKeySchema = new ArrayList<KeySchemaElement>(); \nindexKeySchema.add(new KeySchemaElement() \n .withAttributeName(\"Date\") \n .withKeyType(KeyType.HASH)); //Partition key\n \nindexKeySchema.add(new KeySchemaElement() \n .withAttributeName(\"Wind\") \n .withKeyType(KeyType.RANGE)); //Sort key\n \nwindIndex.setKeySchema(indexKeySchema); \nCreateTableRequest createTableRequest = new CreateTableRequest() \n .withTableName(\"ClimateInfo\") \n .withProvisionedThroughput(new ProvisionedThroughput() \n .withReadCapacityUnits((long) 5) \n .withWriteCapacityUnits((long) 1))\n .withAttributeDefinitions(attributeDefinitions) \n .withKeySchema(tableKeySchema) \n .withGlobalSecondaryIndexes(windIndex); \nTable table = dynamoDB.createTable(createTableRequest); \nSystem.out.println(table.getDescription());"
},
{
"code": null,
"e": 14560,
"s": 14365,
"text": "Retrieve the index information with DescribeTable. First, create a DynamoDB class instance. Then create a Table class instance to target an index. Finally, pass the table to the describe method."
},
{
"code": null,
"e": 14586,
"s": 14560,
"text": "Here is a short example β"
},
{
"code": null,
"e": 15630,
"s": 14586,
"text": "DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient ( \n new ProfileCredentialsProvider()));\n \nTable table = dynamoDB.getTable(\"ClimateInfo\"); \nTableDescription tableDesc = table.describe(); \nIterator<GlobalSecondaryIndexDescription> gsiIter = \n tableDesc.getGlobalSecondaryIndexes().iterator(); \n\nwhile (gsiIter.hasNext()) { \n GlobalSecondaryIndexDescription gsiDesc = gsiIter.next(); \n System.out.println(\"Index data \" + gsiDesc.getIndexName() + \":\"); \n Iterator<KeySchemaElement> kse7Iter = gsiDesc.getKeySchema().iterator(); \n \n while (kseIter.hasNext()) { \n KeySchemaElement kse = kseIter.next(); \n System.out.printf(\"\\t%s: %s\\n\", kse.getAttributeName(), kse.getKeyType()); \n }\n Projection projection = gsiDesc.getProjection(); \n System.out.println(\"\\tProjection type: \" + projection.getProjectionType()); \n \n if (projection.getProjectionType().toString().equals(\"INCLUDE\")) { \n System.out.println(\"\\t\\tNon-key projected attributes: \" \n + projection.getNonKeyAttributes()); \n } \n}"
},
{
"code": null,
"e": 15880,
"s": 15630,
"text": "Use Query to perform an index query as with a table query. Simply create a DynamoDB class instance, a Table class instance for the target index, an Index class instance for the specific index, and pass the index and query object to the query method."
},
{
"code": null,
"e": 15937,
"s": 15880,
"text": "Take a look at the following code to understand better β"
},
{
"code": null,
"e": 16574,
"s": 15937,
"text": "DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient ( \n new ProfileCredentialsProvider()));\n \nTable table = dynamoDB.getTable(\"ClimateInfo\"); \nIndex index = table.getIndex(\"WindIndex\"); \nQuerySpec spec = new QuerySpec() \n .withKeyConditionExpression(\"#d = :v_date and Wind = :v_wind\") \n .withNameMap(new NameMap() \n .with(\"#d\", \"Date\"))\n .withValueMap(new ValueMap() \n .withString(\":v_date\",\"2016-05-15\") \n .withNumber(\":v_wind\",0));\n \nItemCollection<QueryOutcome> items = index.query(spec);\nIterator<Item> iter = items.iterator();\n\nwhile (iter.hasNext()) {\n System.out.println(iter.next().toJSONPretty()); \n}"
},
{
"code": null,
"e": 16643,
"s": 16574,
"text": "The following program is a bigger example for better understanding β"
},
{
"code": null,
"e": 16879,
"s": 16643,
"text": "Note β The following program may assume a previously created data source. Before attempting to execute, acquire supporting libraries and create necessary data sources (tables with required characteristics, or other referenced sources)."
},
{
"code": null,
"e": 16996,
"s": 16879,
"text": "This example also uses Eclipse IDE, an AWS credentials file, and the AWS Toolkit within an Eclipse AWS Java Project."
}
] |
Python program to check a sentence is a pangrams or not. | Given a sentence. Our task is to check whether this sentence is pan grams or not. The logic of Pan grams checking is that words or sentences containing every letter of the alphabet at least once. To solve this problem we use set () method and list comprehension technique.
Input: string = 'abc def ghi jkl mno pqr stu vwx yz'
Output: Yes
// contains all the characters from βaβ to βzβ
Input: str='python program'
Output: No
// Does not contains all the characters from βaβ to 'z'
Step 1: create a string.
Step 2: Convert the complete sentence to a lower case using lower () method.
Step 3: convert the input string into a set (), so that we will list of all unique characters present in the sentence.
Step 4: separate out all alphabets ord () returns ASCII value of the character.
Step 5: If length of list is 26 that means all characters are present and sentence is Pangram otherwise not.
def checkPangram(s):
lst = []
for i in range(26):
lst.append(False)
for c in s.lower():
if not c == " ":
lst[ord(c) -ord('a')]=True
for ch in lst:
if ch == False:
return False
return True
# Driver Program
str1=input("Enter The String ::7gt;")
if (checkPangram(str1)):
print ('"'+str1+'"')
print ("is a pangram")
else:
print ('"'+str1+'"')
print ("is not a pangram")
Enter The String ::abc def ghi jkl mno pqr stu vwx yz
"abc def ghi jkl mno pqr stu vwx yz"
is a pangram
Enter The String ::> python program
"pyhton program"
is not a pangram | [
{
"code": null,
"e": 1460,
"s": 1187,
"text": "Given a sentence. Our task is to check whether this sentence is pan grams or not. The logic of Pan grams checking is that words or sentences containing every letter of the alphabet at least once. To solve this problem we use set () method and list comprehension technique."
},
{
"code": null,
"e": 1668,
"s": 1460,
"text": "Input: string = 'abc def ghi jkl mno pqr stu vwx yz'\nOutput: Yes\n// contains all the characters from βaβ to βzβ\nInput: str='python program'\nOutput: No\n// Does not contains all the characters from βaβ to 'z'\n"
},
{
"code": null,
"e": 2079,
"s": 1668,
"text": "Step 1: create a string.\nStep 2: Convert the complete sentence to a lower case using lower () method.\nStep 3: convert the input string into a set (), so that we will list of all unique characters present in the sentence.\nStep 4: separate out all alphabets ord () returns ASCII value of the character.\nStep 5: If length of list is 26 that means all characters are present and sentence is Pangram otherwise not.\n"
},
{
"code": null,
"e": 2510,
"s": 2079,
"text": "def checkPangram(s):\n lst = []\n for i in range(26):\n lst.append(False)\n for c in s.lower(): \n if not c == \" \":\n lst[ord(c) -ord('a')]=True\n for ch in lst:\n if ch == False:\n return False\n return True\n# Driver Program \nstr1=input(\"Enter The String ::7gt;\")\nif (checkPangram(str1)):\n print ('\"'+str1+'\"')\n print (\"is a pangram\")\nelse:\n print ('\"'+str1+'\"')\n print (\"is not a pangram\")"
},
{
"code": null,
"e": 2685,
"s": 2510,
"text": "Enter The String ::abc def ghi jkl mno pqr stu vwx yz\n\"abc def ghi jkl mno pqr stu vwx yz\"\nis a pangram\nEnter The String ::> python program\n\"pyhton program\"\nis not a pangram\n"
}
] |
Tryit Editor v3.7 | Tryit: Create a full-width input field | [] |
Python 3 - String center() Method | The method center() returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space.
Following is the syntax for center() method β
str.center(width[, fillchar])
width β This is the total width of the string.
width β This is the total width of the string.
fillchar β This is the filler character.
fillchar β This is the filler character.
This method returns a string that is at least width characters wide, created by padding the string with the character fillchar (default is a space).
The following example shows the usage of center() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print ("str.center(40, 'a') : ", str.center(40, 'a'))
When we run above program, it produces the following result β
str.center(40, 'a') : aaaathis is string example....wow!!!aaaa
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2479,
"s": 2340,
"text": "The method center() returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space."
},
{
"code": null,
"e": 2525,
"s": 2479,
"text": "Following is the syntax for center() method β"
},
{
"code": null,
"e": 2556,
"s": 2525,
"text": "str.center(width[, fillchar])\n"
},
{
"code": null,
"e": 2603,
"s": 2556,
"text": "width β This is the total width of the string."
},
{
"code": null,
"e": 2650,
"s": 2603,
"text": "width β This is the total width of the string."
},
{
"code": null,
"e": 2691,
"s": 2650,
"text": "fillchar β This is the filler character."
},
{
"code": null,
"e": 2732,
"s": 2691,
"text": "fillchar β This is the filler character."
},
{
"code": null,
"e": 2881,
"s": 2732,
"text": "This method returns a string that is at least width characters wide, created by padding the string with the character fillchar (default is a space)."
},
{
"code": null,
"e": 2939,
"s": 2881,
"text": "The following example shows the usage of center() method."
},
{
"code": null,
"e": 3054,
"s": 2939,
"text": "#!/usr/bin/python3\n\nstr = \"this is string example....wow!!!\"\nprint (\"str.center(40, 'a') : \", str.center(40, 'a'))"
},
{
"code": null,
"e": 3116,
"s": 3054,
"text": "When we run above program, it produces the following result β"
},
{
"code": null,
"e": 3181,
"s": 3116,
"text": "str.center(40, 'a') : aaaathis is string example....wow!!!aaaa\n"
},
{
"code": null,
"e": 3218,
"s": 3181,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3234,
"s": 3218,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3267,
"s": 3234,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3286,
"s": 3267,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3321,
"s": 3286,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3343,
"s": 3321,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3377,
"s": 3343,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3405,
"s": 3377,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3440,
"s": 3405,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3454,
"s": 3440,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3487,
"s": 3454,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3504,
"s": 3487,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3511,
"s": 3504,
"text": " Print"
},
{
"code": null,
"e": 3522,
"s": 3511,
"text": " Add Notes"
}
] |
Maximum equlibrium sum in an array in C++ | Given an array arr[]. Find maximum value of prefix sum which is also suffix sum for index i in arr[].
If input array is β
Arr[] = {1, 2, 3, 5, 3, 2, 1} then output is 11 as β
Prefix sum = arr[0..3] = 1 + 2 + 3 + 5 = 11 and
Suffix sum = arr[3..6] = 5 + 3 + 2 + 1 = 11
Traverse the array and store prefix sum for each index in array presum[], in which presum[i] stores sum of subarray arr[0..i]
Traverse array again and store suffix sum in another array suffsum[], in which suffsum[i] stores sum of subarray arr[i..n-1]
For each index check if presum[i] is equal to suffsum[i] and if they are equal then compare, there value with overall maximum so far
Live Demo
#include <bits/stdc++.h>
using namespace std;
int getMaxSum(int *arr, int n) {
int preSum[n];
int suffSum[n];
int result = INT_MIN;
preSum[0] = arr[0];
for (int i = 1; i < n; ++i) {
preSum[i] = preSum[i - 1] + arr[i];
}
suffSum[n - 1] = arr[n - 1];
if (preSum[n - 1] == suffSum[n - 1]) {
result = max(result, preSum[n - 1]);
}
for (int i = n - 2; i >= 0; --i) {
suffSum[i] = suffSum[i + 1] + arr[i];
if (suffSum[i] == preSum[i]) {
result = max(result, preSum[i]);
}
}
return result;
}
int main() {
int arr[] = {1, 2, 3, 5, 3, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Max equlibrium sum = " << getMaxSum(arr, n) << endl;
return 0;
}
When you compile and execute above program. It generates following output β
Max equlibrium sum = 11 | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "Given an array arr[]. Find maximum value of prefix sum which is also suffix sum for index i in arr[]."
},
{
"code": null,
"e": 1184,
"s": 1164,
"text": "If input array is β"
},
{
"code": null,
"e": 1237,
"s": 1184,
"text": "Arr[] = {1, 2, 3, 5, 3, 2, 1} then output is 11 as β"
},
{
"code": null,
"e": 1285,
"s": 1237,
"text": "Prefix sum = arr[0..3] = 1 + 2 + 3 + 5 = 11 and"
},
{
"code": null,
"e": 1329,
"s": 1285,
"text": "Suffix sum = arr[3..6] = 5 + 3 + 2 + 1 = 11"
},
{
"code": null,
"e": 1455,
"s": 1329,
"text": "Traverse the array and store prefix sum for each index in array presum[], in which presum[i] stores sum of subarray arr[0..i]"
},
{
"code": null,
"e": 1580,
"s": 1455,
"text": "Traverse array again and store suffix sum in another array suffsum[], in which suffsum[i] stores sum of subarray arr[i..n-1]"
},
{
"code": null,
"e": 1713,
"s": 1580,
"text": "For each index check if presum[i] is equal to suffsum[i] and if they are equal then compare, there value with overall maximum so far"
},
{
"code": null,
"e": 1724,
"s": 1713,
"text": " Live Demo"
},
{
"code": null,
"e": 2456,
"s": 1724,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint getMaxSum(int *arr, int n) {\n int preSum[n];\n int suffSum[n];\n int result = INT_MIN;\n preSum[0] = arr[0];\n for (int i = 1; i < n; ++i) {\n preSum[i] = preSum[i - 1] + arr[i];\n }\n suffSum[n - 1] = arr[n - 1];\n if (preSum[n - 1] == suffSum[n - 1]) {\n result = max(result, preSum[n - 1]);\n }\n for (int i = n - 2; i >= 0; --i) {\n suffSum[i] = suffSum[i + 1] + arr[i];\n if (suffSum[i] == preSum[i]) {\n result = max(result, preSum[i]);\n }\n }\n return result;\n}\nint main() {\n int arr[] = {1, 2, 3, 5, 3, 2, 1};\n int n = sizeof(arr) / sizeof(arr[0]);\n cout << \"Max equlibrium sum = \" << getMaxSum(arr, n) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2532,
"s": 2456,
"text": "When you compile and execute above program. It generates following output β"
},
{
"code": null,
"e": 2556,
"s": 2532,
"text": "Max equlibrium sum = 11"
}
] |
JavaScript - Math random Method | This method returns a random number between 0 (inclusive) and 1 (exclusive).
Its syntax is as follows β
Math.random() ;
Returns a random number between 0 (inclusive) and 1 (exclusive).
Try the following example program.
<html>
<head>
<title>JavaScript Math random() Method</title>
</head>
<body>
<script type = "text/javascript">
var value = Math.random( );
document.write("First Test Value : " + value );
var value = Math.random( );
document.write("<br />Second Test Value : " + value );
var value = Math.random( );
document.write("<br />Third Test Value : " + value );
var value = Math.random( );
document.write("<br />Fourth Test Value : " + value );
</script>
</body>
</html>
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2543,
"s": 2466,
"text": "This method returns a random number between 0 (inclusive) and 1 (exclusive)."
},
{
"code": null,
"e": 2570,
"s": 2543,
"text": "Its syntax is as follows β"
},
{
"code": null,
"e": 2587,
"s": 2570,
"text": "Math.random() ;\n"
},
{
"code": null,
"e": 2652,
"s": 2587,
"text": "Returns a random number between 0 (inclusive) and 1 (exclusive)."
},
{
"code": null,
"e": 2687,
"s": 2652,
"text": "Try the following example program."
},
{
"code": null,
"e": 3287,
"s": 2687,
"text": "<html>\n <head>\n <title>JavaScript Math random() Method</title>\n </head>\n \n <body>\n <script type = \"text/javascript\">\n var value = Math.random( );\n document.write(\"First Test Value : \" + value ); \n \n var value = Math.random( );\n document.write(\"<br />Second Test Value : \" + value ); \n \n var value = Math.random( );\n document.write(\"<br />Third Test Value : \" + value ); \n \n var value = Math.random( );\n document.write(\"<br />Fourth Test Value : \" + value ); \n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 3322,
"s": 3287,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3336,
"s": 3322,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3370,
"s": 3336,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3384,
"s": 3370,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3419,
"s": 3384,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3436,
"s": 3419,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3471,
"s": 3436,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3488,
"s": 3471,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3521,
"s": 3488,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3549,
"s": 3521,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3583,
"s": 3549,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3611,
"s": 3583,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3618,
"s": 3611,
"text": " Print"
},
{
"code": null,
"e": 3629,
"s": 3618,
"text": " Add Notes"
}
] |
SAP Testing - Quick Guide | Many organizations implement SAP ERP (Enterprise Resource Planning) to manage their business operations and adapt according to new market challenges. SAP R/3 is an integrated ERP software that allows organizations to manage their business efficiently. Organizations can reduce the cost to run their operations by using SAP R/3 ERP packages.
SAP R/3 also allows customers to interact with different databases to run different applications with the help of a user-friendly GUI. The SAP R/3 system is divided into different modules to cover the functionality of different business operations in an organization.
The most common SAP R/3 modules are β
SAP Material Management.
SAP Financial Accounting and Controlling.
SAP Sales and Distribution.
SAP Human Resource.
SAP Supply Chain Management.
SAP Plant Management.
SAP Testing is about testing the functionality of these modules and to ensure that they perform as per the configuration.
A SAP system undergoes various changes like patch management and fixes, new module implementations, and various other configuration changes. All these modifications raise a need for Regression testing that is to be performed in SAP environments. SAP testing automation tools like SAP Test Acceleration and Optimization tools can be used for this purpose.
SAP TAO is an automation tool to generate test cases for end-to-end scenarios for SAP applications. Apart from this, there are various other Automation testing tools for SAP testing like HP QTP, and ECATT, etc. that can be used.
Here is a list of key reasons why SAP testing is performed and why it is an important function in the growth of an organization β
System Validation β SAP Testing involves complete end-to-end testing and validation of all SAP modules in SAP ERP environment.
System Validation β SAP Testing involves complete end-to-end testing and validation of all SAP modules in SAP ERP environment.
Quality and Revenue β SAP Testing is an output-based testing and not like conventional testing methods which are input-based. It ensures the quality of SAP system and also focuses on revenue and cost of the organization.
Quality and Revenue β SAP Testing is an output-based testing and not like conventional testing methods which are input-based. It ensures the quality of SAP system and also focuses on revenue and cost of the organization.
Cost and Predictability β SAP Testing involves reducing the SAP development costs and improve predictability.
Cost and Predictability β SAP Testing involves reducing the SAP development costs and improve predictability.
Compliance Requirement β SAP Testing ensures that the SAP implementation is meeting the new compliance requirements in a specific organization and all the modules are working as per the expected configuration.
Compliance Requirement β SAP Testing ensures that the SAP implementation is meeting the new compliance requirements in a specific organization and all the modules are working as per the expected configuration.
New Implementation and Configuration Changes β There are different types of changes implemented in a SAP system, like patches and fixes, new implementation, configurational changes. Therefore, SAP testing ensures that all the modules are performing as per requirement in this dynamic system environment.
New Implementation and Configuration Changes β There are different types of changes implemented in a SAP system, like patches and fixes, new implementation, configurational changes. Therefore, SAP testing ensures that all the modules are performing as per requirement in this dynamic system environment.
Integration β SAP testing is performed to test various reports, data flows and work flows, GUI forms, etc. It is used to check system integration between different modules. For example, if an order posting is done that requires an action in Sales and Distribution, MM and FICO, then SAP testing checks the integration between these systems.
Integration β SAP testing is performed to test various reports, data flows and work flows, GUI forms, etc. It is used to check system integration between different modules. For example, if an order posting is done that requires an action in Sales and Distribution, MM and FICO, then SAP testing checks the integration between these systems.
Performance β It is also used to ensure if the system will be able to meet the Service Level agreements, time taken by system to perform specific actions, performance of the system, etc.
Performance β It is also used to ensure if the system will be able to meet the Service Level agreements, time taken by system to perform specific actions, performance of the system, etc.
There are different testing methods that can be used to test the functionality of a software, system, or an application.
The most common testing techniques are β
Unit Testing β It is a type of white-box testing that involves testing a single unit or group of units.
Unit Testing β It is a type of white-box testing that involves testing a single unit or group of units.
Integration Testing β In this testing, multiple systems are combined together to test the output of the integrated system.
Integration Testing β In this testing, multiple systems are combined together to test the output of the integrated system.
Functional Testing β It checks the functionality of each module as per the desired result.
Functional Testing β It checks the functionality of each module as per the desired result.
Usability Testing β It checks the ease of use of an application or a system. It checks how easy it would be for a new user to use an application or to understand the system.
Usability Testing β It checks the ease of use of an application or a system. It checks how easy it would be for a new user to use an application or to understand the system.
Acceptance Testing β Acceptance testing is performed to test if a system meets the user requirement and whether to accept the application or system.
Acceptance Testing β Acceptance testing is performed to test if a system meets the user requirement and whether to accept the application or system.
System Testing β Entire system is tested as per the requirement and specification.
System Testing β Entire system is tested as per the requirement and specification.
Stress Testing β In this testing, the system is put into stress beyond its specification to check when it fails.
Stress Testing β In this testing, the system is put into stress beyond its specification to check when it fails.
Performance Testing β This testing is performed to check if the system meets the performance requirement.
Performance Testing β This testing is performed to check if the system meets the performance requirement.
Regression Testing β It includes testing the full application or system for the modifications.
Regression Testing β It includes testing the full application or system for the modifications.
Beta Testing β The aim of beta testing is to cover unexpected errors. It falls under the class of black-box testing. It is performed by releasing the pre-version of the final product, called Beta.
Beta Testing β The aim of beta testing is to cover unexpected errors. It falls under the class of black-box testing. It is performed by releasing the pre-version of the final product, called Beta.
Database Testing β Database testing is used to test the data in the database. It is performed using SQL statements.
Database Testing β Database testing is used to test the data in the database. It is performed using SQL statements.
ETL Testing β ETL testing is performed to ensure if data is correctly extracted, transformed, and loaded from a source system to a target system.
ETL Testing β ETL testing is performed to ensure if data is correctly extracted, transformed, and loaded from a source system to a target system.
Manual testing means you are testing a software manually without using any automated tools or any script. In this type of testing, the tester takes over the role of an end-user and tests the software to identify bugs or any unexpected behavior.
There are different stages of a manual testing. They are β unit testing, integration testing, system testing, and user acceptance testing.
Various test plans, test cases, or test scenarios are used by a manual tester to ensure the completeness of testing. Manual testing can also be called exploratory testing because the testers explore the software to identify errors in it manually.
In Automation testing, the tester writes the scripts and uses software tools to test the product. This process involves the automation of a manual process. Automation testing includes re-running the test-cases multiple times that were performed manually.
Automation testing is also used to test the application from load, performance, and stress purpose. It is used to increase the coverage of test. Automation testing improves the accuracy and saves time and money in comparison to manual testing.
The following tools can be used for Automation testing β
HP Quick Test Professional (QTP)
Selenium
SAP TAO
ECATT
IBM Rational Functional Tester
SilkTest
TestComplete
Testing Anywhere
WinRunner
LaodRunner
Visual Studio Test Professional
WATIR
Software Development Life Cycle determines the series of steps to be performed to develop an application or the efficiency of a software. In this chapter, we will discuss the phases defined in SDLC. Each phase has its own process and deliverables that goes into the next phase.
The first stage of SDLC is requirement gathering. After the requirements are gathered, the team comes up with a rough plan of software process. At this step, the team analyzes if a software can be made to fulfill all the requirements of the user. It is found out if the project is financially, practically, and technologically feasible for the organization to take up. There are many algorithms available, which help the developers to conclude the feasibility of a software project.
At this step, the developers decide a roadmap of their plan and try to bring up the best software model suitable for the project. System analysis includes understanding of software product limitations, learning system-related problems or changes to be done in the existing systems, identifying and addressing the impact of the project on the organization and personnel etc. The project team analyzes the scope of the project and plans the schedule and resources accordingly.
The next step is to bring the whole knowledge of requirements and analysis on to the desk and design the software product. The inputs from the users and the information gathered in the requirement gathering phase are the inputs of this step. The output of this step comes in the form of two designs; logical design and physical design. Engineers produce meta-data and data dictionaries, logical diagrams, data-flow diagrams and in some cases pseudocodes.
This step is also known as programming phase. The implementation of software design starts in terms of writing the program code in a suitable programming language and developing error-free executable programs efficiently.
An estimate says that 50% of the whole software development process should be tested. Errors may ruin the software from critical level to its own removal. Software testing is done while coding by the developers and thorough testing is conducted by testing experts at various levels of code such as module testing, program testing, product testing, in-house testing and testing the product at userβs end. Early discovery of errors and their remedy is the key to developing a reliable software.
Software may need to be integrated with the libraries, databases, and other program(s). This stage of SDLC deals with the integration of the software with outer world entities.
Implementation or deployment means installing the software on user machines. At times, the software needs post-installation configurations at the userβs end. Software is tested for portability and adaptability and integration related issues are solved during implementation.
Software Testing Life Cycle (STLC) consists of all the steps that are performed in a specific way to ensure that quality goals are met and each step has specific goals and deliverables.
STLC is used to improve the quality of a software product and to make it capable to meet the business requirements to achieve certain goals.
The different stages that come under Software Testing Life Cycle are as follows β
Requirements phase
Test Planning
Test Analysis
Test Design Phase
Test Implementation
Test Execution Phase
Test Closure Phase
This is the first phase of Software Testing Life Cycle. During this phase, the testerβs job is to analyze the requirements. There are various methods for Requirement Analysis like conducting brainstorming sessions with business people, team members, and try to find out whether the requirements are testable or not.
This phase determines the scope of the testing. If a testing team finds any features that canβt be tested, then that should be communicated to the client.
In this phase, the tester identifies the activities and resources which would help to meet the testing objectives.
Various metrics are defined and there are methods available to determine and track those metrics. Test planning also includes identifying key performance indicators for testing evaluation.
This phase determines the guidelines that has to be tested. It includes identifying the test conditions using the requirements document, any risks involved, and other test criteria.
Various factors are used to find out the test conditions β
Product Complexity
Depth of Testing
Risk Involved
Skills Required
Knowledge of testing team members
Test management
Availability of the stakeholders
Test conditions should be written in a detailed way.
Let us take an example. For a website selling products online, a test condition is that a customer should be able to make an online payment. You can add detailed conditions like, payment should be feasible using Credit card, NEFT transfer, debit card or net banking.
The advantage of writing the detailed test condition is that it increases the scope of testing because test-cases are normally written on the basis of the test condition. It allows to write more detailed test cases. It also helps in determining the condition of when to stop the testing of a software product.
This phase determines how the tests are performed.
Break down the test conditions into multiple sub-conditions to increase its coverage.
Break down the test conditions into multiple sub-conditions to increase its coverage.
Get the test data.
Get the test data.
Set up the test environment.
Set up the test environment.
Get the requirement traceability metrics.
Get the requirement traceability metrics.
Create the test coverage metrics.
Create the test coverage metrics.
This phase includes the creation of detailed test-cases as per the test conditions and metrics defined.
Prioritize the test case.
Test-case to be used for Regression.
Ensure the correctness of the test-cases.
Sign off of the test-cases before the actual execution starts.
This phase of Software Testing Life Cycle involves actual execution of test-cases.
Execute the test-cases.
Log the defects.
Check traceability metrics to track progress.
This phase includes checking for the completion of the test.
Check if all the test-cases are executed and opened defects.
Note down the lessons learnt.
Close the Testing phase.
There are different types of testing methods available that can be used to perform SAP testing.
Unit testing is used to test the functionality of a SAP system and its various components. It is performed by domain and configuration experts who know the functionality of each unit in a system.
Suppose the task is to create a sales order and save it. To perform unit testing for this task, the tester should know that the sales order can be saved using the SAP organization elements like customer master data, partner functions, material master data, company code, credit control area, sales organization, etc.
In ABAP development, Unit testing can be performed to check if a report can be created from developer-generated data. It requires assistance from the domain expert.
System Testing involves the integration of elements of a SAP system to ensure that related SAP functionality are linked together in the development environment.
If you say a cash flow for a quotation in an organization would show that a quote can be used to create a sales order, a delivery can be created and processed from the order, the delivery can be billed, the billing released to accounting, and a customer payment applied against the accounting invoice.
Each unit is tested like this and then the test results are combined using system testing.
Scenario testing, as the name suggests, is performed as per specific business cases.
Suppose there are a few tasks that are specific to a customer segment or a given product line or a set of services. For these specific line of target, you have different scenarios that you need to test. This testing is also performed in the development environment.
In this testing, testing data comes from a real data extraction source. Data is known to business end-users.
Integration testing is used to present that the business process, as designed and configured in SAP, runs using real-world data. In addition the testing shows that the interface triggers, reports, workflows are working.
Interface testing ensures that a business process on a SAP system runs automatically, the events are triggered, and the results are transferred to the receiver system. Interface testing involves execution on the sending system followed by automatic generation of the interface output, and then the receiving system consuming that file and proving that a business process continues on the receiver.
Ideally, interface testing involves larger testing activities as a project progresses. Interface testing shows that triggering works, the data selection is accurate and complete, data transfer is successful, and the receiver is able to consume the sent data.
SAP UAT is used to ensure that the end-users are able to perform the assigned job functions with the new system. The important aspect of this testing is to understand the business requirement and to ensure that the expected features, functions and capabilities are available.
Performance testing checks the following aspects β
Whether the system response time is acceptable as per the business requirement
Whether the system response time is acceptable as per the business requirement
Whether periodic processes are running within permissible time,
Whether periodic processes are running within permissible time,
Whether the expected concurrent user load can be supported
Whether the expected concurrent user load can be supported
Performance testing identifies bottlenecks and coding inefficiencies in the SAP system. It is not likely that system performance tuning is perfectly set up and the program is running with optimized code.
In Load Testing, the tester applies maximum load on a system, either online users or periodic batch processing, and identifies whether the system is capable enough to handle the load. If not, it finds out the steps needed to improve performance.
Security and Authorizations Testing is used to ensure that users are only able to execute transactions and access appropriate data that is relevant to their project.
As with the implementation of Security standards, this is really important to test if security and authorization is placed in a system. Test IDs for job roles are created and used to both confirm what a user can do and what a user cannot do.
Cutover testing is usually performed once in a project lifecycle. Here a full-scale execution is done of all the tasks involved to extract data from legacy systems. Then, to perform any kind of data conversion, load the results into the SAP system and fully validate the results, including a user sign-off.
Regression testing is used to find new functionalities and to test previous functionalities in a system when it is upgraded or a new system is set up. The key role of regression testing is to test the existing functionality and newly updated configuration and codebase.
When you upgrade your SAP system or apply a patch, it shouldnβt affect the functionality that is expected to be performed by the users. In addition, it should not affect the new features that are supposed to be introduced in a new release.
SAP testing process is usually divided into three phases β
Test Planning
Test System setup
Test Execution and evaluation
Test planning includes the steps that are involved in the initial phase of testing.
Gathering the requirement. What needs to be tested? Functional requirements to be collected for system and application testing.
Gathering the requirement. What needs to be tested? Functional requirements to be collected for system and application testing.
Test-case development for manual and automation testing. In automation testing, various tools can be used for creating test-cases.
Test-case development for manual and automation testing. In automation testing, various tools can be used for creating test-cases.
Reviewing the test-cases.
Reviewing the test-cases.
Test system setup involves setting up the test environment to run the test-cases. Here, the tester needs to define key metrics for reporting.
Test execution and evaluation involves executing the test-cases and noting down the output. It includes the following activities β
Defect handling and reporting.
Assessment of Test plans as per result.
Documentation of all defects and compare the results with key metrics.
In SAP system testing, you need to identify critical business processes that will be affected by implementing changes in a SAP system. It mostly comes under Regression testing, where you apply a patch or implement a new system.
The first step before applying these changes is to perform change impact analysis. This covers critical processes that will be affected by implementing the change.
Let us take an example. Suppose the planned changes are as follows β
SAP support pack 7
Custom code
SAP enhance package
Sales Order
Delivery of goods
Payment method
Here, the following activities are to be carried out in Impact Analysis β
Identification of the critical business processes impacted by change implementation.
Identification of the critical business processes impacted by change implementation.
Business justification to be provided as to why this change has to be implemented.
Business justification to be provided as to why this change has to be implemented.
Creating the test plan to monitor critical processes for SAP testing while performing the change.
Creating the test plan to monitor critical processes for SAP testing while performing the change.
Evaluation of impact of change on critical processes and the purpose to implement the change.
Evaluation of impact of change on critical processes and the purpose to implement the change.
SAP testing navigation ensures that you cover each module of your SAP system and perform at least one test for each functionality. It also reduces the manual testing effort and covers most of the testing paths in a SAP system.
OPA tests can be performed to check SAP Testing Navigation. OPA is known as Open Source Programming language and it is mostly used for developing web applications. For compilation of OPA program, you can use Node.js on the server and JavaScript on the client side.
OPA allows you to use three objects in Qunit. These functions should be defined in a test so that OPA knows what actions to be taken.
Given β to pass arrangements.
Given β to pass arrangements.
When β actions to be taken.
When β actions to be taken.
Then β assertion.
Then β assertion.
The following example shows how to use all the 3 objects in Qunit β
jQuery.sap.require("sap.ui.test.Opa");
jQuery.sap.require("sap.ui.test.opaQunit");
opaTest("press a Button", function (Given, When, Then) {
// Arrangements
Given.iStartMyApp();
//Actions
When.iPressOnTheButton();
// Assertions
Then.theButtonShouldHaveADifferentText();
}
The next step is to define the three functions.
var arrangements = new sap.ui.test.Opa ({
iStartMyApp : function (){
return this.iStartMyAppInAFrame("../index.html");
}
});
In the above function, we have assumed that the app runs in a page called index.html. Our OPA test is located in the test/opa.html folder.
var actions = new sap.ui.test.Opa ({
iPressOnTheButton : function (){
return this.waitFor ({
viewName : "Main", id : "pressMeButton", success : function (oButton) {
oButton.$().trigger("tap");
},
errorMessage : "No Button found"
});
}
})
var assertions = new sap.ui.test.Opa ({
theButtonShouldHaveADifferentText : function () {
return this.waitFor ({
viewName : "Main",
id : "pressMeButton",
matchers : new sap.ui.test.matchers.PropertyStrictEquals ({
name : "text",
value : "got pressed"
}),
success : function (oButton) {
Opa.assert.ok(true, "The button's text changed to: " + oButton.getText());
},
errorMessage : "No change in Button's text"
)}
}
})
sap.ui.test.Opa.extendConfig ({
arrangements : arrangements,
actions : actions,
assertions : assertions,
viewNamespace : "view."
});
Screen flow logic in SAP Testing is like an ABAP code and it is used to contain the processing blocks. It contains the procedural part of the screen. It is created in screen painter and this screen painter is similar to an ABAP editor.
Screen flow logic involves no external data declaration and each processing block is defined with a prefix βPROCESSβ. For example,
PROCESS AFTER INPUT
PROCESS BEFORE OUTPUT
PROCESS ON HELP-REQUEST
PROCESS ON VALUE-REQUEST
Each screen flow logic should contain PROCESS AFTER INPUT and PROCESS BEFORE OUTPUT keywords.
In an event block, you can use keywords like MODULE, FIELD, ON, VALUES, CALL, etc.
MODULE
Calls a dialog module in an ABAP program
FIELD
Specifies the point at which the contents of a screen field should be transported
ON
Used in conjuction with FIELD
VALUES
Used in conjunction with FIELD
CHAIN
Starts a processing chain.
ENDCHAIN
Ends a processing chain.
CALL
Calls a subscreen.
LOOP
Starts processing a screen table.
ENDLOOP
Ends processing a screen table.
In the Repository browser, double-click on the name of a screen and it will display the flow logic of the screen.
The Flow Logic Editor of the Screen Painter will open and you edit the screen flow logic. You can use any of the available ABAP source code editors to define the flow logic.
You can use the following keywords to create the screen flow logic β
CALL
Calls a subscreen.
CHAIN
Starts a processing chain.
ENDCHAIN
Ends a processing chain.
ENDLOOP
Ends loop processing.
FIELD
Refers to a field. Can be combined with the keywords MODULE and SELECT.
LOOP
Starts loop processing.
MODIFY
Modifies a table.
MODULE
Identifies a processing module.
ON
Used with FIELD assignments.
PROCESS
Defines a processing event.
SELECT
Checks an entry in a table.
Testing screens are used to test the appearance of a screen as it will appear at runtime. If you have already programmed the flow logic, you can choose whether to simulate the screen with or without it.
To perform Screen test, follow the steps given below β
Select Screen β Test.
The system will display a dialog box for the runtime simulation.
You can change the window coordinates, if it is required.
Next, define the scope of simulation.
To include the flow logic, click 'choose complete flow logic'.
Click Continue and the screen simulation will appear.
There are different SAP modules implemented in an organization that can be tested using various testing tools like HP Quick Test Professional (QTP), IBM Rational Functional Tester (RFT), and SAP Test Acceleration and Optimization (TAO) tool.
The common SAP modules are listed below β
Financial Modules β Finance Accounting and Controlling (FICO), Treasure (TR), and Enterprise Control (EC).
Financial Modules β Finance Accounting and Controlling (FICO), Treasure (TR), and Enterprise Control (EC).
Logistics Modules β Material Management (MM), Plant Maintenance (PM), Sales and Distribution (SD), Quality Management (QM), etc.
Logistics Modules β Material Management (MM), Plant Maintenance (PM), Sales and Distribution (SD), Quality Management (QM), etc.
Human Resource Management β Accounting Payroll, Time Management, Training and Event Management.
Human Resource Management β Accounting Payroll, Time Management, Training and Event Management.
All these modules are inter-dependent and the functionality of one module affects the functionality of other modules.
Suppose you have to create a Sales Order in Sales and Distribution (SD) module. Here, you first need to enter the transaction code(e.g., Transaction Code VA01). Next, check the stock of the item in Inventory module and check the credit limit available on Customer profile in Customer Relationship Module. It shows that all these modules are interdependent; if you customize any of these modules, it will affect the related ERP system.
To perform SAP testing, you need to understand the features, functionalities, and how the workflow takes place in these SAP modules. Most of the common reasons of failure of ERP implementation project is incorrect test planning and the use of wrong test-cases.
Non SAP ERP systems like PeopleSoft, Edwards, Oracle E business suite have different customers and capabilities. The testing team needs to understand the functionality of complete system.
There are normally two types of testers available in SAP projects β
Core Testers β who are responsible to perform basic testing of ERP system and modules.
Core Testers β who are responsible to perform basic testing of ERP system and modules.
Implementation Testers β who work on implementation project and cover the customization functionalities of SAP modules.
Implementation Testers β who work on implementation project and cover the customization functionalities of SAP modules.
Customization requests from clients can impact the modules of a SAP system. The testing team should be able to record each customization request and its impact on the other SAP modules.
ERP systems are large systems and therefore the testing process should ideally be automated. It is always advisable to perform automated testing for ERP systems, as manual testing is a very time-consuming and lengthy process. Without testing each component of the SAP system, it is really tough to achieve 100% quality and successful implementation of SAP project.
To perform SAP testing for the above example, follow the steps given below β
The first step is to install HP QTP tool and to install necessary plug-ins within QTP to make it compatible to connect to ERP system.
The first step is to install HP QTP tool and to install necessary plug-ins within QTP to make it compatible to connect to ERP system.
The next step is to use HP Quality Center (QC) to develop the test plan and then to convert test plan design to Test Scripts. These test plans can be converted to scripts using HP QTP.
The next step is to use HP Quality Center (QC) to develop the test plan and then to convert test plan design to Test Scripts. These test plans can be converted to scripts using HP QTP.
Next, record the R/3 GUI screen of SAP system for SD module while creating Sales Order or creating PR in MM.
Next, record the R/3 GUI screen of SAP system for SD module while creating Sales Order or creating PR in MM.
After you are done with the recording in QTP tool, create a script in VB.
After you are done with the recording in QTP tool, create a script in VB.
SAPGuiSession("Session").SAPGuiWindow("SAP Easy Access - User")
.SAPGuiOKCode("OKCode").Set "/nVA01"
SAPGuiSession("Session").SAPGuiWindow("SAP Easy Access - User"). SendKey ENTER
You can also add different parameters and customizations as per your requirement.
An Interface in an ERP system is known as a tool that is responsible to get data from one system and move that data to another system. For example, assume you have a program that produces a report in XML format and then this program reads the XML file to provide input to another system. You can also manipulate while passing the information from one system to other.
Consider a vendor tool that takes care of employee attendance. Now, the system interface will take this information and populate it in the SAP HR system.
Interface testing ensures that this job is running successfully to ensure that the data is transferred completely and there is no error while transferring the data to the SAP HR system.
SAP Interface testing is purely dependent on the operations and organizational processes. While performing SAP Interface Testing, you need to consider the following key points β
What is the purpose of using SAP Interface and what business scenarios are processed by the interface?
What is the purpose of using SAP Interface and what business scenarios are processed by the interface?
Check if the Interface is processing all business scenarios accurately as per the test strategy.
Check if the Interface is processing all business scenarios accurately as per the test strategy.
To perform Interface testing, the best practice is to start with performing Unit testing.
To perform Interface testing, the best practice is to start with performing Unit testing.
You have to check if the outbound interface is alright, which means that it ensures to perform file meeting specifications in terms of layout, etc.
You have to check if the outbound interface is alright, which means that it ensures to perform file meeting specifications in terms of layout, etc.
You have to check if the inbound interface is okay. Check if it is reading the file correctly and if it is performing the correct steps in the target system.
You have to check if the inbound interface is okay. Check if it is reading the file correctly and if it is performing the correct steps in the target system.
SAP test-cases are required to perform a check on the installation and configuration of the SAP system, any new implementation, multi-language and device testing, intranet testing, real-time testing, etc.
An ERP system is a common centralized system and is used by multiple users simultaneously in real time. Hence it creates a need to write the test-cases with lot of effort and dedication.
An ERP system also involves various FI transactions, so each test-case should cover the scope of all the configuration and implementation part. Test data should be passed carefully and each test should have a column with name output data.
Test Case ID β XYZ_ERP_SD_A20301
Module β SAP Sales & Distribution SD
Let us check the transaction VA01 to create a sales order in the Sales and Distribution (SD) system.
Fields to be entered while creating an Order β
Order Date
Order Type
Expiry Date
Customer ID
Shipping Id, Shipping Details, etc
Once you enter the details, press Enter and add all the details in the Sales Order.
To create a SAP test-case, you can pass input data (correct and Incorrect and see the outcome) β
Order Date 01/01/2016, Order Type Sales Order
Expiry Date 15/01/2016, Shipping Date 10/01/2016,
Select Payment Due Date 10/01/2015, Item Qty 10, etc.
Order Date 01/01/2017, Order Type Sales Order
Expiry Date 15/01/2017, Shipping Date 10/01/2017,
Select Payment Due Date 10/01/2017, Item Qty 0, etc.
Order is successfully saved in SAP module and invoiced.
Next is Packing slip number.
Next is Shipping Order number, etc.
Error message for incorrect data input. Text message for incorrect input data should be defined in the system.
Error message for incorrect data input. Text message for incorrect input data should be defined in the system.
Sales Order#
Sales Invoice#
Packing List#, etc.
SAP Testing TAO (Test Acceleration and Optimization) is a tool used to perform automated testing of SAP systems. SAP TAO helps customers to fasten the process of creating automated test cases for SAP systems. Automation testing using TAO is performed by creating test components for various transactions in SAP modules.
Test components using TAO are uploaded to HP Quality Center. Test components created like this are normally for the single transactions and can be later used to create test scenarios. This tool can be easily integrated with SAP Solution Manager to maintain the different test components.
In short, you can say that SAP TAO enables SAP clients in automating the business needs by automatically creating draft test-cases and test components.
SAP TAO enables customers to breakdown a single software into multiple parts which can be integrated to test cases using a simple interface by dragging and dropping each part.
TAO supports flexible reuse of test cases and data.
TAO supports flexible reuse of test cases and data.
If there is any functional change in the system, it is easy to maintain test-cases because of this change.
If there is any functional change in the system, it is easy to maintain test-cases because of this change.
The common versions of SAP TAO are TAO 2.0 and TAO 3.0.
One of the key features of SAP TAO is that it can be easily integrated with various tools to create automated test-cases. Some common tools which can be integrated with TAO are β
SAP Solution Manager (Solman).
HP Quality Center QC.
HP Quality Test Professional QTP.
SAP TAO 2.0 is a tool that is used to create automatic test-cases during Regression testing of a system. It helps SAP customers to create different test components from the screens of a transaction and parameterize them.
These test components are created normally for one transaction code and later they can be combined to test scenarios. It can be easily integrated with the Business Process Change Analyzer in SAP Solution Manager.
SAP TAO 2.0 comes with different Service pack SP 02, SP 04, and SP 06.
SAP TAO performs the following tasks in SAP Testing Lifecycle β
Test Cases creation
Regeneration of affected components
Test Cases Consolidation
Test Execution
The following illustration shows the process architecture of SAP TAO.
The steps are as follows β
The first step is to get the requirements for SAP Testing. This includes understanding the functionality of SAP modules and identifying the requirement for testing to be performed.
The first step is to get the requirements for SAP Testing. This includes understanding the functionality of SAP modules and identifying the requirement for testing to be performed.
Next, get the information from the requirement analysis to generate the Test components.
Next, get the information from the requirement analysis to generate the Test components.
The next step is to generate test-cases and components using SAP TAO tool.
The next step is to generate test-cases and components using SAP TAO tool.
The last step is to document the test results and update the analysis with test results.
The last step is to document the test results and update the analysis with test results.
Downloaded SAP Solution Manager Solman compatibility Matrix, Quality Center, and SAP TAO from this link β http://service.sap.com
Go to Test Management and Additional Information > Test Management. It will show all the compatible components supported by SAP TAO.
Check the prerequisites for components on SAP systems in your system landscape β
Version of SAP Solution Manager SOLMAN, after checking the compatibility matrix as above.
Version of SAP Solution Manager SOLMAN, after checking the compatibility matrix as above.
Version of ST-PI on all systems under test.
Version of ST-PI on all systems under test.
Version of ST-A/PI on systems under test of type CRM.
Version of ST-A/PI on systems under test of type CRM.
For SAP Solution Manager Configuration work center, ensure that the systems on which testing has to be done are connected to SOLMAN.
SAP TAO client installation requires the following configuration on local system β
RAM: 4 GB.
Free disk space: 500 MB.
LAN connection to SAP Quality Center QC server and SOLMAN.
Administration Rights.
SAPGUI with the latest patch level.
Microsoft Excel 97 or higher.
Microsoft Internet Explorer for CRM UI support.
There are various modules inside the SAP TAO tool. We have discussed the key components in this chapter.
The first component is Process Flow Analyzer which is used to automatically find out the user interfaces used in transaction codes executed in the SAP system. It automatically creates the test components and uploads them to Quality Center.
Process Flow Analyzer is also used to identify the sequence of test components as per user actions and creation of spreadsheet values.
You have to add Transaction codes to the list. SAP TAO will return all the screens associated with a particular transaction. You can choose any screen and click on Inspect option.
It allows you to collect multiple test components into one test. You need to find the test in Quality Center from QC tree and click on Consolidate.
Select the Transaction code you want to consolidate and click Add to Consolidate list at the bottom to create a test scenario.
Import and Export options are used to export to Quality Center and import from Quality Center. You need to select the components to be imported and exported and click on the required button.
Change Analyzer is used to track the changes and impact on the SAP system. When you make any change to a SAP system, it identifies the affected business processes.
To use Change Analyzer, select the specific project and click the change impact analysis option. It will allow you to review and repair the impacted components in the SAP system because of this change.
Repository is used to contain information about all the test components and flow in a project. To review information about any test component and to check the process flow, you can click Component Explorer or PFA Explorer.
Configuration of SAP Quality Center can be done in two ways β
HP Server Attributes
HP Project
Step 1 β In SAP TAO, click SAP Quality Center. You should have SAP Quality Center URL in the connection panel of SAP TAO. Next, enter the URL in the web browser.
Step 2 β Enter the following values in SAP Quality Center by HP Site Administration and click apply to entire.
DISABLE_EXTENDED_STORAGE = N
BACKWARD_SUPPORT_ALL_DOMAINS_PROJECTS = Y
Step 3 β For a new project, perform the following steps β
Create new domain and project in SAP QC.
Create new user to assign that project to new user.
Allocate Project Administrator role to newly created user.
Step 4 β Log off from SAP Quality Center by HP Site Administration.
In SAP TAO, click SAP Quality Center. You should have SAP Quality Center URL in connection panel of SAP TAO.
Step 1 β Enter the URL in your web browser.
Step 1 β Enter the URL in your web browser.
Step 2 β The next step is to login to domain/project.
Step 2 β The next step is to login to domain/project.
Step 3 β Navigate to the Test Plan.
Step 3 β Navigate to the Test Plan.
Step 4 β Under Subject folder, create a folder with the name BPT Resources β create a folder library.
Step 4 β Under Subject folder, create a folder with the name BPT Resources β create a folder library.
Step 5 β SAP TAO notes information about test Consolidation into a user field of the test entities in QC and by default it is TS_USER_01. Note that this is correct when connected to SOLMAN for all the tests created by SAP TAO.
Step 5 β SAP TAO notes information about test Consolidation into a user field of the test entities in QC and by default it is TS_USER_01. Note that this is correct when connected to SOLMAN for all the tests created by SAP TAO.
Step 6 β SAP QC users shouldnβt use the similar user field for other purposes in their Quality Center projects.
Step 6 β SAP QC users shouldnβt use the similar user field for other purposes in their Quality Center projects.
Application area is required by SAP TAO components to contain HP QTP and web add-ons. To create an application area in QTP, you need to perform the following steps β
Run QTP by HP as Administrator. It varies as per the operating system.
Run QTP by HP as Administrator. It varies as per the operating system.
You can select Web addins and SAP.
You can select Web addins and SAP.
Next, connect automatically or manually to Quality Center project. This step is automatic if it is configured.
Next, connect automatically or manually to Quality Center project. This step is automatic if it is configured.
Next, create an application area with the name_SAP_Doc. The name of application area is entered when the Save button is clicked.
Next, create an application area with the name_SAP_Doc. The name of application area is entered when the Save button is clicked.
Process Flow Analyzer is used to automatically find out the user interfaces used in transactions codes executed in SAP system. It automatically creates the test components and upload them to Quality Center.
It is also used to identify sequence of test components as per user actions and creation of spreadsheet values.
Click Add Transaction button β Enter the Transaction-code and click OK.
The next step is to click the Start button.
TAO will launch SAP and will log the Transaction entered by you. Once the transaction process is completed, click the Stop button.
TAO will return all the screens that are used to create the process flow. Next, upload the analysis to QC. This can be done by clicking the Upload button.
Import and Export options are used to export to Quality Center and import from Quality Center. You need to select the components to be imported and exported and click the required button.
First, identify the components to be imported or exported. Click Export to SAP QC or Import from SAP QC to import/export the required components.
Change Analyzer is used to track the changes and impact on the SAP system. When you make any change to a SAP system, it identifies the affected business processes.
To use Change Analyzer, select the specific project and click the change impact analysis option. It will allow you to review and repair the impacted components in the SAP system.
You have to add Transaction codes to the list. SAP TAO will return all the screens associated with a particular transaction. You can choose any screen and click the Inspect option.
To analyze the results of SAP TAO, perform the following steps β
Step 1 β Go to the Tests list and in the tree, click the test for the analysis. It will take you to list of reports and the status of running tests will be displayed.
Step 2 β Analyze a test, click the View Report option. It will open a new window with a detailed report.
There is an option to adjust the columns to be displayed by clicking the mouse icon. You can also see the HTML format of the test report by clicking the HTML Report. To investigate the test results further, you can go to the log folder from the HTML report.
Test building is done in SAP Quality Center using SAP TAO. You need to consolidate test components to create test scenarios. You can execute a single or multiple tests in SAP TAO using Technical Bill of Material TBOM.
Technical Bill of Material (TBOM) is used to contain the objects in an executable form. Change Analyzer makes use of this to tell if an executable object is affected when a change is performed.
In case you want to use the Business Process Change Analyzer, you need to generate a TBOM for each executable object in test scenarios and processes.
Note β If you need to run a single test and you have to update TBOM, click Execute and update TBOM.
You can check the details of update on the TBOM page. You can modify the run list that is created in SAP TAO.
In Business Process Change Analyzer, to execute multiple tests, you can select a folder and add it to the run list. You can also select TBOM creation at the time of execution.
Note β If TBOM already exists at time of execution, it will only update the existing TBOM.
Consolidate is known as a process to combine SAP TAO components with inbuilt components to create test scenarios as single transactional business components. It allows you to collect multiple test components into one test.
It happens when transactional components are gathered. The following screenshot shows the transaction components in QC.
You need to find the test in Quality Center from QC tree and click the Consolidate option.
Select the Transaction code you want to consolidate and click Add to Consolidate list at the bottom to create a test scenario.
As covered in the previous chapters, you need to follow the steps given below β
Step 1 β Find out the transaction you want to consolidate in QC.
Step 1 β Find out the transaction you want to consolidate in QC.
Step 2 β Add the transactions to consolidate list.
Step 2 β Add the transactions to consolidate list.
Step 3 β Press the consolidate button.
Step 3 β Press the consolidate button.
UI scanner is used to create new screen components with existing components. It is a plugin for QTP tool. You should try to use inspect tab over UI scanner. The standard UI scanner works only with GUI front-end client. You can also use third-party UI scanner for capturing the screen components.
If you have to use UI scanner, you need to activate it in the Inspection tab of SAP TAO tool. UI scanner is used to get the information from one screen in one go and transfer these screen objects to QC as a screen component.
UI scanner allows you to create components from SAP GUI screen which are not supported by Process Flow Analyzer or Inspection tab.
When you login to SAP TAO, click the Inspect tab. It will show an option to use UI Scanner.
Login to the SAP system. Enter the transaction code and go to the screen to be scanned and log off.
You can use the default UI Scanner option with QTP tool, by going to UI Scanning tab under Inspect option in SAP TAO. Otherwise, you can use custom QTP test with UI Scanner process by going to UI Scanner and selecting external option.
In Automation testing, the testers write the scripts and use other software tools to test the product. This process involves automation of a manual process. In comparison, manual testing is time-consuming and requires a team of experience test professionals, subject matter experts, and effective communication between the team members.
Automation Testing includes re-running the test-cases multiple times that were performed manually.
In addition to Regression testing, you can say that Automation testing is also used to test the application from load, performance, and stress purpose. It is used to increase the coverage of test, improves accuracy, and saves time and money in comparison to manual testing.
The following tools can be used for Automation testing β
HP Quick Test Professional (QTP)
Selenium
SAP TAO
ECATT
IBM Rational Functional Tester
SilkTest
TestComplete
Testing Anywhere
WinRunner
LaodRunner
Visual Studio Test Professional
WATIR
To perform SAP Automation testing, there is a need to set up a communication between SAP TAO, SAP Solution Manager, and the system to be tested.
To set up this configuration, you need an administration authorization on SAP SOLMAN. This is required to access and modify data table content.
T-Code: SE16
You need to display the table name: AGS_TAO_SETTING and change the value for AGS_TAO_ENABLE_SM_SETUP to ON.
Next, check the compatibility matrix for SAP TAO and Solution Manager. SAP TAO 3.0 contains a Process Flow Analyzer recording wizard which can be used to ease the test recording.
Note β SAP TAO 3.0 is a component for Solution Manager 7.1 and does not support Solution Manager 7.0. Open SAP Solution Manager Configuration work center and run Transaction code β SOLMAN_SETUP.
Open SAP Logon and add the system to be tested under logon.
Go to SAP TAO and login and select SAP SOLMAN in the list. This list of system in SAP TAO is fetched from the configuration file of SAP logon. To add a system in SAP TAO, you need to add a new system in SAP Logon and refresh the list in TAO.
Enter the login credentials and click on logon. SAP TAO will be connected to SAP Solution Manager and TAO configuration wizard will open up.
Business Process Testing (BPT) is a part of QTP automation framework and is used with the Quality Center by HP. BPT is used to create automation test scenarios and run those scenarios without any prior knowledge of automation.
HP BPT removes the complexity of test-case creation and maintenance and combines all the documentation and test automation in one effort.
Business Process Testing aligns the testing process with business goals and reduces the testing lifecycle time considerably.
Business Process Testing tool uses reusable components for creating test-cases and hence reduces the testing maintenance time and increases the efficiency of testing process.
To fasten the process of test automation, it uses the method of keyword driven. You can add common best practices to the testing process. It allows you to use a test solution which is not based on test scripts. Once a manual test is created in BPT, you can easily automate the test-case.
You can also maintain different versions and baseline for different test components, process flows without any chance of overwriting the old cases.
Test cases that are created using Business Process Testing tool can be executed using HP Quality Center QC.
Using BPT, a non-technical SME can easily create, maintain, and run the test-cases and can document them in a Web-based system.
It allows you to design and create the reusable components in test-cases and use them as per the business requirements.
It allows you to design and create the reusable components in test-cases and use them as per the business requirements.
You can also run testing scripts using HP Sprinter.
You can also run testing scripts using HP Sprinter.
With the availability of framework to use reusable components, it decreases the effort for maintaining the test-cases.
With the availability of framework to use reusable components, it decreases the effort for maintaining the test-cases.
HP Quality Center, a test management tool, is now popularly known as Application Life Cycle Management (ALM) tool, as it is no longer just a test management tool but it supports various phases of the software development life cycle.
HP-ALM helps us to manage project milestones, deliverables, resources and keeping track of project health, standards that allow Product owners to gauge the current status of the product. It is important to understand history, architecture, and Quality Center Workflow.
The Requirements module enables users to define, manage and track requirements at all stages of the software lifecycle. The following are the key functionalities in requirements module.
Create requirements, assign to releases/cycles.
Uploading requirements using ALM-MS Excel Add-ins
Enables how to define traceability links between requirements and dependencies that exist between the requirements.
Enables user to view the traceability matrix that lists source requirements and their associated requirements and tests.
The crucial step in testing any application is to develop a clear and a precise test plan. A good test plan enables the team to assess the quality of the application under test at any point in the software development life cycle.
Following functionalities are very important in order to understand the test plan module better.
Creating Tests
This module describes how to create folders of test subjects in the test plan tree and also to add tests.
Uploading Tests
Uploading Teats using ALM-MS Excel Addins
Requirement and Test Coverage
Enable how to define the relationship between the requirements and tests.
Test Configuration
Specific the subset of data or a run-time environment that the test should use.
More details on how HP QC, please go to β http://www.tutorialspoint.com/qc/index.htm
HP Quick Test Professional (QTP) is an automated functional testing tool that helps testers to perform automated regression testing in order to identify any gaps, errors/defects in contrary to the actual/desired results of the application under test.
Object Repository is a collection of objects and properties with which QTP will be able to recognize the objects and act on it. When a user records a test, the objects and its properties are captured by default. Without understanding the objects and its properties, QTP will NOT be able to play back the scripts.
Actions help testers to divide scripts into groups of QTP statements called actions. Actions are similar to functions in VBScript, however there are a few differences. By default, QTP creates a test with 1 action.
The properties of the action can be accessed by right-clicking the Script Editor Window and selecting "Properties".
Action properties contain following information β
Action Name
Location
Reusable Flag
Input Parameters
Output Parameters
There are three types of actions β
Non-reusable action β An action that can be called only in that specific test in which it has been designed and can be called only once.
Non-reusable action β An action that can be called only in that specific test in which it has been designed and can be called only once.
Reusable action β An action that can be called multiple times any test in which it resides and can also be used by any other tests
Reusable action β An action that can be called multiple times any test in which it resides and can also be used by any other tests
External Reusable action β It is a reusable action stored in another test. External actions are read-only in the calling test, but it can be used locally with the editable copy of the Data Table information for the external action.
External Reusable action β It is a reusable action stored in another test. External actions are read-only in the calling test, but it can be used locally with the editable copy of the Data Table information for the external action.
For more information, please use the following link β http://www.tutorialspoint.com/qtp/index.htm
Most of the companies that implement SAP need to perform testing. As the scope of testing is too large, an automated approach can be followed to maintain the changes in SAP system.
Various companies have designed their internal solutions to meet client requirements to perform SAP Testing. Clients can be from banking, finance, manufacturing or healthcare domain.
Given below is an example of performing SAP testing for a manufacturing company.
Client Requirement β The client is a UK based manufacturing company. Project requirement was to perform SAP testing using QTP and to perform automation and functional testing key operations in field of Human Resource, Supply Chain, Logistics, Material Management and Plant maintenance and to use automated test cases for SAP upgrade and to perform integration and Regression testing.
Tasks Performed β It started with understanding of key business processes and SAP system tasks to be automated. Testing team referenced an old pilot project to finalize test strategy, time and effort required to run test execution in HP QTP tool.
As Part of project implementation 100 business processes were successfully automated. Implemented solution resulted in faster execution, more accuracy, increased scope and quality of service.
Tools Used β The following tools were used: SAP R/3, HP QTP, Test scripts written in VB, and Data in XML and XLS format.
Key Benefits Achieved β The following benefits were achieved β
System Validation
Quality and Revenue
Cost and Predictability
Compliance Management
New Implementation and Configuration Changes
SAP Testing is about testing the functionality of various SAP modules to ensure that they are performing as per the configuration. SAP system undergoes various changes like patch management and fixes, new module implementations and various other configuration changes. All these raise a need for Regression testing to be performed in SAP environments. SAP testing automation tools like SAP TAO can be used for this purpose and is recommended by SAP for testing.
The benefits of performing SAP Testing are manifold. They are as follows β
System Validation β SAP Testing involves complete end to end testing and validation of all SAP modules in SAP ERP environment.
System Validation β SAP Testing involves complete end to end testing and validation of all SAP modules in SAP ERP environment.
Quality and Revenue β SAP Testing is an output based testing and not like conventional testing methods which are input based and it ensures the quality of SAP system and also focuses on revenue and cost of the organization.
Quality and Revenue β SAP Testing is an output based testing and not like conventional testing methods which are input based and it ensures the quality of SAP system and also focuses on revenue and cost of the organization.
Cost and Predictability β SAP Testing involves reducing the SAP development costs and improve predictability.
Cost and Predictability β SAP Testing involves reducing the SAP development costs and improve predictability.
Compliance Requirement β SAP Testing ensures that SAP implementation is meeting the new compliance requirements in a specific organization and all modules are working as per expected configuration.
Compliance Requirement β SAP Testing ensures that SAP implementation is meeting the new compliance requirements in a specific organization and all modules are working as per expected configuration.
New Implementation and Configuration Changes β There are different type of changes implemented in SAP system, like patches and fixes, new implementation, configurational changes. SAP testing ensures that all the modules are performing as per requirement in this dynamic system environment.
New Implementation and Configuration Changes β There are different type of changes implemented in SAP system, like patches and fixes, new implementation, configurational changes. SAP testing ensures that all the modules are performing as per requirement in this dynamic system environment.
Integration β SAP testing is performed to test various reports, data flows and work flows, GUI forms, etc. It is used to check system integration between different modules. For example, if an order posting is done that requires an action in Sales and Distribution, MM and FICO so SAP testing check the integration between these systems.
Integration β SAP testing is performed to test various reports, data flows and work flows, GUI forms, etc. It is used to check system integration between different modules. For example, if an order posting is done that requires an action in Sales and Distribution, MM and FICO so SAP testing check the integration between these systems.
Performance β It is also used to ensure if system will be able to meet the Service Level agreements, time taken by system to perform specific actions, performance of the system, etc.
Performance β It is also used to ensure if system will be able to meet the Service Level agreements, time taken by system to perform specific actions, performance of the system, etc.
SAP testing can be performed on the following modules β
SAP Material Management
SAP Financial Accounting and Controlling
SAP Sales and Distribution
SAP Human Resource
SAP Supply Chain Management
SAP Plant Management
Some of the automating testing tools are β HP Quick Test Professional (QTP), Selenium, SAP TAO, ECATT, IBM Rational Functional Tester, WinRunner, and LoadRunner.
The different stages that come under Software Testing Life Cycle are β Requirements phase, Test Planning, Test Analysis, Test Design Phase, Test Implementation, Test Execution Phase, and Test Closure Phase.
Unit testing is used to test the functionality of various components in a SAP system. It is performed by domain and configuration experts who know the functionality of each unit in a system.
Example β To create a sales order and to save it. To perform Unit testing for this task, tester should know that the sales order can be saved using the SAP organization elements like customer master data, partner functions, material master data, company code, credit control area, sales organization, etc.
Unit testing is used to test functionality of pieces in SAP system. It is performed by domain and configuration expert who knows functionality of each unit in a system.
Example β To create a sales order and to save it. To perform Unit testing for this task, tester should know that the sales order can be saved using the SAP organization elements like customer master data, partner functions, material master data, company code, credit control area, sales organization, etc.
System Testing involves integration of elements of SAP system to ensure that related SAP functionality are linked together in the development environment.
Example β If you say a Cash flow for a quotation in an organization would show that a quote can be used to create a sales order, a delivery can be created and processed from the order, the delivery can be billed, the billing released to accounting, and a customer payment applied against the accounting invoice. Each unit is tested like this and then the test results are combined.
Scenario-based testing, as the name suggests, is performed as per specific business cases.
Example β Suppose there are a few tasks that are specific to a customer segment or a given product line or a set of services. For these specific line of target, you have different scenarios you need to test.
This testing is also performed in the development environment, an argument can be made to say this is a test case you would cover in system testing.
In this testing, testing data is coming from a real data extraction source, conversion is done and load exercise and data is known to a business end user.
Example β Integration testing is used to present that the business process as designed and configured in SAP, runs using real world data. In addition the testing shows that interface triggers, reports, workflows are working.
Interface testing ensures that a business process on a SAP system runs automatically. Ideally interface testing involves larger testing activities as a project progresses. Interface testing shows that triggering works, the data selection is accurate and complete, data transfer is successful, and the receiver is able to consume the sent data.
SAP UAT is used to ensure that end-users are able to perform assigned job functions with the new system. The important aspect of this testing is to understand the business requirement and to ensure that the expected features, functions, and capabilities are available.
Performance testing identifies bottlenecks and coding inefficiencies in a SAP system. It is carried out to check β
Whether the system response time is acceptable as per the business requirement
Whether periodic processes are running within permissible time
Whether the expected concurrent user load can be supported
Security and Authorizations Testing is used to ensure that the users are only able to execute transactions and access appropriate data that is relevant to their project.
As with the implementation of Security standards, this is really important to test if security and authorization is placed in a system. Test IDs for job roles are created and used to both confirm what a user can do and what a user cannot do.
This testing is usually performed once in a project lifecycle. The term βcutoverβ means a full scale execution of the all tasks involved to extract data from legacy systems and then to perform any kind of data conversion, load the results into the SAP system and fully validate the results, including a user sign-off.
SAP Regression Testing is used to find new functionalities and to test the old functionalities in a system when it is upgraded or a new system is set up. The key role of regression testing is to test the existing functionality and newly updated configuration and code base.
When you upgrade your SAP system or apply a patch, it shouldnβt affect the functionality that is expected to be performed by users and to check new features that are supposed to be introduced in new release.
SAP testing navigation ensures that you cover each module of your SAP system and at least one test to be performed for each functionality.
It also reduces the manual testing effort and covers most of the testing paths in a SAP system. OPA tests can be performed to check SAP Testing - Navigation.
Screen flow logic in SAP Testing is like an ABAP code and it is used to contain the processing blocks. It contains procedural part of screen and is created in screen painter and this screen painter is similar to an ABAP editor.
Financial Modules β Finance Accounting and Controlling (FICO), Treasure (TR), and Enterprise Control (EC).
Logistics Modules β Material Management (MM), Plant Maintenance (PM), Sales and Distribution (SD), Quality Management (QM), etc.
Human Resource Management β Accounting Payroll, Time Management, Training and Event Management.
SAP Test-cases are required to perform a check on the installation and configuration of SAP system, any new implementation, Multilanguage and device testing, intranet testing, real-time testing, etc.
Since an ERP system is a common centralized system and is used by multiple users simultaneously in real time, it creates a need to write the test cases with lot of effort and dedication.
ERP systems also involve various FI transactions, so each test case should cover the scope of all the configuration and implementation part. Test data should be passed carefully and each test should have a column with name output data.
SAP Test Acceleration and Optimization TAO 2.0 is a tool that is used to create automatic test-cases during Regression testing of a system. It helps SAP customers to create different test components from the screens of a transaction and parameterizes them.
These test components are created normally for one transaction code and later can be combined to test scenarios. It can be easily integrated to the Business Process Change Analyzer in SAP Solution Manager.
RAM: 4 GB
Free disk space: 500 MB
LAN connection to SAP Quality Center QC server and SOLMAN
Administration Rights
SAPGUI with the latest patch level
Microsoft Excel 97 or higher.
Microsoft Internet Explorer for CRM UI support
Process Flow Analyzer is used to automatically find out the user interfaces used in transaction codes executed in a SAP system. It automatically creates the test components and upload them to Quality Center. It is also used to identify the sequence of test components as per user actions and creation of spreadsheet values.
Consolidate is known as a process to combine SAP TAO components with inbuilt components to create test scenarios as single transactional business components. It allows you to collect multiple test components into one test.
Go to SAP TAO and login and select SAP SOLMAN in the list. This list of system is SAP TAO is fetched from configuration file of SAP logon. So to add a system in SAP TAO, you need to add a new system in SAP Logon and refresh the list in TAO.
Enter the login credentials and click on logon.
SAP TAO will be connected to SAP Solution Manager and the TAO configuration wizard will open up.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2587,
"s": 2246,
"text": "Many organizations implement SAP ERP (Enterprise Resource Planning) to manage their business operations and adapt according to new market challenges. SAP R/3 is an integrated ERP software that allows organizations to manage their business efficiently. Organizations can reduce the cost to run their operations by using SAP R/3 ERP packages."
},
{
"code": null,
"e": 2855,
"s": 2587,
"text": "SAP R/3 also allows customers to interact with different databases to run different applications with the help of a user-friendly GUI. The SAP R/3 system is divided into different modules to cover the functionality of different business operations in an organization."
},
{
"code": null,
"e": 2893,
"s": 2855,
"text": "The most common SAP R/3 modules are β"
},
{
"code": null,
"e": 2918,
"s": 2893,
"text": "SAP Material Management."
},
{
"code": null,
"e": 2960,
"s": 2918,
"text": "SAP Financial Accounting and Controlling."
},
{
"code": null,
"e": 2988,
"s": 2960,
"text": "SAP Sales and Distribution."
},
{
"code": null,
"e": 3008,
"s": 2988,
"text": "SAP Human Resource."
},
{
"code": null,
"e": 3037,
"s": 3008,
"text": "SAP Supply Chain Management."
},
{
"code": null,
"e": 3059,
"s": 3037,
"text": "SAP Plant Management."
},
{
"code": null,
"e": 3181,
"s": 3059,
"text": "SAP Testing is about testing the functionality of these modules and to ensure that they perform as per the configuration."
},
{
"code": null,
"e": 3536,
"s": 3181,
"text": "A SAP system undergoes various changes like patch management and fixes, new module implementations, and various other configuration changes. All these modifications raise a need for Regression testing that is to be performed in SAP environments. SAP testing automation tools like SAP Test Acceleration and Optimization tools can be used for this purpose."
},
{
"code": null,
"e": 3765,
"s": 3536,
"text": "SAP TAO is an automation tool to generate test cases for end-to-end scenarios for SAP applications. Apart from this, there are various other Automation testing tools for SAP testing like HP QTP, and ECATT, etc. that can be used."
},
{
"code": null,
"e": 3895,
"s": 3765,
"text": "Here is a list of key reasons why SAP testing is performed and why it is an important function in the growth of an organization β"
},
{
"code": null,
"e": 4022,
"s": 3895,
"text": "System Validation β SAP Testing involves complete end-to-end testing and validation of all SAP modules in SAP ERP environment."
},
{
"code": null,
"e": 4149,
"s": 4022,
"text": "System Validation β SAP Testing involves complete end-to-end testing and validation of all SAP modules in SAP ERP environment."
},
{
"code": null,
"e": 4370,
"s": 4149,
"text": "Quality and Revenue β SAP Testing is an output-based testing and not like conventional testing methods which are input-based. It ensures the quality of SAP system and also focuses on revenue and cost of the organization."
},
{
"code": null,
"e": 4591,
"s": 4370,
"text": "Quality and Revenue β SAP Testing is an output-based testing and not like conventional testing methods which are input-based. It ensures the quality of SAP system and also focuses on revenue and cost of the organization."
},
{
"code": null,
"e": 4701,
"s": 4591,
"text": "Cost and Predictability β SAP Testing involves reducing the SAP development costs and improve predictability."
},
{
"code": null,
"e": 4811,
"s": 4701,
"text": "Cost and Predictability β SAP Testing involves reducing the SAP development costs and improve predictability."
},
{
"code": null,
"e": 5021,
"s": 4811,
"text": "Compliance Requirement β SAP Testing ensures that the SAP implementation is meeting the new compliance requirements in a specific organization and all the modules are working as per the expected configuration."
},
{
"code": null,
"e": 5231,
"s": 5021,
"text": "Compliance Requirement β SAP Testing ensures that the SAP implementation is meeting the new compliance requirements in a specific organization and all the modules are working as per the expected configuration."
},
{
"code": null,
"e": 5535,
"s": 5231,
"text": "New Implementation and Configuration Changes β There are different types of changes implemented in a SAP system, like patches and fixes, new implementation, configurational changes. Therefore, SAP testing ensures that all the modules are performing as per requirement in this dynamic system environment."
},
{
"code": null,
"e": 5839,
"s": 5535,
"text": "New Implementation and Configuration Changes β There are different types of changes implemented in a SAP system, like patches and fixes, new implementation, configurational changes. Therefore, SAP testing ensures that all the modules are performing as per requirement in this dynamic system environment."
},
{
"code": null,
"e": 6180,
"s": 5839,
"text": "Integration β SAP testing is performed to test various reports, data flows and work flows, GUI forms, etc. It is used to check system integration between different modules. For example, if an order posting is done that requires an action in Sales and Distribution, MM and FICO, then SAP testing checks the integration between these systems."
},
{
"code": null,
"e": 6521,
"s": 6180,
"text": "Integration β SAP testing is performed to test various reports, data flows and work flows, GUI forms, etc. It is used to check system integration between different modules. For example, if an order posting is done that requires an action in Sales and Distribution, MM and FICO, then SAP testing checks the integration between these systems."
},
{
"code": null,
"e": 6708,
"s": 6521,
"text": "Performance β It is also used to ensure if the system will be able to meet the Service Level agreements, time taken by system to perform specific actions, performance of the system, etc."
},
{
"code": null,
"e": 6895,
"s": 6708,
"text": "Performance β It is also used to ensure if the system will be able to meet the Service Level agreements, time taken by system to perform specific actions, performance of the system, etc."
},
{
"code": null,
"e": 7016,
"s": 6895,
"text": "There are different testing methods that can be used to test the functionality of a software, system, or an application."
},
{
"code": null,
"e": 7057,
"s": 7016,
"text": "The most common testing techniques are β"
},
{
"code": null,
"e": 7161,
"s": 7057,
"text": "Unit Testing β It is a type of white-box testing that involves testing a single unit or group of units."
},
{
"code": null,
"e": 7265,
"s": 7161,
"text": "Unit Testing β It is a type of white-box testing that involves testing a single unit or group of units."
},
{
"code": null,
"e": 7388,
"s": 7265,
"text": "Integration Testing β In this testing, multiple systems are combined together to test the output of the integrated system."
},
{
"code": null,
"e": 7511,
"s": 7388,
"text": "Integration Testing β In this testing, multiple systems are combined together to test the output of the integrated system."
},
{
"code": null,
"e": 7602,
"s": 7511,
"text": "Functional Testing β It checks the functionality of each module as per the desired result."
},
{
"code": null,
"e": 7693,
"s": 7602,
"text": "Functional Testing β It checks the functionality of each module as per the desired result."
},
{
"code": null,
"e": 7867,
"s": 7693,
"text": "Usability Testing β It checks the ease of use of an application or a system. It checks how easy it would be for a new user to use an application or to understand the system."
},
{
"code": null,
"e": 8041,
"s": 7867,
"text": "Usability Testing β It checks the ease of use of an application or a system. It checks how easy it would be for a new user to use an application or to understand the system."
},
{
"code": null,
"e": 8190,
"s": 8041,
"text": "Acceptance Testing β Acceptance testing is performed to test if a system meets the user requirement and whether to accept the application or system."
},
{
"code": null,
"e": 8339,
"s": 8190,
"text": "Acceptance Testing β Acceptance testing is performed to test if a system meets the user requirement and whether to accept the application or system."
},
{
"code": null,
"e": 8422,
"s": 8339,
"text": "System Testing β Entire system is tested as per the requirement and specification."
},
{
"code": null,
"e": 8505,
"s": 8422,
"text": "System Testing β Entire system is tested as per the requirement and specification."
},
{
"code": null,
"e": 8618,
"s": 8505,
"text": "Stress Testing β In this testing, the system is put into stress beyond its specification to check when it fails."
},
{
"code": null,
"e": 8731,
"s": 8618,
"text": "Stress Testing β In this testing, the system is put into stress beyond its specification to check when it fails."
},
{
"code": null,
"e": 8837,
"s": 8731,
"text": "Performance Testing β This testing is performed to check if the system meets the performance requirement."
},
{
"code": null,
"e": 8943,
"s": 8837,
"text": "Performance Testing β This testing is performed to check if the system meets the performance requirement."
},
{
"code": null,
"e": 9038,
"s": 8943,
"text": "Regression Testing β It includes testing the full application or system for the modifications."
},
{
"code": null,
"e": 9133,
"s": 9038,
"text": "Regression Testing β It includes testing the full application or system for the modifications."
},
{
"code": null,
"e": 9330,
"s": 9133,
"text": "Beta Testing β The aim of beta testing is to cover unexpected errors. It falls under the class of black-box testing. It is performed by releasing the pre-version of the final product, called Beta."
},
{
"code": null,
"e": 9527,
"s": 9330,
"text": "Beta Testing β The aim of beta testing is to cover unexpected errors. It falls under the class of black-box testing. It is performed by releasing the pre-version of the final product, called Beta."
},
{
"code": null,
"e": 9643,
"s": 9527,
"text": "Database Testing β Database testing is used to test the data in the database. It is performed using SQL statements."
},
{
"code": null,
"e": 9759,
"s": 9643,
"text": "Database Testing β Database testing is used to test the data in the database. It is performed using SQL statements."
},
{
"code": null,
"e": 9905,
"s": 9759,
"text": "ETL Testing β ETL testing is performed to ensure if data is correctly extracted, transformed, and loaded from a source system to a target system."
},
{
"code": null,
"e": 10051,
"s": 9905,
"text": "ETL Testing β ETL testing is performed to ensure if data is correctly extracted, transformed, and loaded from a source system to a target system."
},
{
"code": null,
"e": 10296,
"s": 10051,
"text": "Manual testing means you are testing a software manually without using any automated tools or any script. In this type of testing, the tester takes over the role of an end-user and tests the software to identify bugs or any unexpected behavior."
},
{
"code": null,
"e": 10435,
"s": 10296,
"text": "There are different stages of a manual testing. They are β unit testing, integration testing, system testing, and user acceptance testing."
},
{
"code": null,
"e": 10682,
"s": 10435,
"text": "Various test plans, test cases, or test scenarios are used by a manual tester to ensure the completeness of testing. Manual testing can also be called exploratory testing because the testers explore the software to identify errors in it manually."
},
{
"code": null,
"e": 10937,
"s": 10682,
"text": "In Automation testing, the tester writes the scripts and uses software tools to test the product. This process involves the automation of a manual process. Automation testing includes re-running the test-cases multiple times that were performed manually."
},
{
"code": null,
"e": 11181,
"s": 10937,
"text": "Automation testing is also used to test the application from load, performance, and stress purpose. It is used to increase the coverage of test. Automation testing improves the accuracy and saves time and money in comparison to manual testing."
},
{
"code": null,
"e": 11239,
"s": 11181,
"text": "The following tools can be used for Automation testing β "
},
{
"code": null,
"e": 11272,
"s": 11239,
"text": "HP Quick Test Professional (QTP)"
},
{
"code": null,
"e": 11281,
"s": 11272,
"text": "Selenium"
},
{
"code": null,
"e": 11289,
"s": 11281,
"text": "SAP TAO"
},
{
"code": null,
"e": 11295,
"s": 11289,
"text": "ECATT"
},
{
"code": null,
"e": 11326,
"s": 11295,
"text": "IBM Rational Functional Tester"
},
{
"code": null,
"e": 11335,
"s": 11326,
"text": "SilkTest"
},
{
"code": null,
"e": 11348,
"s": 11335,
"text": "TestComplete"
},
{
"code": null,
"e": 11365,
"s": 11348,
"text": "Testing Anywhere"
},
{
"code": null,
"e": 11375,
"s": 11365,
"text": "WinRunner"
},
{
"code": null,
"e": 11386,
"s": 11375,
"text": "LaodRunner"
},
{
"code": null,
"e": 11418,
"s": 11386,
"text": "Visual Studio Test Professional"
},
{
"code": null,
"e": 11424,
"s": 11418,
"text": "WATIR"
},
{
"code": null,
"e": 11702,
"s": 11424,
"text": "Software Development Life Cycle determines the series of steps to be performed to develop an application or the efficiency of a software. In this chapter, we will discuss the phases defined in SDLC. Each phase has its own process and deliverables that goes into the next phase."
},
{
"code": null,
"e": 12185,
"s": 11702,
"text": "The first stage of SDLC is requirement gathering. After the requirements are gathered, the team comes up with a rough plan of software process. At this step, the team analyzes if a software can be made to fulfill all the requirements of the user. It is found out if the project is financially, practically, and technologically feasible for the organization to take up. There are many algorithms available, which help the developers to conclude the feasibility of a software project."
},
{
"code": null,
"e": 12660,
"s": 12185,
"text": "At this step, the developers decide a roadmap of their plan and try to bring up the best software model suitable for the project. System analysis includes understanding of software product limitations, learning system-related problems or changes to be done in the existing systems, identifying and addressing the impact of the project on the organization and personnel etc. The project team analyzes the scope of the project and plans the schedule and resources accordingly."
},
{
"code": null,
"e": 13115,
"s": 12660,
"text": "The next step is to bring the whole knowledge of requirements and analysis on to the desk and design the software product. The inputs from the users and the information gathered in the requirement gathering phase are the inputs of this step. The output of this step comes in the form of two designs; logical design and physical design. Engineers produce meta-data and data dictionaries, logical diagrams, data-flow diagrams and in some cases pseudocodes."
},
{
"code": null,
"e": 13337,
"s": 13115,
"text": "This step is also known as programming phase. The implementation of software design starts in terms of writing the program code in a suitable programming language and developing error-free executable programs efficiently."
},
{
"code": null,
"e": 13830,
"s": 13337,
"text": "An estimate says that 50% of the whole software development process should be tested. Errors may ruin the software from critical level to its own removal. Software testing is done while coding by the developers and thorough testing is conducted by testing experts at various levels of code such as module testing, program testing, product testing, in-house testing and testing the product at userβs end. Early discovery of errors and their remedy is the key to developing a reliable software."
},
{
"code": null,
"e": 14007,
"s": 13830,
"text": "Software may need to be integrated with the libraries, databases, and other program(s). This stage of SDLC deals with the integration of the software with outer world entities."
},
{
"code": null,
"e": 14282,
"s": 14007,
"text": "Implementation or deployment means installing the software on user machines. At times, the software needs post-installation configurations at the userβs end. Software is tested for portability and adaptability and integration related issues are solved during implementation."
},
{
"code": null,
"e": 14468,
"s": 14282,
"text": "Software Testing Life Cycle (STLC) consists of all the steps that are performed in a specific way to ensure that quality goals are met and each step has specific goals and deliverables."
},
{
"code": null,
"e": 14609,
"s": 14468,
"text": "STLC is used to improve the quality of a software product and to make it capable to meet the business requirements to achieve certain goals."
},
{
"code": null,
"e": 14692,
"s": 14609,
"text": "The different stages that come under Software Testing Life Cycle are as follows β "
},
{
"code": null,
"e": 14711,
"s": 14692,
"text": "Requirements phase"
},
{
"code": null,
"e": 14725,
"s": 14711,
"text": "Test Planning"
},
{
"code": null,
"e": 14739,
"s": 14725,
"text": "Test Analysis"
},
{
"code": null,
"e": 14757,
"s": 14739,
"text": "Test Design Phase"
},
{
"code": null,
"e": 14777,
"s": 14757,
"text": "Test Implementation"
},
{
"code": null,
"e": 14798,
"s": 14777,
"text": "Test Execution Phase"
},
{
"code": null,
"e": 14817,
"s": 14798,
"text": "Test Closure Phase"
},
{
"code": null,
"e": 15133,
"s": 14817,
"text": "This is the first phase of Software Testing Life Cycle. During this phase, the testerβs job is to analyze the requirements. There are various methods for Requirement Analysis like conducting brainstorming sessions with business people, team members, and try to find out whether the requirements are testable or not."
},
{
"code": null,
"e": 15288,
"s": 15133,
"text": "This phase determines the scope of the testing. If a testing team finds any features that canβt be tested, then that should be communicated to the client."
},
{
"code": null,
"e": 15403,
"s": 15288,
"text": "In this phase, the tester identifies the activities and resources which would help to meet the testing objectives."
},
{
"code": null,
"e": 15592,
"s": 15403,
"text": "Various metrics are defined and there are methods available to determine and track those metrics. Test planning also includes identifying key performance indicators for testing evaluation."
},
{
"code": null,
"e": 15774,
"s": 15592,
"text": "This phase determines the guidelines that has to be tested. It includes identifying the test conditions using the requirements document, any risks involved, and other test criteria."
},
{
"code": null,
"e": 15833,
"s": 15774,
"text": "Various factors are used to find out the test conditions β"
},
{
"code": null,
"e": 15852,
"s": 15833,
"text": "Product Complexity"
},
{
"code": null,
"e": 15869,
"s": 15852,
"text": "Depth of Testing"
},
{
"code": null,
"e": 15883,
"s": 15869,
"text": "Risk Involved"
},
{
"code": null,
"e": 15899,
"s": 15883,
"text": "Skills Required"
},
{
"code": null,
"e": 15933,
"s": 15899,
"text": "Knowledge of testing team members"
},
{
"code": null,
"e": 15949,
"s": 15933,
"text": "Test management"
},
{
"code": null,
"e": 15982,
"s": 15949,
"text": "Availability of the stakeholders"
},
{
"code": null,
"e": 16035,
"s": 15982,
"text": "Test conditions should be written in a detailed way."
},
{
"code": null,
"e": 16302,
"s": 16035,
"text": "Let us take an example. For a website selling products online, a test condition is that a customer should be able to make an online payment. You can add detailed conditions like, payment should be feasible using Credit card, NEFT transfer, debit card or net banking."
},
{
"code": null,
"e": 16612,
"s": 16302,
"text": "The advantage of writing the detailed test condition is that it increases the scope of testing because test-cases are normally written on the basis of the test condition. It allows to write more detailed test cases. It also helps in determining the condition of when to stop the testing of a software product."
},
{
"code": null,
"e": 16663,
"s": 16612,
"text": "This phase determines how the tests are performed."
},
{
"code": null,
"e": 16749,
"s": 16663,
"text": "Break down the test conditions into multiple sub-conditions to increase its coverage."
},
{
"code": null,
"e": 16835,
"s": 16749,
"text": "Break down the test conditions into multiple sub-conditions to increase its coverage."
},
{
"code": null,
"e": 16854,
"s": 16835,
"text": "Get the test data."
},
{
"code": null,
"e": 16873,
"s": 16854,
"text": "Get the test data."
},
{
"code": null,
"e": 16902,
"s": 16873,
"text": "Set up the test environment."
},
{
"code": null,
"e": 16931,
"s": 16902,
"text": "Set up the test environment."
},
{
"code": null,
"e": 16973,
"s": 16931,
"text": "Get the requirement traceability metrics."
},
{
"code": null,
"e": 17015,
"s": 16973,
"text": "Get the requirement traceability metrics."
},
{
"code": null,
"e": 17049,
"s": 17015,
"text": "Create the test coverage metrics."
},
{
"code": null,
"e": 17083,
"s": 17049,
"text": "Create the test coverage metrics."
},
{
"code": null,
"e": 17187,
"s": 17083,
"text": "This phase includes the creation of detailed test-cases as per the test conditions and metrics defined."
},
{
"code": null,
"e": 17213,
"s": 17187,
"text": "Prioritize the test case."
},
{
"code": null,
"e": 17250,
"s": 17213,
"text": "Test-case to be used for Regression."
},
{
"code": null,
"e": 17292,
"s": 17250,
"text": "Ensure the correctness of the test-cases."
},
{
"code": null,
"e": 17355,
"s": 17292,
"text": "Sign off of the test-cases before the actual execution starts."
},
{
"code": null,
"e": 17438,
"s": 17355,
"text": "This phase of Software Testing Life Cycle involves actual execution of test-cases."
},
{
"code": null,
"e": 17462,
"s": 17438,
"text": "Execute the test-cases."
},
{
"code": null,
"e": 17479,
"s": 17462,
"text": "Log the defects."
},
{
"code": null,
"e": 17525,
"s": 17479,
"text": "Check traceability metrics to track progress."
},
{
"code": null,
"e": 17586,
"s": 17525,
"text": "This phase includes checking for the completion of the test."
},
{
"code": null,
"e": 17647,
"s": 17586,
"text": "Check if all the test-cases are executed and opened defects."
},
{
"code": null,
"e": 17677,
"s": 17647,
"text": "Note down the lessons learnt."
},
{
"code": null,
"e": 17702,
"s": 17677,
"text": "Close the Testing phase."
},
{
"code": null,
"e": 17798,
"s": 17702,
"text": "There are different types of testing methods available that can be used to perform SAP testing."
},
{
"code": null,
"e": 17994,
"s": 17798,
"text": "Unit testing is used to test the functionality of a SAP system and its various components. It is performed by domain and configuration experts who know the functionality of each unit in a system."
},
{
"code": null,
"e": 18311,
"s": 17994,
"text": "Suppose the task is to create a sales order and save it. To perform unit testing for this task, the tester should know that the sales order can be saved using the SAP organization elements like customer master data, partner functions, material master data, company code, credit control area, sales organization, etc."
},
{
"code": null,
"e": 18476,
"s": 18311,
"text": "In ABAP development, Unit testing can be performed to check if a report can be created from developer-generated data. It requires assistance from the domain expert."
},
{
"code": null,
"e": 18637,
"s": 18476,
"text": "System Testing involves the integration of elements of a SAP system to ensure that related SAP functionality are linked together in the development environment."
},
{
"code": null,
"e": 18939,
"s": 18637,
"text": "If you say a cash flow for a quotation in an organization would show that a quote can be used to create a sales order, a delivery can be created and processed from the order, the delivery can be billed, the billing released to accounting, and a customer payment applied against the accounting invoice."
},
{
"code": null,
"e": 19030,
"s": 18939,
"text": "Each unit is tested like this and then the test results are combined using system testing."
},
{
"code": null,
"e": 19115,
"s": 19030,
"text": "Scenario testing, as the name suggests, is performed as per specific business cases."
},
{
"code": null,
"e": 19381,
"s": 19115,
"text": "Suppose there are a few tasks that are specific to a customer segment or a given product line or a set of services. For these specific line of target, you have different scenarios that you need to test. This testing is also performed in the development environment."
},
{
"code": null,
"e": 19490,
"s": 19381,
"text": "In this testing, testing data comes from a real data extraction source. Data is known to business end-users."
},
{
"code": null,
"e": 19710,
"s": 19490,
"text": "Integration testing is used to present that the business process, as designed and configured in SAP, runs using real-world data. In addition the testing shows that the interface triggers, reports, workflows are working."
},
{
"code": null,
"e": 20108,
"s": 19710,
"text": "Interface testing ensures that a business process on a SAP system runs automatically, the events are triggered, and the results are transferred to the receiver system. Interface testing involves execution on the sending system followed by automatic generation of the interface output, and then the receiving system consuming that file and proving that a business process continues on the receiver."
},
{
"code": null,
"e": 20367,
"s": 20108,
"text": "Ideally, interface testing involves larger testing activities as a project progresses. Interface testing shows that triggering works, the data selection is accurate and complete, data transfer is successful, and the receiver is able to consume the sent data."
},
{
"code": null,
"e": 20643,
"s": 20367,
"text": "SAP UAT is used to ensure that the end-users are able to perform the assigned job functions with the new system. The important aspect of this testing is to understand the business requirement and to ensure that the expected features, functions and capabilities are available."
},
{
"code": null,
"e": 20695,
"s": 20643,
"text": "Performance testing checks the following aspects β "
},
{
"code": null,
"e": 20774,
"s": 20695,
"text": "Whether the system response time is acceptable as per the business requirement"
},
{
"code": null,
"e": 20853,
"s": 20774,
"text": "Whether the system response time is acceptable as per the business requirement"
},
{
"code": null,
"e": 20917,
"s": 20853,
"text": "Whether periodic processes are running within permissible time,"
},
{
"code": null,
"e": 20981,
"s": 20917,
"text": "Whether periodic processes are running within permissible time,"
},
{
"code": null,
"e": 21040,
"s": 20981,
"text": "Whether the expected concurrent user load can be supported"
},
{
"code": null,
"e": 21099,
"s": 21040,
"text": "Whether the expected concurrent user load can be supported"
},
{
"code": null,
"e": 21303,
"s": 21099,
"text": "Performance testing identifies bottlenecks and coding inefficiencies in the SAP system. It is not likely that system performance tuning is perfectly set up and the program is running with optimized code."
},
{
"code": null,
"e": 21549,
"s": 21303,
"text": "In Load Testing, the tester applies maximum load on a system, either online users or periodic batch processing, and identifies whether the system is capable enough to handle the load. If not, it finds out the steps needed to improve performance."
},
{
"code": null,
"e": 21715,
"s": 21549,
"text": "Security and Authorizations Testing is used to ensure that users are only able to execute transactions and access appropriate data that is relevant to their project."
},
{
"code": null,
"e": 21957,
"s": 21715,
"text": "As with the implementation of Security standards, this is really important to test if security and authorization is placed in a system. Test IDs for job roles are created and used to both confirm what a user can do and what a user cannot do."
},
{
"code": null,
"e": 22264,
"s": 21957,
"text": "Cutover testing is usually performed once in a project lifecycle. Here a full-scale execution is done of all the tasks involved to extract data from legacy systems. Then, to perform any kind of data conversion, load the results into the SAP system and fully validate the results, including a user sign-off."
},
{
"code": null,
"e": 22534,
"s": 22264,
"text": "Regression testing is used to find new functionalities and to test previous functionalities in a system when it is upgraded or a new system is set up. The key role of regression testing is to test the existing functionality and newly updated configuration and codebase."
},
{
"code": null,
"e": 22774,
"s": 22534,
"text": "When you upgrade your SAP system or apply a patch, it shouldnβt affect the functionality that is expected to be performed by the users. In addition, it should not affect the new features that are supposed to be introduced in a new release."
},
{
"code": null,
"e": 22833,
"s": 22774,
"text": "SAP testing process is usually divided into three phases β"
},
{
"code": null,
"e": 22847,
"s": 22833,
"text": "Test Planning"
},
{
"code": null,
"e": 22865,
"s": 22847,
"text": "Test System setup"
},
{
"code": null,
"e": 22895,
"s": 22865,
"text": "Test Execution and evaluation"
},
{
"code": null,
"e": 22979,
"s": 22895,
"text": "Test planning includes the steps that are involved in the initial phase of testing."
},
{
"code": null,
"e": 23107,
"s": 22979,
"text": "Gathering the requirement. What needs to be tested? Functional requirements to be collected for system and application testing."
},
{
"code": null,
"e": 23235,
"s": 23107,
"text": "Gathering the requirement. What needs to be tested? Functional requirements to be collected for system and application testing."
},
{
"code": null,
"e": 23366,
"s": 23235,
"text": "Test-case development for manual and automation testing. In automation testing, various tools can be used for creating test-cases."
},
{
"code": null,
"e": 23497,
"s": 23366,
"text": "Test-case development for manual and automation testing. In automation testing, various tools can be used for creating test-cases."
},
{
"code": null,
"e": 23523,
"s": 23497,
"text": "Reviewing the test-cases."
},
{
"code": null,
"e": 23549,
"s": 23523,
"text": "Reviewing the test-cases."
},
{
"code": null,
"e": 23691,
"s": 23549,
"text": "Test system setup involves setting up the test environment to run the test-cases. Here, the tester needs to define key metrics for reporting."
},
{
"code": null,
"e": 23823,
"s": 23691,
"text": "Test execution and evaluation involves executing the test-cases and noting down the output. It includes the following activities β "
},
{
"code": null,
"e": 23854,
"s": 23823,
"text": "Defect handling and reporting."
},
{
"code": null,
"e": 23894,
"s": 23854,
"text": "Assessment of Test plans as per result."
},
{
"code": null,
"e": 23965,
"s": 23894,
"text": "Documentation of all defects and compare the results with key metrics."
},
{
"code": null,
"e": 24193,
"s": 23965,
"text": "In SAP system testing, you need to identify critical business processes that will be affected by implementing changes in a SAP system. It mostly comes under Regression testing, where you apply a patch or implement a new system."
},
{
"code": null,
"e": 24357,
"s": 24193,
"text": "The first step before applying these changes is to perform change impact analysis. This covers critical processes that will be affected by implementing the change."
},
{
"code": null,
"e": 24426,
"s": 24357,
"text": "Let us take an example. Suppose the planned changes are as follows β"
},
{
"code": null,
"e": 24445,
"s": 24426,
"text": "SAP support pack 7"
},
{
"code": null,
"e": 24457,
"s": 24445,
"text": "Custom code"
},
{
"code": null,
"e": 24477,
"s": 24457,
"text": "SAP enhance package"
},
{
"code": null,
"e": 24489,
"s": 24477,
"text": "Sales Order"
},
{
"code": null,
"e": 24507,
"s": 24489,
"text": "Delivery of goods"
},
{
"code": null,
"e": 24522,
"s": 24507,
"text": "Payment method"
},
{
"code": null,
"e": 24597,
"s": 24522,
"text": "Here, the following activities are to be carried out in Impact Analysis β "
},
{
"code": null,
"e": 24682,
"s": 24597,
"text": "Identification of the critical business processes impacted by change implementation."
},
{
"code": null,
"e": 24767,
"s": 24682,
"text": "Identification of the critical business processes impacted by change implementation."
},
{
"code": null,
"e": 24850,
"s": 24767,
"text": "Business justification to be provided as to why this change has to be implemented."
},
{
"code": null,
"e": 24933,
"s": 24850,
"text": "Business justification to be provided as to why this change has to be implemented."
},
{
"code": null,
"e": 25031,
"s": 24933,
"text": "Creating the test plan to monitor critical processes for SAP testing while performing the change."
},
{
"code": null,
"e": 25129,
"s": 25031,
"text": "Creating the test plan to monitor critical processes for SAP testing while performing the change."
},
{
"code": null,
"e": 25223,
"s": 25129,
"text": "Evaluation of impact of change on critical processes and the purpose to implement the change."
},
{
"code": null,
"e": 25317,
"s": 25223,
"text": "Evaluation of impact of change on critical processes and the purpose to implement the change."
},
{
"code": null,
"e": 25544,
"s": 25317,
"text": "SAP testing navigation ensures that you cover each module of your SAP system and perform at least one test for each functionality. It also reduces the manual testing effort and covers most of the testing paths in a SAP system."
},
{
"code": null,
"e": 25809,
"s": 25544,
"text": "OPA tests can be performed to check SAP Testing Navigation. OPA is known as Open Source Programming language and it is mostly used for developing web applications. For compilation of OPA program, you can use Node.js on the server and JavaScript on the client side."
},
{
"code": null,
"e": 25943,
"s": 25809,
"text": "OPA allows you to use three objects in Qunit. These functions should be defined in a test so that OPA knows what actions to be taken."
},
{
"code": null,
"e": 25973,
"s": 25943,
"text": "Given β to pass arrangements."
},
{
"code": null,
"e": 26003,
"s": 25973,
"text": "Given β to pass arrangements."
},
{
"code": null,
"e": 26031,
"s": 26003,
"text": "When β actions to be taken."
},
{
"code": null,
"e": 26059,
"s": 26031,
"text": "When β actions to be taken."
},
{
"code": null,
"e": 26077,
"s": 26059,
"text": "Then β assertion."
},
{
"code": null,
"e": 26095,
"s": 26077,
"text": "Then β assertion."
},
{
"code": null,
"e": 26164,
"s": 26095,
"text": "The following example shows how to use all the 3 objects in Qunit β "
},
{
"code": null,
"e": 26458,
"s": 26164,
"text": "jQuery.sap.require(\"sap.ui.test.Opa\");\njQuery.sap.require(\"sap.ui.test.opaQunit\");\n\nopaTest(\"press a Button\", function (Given, When, Then) {\n // Arrangements\n Given.iStartMyApp();\n\t\n //Actions\n When.iPressOnTheButton();\n\t\n // Assertions\n Then.theButtonShouldHaveADifferentText();\n}"
},
{
"code": null,
"e": 26506,
"s": 26458,
"text": "The next step is to define the three functions."
},
{
"code": null,
"e": 26644,
"s": 26506,
"text": "var arrangements = new sap.ui.test.Opa ({\n iStartMyApp : function (){\n return this.iStartMyAppInAFrame(\"../index.html\");\n }\n}); "
},
{
"code": null,
"e": 26783,
"s": 26644,
"text": "In the above function, we have assumed that the app runs in a page called index.html. Our OPA test is located in the test/opa.html folder."
},
{
"code": null,
"e": 27079,
"s": 26783,
"text": "var actions = new sap.ui.test.Opa ({\n\n iPressOnTheButton : function (){\n return this.waitFor ({\n viewName : \"Main\", id : \"pressMeButton\", success : function (oButton) {\n oButton.$().trigger(\"tap\");\n },\n errorMessage : \"No Button found\"\n });\n }\n})"
},
{
"code": null,
"e": 27633,
"s": 27079,
"text": "var assertions = new sap.ui.test.Opa ({\n\n theButtonShouldHaveADifferentText : function () {\n return this.waitFor ({\n viewName : \"Main\",\n id : \"pressMeButton\",\n\t\t\t\n matchers : new sap.ui.test.matchers.PropertyStrictEquals ({\n name : \"text\",\n value : \"got pressed\"\n }),\n\t\t\t\n success : function (oButton) {\n Opa.assert.ok(true, \"The button's text changed to: \" + oButton.getText());\n },\n\t\t\t\n errorMessage : \"No change in Button's text\"\n )}\n }\n}) "
},
{
"code": null,
"e": 27778,
"s": 27633,
"text": "sap.ui.test.Opa.extendConfig ({\n arrangements : arrangements,\n actions : actions,\n assertions : assertions,\n viewNamespace : \"view.\"\n});"
},
{
"code": null,
"e": 28014,
"s": 27778,
"text": "Screen flow logic in SAP Testing is like an ABAP code and it is used to contain the processing blocks. It contains the procedural part of the screen. It is created in screen painter and this screen painter is similar to an ABAP editor."
},
{
"code": null,
"e": 28145,
"s": 28014,
"text": "Screen flow logic involves no external data declaration and each processing block is defined with a prefix βPROCESSβ. For example,"
},
{
"code": null,
"e": 28165,
"s": 28145,
"text": "PROCESS AFTER INPUT"
},
{
"code": null,
"e": 28187,
"s": 28165,
"text": "PROCESS BEFORE OUTPUT"
},
{
"code": null,
"e": 28211,
"s": 28187,
"text": "PROCESS ON HELP-REQUEST"
},
{
"code": null,
"e": 28236,
"s": 28211,
"text": "PROCESS ON VALUE-REQUEST"
},
{
"code": null,
"e": 28330,
"s": 28236,
"text": "Each screen flow logic should contain PROCESS AFTER INPUT and PROCESS BEFORE OUTPUT keywords."
},
{
"code": null,
"e": 28413,
"s": 28330,
"text": "In an event block, you can use keywords like MODULE, FIELD, ON, VALUES, CALL, etc."
},
{
"code": null,
"e": 28420,
"s": 28413,
"text": "MODULE"
},
{
"code": null,
"e": 28461,
"s": 28420,
"text": "Calls a dialog module in an ABAP program"
},
{
"code": null,
"e": 28467,
"s": 28461,
"text": "FIELD"
},
{
"code": null,
"e": 28549,
"s": 28467,
"text": "Specifies the point at which the contents of a screen field should be transported"
},
{
"code": null,
"e": 28552,
"s": 28549,
"text": "ON"
},
{
"code": null,
"e": 28582,
"s": 28552,
"text": "Used in conjuction with FIELD"
},
{
"code": null,
"e": 28589,
"s": 28582,
"text": "VALUES"
},
{
"code": null,
"e": 28620,
"s": 28589,
"text": "Used in conjunction with FIELD"
},
{
"code": null,
"e": 28626,
"s": 28620,
"text": "CHAIN"
},
{
"code": null,
"e": 28653,
"s": 28626,
"text": "Starts a processing chain."
},
{
"code": null,
"e": 28662,
"s": 28653,
"text": "ENDCHAIN"
},
{
"code": null,
"e": 28687,
"s": 28662,
"text": "Ends a processing chain."
},
{
"code": null,
"e": 28692,
"s": 28687,
"text": "CALL"
},
{
"code": null,
"e": 28711,
"s": 28692,
"text": "Calls a subscreen."
},
{
"code": null,
"e": 28716,
"s": 28711,
"text": "LOOP"
},
{
"code": null,
"e": 28750,
"s": 28716,
"text": "Starts processing a screen table."
},
{
"code": null,
"e": 28758,
"s": 28750,
"text": "ENDLOOP"
},
{
"code": null,
"e": 28790,
"s": 28758,
"text": "Ends processing a screen table."
},
{
"code": null,
"e": 28904,
"s": 28790,
"text": "In the Repository browser, double-click on the name of a screen and it will display the flow logic of the screen."
},
{
"code": null,
"e": 29078,
"s": 28904,
"text": "The Flow Logic Editor of the Screen Painter will open and you edit the screen flow logic. You can use any of the available ABAP source code editors to define the flow logic."
},
{
"code": null,
"e": 29147,
"s": 29078,
"text": "You can use the following keywords to create the screen flow logic β"
},
{
"code": null,
"e": 29152,
"s": 29147,
"text": "CALL"
},
{
"code": null,
"e": 29171,
"s": 29152,
"text": "Calls a subscreen."
},
{
"code": null,
"e": 29177,
"s": 29171,
"text": "CHAIN"
},
{
"code": null,
"e": 29204,
"s": 29177,
"text": "Starts a processing chain."
},
{
"code": null,
"e": 29213,
"s": 29204,
"text": "ENDCHAIN"
},
{
"code": null,
"e": 29238,
"s": 29213,
"text": "Ends a processing chain."
},
{
"code": null,
"e": 29246,
"s": 29238,
"text": "ENDLOOP"
},
{
"code": null,
"e": 29268,
"s": 29246,
"text": "Ends loop processing."
},
{
"code": null,
"e": 29274,
"s": 29268,
"text": "FIELD"
},
{
"code": null,
"e": 29346,
"s": 29274,
"text": "Refers to a field. Can be combined with the keywords MODULE and SELECT."
},
{
"code": null,
"e": 29351,
"s": 29346,
"text": "LOOP"
},
{
"code": null,
"e": 29375,
"s": 29351,
"text": "Starts loop processing."
},
{
"code": null,
"e": 29382,
"s": 29375,
"text": "MODIFY"
},
{
"code": null,
"e": 29400,
"s": 29382,
"text": "Modifies a table."
},
{
"code": null,
"e": 29407,
"s": 29400,
"text": "MODULE"
},
{
"code": null,
"e": 29439,
"s": 29407,
"text": "Identifies a processing module."
},
{
"code": null,
"e": 29442,
"s": 29439,
"text": "ON"
},
{
"code": null,
"e": 29471,
"s": 29442,
"text": "Used with FIELD assignments."
},
{
"code": null,
"e": 29479,
"s": 29471,
"text": "PROCESS"
},
{
"code": null,
"e": 29507,
"s": 29479,
"text": "Defines a processing event."
},
{
"code": null,
"e": 29514,
"s": 29507,
"text": "SELECT"
},
{
"code": null,
"e": 29542,
"s": 29514,
"text": "Checks an entry in a table."
},
{
"code": null,
"e": 29745,
"s": 29542,
"text": "Testing screens are used to test the appearance of a screen as it will appear at runtime. If you have already programmed the flow logic, you can choose whether to simulate the screen with or without it."
},
{
"code": null,
"e": 29800,
"s": 29745,
"text": "To perform Screen test, follow the steps given below β"
},
{
"code": null,
"e": 29822,
"s": 29800,
"text": "Select Screen β Test."
},
{
"code": null,
"e": 29887,
"s": 29822,
"text": "The system will display a dialog box for the runtime simulation."
},
{
"code": null,
"e": 29945,
"s": 29887,
"text": "You can change the window coordinates, if it is required."
},
{
"code": null,
"e": 29983,
"s": 29945,
"text": "Next, define the scope of simulation."
},
{
"code": null,
"e": 30046,
"s": 29983,
"text": "To include the flow logic, click 'choose complete flow logic'."
},
{
"code": null,
"e": 30100,
"s": 30046,
"text": "Click Continue and the screen simulation will appear."
},
{
"code": null,
"e": 30342,
"s": 30100,
"text": "There are different SAP modules implemented in an organization that can be tested using various testing tools like HP Quick Test Professional (QTP), IBM Rational Functional Tester (RFT), and SAP Test Acceleration and Optimization (TAO) tool."
},
{
"code": null,
"e": 30384,
"s": 30342,
"text": "The common SAP modules are listed below β"
},
{
"code": null,
"e": 30491,
"s": 30384,
"text": "Financial Modules β Finance Accounting and Controlling (FICO), Treasure (TR), and Enterprise Control (EC)."
},
{
"code": null,
"e": 30598,
"s": 30491,
"text": "Financial Modules β Finance Accounting and Controlling (FICO), Treasure (TR), and Enterprise Control (EC)."
},
{
"code": null,
"e": 30727,
"s": 30598,
"text": "Logistics Modules β Material Management (MM), Plant Maintenance (PM), Sales and Distribution (SD), Quality Management (QM), etc."
},
{
"code": null,
"e": 30856,
"s": 30727,
"text": "Logistics Modules β Material Management (MM), Plant Maintenance (PM), Sales and Distribution (SD), Quality Management (QM), etc."
},
{
"code": null,
"e": 30952,
"s": 30856,
"text": "Human Resource Management β Accounting Payroll, Time Management, Training and Event Management."
},
{
"code": null,
"e": 31048,
"s": 30952,
"text": "Human Resource Management β Accounting Payroll, Time Management, Training and Event Management."
},
{
"code": null,
"e": 31166,
"s": 31048,
"text": "All these modules are inter-dependent and the functionality of one module affects the functionality of other modules."
},
{
"code": null,
"e": 31601,
"s": 31166,
"text": "Suppose you have to create a Sales Order in Sales and Distribution (SD) module. Here, you first need to enter the transaction code(e.g., Transaction Code VA01). Next, check the stock of the item in Inventory module and check the credit limit available on Customer profile in Customer Relationship Module. It shows that all these modules are interdependent; if you customize any of these modules, it will affect the related ERP system."
},
{
"code": null,
"e": 31862,
"s": 31601,
"text": "To perform SAP testing, you need to understand the features, functionalities, and how the workflow takes place in these SAP modules. Most of the common reasons of failure of ERP implementation project is incorrect test planning and the use of wrong test-cases."
},
{
"code": null,
"e": 32050,
"s": 31862,
"text": "Non SAP ERP systems like PeopleSoft, Edwards, Oracle E business suite have different customers and capabilities. The testing team needs to understand the functionality of complete system."
},
{
"code": null,
"e": 32118,
"s": 32050,
"text": "There are normally two types of testers available in SAP projects β"
},
{
"code": null,
"e": 32205,
"s": 32118,
"text": "Core Testers β who are responsible to perform basic testing of ERP system and modules."
},
{
"code": null,
"e": 32292,
"s": 32205,
"text": "Core Testers β who are responsible to perform basic testing of ERP system and modules."
},
{
"code": null,
"e": 32412,
"s": 32292,
"text": "Implementation Testers β who work on implementation project and cover the customization functionalities of SAP modules."
},
{
"code": null,
"e": 32532,
"s": 32412,
"text": "Implementation Testers β who work on implementation project and cover the customization functionalities of SAP modules."
},
{
"code": null,
"e": 32718,
"s": 32532,
"text": "Customization requests from clients can impact the modules of a SAP system. The testing team should be able to record each customization request and its impact on the other SAP modules."
},
{
"code": null,
"e": 33083,
"s": 32718,
"text": "ERP systems are large systems and therefore the testing process should ideally be automated. It is always advisable to perform automated testing for ERP systems, as manual testing is a very time-consuming and lengthy process. Without testing each component of the SAP system, it is really tough to achieve 100% quality and successful implementation of SAP project."
},
{
"code": null,
"e": 33160,
"s": 33083,
"text": "To perform SAP testing for the above example, follow the steps given below β"
},
{
"code": null,
"e": 33294,
"s": 33160,
"text": "The first step is to install HP QTP tool and to install necessary plug-ins within QTP to make it compatible to connect to ERP system."
},
{
"code": null,
"e": 33428,
"s": 33294,
"text": "The first step is to install HP QTP tool and to install necessary plug-ins within QTP to make it compatible to connect to ERP system."
},
{
"code": null,
"e": 33613,
"s": 33428,
"text": "The next step is to use HP Quality Center (QC) to develop the test plan and then to convert test plan design to Test Scripts. These test plans can be converted to scripts using HP QTP."
},
{
"code": null,
"e": 33798,
"s": 33613,
"text": "The next step is to use HP Quality Center (QC) to develop the test plan and then to convert test plan design to Test Scripts. These test plans can be converted to scripts using HP QTP."
},
{
"code": null,
"e": 33907,
"s": 33798,
"text": "Next, record the R/3 GUI screen of SAP system for SD module while creating Sales Order or creating PR in MM."
},
{
"code": null,
"e": 34016,
"s": 33907,
"text": "Next, record the R/3 GUI screen of SAP system for SD module while creating Sales Order or creating PR in MM."
},
{
"code": null,
"e": 34090,
"s": 34016,
"text": "After you are done with the recording in QTP tool, create a script in VB."
},
{
"code": null,
"e": 34164,
"s": 34090,
"text": "After you are done with the recording in QTP tool, create a script in VB."
},
{
"code": null,
"e": 34348,
"s": 34164,
"text": "SAPGuiSession(\"Session\").SAPGuiWindow(\"SAP Easy Access - User\")\n .SAPGuiOKCode(\"OKCode\").Set \"/nVA01\"\n\nSAPGuiSession(\"Session\").SAPGuiWindow(\"SAP Easy Access - User\"). SendKey ENTER"
},
{
"code": null,
"e": 34430,
"s": 34348,
"text": "You can also add different parameters and customizations as per your requirement."
},
{
"code": null,
"e": 34798,
"s": 34430,
"text": "An Interface in an ERP system is known as a tool that is responsible to get data from one system and move that data to another system. For example, assume you have a program that produces a report in XML format and then this program reads the XML file to provide input to another system. You can also manipulate while passing the information from one system to other."
},
{
"code": null,
"e": 34952,
"s": 34798,
"text": "Consider a vendor tool that takes care of employee attendance. Now, the system interface will take this information and populate it in the SAP HR system."
},
{
"code": null,
"e": 35138,
"s": 34952,
"text": "Interface testing ensures that this job is running successfully to ensure that the data is transferred completely and there is no error while transferring the data to the SAP HR system."
},
{
"code": null,
"e": 35316,
"s": 35138,
"text": "SAP Interface testing is purely dependent on the operations and organizational processes. While performing SAP Interface Testing, you need to consider the following key points β"
},
{
"code": null,
"e": 35419,
"s": 35316,
"text": "What is the purpose of using SAP Interface and what business scenarios are processed by the interface?"
},
{
"code": null,
"e": 35522,
"s": 35419,
"text": "What is the purpose of using SAP Interface and what business scenarios are processed by the interface?"
},
{
"code": null,
"e": 35619,
"s": 35522,
"text": "Check if the Interface is processing all business scenarios accurately as per the test strategy."
},
{
"code": null,
"e": 35716,
"s": 35619,
"text": "Check if the Interface is processing all business scenarios accurately as per the test strategy."
},
{
"code": null,
"e": 35806,
"s": 35716,
"text": "To perform Interface testing, the best practice is to start with performing Unit testing."
},
{
"code": null,
"e": 35896,
"s": 35806,
"text": "To perform Interface testing, the best practice is to start with performing Unit testing."
},
{
"code": null,
"e": 36044,
"s": 35896,
"text": "You have to check if the outbound interface is alright, which means that it ensures to perform file meeting specifications in terms of layout, etc."
},
{
"code": null,
"e": 36192,
"s": 36044,
"text": "You have to check if the outbound interface is alright, which means that it ensures to perform file meeting specifications in terms of layout, etc."
},
{
"code": null,
"e": 36350,
"s": 36192,
"text": "You have to check if the inbound interface is okay. Check if it is reading the file correctly and if it is performing the correct steps in the target system."
},
{
"code": null,
"e": 36508,
"s": 36350,
"text": "You have to check if the inbound interface is okay. Check if it is reading the file correctly and if it is performing the correct steps in the target system."
},
{
"code": null,
"e": 36713,
"s": 36508,
"text": "SAP test-cases are required to perform a check on the installation and configuration of the SAP system, any new implementation, multi-language and device testing, intranet testing, real-time testing, etc."
},
{
"code": null,
"e": 36900,
"s": 36713,
"text": "An ERP system is a common centralized system and is used by multiple users simultaneously in real time. Hence it creates a need to write the test-cases with lot of effort and dedication."
},
{
"code": null,
"e": 37139,
"s": 36900,
"text": "An ERP system also involves various FI transactions, so each test-case should cover the scope of all the configuration and implementation part. Test data should be passed carefully and each test should have a column with name output data."
},
{
"code": null,
"e": 37172,
"s": 37139,
"text": "Test Case ID β XYZ_ERP_SD_A20301"
},
{
"code": null,
"e": 37209,
"s": 37172,
"text": "Module β SAP Sales & Distribution SD"
},
{
"code": null,
"e": 37310,
"s": 37209,
"text": "Let us check the transaction VA01 to create a sales order in the Sales and Distribution (SD) system."
},
{
"code": null,
"e": 37357,
"s": 37310,
"text": "Fields to be entered while creating an Order β"
},
{
"code": null,
"e": 37368,
"s": 37357,
"text": "Order Date"
},
{
"code": null,
"e": 37379,
"s": 37368,
"text": "Order Type"
},
{
"code": null,
"e": 37391,
"s": 37379,
"text": "Expiry Date"
},
{
"code": null,
"e": 37403,
"s": 37391,
"text": "Customer ID"
},
{
"code": null,
"e": 37438,
"s": 37403,
"text": "Shipping Id, Shipping Details, etc"
},
{
"code": null,
"e": 37522,
"s": 37438,
"text": "Once you enter the details, press Enter and add all the details in the Sales Order."
},
{
"code": null,
"e": 37619,
"s": 37522,
"text": "To create a SAP test-case, you can pass input data (correct and Incorrect and see the outcome) β"
},
{
"code": null,
"e": 37665,
"s": 37619,
"text": "Order Date 01/01/2016, Order Type Sales Order"
},
{
"code": null,
"e": 37715,
"s": 37665,
"text": "Expiry Date 15/01/2016, Shipping Date 10/01/2016,"
},
{
"code": null,
"e": 37769,
"s": 37715,
"text": "Select Payment Due Date 10/01/2015, Item Qty 10, etc."
},
{
"code": null,
"e": 37815,
"s": 37769,
"text": "Order Date 01/01/2017, Order Type Sales Order"
},
{
"code": null,
"e": 37865,
"s": 37815,
"text": "Expiry Date 15/01/2017, Shipping Date 10/01/2017,"
},
{
"code": null,
"e": 37918,
"s": 37865,
"text": "Select Payment Due Date 10/01/2017, Item Qty 0, etc."
},
{
"code": null,
"e": 37974,
"s": 37918,
"text": "Order is successfully saved in SAP module and invoiced."
},
{
"code": null,
"e": 38003,
"s": 37974,
"text": "Next is Packing slip number."
},
{
"code": null,
"e": 38039,
"s": 38003,
"text": "Next is Shipping Order number, etc."
},
{
"code": null,
"e": 38150,
"s": 38039,
"text": "Error message for incorrect data input. Text message for incorrect input data should be defined in the system."
},
{
"code": null,
"e": 38261,
"s": 38150,
"text": "Error message for incorrect data input. Text message for incorrect input data should be defined in the system."
},
{
"code": null,
"e": 38274,
"s": 38261,
"text": "Sales Order#"
},
{
"code": null,
"e": 38289,
"s": 38274,
"text": "Sales Invoice#"
},
{
"code": null,
"e": 38309,
"s": 38289,
"text": "Packing List#, etc."
},
{
"code": null,
"e": 38629,
"s": 38309,
"text": "SAP Testing TAO (Test Acceleration and Optimization) is a tool used to perform automated testing of SAP systems. SAP TAO helps customers to fasten the process of creating automated test cases for SAP systems. Automation testing using TAO is performed by creating test components for various transactions in SAP modules."
},
{
"code": null,
"e": 38917,
"s": 38629,
"text": "Test components using TAO are uploaded to HP Quality Center. Test components created like this are normally for the single transactions and can be later used to create test scenarios. This tool can be easily integrated with SAP Solution Manager to maintain the different test components."
},
{
"code": null,
"e": 39069,
"s": 38917,
"text": "In short, you can say that SAP TAO enables SAP clients in automating the business needs by automatically creating draft test-cases and test components."
},
{
"code": null,
"e": 39245,
"s": 39069,
"text": "SAP TAO enables customers to breakdown a single software into multiple parts which can be integrated to test cases using a simple interface by dragging and dropping each part."
},
{
"code": null,
"e": 39297,
"s": 39245,
"text": "TAO supports flexible reuse of test cases and data."
},
{
"code": null,
"e": 39349,
"s": 39297,
"text": "TAO supports flexible reuse of test cases and data."
},
{
"code": null,
"e": 39456,
"s": 39349,
"text": "If there is any functional change in the system, it is easy to maintain test-cases because of this change."
},
{
"code": null,
"e": 39563,
"s": 39456,
"text": "If there is any functional change in the system, it is easy to maintain test-cases because of this change."
},
{
"code": null,
"e": 39619,
"s": 39563,
"text": "The common versions of SAP TAO are TAO 2.0 and TAO 3.0."
},
{
"code": null,
"e": 39798,
"s": 39619,
"text": "One of the key features of SAP TAO is that it can be easily integrated with various tools to create automated test-cases. Some common tools which can be integrated with TAO are β"
},
{
"code": null,
"e": 39829,
"s": 39798,
"text": "SAP Solution Manager (Solman)."
},
{
"code": null,
"e": 39851,
"s": 39829,
"text": "HP Quality Center QC."
},
{
"code": null,
"e": 39885,
"s": 39851,
"text": "HP Quality Test Professional QTP."
},
{
"code": null,
"e": 40106,
"s": 39885,
"text": "SAP TAO 2.0 is a tool that is used to create automatic test-cases during Regression testing of a system. It helps SAP customers to create different test components from the screens of a transaction and parameterize them."
},
{
"code": null,
"e": 40319,
"s": 40106,
"text": "These test components are created normally for one transaction code and later they can be combined to test scenarios. It can be easily integrated with the Business Process Change Analyzer in SAP Solution Manager."
},
{
"code": null,
"e": 40390,
"s": 40319,
"text": "SAP TAO 2.0 comes with different Service pack SP 02, SP 04, and SP 06."
},
{
"code": null,
"e": 40454,
"s": 40390,
"text": "SAP TAO performs the following tasks in SAP Testing Lifecycle β"
},
{
"code": null,
"e": 40474,
"s": 40454,
"text": "Test Cases creation"
},
{
"code": null,
"e": 40510,
"s": 40474,
"text": "Regeneration of affected components"
},
{
"code": null,
"e": 40535,
"s": 40510,
"text": "Test Cases Consolidation"
},
{
"code": null,
"e": 40550,
"s": 40535,
"text": "Test Execution"
},
{
"code": null,
"e": 40620,
"s": 40550,
"text": "The following illustration shows the process architecture of SAP TAO."
},
{
"code": null,
"e": 40648,
"s": 40620,
"text": "The steps are as follows β "
},
{
"code": null,
"e": 40829,
"s": 40648,
"text": "The first step is to get the requirements for SAP Testing. This includes understanding the functionality of SAP modules and identifying the requirement for testing to be performed."
},
{
"code": null,
"e": 41010,
"s": 40829,
"text": "The first step is to get the requirements for SAP Testing. This includes understanding the functionality of SAP modules and identifying the requirement for testing to be performed."
},
{
"code": null,
"e": 41099,
"s": 41010,
"text": "Next, get the information from the requirement analysis to generate the Test components."
},
{
"code": null,
"e": 41188,
"s": 41099,
"text": "Next, get the information from the requirement analysis to generate the Test components."
},
{
"code": null,
"e": 41263,
"s": 41188,
"text": "The next step is to generate test-cases and components using SAP TAO tool."
},
{
"code": null,
"e": 41338,
"s": 41263,
"text": "The next step is to generate test-cases and components using SAP TAO tool."
},
{
"code": null,
"e": 41427,
"s": 41338,
"text": "The last step is to document the test results and update the analysis with test results."
},
{
"code": null,
"e": 41516,
"s": 41427,
"text": "The last step is to document the test results and update the analysis with test results."
},
{
"code": null,
"e": 41645,
"s": 41516,
"text": "Downloaded SAP Solution Manager Solman compatibility Matrix, Quality Center, and SAP TAO from this link β http://service.sap.com"
},
{
"code": null,
"e": 41778,
"s": 41645,
"text": "Go to Test Management and Additional Information > Test Management. It will show all the compatible components supported by SAP TAO."
},
{
"code": null,
"e": 41859,
"s": 41778,
"text": "Check the prerequisites for components on SAP systems in your system landscape β"
},
{
"code": null,
"e": 41949,
"s": 41859,
"text": "Version of SAP Solution Manager SOLMAN, after checking the compatibility matrix as above."
},
{
"code": null,
"e": 42039,
"s": 41949,
"text": "Version of SAP Solution Manager SOLMAN, after checking the compatibility matrix as above."
},
{
"code": null,
"e": 42083,
"s": 42039,
"text": "Version of ST-PI on all systems under test."
},
{
"code": null,
"e": 42127,
"s": 42083,
"text": "Version of ST-PI on all systems under test."
},
{
"code": null,
"e": 42181,
"s": 42127,
"text": "Version of ST-A/PI on systems under test of type CRM."
},
{
"code": null,
"e": 42235,
"s": 42181,
"text": "Version of ST-A/PI on systems under test of type CRM."
},
{
"code": null,
"e": 42368,
"s": 42235,
"text": "For SAP Solution Manager Configuration work center, ensure that the systems on which testing has to be done are connected to SOLMAN."
},
{
"code": null,
"e": 42451,
"s": 42368,
"text": "SAP TAO client installation requires the following configuration on local system β"
},
{
"code": null,
"e": 42462,
"s": 42451,
"text": "RAM: 4 GB."
},
{
"code": null,
"e": 42487,
"s": 42462,
"text": "Free disk space: 500 MB."
},
{
"code": null,
"e": 42546,
"s": 42487,
"text": "LAN connection to SAP Quality Center QC server and SOLMAN."
},
{
"code": null,
"e": 42569,
"s": 42546,
"text": "Administration Rights."
},
{
"code": null,
"e": 42605,
"s": 42569,
"text": "SAPGUI with the latest patch level."
},
{
"code": null,
"e": 42635,
"s": 42605,
"text": "Microsoft Excel 97 or higher."
},
{
"code": null,
"e": 42683,
"s": 42635,
"text": "Microsoft Internet Explorer for CRM UI support."
},
{
"code": null,
"e": 42788,
"s": 42683,
"text": "There are various modules inside the SAP TAO tool. We have discussed the key components in this chapter."
},
{
"code": null,
"e": 43028,
"s": 42788,
"text": "The first component is Process Flow Analyzer which is used to automatically find out the user interfaces used in transaction codes executed in the SAP system. It automatically creates the test components and uploads them to Quality Center."
},
{
"code": null,
"e": 43163,
"s": 43028,
"text": "Process Flow Analyzer is also used to identify the sequence of test components as per user actions and creation of spreadsheet values."
},
{
"code": null,
"e": 43343,
"s": 43163,
"text": "You have to add Transaction codes to the list. SAP TAO will return all the screens associated with a particular transaction. You can choose any screen and click on Inspect option."
},
{
"code": null,
"e": 43491,
"s": 43343,
"text": "It allows you to collect multiple test components into one test. You need to find the test in Quality Center from QC tree and click on Consolidate."
},
{
"code": null,
"e": 43618,
"s": 43491,
"text": "Select the Transaction code you want to consolidate and click Add to Consolidate list at the bottom to create a test scenario."
},
{
"code": null,
"e": 43809,
"s": 43618,
"text": "Import and Export options are used to export to Quality Center and import from Quality Center. You need to select the components to be imported and exported and click on the required button."
},
{
"code": null,
"e": 43973,
"s": 43809,
"text": "Change Analyzer is used to track the changes and impact on the SAP system. When you make any change to a SAP system, it identifies the affected business processes."
},
{
"code": null,
"e": 44175,
"s": 43973,
"text": "To use Change Analyzer, select the specific project and click the change impact analysis option. It will allow you to review and repair the impacted components in the SAP system because of this change."
},
{
"code": null,
"e": 44398,
"s": 44175,
"text": "Repository is used to contain information about all the test components and flow in a project. To review information about any test component and to check the process flow, you can click Component Explorer or PFA Explorer."
},
{
"code": null,
"e": 44460,
"s": 44398,
"text": "Configuration of SAP Quality Center can be done in two ways β"
},
{
"code": null,
"e": 44481,
"s": 44460,
"text": "HP Server Attributes"
},
{
"code": null,
"e": 44492,
"s": 44481,
"text": "HP Project"
},
{
"code": null,
"e": 44654,
"s": 44492,
"text": "Step 1 β In SAP TAO, click SAP Quality Center. You should have SAP Quality Center URL in the connection panel of SAP TAO. Next, enter the URL in the web browser."
},
{
"code": null,
"e": 44765,
"s": 44654,
"text": "Step 2 β Enter the following values in SAP Quality Center by HP Site Administration and click apply to entire."
},
{
"code": null,
"e": 44838,
"s": 44765,
"text": "DISABLE_EXTENDED_STORAGE = N \nBACKWARD_SUPPORT_ALL_DOMAINS_PROJECTS = Y\n"
},
{
"code": null,
"e": 44896,
"s": 44838,
"text": "Step 3 β For a new project, perform the following steps β"
},
{
"code": null,
"e": 44937,
"s": 44896,
"text": "Create new domain and project in SAP QC."
},
{
"code": null,
"e": 44989,
"s": 44937,
"text": "Create new user to assign that project to new user."
},
{
"code": null,
"e": 45048,
"s": 44989,
"text": "Allocate Project Administrator role to newly created user."
},
{
"code": null,
"e": 45116,
"s": 45048,
"text": "Step 4 β Log off from SAP Quality Center by HP Site Administration."
},
{
"code": null,
"e": 45225,
"s": 45116,
"text": "In SAP TAO, click SAP Quality Center. You should have SAP Quality Center URL in connection panel of SAP TAO."
},
{
"code": null,
"e": 45269,
"s": 45225,
"text": "Step 1 β Enter the URL in your web browser."
},
{
"code": null,
"e": 45313,
"s": 45269,
"text": "Step 1 β Enter the URL in your web browser."
},
{
"code": null,
"e": 45367,
"s": 45313,
"text": "Step 2 β The next step is to login to domain/project."
},
{
"code": null,
"e": 45421,
"s": 45367,
"text": "Step 2 β The next step is to login to domain/project."
},
{
"code": null,
"e": 45457,
"s": 45421,
"text": "Step 3 β Navigate to the Test Plan."
},
{
"code": null,
"e": 45493,
"s": 45457,
"text": "Step 3 β Navigate to the Test Plan."
},
{
"code": null,
"e": 45595,
"s": 45493,
"text": "Step 4 β Under Subject folder, create a folder with the name BPT Resources β create a folder library."
},
{
"code": null,
"e": 45697,
"s": 45595,
"text": "Step 4 β Under Subject folder, create a folder with the name BPT Resources β create a folder library."
},
{
"code": null,
"e": 45924,
"s": 45697,
"text": "Step 5 β SAP TAO notes information about test Consolidation into a user field of the test entities in QC and by default it is TS_USER_01. Note that this is correct when connected to SOLMAN for all the tests created by SAP TAO."
},
{
"code": null,
"e": 46151,
"s": 45924,
"text": "Step 5 β SAP TAO notes information about test Consolidation into a user field of the test entities in QC and by default it is TS_USER_01. Note that this is correct when connected to SOLMAN for all the tests created by SAP TAO."
},
{
"code": null,
"e": 46263,
"s": 46151,
"text": "Step 6 β SAP QC users shouldnβt use the similar user field for other purposes in their Quality Center projects."
},
{
"code": null,
"e": 46375,
"s": 46263,
"text": "Step 6 β SAP QC users shouldnβt use the similar user field for other purposes in their Quality Center projects."
},
{
"code": null,
"e": 46541,
"s": 46375,
"text": "Application area is required by SAP TAO components to contain HP QTP and web add-ons. To create an application area in QTP, you need to perform the following steps β"
},
{
"code": null,
"e": 46612,
"s": 46541,
"text": "Run QTP by HP as Administrator. It varies as per the operating system."
},
{
"code": null,
"e": 46683,
"s": 46612,
"text": "Run QTP by HP as Administrator. It varies as per the operating system."
},
{
"code": null,
"e": 46718,
"s": 46683,
"text": "You can select Web addins and SAP."
},
{
"code": null,
"e": 46753,
"s": 46718,
"text": "You can select Web addins and SAP."
},
{
"code": null,
"e": 46864,
"s": 46753,
"text": "Next, connect automatically or manually to Quality Center project. This step is automatic if it is configured."
},
{
"code": null,
"e": 46975,
"s": 46864,
"text": "Next, connect automatically or manually to Quality Center project. This step is automatic if it is configured."
},
{
"code": null,
"e": 47104,
"s": 46975,
"text": "Next, create an application area with the name_SAP_Doc. The name of application area is entered when the Save button is clicked."
},
{
"code": null,
"e": 47233,
"s": 47104,
"text": "Next, create an application area with the name_SAP_Doc. The name of application area is entered when the Save button is clicked."
},
{
"code": null,
"e": 47440,
"s": 47233,
"text": "Process Flow Analyzer is used to automatically find out the user interfaces used in transactions codes executed in SAP system. It automatically creates the test components and upload them to Quality Center."
},
{
"code": null,
"e": 47552,
"s": 47440,
"text": "It is also used to identify sequence of test components as per user actions and creation of spreadsheet values."
},
{
"code": null,
"e": 47624,
"s": 47552,
"text": "Click Add Transaction button β Enter the Transaction-code and click OK."
},
{
"code": null,
"e": 47668,
"s": 47624,
"text": "The next step is to click the Start button."
},
{
"code": null,
"e": 47799,
"s": 47668,
"text": "TAO will launch SAP and will log the Transaction entered by you. Once the transaction process is completed, click the Stop button."
},
{
"code": null,
"e": 47954,
"s": 47799,
"text": "TAO will return all the screens that are used to create the process flow. Next, upload the analysis to QC. This can be done by clicking the Upload button."
},
{
"code": null,
"e": 48142,
"s": 47954,
"text": "Import and Export options are used to export to Quality Center and import from Quality Center. You need to select the components to be imported and exported and click the required button."
},
{
"code": null,
"e": 48288,
"s": 48142,
"text": "First, identify the components to be imported or exported. Click Export to SAP QC or Import from SAP QC to import/export the required components."
},
{
"code": null,
"e": 48452,
"s": 48288,
"text": "Change Analyzer is used to track the changes and impact on the SAP system. When you make any change to a SAP system, it identifies the affected business processes."
},
{
"code": null,
"e": 48631,
"s": 48452,
"text": "To use Change Analyzer, select the specific project and click the change impact analysis option. It will allow you to review and repair the impacted components in the SAP system."
},
{
"code": null,
"e": 48812,
"s": 48631,
"text": "You have to add Transaction codes to the list. SAP TAO will return all the screens associated with a particular transaction. You can choose any screen and click the Inspect option."
},
{
"code": null,
"e": 48877,
"s": 48812,
"text": "To analyze the results of SAP TAO, perform the following steps β"
},
{
"code": null,
"e": 49044,
"s": 48877,
"text": "Step 1 β Go to the Tests list and in the tree, click the test for the analysis. It will take you to list of reports and the status of running tests will be displayed."
},
{
"code": null,
"e": 49149,
"s": 49044,
"text": "Step 2 β Analyze a test, click the View Report option. It will open a new window with a detailed report."
},
{
"code": null,
"e": 49407,
"s": 49149,
"text": "There is an option to adjust the columns to be displayed by clicking the mouse icon. You can also see the HTML format of the test report by clicking the HTML Report. To investigate the test results further, you can go to the log folder from the HTML report."
},
{
"code": null,
"e": 49625,
"s": 49407,
"text": "Test building is done in SAP Quality Center using SAP TAO. You need to consolidate test components to create test scenarios. You can execute a single or multiple tests in SAP TAO using Technical Bill of Material TBOM."
},
{
"code": null,
"e": 49819,
"s": 49625,
"text": "Technical Bill of Material (TBOM) is used to contain the objects in an executable form. Change Analyzer makes use of this to tell if an executable object is affected when a change is performed."
},
{
"code": null,
"e": 49969,
"s": 49819,
"text": "In case you want to use the Business Process Change Analyzer, you need to generate a TBOM for each executable object in test scenarios and processes."
},
{
"code": null,
"e": 50069,
"s": 49969,
"text": "Note β If you need to run a single test and you have to update TBOM, click Execute and update TBOM."
},
{
"code": null,
"e": 50179,
"s": 50069,
"text": "You can check the details of update on the TBOM page. You can modify the run list that is created in SAP TAO."
},
{
"code": null,
"e": 50355,
"s": 50179,
"text": "In Business Process Change Analyzer, to execute multiple tests, you can select a folder and add it to the run list. You can also select TBOM creation at the time of execution."
},
{
"code": null,
"e": 50446,
"s": 50355,
"text": "Note β If TBOM already exists at time of execution, it will only update the existing TBOM."
},
{
"code": null,
"e": 50669,
"s": 50446,
"text": "Consolidate is known as a process to combine SAP TAO components with inbuilt components to create test scenarios as single transactional business components. It allows you to collect multiple test components into one test."
},
{
"code": null,
"e": 50789,
"s": 50669,
"text": "It happens when transactional components are gathered. The following screenshot shows the transaction components in QC."
},
{
"code": null,
"e": 50880,
"s": 50789,
"text": "You need to find the test in Quality Center from QC tree and click the Consolidate option."
},
{
"code": null,
"e": 51007,
"s": 50880,
"text": "Select the Transaction code you want to consolidate and click Add to Consolidate list at the bottom to create a test scenario."
},
{
"code": null,
"e": 51087,
"s": 51007,
"text": "As covered in the previous chapters, you need to follow the steps given below β"
},
{
"code": null,
"e": 51152,
"s": 51087,
"text": "Step 1 β Find out the transaction you want to consolidate in QC."
},
{
"code": null,
"e": 51217,
"s": 51152,
"text": "Step 1 β Find out the transaction you want to consolidate in QC."
},
{
"code": null,
"e": 51268,
"s": 51217,
"text": "Step 2 β Add the transactions to consolidate list."
},
{
"code": null,
"e": 51319,
"s": 51268,
"text": "Step 2 β Add the transactions to consolidate list."
},
{
"code": null,
"e": 51358,
"s": 51319,
"text": "Step 3 β Press the consolidate button."
},
{
"code": null,
"e": 51397,
"s": 51358,
"text": "Step 3 β Press the consolidate button."
},
{
"code": null,
"e": 51693,
"s": 51397,
"text": "UI scanner is used to create new screen components with existing components. It is a plugin for QTP tool. You should try to use inspect tab over UI scanner. The standard UI scanner works only with GUI front-end client. You can also use third-party UI scanner for capturing the screen components."
},
{
"code": null,
"e": 51918,
"s": 51693,
"text": "If you have to use UI scanner, you need to activate it in the Inspection tab of SAP TAO tool. UI scanner is used to get the information from one screen in one go and transfer these screen objects to QC as a screen component."
},
{
"code": null,
"e": 52049,
"s": 51918,
"text": "UI scanner allows you to create components from SAP GUI screen which are not supported by Process Flow Analyzer or Inspection tab."
},
{
"code": null,
"e": 52141,
"s": 52049,
"text": "When you login to SAP TAO, click the Inspect tab. It will show an option to use UI Scanner."
},
{
"code": null,
"e": 52241,
"s": 52141,
"text": "Login to the SAP system. Enter the transaction code and go to the screen to be scanned and log off."
},
{
"code": null,
"e": 52476,
"s": 52241,
"text": "You can use the default UI Scanner option with QTP tool, by going to UI Scanning tab under Inspect option in SAP TAO. Otherwise, you can use custom QTP test with UI Scanner process by going to UI Scanner and selecting external option."
},
{
"code": null,
"e": 52813,
"s": 52476,
"text": "In Automation testing, the testers write the scripts and use other software tools to test the product. This process involves automation of a manual process. In comparison, manual testing is time-consuming and requires a team of experience test professionals, subject matter experts, and effective communication between the team members."
},
{
"code": null,
"e": 52912,
"s": 52813,
"text": "Automation Testing includes re-running the test-cases multiple times that were performed manually."
},
{
"code": null,
"e": 53186,
"s": 52912,
"text": "In addition to Regression testing, you can say that Automation testing is also used to test the application from load, performance, and stress purpose. It is used to increase the coverage of test, improves accuracy, and saves time and money in comparison to manual testing."
},
{
"code": null,
"e": 53243,
"s": 53186,
"text": "The following tools can be used for Automation testing β"
},
{
"code": null,
"e": 53276,
"s": 53243,
"text": "HP Quick Test Professional (QTP)"
},
{
"code": null,
"e": 53285,
"s": 53276,
"text": "Selenium"
},
{
"code": null,
"e": 53293,
"s": 53285,
"text": "SAP TAO"
},
{
"code": null,
"e": 53299,
"s": 53293,
"text": "ECATT"
},
{
"code": null,
"e": 53330,
"s": 53299,
"text": "IBM Rational Functional Tester"
},
{
"code": null,
"e": 53339,
"s": 53330,
"text": "SilkTest"
},
{
"code": null,
"e": 53352,
"s": 53339,
"text": "TestComplete"
},
{
"code": null,
"e": 53369,
"s": 53352,
"text": "Testing Anywhere"
},
{
"code": null,
"e": 53379,
"s": 53369,
"text": "WinRunner"
},
{
"code": null,
"e": 53390,
"s": 53379,
"text": "LaodRunner"
},
{
"code": null,
"e": 53422,
"s": 53390,
"text": "Visual Studio Test Professional"
},
{
"code": null,
"e": 53428,
"s": 53422,
"text": "WATIR"
},
{
"code": null,
"e": 53573,
"s": 53428,
"text": "To perform SAP Automation testing, there is a need to set up a communication between SAP TAO, SAP Solution Manager, and the system to be tested."
},
{
"code": null,
"e": 53717,
"s": 53573,
"text": "To set up this configuration, you need an administration authorization on SAP SOLMAN. This is required to access and modify data table content."
},
{
"code": null,
"e": 53730,
"s": 53717,
"text": "T-Code: SE16"
},
{
"code": null,
"e": 53838,
"s": 53730,
"text": "You need to display the table name: AGS_TAO_SETTING and change the value for AGS_TAO_ENABLE_SM_SETUP to ON."
},
{
"code": null,
"e": 54017,
"s": 53838,
"text": "Next, check the compatibility matrix for SAP TAO and Solution Manager. SAP TAO 3.0 contains a Process Flow Analyzer recording wizard which can be used to ease the test recording."
},
{
"code": null,
"e": 54212,
"s": 54017,
"text": "Note β SAP TAO 3.0 is a component for Solution Manager 7.1 and does not support Solution Manager 7.0. Open SAP Solution Manager Configuration work center and run Transaction code β SOLMAN_SETUP."
},
{
"code": null,
"e": 54272,
"s": 54212,
"text": "Open SAP Logon and add the system to be tested under logon."
},
{
"code": null,
"e": 54514,
"s": 54272,
"text": "Go to SAP TAO and login and select SAP SOLMAN in the list. This list of system in SAP TAO is fetched from the configuration file of SAP logon. To add a system in SAP TAO, you need to add a new system in SAP Logon and refresh the list in TAO."
},
{
"code": null,
"e": 54655,
"s": 54514,
"text": "Enter the login credentials and click on logon. SAP TAO will be connected to SAP Solution Manager and TAO configuration wizard will open up."
},
{
"code": null,
"e": 54882,
"s": 54655,
"text": "Business Process Testing (BPT) is a part of QTP automation framework and is used with the Quality Center by HP. BPT is used to create automation test scenarios and run those scenarios without any prior knowledge of automation."
},
{
"code": null,
"e": 55020,
"s": 54882,
"text": "HP BPT removes the complexity of test-case creation and maintenance and combines all the documentation and test automation in one effort."
},
{
"code": null,
"e": 55145,
"s": 55020,
"text": "Business Process Testing aligns the testing process with business goals and reduces the testing lifecycle time considerably."
},
{
"code": null,
"e": 55320,
"s": 55145,
"text": "Business Process Testing tool uses reusable components for creating test-cases and hence reduces the testing maintenance time and increases the efficiency of testing process."
},
{
"code": null,
"e": 55608,
"s": 55320,
"text": "To fasten the process of test automation, it uses the method of keyword driven. You can add common best practices to the testing process. It allows you to use a test solution which is not based on test scripts. Once a manual test is created in BPT, you can easily automate the test-case."
},
{
"code": null,
"e": 55756,
"s": 55608,
"text": "You can also maintain different versions and baseline for different test components, process flows without any chance of overwriting the old cases."
},
{
"code": null,
"e": 55864,
"s": 55756,
"text": "Test cases that are created using Business Process Testing tool can be executed using HP Quality Center QC."
},
{
"code": null,
"e": 55992,
"s": 55864,
"text": "Using BPT, a non-technical SME can easily create, maintain, and run the test-cases and can document them in a Web-based system."
},
{
"code": null,
"e": 56112,
"s": 55992,
"text": "It allows you to design and create the reusable components in test-cases and use them as per the business requirements."
},
{
"code": null,
"e": 56232,
"s": 56112,
"text": "It allows you to design and create the reusable components in test-cases and use them as per the business requirements."
},
{
"code": null,
"e": 56284,
"s": 56232,
"text": "You can also run testing scripts using HP Sprinter."
},
{
"code": null,
"e": 56336,
"s": 56284,
"text": "You can also run testing scripts using HP Sprinter."
},
{
"code": null,
"e": 56455,
"s": 56336,
"text": "With the availability of framework to use reusable components, it decreases the effort for maintaining the test-cases."
},
{
"code": null,
"e": 56574,
"s": 56455,
"text": "With the availability of framework to use reusable components, it decreases the effort for maintaining the test-cases."
},
{
"code": null,
"e": 56807,
"s": 56574,
"text": "HP Quality Center, a test management tool, is now popularly known as Application Life Cycle Management (ALM) tool, as it is no longer just a test management tool but it supports various phases of the software development life cycle."
},
{
"code": null,
"e": 57076,
"s": 56807,
"text": "HP-ALM helps us to manage project milestones, deliverables, resources and keeping track of project health, standards that allow Product owners to gauge the current status of the product. It is important to understand history, architecture, and Quality Center Workflow."
},
{
"code": null,
"e": 57262,
"s": 57076,
"text": "The Requirements module enables users to define, manage and track requirements at all stages of the software lifecycle. The following are the key functionalities in requirements module."
},
{
"code": null,
"e": 57310,
"s": 57262,
"text": "Create requirements, assign to releases/cycles."
},
{
"code": null,
"e": 57360,
"s": 57310,
"text": "Uploading requirements using ALM-MS Excel Add-ins"
},
{
"code": null,
"e": 57476,
"s": 57360,
"text": "Enables how to define traceability links between requirements and dependencies that exist between the requirements."
},
{
"code": null,
"e": 57597,
"s": 57476,
"text": "Enables user to view the traceability matrix that lists source requirements and their associated requirements and tests."
},
{
"code": null,
"e": 57827,
"s": 57597,
"text": "The crucial step in testing any application is to develop a clear and a precise test plan. A good test plan enables the team to assess the quality of the application under test at any point in the software development life cycle."
},
{
"code": null,
"e": 57924,
"s": 57827,
"text": "Following functionalities are very important in order to understand the test plan module better."
},
{
"code": null,
"e": 57939,
"s": 57924,
"text": "Creating Tests"
},
{
"code": null,
"e": 58045,
"s": 57939,
"text": "This module describes how to create folders of test subjects in the test plan tree and also to add tests."
},
{
"code": null,
"e": 58061,
"s": 58045,
"text": "Uploading Tests"
},
{
"code": null,
"e": 58103,
"s": 58061,
"text": "Uploading Teats using ALM-MS Excel Addins"
},
{
"code": null,
"e": 58133,
"s": 58103,
"text": "Requirement and Test Coverage"
},
{
"code": null,
"e": 58207,
"s": 58133,
"text": "Enable how to define the relationship between the requirements and tests."
},
{
"code": null,
"e": 58226,
"s": 58207,
"text": "Test Configuration"
},
{
"code": null,
"e": 58306,
"s": 58226,
"text": "Specific the subset of data or a run-time environment that the test should use."
},
{
"code": null,
"e": 58391,
"s": 58306,
"text": "More details on how HP QC, please go to β http://www.tutorialspoint.com/qc/index.htm"
},
{
"code": null,
"e": 58642,
"s": 58391,
"text": "HP Quick Test Professional (QTP) is an automated functional testing tool that helps testers to perform automated regression testing in order to identify any gaps, errors/defects in contrary to the actual/desired results of the application under test."
},
{
"code": null,
"e": 58955,
"s": 58642,
"text": "Object Repository is a collection of objects and properties with which QTP will be able to recognize the objects and act on it. When a user records a test, the objects and its properties are captured by default. Without understanding the objects and its properties, QTP will NOT be able to play back the scripts."
},
{
"code": null,
"e": 59169,
"s": 58955,
"text": "Actions help testers to divide scripts into groups of QTP statements called actions. Actions are similar to functions in VBScript, however there are a few differences. By default, QTP creates a test with 1 action."
},
{
"code": null,
"e": 59285,
"s": 59169,
"text": "The properties of the action can be accessed by right-clicking the Script Editor Window and selecting \"Properties\"."
},
{
"code": null,
"e": 59335,
"s": 59285,
"text": "Action properties contain following information β"
},
{
"code": null,
"e": 59347,
"s": 59335,
"text": "Action Name"
},
{
"code": null,
"e": 59356,
"s": 59347,
"text": "Location"
},
{
"code": null,
"e": 59370,
"s": 59356,
"text": "Reusable Flag"
},
{
"code": null,
"e": 59387,
"s": 59370,
"text": "Input Parameters"
},
{
"code": null,
"e": 59405,
"s": 59387,
"text": "Output Parameters"
},
{
"code": null,
"e": 59440,
"s": 59405,
"text": "There are three types of actions β"
},
{
"code": null,
"e": 59577,
"s": 59440,
"text": "Non-reusable action β An action that can be called only in that specific test in which it has been designed and can be called only once."
},
{
"code": null,
"e": 59714,
"s": 59577,
"text": "Non-reusable action β An action that can be called only in that specific test in which it has been designed and can be called only once."
},
{
"code": null,
"e": 59845,
"s": 59714,
"text": "Reusable action β An action that can be called multiple times any test in which it resides and can also be used by any other tests"
},
{
"code": null,
"e": 59976,
"s": 59845,
"text": "Reusable action β An action that can be called multiple times any test in which it resides and can also be used by any other tests"
},
{
"code": null,
"e": 60208,
"s": 59976,
"text": "External Reusable action β It is a reusable action stored in another test. External actions are read-only in the calling test, but it can be used locally with the editable copy of the Data Table information for the external action."
},
{
"code": null,
"e": 60440,
"s": 60208,
"text": "External Reusable action β It is a reusable action stored in another test. External actions are read-only in the calling test, but it can be used locally with the editable copy of the Data Table information for the external action."
},
{
"code": null,
"e": 60538,
"s": 60440,
"text": "For more information, please use the following link β http://www.tutorialspoint.com/qtp/index.htm"
},
{
"code": null,
"e": 60719,
"s": 60538,
"text": "Most of the companies that implement SAP need to perform testing. As the scope of testing is too large, an automated approach can be followed to maintain the changes in SAP system."
},
{
"code": null,
"e": 60902,
"s": 60719,
"text": "Various companies have designed their internal solutions to meet client requirements to perform SAP Testing. Clients can be from banking, finance, manufacturing or healthcare domain."
},
{
"code": null,
"e": 60983,
"s": 60902,
"text": "Given below is an example of performing SAP testing for a manufacturing company."
},
{
"code": null,
"e": 61367,
"s": 60983,
"text": "Client Requirement β The client is a UK based manufacturing company. Project requirement was to perform SAP testing using QTP and to perform automation and functional testing key operations in field of Human Resource, Supply Chain, Logistics, Material Management and Plant maintenance and to use automated test cases for SAP upgrade and to perform integration and Regression testing."
},
{
"code": null,
"e": 61614,
"s": 61367,
"text": "Tasks Performed β It started with understanding of key business processes and SAP system tasks to be automated. Testing team referenced an old pilot project to finalize test strategy, time and effort required to run test execution in HP QTP tool."
},
{
"code": null,
"e": 61806,
"s": 61614,
"text": "As Part of project implementation 100 business processes were successfully automated. Implemented solution resulted in faster execution, more accuracy, increased scope and quality of service."
},
{
"code": null,
"e": 61927,
"s": 61806,
"text": "Tools Used β The following tools were used: SAP R/3, HP QTP, Test scripts written in VB, and Data in XML and XLS format."
},
{
"code": null,
"e": 61990,
"s": 61927,
"text": "Key Benefits Achieved β The following benefits were achieved β"
},
{
"code": null,
"e": 62008,
"s": 61990,
"text": "System Validation"
},
{
"code": null,
"e": 62028,
"s": 62008,
"text": "Quality and Revenue"
},
{
"code": null,
"e": 62052,
"s": 62028,
"text": "Cost and Predictability"
},
{
"code": null,
"e": 62074,
"s": 62052,
"text": "Compliance Management"
},
{
"code": null,
"e": 62119,
"s": 62074,
"text": "New Implementation and Configuration Changes"
},
{
"code": null,
"e": 62581,
"s": 62119,
"text": "SAP Testing is about testing the functionality of various SAP modules to ensure that they are performing as per the configuration. SAP system undergoes various changes like patch management and fixes, new module implementations and various other configuration changes. All these raise a need for Regression testing to be performed in SAP environments. SAP testing automation tools like SAP TAO can be used for this purpose and is recommended by SAP for testing."
},
{
"code": null,
"e": 62656,
"s": 62581,
"text": "The benefits of performing SAP Testing are manifold. They are as follows β"
},
{
"code": null,
"e": 62783,
"s": 62656,
"text": "System Validation β SAP Testing involves complete end to end testing and validation of all SAP modules in SAP ERP environment."
},
{
"code": null,
"e": 62910,
"s": 62783,
"text": "System Validation β SAP Testing involves complete end to end testing and validation of all SAP modules in SAP ERP environment."
},
{
"code": null,
"e": 63134,
"s": 62910,
"text": "Quality and Revenue β SAP Testing is an output based testing and not like conventional testing methods which are input based and it ensures the quality of SAP system and also focuses on revenue and cost of the organization."
},
{
"code": null,
"e": 63358,
"s": 63134,
"text": "Quality and Revenue β SAP Testing is an output based testing and not like conventional testing methods which are input based and it ensures the quality of SAP system and also focuses on revenue and cost of the organization."
},
{
"code": null,
"e": 63468,
"s": 63358,
"text": "Cost and Predictability β SAP Testing involves reducing the SAP development costs and improve predictability."
},
{
"code": null,
"e": 63578,
"s": 63468,
"text": "Cost and Predictability β SAP Testing involves reducing the SAP development costs and improve predictability."
},
{
"code": null,
"e": 63776,
"s": 63578,
"text": "Compliance Requirement β SAP Testing ensures that SAP implementation is meeting the new compliance requirements in a specific organization and all modules are working as per expected configuration."
},
{
"code": null,
"e": 63974,
"s": 63776,
"text": "Compliance Requirement β SAP Testing ensures that SAP implementation is meeting the new compliance requirements in a specific organization and all modules are working as per expected configuration."
},
{
"code": null,
"e": 64264,
"s": 63974,
"text": "New Implementation and Configuration Changes β There are different type of changes implemented in SAP system, like patches and fixes, new implementation, configurational changes. SAP testing ensures that all the modules are performing as per requirement in this dynamic system environment."
},
{
"code": null,
"e": 64554,
"s": 64264,
"text": "New Implementation and Configuration Changes β There are different type of changes implemented in SAP system, like patches and fixes, new implementation, configurational changes. SAP testing ensures that all the modules are performing as per requirement in this dynamic system environment."
},
{
"code": null,
"e": 64891,
"s": 64554,
"text": "Integration β SAP testing is performed to test various reports, data flows and work flows, GUI forms, etc. It is used to check system integration between different modules. For example, if an order posting is done that requires an action in Sales and Distribution, MM and FICO so SAP testing check the integration between these systems."
},
{
"code": null,
"e": 65228,
"s": 64891,
"text": "Integration β SAP testing is performed to test various reports, data flows and work flows, GUI forms, etc. It is used to check system integration between different modules. For example, if an order posting is done that requires an action in Sales and Distribution, MM and FICO so SAP testing check the integration between these systems."
},
{
"code": null,
"e": 65411,
"s": 65228,
"text": "Performance β It is also used to ensure if system will be able to meet the Service Level agreements, time taken by system to perform specific actions, performance of the system, etc."
},
{
"code": null,
"e": 65594,
"s": 65411,
"text": "Performance β It is also used to ensure if system will be able to meet the Service Level agreements, time taken by system to perform specific actions, performance of the system, etc."
},
{
"code": null,
"e": 65650,
"s": 65594,
"text": "SAP testing can be performed on the following modules β"
},
{
"code": null,
"e": 65674,
"s": 65650,
"text": "SAP Material Management"
},
{
"code": null,
"e": 65715,
"s": 65674,
"text": "SAP Financial Accounting and Controlling"
},
{
"code": null,
"e": 65742,
"s": 65715,
"text": "SAP Sales and Distribution"
},
{
"code": null,
"e": 65761,
"s": 65742,
"text": "SAP Human Resource"
},
{
"code": null,
"e": 65789,
"s": 65761,
"text": "SAP Supply Chain Management"
},
{
"code": null,
"e": 65810,
"s": 65789,
"text": "SAP Plant Management"
},
{
"code": null,
"e": 65972,
"s": 65810,
"text": "Some of the automating testing tools are β HP Quick Test Professional (QTP), Selenium, SAP TAO, ECATT, IBM Rational Functional Tester, WinRunner, and LoadRunner."
},
{
"code": null,
"e": 66179,
"s": 65972,
"text": "The different stages that come under Software Testing Life Cycle are β Requirements phase, Test Planning, Test Analysis, Test Design Phase, Test Implementation, Test Execution Phase, and Test Closure Phase."
},
{
"code": null,
"e": 66370,
"s": 66179,
"text": "Unit testing is used to test the functionality of various components in a SAP system. It is performed by domain and configuration experts who know the functionality of each unit in a system."
},
{
"code": null,
"e": 66676,
"s": 66370,
"text": "Example β To create a sales order and to save it. To perform Unit testing for this task, tester should know that the sales order can be saved using the SAP organization elements like customer master data, partner functions, material master data, company code, credit control area, sales organization, etc."
},
{
"code": null,
"e": 66845,
"s": 66676,
"text": "Unit testing is used to test functionality of pieces in SAP system. It is performed by domain and configuration expert who knows functionality of each unit in a system."
},
{
"code": null,
"e": 67151,
"s": 66845,
"text": "Example β To create a sales order and to save it. To perform Unit testing for this task, tester should know that the sales order can be saved using the SAP organization elements like customer master data, partner functions, material master data, company code, credit control area, sales organization, etc."
},
{
"code": null,
"e": 67306,
"s": 67151,
"text": "System Testing involves integration of elements of SAP system to ensure that related SAP functionality are linked together in the development environment."
},
{
"code": null,
"e": 67688,
"s": 67306,
"text": "Example β If you say a Cash flow for a quotation in an organization would show that a quote can be used to create a sales order, a delivery can be created and processed from the order, the delivery can be billed, the billing released to accounting, and a customer payment applied against the accounting invoice. Each unit is tested like this and then the test results are combined."
},
{
"code": null,
"e": 67779,
"s": 67688,
"text": "Scenario-based testing, as the name suggests, is performed as per specific business cases."
},
{
"code": null,
"e": 67987,
"s": 67779,
"text": "Example β Suppose there are a few tasks that are specific to a customer segment or a given product line or a set of services. For these specific line of target, you have different scenarios you need to test."
},
{
"code": null,
"e": 68136,
"s": 67987,
"text": "This testing is also performed in the development environment, an argument can be made to say this is a test case you would cover in system testing."
},
{
"code": null,
"e": 68291,
"s": 68136,
"text": "In this testing, testing data is coming from a real data extraction source, conversion is done and load exercise and data is known to a business end user."
},
{
"code": null,
"e": 68517,
"s": 68291,
"text": "Example β Integration testing is used to present that the business process as designed and configured in SAP, runs using real world data. In addition the testing shows that interface triggers, reports, workflows are working."
},
{
"code": null,
"e": 68861,
"s": 68517,
"text": "Interface testing ensures that a business process on a SAP system runs automatically. Ideally interface testing involves larger testing activities as a project progresses. Interface testing shows that triggering works, the data selection is accurate and complete, data transfer is successful, and the receiver is able to consume the sent data."
},
{
"code": null,
"e": 69130,
"s": 68861,
"text": "SAP UAT is used to ensure that end-users are able to perform assigned job functions with the new system. The important aspect of this testing is to understand the business requirement and to ensure that the expected features, functions, and capabilities are available."
},
{
"code": null,
"e": 69245,
"s": 69130,
"text": "Performance testing identifies bottlenecks and coding inefficiencies in a SAP system. It is carried out to check β"
},
{
"code": null,
"e": 69324,
"s": 69245,
"text": "Whether the system response time is acceptable as per the business requirement"
},
{
"code": null,
"e": 69387,
"s": 69324,
"text": "Whether periodic processes are running within permissible time"
},
{
"code": null,
"e": 69446,
"s": 69387,
"text": "Whether the expected concurrent user load can be supported"
},
{
"code": null,
"e": 69616,
"s": 69446,
"text": "Security and Authorizations Testing is used to ensure that the users are only able to execute transactions and access appropriate data that is relevant to their project."
},
{
"code": null,
"e": 69858,
"s": 69616,
"text": "As with the implementation of Security standards, this is really important to test if security and authorization is placed in a system. Test IDs for job roles are created and used to both confirm what a user can do and what a user cannot do."
},
{
"code": null,
"e": 70176,
"s": 69858,
"text": "This testing is usually performed once in a project lifecycle. The term βcutoverβ means a full scale execution of the all tasks involved to extract data from legacy systems and then to perform any kind of data conversion, load the results into the SAP system and fully validate the results, including a user sign-off."
},
{
"code": null,
"e": 70450,
"s": 70176,
"text": "SAP Regression Testing is used to find new functionalities and to test the old functionalities in a system when it is upgraded or a new system is set up. The key role of regression testing is to test the existing functionality and newly updated configuration and code base."
},
{
"code": null,
"e": 70658,
"s": 70450,
"text": "When you upgrade your SAP system or apply a patch, it shouldnβt affect the functionality that is expected to be performed by users and to check new features that are supposed to be introduced in new release."
},
{
"code": null,
"e": 70797,
"s": 70658,
"text": "SAP testing navigation ensures that you cover each module of your SAP system and at least one test to be performed for each functionality."
},
{
"code": null,
"e": 70955,
"s": 70797,
"text": "It also reduces the manual testing effort and covers most of the testing paths in a SAP system. OPA tests can be performed to check SAP Testing - Navigation."
},
{
"code": null,
"e": 71183,
"s": 70955,
"text": "Screen flow logic in SAP Testing is like an ABAP code and it is used to contain the processing blocks. It contains procedural part of screen and is created in screen painter and this screen painter is similar to an ABAP editor."
},
{
"code": null,
"e": 71290,
"s": 71183,
"text": "Financial Modules β Finance Accounting and Controlling (FICO), Treasure (TR), and Enterprise Control (EC)."
},
{
"code": null,
"e": 71419,
"s": 71290,
"text": "Logistics Modules β Material Management (MM), Plant Maintenance (PM), Sales and Distribution (SD), Quality Management (QM), etc."
},
{
"code": null,
"e": 71515,
"s": 71419,
"text": "Human Resource Management β Accounting Payroll, Time Management, Training and Event Management."
},
{
"code": null,
"e": 71715,
"s": 71515,
"text": "SAP Test-cases are required to perform a check on the installation and configuration of SAP system, any new implementation, Multilanguage and device testing, intranet testing, real-time testing, etc."
},
{
"code": null,
"e": 71902,
"s": 71715,
"text": "Since an ERP system is a common centralized system and is used by multiple users simultaneously in real time, it creates a need to write the test cases with lot of effort and dedication."
},
{
"code": null,
"e": 72138,
"s": 71902,
"text": "ERP systems also involve various FI transactions, so each test case should cover the scope of all the configuration and implementation part. Test data should be passed carefully and each test should have a column with name output data."
},
{
"code": null,
"e": 72395,
"s": 72138,
"text": "SAP Test Acceleration and Optimization TAO 2.0 is a tool that is used to create automatic test-cases during Regression testing of a system. It helps SAP customers to create different test components from the screens of a transaction and parameterizes them."
},
{
"code": null,
"e": 72601,
"s": 72395,
"text": "These test components are created normally for one transaction code and later can be combined to test scenarios. It can be easily integrated to the Business Process Change Analyzer in SAP Solution Manager."
},
{
"code": null,
"e": 72611,
"s": 72601,
"text": "RAM: 4 GB"
},
{
"code": null,
"e": 72635,
"s": 72611,
"text": "Free disk space: 500 MB"
},
{
"code": null,
"e": 72693,
"s": 72635,
"text": "LAN connection to SAP Quality Center QC server and SOLMAN"
},
{
"code": null,
"e": 72715,
"s": 72693,
"text": "Administration Rights"
},
{
"code": null,
"e": 72750,
"s": 72715,
"text": "SAPGUI with the latest patch level"
},
{
"code": null,
"e": 72780,
"s": 72750,
"text": "Microsoft Excel 97 or higher."
},
{
"code": null,
"e": 72827,
"s": 72780,
"text": "Microsoft Internet Explorer for CRM UI support"
},
{
"code": null,
"e": 73151,
"s": 72827,
"text": "Process Flow Analyzer is used to automatically find out the user interfaces used in transaction codes executed in a SAP system. It automatically creates the test components and upload them to Quality Center. It is also used to identify the sequence of test components as per user actions and creation of spreadsheet values."
},
{
"code": null,
"e": 73374,
"s": 73151,
"text": "Consolidate is known as a process to combine SAP TAO components with inbuilt components to create test scenarios as single transactional business components. It allows you to collect multiple test components into one test."
},
{
"code": null,
"e": 73615,
"s": 73374,
"text": "Go to SAP TAO and login and select SAP SOLMAN in the list. This list of system is SAP TAO is fetched from configuration file of SAP logon. So to add a system in SAP TAO, you need to add a new system in SAP Logon and refresh the list in TAO."
},
{
"code": null,
"e": 73663,
"s": 73615,
"text": "Enter the login credentials and click on logon."
},
{
"code": null,
"e": 73760,
"s": 73663,
"text": "SAP TAO will be connected to SAP Solution Manager and the TAO configuration wizard will open up."
},
{
"code": null,
"e": 73793,
"s": 73760,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 73807,
"s": 73793,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 73840,
"s": 73807,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 73852,
"s": 73840,
"text": " Neha Gupta"
},
{
"code": null,
"e": 73887,
"s": 73852,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 73902,
"s": 73887,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 73935,
"s": 73902,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 73950,
"s": 73935,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 73985,
"s": 73950,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 73997,
"s": 73985,
"text": " Neha Malik"
},
{
"code": null,
"e": 74032,
"s": 73997,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 74044,
"s": 74032,
"text": " Neha Malik"
},
{
"code": null,
"e": 74051,
"s": 74044,
"text": " Print"
},
{
"code": null,
"e": 74062,
"s": 74051,
"text": " Add Notes"
}
] |
C++ Program to Implement Euler Theorem | This is a C++ Program which demonstrates the implementation of Euler Theorem. The number and modular must be coprime for the modular multiplicative inverse to exist.
Begin
Take input to find modular multiplicative inverse
Take input as modular value
Perform inverse array function:
modInverse(x + 1, 0);
modInverse[1] = 1;
for i = 2 to x
modInverse[i] = (-(y / i) * modInverse[y mod i]) mod y + y
return modInverse
End
#include <iostream>
#include <vector>
using namespace std;
vector<int> inverseArray(int x, int y) {
vector<int> modInverse(x + 1, 0);
modInverse[1] = 1;
for (int i = 2; i <= x; i++) {
modInverse[i] = (-(y / i) * modInverse[y % i]) % y + y;
}
return modInverse;
}
int main() {
vector<int>::iterator it;
int a, m;
cout<<"Enter number to find modular multiplicative inverse: ";
cin>>a;
cout<<"Enter Modular Value: ";
cin>>m;
cout<<inverseArray(a, m)[a]<<endl;
}
Enter number to find modular multiplicative inverse: 26
Enter Modular Value: 7
7 | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "This is a C++ Program which demonstrates the implementation of Euler Theorem. The number and modular must be coprime for the modular multiplicative inverse to exist."
},
{
"code": null,
"e": 1508,
"s": 1228,
"text": "Begin\n Take input to find modular multiplicative inverse\n Take input as modular value\n Perform inverse array function:\n modInverse(x + 1, 0);\n modInverse[1] = 1;\n for i = 2 to x\n modInverse[i] = (-(y / i) * modInverse[y mod i]) mod y + y\n return modInverse\nEnd"
},
{
"code": null,
"e": 2009,
"s": 1508,
"text": "#include <iostream>\n#include <vector>\nusing namespace std;\nvector<int> inverseArray(int x, int y) {\n vector<int> modInverse(x + 1, 0);\n modInverse[1] = 1;\n for (int i = 2; i <= x; i++) {\n modInverse[i] = (-(y / i) * modInverse[y % i]) % y + y;\n }\n return modInverse;\n}\nint main() {\n vector<int>::iterator it;\n int a, m;\n cout<<\"Enter number to find modular multiplicative inverse: \";\n cin>>a;\n cout<<\"Enter Modular Value: \";\n cin>>m;\n cout<<inverseArray(a, m)[a]<<endl;\n}"
},
{
"code": null,
"e": 2090,
"s": 2009,
"text": "Enter number to find modular multiplicative inverse: 26\nEnter Modular Value: 7\n7"
}
] |
EJB - Timer Service | Timer Service is a mechanism by which scheduled application can be build. For example, salary slip generation on the 1st of every month. EJB 3.0 specification has specified @Timeout annotation, which helps in programming the EJB service in a stateless or message driven bean. EJB Container calls the method, which is annotated by @Timeout.
EJB Timer Service is a service provided by EJB container, which helps to create timer and to schedule callback when timer expires.
Inject SessionContext in bean using @Resource annotation β
@Stateless
public class TimerSessionBean {
@Resource
private SessionContext context;
...
}
Use SessionContext object to get TimerService and to create timer. Pass time in milliseconds and message.
public void createTimer(long duration) {
context.getTimerService().createTimer(duration, "Hello World!");
}
Use @Timeout annotation to a method. Return type should be void and pass a parameter of type Timer. We are canceling the timer after first execution otherwise it will keep running after fix intervals.
@Timeout
public void timeOutHandler(Timer timer) {
System.out.println("timeoutHandler : " + timer.getInfo());
timer.cancel();
}
Let us create a test EJB application to test Timer Service in EJB.
Create a project with a name EjbComponent under a package com.tutorialspoint.timer as explained in the EJB - Create Application chapter.
Create TimerSessionBean.java and TimerSessionBeanRemote as explained in the EJB - Create Application chapter. Keep rest of the files unchanged.
Clean and Build the application to make sure business logic is working as per the requirements.
Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet.
Now create the EJB client, a console based application in the same way as explained in the EJB - Create Application chapter under topic Create Client to access EJB.
package com.tutorialspoint.timer;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Timer;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
@Stateless
public class TimerSessionBean implements TimerSessionBeanRemote {
@Resource
private SessionContext context;
public void createTimer(long duration) {
context.getTimerService().createTimer(duration, "Hello World!");
}
@Timeout
public void timeOutHandler(Timer timer) {
System.out.println("timeoutHandler : " + timer.getInfo());
timer.cancel();
}
}
package com.tutorialspoint.timer;
import javax.ejb.Remote;
@Remote
public interface TimerSessionBeanRemote {
public void createTimer(long milliseconds);
}
As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log.
As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log.
JBoss has automatically created a JNDI entry for our session bean β TimerSessionBean/remote.
JBoss has automatically created a JNDI entry for our session bean β TimerSessionBean/remote.
We will using this lookup string to get remote business object of type β
com.tutorialspoint.timer.TimerSessionBeanRemote
We will using this lookup string to get remote business object of type β
com.tutorialspoint.timer.TimerSessionBeanRemote
...
16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
TimerSessionBean/remote - EJB3.x Default Remote Business Interface
TimerSessionBean/remote-com.tutorialspoint.timer.TimerSessionBeanRemote - EJB3.x Remote Business Interface
16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=TimerSessionBean,service=EJB3
16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.timer.TimerSessionBeanRemote ejbName: TimerSessionBean
...
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost
These properties are used to initialize the InitialContext object of java naming service.
These properties are used to initialize the InitialContext object of java naming service.
InitialContext object will be used to lookup stateless session bean.
InitialContext object will be used to lookup stateless session bean.
package com.tutorialspoint.test;
import com.tutorialspoint.stateful.TimerSessionBeanRemote;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class EJBTester {
BufferedReader brConsoleReader = null;
Properties props;
InitialContext ctx;
{
props = new Properties();
try {
props.load(new FileInputStream("jndi.properties"));
} catch (IOException ex) {
ex.printStackTrace();
}
try {
ctx = new InitialContext(props);
} catch (NamingException ex) {
ex.printStackTrace();
}
brConsoleReader =
new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) {
EJBTester ejbTester = new EJBTester();
ejbTester.testTimerService();
}
private void showGUI() {
System.out.println("**********************");
System.out.println("Welcome to Book Store");
System.out.println("**********************");
System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");
}
private void testTimerService() {
try {
TimerSessionBeanRemote timerServiceBean = (TimerSessionBeanRemote)ctx.lookup("TimerSessionBean/remote");
System.out.println("["+(new Date()).toString()+ "]" + "timer created.");
timerServiceBean.createTimer(2000);
} catch (NamingException ex) {
ex.printStackTrace();
}
}
}
EJBTester is doing the following tasks.
Load properties from jndi.properties and initialize the InitialContext object.
Load properties from jndi.properties and initialize the InitialContext object.
In testTimerService() method, jndi lookup is done with the name - "TimerSessionBean/remote" to obtain the remote business object (timer stateless EJB).
In testTimerService() method, jndi lookup is done with the name - "TimerSessionBean/remote" to obtain the remote business object (timer stateless EJB).
Then createTimer is invoked passing 2000 milliseconds as schedule time.
Then createTimer is invoked passing 2000 milliseconds as schedule time.
EJB Container calls the timeoutHandler method after 2 seconds.
EJB Container calls the timeoutHandler method after 2 seconds.
Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file.
Verify the following output in Netbeans console.
run:
[Wed Jun 19 11:35:47 IST 2013]timer created.
BUILD SUCCESSFUL (total time: 0 seconds)
You can find the following callback entries in JBoss log
...
11:35:49,555 INFO [STDOUT] timeoutHandler : Hello World!
...
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2387,
"s": 2047,
"text": "Timer Service is a mechanism by which scheduled application can be build. For example, salary slip generation on the 1st of every month. EJB 3.0 specification has specified @Timeout annotation, which helps in programming the EJB service in a stateless or message driven bean. EJB Container calls the method, which is annotated by @Timeout."
},
{
"code": null,
"e": 2518,
"s": 2387,
"text": "EJB Timer Service is a service provided by EJB container, which helps to create timer and to schedule callback when timer expires."
},
{
"code": null,
"e": 2577,
"s": 2518,
"text": "Inject SessionContext in bean using @Resource annotation β"
},
{
"code": null,
"e": 2678,
"s": 2577,
"text": "@Stateless\npublic class TimerSessionBean {\n\n @Resource\n private SessionContext context;\n ...\n}"
},
{
"code": null,
"e": 2784,
"s": 2678,
"text": "Use SessionContext object to get TimerService and to create timer. Pass time in milliseconds and message."
},
{
"code": null,
"e": 2895,
"s": 2784,
"text": "public void createTimer(long duration) {\n context.getTimerService().createTimer(duration, \"Hello World!\");\n}"
},
{
"code": null,
"e": 3096,
"s": 2895,
"text": "Use @Timeout annotation to a method. Return type should be void and pass a parameter of type Timer. We are canceling the timer after first execution otherwise it will keep running after fix intervals."
},
{
"code": null,
"e": 3238,
"s": 3096,
"text": "@Timeout\npublic void timeOutHandler(Timer timer) {\n System.out.println(\"timeoutHandler : \" + timer.getInfo()); \n timer.cancel();\n}"
},
{
"code": null,
"e": 3305,
"s": 3238,
"text": "Let us create a test EJB application to test Timer Service in EJB."
},
{
"code": null,
"e": 3442,
"s": 3305,
"text": "Create a project with a name EjbComponent under a package com.tutorialspoint.timer as explained in the EJB - Create Application chapter."
},
{
"code": null,
"e": 3586,
"s": 3442,
"text": "Create TimerSessionBean.java and TimerSessionBeanRemote as explained in the EJB - Create Application chapter. Keep rest of the files unchanged."
},
{
"code": null,
"e": 3682,
"s": 3586,
"text": "Clean and Build the application to make sure business logic is working as per the requirements."
},
{
"code": null,
"e": 3849,
"s": 3682,
"text": "Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet."
},
{
"code": null,
"e": 4014,
"s": 3849,
"text": "Now create the EJB client, a console based application in the same way as explained in the EJB - Create Application chapter under topic Create Client to access EJB."
},
{
"code": null,
"e": 4602,
"s": 4014,
"text": "package com.tutorialspoint.timer;\n\nimport javax.annotation.Resource;\nimport javax.ejb.SessionContext;\nimport javax.ejb.Timer;\nimport javax.ejb.Stateless;\nimport javax.ejb.Timeout;\n\n@Stateless\npublic class TimerSessionBean implements TimerSessionBeanRemote {\n\n @Resource\n private SessionContext context;\n\n public void createTimer(long duration) {\n context.getTimerService().createTimer(duration, \"Hello World!\");\n }\n\n @Timeout\n public void timeOutHandler(Timer timer) {\n System.out.println(\"timeoutHandler : \" + timer.getInfo()); \n timer.cancel();\n }\n}"
},
{
"code": null,
"e": 4762,
"s": 4602,
"text": "package com.tutorialspoint.timer;\n\nimport javax.ejb.Remote;\n\n@Remote\npublic interface TimerSessionBeanRemote {\n public void createTimer(long milliseconds);\n}"
},
{
"code": null,
"e": 4841,
"s": 4762,
"text": "As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log."
},
{
"code": null,
"e": 4920,
"s": 4841,
"text": "As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log."
},
{
"code": null,
"e": 5013,
"s": 4920,
"text": "JBoss has automatically created a JNDI entry for our session bean β TimerSessionBean/remote."
},
{
"code": null,
"e": 5106,
"s": 5013,
"text": "JBoss has automatically created a JNDI entry for our session bean β TimerSessionBean/remote."
},
{
"code": null,
"e": 5230,
"s": 5106,
"text": "We will using this lookup string to get remote business object of type β\n com.tutorialspoint.timer.TimerSessionBeanRemote "
},
{
"code": null,
"e": 5354,
"s": 5230,
"text": "We will using this lookup string to get remote business object of type β\n com.tutorialspoint.timer.TimerSessionBeanRemote "
},
{
"code": null,
"e": 5877,
"s": 5354,
"text": "...\n16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:\n TimerSessionBean/remote - EJB3.x Default Remote Business Interface\n TimerSessionBean/remote-com.tutorialspoint.timer.TimerSessionBeanRemote - EJB3.x Remote Business Interface\n16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=TimerSessionBean,service=EJB3\n16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.timer.TimerSessionBeanRemote ejbName: TimerSessionBean\n... \n"
},
{
"code": null,
"e": 6045,
"s": 5877,
"text": "java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory\njava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces\njava.naming.provider.url=localhost"
},
{
"code": null,
"e": 6135,
"s": 6045,
"text": "These properties are used to initialize the InitialContext object of java naming service."
},
{
"code": null,
"e": 6225,
"s": 6135,
"text": "These properties are used to initialize the InitialContext object of java naming service."
},
{
"code": null,
"e": 6294,
"s": 6225,
"text": "InitialContext object will be used to lookup stateless session bean."
},
{
"code": null,
"e": 6363,
"s": 6294,
"text": "InitialContext object will be used to lookup stateless session bean."
},
{
"code": null,
"e": 8031,
"s": 6363,
"text": "package com.tutorialspoint.test;\n \nimport com.tutorialspoint.stateful.TimerSessionBeanRemote;\nimport java.io.BufferedReader;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.List;\nimport java.util.Properties;\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\n\npublic class EJBTester {\n\n BufferedReader brConsoleReader = null; \n Properties props;\n InitialContext ctx;\n {\n props = new Properties();\n try {\n props.load(new FileInputStream(\"jndi.properties\"));\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n try {\n ctx = new InitialContext(props); \n } catch (NamingException ex) {\n ex.printStackTrace();\n }\n brConsoleReader = \n new BufferedReader(new InputStreamReader(System.in));\n }\n \n public static void main(String[] args) {\n\n EJBTester ejbTester = new EJBTester();\n\n ejbTester.testTimerService();\n }\n \n private void showGUI() {\n System.out.println(\"**********************\");\n System.out.println(\"Welcome to Book Store\");\n System.out.println(\"**********************\");\n System.out.print(\"Options \\n1. Add Book\\n2. Exit \\nEnter Choice: \");\n }\n \n private void testTimerService() {\n try {\n TimerSessionBeanRemote timerServiceBean = (TimerSessionBeanRemote)ctx.lookup(\"TimerSessionBean/remote\");\n\n System.out.println(\"[\"+(new Date()).toString()+ \"]\" + \"timer created.\");\n timerServiceBean.createTimer(2000); \n\n } catch (NamingException ex) {\n ex.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 8071,
"s": 8031,
"text": "EJBTester is doing the following tasks."
},
{
"code": null,
"e": 8150,
"s": 8071,
"text": "Load properties from jndi.properties and initialize the InitialContext object."
},
{
"code": null,
"e": 8229,
"s": 8150,
"text": "Load properties from jndi.properties and initialize the InitialContext object."
},
{
"code": null,
"e": 8381,
"s": 8229,
"text": "In testTimerService() method, jndi lookup is done with the name - \"TimerSessionBean/remote\" to obtain the remote business object (timer stateless EJB)."
},
{
"code": null,
"e": 8533,
"s": 8381,
"text": "In testTimerService() method, jndi lookup is done with the name - \"TimerSessionBean/remote\" to obtain the remote business object (timer stateless EJB)."
},
{
"code": null,
"e": 8605,
"s": 8533,
"text": "Then createTimer is invoked passing 2000 milliseconds as schedule time."
},
{
"code": null,
"e": 8677,
"s": 8605,
"text": "Then createTimer is invoked passing 2000 milliseconds as schedule time."
},
{
"code": null,
"e": 8740,
"s": 8677,
"text": "EJB Container calls the timeoutHandler method after 2 seconds."
},
{
"code": null,
"e": 8803,
"s": 8740,
"text": "EJB Container calls the timeoutHandler method after 2 seconds."
},
{
"code": null,
"e": 8898,
"s": 8803,
"text": "Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file."
},
{
"code": null,
"e": 8947,
"s": 8898,
"text": "Verify the following output in Netbeans console."
},
{
"code": null,
"e": 9039,
"s": 8947,
"text": "run:\n[Wed Jun 19 11:35:47 IST 2013]timer created.\nBUILD SUCCESSFUL (total time: 0 seconds)\n"
},
{
"code": null,
"e": 9096,
"s": 9039,
"text": "You can find the following callback entries in JBoss log"
},
{
"code": null,
"e": 9163,
"s": 9096,
"text": "...\n11:35:49,555 INFO [STDOUT] timeoutHandler : Hello World!\n...\n"
},
{
"code": null,
"e": 9170,
"s": 9163,
"text": " Print"
},
{
"code": null,
"e": 9181,
"s": 9170,
"text": " Add Notes"
}
] |
Subtracting a day in MySQL | To subtract a day in MySQL, use the DATE_SUB() method. Let us first create a table β
mysql> create table DemoTable
-> (
-> AdmissionDate timestamp
-> );
Query OK, 0 rows affected (1.05 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable values('2019-01-01');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('2018-12-31');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('2017-03-13');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('2019-01-02');
Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable;
This will produce the following output β
+---------------------+
| AdmissionDate |
+---------------------+
| 2019-01-01 00:00:00 |
| 2018-12-31 00:00:00 |
| 2017-03-13 00:00:00 |
| 2019-01-02 00:00:00 |
+---------------------+
4 rows in set (0.00 sec)
Here is the query to subtract a dayβ
mysql> select date_sub(AdmissionDate,interval 1 day) from DemoTable;
This will produce the following output β
+----------------------------------------+
| date_sub(AdmissionDate,interval 1 day) |
+----------------------------------------+
| 2018-12-31 00:00:00 |
| 2018-12-30 00:00:00 |
| 2017-03-12 00:00:00 |
| 2019-01-01 00:00:00 |
+----------------------------------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "To subtract a day in MySQL, use the DATE_SUB() method. Let us first create a table β"
},
{
"code": null,
"e": 1261,
"s": 1147,
"text": "mysql> create table DemoTable\n -> (\n -> AdmissionDate timestamp\n -> );\nQuery OK, 0 rows affected (1.05 sec)"
},
{
"code": null,
"e": 1317,
"s": 1261,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1665,
"s": 1317,
"text": "mysql> insert into DemoTable values('2019-01-01');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values('2018-12-31');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('2017-03-13');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values('2019-01-02');\nQuery OK, 1 row affected (0.08 sec)"
},
{
"code": null,
"e": 1725,
"s": 1665,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1756,
"s": 1725,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1797,
"s": 1756,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2014,
"s": 1797,
"text": "+---------------------+\n| AdmissionDate |\n+---------------------+\n| 2019-01-01 00:00:00 |\n| 2018-12-31 00:00:00 |\n| 2017-03-13 00:00:00 |\n| 2019-01-02 00:00:00 |\n+---------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2051,
"s": 2014,
"text": "Here is the query to subtract a dayβ"
},
{
"code": null,
"e": 2120,
"s": 2051,
"text": "mysql> select date_sub(AdmissionDate,interval 1 day) from DemoTable;"
},
{
"code": null,
"e": 2161,
"s": 2120,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2530,
"s": 2161,
"text": "+----------------------------------------+\n| date_sub(AdmissionDate,interval 1 day) |\n+----------------------------------------+\n| 2018-12-31 00:00:00 |\n| 2018-12-30 00:00:00 |\n| 2017-03-12 00:00:00 |\n| 2019-01-01 00:00:00 |\n+----------------------------------------+\n4 rows in set (0.00 sec)"
}
] |
Powershell - Quick Guide | Windows PowerShell is a command-line shell and scripting language designed especially for system administration. It's analogue in Linux is called as Bash Scripting. Built on the .NET Framework, Windows PowerShell helps IT professionals to control and automate the administration of the Windows operating system and applications that run on Windows Server environment.
Windows PowerShell commands, called cmdlets, let you manage the computers from the command line. Windows PowerShell providers let you access data stores, such as the Registry and Certificate Store, as easily as you access the file system.
In addition, Windows PowerShell has a rich expression parser and a fully developed scripting language. So in simple words you can complete all the tasks that you do with GUI and much more.
The Windows PowerShell Integrated Scripting Environment (ISE) is a host application for Windows PowerShell. In Windows PowerShell ISE, you can run commands and write, test, and debug scripts in a single Windows-based graphic user interface with multiline editing, tab completion, syntax coloring, selective execution, context-sensitive help, and support for right-to-left languages.
You can use menu items and keyboard shortcuts to perform many of the same tasks that you would perform in the Windows PowerShell console. For example, when you debug a script in the Windows PowerShell ISE, to set a line breakpoint in a script, right-click the line of code, and then click Toggle Breakpoint.
There are a lot of PowerShell commands and it is very difficult to put in all these commands in this tutorial, we will focus on some of the most important as well as basic commands of PowerShell.
The first step is to go to the Get-Help command which gives you an explanation about how to give a command and its parameter.
PowerShell Icon can be found in the task bar and in the start menu. Just by clicking on the icon, it will open.
To open it, just click on the icon and then the following screen will open and it means that PowerShell is ready for you to work on.
The latest version of PowerShell is 5.0 and to check what is installed in our server we type the following command β :$PSVersionTable as shown in the following screenshot and from the screen we also know that we have PSVersion 4.0
To update with the latest version where it has more Cmdlets we have to download Windows Management Framework 5.0 from the following link β https://www.microsoft.com/en-us/download/details.aspx?id=50395 and install it.
The Windows PowerShell Integrated Scripting Environment (ISE) is a host application for Windows PowerShell. In Windows PowerShell ISE, you can run commands and write, test, and debug scripts in a single Windows-based graphic user interface with multiline editing, tab completion, syntax coloring, selective execution, context-sensitive help, and support for right-to-left languages.
You can use menu items and keyboard shortcuts to perform many of the same tasks that you would perform in the Windows PowerShell console. For example, when you debug a script in the Windows PowerShell ISE, to set a line breakpoint in a script, right-click the line of code, and then click Toggle Breakpoint.
To open it you just go to Start - Search and then Type - PowerShell as shown in the following screenshot.
Then click on Windows PowerShell ISE. Or click on the downward Arrow as shown in the following screenshot.
It will list all the applications installed on the server and then click on Windows PowerShell ISE.
The following table will be open β
It has three sections, which include - The PowerShell Console with number 1, then Scripting File number 2 and the third is the Command Module where you can find the module.
While creating the script you can run directly and see the result like the following example β
There are a lot of PowerShell commands and it is very difficult to put in all these commands in this tutorial, we will focus on some of the most important as well as basic commands of PowerShell.
The first step is to go to the Get-Help command which gives you an explanation about how to give a command and its parameter.
To get the list of Updates β
Get-HotFix and to install a hot fix as follows
Get-HotFix -id kb2741530
A cmdlet or "Command let" is a lightweight command used in the Windows PowerShell environment. The Windows PowerShell runtime invokes these cmdlets at command prompt. You can create and invoke them programmatically through Windows PowerShell APIs.
Cmdlets are way different from commands in other command-shell environments in the following manners β
Cmdlets are .NET Framework class objects; and not just stand-alone executables.
Cmdlets are .NET Framework class objects; and not just stand-alone executables.
Cmdlets can be easily constructed from as few as a dozen lines of code.
Cmdlets can be easily constructed from as few as a dozen lines of code.
Parsing, error presentation, and output formatting are not handled by cmdlets. It is done by the Windows PowerShell runtime.
Parsing, error presentation, and output formatting are not handled by cmdlets. It is done by the Windows PowerShell runtime.
Cmdlets process works on objects not on text stream and objects can be passed as output for pipelining.
Cmdlets process works on objects not on text stream and objects can be passed as output for pipelining.
Cmdlets are record-based as they process a single object at a time.
Cmdlets are record-based as they process a single object at a time.
The first step is to go to the Get-Help command which gives you an explanation about how to give a command and its parameter.
Following are the examples of powershell scripts on Files and Folders.
Example Script to show how to create folder(s) using PowerShell scripts.
Example Script to show how to create file(s) using PowerShell scripts.
Example Script to show how to copy file(s) using PowerShell scripts.
Example Script to show how to create file(s) using PowerShell scripts.
Example Script to show how to delete folder(s) using PowerShell scripts.
Example Script to show how to delete file(s) using PowerShell scripts.
Example Script to show how to move folder(s) using PowerShell scripts.
Example Script to show how to move file(s) using PowerShell scripts.
Example Script to show how to rename folder(s) using PowerShell scripts.
Example Script to show how to rename file(s) using PowerShell scripts.
Example Script to show how to retrieve item(s) using PowerShell scripts.
Example Script to show how to check folder existence using PowerShell scripts.
Example Script to show how to check file existence using PowerShell scripts.
Following are the examples of powershell scripts on System Date and Time.
Example Script to show how to get system date using PowerShell scripts.
Example Script to show how to set system date using PowerShell scripts.
Example Script to show how to get system time using PowerShell scripts.
Example Script to show how to set system time using PowerShell scripts.
Following are the examples of powershell scripts of creating and reading different types of files.
Example Script to show how to create a text file using PowerShell scripts.
Example Script to show how to read a text file using PowerShell scripts.
Example Script to show how to create a XML file using PowerShell scripts.
Example Script to show how to read a XML file using PowerShell scripts.
Example Script to show how to create a CSV file using PowerShell scripts.
Example Script to show how to read a CSV file using PowerShell scripts.
Example Script to show how to create a HTML file using PowerShell scripts.
Example Script to show how to read a HTML file using PowerShell scripts.
Example Script to show how to erase file contents using PowerShell scripts.
Example Script to show how to append text to a file contents using PowerShell scripts.
A cmdlet or "Command let" is a lightweight command used in the Windows PowerShell environment. The Windows PowerShell runtime invokes these cmdlets at command prompt. You can create and invoke them programmatically through Windows PowerShell APIs. Following are advanced usage example of cmdlets.
Example program to showcase Get-Unique Cmdlet.
Group-Object Cmdlet
Example program to showcase Group-Object Cmdlet.
Example program to showcase Measure-Object Cmdlet.
Example program to showcase Compare-Object Cmdlet.
Example program to showcase Format-List Cmdlet.
Example program to showcase Format-Wide Cmdlet.
Example program to showcase Where-Object Cmdlet.
Example program to showcase Get-ChildItem Cmdlet.
Example program to showcase ForEach-Object Cmdlet.
Example program to showcase Start-Sleep Cmdlet.
Example program to showcase Read-Host Cmdlet.
Example program to showcase Select-Object Cmdlet.
Example program to showcase Sort-Object Cmdlet.
Example program to showcase Write-Warning Cmdlet.
Example program to showcase Write-Host Cmdlet.
Example program to showcase Invoke-Item Cmdlet.
Example program to showcase Invoke-Expression Cmdlet.
Example program to showcase Measure-Command Cmdlet.
Example program to showcase Invoke-History Cmdlet.
Example program to showcase Add-History Cmdlet.
Example program to showcase Get-History Cmdlet.
Example program to showcase Get-Culture Cmdlet.
Windows PowerShell is a command-line shell and scripting language designed especially for system administration. Its analogue in Linux is called as Bash Scripting. Built on the .NET Framework, Windows PowerShell helps IT professionals to control and automate the administration of the Windows operating system and applications that run on Windows Server environment.
Windows PowerShell commands, called cmdlets, let you manage the computers from the command line. Windows PowerShell providers let you access data stores, such as the Registry and Certificate Store, as easily as you access the file system.
In addition, Windows PowerShell has a rich expression parser and a fully developed scripting language. So in simple words you can complete all the tasks that you do with GUI and much more. Windows PowerShell Scripting is a fully developed scripting language and has a rich expression parser/
Cmdlets β Cmdlets perform common system administration tasks, for example managing the registry, services, processes, event logs, and using Windows Management Instrumentation (WMI).
Cmdlets β Cmdlets perform common system administration tasks, for example managing the registry, services, processes, event logs, and using Windows Management Instrumentation (WMI).
Task oriented β PowerShell scripting language is task based and provide supports for existing scripts and command-line tools.
Task oriented β PowerShell scripting language is task based and provide supports for existing scripts and command-line tools.
Consistent design β As cmdlets and system data stores use common syntax and have common naming conventions, data sharing is easy. The output from one cmdlet can be pipelined to another cmdlet without any manipulation.
Consistent design β As cmdlets and system data stores use common syntax and have common naming conventions, data sharing is easy. The output from one cmdlet can be pipelined to another cmdlet without any manipulation.
Simple to Use β Simplified, command-based navigation lets users navigate the registry and other data stores similar to the file system navigation.
Simple to Use β Simplified, command-based navigation lets users navigate the registry and other data stores similar to the file system navigation.
Object based β PowerShell possesses powerful object manipulation capabilities. Objects can be sent to other tools or databases directly.
Object based β PowerShell possesses powerful object manipulation capabilities. Objects can be sent to other tools or databases directly.
Extensible interface. β PowerShell is customizable as independent software vendors and enterprise developers can build custom tools and utilities using PowerShell to administer their software.
Extensible interface. β PowerShell is customizable as independent software vendors and enterprise developers can build custom tools and utilities using PowerShell to administer their software.
PowerShell variables are named objects. As PowerShell works with objects, these variables are used to work with objects.
Variable name should start with $ and can contain alphanumeric characters and underscore in their names. A variable can be created by typing a valid variable name.
Type the following command in PowerShell ISE Console. Assuming you are in D:\test folder.
$location = Get-Location
Here we've created a variable $location and assigned it the output of Get-Location cmdlet. It now contains the current location.
Type the following command in PowerShell ISE Console.
$location
You can see following output in PowerShell console.
Path
----
D:\test
Get-Member cmdlet can tell the type of variable being used. See the example below.
$location | Get-Member
You can see following output in PowerShell console.
TypeName: System.Management.Automation.PathInfo
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Drive Property System.Management.Automation.PSDriveInfo Drive {get;}
Path Property System.String Path {get;}
Provider Property System.Management.Automation.ProviderInfo Provider {get;}
ProviderPath Property System.String ProviderPath {get;}
PowerShell Special variables store information about PowerShell. These are also called automatic variables. Following is the list of automatic variables β
PowerShell provides a rich set of operators to manipulate variables. We can divide all the PowerShell operators into the following groups β
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Redirectional Operators
Spilt and Join Operators
Type Operators
Unary Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators β
Assume integer variable A holds 10 and variable B holds 20, then β
Show Examples
Following are the assignment operators supported by PowerShell language β
Assume integer variable A holds 10 and variable B holds 20, then β
Show Examples
Following are the assignment operators supported by PowerShell language β
Show Examples
The following table lists the logical operators β
Assume Boolean variables A holds true and variable B holds false, then β
Show Examples
Following are various important operators supported by PowerShell language β
Show Examples
There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages β
PowerShell programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Enhanced for loop. This is mainly used to traverse collection of elements including arrays.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Like a while statement, except that it tests the condition at the end of the loop body.
Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages β
PowerShell scripting language provides following types of decision making statements. Click the following links to check their detail.
An if statement consists of a boolean expression followed by one or more statements.
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
You can use one if or elseif statement inside another if or elseif statement(s).
A switch statement allows a variable to be tested for equality against a list of values.
PowerShell provides a data structure, the array, which stores a fixed-size sequential collection of elements of the any type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables or objects.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.
To use an array in a program, you must declare a variable to reference the array, and you can specify the type of array the variable can reference. Here is the syntax for declaring an array variable β
$A = 1, 2, 3, 4
or
$A = 1..4
Note β By default type of objects of array is System.Object. GetType() method returns the type of the array. Type can be passed.
The following code snippets are examples of this syntax β
[int32[]]$intA = 1500,2230,3350,4000
$A = 1, 2, 3, 4
$A.getType()
This will produce the following result β
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList β
$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123
Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.
When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.
Here is a complete example showing how to create, initialize, and process arrays β
$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123
write-host("Print all the array elements")
$myList
write-host("Get the length of array")
$myList.Length
write-host("Get Second element of array")
$myList[1]
write-host("Get partial array")
$subList = $myList[1..3]
write-host("print subList")
$subList
write-host("using for loop")
for ($i = 0; $i -le ($myList.length - 1); $i += 1) {
$myList[$i]
}
write-host("using forEach Loop")
foreach ($element in $myList) {
$element
}
write-host("using while Loop")
$i = 0
while($i -lt 4) {
$myList[$i];
$i++
}
write-host("Assign values")
$myList[1] = 10
$myList
This will produce the following result β
Print all the array elements
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
Get the length of array
10
Get Second element of array
4.5
Get partial array
print subList
4.5
3.3
13.2
using for loop
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
using forEach Loop
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
using while Loop
5.6
4.5
3.3
13.2
Assign values
5.6
10
3.3
13.2
4
34.33
34
45.45
99.993
11123
Here is a complete example showing operations on arrays using its methods
$myList = @(0..4)
write-host("Print array")
$myList
$myList = @(0..4)
write-host("Assign values")
$myList[1] = 10
$myList
This will produce the following result β
Clear array
Print array
0
1
2
3
4
Assign values
0
10
2
3
4
Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. Generally we used String or numbers as keys.
This tutorial introduces how to declare hashtable variables, create hashtables, and process hashtable using its methods.
To use an hashtable in a program, you must declare a variable to reference the hashtable. Here is the syntax for declaring an hashtable variable β
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
or
$hash = @{}
Note β Ordered dictionaries can be created using similar syntax. Ordered dictionaries maintain the order in which entries are added whereas hashtables do not.
The following code snippets are examples of this syntax β
$hash = [ordered]@{ ID = 1; Shape = "Square"; Color = "Blue"}
Print the hashtable.
$hash
Name Value
---- -----
ID 1
Color Blue
Shape Square
The hashtable values are accessed through the keys.
> $hash["ID"]
1
Dot notation can be used to access hashtables keys or values.
> $hash.keys
ID
Color
Shape
> $hash.values
1
Blue
Square
Here is a complete example showing how to create, initialize, and process hashtable β
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
write-host("Print all hashtable keys")
$hash.keys
write-host("Print all hashtable values")
$hash.values
write-host("Get ID")
$hash["ID"]
write-host("Get Shape")
$hash.Number
write-host("print Size")
$hash.Count
write-host("Add key-value")
$hash["Updated"] = "Now"
write-host("Add key-value")
$hash.Add("Created","Now")
write-host("print Size")
$hash.Count
write-host("Remove key-value")
$hash.Remove("Updated")
write-host("print Size")
$hash.Count
write-host("sort by key")
$hash.GetEnumerator() | Sort-Object -Property key
This will produce the following result β
Print all hashtable keys
ID
Color
Shape
Print all hashtable values
1
Blue
Square
Get ID
1
Get Shape
print Size
3
Add key-value
Add key-value
print Size
5
Remove key-value
print Size
4
sort by key
Name Value
---- -----
Color Blue
Created Now
ID 1
Shape
Square
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data.
Here is the table listing down all the regular expression metacharacter syntax available in PowerShell β
Here is a complete examples showing how to use regex in PowerShell;
Example of supported regular expression characters.
Example of supported character classes.
Example of supported quantifiers.
Backtick (`) operator is also called word-wrap operator. It allows a command to be written in multiple lines. It can be used for new line (`n) or tab (`t) in sentences as well. See the examples below β
Get-Service * | Sort-Object ServiceType `
| Format-Table Name, ServiceType, Status -AutoSize
It will become
Get-Service * | Sort-Object ServiceType | Format-Table Name, ServiceType, Status -AutoSize
Verify the output as
Name ServiceType Status
---- ----------- ------
MSSQLServerADHelper100 Win32OwnProcess Stopped
ntrtscan Win32OwnProcess Running
...
Use of new line and tab.
> Write-host "Title Subtitle"
Title Subtitle
> Write-host "Title `nSubtitle"
Title
Subtitle
> Write-host "Title `tSubtitle"
Title Subtitle
Powershell supports three types of brackets.
Parenthesis brackets. β ()
Parenthesis brackets. β ()
Braces brackets. β {}
Braces brackets. β {}
Square brackets. β []
Square brackets. β []
This type of brackets is used to
pass arguments
pass arguments
enclose multiple set of instructions
enclose multiple set of instructions
resolve ambiguity
resolve ambiguity
create array
create array
> $array = @("item1", "item2", "item3")
> foreach ($element in $array) { $element }
item1
item2
item3
This type of brackets is used to
enclose statements
enclose statements
block commands
block commands
$x = 10
if($x -le 20){
write-host("This is if statement")
}
This will produce the following result β
This is if statement.
This type of brackets is used to
access to array
access to array
access to hashtables
access to hashtables
filter using regular expression
filter using regular expression
> $array = @("item1", "item2", "item3")
> for($i = 0; $i -lt $array.length; $i++){ $array[$i] }
item1
item2
item3
>Get-Process [r-s]*
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
320 72 27300 33764 227 3.95 4028 SCNotification
2298 77 57792 48712 308 2884 SearchIndexer
...
PowerShell alias is another name for the cmdlet or for any command element.
Use New-Alias cmdlet to create a alias. In the below example, we've created an alias help for Get-Help cmdlet.
New-Alias -Name help -Value Get-Help
Now invoke the alias.
help Get-WmiObject -Detailed
You will see the following output.
NAME
Get-WmiObject
SYNOPSIS
Gets instances of Windows Management Instrumentation (WMI) classes or information about the available classes.
SYNTAX
Get-WmiObject [
...
Use get-alias cmdlet to get all the alias present in current session of powershell.
Get-Alias
You will see the following output.
CommandType Name Definition
----------- ---- ----------
Alias % ForEach-Object
Alias ? Where-Object
Alias ac Add-Content
Alias asnp Add-PSSnapIn
...
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2402,
"s": 2034,
"text": "Windows PowerShell is a command-line shell and scripting language designed especially for system administration. It's analogue in Linux is called as Bash Scripting. Built on the .NET Framework, Windows PowerShell helps IT professionals to control and automate the administration of the Windows operating system and applications that run on Windows Server environment."
},
{
"code": null,
"e": 2641,
"s": 2402,
"text": "Windows PowerShell commands, called cmdlets, let you manage the computers from the command line. Windows PowerShell providers let you access data stores, such as the Registry and Certificate Store, as easily as you access the file system."
},
{
"code": null,
"e": 2830,
"s": 2641,
"text": "In addition, Windows PowerShell has a rich expression parser and a fully developed scripting language. So in simple words you can complete all the tasks that you do with GUI and much more."
},
{
"code": null,
"e": 3213,
"s": 2830,
"text": "The Windows PowerShell Integrated Scripting Environment (ISE) is a host application for Windows PowerShell. In Windows PowerShell ISE, you can run commands and write, test, and debug scripts in a single Windows-based graphic user interface with multiline editing, tab completion, syntax coloring, selective execution, context-sensitive help, and support for right-to-left languages."
},
{
"code": null,
"e": 3521,
"s": 3213,
"text": "You can use menu items and keyboard shortcuts to perform many of the same tasks that you would perform in the Windows PowerShell console. For example, when you debug a script in the Windows PowerShell ISE, to set a line breakpoint in a script, right-click the line of code, and then click Toggle Breakpoint."
},
{
"code": null,
"e": 3717,
"s": 3521,
"text": "There are a lot of PowerShell commands and it is very difficult to put in all these commands in this tutorial, we will focus on some of the most important as well as basic commands of PowerShell."
},
{
"code": null,
"e": 3843,
"s": 3717,
"text": "The first step is to go to the Get-Help command which gives you an explanation about how to give a command and its parameter."
},
{
"code": null,
"e": 3955,
"s": 3843,
"text": "PowerShell Icon can be found in the task bar and in the start menu. Just by clicking on the icon, it will open."
},
{
"code": null,
"e": 4088,
"s": 3955,
"text": "To open it, just click on the icon and then the following screen will open and it means that PowerShell is ready for you to work on."
},
{
"code": null,
"e": 4319,
"s": 4088,
"text": "The latest version of PowerShell is 5.0 and to check what is installed in our server we type the following command β :$PSVersionTable as shown in the following screenshot and from the screen we also know that we have PSVersion 4.0"
},
{
"code": null,
"e": 4537,
"s": 4319,
"text": "To update with the latest version where it has more Cmdlets we have to download Windows Management Framework 5.0 from the following link β https://www.microsoft.com/en-us/download/details.aspx?id=50395 and install it."
},
{
"code": null,
"e": 4920,
"s": 4537,
"text": "The Windows PowerShell Integrated Scripting Environment (ISE) is a host application for Windows PowerShell. In Windows PowerShell ISE, you can run commands and write, test, and debug scripts in a single Windows-based graphic user interface with multiline editing, tab completion, syntax coloring, selective execution, context-sensitive help, and support for right-to-left languages."
},
{
"code": null,
"e": 5228,
"s": 4920,
"text": "You can use menu items and keyboard shortcuts to perform many of the same tasks that you would perform in the Windows PowerShell console. For example, when you debug a script in the Windows PowerShell ISE, to set a line breakpoint in a script, right-click the line of code, and then click Toggle Breakpoint."
},
{
"code": null,
"e": 5334,
"s": 5228,
"text": "To open it you just go to Start - Search and then Type - PowerShell as shown in the following screenshot."
},
{
"code": null,
"e": 5441,
"s": 5334,
"text": "Then click on Windows PowerShell ISE. Or click on the downward Arrow as shown in the following screenshot."
},
{
"code": null,
"e": 5541,
"s": 5441,
"text": "It will list all the applications installed on the server and then click on Windows PowerShell ISE."
},
{
"code": null,
"e": 5576,
"s": 5541,
"text": "The following table will be open β"
},
{
"code": null,
"e": 5749,
"s": 5576,
"text": "It has three sections, which include - The PowerShell Console with number 1, then Scripting File number 2 and the third is the Command Module where you can find the module."
},
{
"code": null,
"e": 5844,
"s": 5749,
"text": "While creating the script you can run directly and see the result like the following example β"
},
{
"code": null,
"e": 6040,
"s": 5844,
"text": "There are a lot of PowerShell commands and it is very difficult to put in all these commands in this tutorial, we will focus on some of the most important as well as basic commands of PowerShell."
},
{
"code": null,
"e": 6166,
"s": 6040,
"text": "The first step is to go to the Get-Help command which gives you an explanation about how to give a command and its parameter."
},
{
"code": null,
"e": 6195,
"s": 6166,
"text": "To get the list of Updates β"
},
{
"code": null,
"e": 6242,
"s": 6195,
"text": "Get-HotFix and to install a hot fix as follows"
},
{
"code": null,
"e": 6267,
"s": 6242,
"text": "Get-HotFix -id kb2741530"
},
{
"code": null,
"e": 6515,
"s": 6267,
"text": "A cmdlet or \"Command let\" is a lightweight command used in the Windows PowerShell environment. The Windows PowerShell runtime invokes these cmdlets at command prompt. You can create and invoke them programmatically through Windows PowerShell APIs."
},
{
"code": null,
"e": 6618,
"s": 6515,
"text": "Cmdlets are way different from commands in other command-shell environments in the following manners β"
},
{
"code": null,
"e": 6698,
"s": 6618,
"text": "Cmdlets are .NET Framework class objects; and not just stand-alone executables."
},
{
"code": null,
"e": 6778,
"s": 6698,
"text": "Cmdlets are .NET Framework class objects; and not just stand-alone executables."
},
{
"code": null,
"e": 6850,
"s": 6778,
"text": "Cmdlets can be easily constructed from as few as a dozen lines of code."
},
{
"code": null,
"e": 6922,
"s": 6850,
"text": "Cmdlets can be easily constructed from as few as a dozen lines of code."
},
{
"code": null,
"e": 7047,
"s": 6922,
"text": "Parsing, error presentation, and output formatting are not handled by cmdlets. It is done by the Windows PowerShell runtime."
},
{
"code": null,
"e": 7172,
"s": 7047,
"text": "Parsing, error presentation, and output formatting are not handled by cmdlets. It is done by the Windows PowerShell runtime."
},
{
"code": null,
"e": 7277,
"s": 7172,
"text": "Cmdlets process works on objects not on text stream and objects can be passed as output for pipelining. "
},
{
"code": null,
"e": 7382,
"s": 7277,
"text": "Cmdlets process works on objects not on text stream and objects can be passed as output for pipelining. "
},
{
"code": null,
"e": 7450,
"s": 7382,
"text": "Cmdlets are record-based as they process a single object at a time."
},
{
"code": null,
"e": 7518,
"s": 7450,
"text": "Cmdlets are record-based as they process a single object at a time."
},
{
"code": null,
"e": 7644,
"s": 7518,
"text": "The first step is to go to the Get-Help command which gives you an explanation about how to give a command and its parameter."
},
{
"code": null,
"e": 7715,
"s": 7644,
"text": "Following are the examples of powershell scripts on Files and Folders."
},
{
"code": null,
"e": 7788,
"s": 7715,
"text": "Example Script to show how to create folder(s) using PowerShell scripts."
},
{
"code": null,
"e": 7859,
"s": 7788,
"text": "Example Script to show how to create file(s) using PowerShell scripts."
},
{
"code": null,
"e": 7928,
"s": 7859,
"text": "Example Script to show how to copy file(s) using PowerShell scripts."
},
{
"code": null,
"e": 7999,
"s": 7928,
"text": "Example Script to show how to create file(s) using PowerShell scripts."
},
{
"code": null,
"e": 8072,
"s": 7999,
"text": "Example Script to show how to delete folder(s) using PowerShell scripts."
},
{
"code": null,
"e": 8143,
"s": 8072,
"text": "Example Script to show how to delete file(s) using PowerShell scripts."
},
{
"code": null,
"e": 8214,
"s": 8143,
"text": "Example Script to show how to move folder(s) using PowerShell scripts."
},
{
"code": null,
"e": 8283,
"s": 8214,
"text": "Example Script to show how to move file(s) using PowerShell scripts."
},
{
"code": null,
"e": 8356,
"s": 8283,
"text": "Example Script to show how to rename folder(s) using PowerShell scripts."
},
{
"code": null,
"e": 8427,
"s": 8356,
"text": "Example Script to show how to rename file(s) using PowerShell scripts."
},
{
"code": null,
"e": 8500,
"s": 8427,
"text": "Example Script to show how to retrieve item(s) using PowerShell scripts."
},
{
"code": null,
"e": 8579,
"s": 8500,
"text": "Example Script to show how to check folder existence using PowerShell scripts."
},
{
"code": null,
"e": 8656,
"s": 8579,
"text": "Example Script to show how to check file existence using PowerShell scripts."
},
{
"code": null,
"e": 8730,
"s": 8656,
"text": "Following are the examples of powershell scripts on System Date and Time."
},
{
"code": null,
"e": 8802,
"s": 8730,
"text": "Example Script to show how to get system date using PowerShell scripts."
},
{
"code": null,
"e": 8874,
"s": 8802,
"text": "Example Script to show how to set system date using PowerShell scripts."
},
{
"code": null,
"e": 8946,
"s": 8874,
"text": "Example Script to show how to get system time using PowerShell scripts."
},
{
"code": null,
"e": 9018,
"s": 8946,
"text": "Example Script to show how to set system time using PowerShell scripts."
},
{
"code": null,
"e": 9117,
"s": 9018,
"text": "Following are the examples of powershell scripts of creating and reading different types of files."
},
{
"code": null,
"e": 9192,
"s": 9117,
"text": "Example Script to show how to create a text file using PowerShell scripts."
},
{
"code": null,
"e": 9265,
"s": 9192,
"text": "Example Script to show how to read a text file using PowerShell scripts."
},
{
"code": null,
"e": 9339,
"s": 9265,
"text": "Example Script to show how to create a XML file using PowerShell scripts."
},
{
"code": null,
"e": 9411,
"s": 9339,
"text": "Example Script to show how to read a XML file using PowerShell scripts."
},
{
"code": null,
"e": 9485,
"s": 9411,
"text": "Example Script to show how to create a CSV file using PowerShell scripts."
},
{
"code": null,
"e": 9557,
"s": 9485,
"text": "Example Script to show how to read a CSV file using PowerShell scripts."
},
{
"code": null,
"e": 9632,
"s": 9557,
"text": "Example Script to show how to create a HTML file using PowerShell scripts."
},
{
"code": null,
"e": 9705,
"s": 9632,
"text": "Example Script to show how to read a HTML file using PowerShell scripts."
},
{
"code": null,
"e": 9781,
"s": 9705,
"text": "Example Script to show how to erase file contents using PowerShell scripts."
},
{
"code": null,
"e": 9868,
"s": 9781,
"text": "Example Script to show how to append text to a file contents using PowerShell scripts."
},
{
"code": null,
"e": 10165,
"s": 9868,
"text": "A cmdlet or \"Command let\" is a lightweight command used in the Windows PowerShell environment. The Windows PowerShell runtime invokes these cmdlets at command prompt. You can create and invoke them programmatically through Windows PowerShell APIs. Following are advanced usage example of cmdlets."
},
{
"code": null,
"e": 10212,
"s": 10165,
"text": "Example program to showcase Get-Unique Cmdlet."
},
{
"code": null,
"e": 10232,
"s": 10212,
"text": "Group-Object Cmdlet"
},
{
"code": null,
"e": 10281,
"s": 10232,
"text": "Example program to showcase Group-Object Cmdlet."
},
{
"code": null,
"e": 10332,
"s": 10281,
"text": "Example program to showcase Measure-Object Cmdlet."
},
{
"code": null,
"e": 10383,
"s": 10332,
"text": "Example program to showcase Compare-Object Cmdlet."
},
{
"code": null,
"e": 10431,
"s": 10383,
"text": "Example program to showcase Format-List Cmdlet."
},
{
"code": null,
"e": 10479,
"s": 10431,
"text": "Example program to showcase Format-Wide Cmdlet."
},
{
"code": null,
"e": 10528,
"s": 10479,
"text": "Example program to showcase Where-Object Cmdlet."
},
{
"code": null,
"e": 10578,
"s": 10528,
"text": "Example program to showcase Get-ChildItem Cmdlet."
},
{
"code": null,
"e": 10629,
"s": 10578,
"text": "Example program to showcase ForEach-Object Cmdlet."
},
{
"code": null,
"e": 10677,
"s": 10629,
"text": "Example program to showcase Start-Sleep Cmdlet."
},
{
"code": null,
"e": 10723,
"s": 10677,
"text": "Example program to showcase Read-Host Cmdlet."
},
{
"code": null,
"e": 10773,
"s": 10723,
"text": "Example program to showcase Select-Object Cmdlet."
},
{
"code": null,
"e": 10821,
"s": 10773,
"text": "Example program to showcase Sort-Object Cmdlet."
},
{
"code": null,
"e": 10871,
"s": 10821,
"text": "Example program to showcase Write-Warning Cmdlet."
},
{
"code": null,
"e": 10918,
"s": 10871,
"text": "Example program to showcase Write-Host Cmdlet."
},
{
"code": null,
"e": 10966,
"s": 10918,
"text": "Example program to showcase Invoke-Item Cmdlet."
},
{
"code": null,
"e": 11020,
"s": 10966,
"text": "Example program to showcase Invoke-Expression Cmdlet."
},
{
"code": null,
"e": 11072,
"s": 11020,
"text": "Example program to showcase Measure-Command Cmdlet."
},
{
"code": null,
"e": 11123,
"s": 11072,
"text": "Example program to showcase Invoke-History Cmdlet."
},
{
"code": null,
"e": 11171,
"s": 11123,
"text": "Example program to showcase Add-History Cmdlet."
},
{
"code": null,
"e": 11219,
"s": 11171,
"text": "Example program to showcase Get-History Cmdlet."
},
{
"code": null,
"e": 11267,
"s": 11219,
"text": "Example program to showcase Get-Culture Cmdlet."
},
{
"code": null,
"e": 11634,
"s": 11267,
"text": "Windows PowerShell is a command-line shell and scripting language designed especially for system administration. Its analogue in Linux is called as Bash Scripting. Built on the .NET Framework, Windows PowerShell helps IT professionals to control and automate the administration of the Windows operating system and applications that run on Windows Server environment."
},
{
"code": null,
"e": 11873,
"s": 11634,
"text": "Windows PowerShell commands, called cmdlets, let you manage the computers from the command line. Windows PowerShell providers let you access data stores, such as the Registry and Certificate Store, as easily as you access the file system."
},
{
"code": null,
"e": 12165,
"s": 11873,
"text": "In addition, Windows PowerShell has a rich expression parser and a fully developed scripting language. So in simple words you can complete all the tasks that you do with GUI and much more. Windows PowerShell Scripting is a fully developed scripting language and has a rich expression parser/"
},
{
"code": null,
"e": 12347,
"s": 12165,
"text": "Cmdlets β Cmdlets perform common system administration tasks, for example managing the registry, services, processes, event logs, and using Windows Management Instrumentation (WMI)."
},
{
"code": null,
"e": 12529,
"s": 12347,
"text": "Cmdlets β Cmdlets perform common system administration tasks, for example managing the registry, services, processes, event logs, and using Windows Management Instrumentation (WMI)."
},
{
"code": null,
"e": 12655,
"s": 12529,
"text": "Task oriented β PowerShell scripting language is task based and provide supports for existing scripts and command-line tools."
},
{
"code": null,
"e": 12781,
"s": 12655,
"text": "Task oriented β PowerShell scripting language is task based and provide supports for existing scripts and command-line tools."
},
{
"code": null,
"e": 12999,
"s": 12781,
"text": "Consistent design β As cmdlets and system data stores use common syntax and have common naming conventions, data sharing is easy. The output from one cmdlet can be pipelined to another cmdlet without any manipulation."
},
{
"code": null,
"e": 13217,
"s": 12999,
"text": "Consistent design β As cmdlets and system data stores use common syntax and have common naming conventions, data sharing is easy. The output from one cmdlet can be pipelined to another cmdlet without any manipulation."
},
{
"code": null,
"e": 13364,
"s": 13217,
"text": "Simple to Use β Simplified, command-based navigation lets users navigate the registry and other data stores similar to the file system navigation."
},
{
"code": null,
"e": 13511,
"s": 13364,
"text": "Simple to Use β Simplified, command-based navigation lets users navigate the registry and other data stores similar to the file system navigation."
},
{
"code": null,
"e": 13648,
"s": 13511,
"text": "Object based β PowerShell possesses powerful object manipulation capabilities. Objects can be sent to other tools or databases directly."
},
{
"code": null,
"e": 13785,
"s": 13648,
"text": "Object based β PowerShell possesses powerful object manipulation capabilities. Objects can be sent to other tools or databases directly."
},
{
"code": null,
"e": 13978,
"s": 13785,
"text": "Extensible interface. β PowerShell is customizable as independent software vendors and enterprise developers can build custom tools and utilities using PowerShell to administer their software."
},
{
"code": null,
"e": 14171,
"s": 13978,
"text": "Extensible interface. β PowerShell is customizable as independent software vendors and enterprise developers can build custom tools and utilities using PowerShell to administer their software."
},
{
"code": null,
"e": 14292,
"s": 14171,
"text": "PowerShell variables are named objects. As PowerShell works with objects, these variables are used to work with objects."
},
{
"code": null,
"e": 14456,
"s": 14292,
"text": "Variable name should start with $ and can contain alphanumeric characters and underscore in their names. A variable can be created by typing a valid variable name."
},
{
"code": null,
"e": 14546,
"s": 14456,
"text": "Type the following command in PowerShell ISE Console. Assuming you are in D:\\test folder."
},
{
"code": null,
"e": 14571,
"s": 14546,
"text": "$location = Get-Location"
},
{
"code": null,
"e": 14700,
"s": 14571,
"text": "Here we've created a variable $location and assigned it the output of Get-Location cmdlet. It now contains the current location."
},
{
"code": null,
"e": 14754,
"s": 14700,
"text": "Type the following command in PowerShell ISE Console."
},
{
"code": null,
"e": 14765,
"s": 14754,
"text": " $location"
},
{
"code": null,
"e": 14817,
"s": 14765,
"text": "You can see following output in PowerShell console."
},
{
"code": null,
"e": 15085,
"s": 14817,
"text": "Path \n---- \nD:\\test \n"
},
{
"code": null,
"e": 15168,
"s": 15085,
"text": "Get-Member cmdlet can tell the type of variable being used. See the example below."
},
{
"code": null,
"e": 15192,
"s": 15168,
"text": " $location | Get-Member"
},
{
"code": null,
"e": 15244,
"s": 15192,
"text": "You can see following output in PowerShell console."
},
{
"code": null,
"e": 16123,
"s": 15244,
"text": " TypeName: System.Management.Automation.PathInfo\n\nName MemberType Definition \n---- ---------- ---------- \nEquals Method bool Equals(System.Object obj) \nGetHashCode Method int GetHashCode() \nGetType Method type GetType() \nToString Method string ToString() \nDrive Property System.Management.Automation.PSDriveInfo Drive {get;} \nPath Property System.String Path {get;} \nProvider Property System.Management.Automation.ProviderInfo Provider {get;}\nProviderPath Property System.String ProviderPath {get;}\n"
},
{
"code": null,
"e": 16278,
"s": 16123,
"text": "PowerShell Special variables store information about PowerShell. These are also called automatic variables. Following is the list of automatic variables β"
},
{
"code": null,
"e": 16418,
"s": 16278,
"text": "PowerShell provides a rich set of operators to manipulate variables. We can divide all the PowerShell operators into the following groups β"
},
{
"code": null,
"e": 16439,
"s": 16418,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 16460,
"s": 16439,
"text": "Assignment Operators"
},
{
"code": null,
"e": 16481,
"s": 16460,
"text": "Comparison Operators"
},
{
"code": null,
"e": 16499,
"s": 16481,
"text": "Logical Operators"
},
{
"code": null,
"e": 16523,
"s": 16499,
"text": "Redirectional Operators"
},
{
"code": null,
"e": 16548,
"s": 16523,
"text": "Spilt and Join Operators"
},
{
"code": null,
"e": 16563,
"s": 16548,
"text": "Type Operators"
},
{
"code": null,
"e": 16579,
"s": 16563,
"text": "Unary Operators"
},
{
"code": null,
"e": 16737,
"s": 16579,
"text": "Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators β"
},
{
"code": null,
"e": 16804,
"s": 16737,
"text": "Assume integer variable A holds 10 and variable B holds 20, then β"
},
{
"code": null,
"e": 16818,
"s": 16804,
"text": "Show Examples"
},
{
"code": null,
"e": 16892,
"s": 16818,
"text": "Following are the assignment operators supported by PowerShell language β"
},
{
"code": null,
"e": 16959,
"s": 16892,
"text": "Assume integer variable A holds 10 and variable B holds 20, then β"
},
{
"code": null,
"e": 16973,
"s": 16959,
"text": "Show Examples"
},
{
"code": null,
"e": 17047,
"s": 16973,
"text": "Following are the assignment operators supported by PowerShell language β"
},
{
"code": null,
"e": 17061,
"s": 17047,
"text": "Show Examples"
},
{
"code": null,
"e": 17111,
"s": 17061,
"text": "The following table lists the logical operators β"
},
{
"code": null,
"e": 17184,
"s": 17111,
"text": "Assume Boolean variables A holds true and variable B holds false, then β"
},
{
"code": null,
"e": 17198,
"s": 17184,
"text": "Show Examples"
},
{
"code": null,
"e": 17275,
"s": 17198,
"text": "Following are various important operators supported by PowerShell language β"
},
{
"code": null,
"e": 17289,
"s": 17275,
"text": "Show Examples"
},
{
"code": null,
"e": 17518,
"s": 17289,
"text": "There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on."
},
{
"code": null,
"e": 17624,
"s": 17518,
"text": "Programming languages provide various control structures that allow for more complicated execution paths."
},
{
"code": null,
"e": 17805,
"s": 17624,
"text": "A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages β"
},
{
"code": null,
"e": 17955,
"s": 17805,
"text": "PowerShell programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail."
},
{
"code": null,
"e": 18060,
"s": 17955,
"text": "Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable."
},
{
"code": null,
"e": 18152,
"s": 18060,
"text": "Enhanced for loop. This is mainly used to traverse collection of elements including arrays."
},
{
"code": null,
"e": 18283,
"s": 18152,
"text": "Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body."
},
{
"code": null,
"e": 18371,
"s": 18283,
"text": "Like a while statement, except that it tests the condition at the end of the loop body."
},
{
"code": null,
"e": 18664,
"s": 18371,
"text": "Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false."
},
{
"code": null,
"e": 18778,
"s": 18664,
"text": "Following is the general form of a typical decision making structure found in most of the programming languages β"
},
{
"code": null,
"e": 18913,
"s": 18778,
"text": "PowerShell scripting language provides following types of decision making statements. Click the following links to check their detail."
},
{
"code": null,
"e": 18998,
"s": 18913,
"text": "An if statement consists of a boolean expression followed by one or more statements."
},
{
"code": null,
"e": 19114,
"s": 18998,
"text": "An if statement can be followed by an optional else statement, which executes when the boolean expression is false."
},
{
"code": null,
"e": 19195,
"s": 19114,
"text": "You can use one if or elseif statement inside another if or elseif statement(s)."
},
{
"code": null,
"e": 19284,
"s": 19195,
"text": "A switch statement allows a variable to be tested for equality against a list of values."
},
{
"code": null,
"e": 19548,
"s": 19284,
"text": "PowerShell provides a data structure, the array, which stores a fixed-size sequential collection of elements of the any type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables or objects."
},
{
"code": null,
"e": 19771,
"s": 19548,
"text": "Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables."
},
{
"code": null,
"e": 19887,
"s": 19771,
"text": "This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables."
},
{
"code": null,
"e": 20088,
"s": 19887,
"text": "To use an array in a program, you must declare a variable to reference the array, and you can specify the type of array the variable can reference. Here is the syntax for declaring an array variable β"
},
{
"code": null,
"e": 20120,
"s": 20088,
"text": "$A = 1, 2, 3, 4\nor\n$A = 1..4 \n"
},
{
"code": null,
"e": 20249,
"s": 20120,
"text": "Note β By default type of objects of array is System.Object. GetType() method returns the type of the array. Type can be passed."
},
{
"code": null,
"e": 20307,
"s": 20249,
"text": "The following code snippets are examples of this syntax β"
},
{
"code": null,
"e": 20374,
"s": 20307,
"text": "[int32[]]$intA = 1500,2230,3350,4000\n\n$A = 1, 2, 3, 4\n$A.getType()"
},
{
"code": null,
"e": 20415,
"s": 20374,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 20646,
"s": 20415,
"text": "IsPublic IsSerial Name BaseType \n-------- -------- ---- -------- \nTrue True Object[] System.Array \n"
},
{
"code": null,
"e": 20776,
"s": 20646,
"text": "The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1."
},
{
"code": null,
"e": 20917,
"s": 20776,
"text": "Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList β"
},
{
"code": null,
"e": 20987,
"s": 20917,
"text": "$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123"
},
{
"code": null,
"e": 21100,
"s": 20987,
"text": "Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9."
},
{
"code": null,
"e": 21274,
"s": 21100,
"text": "When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known."
},
{
"code": null,
"e": 21357,
"s": 21274,
"text": "Here is a complete example showing how to create, initialize, and process arrays β"
},
{
"code": null,
"e": 21999,
"s": 21357,
"text": "$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123\n\nwrite-host(\"Print all the array elements\")\n$myList\n\nwrite-host(\"Get the length of array\")\n$myList.Length\n\nwrite-host(\"Get Second element of array\")\n$myList[1]\n\nwrite-host(\"Get partial array\")\n$subList = $myList[1..3]\n\nwrite-host(\"print subList\")\n$subList\n\nwrite-host(\"using for loop\")\nfor ($i = 0; $i -le ($myList.length - 1); $i += 1) {\n $myList[$i]\n}\n\nwrite-host(\"using forEach Loop\")\nforeach ($element in $myList) {\n $element\n}\n\nwrite-host(\"using while Loop\")\n$i = 0\nwhile($i -lt 4) {\n $myList[$i];\n $i++\n}\n\nwrite-host(\"Assign values\")\n$myList[1] = 10\n$myList"
},
{
"code": null,
"e": 22040,
"s": 21999,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 22443,
"s": 22040,
"text": "Print all the array elements\n5.6\n4.5\n3.3\n13.2\n4\n34.33\n34\n45.45\n99.993\n11123\nGet the length of array\n10\nGet Second element of array\n4.5\nGet partial array\nprint subList\n4.5\n3.3\n13.2\nusing for loop\n5.6\n4.5\n3.3\n13.2\n4\n34.33\n34\n45.45\n99.993\n11123\nusing forEach Loop\n5.6\n4.5\n3.3\n13.2\n4\n34.33\n34\n45.45\n99.993\n11123\nusing while Loop\n5.6\n4.5\n3.3\n13.2\nAssign values\n5.6\n10\n3.3\n13.2\n4\n34.33\n34\n45.45\n99.993\n11123\n"
},
{
"code": null,
"e": 22517,
"s": 22443,
"text": "Here is a complete example showing operations on arrays using its methods"
},
{
"code": null,
"e": 22643,
"s": 22517,
"text": "$myList = @(0..4)\n\nwrite-host(\"Print array\")\n$myList\n\n$myList = @(0..4)\n\nwrite-host(\"Assign values\")\n$myList[1] = 10\n$myList"
},
{
"code": null,
"e": 22684,
"s": 22643,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 22744,
"s": 22684,
"text": "Clear array\nPrint array\n0\n1\n2\n3\n4\nAssign values\n0\n10\n2\n3\n4\n"
},
{
"code": null,
"e": 22956,
"s": 22744,
"text": "Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. Generally we used String or numbers as keys."
},
{
"code": null,
"e": 23077,
"s": 22956,
"text": "This tutorial introduces how to declare hashtable variables, create hashtables, and process hashtable using its methods."
},
{
"code": null,
"e": 23224,
"s": 23077,
"text": "To use an hashtable in a program, you must declare a variable to reference the hashtable. Here is the syntax for declaring an hashtable variable β"
},
{
"code": null,
"e": 23294,
"s": 23224,
"text": "$hash = @{ ID = 1; Shape = \"Square\"; Color = \"Blue\"}\nor\n$hash = @{} \n"
},
{
"code": null,
"e": 23453,
"s": 23294,
"text": "Note β Ordered dictionaries can be created using similar syntax. Ordered dictionaries maintain the order in which entries are added whereas hashtables do not."
},
{
"code": null,
"e": 23511,
"s": 23453,
"text": "The following code snippets are examples of this syntax β"
},
{
"code": null,
"e": 23573,
"s": 23511,
"text": "$hash = [ordered]@{ ID = 1; Shape = \"Square\"; Color = \"Blue\"}"
},
{
"code": null,
"e": 23594,
"s": 23573,
"text": "Print the hashtable."
},
{
"code": null,
"e": 23600,
"s": 23594,
"text": "$hash"
},
{
"code": null,
"e": 23948,
"s": 23600,
"text": "Name Value \n---- ----- \nID 1 \nColor Blue \nShape Square \n"
},
{
"code": null,
"e": 24000,
"s": 23948,
"text": "The hashtable values are accessed through the keys."
},
{
"code": null,
"e": 24017,
"s": 24000,
"text": "> $hash[\"ID\"]\n 1"
},
{
"code": null,
"e": 24079,
"s": 24017,
"text": "Dot notation can be used to access hashtables keys or values."
},
{
"code": null,
"e": 24137,
"s": 24079,
"text": "> $hash.keys\nID\nColor\nShape\n\n> $hash.values\n1\nBlue\nSquare"
},
{
"code": null,
"e": 24223,
"s": 24137,
"text": "Here is a complete example showing how to create, initialize, and process hashtable β"
},
{
"code": null,
"e": 24811,
"s": 24223,
"text": "$hash = @{ ID = 1; Shape = \"Square\"; Color = \"Blue\"}\n\nwrite-host(\"Print all hashtable keys\")\n$hash.keys\n\nwrite-host(\"Print all hashtable values\")\n$hash.values\n\nwrite-host(\"Get ID\")\n$hash[\"ID\"]\n\nwrite-host(\"Get Shape\")\n$hash.Number\n\nwrite-host(\"print Size\")\n$hash.Count\n\nwrite-host(\"Add key-value\")\n$hash[\"Updated\"] = \"Now\"\n\nwrite-host(\"Add key-value\")\n$hash.Add(\"Created\",\"Now\")\n\nwrite-host(\"print Size\")\n$hash.Count\n\nwrite-host(\"Remove key-value\")\n$hash.Remove(\"Updated\")\n\nwrite-host(\"print Size\")\n$hash.Count\n\nwrite-host(\"sort by key\")\n$hash.GetEnumerator() | Sort-Object -Property key"
},
{
"code": null,
"e": 24852,
"s": 24811,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 25773,
"s": 24852,
"text": "Print all hashtable keys\nID\nColor\nShape\nPrint all hashtable values\n1\nBlue\nSquare\nGet ID\n1\nGet Shape\nprint Size\n3\nAdd key-value\nAdd key-value\nprint Size\n5\nRemove key-value\nprint Size\n4\nsort by key\n\nName Value \n---- ----- \nColor Blue \nCreated Now \nID 1 \nShape \nSquare \n"
},
{
"code": null,
"e": 26002,
"s": 25773,
"text": "A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data."
},
{
"code": null,
"e": 26107,
"s": 26002,
"text": "Here is the table listing down all the regular expression metacharacter syntax available in PowerShell β"
},
{
"code": null,
"e": 26175,
"s": 26107,
"text": "Here is a complete examples showing how to use regex in PowerShell;"
},
{
"code": null,
"e": 26227,
"s": 26175,
"text": "Example of supported regular expression characters."
},
{
"code": null,
"e": 26267,
"s": 26227,
"text": "Example of supported character classes."
},
{
"code": null,
"e": 26301,
"s": 26267,
"text": "Example of supported quantifiers."
},
{
"code": null,
"e": 26503,
"s": 26301,
"text": "Backtick (`) operator is also called word-wrap operator. It allows a command to be written in multiple lines. It can be used for new line (`n) or tab (`t) in sentences as well. See the examples below β"
},
{
"code": null,
"e": 26596,
"s": 26503,
"text": "Get-Service * | Sort-Object ServiceType `\n| Format-Table Name, ServiceType, Status -AutoSize"
},
{
"code": null,
"e": 26612,
"s": 26596,
"text": "It will become "
},
{
"code": null,
"e": 26703,
"s": 26612,
"text": "Get-Service * | Sort-Object ServiceType | Format-Table Name, ServiceType, Status -AutoSize"
},
{
"code": null,
"e": 26724,
"s": 26703,
"text": "Verify the output as"
},
{
"code": null,
"e": 27029,
"s": 26724,
"text": "Name ServiceType Status\n---- ----------- ------\nMSSQLServerADHelper100 Win32OwnProcess Stopped\nntrtscan Win32OwnProcess Running\n...\n"
},
{
"code": null,
"e": 27054,
"s": 27029,
"text": "Use of new line and tab."
},
{
"code": null,
"e": 27198,
"s": 27054,
"text": "> Write-host \"Title Subtitle\"\nTitle Subtitle\n\n> Write-host \"Title `nSubtitle\"\nTitle \nSubtitle\n\n> Write-host \"Title `tSubtitle\"\nTitle Subtitle"
},
{
"code": null,
"e": 27243,
"s": 27198,
"text": "Powershell supports three types of brackets."
},
{
"code": null,
"e": 27272,
"s": 27243,
"text": "Parenthesis brackets. β () \n"
},
{
"code": null,
"e": 27300,
"s": 27272,
"text": "Parenthesis brackets. β () "
},
{
"code": null,
"e": 27324,
"s": 27300,
"text": "Braces brackets. β {} \n"
},
{
"code": null,
"e": 27347,
"s": 27324,
"text": "Braces brackets. β {} "
},
{
"code": null,
"e": 27371,
"s": 27347,
"text": "Square brackets. β [] \n"
},
{
"code": null,
"e": 27394,
"s": 27371,
"text": "Square brackets. β [] "
},
{
"code": null,
"e": 27427,
"s": 27394,
"text": "This type of brackets is used to"
},
{
"code": null,
"e": 27442,
"s": 27427,
"text": "pass arguments"
},
{
"code": null,
"e": 27457,
"s": 27442,
"text": "pass arguments"
},
{
"code": null,
"e": 27494,
"s": 27457,
"text": "enclose multiple set of instructions"
},
{
"code": null,
"e": 27531,
"s": 27494,
"text": "enclose multiple set of instructions"
},
{
"code": null,
"e": 27549,
"s": 27531,
"text": "resolve ambiguity"
},
{
"code": null,
"e": 27567,
"s": 27549,
"text": "resolve ambiguity"
},
{
"code": null,
"e": 27580,
"s": 27567,
"text": "create array"
},
{
"code": null,
"e": 27593,
"s": 27580,
"text": "create array"
},
{
"code": null,
"e": 27697,
"s": 27593,
"text": "> $array = @(\"item1\", \"item2\", \"item3\")\n \n> foreach ($element in $array) { $element }\nitem1\nitem2\nitem3"
},
{
"code": null,
"e": 27730,
"s": 27697,
"text": "This type of brackets is used to"
},
{
"code": null,
"e": 27749,
"s": 27730,
"text": "enclose statements"
},
{
"code": null,
"e": 27768,
"s": 27749,
"text": "enclose statements"
},
{
"code": null,
"e": 27783,
"s": 27768,
"text": "block commands"
},
{
"code": null,
"e": 27798,
"s": 27783,
"text": "block commands"
},
{
"code": null,
"e": 27862,
"s": 27798,
"text": "$x = 10\n\nif($x -le 20){\n write-host(\"This is if statement\")\n}"
},
{
"code": null,
"e": 27903,
"s": 27862,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 27926,
"s": 27903,
"text": "This is if statement.\n"
},
{
"code": null,
"e": 27959,
"s": 27926,
"text": "This type of brackets is used to"
},
{
"code": null,
"e": 27975,
"s": 27959,
"text": "access to array"
},
{
"code": null,
"e": 27991,
"s": 27975,
"text": "access to array"
},
{
"code": null,
"e": 28012,
"s": 27991,
"text": "access to hashtables"
},
{
"code": null,
"e": 28033,
"s": 28012,
"text": "access to hashtables"
},
{
"code": null,
"e": 28065,
"s": 28033,
"text": "filter using regular expression"
},
{
"code": null,
"e": 28097,
"s": 28065,
"text": "filter using regular expression"
},
{
"code": null,
"e": 28558,
"s": 28097,
"text": "> $array = @(\"item1\", \"item2\", \"item3\")\n \n> for($i = 0; $i -lt $array.length; $i++){ $array[$i] }\nitem1\nitem2\nitem3\n \n>Get-Process [r-s]*\n Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName\n------- ------ ----- ----- ----- ------ -- ----------- \n 320 72 27300 33764 227 3.95 4028 SCNotification \n 2298 77 57792 48712 308 2884 SearchIndexer\n ..."
},
{
"code": null,
"e": 28634,
"s": 28558,
"text": "PowerShell alias is another name for the cmdlet or for any command element."
},
{
"code": null,
"e": 28745,
"s": 28634,
"text": "Use New-Alias cmdlet to create a alias. In the below example, we've created an alias help for Get-Help cmdlet."
},
{
"code": null,
"e": 28785,
"s": 28745,
"text": " New-Alias -Name help -Value Get-Help "
},
{
"code": null,
"e": 28807,
"s": 28785,
"text": "Now invoke the alias."
},
{
"code": null,
"e": 28839,
"s": 28807,
"text": " help Get-WmiObject -Detailed "
},
{
"code": null,
"e": 28874,
"s": 28839,
"text": "You will see the following output."
},
{
"code": null,
"e": 29064,
"s": 28874,
"text": "NAME\n Get-WmiObject\n \nSYNOPSIS\n Gets instances of Windows Management Instrumentation (WMI) classes or information about the available classes. \n \nSYNTAX\n Get-WmiObject [\n...\n"
},
{
"code": null,
"e": 29148,
"s": 29064,
"text": "Use get-alias cmdlet to get all the alias present in current session of powershell."
},
{
"code": null,
"e": 29159,
"s": 29148,
"text": " Get-Alias"
},
{
"code": null,
"e": 29194,
"s": 29159,
"text": "You will see the following output."
},
{
"code": null,
"e": 29523,
"s": 29194,
"text": "CommandType Name Definition\n----------- ---- ---------- \nAlias % ForEach-Object\nAlias ? Where-Object\nAlias ac Add-Content\nAlias asnp Add-PSSnapIn \n...\n"
},
{
"code": null,
"e": 29558,
"s": 29523,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 29579,
"s": 29558,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 29614,
"s": 29579,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 29627,
"s": 29614,
"text": " Vijay Saini"
},
{
"code": null,
"e": 29664,
"s": 29627,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 29676,
"s": 29664,
"text": " Fettah Ben"
},
{
"code": null,
"e": 29683,
"s": 29676,
"text": " Print"
},
{
"code": null,
"e": 29694,
"s": 29683,
"text": " Add Notes"
}
] |
HTML - <input> Tag | The HTML <input>tag is used within a form to declare an input element β a control that allows the user to input data.
<!DOCTYPE html>
<html>
<head>
<title>HTML input Tag</title>
</head>
<body>
<form action = "/cgi-bin/hello_get.cgi" method = "get">
First name:
<input type = "text" name = "first_name" value = "" maxlength = "100" />
<br />
Last name:
<input type = "text" name = "last_name" value = "" maxlength = "100" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
This will produce the following result β
This tag supports all the global attributes described in β HTML Attribute Reference
The HTML <input> tag also supports the following additional attributes β
application/x-www-form-urlencoded
multipart/form-data
text/plain
This tag supports all the event attributes described in HTML Events Reference
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2492,
"s": 2374,
"text": "The HTML <input>tag is used within a form to declare an input element β a control that allows the user to input data."
},
{
"code": null,
"e": 2978,
"s": 2492,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML input Tag</title>\n </head>\n\t\n <body>\n <form action = \"/cgi-bin/hello_get.cgi\" method = \"get\">\n First name: \n <input type = \"text\" name = \"first_name\" value = \"\" maxlength = \"100\" />\n <br />\n \n Last name: \n <input type = \"text\" name = \"last_name\" value = \"\" maxlength = \"100\" />\n <input type = \"submit\" value = \"Submit\" />\n </form>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 3019,
"s": 2978,
"text": "This will produce the following result β"
},
{
"code": null,
"e": 3103,
"s": 3019,
"text": "This tag supports all the global attributes described in β HTML Attribute Reference"
},
{
"code": null,
"e": 3176,
"s": 3103,
"text": "The HTML <input> tag also supports the following additional attributes β"
},
{
"code": null,
"e": 3210,
"s": 3176,
"text": "application/x-www-form-urlencoded"
},
{
"code": null,
"e": 3230,
"s": 3210,
"text": "multipart/form-data"
},
{
"code": null,
"e": 3241,
"s": 3230,
"text": "text/plain"
},
{
"code": null,
"e": 3319,
"s": 3241,
"text": "This tag supports all the event attributes described in HTML Events Reference"
},
{
"code": null,
"e": 3352,
"s": 3319,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3366,
"s": 3352,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3401,
"s": 3366,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3415,
"s": 3401,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3450,
"s": 3415,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3467,
"s": 3450,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3502,
"s": 3467,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3533,
"s": 3502,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3566,
"s": 3533,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3597,
"s": 3566,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3632,
"s": 3597,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3663,
"s": 3632,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3670,
"s": 3663,
"text": " Print"
},
{
"code": null,
"e": 3681,
"s": 3670,
"text": " Add Notes"
}
] |
Adding OrbitControls in React using reactthree-fiber | In this article, we will see how to add OrbitControls in React using react-three-fiber. It is like making a camera; we can move on screen and view each side of any 3D object. We can use OrbitControl to provide zoom and sliding effects too. So, let's get started.
Install the react-three/fiber library β
npm i --save @react-three/fiber three
threejs and react-three/fiber will be used to add webGL renderer to the website. three-fiber will be used to connect threejs and react.
First create an orbital control object in App.js β
import React, { useEffect } from "react";
import { Canvas, useThree } from "@react-three/fiber";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import * as THREE from "three";
import "./App.scss";
const CameraController = () => {
const { camera, gl } = useThree();
useEffect(
() => {
const controls = new OrbitControls(camera, gl.domElement);
controls.minDistance = 3;
controls.maxDistance = 20;
return () => {
controls.dispose();
};
},
[camera, gl]
);
return null;
};
CameraController is used to add orbital control on the whole screen.
CameraController is used to add orbital control on the whole screen.
useThree() gives you a camera object, which is used to move on screen.
useThree() gives you a camera object, which is used to move on screen.
gl indicates the area on which you are moving.
gl indicates the area on which you are moving.
In useEffect, we combined both the OrbitControls object.
In useEffect, we combined both the OrbitControls object.
Then we added the minDistance and maxDistance parameters
to restrict the movement on screen.
Then we added the minDistance and maxDistance parameters
to restrict the movement on screen.
Next, add the following lines in App.css β
* {
box-sizing: border-box;
}
html,body,#root{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body{
background: #f1f4f8;
position: fixed;
}
This CSS is used to make the canvas match parent size.
Now, let's add OrbitControl in the App component. Add the following lines of code in App.js β
export default function App(){
return (
<Canvas>
<CameraController />
<ambientLight />
<spotLight intensity={0.3} position={[5, 10, 50]} />
<mesh>
<boxGeometry attach="geometry" args={[3, 2, 1]} />
<meshPhongMaterial attach="material" color="hotpink" />
</mesh>
</Canvas>
);
};
We created a cuboid and added our previous orbitcontrol object βCameraControllerβ in the App component. OrbitControl is used to add zoomIn, zoomOut, moving, and other effects on our canvas.
On execution, it will produce the following output β
Your browser does not support HTML5 video. | [
{
"code": null,
"e": 1325,
"s": 1062,
"text": "In this article, we will see how to add OrbitControls in React using react-three-fiber. It is like making a camera; we can move on screen and view each side of any 3D object. We can use OrbitControl to provide zoom and sliding effects too. So, let's get started."
},
{
"code": null,
"e": 1365,
"s": 1325,
"text": "Install the react-three/fiber library β"
},
{
"code": null,
"e": 1403,
"s": 1365,
"text": "npm i --save @react-three/fiber three"
},
{
"code": null,
"e": 1539,
"s": 1403,
"text": "threejs and react-three/fiber will be used to add webGL renderer to the website. three-fiber will be used to connect threejs and react."
},
{
"code": null,
"e": 1590,
"s": 1539,
"text": "First create an orbital control object in App.js β"
},
{
"code": null,
"e": 2174,
"s": 1590,
"text": "import React, { useEffect } from \"react\";\nimport { Canvas, useThree } from \"@react-three/fiber\";\nimport { OrbitControls } from \"three/examples/jsm/controls/OrbitControls\";\nimport * as THREE from \"three\";\nimport \"./App.scss\";\n\nconst CameraController = () => {\n const { camera, gl } = useThree();\n useEffect(\n () => {\n const controls = new OrbitControls(camera, gl.domElement);\n controls.minDistance = 3;\n controls.maxDistance = 20;\n return () => {\n controls.dispose();\n };\n },\n [camera, gl]\n );\n return null;\n};"
},
{
"code": null,
"e": 2243,
"s": 2174,
"text": "CameraController is used to add orbital control on the whole screen."
},
{
"code": null,
"e": 2312,
"s": 2243,
"text": "CameraController is used to add orbital control on the whole screen."
},
{
"code": null,
"e": 2383,
"s": 2312,
"text": "useThree() gives you a camera object, which is used to move on screen."
},
{
"code": null,
"e": 2454,
"s": 2383,
"text": "useThree() gives you a camera object, which is used to move on screen."
},
{
"code": null,
"e": 2501,
"s": 2454,
"text": "gl indicates the area on which you are moving."
},
{
"code": null,
"e": 2548,
"s": 2501,
"text": "gl indicates the area on which you are moving."
},
{
"code": null,
"e": 2605,
"s": 2548,
"text": "In useEffect, we combined both the OrbitControls object."
},
{
"code": null,
"e": 2662,
"s": 2605,
"text": "In useEffect, we combined both the OrbitControls object."
},
{
"code": null,
"e": 2755,
"s": 2662,
"text": "Then we added the minDistance and maxDistance parameters\nto restrict the movement on screen."
},
{
"code": null,
"e": 2848,
"s": 2755,
"text": "Then we added the minDistance and maxDistance parameters\nto restrict the movement on screen."
},
{
"code": null,
"e": 2891,
"s": 2848,
"text": "Next, add the following lines in App.css β"
},
{
"code": null,
"e": 3061,
"s": 2891,
"text": "* {\n box-sizing: border-box;\n}\n html,body,#root{\n width: 100%;\n height: 100%;\n margin: 0;\n padding: 0;\n}\n\nbody{\n background: #f1f4f8;\n position: fixed;\n}"
},
{
"code": null,
"e": 3116,
"s": 3061,
"text": "This CSS is used to make the canvas match parent size."
},
{
"code": null,
"e": 3210,
"s": 3116,
"text": "Now, let's add OrbitControl in the App component. Add the following lines of code in App.js β"
},
{
"code": null,
"e": 3575,
"s": 3210,
"text": "export default function App(){\n return (\n <Canvas>\n <CameraController />\n <ambientLight />\n <spotLight intensity={0.3} position={[5, 10, 50]} />\n <mesh>\n <boxGeometry attach=\"geometry\" args={[3, 2, 1]} />\n <meshPhongMaterial attach=\"material\" color=\"hotpink\" />\n </mesh>\n </Canvas>\n );\n};"
},
{
"code": null,
"e": 3765,
"s": 3575,
"text": "We created a cuboid and added our previous orbitcontrol object βCameraControllerβ in the App component. OrbitControl is used to add zoomIn, zoomOut, moving, and other effects on our canvas."
},
{
"code": null,
"e": 3818,
"s": 3765,
"text": "On execution, it will produce the following output β"
},
{
"code": null,
"e": 3861,
"s": 3818,
"text": "Your browser does not support HTML5 video."
}
] |
5 Python Best Practices That Every Programmer Should Follow | by Pranjal Saxena | Towards Data Science | Python, one of the most popular languages of recent times, has a huge community of developers and programmers across the globe.
Many beginners, as well as experienced programmers, are taking up Python as their preferred programming language. Also, as it is an open-source language, sharing knowledge within the community is also prominent.
That is why it becomes necessary to follow some coding conventions that help to improve the quality and the readability of the code.
This article will discuss five such Python best practices that can be really useful for Python programmers to improve their coding experience.
Whether you are writing a small script for making a detailed project, having a well-structured code with proper names of the modules, correct indentations, and documentation improves the code's usability in the future.
Especially while making projects, you must include a README file for describing your project, the setup.py file for properly setting up your project in a new environment, and the requirements.txt for describing the dependencies that are needed. And, also last but not least, documentation describing how all the components of your projects work. You can also include some tests in your repository.
Incorporating comments in your code can be the first step of having proper documentation. For example, what is the role of a specific module in your code, how a function works, or the role of a function, and much more can be described using comments.
In Python, two types of comments are available. One is single-line comments which start with a hash symbol (#). These types of comments can help us describe a specific line of code like what an expression does.
print(βhello worldβ) #one line comment: this prints hello world
The other type is a multiline comment which starts and ends with triple quotes (βββ). They are more useful while describing a module or a function.
Having meaningful comments and proper documentation improves the readability and usability of your code a lot.
βββ this is a comment that can
Take multiple
Lines βββ
One of the most common mistakes among beginner Python developers is improper naming of variables, classes, functions etc. We should always avoid writing single-letter variable names for heavily abbreviated function or class names.
e.g. a variable that stores the temperature of a substance should be named temperature or temp instead of t. The PEP-8 is a popular guideline among Python programmers, which tells us how to name our variables, classes and functions properly.
For example:
A long variable should be separated using underscores(_), e.g. long_variable_name
While writing class name CamelCase should be used, e.g. LongClassName
For writing functions using underscores is advised e.g. function_name()
The best way to improve the quality of the codebase is to make it more compact and modular. The module is like a collection of functions that you can use in your code when needed.
Python has many modules and libraries under a repository known as PyPI or the python package index. It contains numerous models written by Python developers, which you can implement in your code just by installing them from the internet. This prevents you from implementing all the logic from scratch and makes your script compact and readable.
Another good side of using modules is that most of these existing models are written by programmers with years of experience, and they can give you the best possible solution, which will take a lot of time for you to think from scratch.
The main purpose of a virtual environment in Python is to create a separate environment for Python projects. This becomes particularly useful when you are using any third-party module or library in your project.
If two projects use different versions of the same module (third party), it becomes difficult for python to understand which version is required for which project as both the versions are saved in the same directory with the same filename.
This problem can be easily tackled by using a virtual environment for each project where the dependencies are stored independently.
To use the virtual environment, we have to install it using the following line of code.
pip install virtualenv
And to create a new environment, we can use:
python3 -m venv env
This makes your life a lot easier when you are working on different projects at the same time.
When you are working on a professional project along with the team, it becomes really necessary that your team members understand your code.
Following these practices will help you with that as these inventions are being used by millions of python developers across the globe. You can also implement these principles while doing personal projects to improve your understanding of the project and reflect professionalism in your work.
Before you go...
If you liked this article and want to stay tuned with more exciting articles on Python & Data Science β do consider becoming a medium member by clicking here https://pranjalai.medium.com/membership.
Please do consider signing up using my referral link. In this way, the portion of the membership fee goes to me, which motivates me to write more exciting stuff on Python and Data Science.
Also, feel free to subscribe to my free newsletter: Pranjalβs Newsletter. | [
{
"code": null,
"e": 174,
"s": 46,
"text": "Python, one of the most popular languages of recent times, has a huge community of developers and programmers across the globe."
},
{
"code": null,
"e": 386,
"s": 174,
"text": "Many beginners, as well as experienced programmers, are taking up Python as their preferred programming language. Also, as it is an open-source language, sharing knowledge within the community is also prominent."
},
{
"code": null,
"e": 519,
"s": 386,
"text": "That is why it becomes necessary to follow some coding conventions that help to improve the quality and the readability of the code."
},
{
"code": null,
"e": 662,
"s": 519,
"text": "This article will discuss five such Python best practices that can be really useful for Python programmers to improve their coding experience."
},
{
"code": null,
"e": 881,
"s": 662,
"text": "Whether you are writing a small script for making a detailed project, having a well-structured code with proper names of the modules, correct indentations, and documentation improves the code's usability in the future."
},
{
"code": null,
"e": 1279,
"s": 881,
"text": "Especially while making projects, you must include a README file for describing your project, the setup.py file for properly setting up your project in a new environment, and the requirements.txt for describing the dependencies that are needed. And, also last but not least, documentation describing how all the components of your projects work. You can also include some tests in your repository."
},
{
"code": null,
"e": 1530,
"s": 1279,
"text": "Incorporating comments in your code can be the first step of having proper documentation. For example, what is the role of a specific module in your code, how a function works, or the role of a function, and much more can be described using comments."
},
{
"code": null,
"e": 1741,
"s": 1530,
"text": "In Python, two types of comments are available. One is single-line comments which start with a hash symbol (#). These types of comments can help us describe a specific line of code like what an expression does."
},
{
"code": null,
"e": 1805,
"s": 1741,
"text": "print(βhello worldβ) #one line comment: this prints hello world"
},
{
"code": null,
"e": 1953,
"s": 1805,
"text": "The other type is a multiline comment which starts and ends with triple quotes (βββ). They are more useful while describing a module or a function."
},
{
"code": null,
"e": 2064,
"s": 1953,
"text": "Having meaningful comments and proper documentation improves the readability and usability of your code a lot."
},
{
"code": null,
"e": 2095,
"s": 2064,
"text": "βββ this is a comment that can"
},
{
"code": null,
"e": 2109,
"s": 2095,
"text": "Take multiple"
},
{
"code": null,
"e": 2119,
"s": 2109,
"text": "Lines βββ"
},
{
"code": null,
"e": 2350,
"s": 2119,
"text": "One of the most common mistakes among beginner Python developers is improper naming of variables, classes, functions etc. We should always avoid writing single-letter variable names for heavily abbreviated function or class names."
},
{
"code": null,
"e": 2592,
"s": 2350,
"text": "e.g. a variable that stores the temperature of a substance should be named temperature or temp instead of t. The PEP-8 is a popular guideline among Python programmers, which tells us how to name our variables, classes and functions properly."
},
{
"code": null,
"e": 2605,
"s": 2592,
"text": "For example:"
},
{
"code": null,
"e": 2687,
"s": 2605,
"text": "A long variable should be separated using underscores(_), e.g. long_variable_name"
},
{
"code": null,
"e": 2757,
"s": 2687,
"text": "While writing class name CamelCase should be used, e.g. LongClassName"
},
{
"code": null,
"e": 2829,
"s": 2757,
"text": "For writing functions using underscores is advised e.g. function_name()"
},
{
"code": null,
"e": 3009,
"s": 2829,
"text": "The best way to improve the quality of the codebase is to make it more compact and modular. The module is like a collection of functions that you can use in your code when needed."
},
{
"code": null,
"e": 3354,
"s": 3009,
"text": "Python has many modules and libraries under a repository known as PyPI or the python package index. It contains numerous models written by Python developers, which you can implement in your code just by installing them from the internet. This prevents you from implementing all the logic from scratch and makes your script compact and readable."
},
{
"code": null,
"e": 3591,
"s": 3354,
"text": "Another good side of using modules is that most of these existing models are written by programmers with years of experience, and they can give you the best possible solution, which will take a lot of time for you to think from scratch."
},
{
"code": null,
"e": 3803,
"s": 3591,
"text": "The main purpose of a virtual environment in Python is to create a separate environment for Python projects. This becomes particularly useful when you are using any third-party module or library in your project."
},
{
"code": null,
"e": 4043,
"s": 3803,
"text": "If two projects use different versions of the same module (third party), it becomes difficult for python to understand which version is required for which project as both the versions are saved in the same directory with the same filename."
},
{
"code": null,
"e": 4175,
"s": 4043,
"text": "This problem can be easily tackled by using a virtual environment for each project where the dependencies are stored independently."
},
{
"code": null,
"e": 4263,
"s": 4175,
"text": "To use the virtual environment, we have to install it using the following line of code."
},
{
"code": null,
"e": 4286,
"s": 4263,
"text": "pip install virtualenv"
},
{
"code": null,
"e": 4331,
"s": 4286,
"text": "And to create a new environment, we can use:"
},
{
"code": null,
"e": 4351,
"s": 4331,
"text": "python3 -m venv env"
},
{
"code": null,
"e": 4446,
"s": 4351,
"text": "This makes your life a lot easier when you are working on different projects at the same time."
},
{
"code": null,
"e": 4587,
"s": 4446,
"text": "When you are working on a professional project along with the team, it becomes really necessary that your team members understand your code."
},
{
"code": null,
"e": 4880,
"s": 4587,
"text": "Following these practices will help you with that as these inventions are being used by millions of python developers across the globe. You can also implement these principles while doing personal projects to improve your understanding of the project and reflect professionalism in your work."
},
{
"code": null,
"e": 4897,
"s": 4880,
"text": "Before you go..."
},
{
"code": null,
"e": 5096,
"s": 4897,
"text": "If you liked this article and want to stay tuned with more exciting articles on Python & Data Science β do consider becoming a medium member by clicking here https://pranjalai.medium.com/membership."
},
{
"code": null,
"e": 5285,
"s": 5096,
"text": "Please do consider signing up using my referral link. In this way, the portion of the membership fee goes to me, which motivates me to write more exciting stuff on Python and Data Science."
}
] |
Python Selenium Automate the Login Form - onlinetutorialspoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Here we will see how to automate the login form using selenium framework and python.
This example requires the following Softwares to be installed in your machine.
Install Python
Install Selenium
Install ChromeDriver and Browser
You can follow my previous article about how to install the selenium and kickstart with selenium HelloWorld example to get all prerequisites.
We are going to automate the Facebook login form using python.
from selenium import webdriver
driver = webdriver.Chrome(executable_path="D:\\softwares\\chromedriver_win\\chromedriver.exe")
driver.get("http://www.facebook.com")
driver.find_element_by_id("email").send_keys("facebookuser")
driver.find_element_by_id("pass").send_keys("password")
driver.find_element_by_id("u_0_b").click()
driver.close()
importing webdriver from selenium package
webdriver.Chrome() function is used to launch the web browser. for this, we have to provide the chromedriver.exe path as an executable_path=β{chromedriverpath}β
diver.get("URL") function loads a web page (http://www.facebook.com) in the current browser session.
driver.find_element_by_id() is a driver function used to finds an element in the web page and returns the element as WebElement. if the element wasnβt found it raises NoSuchElementException exception.
send_keys() is a WebElement function used to send simple key events or form fields. In our case, we are sending Facebook username and passwords to the form fields.
click() is a WebElement function is used to perform the click event on the element.
Finally closing the driver using the close() function.
On the above example, we used find_element_by_id(id) function, this function needs an exact dom element id to find it. So we have to provide that dom element id to this function to get the element.
Inspect the elements using developer tools (F12).
You can observe the above-highlighted dom elements. We can also use the name and class attributes for selection using find_element_by_name() and find_element_by_class_name() functions respectively, you can find more selectors here,
Output:
Finally, run the application so that you could see the browser window popping up and automate the login process from selenium on your behalf π
C:\Users\Lenovo\python_samples>python selenium_helloworld.py
Selenium Helloworld Example
Selenium Locating Elements
Happy Learning π
How install Python on Windows 10
How to upgrade Python PIP version on Windows
Python raw_input read input from keyboard
Python Selenium HelloWorld Example
Python Set Data Structure in Depth
Python β How to Read Google Search Results in Selenium
Python β Selenium Download a File in Headless Mode
Python Tuple Data Structure in Depth
Python β How to remove duplicate elements from List
Python List Data Structure In Depth
How to Remove Spaces from String in Python
Spring MVC Login Form Example Tutorials
Basic Android Login Form Example
Spring Boot Validation Login Form Example
Python β How to create Zip File in Python ?
How install Python on Windows 10
How to upgrade Python PIP version on Windows
Python raw_input read input from keyboard
Python Selenium HelloWorld Example
Python Set Data Structure in Depth
Python β How to Read Google Search Results in Selenium
Python β Selenium Download a File in Headless Mode
Python Tuple Data Structure in Depth
Python β How to remove duplicate elements from List
Python List Data Structure In Depth
How to Remove Spaces from String in Python
Spring MVC Login Form Example Tutorials
Basic Android Login Form Example
Spring Boot Validation Login Form Example
Python β How to create Zip File in Python ? | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 483,
"s": 398,
"text": "Here we will see how to automate the login form using selenium framework and python."
},
{
"code": null,
"e": 562,
"s": 483,
"text": "This example requires the following Softwares to be installed in your machine."
},
{
"code": null,
"e": 577,
"s": 562,
"text": "Install Python"
},
{
"code": null,
"e": 594,
"s": 577,
"text": "Install Selenium"
},
{
"code": null,
"e": 627,
"s": 594,
"text": "Install ChromeDriver and Browser"
},
{
"code": null,
"e": 769,
"s": 627,
"text": "You can follow my previous article about how to install the selenium and kickstart with selenium HelloWorld example to get all prerequisites."
},
{
"code": null,
"e": 832,
"s": 769,
"text": "We are going to automate the Facebook login form using python."
},
{
"code": null,
"e": 1173,
"s": 832,
"text": "from selenium import webdriver\n\ndriver = webdriver.Chrome(executable_path=\"D:\\\\softwares\\\\chromedriver_win\\\\chromedriver.exe\")\ndriver.get(\"http://www.facebook.com\")\ndriver.find_element_by_id(\"email\").send_keys(\"facebookuser\")\ndriver.find_element_by_id(\"pass\").send_keys(\"password\")\ndriver.find_element_by_id(\"u_0_b\").click()\ndriver.close()\n"
},
{
"code": null,
"e": 1215,
"s": 1173,
"text": "importing webdriver from selenium package"
},
{
"code": null,
"e": 1376,
"s": 1215,
"text": "webdriver.Chrome() function is used to launch the web browser. for this, we have to provide the chromedriver.exe path as an executable_path=β{chromedriverpath}β"
},
{
"code": null,
"e": 1477,
"s": 1376,
"text": "diver.get(\"URL\") function loads a web page (http://www.facebook.com) in the current browser session."
},
{
"code": null,
"e": 1678,
"s": 1477,
"text": "driver.find_element_by_id() is a driver function used to finds an element in the web page and returns the element as WebElement. if the element wasnβt found it raises NoSuchElementException exception."
},
{
"code": null,
"e": 1842,
"s": 1678,
"text": "send_keys() is a WebElement function used to send simple key events or form fields. In our case, we are sending Facebook username and passwords to the form fields."
},
{
"code": null,
"e": 1926,
"s": 1842,
"text": "click() is a WebElement function is used to perform the click event on the element."
},
{
"code": null,
"e": 1981,
"s": 1926,
"text": "Finally closing the driver using the close() function."
},
{
"code": null,
"e": 2179,
"s": 1981,
"text": "On the above example, we used find_element_by_id(id) function, this function needs an exact dom element id to find it. So we have to provide that dom element id to this function to get the element."
},
{
"code": null,
"e": 2229,
"s": 2179,
"text": "Inspect the elements using developer tools (F12)."
},
{
"code": null,
"e": 2461,
"s": 2229,
"text": "You can observe the above-highlighted dom elements. We can also use the name and class attributes for selection using find_element_by_name() and find_element_by_class_name() functions respectively, you can find more selectors here,"
},
{
"code": null,
"e": 2469,
"s": 2461,
"text": "Output:"
},
{
"code": null,
"e": 2612,
"s": 2469,
"text": "Finally, run the application so that you could see the browser window popping up and automate the login process from selenium on your behalf π"
},
{
"code": null,
"e": 2674,
"s": 2612,
"text": "C:\\Users\\Lenovo\\python_samples>python selenium_helloworld.py\n"
},
{
"code": null,
"e": 2702,
"s": 2674,
"text": "Selenium Helloworld Example"
},
{
"code": null,
"e": 2729,
"s": 2702,
"text": "Selenium Locating Elements"
},
{
"code": null,
"e": 2746,
"s": 2729,
"text": "Happy Learning π"
},
{
"code": null,
"e": 3371,
"s": 2746,
"text": "\nHow install Python on Windows 10\nHow to upgrade Python PIP version on Windows\nPython raw_input read input from keyboard\nPython Selenium HelloWorld Example\nPython Set Data Structure in Depth\nPython β How to Read Google Search Results in Selenium\nPython β Selenium Download a File in Headless Mode\nPython Tuple Data Structure in Depth\nPython β How to remove duplicate elements from List\nPython List Data Structure In Depth\nHow to Remove Spaces from String in Python\nSpring MVC Login Form Example Tutorials\nBasic Android Login Form Example\nSpring Boot Validation Login Form Example\nPython β How to create Zip File in Python ?\n"
},
{
"code": null,
"e": 3404,
"s": 3371,
"text": "How install Python on Windows 10"
},
{
"code": null,
"e": 3449,
"s": 3404,
"text": "How to upgrade Python PIP version on Windows"
},
{
"code": null,
"e": 3491,
"s": 3449,
"text": "Python raw_input read input from keyboard"
},
{
"code": null,
"e": 3526,
"s": 3491,
"text": "Python Selenium HelloWorld Example"
},
{
"code": null,
"e": 3561,
"s": 3526,
"text": "Python Set Data Structure in Depth"
},
{
"code": null,
"e": 3616,
"s": 3561,
"text": "Python β How to Read Google Search Results in Selenium"
},
{
"code": null,
"e": 3667,
"s": 3616,
"text": "Python β Selenium Download a File in Headless Mode"
},
{
"code": null,
"e": 3704,
"s": 3667,
"text": "Python Tuple Data Structure in Depth"
},
{
"code": null,
"e": 3756,
"s": 3704,
"text": "Python β How to remove duplicate elements from List"
},
{
"code": null,
"e": 3792,
"s": 3756,
"text": "Python List Data Structure In Depth"
},
{
"code": null,
"e": 3835,
"s": 3792,
"text": "How to Remove Spaces from String in Python"
},
{
"code": null,
"e": 3875,
"s": 3835,
"text": "Spring MVC Login Form Example Tutorials"
},
{
"code": null,
"e": 3908,
"s": 3875,
"text": "Basic Android Login Form Example"
},
{
"code": null,
"e": 3950,
"s": 3908,
"text": "Spring Boot Validation Login Form Example"
}
] |
Instead of using a semicolon (;) terminator symbol, is there any other built-in-commands which execute the MySQL query? | With the help of the following built-in commands, MySQL can execute a query even if semicolon (;) terminator symbol is not used.
We can use this command by using \G option. It means to send the current statement to the server to be executed and display the result in vertical format. When we use \G and omitting semicolon(;) in a statement (single or multiple lines), MySQL determines the end of the statement as and when it encounters \G. Consider the example below β
mysql> Select * from ratelist\G
*************************** 1. row ***************************
Sr: 1
Item: A
Price: 502
*************************** 2. row ***************************
Sr: 2
Item: B
Price: 630
*************************** 3. row ***************************
Sr: 3
Item: C
Price: 1005
*************************** 4. row ***************************
Sr: 4
Item: h
Price: 850
*************************** 5. row ***************************
Sr: 5
Item: T
Price: 250
5 rows in set (0.00 sec)
We can use this command by using \g option. It means to send the current statement to the server to be executed. When we use \g and omitting semicolon (;) in a statement (single or multiple line), MySQL determines the end of the statement as and when it encounters \g. It gives the output in same format as we get by using semicolon (;). Consider the example below β
mysql> Select * from ratelist\g
+----+------+-------+
| Sr | Item | Price |
+----+------+-------+
| 1 | A | 502 |
| 2 | B | 630 |
| 3 | C | 1005 |
| 4 | h | 850 |
| 5 | T | 250 |
+----+------+-------+
5 rows in set (0.00 sec) | [
{
"code": null,
"e": 1191,
"s": 1062,
"text": "With the help of the following built-in commands, MySQL can execute a query even if semicolon (;) terminator symbol is not used."
},
{
"code": null,
"e": 1531,
"s": 1191,
"text": "We can use this command by using \\G option. It means to send the current statement to the server to be executed and display the result in vertical format. When we use \\G and omitting semicolon(;) in a statement (single or multiple lines), MySQL determines the end of the statement as and when it encounters \\G. Consider the example below β"
},
{
"code": null,
"e": 2045,
"s": 1531,
"text": "mysql> Select * from ratelist\\G\n*************************** 1. row ***************************\n Sr: 1\n Item: A\nPrice: 502\n*************************** 2. row ***************************\nSr: 2\nItem: B\nPrice: 630\n*************************** 3. row ***************************\n Sr: 3\n Item: C\nPrice: 1005\n*************************** 4. row ***************************\n Sr: 4\n Item: h\nPrice: 850\n*************************** 5. row ***************************\n Sr: 5\n Item: T\nPrice: 250\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2412,
"s": 2045,
"text": "We can use this command by using \\g option. It means to send the current statement to the server to be executed. When we use \\g and omitting semicolon (;) in a statement (single or multiple line), MySQL determines the end of the statement as and when it encounters \\g. It gives the output in same format as we get by using semicolon (;). Consider the example below β"
},
{
"code": null,
"e": 2667,
"s": 2412,
"text": "mysql> Select * from ratelist\\g\n+----+------+-------+\n| Sr | Item | Price |\n+----+------+-------+\n| 1 | A | 502 |\n| 2 | B | 630 |\n| 3 | C | 1005 |\n| 4 | h | 850 |\n| 5 | T | 250 |\n+----+------+-------+\n5 rows in set (0.00 sec)"
}
] |
multiset insert() function in C++ STL - GeeksforGeeks | 17 Nov, 2020
The multiset::insert() is a built-in function in C++ STL which insert elements in the multiset container or inserts the elements from a position to another position from one multiset to a different multiset.
Syntax:
iterator multiset_name.insert(element)
Parameters: The function accepts a mandatory parameter element which is to be inserted in the multiset container.
Return Value: The function returns an iterator pointing to the inserted element in the multiset container.
Below program illustrates the above function:
C++
// C++ program to demonstrate the// multiset::insert(element) function#include <bits/stdc++.h>using namespace std;int main(){ multiset<int> s; // Function to insert elements // in the set container s.insert(1); s.insert(4); s.insert(1); s.insert(5); s.insert(1); cout << "The elements in multiset are: "; for (auto it = s.begin(); it != s.end(); it++) cout << *it << " "; return 0;}
The elements in multiset are: 1 1 1 4 5
Syntax:
iterator multiset_name.insert(iterator position, element)
Parameters: The function accepts two parameters which are described below:
element: It specifies the element to be inserted in the multiset container.
position: It does not specify the position where the insertion is to be done, it only points to a position from where the searching operation is to be started for insertion to make the process faster. The insertion is done according to the order which is followed by the multiset container.
Return Value: The function returns an iterator pointing to the inserted element in the multiset container.
Below program illustrates the above function:
C++
// C++ program to demonstrate the// multiset::insert(iterator, element) function#include <bits/stdc++.h>using namespace std;int main(){ multiset<int> s; // Function to insert elements // in the set container auto itr = s.insert(s.begin(), 1); // the time taken to insertion // is very less as the correct // position for insertion is given itr = s.insert(itr, 4); itr = s.insert(itr, 1); itr = s.insert(itr, 5); // Slow insertion as position is // not given correctly itr = s.insert(s.begin(), 3); cout << "The elements in multiset are: "; for (auto it = s.begin(); it != s.end(); it++) cout << *it << " "; return 0;}
Output:
The elements in multiset are: 1 1 3 4 5
Syntax:
iterator multiset_name.insert(iterator position1, iterator position2)
Parameters: The function accepts two parameters position1 and position2 which specifies the range of elements. All the elements in the range [position1, last) are inserted in another set container.
Return Value: The function returns a multiset which has all the elements in range [position1, last).
Below program illustrates the above function:
C++
// C++ program to demonstrate the// multiset::insert(iteratorposition1, iteratorposition2) function#include <bits/stdc++.h>using namespace std;int main(){ multiset<int> s1; // Function to insert elements // in the set container s1.insert(1); s1.insert(4); s1.insert(1); s1.insert(5); s1.insert(1); s1.insert(3); cout << "The elements in multiset1 are: "; for (auto it = s1.begin(); it != s1.end(); it++) cout << *it << " "; multiset<int> s2; // Function to insert one multiset to another // all elements from where 3 is to end is // inserted to multiset2 s2.insert(s1.find(3), s1.end()); cout << "\nThe elements in multiset2 are: "; for (auto it = s2.begin(); it != s2.end(); it++) cout << *it << " "; return 0;}
The elements in multiset1 are: 1 1 1 3 4 5
The elements in multiset2 are: 3 4 5
arorakashish0911
CPP-Functions
cpp-multiset
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Operator Overloading in C++
Constructors in C++
Socket Programming in C/C++
Virtual Function in C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
Copy Constructor in C++ | [
{
"code": null,
"e": 24644,
"s": 24616,
"text": "\n17 Nov, 2020"
},
{
"code": null,
"e": 24853,
"s": 24644,
"text": "The multiset::insert() is a built-in function in C++ STL which insert elements in the multiset container or inserts the elements from a position to another position from one multiset to a different multiset. "
},
{
"code": null,
"e": 24862,
"s": 24853,
"text": "Syntax: "
},
{
"code": null,
"e": 24903,
"s": 24862,
"text": "iterator multiset_name.insert(element)\n\n"
},
{
"code": null,
"e": 25018,
"s": 24903,
"text": "Parameters: The function accepts a mandatory parameter element which is to be inserted in the multiset container. "
},
{
"code": null,
"e": 25126,
"s": 25018,
"text": "Return Value: The function returns an iterator pointing to the inserted element in the multiset container. "
},
{
"code": null,
"e": 25173,
"s": 25126,
"text": "Below program illustrates the above function: "
},
{
"code": null,
"e": 25177,
"s": 25173,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// multiset::insert(element) function#include <bits/stdc++.h>using namespace std;int main(){ multiset<int> s; // Function to insert elements // in the set container s.insert(1); s.insert(4); s.insert(1); s.insert(5); s.insert(1); cout << \"The elements in multiset are: \"; for (auto it = s.begin(); it != s.end(); it++) cout << *it << \" \"; return 0;}",
"e": 25604,
"s": 25177,
"text": null
},
{
"code": null,
"e": 25649,
"s": 25604,
"text": "The elements in multiset are: 1 1 1 4 5\n\n\n\n\n"
},
{
"code": null,
"e": 25660,
"s": 25651,
"text": "Syntax: "
},
{
"code": null,
"e": 25720,
"s": 25660,
"text": "iterator multiset_name.insert(iterator position, element)\n\n"
},
{
"code": null,
"e": 25796,
"s": 25720,
"text": "Parameters: The function accepts two parameters which are described below: "
},
{
"code": null,
"e": 25872,
"s": 25796,
"text": "element: It specifies the element to be inserted in the multiset container."
},
{
"code": null,
"e": 26163,
"s": 25872,
"text": "position: It does not specify the position where the insertion is to be done, it only points to a position from where the searching operation is to be started for insertion to make the process faster. The insertion is done according to the order which is followed by the multiset container."
},
{
"code": null,
"e": 26270,
"s": 26163,
"text": "Return Value: The function returns an iterator pointing to the inserted element in the multiset container."
},
{
"code": null,
"e": 26316,
"s": 26270,
"text": "Below program illustrates the above function:"
},
{
"code": null,
"e": 26320,
"s": 26316,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// multiset::insert(iterator, element) function#include <bits/stdc++.h>using namespace std;int main(){ multiset<int> s; // Function to insert elements // in the set container auto itr = s.insert(s.begin(), 1); // the time taken to insertion // is very less as the correct // position for insertion is given itr = s.insert(itr, 4); itr = s.insert(itr, 1); itr = s.insert(itr, 5); // Slow insertion as position is // not given correctly itr = s.insert(s.begin(), 3); cout << \"The elements in multiset are: \"; for (auto it = s.begin(); it != s.end(); it++) cout << *it << \" \"; return 0;}",
"e": 26999,
"s": 26320,
"text": null
},
{
"code": null,
"e": 27007,
"s": 26999,
"text": "Output:"
},
{
"code": null,
"e": 27048,
"s": 27007,
"text": "The elements in multiset are: 1 1 3 4 5\n"
},
{
"code": null,
"e": 27057,
"s": 27048,
"text": "Syntax: "
},
{
"code": null,
"e": 27129,
"s": 27057,
"text": "iterator multiset_name.insert(iterator position1, iterator position2)\n\n"
},
{
"code": null,
"e": 27328,
"s": 27129,
"text": "Parameters: The function accepts two parameters position1 and position2 which specifies the range of elements. All the elements in the range [position1, last) are inserted in another set container. "
},
{
"code": null,
"e": 27430,
"s": 27328,
"text": "Return Value: The function returns a multiset which has all the elements in range [position1, last). "
},
{
"code": null,
"e": 27477,
"s": 27430,
"text": "Below program illustrates the above function: "
},
{
"code": null,
"e": 27481,
"s": 27477,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// multiset::insert(iteratorposition1, iteratorposition2) function#include <bits/stdc++.h>using namespace std;int main(){ multiset<int> s1; // Function to insert elements // in the set container s1.insert(1); s1.insert(4); s1.insert(1); s1.insert(5); s1.insert(1); s1.insert(3); cout << \"The elements in multiset1 are: \"; for (auto it = s1.begin(); it != s1.end(); it++) cout << *it << \" \"; multiset<int> s2; // Function to insert one multiset to another // all elements from where 3 is to end is // inserted to multiset2 s2.insert(s1.find(3), s1.end()); cout << \"\\nThe elements in multiset2 are: \"; for (auto it = s2.begin(); it != s2.end(); it++) cout << *it << \" \"; return 0;}",
"e": 28272,
"s": 27481,
"text": null
},
{
"code": null,
"e": 28358,
"s": 28272,
"text": "The elements in multiset1 are: 1 1 1 3 4 5 \nThe elements in multiset2 are: 3 4 5\n\n\n\n\n"
},
{
"code": null,
"e": 28381,
"s": 28364,
"text": "arorakashish0911"
},
{
"code": null,
"e": 28395,
"s": 28381,
"text": "CPP-Functions"
},
{
"code": null,
"e": 28408,
"s": 28395,
"text": "cpp-multiset"
},
{
"code": null,
"e": 28412,
"s": 28408,
"text": "STL"
},
{
"code": null,
"e": 28416,
"s": 28412,
"text": "C++"
},
{
"code": null,
"e": 28420,
"s": 28416,
"text": "STL"
},
{
"code": null,
"e": 28424,
"s": 28420,
"text": "CPP"
},
{
"code": null,
"e": 28522,
"s": 28424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28541,
"s": 28522,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28565,
"s": 28541,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 28592,
"s": 28565,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 28620,
"s": 28592,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28640,
"s": 28620,
"text": "Constructors in C++"
},
{
"code": null,
"e": 28668,
"s": 28640,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 28692,
"s": 28668,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 28727,
"s": 28692,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 28758,
"s": 28727,
"text": "Templates in C++ with Examples"
}
] |
Computing Mass Properties of Ansys Dynamic Models | by Steve Kiefer | Towards Data Science | Ansys is a commercial Finite Element Analysis (FEA) package. While Ansys has acquired and integrated many different analysis tools, its implicit structures package is robust and well-supported. One unique feature of Ansys for its implicit structural solver is the ability to script commands using simple comma-delimited MAPDL commands. whether using the Ansys classic interface or the modern Ansys Mechanical via the Workbench interface, MAPDL can be very useful for pre-processing models and/or post-processing results. This article covers some MAPDL commands to extract mass properties of the whole or parts of a model about user-defined coordinate systems.
When performing dynamic finite element analyses, verifying mass is an important step. It's half the equation after all! For 3D solid models, mass is pretty trivial. However, in dynamic models components are typically represented as shells, beams, and/or springs. In addition, dynamic models often contain non-structural mass such as SURF154 surface elements and point mass elements. Verifying mass can become non-trivial.
In the dark ages before switching to Ansys Mechanical, I would rely heavily on MAPDL text files to define all of the material property and element type data. I would try and group or otherwise control the numbering of these properties (usually in a spreadsheet) so that I could check the element type mass output listing from the solve.out file against what I was intending. If the dynamic representation did not match the component mass (usually obtained from CAD) I would apply βmass factorsβ to densities then rinse and repeat until the individual element type masses and the total mass matched the intended values. While this worked it was a bit cumbersome and didnβt give me the fine control I sometimes wanted.
I now almost exclusively use the Ansys Mechanical application for pre-processing. In Mechanical one can click on individual bodies and get mass from the properties window (without a solve!) or use the selection tool to get mass of multiple selected bodies, the presence of non-structural mass posses a small challenge. With Ansys Mechanical we give up property numbering controls in exchange for an array of ease of use features. You can get some limited information using the selection tool but again, we miss the non structural mass and inertia mass properties.
Over the years i have picked up hints here and there from Sheldon Imaokaβs / Collaborative Solutions now down ansys.net as well as the xansys forum hosted by PADT (which appears inactive). So standing on the shoulders of giants I have created a boiler-plate MAPDL script that uses components to group portions of the model and write out a csv summary file I can then copy/paste into a spreadsheet for additional verification. The main advantages it provides are:
Grouping arbitrary portions of the model using components
Obtain partial model mass properties (including rotational inertia) about arbitrary coordinate system(s)
Formatted output file specifically for mass properties summary
Here is a github repository that includes a couple of versions of MAPDL script files and an example workbench project archive that incorporates them. Lets check out the important bits!
While we could translate the model to the coordinate system of interest, run the analysis, and read the properties from the solve.out file, that isnβt always ideal. Note: we can not use CSYS or RSYS commands to force Ansys to analyze mass about a different coordinate system.
Here is a script that computes the mass properties of the entire model about a user defined coordinate system. Let's walk through it!
In the above section we make sure everything is selected with ALLSEL, then assign our coordinate system id to the cs_mass parameter. my_cs can be an integer if using manual numbering control (or Ansys Classic) or it can be an βAPDL_nameβ defined on the coordinate system property card. We *GET the location and Euler angles of the coordinate system. Note the use of variable replacement syntax (%var_name%) will fill that part of the string or command with the variable value when executed. It's not vital here but will be helpful later.
In this next section we enter the /sol module and run the magic commands (IRLF, & PSOLVE) that form the element matrices so we can get the mass properties but doesnβt run a full solution of the model. Again, this isnβt totally necessary for mass properties of the entire model but we will use it later.
Now we start some calculation! In the above section we are translating the inertia properties from the center of gravity (CG) to the location of the coordinate system. We then create an APDL 2D array and fill it as the inertia tensor.
Here we build the transformation matrix and assign it to an APDL 2D array.
Now for some interesting stuff. In order to use some of the linear algebra commands for matrix multiplication we need to move the APDL arrays to βAPDL mathβ space. We do that with the *DMAT command. Once in βAPDL mathβ we perform the matrix multiplication with appropriate transpose and finally copy the results from APDL math space back to APDL with the *EXPORT command. Next we assign the mass properties to variables that start with my_ which is the default prefix that Mechanical looks for to print the parameter values to the command snippet property card.
While getting the mass properties of the entire model about an arbitrary coordinate system is nice, it is not particularly useful. Here we will extend the commands above by adding components to some arrays, defining a *DO loop, and using *VWRITE commands to write formatted output to a text file. Here is the full file for component based mass properties that i will walk through below.
First we begin by partitioning the model into components that we want to compute the mass properties of. If using the Ansys Mechanical application Named Selections are sent to the solver as components with the same name. One caveat is that Mechanical allows spaces in the name of the Named Selection but the solver does not. Its best to avoid spaces in names of Named Selections. Components can contain nodes or elements but not both. For mass properties we want to use element based components. Typically when selecting any portions of the model for mass properties we also want the non-structural mass on those bodies. Ansys adds distributed non-structural mass using SURF154 elements that share the same nodes as the underlying structural elements but do not add any stiffness. I think this is much more flexible than keeping non-structural mass tied to a property. The snippet below ensures any SURF154 element on the nodes of the elements in the Component are added to the Component. It can be repeated for each Named Selection.
cmsel,s,my_named_selectionnsle,s esln,1 cm,my_named_selection,elem
In a similar fashion we can create a component of a Point Mass element attached to a Remote Point by using the Pilot Node APDL Name property on the Remote Point. Below we create a component that includes the single node point mass element by selecting all elements attached to the pilot node of the remote point which are completely defined by that one node.
nsel,s,node,,my_rp_nameesln,1cm,my_pm_component,elem
Now that we have all of the components created and augmented as necessary to include non-structural mass elements we can move on to the next step. The commands below set the f_name parameter we will use for the filename and initializes two arrays. One array is for strings of component names and the other is for strings of variables assigned to coordinate system IDs. This way I can keep most of the script generic and change out this array for each use.
Next I initialize the output file. The %_wb_userfiles_dir(1)% gets replaced by the absolute path to the project user_files folder in the workbench project directory and %f_name% gets replaced for the string we assigned to the f_name parameter above. I then use *VWRITE to write the header to the file. I initialize a temporary output array outVars and tell Ansys to use a new filename to keep this output segregated from the structural analysis output.
Next we enter the component loop and as with the total model case we start by getting the properties (locations and angles) of the coordinate system for this component. The only difference is the use of the %css(1,j)% to get the parameter value assigned using the name of the variable with the coordinate system ID as the value. We then select only the elements in the component of interest and the associated nodes and issue the IRLF and PSOLVE commands. The beauty with these commands is that Ansys doesnβt have to perform a full solve to get the mass properties of each component.
The next set of commands is exactly the same as the total model case from translating the inertia tensor from the CG to the coordinate system through the *EXPORT command when we bring the rotated tensor back to an APDL 2D array. The only difference is we are inside the loop. I won't repeat them here.
Now instead of assigning the mass properties to variables that start with the my_ prefix we assign them to the outVars array. We then exit the loop and *vwrite our component names, coordinate system variable names, and mass properties for each component. Then close the file with a *cfclos, return to the default filename and post processor.
And here is an example from an output file:
I usually put a command snippet containing these commands in the Solution object of the Mechanical model tree as a post-processing step. Once a solve is completed you should find a my_mass.txt file in the user_files folder of the project directory.
That is it! Check out the github repository for the command snippets, an example output file, and a very simple workbench archive file (version 2020 R1) that contains 2 systems that use these command snippets. I hope this helps you with your dynamic modeling/mass verification adventures in Ansys!
Check out these other Ansys MAPDL related articles: | [
{
"code": null,
"e": 832,
"s": 172,
"text": "Ansys is a commercial Finite Element Analysis (FEA) package. While Ansys has acquired and integrated many different analysis tools, its implicit structures package is robust and well-supported. One unique feature of Ansys for its implicit structural solver is the ability to script commands using simple comma-delimited MAPDL commands. whether using the Ansys classic interface or the modern Ansys Mechanical via the Workbench interface, MAPDL can be very useful for pre-processing models and/or post-processing results. This article covers some MAPDL commands to extract mass properties of the whole or parts of a model about user-defined coordinate systems."
},
{
"code": null,
"e": 1254,
"s": 832,
"text": "When performing dynamic finite element analyses, verifying mass is an important step. It's half the equation after all! For 3D solid models, mass is pretty trivial. However, in dynamic models components are typically represented as shells, beams, and/or springs. In addition, dynamic models often contain non-structural mass such as SURF154 surface elements and point mass elements. Verifying mass can become non-trivial."
},
{
"code": null,
"e": 1971,
"s": 1254,
"text": "In the dark ages before switching to Ansys Mechanical, I would rely heavily on MAPDL text files to define all of the material property and element type data. I would try and group or otherwise control the numbering of these properties (usually in a spreadsheet) so that I could check the element type mass output listing from the solve.out file against what I was intending. If the dynamic representation did not match the component mass (usually obtained from CAD) I would apply βmass factorsβ to densities then rinse and repeat until the individual element type masses and the total mass matched the intended values. While this worked it was a bit cumbersome and didnβt give me the fine control I sometimes wanted."
},
{
"code": null,
"e": 2535,
"s": 1971,
"text": "I now almost exclusively use the Ansys Mechanical application for pre-processing. In Mechanical one can click on individual bodies and get mass from the properties window (without a solve!) or use the selection tool to get mass of multiple selected bodies, the presence of non-structural mass posses a small challenge. With Ansys Mechanical we give up property numbering controls in exchange for an array of ease of use features. You can get some limited information using the selection tool but again, we miss the non structural mass and inertia mass properties."
},
{
"code": null,
"e": 2998,
"s": 2535,
"text": "Over the years i have picked up hints here and there from Sheldon Imaokaβs / Collaborative Solutions now down ansys.net as well as the xansys forum hosted by PADT (which appears inactive). So standing on the shoulders of giants I have created a boiler-plate MAPDL script that uses components to group portions of the model and write out a csv summary file I can then copy/paste into a spreadsheet for additional verification. The main advantages it provides are:"
},
{
"code": null,
"e": 3056,
"s": 2998,
"text": "Grouping arbitrary portions of the model using components"
},
{
"code": null,
"e": 3161,
"s": 3056,
"text": "Obtain partial model mass properties (including rotational inertia) about arbitrary coordinate system(s)"
},
{
"code": null,
"e": 3224,
"s": 3161,
"text": "Formatted output file specifically for mass properties summary"
},
{
"code": null,
"e": 3409,
"s": 3224,
"text": "Here is a github repository that includes a couple of versions of MAPDL script files and an example workbench project archive that incorporates them. Lets check out the important bits!"
},
{
"code": null,
"e": 3685,
"s": 3409,
"text": "While we could translate the model to the coordinate system of interest, run the analysis, and read the properties from the solve.out file, that isnβt always ideal. Note: we can not use CSYS or RSYS commands to force Ansys to analyze mass about a different coordinate system."
},
{
"code": null,
"e": 3819,
"s": 3685,
"text": "Here is a script that computes the mass properties of the entire model about a user defined coordinate system. Let's walk through it!"
},
{
"code": null,
"e": 4357,
"s": 3819,
"text": "In the above section we make sure everything is selected with ALLSEL, then assign our coordinate system id to the cs_mass parameter. my_cs can be an integer if using manual numbering control (or Ansys Classic) or it can be an βAPDL_nameβ defined on the coordinate system property card. We *GET the location and Euler angles of the coordinate system. Note the use of variable replacement syntax (%var_name%) will fill that part of the string or command with the variable value when executed. It's not vital here but will be helpful later."
},
{
"code": null,
"e": 4660,
"s": 4357,
"text": "In this next section we enter the /sol module and run the magic commands (IRLF, & PSOLVE) that form the element matrices so we can get the mass properties but doesnβt run a full solution of the model. Again, this isnβt totally necessary for mass properties of the entire model but we will use it later."
},
{
"code": null,
"e": 4895,
"s": 4660,
"text": "Now we start some calculation! In the above section we are translating the inertia properties from the center of gravity (CG) to the location of the coordinate system. We then create an APDL 2D array and fill it as the inertia tensor."
},
{
"code": null,
"e": 4970,
"s": 4895,
"text": "Here we build the transformation matrix and assign it to an APDL 2D array."
},
{
"code": null,
"e": 5532,
"s": 4970,
"text": "Now for some interesting stuff. In order to use some of the linear algebra commands for matrix multiplication we need to move the APDL arrays to βAPDL mathβ space. We do that with the *DMAT command. Once in βAPDL mathβ we perform the matrix multiplication with appropriate transpose and finally copy the results from APDL math space back to APDL with the *EXPORT command. Next we assign the mass properties to variables that start with my_ which is the default prefix that Mechanical looks for to print the parameter values to the command snippet property card."
},
{
"code": null,
"e": 5919,
"s": 5532,
"text": "While getting the mass properties of the entire model about an arbitrary coordinate system is nice, it is not particularly useful. Here we will extend the commands above by adding components to some arrays, defining a *DO loop, and using *VWRITE commands to write formatted output to a text file. Here is the full file for component based mass properties that i will walk through below."
},
{
"code": null,
"e": 6953,
"s": 5919,
"text": "First we begin by partitioning the model into components that we want to compute the mass properties of. If using the Ansys Mechanical application Named Selections are sent to the solver as components with the same name. One caveat is that Mechanical allows spaces in the name of the Named Selection but the solver does not. Its best to avoid spaces in names of Named Selections. Components can contain nodes or elements but not both. For mass properties we want to use element based components. Typically when selecting any portions of the model for mass properties we also want the non-structural mass on those bodies. Ansys adds distributed non-structural mass using SURF154 elements that share the same nodes as the underlying structural elements but do not add any stiffness. I think this is much more flexible than keeping non-structural mass tied to a property. The snippet below ensures any SURF154 element on the nodes of the elements in the Component are added to the Component. It can be repeated for each Named Selection."
},
{
"code": null,
"e": 7020,
"s": 6953,
"text": "cmsel,s,my_named_selectionnsle,s esln,1 cm,my_named_selection,elem"
},
{
"code": null,
"e": 7379,
"s": 7020,
"text": "In a similar fashion we can create a component of a Point Mass element attached to a Remote Point by using the Pilot Node APDL Name property on the Remote Point. Below we create a component that includes the single node point mass element by selecting all elements attached to the pilot node of the remote point which are completely defined by that one node."
},
{
"code": null,
"e": 7432,
"s": 7379,
"text": "nsel,s,node,,my_rp_nameesln,1cm,my_pm_component,elem"
},
{
"code": null,
"e": 7888,
"s": 7432,
"text": "Now that we have all of the components created and augmented as necessary to include non-structural mass elements we can move on to the next step. The commands below set the f_name parameter we will use for the filename and initializes two arrays. One array is for strings of component names and the other is for strings of variables assigned to coordinate system IDs. This way I can keep most of the script generic and change out this array for each use."
},
{
"code": null,
"e": 8341,
"s": 7888,
"text": "Next I initialize the output file. The %_wb_userfiles_dir(1)% gets replaced by the absolute path to the project user_files folder in the workbench project directory and %f_name% gets replaced for the string we assigned to the f_name parameter above. I then use *VWRITE to write the header to the file. I initialize a temporary output array outVars and tell Ansys to use a new filename to keep this output segregated from the structural analysis output."
},
{
"code": null,
"e": 8925,
"s": 8341,
"text": "Next we enter the component loop and as with the total model case we start by getting the properties (locations and angles) of the coordinate system for this component. The only difference is the use of the %css(1,j)% to get the parameter value assigned using the name of the variable with the coordinate system ID as the value. We then select only the elements in the component of interest and the associated nodes and issue the IRLF and PSOLVE commands. The beauty with these commands is that Ansys doesnβt have to perform a full solve to get the mass properties of each component."
},
{
"code": null,
"e": 9227,
"s": 8925,
"text": "The next set of commands is exactly the same as the total model case from translating the inertia tensor from the CG to the coordinate system through the *EXPORT command when we bring the rotated tensor back to an APDL 2D array. The only difference is we are inside the loop. I won't repeat them here."
},
{
"code": null,
"e": 9569,
"s": 9227,
"text": "Now instead of assigning the mass properties to variables that start with the my_ prefix we assign them to the outVars array. We then exit the loop and *vwrite our component names, coordinate system variable names, and mass properties for each component. Then close the file with a *cfclos, return to the default filename and post processor."
},
{
"code": null,
"e": 9613,
"s": 9569,
"text": "And here is an example from an output file:"
},
{
"code": null,
"e": 9862,
"s": 9613,
"text": "I usually put a command snippet containing these commands in the Solution object of the Mechanical model tree as a post-processing step. Once a solve is completed you should find a my_mass.txt file in the user_files folder of the project directory."
},
{
"code": null,
"e": 10160,
"s": 9862,
"text": "That is it! Check out the github repository for the command snippets, an example output file, and a very simple workbench archive file (version 2020 R1) that contains 2 systems that use these command snippets. I hope this helps you with your dynamic modeling/mass verification adventures in Ansys!"
}
] |
Adding a new NOT NULL column to an existing table with records | To add a new NOT NULL column to an already created table, use ALTER command. Let us first create a table β
mysql> create table DemoTable
-> (
-> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentName varchar(20)
-> );
Query OK, 0 rows affected (0.60 sec)
Following is the query to add a new NOT NULL column to an existing table β
mysql> alter table DemoTable add column StudentAge int NOT NULL;
Query OK, 0 rows affected (0.52 sec)
Records: 0 Duplicates: 0 Warnings: 0
Insert some records in the table using insert command β
mysql> insert into DemoTable(StudentName,StudentAge) values('Chris',21);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName,StudentAge) values('David',23);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentName,StudentAge) values('Mike',NULL);
ERROR 1048 (23000): Column 'StudentAge' cannot be null
Display all records from the table using select statement β
mysql> select * from DemoTable;
This will produce the following output β
+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 1 | Chris | 21 |
| 2 | David | 23 |
+-----------+-------------+------------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "To add a new NOT NULL column to an already created table, use ALTER command. Let us first create a table β"
},
{
"code": null,
"e": 1340,
"s": 1169,
"text": "mysql> create table DemoTable\n -> (\n -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.60 sec)"
},
{
"code": null,
"e": 1415,
"s": 1340,
"text": "Following is the query to add a new NOT NULL column to an existing table β"
},
{
"code": null,
"e": 1554,
"s": 1415,
"text": "mysql> alter table DemoTable add column StudentAge int NOT NULL;\nQuery OK, 0 rows affected (0.52 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 1610,
"s": 1554,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1957,
"s": 1610,
"text": "mysql> insert into DemoTable(StudentName,StudentAge) values('Chris',21);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(StudentName,StudentAge) values('David',23);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(StudentName,StudentAge) values('Mike',NULL);\nERROR 1048 (23000): Column 'StudentAge' cannot be null"
},
{
"code": null,
"e": 2017,
"s": 1957,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 2049,
"s": 2017,
"text": "mysql> select * from DemoTable;"
},
{
"code": null,
"e": 2090,
"s": 2049,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2361,
"s": 2090,
"text": "+-----------+-------------+------------+\n| StudentId | StudentName | StudentAge |\n+-----------+-------------+------------+\n| 1 | Chris | 21 |\n| 2 | David | 23 |\n+-----------+-------------+------------+\n2 rows in set (0.00 sec)"
}
] |
Format function in Python. Pythonβs str.format() technique of the... | by sunil kumar | Towards Data Science | Pythonβs str.format() technique of the string category permits you to try and do variable substitutions and data formatting. This enables you to concatenate parts of a string at desired intervals through point data format.
This article can guide you through a number of the common uses of formatters in Python, which may help your code and program to be user friendly.
1) Single Formatter:
Formatters work by fixing one or a lot of replacement fields or placeholders outlined by a pair of curled brackets β{}β β into a string and calling the str.format() technique. Youβll pass into the format() method the value you wish to concatenate with the string. This value will be printed in the same place that your placeholder {} is positioned once you run the program. Single formatters can be defined as those where there is only one placeholder. In the below example you can see the implementation of format in the print statement.
print("{} is a good option for beginners in python".format("Research Papers"))OUTPUT:Research Papers is a good option for beginners in python
Apart from directly using it in the print statement, we can also use format() to a variable
my_string = "{} is a good option for beginners in python"print(my_string.format("Research Papers"))OUTPUT:Research Papers is a good option for beginners in python
2) Multiple Formatter:
Letβs say if there is another variable substitution required in a sentence, this can be done by adding a second curly bracket where we want the substitution and passing a second value into format(). Python will then replace the placeholders by values that are passed in the inputs.
my_string = "{} is a good option for beginners in {}"print(my_string.format("Research Papers","Machine Learning"))OUTPUT:Research Papers is a good option for beginners in Machine Learning
We can add any number of placeholders or curly brackets that we require in a given variable along with the same number of inputs for the format().
my_string = "{} is an {} option for {} in {}"print(my_string.format("Research Papers","excellent","experienced","Machine Learning"))OUTPUT:Research Papers is an excellent option for experienced in Machine Learning
3) Formatters using Positional and Keyword Arguments:
When placeholders are empty {}, Python interpreter will be replacing the values through str.format() in order.
The values that exist among the str.format() method are primarily tuple (βA tuple is a sequence of immutable Python objectsβ) data types and every individual item contained within the tuple are often referred by its index number, which starts with zero. These index numbers are then passed into the curly brackets within the original string.
You can use the positional arguments or the index numbers inside the curly brackets in order to get that particular value from the format() into your variable:
my_string = "{0} is a good option for beginners in {1}"print(my_string.format("Research Papers","Machine Learning"))OUTPUT:Research Papers is a good option for beginners in Machine Learningmy_string = "{1} is a good option for beginners in {0}"print(my_string.format("Research Papers","Machine Learning"))OUTPUT:Machine Learning is a good option for beginners in Research Papers
Keyword arguments help to call the variable in format() by calling that variable name inside the curly brackets:
my_string = "{0} is a good option for beginners in {domain}"print(my_string.format("Research Papers",domain = "Machine Learning"))OUTPUT:Research Papers is a good option for beginners in Machine Learning
We can use both the keyword and positional arguments together:
my_string = "{domain} is a good option for beginners in {0}"print(my_string.format("Research Papers",domain = "Artificial Intelligence"))OUTPUT:Artificial Intelligence is a good option for beginners in Research Papers
4) Type Specification:
More parameters can be enclosed among the curly brackets of our syntax by using format code syntax. In this syntax, wherever field_name is, there it specifies the indicant of the argument or keyword to the str.format() technique, and conversion refers to the conversion code of the data type. Some conversion types are:
s β strings
d β decimal integers (base-10)
f β float
c β character
b β binary
o β octal
x β hexadecimal with lowercase letters after 9
e β exponent notation
my_string = "The Temperature in {0} today is {1:d} degrees outside!"print(my_string.format("Research Papers",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!
Make sure you are using the correct conversion. You will get the below error if you are using different conversion codes :
my_string = "The Temperature in {0} today is {1:d} degrees outside!"print(my_string.format("Vizag",22.025))--------------------------------------------------------------------ValueError Traceback (most recent call last) in () 1 my_string = "The Temperature in {0} today is {1:d} degrees outside!" ----> 2 print(my_string.format("Vizag",22.025)) ValueError: Unknown format code 'd' for object of type 'float'
You can even limit the number of decimal points in a floating integer:
my_string = "The Temperature in {0} today is {1:f} degrees outside!"print(my_string.format("Vizag",22.025))OUTPUT:The Temperature in Vizag today is 22.025000 degrees outside!my_string = "The Temperature in {0:20} today is {1:.2f} degrees outside!"print(my_string.format("Vizag",22))OUTPUT:The Temperature in Vizag today is 22.02 degrees outside!
5) Spacing and Alignments using formatter:
We can use the format() to apply spaces or alignment to the right or left or both sides of placeholder. The alignment codes are:
< : left-align text
^ : center text
> : right-align
my_string = "The Temperature in {0:20} today is {1:d} degrees outside!"print(my_string.format("Vizag",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!my_string = "The Temperature in {0} today is {1:20} degrees outside!"print(my_string.format("Vizag",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!
We can see that strings are left-justified and numbers are right-justified. By using format() we can alter both of them as below:
my_string = "The Temperature in {0:>20} today is {1:d} degrees outside!"print(my_string.format("Vizag",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!my_string = "The Temperature in {0:<20} today is {1:d} degrees outside!"print(my_string.format("Vizag",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!my_string = "The Temperature in {0:^20} today is {1:d} degrees outside!"print(my_string.format("Vizag",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!
6 )Organizing data:
We tend to organize data in Excel sheet where we can adjust the column size in various methods, but how can we apply the same thing in the program where the values in a column increments in an exponential way and the items in one column comes into the other or the end user may find difficult to understand which value belongs to which column.
for i in range(4,15): print(i,i*i,i*i*i)OUTPUT: 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 11 121 1331 12 144 1728 13 169 2197 14 196 2744
This is where we can use format() to define the space between each column so that the end user can easily differentiate between values of different columns.
for i in range(4,15): print("{:6d} {:6d} {:6d}".format(i,i*i,i*i*i))OUTPUT: 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 11 121 1331 12 144 1728 13 169 2197 14 196 2744
Summary:
From the above uses, we can say that formatters for variable substitution are an effective way to concatenate strings, convert values, organize values and data. Formatters represent an easy however non-descriptive manner for passing variable substitutions into a string, and are helpful for creating certain output that is decipherable and user friendly. | [
{
"code": null,
"e": 394,
"s": 171,
"text": "Pythonβs str.format() technique of the string category permits you to try and do variable substitutions and data formatting. This enables you to concatenate parts of a string at desired intervals through point data format."
},
{
"code": null,
"e": 540,
"s": 394,
"text": "This article can guide you through a number of the common uses of formatters in Python, which may help your code and program to be user friendly."
},
{
"code": null,
"e": 561,
"s": 540,
"text": "1) Single Formatter:"
},
{
"code": null,
"e": 1100,
"s": 561,
"text": "Formatters work by fixing one or a lot of replacement fields or placeholders outlined by a pair of curled brackets β{}β β into a string and calling the str.format() technique. Youβll pass into the format() method the value you wish to concatenate with the string. This value will be printed in the same place that your placeholder {} is positioned once you run the program. Single formatters can be defined as those where there is only one placeholder. In the below example you can see the implementation of format in the print statement."
},
{
"code": null,
"e": 1242,
"s": 1100,
"text": "print(\"{} is a good option for beginners in python\".format(\"Research Papers\"))OUTPUT:Research Papers is a good option for beginners in python"
},
{
"code": null,
"e": 1334,
"s": 1242,
"text": "Apart from directly using it in the print statement, we can also use format() to a variable"
},
{
"code": null,
"e": 1497,
"s": 1334,
"text": "my_string = \"{} is a good option for beginners in python\"print(my_string.format(\"Research Papers\"))OUTPUT:Research Papers is a good option for beginners in python"
},
{
"code": null,
"e": 1520,
"s": 1497,
"text": "2) Multiple Formatter:"
},
{
"code": null,
"e": 1802,
"s": 1520,
"text": "Letβs say if there is another variable substitution required in a sentence, this can be done by adding a second curly bracket where we want the substitution and passing a second value into format(). Python will then replace the placeholders by values that are passed in the inputs."
},
{
"code": null,
"e": 1990,
"s": 1802,
"text": "my_string = \"{} is a good option for beginners in {}\"print(my_string.format(\"Research Papers\",\"Machine Learning\"))OUTPUT:Research Papers is a good option for beginners in Machine Learning"
},
{
"code": null,
"e": 2137,
"s": 1990,
"text": "We can add any number of placeholders or curly brackets that we require in a given variable along with the same number of inputs for the format()."
},
{
"code": null,
"e": 2351,
"s": 2137,
"text": "my_string = \"{} is an {} option for {} in {}\"print(my_string.format(\"Research Papers\",\"excellent\",\"experienced\",\"Machine Learning\"))OUTPUT:Research Papers is an excellent option for experienced in Machine Learning"
},
{
"code": null,
"e": 2405,
"s": 2351,
"text": "3) Formatters using Positional and Keyword Arguments:"
},
{
"code": null,
"e": 2516,
"s": 2405,
"text": "When placeholders are empty {}, Python interpreter will be replacing the values through str.format() in order."
},
{
"code": null,
"e": 2858,
"s": 2516,
"text": "The values that exist among the str.format() method are primarily tuple (βA tuple is a sequence of immutable Python objectsβ) data types and every individual item contained within the tuple are often referred by its index number, which starts with zero. These index numbers are then passed into the curly brackets within the original string."
},
{
"code": null,
"e": 3018,
"s": 2858,
"text": "You can use the positional arguments or the index numbers inside the curly brackets in order to get that particular value from the format() into your variable:"
},
{
"code": null,
"e": 3397,
"s": 3018,
"text": "my_string = \"{0} is a good option for beginners in {1}\"print(my_string.format(\"Research Papers\",\"Machine Learning\"))OUTPUT:Research Papers is a good option for beginners in Machine Learningmy_string = \"{1} is a good option for beginners in {0}\"print(my_string.format(\"Research Papers\",\"Machine Learning\"))OUTPUT:Machine Learning is a good option for beginners in Research Papers"
},
{
"code": null,
"e": 3510,
"s": 3397,
"text": "Keyword arguments help to call the variable in format() by calling that variable name inside the curly brackets:"
},
{
"code": null,
"e": 3714,
"s": 3510,
"text": "my_string = \"{0} is a good option for beginners in {domain}\"print(my_string.format(\"Research Papers\",domain = \"Machine Learning\"))OUTPUT:Research Papers is a good option for beginners in Machine Learning"
},
{
"code": null,
"e": 3777,
"s": 3714,
"text": "We can use both the keyword and positional arguments together:"
},
{
"code": null,
"e": 3995,
"s": 3777,
"text": "my_string = \"{domain} is a good option for beginners in {0}\"print(my_string.format(\"Research Papers\",domain = \"Artificial Intelligence\"))OUTPUT:Artificial Intelligence is a good option for beginners in Research Papers"
},
{
"code": null,
"e": 4018,
"s": 3995,
"text": "4) Type Specification:"
},
{
"code": null,
"e": 4338,
"s": 4018,
"text": "More parameters can be enclosed among the curly brackets of our syntax by using format code syntax. In this syntax, wherever field_name is, there it specifies the indicant of the argument or keyword to the str.format() technique, and conversion refers to the conversion code of the data type. Some conversion types are:"
},
{
"code": null,
"e": 4350,
"s": 4338,
"text": "s β strings"
},
{
"code": null,
"e": 4381,
"s": 4350,
"text": "d β decimal integers (base-10)"
},
{
"code": null,
"e": 4391,
"s": 4381,
"text": "f β float"
},
{
"code": null,
"e": 4405,
"s": 4391,
"text": "c β character"
},
{
"code": null,
"e": 4416,
"s": 4405,
"text": "b β binary"
},
{
"code": null,
"e": 4426,
"s": 4416,
"text": "o β octal"
},
{
"code": null,
"e": 4473,
"s": 4426,
"text": "x β hexadecimal with lowercase letters after 9"
},
{
"code": null,
"e": 4495,
"s": 4473,
"text": "e β exponent notation"
},
{
"code": null,
"e": 4669,
"s": 4495,
"text": "my_string = \"The Temperature in {0} today is {1:d} degrees outside!\"print(my_string.format(\"Research Papers\",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!"
},
{
"code": null,
"e": 4792,
"s": 4669,
"text": "Make sure you are using the correct conversion. You will get the below error if you are using different conversion codes :"
},
{
"code": null,
"e": 5239,
"s": 4792,
"text": "my_string = \"The Temperature in {0} today is {1:d} degrees outside!\"print(my_string.format(\"Vizag\",22.025))--------------------------------------------------------------------ValueError Traceback (most recent call last) in () 1 my_string = \"The Temperature in {0} today is {1:d} degrees outside!\" ----> 2 print(my_string.format(\"Vizag\",22.025)) ValueError: Unknown format code 'd' for object of type 'float'"
},
{
"code": null,
"e": 5310,
"s": 5239,
"text": "You can even limit the number of decimal points in a floating integer:"
},
{
"code": null,
"e": 5656,
"s": 5310,
"text": "my_string = \"The Temperature in {0} today is {1:f} degrees outside!\"print(my_string.format(\"Vizag\",22.025))OUTPUT:The Temperature in Vizag today is 22.025000 degrees outside!my_string = \"The Temperature in {0:20} today is {1:.2f} degrees outside!\"print(my_string.format(\"Vizag\",22))OUTPUT:The Temperature in Vizag today is 22.02 degrees outside!"
},
{
"code": null,
"e": 5699,
"s": 5656,
"text": "5) Spacing and Alignments using formatter:"
},
{
"code": null,
"e": 5828,
"s": 5699,
"text": "We can use the format() to apply spaces or alignment to the right or left or both sides of placeholder. The alignment codes are:"
},
{
"code": null,
"e": 5848,
"s": 5828,
"text": "< : left-align text"
},
{
"code": null,
"e": 5864,
"s": 5848,
"text": "^ : center text"
},
{
"code": null,
"e": 5880,
"s": 5864,
"text": "> : right-align"
},
{
"code": null,
"e": 6244,
"s": 5880,
"text": "my_string = \"The Temperature in {0:20} today is {1:d} degrees outside!\"print(my_string.format(\"Vizag\",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!my_string = \"The Temperature in {0} today is {1:20} degrees outside!\"print(my_string.format(\"Vizag\",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!"
},
{
"code": null,
"e": 6374,
"s": 6244,
"text": "We can see that strings are left-justified and numbers are right-justified. By using format() we can alter both of them as below:"
},
{
"code": null,
"e": 6921,
"s": 6374,
"text": "my_string = \"The Temperature in {0:>20} today is {1:d} degrees outside!\"print(my_string.format(\"Vizag\",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!my_string = \"The Temperature in {0:<20} today is {1:d} degrees outside!\"print(my_string.format(\"Vizag\",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!my_string = \"The Temperature in {0:^20} today is {1:d} degrees outside!\"print(my_string.format(\"Vizag\",22))OUTPUT:The Temperature in Vizag today is 22 degrees outside!"
},
{
"code": null,
"e": 6941,
"s": 6921,
"text": "6 )Organizing data:"
},
{
"code": null,
"e": 7285,
"s": 6941,
"text": "We tend to organize data in Excel sheet where we can adjust the column size in various methods, but how can we apply the same thing in the program where the values in a column increments in an exponential way and the items in one column comes into the other or the end user may find difficult to understand which value belongs to which column."
},
{
"code": null,
"e": 7448,
"s": 7285,
"text": "for i in range(4,15): print(i,i*i,i*i*i)OUTPUT: 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 11 121 1331 12 144 1728 13 169 2197 14 196 2744"
},
{
"code": null,
"e": 7605,
"s": 7448,
"text": "This is where we can use format() to define the space between each column so that the end user can easily differentiate between values of different columns."
},
{
"code": null,
"e": 7915,
"s": 7605,
"text": "for i in range(4,15): print(\"{:6d} {:6d} {:6d}\".format(i,i*i,i*i*i))OUTPUT: 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 11 121 1331 12 144 1728 13 169 2197 14 196 2744"
},
{
"code": null,
"e": 7924,
"s": 7915,
"text": "Summary:"
}
] |
A Review of Named Entity Recognition (NER) Using Automatic Summarization of Resumes | by Mohan Gupta | Towards Data Science | Understand what NER is and how it is used in the industry, various libraries for NER, code walk through of using NER for resume summarization.
This blog speaks about a field in Natural language Processing (NLP) and Information Retrieval (IR) called Named Entity Recognition and how we can apply it for automatically generating summaries of resumes by extracting only chief entities like name, education background, skills, etc.
Named-entity recognition (NER) (also known as entity identification, entity chunking and entity extraction) is a sub-task of information extraction that seeks to locate and classify named entities in text into pre-defined categories such as the names of persons, organizations, locations, expressions of times, quantities, monetary values, percentages, etc.
NER systems have been created that use linguistic grammar-based techniques as well as statistical models such as machine learning. Hand-crafted grammar-based systems typically obtain better precision, but at the cost of lower recall and months of work by experienced computational linguists . Statistical NER systems typically require a large amount of manually annotated training data. Semi-supervised approaches have been suggested to avoid part of the annotation effort.
Being a free and an open-source library, spaCy has made advanced Natural Language Processing (NLP) much simpler in Python.
spaCy provides an exceptionally efficient statistical system for named entity recognition in python, which can assign labels to groups of tokens which are contiguous. It provides a default model which can recognize a wide range of named or numerical entities, which include company-name, location, organization, product-name, etc to name a few. Apart from these default entities, spaCy enables the addition of arbitrary classes to the entity-recognition model, by training the model to update it with newer trained examples.
Model Architecture :
The statistical models in spaCy are custom-designed and provide an exceptional performance mixture of both speed, as well as accuracy. The current architecture used has not been published yet, but the following video gives an overview as to how the model works with primary focus on NER model.
Stanford NER is a Named Entity Recognizer, implemented in Java. It provides a default trained model for recognizing chiefly entities like Organization, Person and Location. Apart from this, various models trained for different languages and circumstances are also available.
Model Architecture :
Stanford NER is also referred to as a CRF (Conditional Random Field) Classifier as Linear chain Conditional Random Field (CRF) sequence models have been implemented in the software. We can train our own custom models with our own labeled dataset for various applications.
CRF models were originally pioneered by Lafferty, McCallum, and Pereira (2001); Please refer to Sutton and McCallum (2006) or Sutton and McCallum (2010) for detailed comprehensible introductions.
Named Entity Recognition has a wide range of applications in the field of Natural Language Processing and Information Retrieval. Few such examples have been listed below :
One of the key challenges faced by the HR Department across companies is to evaluate a gigantic pile of resumes to shortlist candidates. To add to their burden, resumes of applicants are often excessively populated in detail, of which, most of the information is irrelevant to what the evaluator is seeking. With the aim of simplifying this process, through our NER model, we could facilitate evaluation of resumes at a quick glance, thereby simplifying the effort required in shortlisting candidates among a pile of resumes.
To design a search engine algorithm, instead of searching for an entered query across the millions of articles and websites online, a more efficient approach would be to run an NER model on the articles once and store the entities associated with them permanently. The key tags in the search query can then be compared with the tags associated with the website articles for a quick and efficient search.
NER can be used in developing algorithms for recommender systems which automatically filter relevant content we might be interested in and accordingly guide us to discover related and unvisited relevant contents based on our previous behaviour. This may be achieved by extracting the entities associated with the content in our history or previous activity and comparing them with label assigned to other unseen content to filter relevant ones.
NER can be used in recognizing relevant entities in customer complaints and feedback such as Product specifications, department or company branch details, so that the feedback is classified accordingly and forwarded to the appropriate department responsible for the identified product.
We describe summarization of resumes using NER models in detail in the further sections.
The first task at hand of course is to create manually annotated training data to train the model. For this purpose, 220 resumes were downloaded from an online jobs platform. These documents were uploaded to Dataturks online annotation tool and manually annotated.
The tool automatically parses the documents and allows for us to create annotations of important entities we are interested in and generates JSON formatted training data with each line containing the text corpus along with the annotations.
A snapshot of the dataset can be seen below :
The above dataset consisting of 220 annotated resumes can be found here. We train the model with 200 resume data and test it on 20 resume data.
Dataset format :
A sample of the generated json formatted data generated by the Dataturks annotation tool, which is supplied to the code is as follows :
Training the Model :
We use pythonβs spaCy module for training the NER model. spaCyβs models are statistical and every βdecisionβ they make β for example, which part-of-speech tag to assign, or whether a word is a named entity β is a prediction. This prediction is based on the examples the model has seen during training.
The model is then shown the unlabelled text and will make a prediction. Because we know the correct answer, we can give the model feedback on its prediction in the form of an error gradient of the loss function that calculates the difference between the training example and the expected output. The greater the difference, the more significant the gradient and the updates to our model.
When training a model, we donβt just want it to memorise our examples β we want it to come up with theory that can be generalised across other examples. After all, we donβt just want the model to learn that this one instance of βAmazonβ right here is a company β we want it to learn that βAmazonβ, in contexts like this, is most likely a company. In order to tune the accuracy, we process our training examples in batches, and experiment with minibatch sizes and dropout rates.
Of course, itβs not enough to only show a model a single example once. Especially if you only have few examples, youβll want to train for a number of iterations. At each iteration, the training data is shuffled to ensure the model doesnβt make any generalisations based on the order of examples.
Another technique to improve the learning results is to set a dropout rate, a rate at which to randomly βdropβ individual features and representations. This makes it harder for the model to memorise the training data. For example, a 0.25dropout means that each feature or internal representation has a 1/4 likelihood of being dropped. We train the model for 10 epochs and keep the dropout rate as 0.2.
Hereβs a code snippet for training the model :
github.com
Results and Evaluation of the spaCy model :
The model is tested on 20 resumes and the predicted summarized resumes are stored as separate .txt files for each resume.
For each resume on which the model is tested, we calculate the accuracy score, precision, recall and f-score for each entity that the model recognizes. The values of these metrics for each entity are summed up and averaged to generate an overall score to evaluate the model on the test data consisting of 20 resumes. The entity wise evaluation results can be observed below . It is observed that the results obtained have been predicted with a commendable accuracy.
A sample summary of an unseen resume of an employee from indeed.com obtained by prediction by our model is shown below :
Dataset Format :
The data for training has to be passed as a text file such that every line contains a word-label pair, where the word and the label tag are separated by a tab space β\tβ. For a text document,as in our case, we tokenize documents into words and add one line for each word and associated tag into the training file. To indicate the start of the next file, we add an empty line in the training file.
Here is a sample of the input training file:
Note: It is compulsory to include a label/tag for each word. Here, for words we do not care about we are using the label zero β0β.
Properties file :
Stanford CoreNLP requires a properties file where the parameters necessary for building a custom model. For instance, we may define ways of extracting features for learning, etc. Following is an example of a properties file:
# location of the training filetrainFile = ./standford_train.txt# location where you would like to save (serialize) your# classifier; adding .gz at the end automatically gzips the file,# making it smaller, and faster to loadserializeTo = ner-model.ser.gz# structure of your training file; this tells the classifier that# the word is in column 0 and the correct answer is in column 1map = word=0,answer=1# This specifies the order of the CRF: order 1 means that features# apply at most to a class pair of previous class and current class# or current class and next class.maxLeft=1# these are the features we'd like to train with# some are discussed below, the rest can be# understood by looking at NERFeatureFactoryuseClassFeature=trueuseWord=true# word character ngrams will be included up to length 6 as prefixes# and suffixes onlyuseNGrams=truenoMidNGrams=truemaxNGramLeng=6usePrev=trueuseNext=trueuseDisjunctive=trueuseSequences=trueusePrevSequences=true# the last 4 properties deal with word shape featuresuseTypeSeqs=trueuseTypeSeqs2=trueuseTypeySequences=true#wordShape=chris2useLCwordShape=none#useBoundarySequences=true#useNeighborNGrams=true#useTaggySequences=true#printFeatures=true#saveFeatureIndexToDisk = true#useObservedSequencesOnly = true#useWordPairs = true
Training the model :
The chief class in Stanford CoreNLP is CRFClassifier, which possesses the actual model. In the code provided in the Github repository, the link to which has been attached below, we have provided the code to train the model using the training data and the properties file and save the model to disk to avoid time consumption for training each time. Next time we use the model for prediction on an unseen document, we just load the trained model from disk and use to for classification.
The first column in the output contains the input tokens while the second column refers to the correct label, and the third column is the label predicted by the classifier.
Hereβs a Code snippet for training the model and saving it to disk:
github.com
Results and Evaluation of the Stanford NER model :
The model is tested on 20 resumes and the predicted summarized resumes are stored as separate .txt files for each resume.
For each resume on which the model is tested, we calculate the accuracy score, precision, recall and f-score for each entity that the model recognizes. The values of these metrics for each entity are summed up and averaged to generate an overall score to evaluate the model on the test data consisting of 20 resumes. The entity wise evaluation results can be observed below . It is observed that the results obtained have been predicted with a commendable accuracy.
A sample summary of an unseen resume of an employee from indeed.com obtained by prediction by our model is shown below :
The vast majority of tokens in real-world resume documents are not part of entity names as usually defined, so the baseline precision, recall is extravagantly high, typically >90%; going by this logic, the entity wise precision recall values of both the models are reasonably good.
From the evaluation of the models and the observed outputs, spaCy seems to outperform Stanford NER for the task of summarizing resumes. A review of the F-scores for the entities identified by both models is as follows :
Here is the dataset of the resumes tagged with NER entities.
The Python code for the above project for training the spaCy model can be found here in the github repository.
The Java code for the above project for training the Stanford NER model can be found here in the GitHub repository.
Note: This blog is an extended version of the NER blog published at Dataturks. | [
{
"code": null,
"e": 314,
"s": 171,
"text": "Understand what NER is and how it is used in the industry, various libraries for NER, code walk through of using NER for resume summarization."
},
{
"code": null,
"e": 599,
"s": 314,
"text": "This blog speaks about a field in Natural language Processing (NLP) and Information Retrieval (IR) called Named Entity Recognition and how we can apply it for automatically generating summaries of resumes by extracting only chief entities like name, education background, skills, etc."
},
{
"code": null,
"e": 957,
"s": 599,
"text": "Named-entity recognition (NER) (also known as entity identification, entity chunking and entity extraction) is a sub-task of information extraction that seeks to locate and classify named entities in text into pre-defined categories such as the names of persons, organizations, locations, expressions of times, quantities, monetary values, percentages, etc."
},
{
"code": null,
"e": 1431,
"s": 957,
"text": "NER systems have been created that use linguistic grammar-based techniques as well as statistical models such as machine learning. Hand-crafted grammar-based systems typically obtain better precision, but at the cost of lower recall and months of work by experienced computational linguists . Statistical NER systems typically require a large amount of manually annotated training data. Semi-supervised approaches have been suggested to avoid part of the annotation effort."
},
{
"code": null,
"e": 1554,
"s": 1431,
"text": "Being a free and an open-source library, spaCy has made advanced Natural Language Processing (NLP) much simpler in Python."
},
{
"code": null,
"e": 2079,
"s": 1554,
"text": "spaCy provides an exceptionally efficient statistical system for named entity recognition in python, which can assign labels to groups of tokens which are contiguous. It provides a default model which can recognize a wide range of named or numerical entities, which include company-name, location, organization, product-name, etc to name a few. Apart from these default entities, spaCy enables the addition of arbitrary classes to the entity-recognition model, by training the model to update it with newer trained examples."
},
{
"code": null,
"e": 2100,
"s": 2079,
"text": "Model Architecture :"
},
{
"code": null,
"e": 2394,
"s": 2100,
"text": "The statistical models in spaCy are custom-designed and provide an exceptional performance mixture of both speed, as well as accuracy. The current architecture used has not been published yet, but the following video gives an overview as to how the model works with primary focus on NER model."
},
{
"code": null,
"e": 2669,
"s": 2394,
"text": "Stanford NER is a Named Entity Recognizer, implemented in Java. It provides a default trained model for recognizing chiefly entities like Organization, Person and Location. Apart from this, various models trained for different languages and circumstances are also available."
},
{
"code": null,
"e": 2690,
"s": 2669,
"text": "Model Architecture :"
},
{
"code": null,
"e": 2962,
"s": 2690,
"text": "Stanford NER is also referred to as a CRF (Conditional Random Field) Classifier as Linear chain Conditional Random Field (CRF) sequence models have been implemented in the software. We can train our own custom models with our own labeled dataset for various applications."
},
{
"code": null,
"e": 3158,
"s": 2962,
"text": "CRF models were originally pioneered by Lafferty, McCallum, and Pereira (2001); Please refer to Sutton and McCallum (2006) or Sutton and McCallum (2010) for detailed comprehensible introductions."
},
{
"code": null,
"e": 3330,
"s": 3158,
"text": "Named Entity Recognition has a wide range of applications in the field of Natural Language Processing and Information Retrieval. Few such examples have been listed below :"
},
{
"code": null,
"e": 3856,
"s": 3330,
"text": "One of the key challenges faced by the HR Department across companies is to evaluate a gigantic pile of resumes to shortlist candidates. To add to their burden, resumes of applicants are often excessively populated in detail, of which, most of the information is irrelevant to what the evaluator is seeking. With the aim of simplifying this process, through our NER model, we could facilitate evaluation of resumes at a quick glance, thereby simplifying the effort required in shortlisting candidates among a pile of resumes."
},
{
"code": null,
"e": 4260,
"s": 3856,
"text": "To design a search engine algorithm, instead of searching for an entered query across the millions of articles and websites online, a more efficient approach would be to run an NER model on the articles once and store the entities associated with them permanently. The key tags in the search query can then be compared with the tags associated with the website articles for a quick and efficient search."
},
{
"code": null,
"e": 4705,
"s": 4260,
"text": "NER can be used in developing algorithms for recommender systems which automatically filter relevant content we might be interested in and accordingly guide us to discover related and unvisited relevant contents based on our previous behaviour. This may be achieved by extracting the entities associated with the content in our history or previous activity and comparing them with label assigned to other unseen content to filter relevant ones."
},
{
"code": null,
"e": 4991,
"s": 4705,
"text": "NER can be used in recognizing relevant entities in customer complaints and feedback such as Product specifications, department or company branch details, so that the feedback is classified accordingly and forwarded to the appropriate department responsible for the identified product."
},
{
"code": null,
"e": 5080,
"s": 4991,
"text": "We describe summarization of resumes using NER models in detail in the further sections."
},
{
"code": null,
"e": 5345,
"s": 5080,
"text": "The first task at hand of course is to create manually annotated training data to train the model. For this purpose, 220 resumes were downloaded from an online jobs platform. These documents were uploaded to Dataturks online annotation tool and manually annotated."
},
{
"code": null,
"e": 5585,
"s": 5345,
"text": "The tool automatically parses the documents and allows for us to create annotations of important entities we are interested in and generates JSON formatted training data with each line containing the text corpus along with the annotations."
},
{
"code": null,
"e": 5631,
"s": 5585,
"text": "A snapshot of the dataset can be seen below :"
},
{
"code": null,
"e": 5775,
"s": 5631,
"text": "The above dataset consisting of 220 annotated resumes can be found here. We train the model with 200 resume data and test it on 20 resume data."
},
{
"code": null,
"e": 5792,
"s": 5775,
"text": "Dataset format :"
},
{
"code": null,
"e": 5928,
"s": 5792,
"text": "A sample of the generated json formatted data generated by the Dataturks annotation tool, which is supplied to the code is as follows :"
},
{
"code": null,
"e": 5949,
"s": 5928,
"text": "Training the Model :"
},
{
"code": null,
"e": 6251,
"s": 5949,
"text": "We use pythonβs spaCy module for training the NER model. spaCyβs models are statistical and every βdecisionβ they make β for example, which part-of-speech tag to assign, or whether a word is a named entity β is a prediction. This prediction is based on the examples the model has seen during training."
},
{
"code": null,
"e": 6639,
"s": 6251,
"text": "The model is then shown the unlabelled text and will make a prediction. Because we know the correct answer, we can give the model feedback on its prediction in the form of an error gradient of the loss function that calculates the difference between the training example and the expected output. The greater the difference, the more significant the gradient and the updates to our model."
},
{
"code": null,
"e": 7117,
"s": 6639,
"text": "When training a model, we donβt just want it to memorise our examples β we want it to come up with theory that can be generalised across other examples. After all, we donβt just want the model to learn that this one instance of βAmazonβ right here is a company β we want it to learn that βAmazonβ, in contexts like this, is most likely a company. In order to tune the accuracy, we process our training examples in batches, and experiment with minibatch sizes and dropout rates."
},
{
"code": null,
"e": 7413,
"s": 7117,
"text": "Of course, itβs not enough to only show a model a single example once. Especially if you only have few examples, youβll want to train for a number of iterations. At each iteration, the training data is shuffled to ensure the model doesnβt make any generalisations based on the order of examples."
},
{
"code": null,
"e": 7815,
"s": 7413,
"text": "Another technique to improve the learning results is to set a dropout rate, a rate at which to randomly βdropβ individual features and representations. This makes it harder for the model to memorise the training data. For example, a 0.25dropout means that each feature or internal representation has a 1/4 likelihood of being dropped. We train the model for 10 epochs and keep the dropout rate as 0.2."
},
{
"code": null,
"e": 7862,
"s": 7815,
"text": "Hereβs a code snippet for training the model :"
},
{
"code": null,
"e": 7873,
"s": 7862,
"text": "github.com"
},
{
"code": null,
"e": 7917,
"s": 7873,
"text": "Results and Evaluation of the spaCy model :"
},
{
"code": null,
"e": 8039,
"s": 7917,
"text": "The model is tested on 20 resumes and the predicted summarized resumes are stored as separate .txt files for each resume."
},
{
"code": null,
"e": 8505,
"s": 8039,
"text": "For each resume on which the model is tested, we calculate the accuracy score, precision, recall and f-score for each entity that the model recognizes. The values of these metrics for each entity are summed up and averaged to generate an overall score to evaluate the model on the test data consisting of 20 resumes. The entity wise evaluation results can be observed below . It is observed that the results obtained have been predicted with a commendable accuracy."
},
{
"code": null,
"e": 8626,
"s": 8505,
"text": "A sample summary of an unseen resume of an employee from indeed.com obtained by prediction by our model is shown below :"
},
{
"code": null,
"e": 8643,
"s": 8626,
"text": "Dataset Format :"
},
{
"code": null,
"e": 9040,
"s": 8643,
"text": "The data for training has to be passed as a text file such that every line contains a word-label pair, where the word and the label tag are separated by a tab space β\\tβ. For a text document,as in our case, we tokenize documents into words and add one line for each word and associated tag into the training file. To indicate the start of the next file, we add an empty line in the training file."
},
{
"code": null,
"e": 9085,
"s": 9040,
"text": "Here is a sample of the input training file:"
},
{
"code": null,
"e": 9216,
"s": 9085,
"text": "Note: It is compulsory to include a label/tag for each word. Here, for words we do not care about we are using the label zero β0β."
},
{
"code": null,
"e": 9234,
"s": 9216,
"text": "Properties file :"
},
{
"code": null,
"e": 9459,
"s": 9234,
"text": "Stanford CoreNLP requires a properties file where the parameters necessary for building a custom model. For instance, we may define ways of extracting features for learning, etc. Following is an example of a properties file:"
},
{
"code": null,
"e": 10734,
"s": 9459,
"text": "# location of the training filetrainFile = ./standford_train.txt# location where you would like to save (serialize) your# classifier; adding .gz at the end automatically gzips the file,# making it smaller, and faster to loadserializeTo = ner-model.ser.gz# structure of your training file; this tells the classifier that# the word is in column 0 and the correct answer is in column 1map = word=0,answer=1# This specifies the order of the CRF: order 1 means that features# apply at most to a class pair of previous class and current class# or current class and next class.maxLeft=1# these are the features we'd like to train with# some are discussed below, the rest can be# understood by looking at NERFeatureFactoryuseClassFeature=trueuseWord=true# word character ngrams will be included up to length 6 as prefixes# and suffixes onlyuseNGrams=truenoMidNGrams=truemaxNGramLeng=6usePrev=trueuseNext=trueuseDisjunctive=trueuseSequences=trueusePrevSequences=true# the last 4 properties deal with word shape featuresuseTypeSeqs=trueuseTypeSeqs2=trueuseTypeySequences=true#wordShape=chris2useLCwordShape=none#useBoundarySequences=true#useNeighborNGrams=true#useTaggySequences=true#printFeatures=true#saveFeatureIndexToDisk = true#useObservedSequencesOnly = true#useWordPairs = true"
},
{
"code": null,
"e": 10755,
"s": 10734,
"text": "Training the model :"
},
{
"code": null,
"e": 11240,
"s": 10755,
"text": "The chief class in Stanford CoreNLP is CRFClassifier, which possesses the actual model. In the code provided in the Github repository, the link to which has been attached below, we have provided the code to train the model using the training data and the properties file and save the model to disk to avoid time consumption for training each time. Next time we use the model for prediction on an unseen document, we just load the trained model from disk and use to for classification."
},
{
"code": null,
"e": 11413,
"s": 11240,
"text": "The first column in the output contains the input tokens while the second column refers to the correct label, and the third column is the label predicted by the classifier."
},
{
"code": null,
"e": 11481,
"s": 11413,
"text": "Hereβs a Code snippet for training the model and saving it to disk:"
},
{
"code": null,
"e": 11492,
"s": 11481,
"text": "github.com"
},
{
"code": null,
"e": 11543,
"s": 11492,
"text": "Results and Evaluation of the Stanford NER model :"
},
{
"code": null,
"e": 11665,
"s": 11543,
"text": "The model is tested on 20 resumes and the predicted summarized resumes are stored as separate .txt files for each resume."
},
{
"code": null,
"e": 12131,
"s": 11665,
"text": "For each resume on which the model is tested, we calculate the accuracy score, precision, recall and f-score for each entity that the model recognizes. The values of these metrics for each entity are summed up and averaged to generate an overall score to evaluate the model on the test data consisting of 20 resumes. The entity wise evaluation results can be observed below . It is observed that the results obtained have been predicted with a commendable accuracy."
},
{
"code": null,
"e": 12252,
"s": 12131,
"text": "A sample summary of an unseen resume of an employee from indeed.com obtained by prediction by our model is shown below :"
},
{
"code": null,
"e": 12534,
"s": 12252,
"text": "The vast majority of tokens in real-world resume documents are not part of entity names as usually defined, so the baseline precision, recall is extravagantly high, typically >90%; going by this logic, the entity wise precision recall values of both the models are reasonably good."
},
{
"code": null,
"e": 12754,
"s": 12534,
"text": "From the evaluation of the models and the observed outputs, spaCy seems to outperform Stanford NER for the task of summarizing resumes. A review of the F-scores for the entities identified by both models is as follows :"
},
{
"code": null,
"e": 12815,
"s": 12754,
"text": "Here is the dataset of the resumes tagged with NER entities."
},
{
"code": null,
"e": 12926,
"s": 12815,
"text": "The Python code for the above project for training the spaCy model can be found here in the github repository."
},
{
"code": null,
"e": 13042,
"s": 12926,
"text": "The Java code for the above project for training the Stanford NER model can be found here in the GitHub repository."
}
] |
Difference Between Process, Parent Process, and Child Process - GeeksforGeeks | 19 May, 2021
Running program is a process. From this process, another process can be created. There is a parent-child relationship between the two processes. This can be achieved using a library function called fork(). fork() function splits the running process into two processes, the existing one is known as parent and the new process is known as a child. Here is a program that demonstrates this:
C
// C program to demonstrate// the above concept#include <sys/types.h>#include<stdio.h>#include <unistd.h> // Driver codeint main(){ printf ("Before Forking\n"); fork(); printf ("After Forking\n");}
Before Forking
After Forking
Before Forking
After Forking
Explanation: All the statements after the fork() are executed twice:
Once by the parent process.The second time the statements are executed by the child process.
Once by the parent process.
The second time the statements are executed by the child process.
Letβs discuss the following concepts in more detail:
Process.Parent Process.Child Process.
Process.
Parent Process.
Child Process.
Process: A process is a program under execution i.e an active program. A process is more than the program code, it includes the following:
Program counter.Process stack.Registers.Program code, etc.
Program counter.
Process stack.
Registers.
Program code, etc.
On the contrary program code is only a text section.
A process changes its state as it executes. The new state partially depends on the current activity of a process. The different states of the process during its execution are:
NewReadyRunningBlockedTerminated.
New
Ready
Running
Blocked
Terminated.
A process control block and process table are associated with each of the processes. It contains the following important information about the process:
Process state.Process number.Program counter.List of files and registers.CPU information.Memory information, etc.
Process state.
Process number.
Program counter.
List of files and registers.
CPU information.
Memory information, etc.
Parent Process: All the processes are created when a process executes the fork() system call except the startup process. The process that executes the fork() system call is the parent process. A parent process is one that creates a child process using a fork() system call. A parent process may have multiple child processes, but a child process only one parent process.
On the success of a fork() system call:
The Process ID (PID) of the child process is returned to the parent process.
0 is returned to the child process.
On the failure of a fork() system call,
-1 is returned to the parent process.
A child process is not created.
Child Process: A child process is created by a parent process in an operating system using a fork() system call. A child process may also be known as subprocess or a subtask.
A child process is created as a copy of its parent process.
The child process inherits most of its attributes.
If a child process has no parent process, then the child process is created directly by the kernel.
If a child process exits or is interrupted, then a SIGCHLD signal is sent to the parent process to inform about the termination or exit of the child process.
Why Do We Need to Create A Child Process?Sometimes there is a need for a program to perform more than one function simultaneously. Since these jobs may be interrelated so two different programs to perform them cannot be created. For example: Suppose there are two jobs: copy contents of source file to target file and display an animated progress bar indicating that the file copy is in progress. The GIF progress bar file should continue to play till file copy is taking place. Once the copying process is finished the playing of the GIF progress bar file should be stopped. Since both these jobs are interrelated they cannot be performed in two different programs. Also, they cannot be performed one after another. Both jobs should be performed simultaneously.
At such times fork() is used to create a child process and then write the program in such a manner that file copy is done by the parent and displaying of the animated GIF file is done by the child process.
Program 1: The task here is to show how to perform two different but interrelated jobs simultaneously. Hence, the actual code for file copying and playing the animated GIF file has been skipped only the approach for performing 2 jobs simultaneously is shown.
C
// C program for the above approach#include <sys/types.h> // Driver Codeint main( ){ int pid; pid = fork(); if (pid == 0) { printf ("In child process\n"); /* code to play animated GIF file */ } else { printf ("In parent process\n"); /* code to copy file */ }}
Explanation: fork() creates a child process and duplicates the code of the parent process in the child process. There onwards the execution of the fork() function continues in both processes. Thus, the duplication code inside fork() is executed once, whereas the remaining code inside it is executed in both the parent and the child process. Hence, control would come back from the fork() twice, even though it is actually called only once. When control returns from the fork() of the parent process it returns the PID of the child process, whereas when control returns from the fork() of the child process it always returns a 0. This can be exploited by the program to segregate the code that we want to execute in the parent process from the code that we want to execute in the child process. This logic is implemented in the above program using an if statement. The βif blockβ is executed in the case of the child process and the βelse blockβ is executed in the case of the parent process.
Program 2:This program would use the fork() call to create a child process. In the child process, we would print the PID of the child and its parent, whereas in the parent process we would print the PID of the parent and its child.
C
// C program to implement// the above approach# include <sys/types.h> // Driver codeint main(){ int pid; pid = fork(); if (pid == 0) { printf ("Child : I am the child process\n"); printf ("Child : Childβs PID: %d\n", getpid()); printf ("Child : Parentβs PID: %d\n", getppid()); } else { printf ("Parent : I am the parent process\n"); printf ("Parent : Parentβs PID: %d\n", getpid()); printf ("Parent : Childβs PID: %d\n", pid); }}
Output:
Child : I am the child process
Child : Child's PID: 4706
Child : Parent's PID: 4705
Parent : I am the Parent process
Parent : Parent's PID: 4705
Parent : Child's PID: 4706
linux
Difference Between
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Informed and Uninformed Search in AI
Difference between Internal and External fragmentation
Difference between HashMap and HashSet
Banker's Algorithm in Operating System
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Program for FCFS CPU Scheduling | Set 1
Program for Round Robin scheduling | Set 1 | [
{
"code": null,
"e": 24492,
"s": 24464,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 24880,
"s": 24492,
"text": "Running program is a process. From this process, another process can be created. There is a parent-child relationship between the two processes. This can be achieved using a library function called fork(). fork() function splits the running process into two processes, the existing one is known as parent and the new process is known as a child. Here is a program that demonstrates this:"
},
{
"code": null,
"e": 24882,
"s": 24880,
"text": "C"
},
{
"code": "// C program to demonstrate// the above concept#include <sys/types.h>#include<stdio.h>#include <unistd.h> // Driver codeint main(){ printf (\"Before Forking\\n\"); fork(); printf (\"After Forking\\n\");}",
"e": 25085,
"s": 24882,
"text": null
},
{
"code": null,
"e": 25143,
"s": 25085,
"text": "Before Forking\nAfter Forking\nBefore Forking\nAfter Forking"
},
{
"code": null,
"e": 25213,
"s": 25143,
"text": "Explanation: All the statements after the fork() are executed twice: "
},
{
"code": null,
"e": 25306,
"s": 25213,
"text": "Once by the parent process.The second time the statements are executed by the child process."
},
{
"code": null,
"e": 25334,
"s": 25306,
"text": "Once by the parent process."
},
{
"code": null,
"e": 25400,
"s": 25334,
"text": "The second time the statements are executed by the child process."
},
{
"code": null,
"e": 25453,
"s": 25400,
"text": "Letβs discuss the following concepts in more detail:"
},
{
"code": null,
"e": 25491,
"s": 25453,
"text": "Process.Parent Process.Child Process."
},
{
"code": null,
"e": 25500,
"s": 25491,
"text": "Process."
},
{
"code": null,
"e": 25516,
"s": 25500,
"text": "Parent Process."
},
{
"code": null,
"e": 25531,
"s": 25516,
"text": "Child Process."
},
{
"code": null,
"e": 25670,
"s": 25531,
"text": "Process: A process is a program under execution i.e an active program. A process is more than the program code, it includes the following:"
},
{
"code": null,
"e": 25729,
"s": 25670,
"text": "Program counter.Process stack.Registers.Program code, etc."
},
{
"code": null,
"e": 25746,
"s": 25729,
"text": "Program counter."
},
{
"code": null,
"e": 25761,
"s": 25746,
"text": "Process stack."
},
{
"code": null,
"e": 25772,
"s": 25761,
"text": "Registers."
},
{
"code": null,
"e": 25791,
"s": 25772,
"text": "Program code, etc."
},
{
"code": null,
"e": 25844,
"s": 25791,
"text": "On the contrary program code is only a text section."
},
{
"code": null,
"e": 26020,
"s": 25844,
"text": "A process changes its state as it executes. The new state partially depends on the current activity of a process. The different states of the process during its execution are:"
},
{
"code": null,
"e": 26054,
"s": 26020,
"text": "NewReadyRunningBlockedTerminated."
},
{
"code": null,
"e": 26058,
"s": 26054,
"text": "New"
},
{
"code": null,
"e": 26064,
"s": 26058,
"text": "Ready"
},
{
"code": null,
"e": 26072,
"s": 26064,
"text": "Running"
},
{
"code": null,
"e": 26080,
"s": 26072,
"text": "Blocked"
},
{
"code": null,
"e": 26092,
"s": 26080,
"text": "Terminated."
},
{
"code": null,
"e": 26244,
"s": 26092,
"text": "A process control block and process table are associated with each of the processes. It contains the following important information about the process:"
},
{
"code": null,
"e": 26358,
"s": 26244,
"text": "Process state.Process number.Program counter.List of files and registers.CPU information.Memory information, etc."
},
{
"code": null,
"e": 26373,
"s": 26358,
"text": "Process state."
},
{
"code": null,
"e": 26389,
"s": 26373,
"text": "Process number."
},
{
"code": null,
"e": 26406,
"s": 26389,
"text": "Program counter."
},
{
"code": null,
"e": 26435,
"s": 26406,
"text": "List of files and registers."
},
{
"code": null,
"e": 26452,
"s": 26435,
"text": "CPU information."
},
{
"code": null,
"e": 26477,
"s": 26452,
"text": "Memory information, etc."
},
{
"code": null,
"e": 26848,
"s": 26477,
"text": "Parent Process: All the processes are created when a process executes the fork() system call except the startup process. The process that executes the fork() system call is the parent process. A parent process is one that creates a child process using a fork() system call. A parent process may have multiple child processes, but a child process only one parent process."
},
{
"code": null,
"e": 26888,
"s": 26848,
"text": "On the success of a fork() system call:"
},
{
"code": null,
"e": 26965,
"s": 26888,
"text": "The Process ID (PID) of the child process is returned to the parent process."
},
{
"code": null,
"e": 27001,
"s": 26965,
"text": "0 is returned to the child process."
},
{
"code": null,
"e": 27042,
"s": 27001,
"text": "On the failure of a fork() system call, "
},
{
"code": null,
"e": 27080,
"s": 27042,
"text": "-1 is returned to the parent process."
},
{
"code": null,
"e": 27112,
"s": 27080,
"text": "A child process is not created."
},
{
"code": null,
"e": 27287,
"s": 27112,
"text": "Child Process: A child process is created by a parent process in an operating system using a fork() system call. A child process may also be known as subprocess or a subtask."
},
{
"code": null,
"e": 27347,
"s": 27287,
"text": "A child process is created as a copy of its parent process."
},
{
"code": null,
"e": 27398,
"s": 27347,
"text": "The child process inherits most of its attributes."
},
{
"code": null,
"e": 27498,
"s": 27398,
"text": "If a child process has no parent process, then the child process is created directly by the kernel."
},
{
"code": null,
"e": 27656,
"s": 27498,
"text": "If a child process exits or is interrupted, then a SIGCHLD signal is sent to the parent process to inform about the termination or exit of the child process."
},
{
"code": null,
"e": 28420,
"s": 27656,
"text": "Why Do We Need to Create A Child Process?Sometimes there is a need for a program to perform more than one function simultaneously. Since these jobs may be interrelated so two different programs to perform them cannot be created. For example: Suppose there are two jobs: copy contents of source file to target file and display an animated progress bar indicating that the file copy is in progress. The GIF progress bar file should continue to play till file copy is taking place. Once the copying process is finished the playing of the GIF progress bar file should be stopped. Since both these jobs are interrelated they cannot be performed in two different programs. Also, they cannot be performed one after another. Both jobs should be performed simultaneously. "
},
{
"code": null,
"e": 28626,
"s": 28420,
"text": "At such times fork() is used to create a child process and then write the program in such a manner that file copy is done by the parent and displaying of the animated GIF file is done by the child process."
},
{
"code": null,
"e": 28886,
"s": 28626,
"text": "Program 1: The task here is to show how to perform two different but interrelated jobs simultaneously. Hence, the actual code for file copying and playing the animated GIF file has been skipped only the approach for performing 2 jobs simultaneously is shown. "
},
{
"code": null,
"e": 28888,
"s": 28886,
"text": "C"
},
{
"code": "// C program for the above approach#include <sys/types.h> // Driver Codeint main( ){ int pid; pid = fork(); if (pid == 0) { printf (\"In child process\\n\"); /* code to play animated GIF file */ } else { printf (\"In parent process\\n\"); /* code to copy file */ }}",
"e": 29181,
"s": 28888,
"text": null
},
{
"code": null,
"e": 30174,
"s": 29181,
"text": "Explanation: fork() creates a child process and duplicates the code of the parent process in the child process. There onwards the execution of the fork() function continues in both processes. Thus, the duplication code inside fork() is executed once, whereas the remaining code inside it is executed in both the parent and the child process. Hence, control would come back from the fork() twice, even though it is actually called only once. When control returns from the fork() of the parent process it returns the PID of the child process, whereas when control returns from the fork() of the child process it always returns a 0. This can be exploited by the program to segregate the code that we want to execute in the parent process from the code that we want to execute in the child process. This logic is implemented in the above program using an if statement. The βif blockβ is executed in the case of the child process and the βelse blockβ is executed in the case of the parent process."
},
{
"code": null,
"e": 30407,
"s": 30174,
"text": "Program 2:This program would use the fork() call to create a child process. In the child process, we would print the PID of the child and its parent, whereas in the parent process we would print the PID of the parent and its child. "
},
{
"code": null,
"e": 30409,
"s": 30407,
"text": "C"
},
{
"code": "// C program to implement// the above approach# include <sys/types.h> // Driver codeint main(){ int pid; pid = fork(); if (pid == 0) { printf (\"Child : I am the child process\\n\"); printf (\"Child : Childβs PID: %d\\n\", getpid()); printf (\"Child : Parentβs PID: %d\\n\", getppid()); } else { printf (\"Parent : I am the parent process\\n\"); printf (\"Parent : Parentβs PID: %d\\n\", getpid()); printf (\"Parent : Childβs PID: %d\\n\", pid); }}",
"e": 30869,
"s": 30409,
"text": null
},
{
"code": null,
"e": 30877,
"s": 30869,
"text": "Output:"
},
{
"code": null,
"e": 31049,
"s": 30877,
"text": "Child : I am the child process\nChild : Child's PID: 4706\nChild : Parent's PID: 4705\nParent : I am the Parent process\nParent : Parent's PID: 4705\nParent : Child's PID: 4706"
},
{
"code": null,
"e": 31055,
"s": 31049,
"text": "linux"
},
{
"code": null,
"e": 31074,
"s": 31055,
"text": "Difference Between"
},
{
"code": null,
"e": 31092,
"s": 31074,
"text": "Operating Systems"
},
{
"code": null,
"e": 31110,
"s": 31092,
"text": "Operating Systems"
},
{
"code": null,
"e": 31208,
"s": 31110,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31217,
"s": 31208,
"text": "Comments"
},
{
"code": null,
"e": 31230,
"s": 31217,
"text": "Old Comments"
},
{
"code": null,
"e": 31291,
"s": 31230,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31359,
"s": 31291,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 31415,
"s": 31359,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 31470,
"s": 31415,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 31509,
"s": 31470,
"text": "Difference between HashMap and HashSet"
},
{
"code": null,
"e": 31548,
"s": 31509,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 31575,
"s": 31548,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 31624,
"s": 31575,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 31664,
"s": 31624,
"text": "Program for FCFS CPU Scheduling | Set 1"
}
] |
EJB - JNDI Bindings | JNDI stands for Java Naming and Directory Interface. It is a set of API and service interfaces. Java based applications use JNDI for naming and directory services. In context of EJB, there are two terms.
Binding β This refers to assigning a name to an EJB object, which can be used later.
Binding β This refers to assigning a name to an EJB object, which can be used later.
Lookup β This refers to looking up and getting an object of EJB.
Lookup β This refers to looking up and getting an object of EJB.
In Jboss, session beans are bound in JNDI in the following format by default.
local β EJB-name/local
local β EJB-name/local
remote β EJB-name/remote
remote β EJB-name/remote
In case, EJB are bundled with <application-name>.ear file, then default format is as following β
local β application-name/ejb-name/local
local β application-name/ejb-name/local
remote β application-name/ejb-name/remote
remote β application-name/ejb-name/remote
Refer to EJB - Create Application chapter's JBoss console output.
...
16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3
16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean
16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
LibrarySessionBean/remote - EJB3.x Default Remote Business Interface
LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote - EJB3.x Remote Business Interface
...
Following annotations can be used to customize the default JNDI bindings β
local β org.jboss.ejb3.LocalBinding
local β org.jboss.ejb3.LocalBinding
remote β org.jboss.ejb3.RemoteBindings
remote β org.jboss.ejb3.RemoteBindings
Update LibrarySessionBean.java. Refer to EJB - Create Application chapter.
package com.tutorialspoint.stateless;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
@Stateless
@LocalBinding(jndiBinding="tutorialsPoint/librarySession")
public class LibrarySessionBean implements LibrarySessionBeanLocal {
List<String> bookShelf;
public LibrarySessionBean() {
bookShelf = new ArrayList<String>();
}
public void addBook(String bookName) {
bookShelf.add(bookName);
}
public List<String> getBooks() {
return bookShelf;
}
}
package com.tutorialspoint.stateless;
import java.util.List;
import javax.ejb.Local;
@Local
public interface LibrarySessionBeanLocal {
void addBook(String bookName);
List getBooks();
}
Build the project, deploy the application on Jboss, and verify the following output in Jboss console β
...
16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3
16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean
16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
tutorialsPoint/librarySession - EJB3.x Default Local Business Interface
tutorialsPoint/librarySession-com.tutorialspoint.stateless.LibrarySessionBeanLocal - EJB3.x Local Business Interface
...
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2251,
"s": 2047,
"text": "JNDI stands for Java Naming and Directory Interface. It is a set of API and service interfaces. Java based applications use JNDI for naming and directory services. In context of EJB, there are two terms."
},
{
"code": null,
"e": 2336,
"s": 2251,
"text": "Binding β This refers to assigning a name to an EJB object, which can be used later."
},
{
"code": null,
"e": 2421,
"s": 2336,
"text": "Binding β This refers to assigning a name to an EJB object, which can be used later."
},
{
"code": null,
"e": 2486,
"s": 2421,
"text": "Lookup β This refers to looking up and getting an object of EJB."
},
{
"code": null,
"e": 2551,
"s": 2486,
"text": "Lookup β This refers to looking up and getting an object of EJB."
},
{
"code": null,
"e": 2629,
"s": 2551,
"text": "In Jboss, session beans are bound in JNDI in the following format by default."
},
{
"code": null,
"e": 2652,
"s": 2629,
"text": "local β EJB-name/local"
},
{
"code": null,
"e": 2675,
"s": 2652,
"text": "local β EJB-name/local"
},
{
"code": null,
"e": 2700,
"s": 2675,
"text": "remote β EJB-name/remote"
},
{
"code": null,
"e": 2725,
"s": 2700,
"text": "remote β EJB-name/remote"
},
{
"code": null,
"e": 2822,
"s": 2725,
"text": "In case, EJB are bundled with <application-name>.ear file, then default format is as following β"
},
{
"code": null,
"e": 2862,
"s": 2822,
"text": "local β application-name/ejb-name/local"
},
{
"code": null,
"e": 2902,
"s": 2862,
"text": "local β application-name/ejb-name/local"
},
{
"code": null,
"e": 2944,
"s": 2902,
"text": "remote β application-name/ejb-name/remote"
},
{
"code": null,
"e": 2986,
"s": 2944,
"text": "remote β application-name/ejb-name/remote"
},
{
"code": null,
"e": 3052,
"s": 2986,
"text": "Refer to EJB - Create Application chapter's JBoss console output."
},
{
"code": null,
"e": 3587,
"s": 3052,
"text": "...\n16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3\n16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean\n16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:\n\n LibrarySessionBean/remote - EJB3.x Default Remote Business Interface\n LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote - EJB3.x Remote Business Interface\n...\n"
},
{
"code": null,
"e": 3662,
"s": 3587,
"text": "Following annotations can be used to customize the default JNDI bindings β"
},
{
"code": null,
"e": 3698,
"s": 3662,
"text": "local β org.jboss.ejb3.LocalBinding"
},
{
"code": null,
"e": 3734,
"s": 3698,
"text": "local β org.jboss.ejb3.LocalBinding"
},
{
"code": null,
"e": 3773,
"s": 3734,
"text": "remote β org.jboss.ejb3.RemoteBindings"
},
{
"code": null,
"e": 3812,
"s": 3773,
"text": "remote β org.jboss.ejb3.RemoteBindings"
},
{
"code": null,
"e": 3887,
"s": 3812,
"text": "Update LibrarySessionBean.java. Refer to EJB - Create Application chapter."
},
{
"code": null,
"e": 4436,
"s": 3887,
"text": "package com.tutorialspoint.stateless;\n \nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.ejb.Stateless;\n \n@Stateless\n@LocalBinding(jndiBinding=\"tutorialsPoint/librarySession\")\npublic class LibrarySessionBean implements LibrarySessionBeanLocal {\n \n List<String> bookShelf; \n \n public LibrarySessionBean() {\n bookShelf = new ArrayList<String>();\n }\n \n public void addBook(String bookName) {\n bookShelf.add(bookName);\n } \n \n public List<String> getBooks() {\n return bookShelf;\n }\n}"
},
{
"code": null,
"e": 4642,
"s": 4436,
"text": "package com.tutorialspoint.stateless;\n \nimport java.util.List;\nimport javax.ejb.Local;\n \n@Local\npublic interface LibrarySessionBeanLocal {\n \n void addBook(String bookName);\n \n List getBooks();\n \n}"
},
{
"code": null,
"e": 4745,
"s": 4642,
"text": "Build the project, deploy the application on Jboss, and verify the following output in Jboss console β"
},
{
"code": null,
"e": 5284,
"s": 4745,
"text": "...\n16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3\n16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean\n16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:\n\n tutorialsPoint/librarySession - EJB3.x Default Local Business Interface\n tutorialsPoint/librarySession-com.tutorialspoint.stateless.LibrarySessionBeanLocal - EJB3.x Local Business Interface\n..."
},
{
"code": null,
"e": 5291,
"s": 5284,
"text": " Print"
},
{
"code": null,
"e": 5302,
"s": 5291,
"text": " Add Notes"
}
] |
Creating a Queue in Javascript | Though Arrays in JavaScript provide all the functionality of a Queue, let us implement our own Queue class. Our class will have the following functions β
enqueue(element): Function to add an element in the queue.
dequeue(): Function that removes an element from the queue.
peek(): Returns the element from the front of the queue.
isFull(): Checks if we reached the element limit on the queue.
isEmpty(): checks if the queue is empty.
clear(): Remove all elements.
display(): display all contents of the array
Let's start by defining a simple class with a constructor that takes the max size of the queue and a helper function that'll help us when we implement the other functions for this class. As we implemented stacks, we'll implement queues using Arrays as well.
class Queue {
constructor(maxSize) {
// Set default max size if not provided
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize;
// Init an array that'll contain the queue values.
this.container = [];
}
// Helper function to display all values while developing
display() {
console.log(this.container);
}
// Checks if queue is empty
isEmpty(){
return this.container.length === 0;
}
// checks if queue is full
isFull() {
return this.container.length >= this.maxSize;
}
}
We have also defined 2 more functions, isFull and isEmpty to check if the queue is full or empty.
The isFull function just checks if the length of the container is equal to or more than maxSize and returns accordingly.
The isEmpty function checks if the size of the container is 0.
These will be helpful when we define other operations. The functions we define from this point onwards will all go inside the Queue class. | [
{
"code": null,
"e": 1216,
"s": 1062,
"text": "Though Arrays in JavaScript provide all the functionality of a Queue, let us implement our own Queue class. Our class will have the following functions β"
},
{
"code": null,
"e": 1276,
"s": 1216,
"text": " enqueue(element): Function to add an element in the queue."
},
{
"code": null,
"e": 1337,
"s": 1276,
"text": " dequeue(): Function that removes an element from the queue."
},
{
"code": null,
"e": 1395,
"s": 1337,
"text": " peek(): Returns the element from the front of the queue."
},
{
"code": null,
"e": 1459,
"s": 1395,
"text": " isFull(): Checks if we reached the element limit on the queue."
},
{
"code": null,
"e": 1501,
"s": 1459,
"text": " isEmpty(): checks if the queue is empty."
},
{
"code": null,
"e": 1532,
"s": 1501,
"text": " clear(): Remove all elements."
},
{
"code": null,
"e": 1578,
"s": 1532,
"text": " display(): display all contents of the array"
},
{
"code": null,
"e": 1836,
"s": 1578,
"text": "Let's start by defining a simple class with a constructor that takes the max size of the queue and a helper function that'll help us when we implement the other functions for this class. As we implemented stacks, we'll implement queues using Arrays as well."
},
{
"code": null,
"e": 2412,
"s": 1836,
"text": "class Queue {\n constructor(maxSize) {\n // Set default max size if not provided\n if (isNaN(maxSize)) {\n maxSize = 10;\n }\n this.maxSize = maxSize;\n // Init an array that'll contain the queue values.\n this.container = [];\n }\n // Helper function to display all values while developing\n display() {\n console.log(this.container);\n }\n // Checks if queue is empty\n isEmpty(){\n return this.container.length === 0;\n }\n // checks if queue is full\n isFull() {\n return this.container.length >= this.maxSize;\n }\n}"
},
{
"code": null,
"e": 2510,
"s": 2412,
"text": "We have also defined 2 more functions, isFull and isEmpty to check if the queue is full or empty."
},
{
"code": null,
"e": 2631,
"s": 2510,
"text": "The isFull function just checks if the length of the container is equal to or more than maxSize and returns accordingly."
},
{
"code": null,
"e": 2694,
"s": 2631,
"text": "The isEmpty function checks if the size of the container is 0."
},
{
"code": null,
"e": 2833,
"s": 2694,
"text": "These will be helpful when we define other operations. The functions we define from this point onwards will all go inside the Queue class."
}
] |
How to set the font size of Matplotlib axis Legend? | To set the font size of matplotlib axis legend, we can take the following steps β
Create the points for x and y using numpy.
Create the points for x and y using numpy.
Plot x and y using the plot() method with label y=sin(x).
Plot x and y using the plot() method with label y=sin(x).
Title the plot using the title() method.
Title the plot using the title() method.
To set the fontsize, we can override rcParams legend fontsize by value 20.
To set the fontsize, we can override rcParams legend fontsize by value 20.
Use the legend() method, and fit the legend at the top-right position.
Use the legend() method, and fit the legend at the top-right position.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(1, 10, 50)
y = np.sin(x)
plt.plot(x, y, c="red", lw=7, label="y=sin(x)")
plt.title("Sine Curve")
matplotlib.rcParams['legend.fontsize'] = 20
plt.legend(loc=1)
plt.show() | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "To set the font size of matplotlib axis legend, we can take the following steps β"
},
{
"code": null,
"e": 1187,
"s": 1144,
"text": "Create the points for x and y using numpy."
},
{
"code": null,
"e": 1230,
"s": 1187,
"text": "Create the points for x and y using numpy."
},
{
"code": null,
"e": 1288,
"s": 1230,
"text": "Plot x and y using the plot() method with label y=sin(x)."
},
{
"code": null,
"e": 1346,
"s": 1288,
"text": "Plot x and y using the plot() method with label y=sin(x)."
},
{
"code": null,
"e": 1387,
"s": 1346,
"text": "Title the plot using the title() method."
},
{
"code": null,
"e": 1428,
"s": 1387,
"text": "Title the plot using the title() method."
},
{
"code": null,
"e": 1503,
"s": 1428,
"text": "To set the fontsize, we can override rcParams legend fontsize by value 20."
},
{
"code": null,
"e": 1578,
"s": 1503,
"text": "To set the fontsize, we can override rcParams legend fontsize by value 20."
},
{
"code": null,
"e": 1649,
"s": 1578,
"text": "Use the legend() method, and fit the legend at the top-right position."
},
{
"code": null,
"e": 1720,
"s": 1649,
"text": "Use the legend() method, and fit the legend at the top-right position."
},
{
"code": null,
"e": 1766,
"s": 1720,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 1812,
"s": 1766,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 2159,
"s": 1812,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nimport matplotlib\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(1, 10, 50)\ny = np.sin(x)\nplt.plot(x, y, c=\"red\", lw=7, label=\"y=sin(x)\")\nplt.title(\"Sine Curve\")\nmatplotlib.rcParams['legend.fontsize'] = 20\nplt.legend(loc=1)\nplt.show()"
}
] |
Write a Python program to export a dataframe to an html file | Assume, we have already saved pandas.csv file and export the file to Html format
To solve this, we will follow the steps given below β
Read the csv file using the read_csv method as follows β
Read the csv file using the read_csv method as follows β
df = pd.read_csv('pandas.csv')
Create new file pandas.html in write mode using file object,
Create new file pandas.html in write mode using file object,
f = open('pandas.html','w')
Declare result variable to convert dataframe to html file format,
Declare result variable to convert dataframe to html file format,
result = df.to_html()
Using the file object, write all the data from the result. Finally close the file object,
Using the file object, write all the data from the result. Finally close the file object,
f.write(result)
f.close()
Letβs see the below implementation to get a better understanding β
import pandas as pd
df = pd.read_csv('pandas.csv')
print(df)
f = open('pandas.html','w')
result = df.to_html()
f.write(result)
f.close()
pandas.html
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Id</th>
<th>Data</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1</td>
<td>11</td>
</tr>
<tr>
<th>1</th>
<td>2</td>
<td>22</td>
</tr>
<tr>
<th>2</th>
<td>3</td>
<td>33</td>
</tr>
<tr>
<th>3</th>
<td>4</td>
<td>44</td>
</tr>
<tr>
<th>4</th>
<td>5</td>
<td>55</td>
</tr>
</tbody>
</table> | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "Assume, we have already saved pandas.csv file and export the file to Html format"
},
{
"code": null,
"e": 1197,
"s": 1143,
"text": "To solve this, we will follow the steps given below β"
},
{
"code": null,
"e": 1254,
"s": 1197,
"text": "Read the csv file using the read_csv method as follows β"
},
{
"code": null,
"e": 1311,
"s": 1254,
"text": "Read the csv file using the read_csv method as follows β"
},
{
"code": null,
"e": 1342,
"s": 1311,
"text": "df = pd.read_csv('pandas.csv')"
},
{
"code": null,
"e": 1403,
"s": 1342,
"text": "Create new file pandas.html in write mode using file object,"
},
{
"code": null,
"e": 1464,
"s": 1403,
"text": "Create new file pandas.html in write mode using file object,"
},
{
"code": null,
"e": 1492,
"s": 1464,
"text": "f = open('pandas.html','w')"
},
{
"code": null,
"e": 1558,
"s": 1492,
"text": "Declare result variable to convert dataframe to html file format,"
},
{
"code": null,
"e": 1624,
"s": 1558,
"text": "Declare result variable to convert dataframe to html file format,"
},
{
"code": null,
"e": 1646,
"s": 1624,
"text": "result = df.to_html()"
},
{
"code": null,
"e": 1736,
"s": 1646,
"text": "Using the file object, write all the data from the result. Finally close the file object,"
},
{
"code": null,
"e": 1826,
"s": 1736,
"text": "Using the file object, write all the data from the result. Finally close the file object,"
},
{
"code": null,
"e": 1852,
"s": 1826,
"text": "f.write(result)\nf.close()"
},
{
"code": null,
"e": 1919,
"s": 1852,
"text": "Letβs see the below implementation to get a better understanding β"
},
{
"code": null,
"e": 2056,
"s": 1919,
"text": "import pandas as pd\ndf = pd.read_csv('pandas.csv')\nprint(df)\nf = open('pandas.html','w')\nresult = df.to_html()\nf.write(result)\nf.close()"
},
{
"code": null,
"e": 2693,
"s": 2056,
"text": "pandas.html\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>Id</th>\n <th>Data</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>1</td>\n <td>11</td>\n </tr>\n <tr>\n <th>1</th>\n <td>2</td>\n <td>22</td>\n </tr>\n <tr>\n <th>2</th>\n <td>3</td>\n <td>33</td>\n </tr>\n <tr>\n <th>3</th>\n <td>4</td>\n <td>44</td>\n </tr>\n <tr>\n <th>4</th>\n <td>5</td>\n <td>55</td>\n </tr>\n </tbody>\n</table>"
}
] |
Ionic - Cordova Icon and Splash Screen | Every mobile app needs an icon and splash screen. Ionic provides excellent solution for adding it and requires minimum work for the developers. Cropping and resizing is automated on the Ionic server.
In the earlier chapters, we have discussed how to add different platforms for the Ionic app. By adding a platform, Ionic will install Cordova splash screen plugin for that platform so we do not need to install anything afterwards. All we need to do is to find two images.
The images should be png, psd or ai files. The minimum dimension should be 192x192 for icon image and 2208Γ2208 for the splash screen image. This dimensions will cover all the devices. In our example, we will use the same image for both. The images need to be saved to resources folder instead of the default ones. After we are done with it, all we need is to run the following in the command prompt window.
C:\Users\Username\Desktop\MyApp>ionic resources
Now, if you check resources/android or resources/ios folders, you will see that the images we added before are resized and cropped to accommodate different screen sizes. When we run our app on the device, we will see a splash screen before the app is started and we will see that a default Ionic icon is changed.
NOTE β If you want to use different images for Android and iOS, you can add it to resources/android and resources/ios instead of the resources folder.
16 Lectures
2.5 hours
Frahaan Hussain
185 Lectures
46.5 hours
Nikhil Agarwal
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2663,
"s": 2463,
"text": "Every mobile app needs an icon and splash screen. Ionic provides excellent solution for adding it and requires minimum work for the developers. Cropping and resizing is automated on the Ionic server."
},
{
"code": null,
"e": 2935,
"s": 2663,
"text": "In the earlier chapters, we have discussed how to add different platforms for the Ionic app. By adding a platform, Ionic will install Cordova splash screen plugin for that platform so we do not need to install anything afterwards. All we need to do is to find two images."
},
{
"code": null,
"e": 3343,
"s": 2935,
"text": "The images should be png, psd or ai files. The minimum dimension should be 192x192 for icon image and 2208Γ2208 for the splash screen image. This dimensions will cover all the devices. In our example, we will use the same image for both. The images need to be saved to resources folder instead of the default ones. After we are done with it, all we need is to run the following in the command prompt window."
},
{
"code": null,
"e": 3392,
"s": 3343,
"text": "C:\\Users\\Username\\Desktop\\MyApp>ionic resources\n"
},
{
"code": null,
"e": 3705,
"s": 3392,
"text": "Now, if you check resources/android or resources/ios folders, you will see that the images we added before are resized and cropped to accommodate different screen sizes. When we run our app on the device, we will see a splash screen before the app is started and we will see that a default Ionic icon is changed."
},
{
"code": null,
"e": 3856,
"s": 3705,
"text": "NOTE β If you want to use different images for Android and iOS, you can add it to resources/android and resources/ios instead of the resources folder."
},
{
"code": null,
"e": 3891,
"s": 3856,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3908,
"s": 3891,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3945,
"s": 3908,
"text": "\n 185 Lectures \n 46.5 hours \n"
},
{
"code": null,
"e": 3961,
"s": 3945,
"text": " Nikhil Agarwal"
},
{
"code": null,
"e": 3968,
"s": 3961,
"text": " Print"
},
{
"code": null,
"e": 3979,
"s": 3968,
"text": " Add Notes"
}
] |
How to Augmentate Data Using Keras | by Ravindu Senaratne | Towards Data Science | Data Augmentation is very useful if you would like to augment your data or increase the amount of training or validation data. For example, If you have 2000 images and you would like to get 5000 or 10000 of those then this can be very useful.
But if you have 5 or 10 images, donβt expect to get 2000 or 10000 images from data augmentation and still be able to get a decent result out of your deep learning model. Because the deep learning model will be highly biased towards these 5 or 10 images.
If you have less than 100 images I would recommend using traditional machine learning
from keras.preprocessing.image import ImageDataGeneratorfrom skimage import iodatagen = ImageDataGenerator( rotation_range=45, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='constant', cval=125)x = io.imread('test_image/test.jpg')x = x.reshape((1, ) + x.shape)i = 0for batch in datagen.flow(x, batch_size=16, save_to_dir='augmented', save_prefix='aug', save_format='png'): i += 1 if i > 20: break
The library we need for data augmentation is ImageDataGenerator of Keras. To read a single image Iβve also imported io from skimage. First, we need to create an instance for the data generator. The way you do that is creating a variable called datagen (you can put any name you like) and equal it to ImageDataGenerator with internal arguments.
rotation_range=45 means I want to randomly rotate my image between 0 and 45 degrees. width_shift_range=0.2 and height_shift_range=0.2 means shift the image along X-axis by 20% and Y-axis by 20%. shear_range=0.2 means shear the image by 20%. zoom_range means zoom-in and zoom-out by 20%. For mirror reflection, I have given horizontal_flip=True. The most important argument of ImageDataGenerator is fill_mode. When your image shift by 20% there is some space left over. You can select a few types of methods to fill the area,
constant β Which will fill the area in black color. You can change the color by giving a value for cval
nearest β Which will fill the area with the nearest pixel and stretching it.
reflect β Which will fill the area with the reflection of the image.
wrap β Which will fill the area by wrapping the image around it.
After that using, io.read we can read an image. After reading the image you can see that the image is (256, 256, 3) after reshaping it you can see the image as (1, 256, 256, 3) because when we go into convolutional layers input size is typically the first one is the number of images. Secondly the dimension and lastly the color scheme.
The way we apply the instancedatagen is using datagen.flow. Here we are using .flow because there is only one image. batch_size=16 means itβs generating or augmenting 16 images and save the images in augmented folder. Since the datagen is in a finite loop we need to use a for-loop and break it once it reaches 20 images. ( Similar toepochs)
Now we know how it works letβs look at examples of different fill_mode,
from keras.preprocessing.image import ImageDataGeneratorfrom skimage import iodatagen = ImageDataGenerator( rotation_range=45, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='reflect')import numpy as npimport osfrom PIL import Imageimage_directory = 'test_folder/'SIZE = 128dataset = []my_images = os.listdir(image_directory)for i, image_name in enumerate(my_images): if (image_name.split('.')[1] == 'jpg'): image = io.imread(image_directory + image_name) image = Image.fromarray(image, 'RGB') image = image.resize((SIZE,SIZE)) dataset.append(np.array(image))x = np.array(dataset)i = 0for batch in datagen.flow(x, batch_size=16, save_to_dir='augmented', save_prefix='aug', save_format='png'): i += 1 if i > 20: break
I have to define SIZE = 128 because no matter what your image size is we can resize it to a common size. To read all the images Iβm going to enumerate it using a for-loop. For each image, we have to split it at .jpg. Finally, the resized images will be added to the array. We can do the rest as we have done above. Now we have both test1.jpg and test2.jpg.
Multi-class is what you would expect in most classes. Now Iβve put each image according to their classes because thatβs how this data would represent in a dataset. Using datagen.flow_from_directory is going to read images inside sub-folders separately. For example, If you have classes like cats, dogs, cars, etc. then put all those images in their corresponding folders.
i = 0for batch in datagen.flow_from_directory(directory='test_folder/', batch_size=16, target_size=(256, 256), color_mode="rgb", save_to_dir='augmented', save_prefix='aug', save_format='png'): i += 1 if i > 31: break
That is it for the article. I hope you learn something new. Thank you and stay safe! | [
{
"code": null,
"e": 415,
"s": 172,
"text": "Data Augmentation is very useful if you would like to augment your data or increase the amount of training or validation data. For example, If you have 2000 images and you would like to get 5000 or 10000 of those then this can be very useful."
},
{
"code": null,
"e": 669,
"s": 415,
"text": "But if you have 5 or 10 images, donβt expect to get 2000 or 10000 images from data augmentation and still be able to get a decent result out of your deep learning model. Because the deep learning model will be highly biased towards these 5 or 10 images."
},
{
"code": null,
"e": 755,
"s": 669,
"text": "If you have less than 100 images I would recommend using traditional machine learning"
},
{
"code": null,
"e": 1431,
"s": 755,
"text": "from keras.preprocessing.image import ImageDataGeneratorfrom skimage import iodatagen = ImageDataGenerator( rotation_range=45, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='constant', cval=125)x = io.imread('test_image/test.jpg')x = x.reshape((1, ) + x.shape)i = 0for batch in datagen.flow(x, batch_size=16, save_to_dir='augmented', save_prefix='aug', save_format='png'): i += 1 if i > 20: break"
},
{
"code": null,
"e": 1775,
"s": 1431,
"text": "The library we need for data augmentation is ImageDataGenerator of Keras. To read a single image Iβve also imported io from skimage. First, we need to create an instance for the data generator. The way you do that is creating a variable called datagen (you can put any name you like) and equal it to ImageDataGenerator with internal arguments."
},
{
"code": null,
"e": 2300,
"s": 1775,
"text": "rotation_range=45 means I want to randomly rotate my image between 0 and 45 degrees. width_shift_range=0.2 and height_shift_range=0.2 means shift the image along X-axis by 20% and Y-axis by 20%. shear_range=0.2 means shear the image by 20%. zoom_range means zoom-in and zoom-out by 20%. For mirror reflection, I have given horizontal_flip=True. The most important argument of ImageDataGenerator is fill_mode. When your image shift by 20% there is some space left over. You can select a few types of methods to fill the area,"
},
{
"code": null,
"e": 2404,
"s": 2300,
"text": "constant β Which will fill the area in black color. You can change the color by giving a value for cval"
},
{
"code": null,
"e": 2481,
"s": 2404,
"text": "nearest β Which will fill the area with the nearest pixel and stretching it."
},
{
"code": null,
"e": 2550,
"s": 2481,
"text": "reflect β Which will fill the area with the reflection of the image."
},
{
"code": null,
"e": 2615,
"s": 2550,
"text": "wrap β Which will fill the area by wrapping the image around it."
},
{
"code": null,
"e": 2952,
"s": 2615,
"text": "After that using, io.read we can read an image. After reading the image you can see that the image is (256, 256, 3) after reshaping it you can see the image as (1, 256, 256, 3) because when we go into convolutional layers input size is typically the first one is the number of images. Secondly the dimension and lastly the color scheme."
},
{
"code": null,
"e": 3294,
"s": 2952,
"text": "The way we apply the instancedatagen is using datagen.flow. Here we are using .flow because there is only one image. batch_size=16 means itβs generating or augmenting 16 images and save the images in augmented folder. Since the datagen is in a finite loop we need to use a for-loop and break it once it reaches 20 images. ( Similar toepochs)"
},
{
"code": null,
"e": 3366,
"s": 3294,
"text": "Now we know how it works letβs look at examples of different fill_mode,"
},
{
"code": null,
"e": 4416,
"s": 3366,
"text": "from keras.preprocessing.image import ImageDataGeneratorfrom skimage import iodatagen = ImageDataGenerator( rotation_range=45, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='reflect')import numpy as npimport osfrom PIL import Imageimage_directory = 'test_folder/'SIZE = 128dataset = []my_images = os.listdir(image_directory)for i, image_name in enumerate(my_images): if (image_name.split('.')[1] == 'jpg'): image = io.imread(image_directory + image_name) image = Image.fromarray(image, 'RGB') image = image.resize((SIZE,SIZE)) dataset.append(np.array(image))x = np.array(dataset)i = 0for batch in datagen.flow(x, batch_size=16, save_to_dir='augmented', save_prefix='aug', save_format='png'): i += 1 if i > 20: break"
},
{
"code": null,
"e": 4773,
"s": 4416,
"text": "I have to define SIZE = 128 because no matter what your image size is we can resize it to a common size. To read all the images Iβm going to enumerate it using a for-loop. For each image, we have to split it at .jpg. Finally, the resized images will be added to the array. We can do the rest as we have done above. Now we have both test1.jpg and test2.jpg."
},
{
"code": null,
"e": 5145,
"s": 4773,
"text": "Multi-class is what you would expect in most classes. Now Iβve put each image according to their classes because thatβs how this data would represent in a dataset. Using datagen.flow_from_directory is going to read images inside sub-folders separately. For example, If you have classes like cats, dogs, cars, etc. then put all those images in their corresponding folders."
},
{
"code": null,
"e": 5647,
"s": 5145,
"text": "i = 0for batch in datagen.flow_from_directory(directory='test_folder/', batch_size=16, target_size=(256, 256), color_mode=\"rgb\", save_to_dir='augmented', save_prefix='aug', save_format='png'): i += 1 if i > 31: break"
}
] |
How to perform element-wise subtraction on tensors in PyTorch? | To perform element-wise subtraction on tensors, we can use the torch.sub() method of PyTorch. The corresponding elements of the tensors are subtracted. We can subtract a scalar or tensor from another tensor. We can subtract a tensor from a tensor with same or different dimension. The dimension of the final tensor will be same as the dimension of the higher-dimensional tensor.
Import the required library. In all the following Python examples, the required Python library is torch. Make sure you have already
installed it.
Import the required library. In all the following Python examples, the required Python library is torch. Make sure you have already
installed it.
Define two or more PyTorch tensors and print them. If you want to
subtract a scalar quantity, define it.
Define two or more PyTorch tensors and print them. If you want to
subtract a scalar quantity, define it.
Subtract a scalar or a tensor from another tensor using torch.sub() and assign the value to a new variable. You can also subtract a scalar quantity from the tensor. Subtracting the tensors using this method does not make any change in the original tensors.
Subtract a scalar or a tensor from another tensor using torch.sub() and assign the value to a new variable. You can also subtract a scalar quantity from the tensor. Subtracting the tensors using this method does not make any change in the original tensors.
Print the final tensor.
Print the final tensor.
Here, we will have a Python 3 program to subtract a scalar quantity from a
tensor. We will see three different ways to perform the same task.
# Python program to perform element-wise subtraction
# import the required library
import torch
# Create a tensor
t = torch.Tensor([1.5, 2.03, 3.8, 2.9])
print("Original Tensor t:\n", t)
# Subtract a scalar value to a tensor
v = torch.sub(t, 5.60)
print("Element-wise subtraction result:\n", v)
# Same result can also be obtained as below
t1 = torch.Tensor([5.60])
w = torch.sub(t, t1)
print("Element-wise subtraction result:\n", w)
# Other way to do above operation
t2 = torch.Tensor([5.60,5.60,5.60,5.60])
x = torch.sub(t, t2)
print("Element-wise subtraction result:\n", x)
Original Tensor t:
tensor([1.5000, 2.0300, 3.8000, 2.9000])
Element-wise subtraction result:
tensor([-4.1000, -3.5700, -1.8000, -2.7000])
Element-wise subtraction result:
tensor([-4.1000, -3.5700, -1.8000, -2.7000])
Element-wise subtraction result:
tensor([-4.1000, -3.5700, -1.8000, -2.7000])
The following program shows how to subtract a 1-D tensor from a 2-D tensor.
# Import necessary library
import torch
# Create a 2D tensor
T1 = torch.Tensor([[8,7],[4,5]])
# Create a 1-D tensor
T2 = torch.Tensor([10, 5])
print("T1:\n", T1)
print("T2:\n", T2)
# Subtract 1-D tensor from 2-D tensor
v = torch.sub(T1, T2)
print("Element-wise subtraction result:\n", v)
T1:
tensor([[8., 7.],
[4., 5.]])
T2:
tensor([10., 5.])
Element-wise subtraction result:
tensor([[-2., 2.],
[-6., 0.]])
The following program shows how to subtract a 2D tensor from a 1D tensor.
# Python program to subtract 2D tensor from 1D tensor
# Import the library
import torch
# Create a 2D tensor
T1 = torch.Tensor([[1,2],[4,5]])
# Create a 1-D tensor
T2 = torch.Tensor([10, 5])
print("T1:\n", T1)
print("T2:\n", T2)
# Subtract 2-D tensor from 1-D tensor
v = torch.sub(T2, T1)
print("Element-wise subtraction result:\n", v)
T1:
tensor([[1., 2.],
[4., 5.]])
T2:
tensor([10., 5.])
Element-wise subtraction result:
tensor([[9., 3.],
[6., 0.]])
You can notice that the final tensor is a 2D tensor.
The following program shows how to subtract a 2D tensor from a 2D tensor.
# import the library
import torch
# Create two 2-D tensors
T1 = torch.Tensor([[8,7],[3,4]])
T2 = torch.Tensor([[0,3],[4,9]])
print("T1:\n", T1)
print("T2:\n", T2)
# Subtract above two 2-D tensors
v = torch.sub(T1,T2)
print("Element-wise subtraction result:\n", v)
T1:
tensor([[8., 7.],
[3., 4.]])
T2:
tensor([[0., 3.],
[4., 9.]])
Element-wise subtraction result:
tensor([[ 8., 4.],
[-1., -5.]]) | [
{
"code": null,
"e": 1441,
"s": 1062,
"text": "To perform element-wise subtraction on tensors, we can use the torch.sub() method of PyTorch. The corresponding elements of the tensors are subtracted. We can subtract a scalar or tensor from another tensor. We can subtract a tensor from a tensor with same or different dimension. The dimension of the final tensor will be same as the dimension of the higher-dimensional tensor."
},
{
"code": null,
"e": 1587,
"s": 1441,
"text": "Import the required library. In all the following Python examples, the required Python library is torch. Make sure you have already\ninstalled it."
},
{
"code": null,
"e": 1733,
"s": 1587,
"text": "Import the required library. In all the following Python examples, the required Python library is torch. Make sure you have already\ninstalled it."
},
{
"code": null,
"e": 1838,
"s": 1733,
"text": "Define two or more PyTorch tensors and print them. If you want to\nsubtract a scalar quantity, define it."
},
{
"code": null,
"e": 1943,
"s": 1838,
"text": "Define two or more PyTorch tensors and print them. If you want to\nsubtract a scalar quantity, define it."
},
{
"code": null,
"e": 2200,
"s": 1943,
"text": "Subtract a scalar or a tensor from another tensor using torch.sub() and assign the value to a new variable. You can also subtract a scalar quantity from the tensor. Subtracting the tensors using this method does not make any change in the original tensors."
},
{
"code": null,
"e": 2457,
"s": 2200,
"text": "Subtract a scalar or a tensor from another tensor using torch.sub() and assign the value to a new variable. You can also subtract a scalar quantity from the tensor. Subtracting the tensors using this method does not make any change in the original tensors."
},
{
"code": null,
"e": 2481,
"s": 2457,
"text": "Print the final tensor."
},
{
"code": null,
"e": 2505,
"s": 2481,
"text": "Print the final tensor."
},
{
"code": null,
"e": 2647,
"s": 2505,
"text": "Here, we will have a Python 3 program to subtract a scalar quantity from a\ntensor. We will see three different ways to perform the same task."
},
{
"code": null,
"e": 3227,
"s": 2647,
"text": "# Python program to perform element-wise subtraction\n# import the required library\nimport torch\n\n# Create a tensor\nt = torch.Tensor([1.5, 2.03, 3.8, 2.9])\nprint(\"Original Tensor t:\\n\", t)\n\n# Subtract a scalar value to a tensor\nv = torch.sub(t, 5.60)\nprint(\"Element-wise subtraction result:\\n\", v)\n\n# Same result can also be obtained as below\nt1 = torch.Tensor([5.60])\nw = torch.sub(t, t1)\nprint(\"Element-wise subtraction result:\\n\", w)\n\n# Other way to do above operation\nt2 = torch.Tensor([5.60,5.60,5.60,5.60])\nx = torch.sub(t, t2)\nprint(\"Element-wise subtraction result:\\n\", x)"
},
{
"code": null,
"e": 3533,
"s": 3227,
"text": "Original Tensor t:\n tensor([1.5000, 2.0300, 3.8000, 2.9000])\nElement-wise subtraction result:\n tensor([-4.1000, -3.5700, -1.8000, -2.7000])\nElement-wise subtraction result:\n tensor([-4.1000, -3.5700, -1.8000, -2.7000])\nElement-wise subtraction result:\n tensor([-4.1000, -3.5700, -1.8000, -2.7000])"
},
{
"code": null,
"e": 3609,
"s": 3533,
"text": "The following program shows how to subtract a 1-D tensor from a 2-D tensor."
},
{
"code": null,
"e": 3900,
"s": 3609,
"text": "# Import necessary library\nimport torch\n\n# Create a 2D tensor\nT1 = torch.Tensor([[8,7],[4,5]])\n\n# Create a 1-D tensor\nT2 = torch.Tensor([10, 5])\nprint(\"T1:\\n\", T1)\nprint(\"T2:\\n\", T2)\n\n# Subtract 1-D tensor from 2-D tensor\nv = torch.sub(T1, T2)\nprint(\"Element-wise subtraction result:\\n\", v)"
},
{
"code": null,
"e": 4040,
"s": 3900,
"text": "T1:\ntensor([[8., 7.],\n [4., 5.]])\nT2:\n tensor([10., 5.])\nElement-wise subtraction result:\ntensor([[-2., 2.],\n [-6., 0.]])"
},
{
"code": null,
"e": 4114,
"s": 4040,
"text": "The following program shows how to subtract a 2D tensor from a 1D tensor."
},
{
"code": null,
"e": 4453,
"s": 4114,
"text": "# Python program to subtract 2D tensor from 1D tensor\n# Import the library\nimport torch\n\n# Create a 2D tensor\nT1 = torch.Tensor([[1,2],[4,5]])\n\n# Create a 1-D tensor\nT2 = torch.Tensor([10, 5])\nprint(\"T1:\\n\", T1)\nprint(\"T2:\\n\", T2)\n\n# Subtract 2-D tensor from 1-D tensor\nv = torch.sub(T2, T1)\nprint(\"Element-wise subtraction result:\\n\", v)"
},
{
"code": null,
"e": 4591,
"s": 4453,
"text": "T1:\ntensor([[1., 2.],\n [4., 5.]])\nT2:\n tensor([10., 5.])\nElement-wise subtraction result:\ntensor([[9., 3.],\n [6., 0.]])"
},
{
"code": null,
"e": 4644,
"s": 4591,
"text": "You can notice that the final tensor is a 2D tensor."
},
{
"code": null,
"e": 4718,
"s": 4644,
"text": "The following program shows how to subtract a 2D tensor from a 2D tensor."
},
{
"code": null,
"e": 4984,
"s": 4718,
"text": "# import the library\nimport torch\n\n# Create two 2-D tensors\nT1 = torch.Tensor([[8,7],[3,4]])\nT2 = torch.Tensor([[0,3],[4,9]])\nprint(\"T1:\\n\", T1)\nprint(\"T2:\\n\", T2)\n\n# Subtract above two 2-D tensors\nv = torch.sub(T1,T2)\nprint(\"Element-wise subtraction result:\\n\", v)"
},
{
"code": null,
"e": 5142,
"s": 4984,
"text": "T1:\ntensor([[8., 7.],\n [3., 4.]])\nT2:\ntensor([[0., 3.],\n [4., 9.]])\nElement-wise subtraction result:\ntensor([[ 8., 4.],\n [-1., -5.]])"
}
] |
What does built-in class attribute __bases__ do in Python? | This built-in class attribute when called prints the tuple of base classes of a class object.
The following code shows how the __bases__ works. B is a child class of the parent/base class A.
class A(object): pass
class B(A): pass
b = B()
print B.__bases__
This gives the output
(<class '__main__.A'>,) | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "This built-in class attribute when called prints the tuple of base classes of a class object."
},
{
"code": null,
"e": 1253,
"s": 1156,
"text": "The following code shows how the __bases__ works. B is a child class of the parent/base class A."
},
{
"code": null,
"e": 1318,
"s": 1253,
"text": "class A(object): pass\nclass B(A): pass\nb = B()\nprint B.__bases__"
},
{
"code": null,
"e": 1340,
"s": 1318,
"text": "This gives the output"
},
{
"code": null,
"e": 1364,
"s": 1340,
"text": "(<class '__main__.A'>,)"
}
] |
How to Build And Publish Command-Line Applications With Python | by Oyetoke Tobi Emmanuel | Towards Data Science | Command-line applications are basically programs you run in your terminal and chances are that you have tried or thought of building one.
Building a Command-Line Application is one thing, publishing it to an open public code repository like PyPI is another thing and shouldnβt be seen as a difficult task or process.
I have previously written an article, where I gave an in-depth explanation of various ways and methods to build command-line applications in Python.
In this article, I will be explaining how you can build a simple CLI with Python and publish it to PyPI.
Recently I have been doing some research on Open Source Vulnerabilities and I would like to have a command-line tool I could use to search and lookup vulnerabilities right from the terminal. Open-source vulnerabilities are usually published in public databases and could be found on websites like CVE, NVD, WhiteSource Vuln, and so on.
In this article, weβll be building a simple scraper to search and lookup vulnerabilities on the CVE websites, wrap it a simple command-line application, and publish it to PyPI.
Cool right?
To get started, you will need to set up your development environment and install the required modules. I suggest setting up a virtual environment as it makes things easier and helps avoid conflict in modules versions.
To create a virtual environment you can either use the python3 command python -m venv <path/name> or install virtualenvwrapper using pip install virtualenvwrapper and create a virtualenv using mkvirtualenv -p /path/topython <path/name>
Once you have the virtualenv set up and activated, you can create the project folder and install the required modules:
mkvirtualenv -p /usr/bin/python cvecli-envmkdir cvecli && cd cveclimkdir cver && touch setup.py && touch README.md && touch cver/__init__.py && touch .gitignorepip install requests beautifulsoup4 lxml twine clickpip freeze > requirements.txt
Once everything runs successfully, you can open the project in any of your code editors and you should see a structure like below:
In order to be able to search and do vulnerabilities lookup on the CVE website, we would need a web scraper that helps scrapes vulnerability details. Weβll be building the scraper on Requests and Beautifulsoup and the scraper will be able to:
Search for vulnerabilitiesGet a vulnerability detail using its CVE name
Search for vulnerabilities
Get a vulnerability detail using its CVE name
Now inside the cver folder, create a file called cve_scraper type in this basic setup:
import requestsfrom bs4 import BeautifulSoupSEARCH_URL = "https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword="CVE_URL = "https://cve.mitre.org/cgi-bin/cvename.cgi?name="def get_html(url): request = requests.get(url) if request.status_code == 200: return request.content else: raise Exception("Bad request")def search(s): passdef lookup_cve(name): pass
To search for a vulnerability on the CVE website, the URL format is like: https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=<keyword>. With this, you should be able to extract a list of matching vulnerabilities with the keyword,
For instance, we can use the URL to get all python related vulnerabilities:
To extract the data, let's open the Developer Console and inspect the DOM element rendering the above data. You can right-click on any part of the page and click on inspect element or press Ctrl + F12.
If you take a look at the DOM structure in the image above you will notice that the results are being displayed in a table and each result is a row under the table. The data can be easily extracted below:
def search(s): url = f"{SEARCH_URL}{s}" results=[] html = get_html(url) soup = BeautifulSoup(html, "lxml") result_rows = soup.select("#TableWithRules table tr") for row in result_rows: _row = {} name = row.select_one("td a") description = row.select_one("td:nth-child(2)") if all([name, description]): _row["name"] = name.text _row["url"] = name.get("href") _row["description"] = description.text results.append(_row) return results
In the above code we:
Sent a request to the SEARCH_URL using Requests and get the DOM contentTransform the DOM content into BeautifulSoup objects where we can use some methods to select the dom element using CSS selectors and others like XPATH.Selected all tr under the #TableWithRules table, and select the first column of the row as name and the second one as description and then extract the text.
Sent a request to the SEARCH_URL using Requests and get the DOM content
Transform the DOM content into BeautifulSoup objects where we can use some methods to select the dom element using CSS selectors and others like XPATH.
Selected all tr under the #TableWithRules table, and select the first column of the row as name and the second one as description and then extract the text.
To lookup a vulnerability details, you will need to provide the CVE-ID of the vulnerability and pass it to this URL: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-ID
Open your Developer Console and let's inspect the DOM structure.
Looking at the structure above is quite a little bit complex as the table rows are not identified with class name or id. We would need to loop through each row check if its a subtitle, if yes then we take the next element as the child content. Each subtitle is rendered inth while content is in td
def lookup_cve(name): url = f"{CVE_URL}{name}" html = get_html(url) soup = BeautifulSoup(html, "lxml") result_rows = soup.select("#GeneratedTable table tr")subtitle = "" description = ""raw_results = {}for row in result_rows: head = row.select_one("th") if head: subtitle = head.text else: body = row.select_one("td") description = body.text.strip().strip("\n") raw_results[subtitle.lower()] = description return raw_results
Tada! We have successfully created our CVE web scraper. You can now the two functions (search and lookup_sve) to search vulnerabilities and get details on vulnerability using its CVE-ID.
The next step is structuring and building our command-line app using the Click library.
Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It's one of the best python packages for creating CLI and easy to get started
With Click, you can build any kind of simple or enterprise level CLI like Heroku CLI.
In our CLI, weβll be implementing two commands:
Search for vulnerabilityLookup a vulnerability
Search for vulnerability
Lookup a vulnerability
Create a file named __main__.py in the cver folder and type in below basic code:
import sysimport [email protected]()@click.version_option("1.0.0")def main(): """A CVE Search and Lookup CLI""" print("Hye") [email protected]()@click.argument('keyword', required=False)def search(**kwargs): """Search through CVE Database for vulnerabilities""" click.echo(kwargs) [email protected]()@click.argument('name', required=False)def look_up(**kwargs): """Get vulnerability details using its CVE-ID on CVE Database""" click.echo(kwargs) passif __name__ == '__main__': args = sys.argv if "--help" in args or len(args) == 1: print("CVE") main()
To implement this, we are going to import the search function from our web scraper and pass it the keyword argument from the command line to search for vulnerabilities matching that keyword:
from scraper import search as cve_search, [email protected]()@click.argument('keyword', required=False)def search(**kwargs): """Search through CVE Database for vulnerabilities""" results = cve_search(kwargs.get("keyword")) for res in results: click.echo(f'{res["name"]} - {res["url"]} \n{res["description"]}')
To run this command:
python cver/__main__.py search python
Same thing here, we are going to use the lookup_cve from the web scraper and pass it the name argument from the look_up command.
@main.command()@click.argument('name', required=False)def look_up(**kwargs): """Get vulnerability details using its CVE-ID on CVE Database""" details = lookup_cve(kwargs.get("name")) click.echo(f'CVE-ID \n\n{details["cve-id"]}\n') click.echo(f'Description \n\n{details["description"]}\n') click.echo(f'References \n\n{details["references"]}\n') click.echo(f'Assigning CNA \n\n{details["assigning cna"]}\n') click.echo(f'Date Entry \n\n{details["date entry created"]}')
To run this command:
python cver/__main__.py look-up CVE-2013-4238
Tada! We have successfully built our CVE lookup command-line tool.
Now that we have successfully built our command-line application and everything is working fine, we can publish it to PyPI for public use and installation.
PyPI is a software repository for Python Package and it holds most python packages we install using pip command tool. To publish a package on PyPI, you need to create an account, so you can head over to the website and create a new account and if you already have one, then you are good to go.
Once you are done with that, the next thing is to configure our Python package using setup.py. In order for your package to be uploaded to PyPI, you need to provide some basic information about the package. This information is typically provided in the setup.py file.
So open the setup.py in the base directory of the project and put this at the beginning of the file:
from setuptools import setup, find_packagesfrom io import openfrom os import pathimport pathlib# The directory containing this fileHERE = pathlib.Path(__file__).parent# The text of the README fileREADME = (HERE / "README.md").read_text()# automatically captured required modules for install_requires in requirements.txt and as well as configure dependency linkswith open(path.join(HERE, 'requirements.txt'), encoding='utf-8') as f: all_reqs = f.read().split('\n')install_requires = [x.strip() for x in all_reqs if ('git+' not in x) and ( not x.startswith('#')) and (not x.startswith('-'))]dependency_links = [x.strip().replace('git+', '') for x in all_reqs \ if 'git+' not in x]
In the above, we converted the content of our README.md file to string for later use. We also captured all required modules from the requirements.txt and as well as generated their dependency links.
Your requirements.txt file should look like this:
clickrequestsbeautifulsoup4lxmltwine
Now let's look at our setup configuration:
setup ( name = 'cver', description = 'A simple commandline app for searching and looking up opensource vulnerabilities', version = '1.0.0', packages = find_packages(), # list of all packages install_requires = install_requires, python_requires='>=2.7', # any python greater than 2.7 entry_points=''' [console_scripts] cver=cver.__main__:main ''', author="Oyetoke Toby", keyword="cve, vuln, vulnerabilities, security, nvd", long_description=README, long_description_content_type="text/markdown", license='MIT', url='https://github.com/CITGuru/cver', download_url='https://github.com/CITGuru/cver/archive/1.0.0.tar.gz', dependency_links=dependency_links, author_email='[email protected]', classifiers=[ "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", ])
In the above code, we added some options and we will only cover some of the options available in the setup here. The setup tool documentation does a good job of going into all the detail.
name: the name of your package as it will appear on PyPIversion: the current version of your packagepackages: the packages and sub-packages containing your source code. We are using the find_packages module in setup to help us find our sub-packages automatically.install_requires: this is used to list any dependencies or third-party libraries your package has. In cver, we are using requests, beautifulsoup4, and click. They must be included in the install_requires setup. We don't need to put it manually as we already reading the requirements.txt to get them.entry_points: this is used to create scripts that call a function within your package. In our setup, we create a new script cver that calls main() within the cver/__main__.py file. Our main entry is the __main__.py and that calls the main() function to initiate click.
name: the name of your package as it will appear on PyPI
version: the current version of your package
packages: the packages and sub-packages containing your source code. We are using the find_packages module in setup to help us find our sub-packages automatically.
install_requires: this is used to list any dependencies or third-party libraries your package has. In cver, we are using requests, beautifulsoup4, and click. They must be included in the install_requires setup. We don't need to put it manually as we already reading the requirements.txt to get them.
entry_points: this is used to create scripts that call a function within your package. In our setup, we create a new script cver that calls main() within the cver/__main__.py file. Our main entry is the __main__.py and that calls the main() function to initiate click.
Before publishing your package to PyPI or the public, you should add some documentation. How you want to document your package depends on your project. It could be a simple README.md file or Readme.rst file totally depends on you.
Hereβs a typical nice README.md :
# CVERA simple commandline app for searching and looking up opensource vulnerabilities# Installation## Using Pip```bash $ pip install cver```## Manual```bash $ git clone https://github.com/citguru/cevr $ cd cver $ python setup.py install```# Usage```bash$ cver```## Search`search <keyword>````bash$ cver search python```## Lookup`search <name>````bash$ cver look-up CVE-2020-2121```
Also, create a .gitignore file:
That's it.
Once everything is done successfully, the package is ready to go public and published on PyPI. Ensure you already have created an account as I mentioned earlier, and also you will need to create a Testing account on the PyPI test server to test the packages before publish to the live server.
Weβll be using a tool called Twine to upload your python packages to PyPI. It should be installed in earlier steps, but if you donβt have it installed, you can just do pip install twine .
Python packages published on PyPI are not distributed as plain source code but are wrapped into distribution packages. Python wheels and source archives are the most common formats in distributing python packages.
Python wheels are essentially a zip archive containing your code and include any extensions ready to use. Source Archives is made up of your source code and any supporting files wrapped into one tar file.
To test our package locally, we just need to run:
python setup.py install
Then we can now use it as:
cver search python
To test our package on PyPI test server, weβll need to generate a build for local testing. Creating a build will generate both python wheel and source archives.
To create a build:
python setup.py sdist bdist_wheel
This will generate two files in a dist directory:
cvecli/ββββ dist/ βββ cver-1.0.0-py3-none-any.whl βββ cver-1.0.0.tar.gz
Then using twine, we can now upload to the TestPyPI server:
twine upload --repository-url https://test.pypi.org/legacy/ dist/*
This will ask for your username and password, so ensure you enter that correctly.
If it uploads successfully with no issues, that means we can publish on the live server. You can check it out here.
To install from the TestPyPI, run the below command:
pip install -i https://test.pypi.org/simple/ cver==1.0.0
From here you can try out all your commands and see if all goes well before we publish to the live server.
Once you have tested all commands and ready to publish to live server:
twine upload dist/*
Enter your username and password when prompted. Thatβs it!
You can now install it using:
pip install cver
Congratulations! Your package is published on PyPI and you can view it here!
In this article, I have explained the step by step process on how to build and publish your next command line application with Python. | [
{
"code": null,
"e": 184,
"s": 46,
"text": "Command-line applications are basically programs you run in your terminal and chances are that you have tried or thought of building one."
},
{
"code": null,
"e": 363,
"s": 184,
"text": "Building a Command-Line Application is one thing, publishing it to an open public code repository like PyPI is another thing and shouldnβt be seen as a difficult task or process."
},
{
"code": null,
"e": 512,
"s": 363,
"text": "I have previously written an article, where I gave an in-depth explanation of various ways and methods to build command-line applications in Python."
},
{
"code": null,
"e": 617,
"s": 512,
"text": "In this article, I will be explaining how you can build a simple CLI with Python and publish it to PyPI."
},
{
"code": null,
"e": 953,
"s": 617,
"text": "Recently I have been doing some research on Open Source Vulnerabilities and I would like to have a command-line tool I could use to search and lookup vulnerabilities right from the terminal. Open-source vulnerabilities are usually published in public databases and could be found on websites like CVE, NVD, WhiteSource Vuln, and so on."
},
{
"code": null,
"e": 1130,
"s": 953,
"text": "In this article, weβll be building a simple scraper to search and lookup vulnerabilities on the CVE websites, wrap it a simple command-line application, and publish it to PyPI."
},
{
"code": null,
"e": 1142,
"s": 1130,
"text": "Cool right?"
},
{
"code": null,
"e": 1360,
"s": 1142,
"text": "To get started, you will need to set up your development environment and install the required modules. I suggest setting up a virtual environment as it makes things easier and helps avoid conflict in modules versions."
},
{
"code": null,
"e": 1596,
"s": 1360,
"text": "To create a virtual environment you can either use the python3 command python -m venv <path/name> or install virtualenvwrapper using pip install virtualenvwrapper and create a virtualenv using mkvirtualenv -p /path/topython <path/name>"
},
{
"code": null,
"e": 1715,
"s": 1596,
"text": "Once you have the virtualenv set up and activated, you can create the project folder and install the required modules:"
},
{
"code": null,
"e": 1957,
"s": 1715,
"text": "mkvirtualenv -p /usr/bin/python cvecli-envmkdir cvecli && cd cveclimkdir cver && touch setup.py && touch README.md && touch cver/__init__.py && touch .gitignorepip install requests beautifulsoup4 lxml twine clickpip freeze > requirements.txt"
},
{
"code": null,
"e": 2088,
"s": 1957,
"text": "Once everything runs successfully, you can open the project in any of your code editors and you should see a structure like below:"
},
{
"code": null,
"e": 2331,
"s": 2088,
"text": "In order to be able to search and do vulnerabilities lookup on the CVE website, we would need a web scraper that helps scrapes vulnerability details. Weβll be building the scraper on Requests and Beautifulsoup and the scraper will be able to:"
},
{
"code": null,
"e": 2403,
"s": 2331,
"text": "Search for vulnerabilitiesGet a vulnerability detail using its CVE name"
},
{
"code": null,
"e": 2430,
"s": 2403,
"text": "Search for vulnerabilities"
},
{
"code": null,
"e": 2476,
"s": 2430,
"text": "Get a vulnerability detail using its CVE name"
},
{
"code": null,
"e": 2563,
"s": 2476,
"text": "Now inside the cver folder, create a file called cve_scraper type in this basic setup:"
},
{
"code": null,
"e": 2942,
"s": 2563,
"text": "import requestsfrom bs4 import BeautifulSoupSEARCH_URL = \"https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=\"CVE_URL = \"https://cve.mitre.org/cgi-bin/cvename.cgi?name=\"def get_html(url): request = requests.get(url) if request.status_code == 200: return request.content else: raise Exception(\"Bad request\")def search(s): passdef lookup_cve(name): pass"
},
{
"code": null,
"e": 3170,
"s": 2942,
"text": "To search for a vulnerability on the CVE website, the URL format is like: https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=<keyword>. With this, you should be able to extract a list of matching vulnerabilities with the keyword,"
},
{
"code": null,
"e": 3246,
"s": 3170,
"text": "For instance, we can use the URL to get all python related vulnerabilities:"
},
{
"code": null,
"e": 3448,
"s": 3246,
"text": "To extract the data, let's open the Developer Console and inspect the DOM element rendering the above data. You can right-click on any part of the page and click on inspect element or press Ctrl + F12."
},
{
"code": null,
"e": 3653,
"s": 3448,
"text": "If you take a look at the DOM structure in the image above you will notice that the results are being displayed in a table and each result is a row under the table. The data can be easily extracted below:"
},
{
"code": null,
"e": 4192,
"s": 3653,
"text": "def search(s): url = f\"{SEARCH_URL}{s}\" results=[] html = get_html(url) soup = BeautifulSoup(html, \"lxml\") result_rows = soup.select(\"#TableWithRules table tr\") for row in result_rows: _row = {} name = row.select_one(\"td a\") description = row.select_one(\"td:nth-child(2)\") if all([name, description]): _row[\"name\"] = name.text _row[\"url\"] = name.get(\"href\") _row[\"description\"] = description.text results.append(_row) return results"
},
{
"code": null,
"e": 4214,
"s": 4192,
"text": "In the above code we:"
},
{
"code": null,
"e": 4593,
"s": 4214,
"text": "Sent a request to the SEARCH_URL using Requests and get the DOM contentTransform the DOM content into BeautifulSoup objects where we can use some methods to select the dom element using CSS selectors and others like XPATH.Selected all tr under the #TableWithRules table, and select the first column of the row as name and the second one as description and then extract the text."
},
{
"code": null,
"e": 4665,
"s": 4593,
"text": "Sent a request to the SEARCH_URL using Requests and get the DOM content"
},
{
"code": null,
"e": 4817,
"s": 4665,
"text": "Transform the DOM content into BeautifulSoup objects where we can use some methods to select the dom element using CSS selectors and others like XPATH."
},
{
"code": null,
"e": 4974,
"s": 4817,
"text": "Selected all tr under the #TableWithRules table, and select the first column of the row as name and the second one as description and then extract the text."
},
{
"code": null,
"e": 5145,
"s": 4974,
"text": "To lookup a vulnerability details, you will need to provide the CVE-ID of the vulnerability and pass it to this URL: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-ID"
},
{
"code": null,
"e": 5210,
"s": 5145,
"text": "Open your Developer Console and let's inspect the DOM structure."
},
{
"code": null,
"e": 5508,
"s": 5210,
"text": "Looking at the structure above is quite a little bit complex as the table rows are not identified with class name or id. We would need to loop through each row check if its a subtitle, if yes then we take the next element as the child content. Each subtitle is rendered inth while content is in td"
},
{
"code": null,
"e": 6030,
"s": 5508,
"text": "def lookup_cve(name): url = f\"{CVE_URL}{name}\" html = get_html(url) soup = BeautifulSoup(html, \"lxml\") result_rows = soup.select(\"#GeneratedTable table tr\")subtitle = \"\" description = \"\"raw_results = {}for row in result_rows: head = row.select_one(\"th\") if head: subtitle = head.text else: body = row.select_one(\"td\") description = body.text.strip().strip(\"\\n\") raw_results[subtitle.lower()] = description return raw_results"
},
{
"code": null,
"e": 6217,
"s": 6030,
"text": "Tada! We have successfully created our CVE web scraper. You can now the two functions (search and lookup_sve) to search vulnerabilities and get details on vulnerability using its CVE-ID."
},
{
"code": null,
"e": 6305,
"s": 6217,
"text": "The next step is structuring and building our command-line app using the Click library."
},
{
"code": null,
"e": 6510,
"s": 6305,
"text": "Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It's one of the best python packages for creating CLI and easy to get started"
},
{
"code": null,
"e": 6596,
"s": 6510,
"text": "With Click, you can build any kind of simple or enterprise level CLI like Heroku CLI."
},
{
"code": null,
"e": 6644,
"s": 6596,
"text": "In our CLI, weβll be implementing two commands:"
},
{
"code": null,
"e": 6691,
"s": 6644,
"text": "Search for vulnerabilityLookup a vulnerability"
},
{
"code": null,
"e": 6716,
"s": 6691,
"text": "Search for vulnerability"
},
{
"code": null,
"e": 6739,
"s": 6716,
"text": "Lookup a vulnerability"
},
{
"code": null,
"e": 6820,
"s": 6739,
"text": "Create a file named __main__.py in the cver folder and type in below basic code:"
},
{
"code": null,
"e": 7415,
"s": 6820,
"text": "import sysimport [email protected]()@click.version_option(\"1.0.0\")def main(): \"\"\"A CVE Search and Lookup CLI\"\"\" print(\"Hye\") [email protected]()@click.argument('keyword', required=False)def search(**kwargs): \"\"\"Search through CVE Database for vulnerabilities\"\"\" click.echo(kwargs) [email protected]()@click.argument('name', required=False)def look_up(**kwargs): \"\"\"Get vulnerability details using its CVE-ID on CVE Database\"\"\" click.echo(kwargs) passif __name__ == '__main__': args = sys.argv if \"--help\" in args or len(args) == 1: print(\"CVE\") main()"
},
{
"code": null,
"e": 7606,
"s": 7415,
"text": "To implement this, we are going to import the search function from our web scraper and pass it the keyword argument from the command line to search for vulnerabilities matching that keyword:"
},
{
"code": null,
"e": 7938,
"s": 7606,
"text": "from scraper import search as cve_search, [email protected]()@click.argument('keyword', required=False)def search(**kwargs): \"\"\"Search through CVE Database for vulnerabilities\"\"\" results = cve_search(kwargs.get(\"keyword\")) for res in results: click.echo(f'{res[\"name\"]} - {res[\"url\"]} \\n{res[\"description\"]}')"
},
{
"code": null,
"e": 7959,
"s": 7938,
"text": "To run this command:"
},
{
"code": null,
"e": 7997,
"s": 7959,
"text": "python cver/__main__.py search python"
},
{
"code": null,
"e": 8126,
"s": 7997,
"text": "Same thing here, we are going to use the lookup_cve from the web scraper and pass it the name argument from the look_up command."
},
{
"code": null,
"e": 8616,
"s": 8126,
"text": "@main.command()@click.argument('name', required=False)def look_up(**kwargs): \"\"\"Get vulnerability details using its CVE-ID on CVE Database\"\"\" details = lookup_cve(kwargs.get(\"name\")) click.echo(f'CVE-ID \\n\\n{details[\"cve-id\"]}\\n') click.echo(f'Description \\n\\n{details[\"description\"]}\\n') click.echo(f'References \\n\\n{details[\"references\"]}\\n') click.echo(f'Assigning CNA \\n\\n{details[\"assigning cna\"]}\\n') click.echo(f'Date Entry \\n\\n{details[\"date entry created\"]}')"
},
{
"code": null,
"e": 8637,
"s": 8616,
"text": "To run this command:"
},
{
"code": null,
"e": 8683,
"s": 8637,
"text": "python cver/__main__.py look-up CVE-2013-4238"
},
{
"code": null,
"e": 8750,
"s": 8683,
"text": "Tada! We have successfully built our CVE lookup command-line tool."
},
{
"code": null,
"e": 8906,
"s": 8750,
"text": "Now that we have successfully built our command-line application and everything is working fine, we can publish it to PyPI for public use and installation."
},
{
"code": null,
"e": 9200,
"s": 8906,
"text": "PyPI is a software repository for Python Package and it holds most python packages we install using pip command tool. To publish a package on PyPI, you need to create an account, so you can head over to the website and create a new account and if you already have one, then you are good to go."
},
{
"code": null,
"e": 9468,
"s": 9200,
"text": "Once you are done with that, the next thing is to configure our Python package using setup.py. In order for your package to be uploaded to PyPI, you need to provide some basic information about the package. This information is typically provided in the setup.py file."
},
{
"code": null,
"e": 9569,
"s": 9468,
"text": "So open the setup.py in the base directory of the project and put this at the beginning of the file:"
},
{
"code": null,
"e": 10273,
"s": 9569,
"text": "from setuptools import setup, find_packagesfrom io import openfrom os import pathimport pathlib# The directory containing this fileHERE = pathlib.Path(__file__).parent# The text of the README fileREADME = (HERE / \"README.md\").read_text()# automatically captured required modules for install_requires in requirements.txt and as well as configure dependency linkswith open(path.join(HERE, 'requirements.txt'), encoding='utf-8') as f: all_reqs = f.read().split('\\n')install_requires = [x.strip() for x in all_reqs if ('git+' not in x) and ( not x.startswith('#')) and (not x.startswith('-'))]dependency_links = [x.strip().replace('git+', '') for x in all_reqs \\ if 'git+' not in x]"
},
{
"code": null,
"e": 10472,
"s": 10273,
"text": "In the above, we converted the content of our README.md file to string for later use. We also captured all required modules from the requirements.txt and as well as generated their dependency links."
},
{
"code": null,
"e": 10522,
"s": 10472,
"text": "Your requirements.txt file should look like this:"
},
{
"code": null,
"e": 10559,
"s": 10522,
"text": "clickrequestsbeautifulsoup4lxmltwine"
},
{
"code": null,
"e": 10602,
"s": 10559,
"text": "Now let's look at our setup configuration:"
},
{
"code": null,
"e": 11526,
"s": 10602,
"text": "setup ( name = 'cver', description = 'A simple commandline app for searching and looking up opensource vulnerabilities', version = '1.0.0', packages = find_packages(), # list of all packages install_requires = install_requires, python_requires='>=2.7', # any python greater than 2.7 entry_points=''' [console_scripts] cver=cver.__main__:main ''', author=\"Oyetoke Toby\", keyword=\"cve, vuln, vulnerabilities, security, nvd\", long_description=README, long_description_content_type=\"text/markdown\", license='MIT', url='https://github.com/CITGuru/cver', download_url='https://github.com/CITGuru/cver/archive/1.0.0.tar.gz', dependency_links=dependency_links, author_email='[email protected]', classifiers=[ \"License :: OSI Approved :: MIT License\", \"Programming Language :: Python :: 2.7\", \"Programming Language :: Python :: 3\", \"Programming Language :: Python :: 3.7\", ])"
},
{
"code": null,
"e": 11714,
"s": 11526,
"text": "In the above code, we added some options and we will only cover some of the options available in the setup here. The setup tool documentation does a good job of going into all the detail."
},
{
"code": null,
"e": 12545,
"s": 11714,
"text": "name: the name of your package as it will appear on PyPIversion: the current version of your packagepackages: the packages and sub-packages containing your source code. We are using the find_packages module in setup to help us find our sub-packages automatically.install_requires: this is used to list any dependencies or third-party libraries your package has. In cver, we are using requests, beautifulsoup4, and click. They must be included in the install_requires setup. We don't need to put it manually as we already reading the requirements.txt to get them.entry_points: this is used to create scripts that call a function within your package. In our setup, we create a new script cver that calls main() within the cver/__main__.py file. Our main entry is the __main__.py and that calls the main() function to initiate click."
},
{
"code": null,
"e": 12602,
"s": 12545,
"text": "name: the name of your package as it will appear on PyPI"
},
{
"code": null,
"e": 12647,
"s": 12602,
"text": "version: the current version of your package"
},
{
"code": null,
"e": 12811,
"s": 12647,
"text": "packages: the packages and sub-packages containing your source code. We are using the find_packages module in setup to help us find our sub-packages automatically."
},
{
"code": null,
"e": 13111,
"s": 12811,
"text": "install_requires: this is used to list any dependencies or third-party libraries your package has. In cver, we are using requests, beautifulsoup4, and click. They must be included in the install_requires setup. We don't need to put it manually as we already reading the requirements.txt to get them."
},
{
"code": null,
"e": 13380,
"s": 13111,
"text": "entry_points: this is used to create scripts that call a function within your package. In our setup, we create a new script cver that calls main() within the cver/__main__.py file. Our main entry is the __main__.py and that calls the main() function to initiate click."
},
{
"code": null,
"e": 13611,
"s": 13380,
"text": "Before publishing your package to PyPI or the public, you should add some documentation. How you want to document your package depends on your project. It could be a simple README.md file or Readme.rst file totally depends on you."
},
{
"code": null,
"e": 13645,
"s": 13611,
"text": "Hereβs a typical nice README.md :"
},
{
"code": null,
"e": 14032,
"s": 13645,
"text": "# CVERA simple commandline app for searching and looking up opensource vulnerabilities# Installation## Using Pip```bash $ pip install cver```## Manual```bash $ git clone https://github.com/citguru/cevr $ cd cver $ python setup.py install```# Usage```bash$ cver```## Search`search <keyword>````bash$ cver search python```## Lookup`search <name>````bash$ cver look-up CVE-2020-2121```"
},
{
"code": null,
"e": 14064,
"s": 14032,
"text": "Also, create a .gitignore file:"
},
{
"code": null,
"e": 14075,
"s": 14064,
"text": "That's it."
},
{
"code": null,
"e": 14368,
"s": 14075,
"text": "Once everything is done successfully, the package is ready to go public and published on PyPI. Ensure you already have created an account as I mentioned earlier, and also you will need to create a Testing account on the PyPI test server to test the packages before publish to the live server."
},
{
"code": null,
"e": 14556,
"s": 14368,
"text": "Weβll be using a tool called Twine to upload your python packages to PyPI. It should be installed in earlier steps, but if you donβt have it installed, you can just do pip install twine ."
},
{
"code": null,
"e": 14770,
"s": 14556,
"text": "Python packages published on PyPI are not distributed as plain source code but are wrapped into distribution packages. Python wheels and source archives are the most common formats in distributing python packages."
},
{
"code": null,
"e": 14975,
"s": 14770,
"text": "Python wheels are essentially a zip archive containing your code and include any extensions ready to use. Source Archives is made up of your source code and any supporting files wrapped into one tar file."
},
{
"code": null,
"e": 15025,
"s": 14975,
"text": "To test our package locally, we just need to run:"
},
{
"code": null,
"e": 15049,
"s": 15025,
"text": "python setup.py install"
},
{
"code": null,
"e": 15076,
"s": 15049,
"text": "Then we can now use it as:"
},
{
"code": null,
"e": 15095,
"s": 15076,
"text": "cver search python"
},
{
"code": null,
"e": 15256,
"s": 15095,
"text": "To test our package on PyPI test server, weβll need to generate a build for local testing. Creating a build will generate both python wheel and source archives."
},
{
"code": null,
"e": 15275,
"s": 15256,
"text": "To create a build:"
},
{
"code": null,
"e": 15309,
"s": 15275,
"text": "python setup.py sdist bdist_wheel"
},
{
"code": null,
"e": 15359,
"s": 15309,
"text": "This will generate two files in a dist directory:"
},
{
"code": null,
"e": 15437,
"s": 15359,
"text": "cvecli/ββββ dist/ βββ cver-1.0.0-py3-none-any.whl βββ cver-1.0.0.tar.gz"
},
{
"code": null,
"e": 15497,
"s": 15437,
"text": "Then using twine, we can now upload to the TestPyPI server:"
},
{
"code": null,
"e": 15564,
"s": 15497,
"text": "twine upload --repository-url https://test.pypi.org/legacy/ dist/*"
},
{
"code": null,
"e": 15646,
"s": 15564,
"text": "This will ask for your username and password, so ensure you enter that correctly."
},
{
"code": null,
"e": 15762,
"s": 15646,
"text": "If it uploads successfully with no issues, that means we can publish on the live server. You can check it out here."
},
{
"code": null,
"e": 15815,
"s": 15762,
"text": "To install from the TestPyPI, run the below command:"
},
{
"code": null,
"e": 15872,
"s": 15815,
"text": "pip install -i https://test.pypi.org/simple/ cver==1.0.0"
},
{
"code": null,
"e": 15979,
"s": 15872,
"text": "From here you can try out all your commands and see if all goes well before we publish to the live server."
},
{
"code": null,
"e": 16050,
"s": 15979,
"text": "Once you have tested all commands and ready to publish to live server:"
},
{
"code": null,
"e": 16070,
"s": 16050,
"text": "twine upload dist/*"
},
{
"code": null,
"e": 16129,
"s": 16070,
"text": "Enter your username and password when prompted. Thatβs it!"
},
{
"code": null,
"e": 16159,
"s": 16129,
"text": "You can now install it using:"
},
{
"code": null,
"e": 16176,
"s": 16159,
"text": "pip install cver"
},
{
"code": null,
"e": 16253,
"s": 16176,
"text": "Congratulations! Your package is published on PyPI and you can view it here!"
}
] |
Rearrange Array Alternately | Practice | GeeksforGeeks | Given a sorted array of positive integers. Your task is to rearrange the array elements alternatively i.e first element should be max value, second should be min value, third should be second max, fourth should be second min and so on.
Example 1:
Input:
N = 6
arr[] = {1,2,3,4,5,6}
Output: 6 1 5 2 4 3
Explanation: Max element = 6, min = 1,
second max = 5, second min = 2, and
so on... Modified array is : 6 1 5 2 4 3.
Example 2:
Input:
N = 11
arr[]={10,20,30,40,50,60,70,80,90,100,110}
Output:110 10 100 20 90 30 80 40 70 50 60
Explanation: Max element = 110, min = 10,
second max = 100, second min = 20, and
so on... Modified array is :
110 10 100 20 90 30 80 40 70 50 60.
Your Task:
The task is to complete the function rearrange() which rearranges elements as explained above. Printing of the modified array will be handled by driver code.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 <= N <= 106
1 <= arr[i] <= 107
0
prashanth742in 8 hours
c#:public void rearrange(long[] arr, int n) { //code here var nArr=new long[n]; if(n%2==1) { nArr[n-1]=arr[n/2]; }
int i=0; int ni=0; while(i<n/2) { nArr[ni]=arr[n-1-i]; nArr[ni+1]=arr[i]; i=i+1; ni=ni+2; } for(int j=0;j<n;j++) { arr[j]=nArr[j]; } }
0
shulabhgillin 5 hours
class Solution{ // temp: input array // n: size of array //Function to rearrange the array elements alternately. public static void rearrange(long arr[], int n){ long a[] =new long[n]; int i=0 , j=n-1; boolean flag=false; int count=0; while(i<=j){ if(flag){ a[count++]=arr[i++]; flag=false; } else{ a[count++]=arr[j--]; flag=true; } } for(i =0;i<n;i++){ arr[i]=a[i]; }
} }
0
shulabhgillin 5 hours
System.out.println(a[0]);
0
mihirdhabe2 days ago
Easy C++ Solution
void rearrange(long long *arr, int n) { // Your code here vector<int>v; for(int i=0;i<n;i++) { v.push_back(arr[i]); } int i=0; int j=1; while(i<n) { arr[i]=v[v.size()-j]; i+=2; j++; } i=1; j=0; while(i<n) { arr[i]=v[j]; i+=2; j++; } }
0
bhavikkasundra551 week ago
if(n==1)return ; vector<long long>v; long long left=0,right=n-1; int count=0; while(left<=right){ // cout<<arr[right]<<" "; v.push_back(arr[right]); right--; // cout<<arr[left]<<" "; v.push_back(arr[left]); left++; } for(long long i=0;i<n;i++){ arr[i] = v[i]; }
0
rishabh21cse1 week ago
best c++ sol ---------------------
void rearrange(long long *arr, int n) { // Your code here int i=0; int j = n-1; vector<int> v; while(i<=j){ if(i==j){ v.push_back(arr[j]); } v.push_back(arr[j]); v.push_back(arr[i]); i++; j--; } for(int i=0;i<v.size();i++){ arr[i]=v[i]; } }
+1
daniilb2 weeks ago
void rearrange(long long *arr, int n) { // this approach is based on calculating the destination position // for a given element, moving it there, and repeating this // procedure for the just replaced element until all elements // are placed in their required positions. // To track that an element has been moved we change its sign //find mid point that will go to the end int mid = (n-1)/2; for (int i = 0; i < n; ++i) { if (arr[i] > 0) { int i_curr = i; int saved = arr[i_curr]; while (1) { // compute destination of the current element int i_next; if (i_curr == mid) { i_next = n-1; } else if (i_curr < mid) { i_next = 2*i_curr+1; } else { i_next = 2*(n-1-i_curr); } if (arr[i_next] < 0) { // found a loop break; } else { // move the current element to its destination // but save value at the destination beforehand int tmp = arr[i_next]; arr[i_next] = -saved; saved = tmp; i_curr = i_next; } } } } // flip all numbers back to being positive for (int i = 0; i < n; ++i) { arr[i] = -arr[i]; } }
-1
sachinsharma291112 weeks ago
class Solution: ##Complete this function #Function to rearrange the array elements alternately. def rearrange(self,arr, n): ##Your code here max_index=n-1 min_index=0 maximum=arr[n-1]+1 for i in range(n): if (i%2==0): arr[i]=(arr[max_index]%maximum)*maximum+arr[i] max_index=max_index-1 else: arr[i]=(arr[min_index]%maximum)*maximum+arr[i] min_index=min_index+1 for i in range(n): arr[i]=arr[i]//maximum
0
mayank180919992 weeks ago
void rearrange(long long *arr, int n)
{
// Your code here
int i=0;
int j=n-1;
vector<int>nums;
while(i<=j){
if(i==j){
nums.push_back(arr[j]);
}
nums.push_back(arr[j]);
nums.push_back(arr[i]);
i++;
j--;
}
for(int i=0;i<nums.size();i++){
arr[i]=nums[i];
}
}
0
user_990i2 weeks ago
void rearrange(long long *arr, int n) { long long prime=1000000007; //prime*rearranged+original long long high=n-1,low=0; for(int i=0;i<n;i++){ long long l=(arr[low]%prime); long long h=(arr[high]%prime); if(i%2==0){ arr[i]=h*prime+arr[i]; high--; } else{ arr[i]=l*prime+arr[i]; low++; } } for(int i=0;i<n;i++){ arr[i]=arr[i]/prime; } }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 475,
"s": 238,
"text": "Given a sorted array of positive integers. Your task is to rearrange the array elements alternatively i.e first element should be max value, second should be min value, third should be second max, fourth should be second min and so on."
},
{
"code": null,
"e": 486,
"s": 475,
"text": "Example 1:"
},
{
"code": null,
"e": 660,
"s": 486,
"text": "Input:\nN = 6\narr[] = {1,2,3,4,5,6}\nOutput: 6 1 5 2 4 3\nExplanation: Max element = 6, min = 1, \nsecond max = 5, second min = 2, and \nso on... Modified array is : 6 1 5 2 4 3."
},
{
"code": null,
"e": 671,
"s": 660,
"text": "Example 2:"
},
{
"code": null,
"e": 920,
"s": 671,
"text": "Input:\nN = 11\narr[]={10,20,30,40,50,60,70,80,90,100,110}\nOutput:110 10 100 20 90 30 80 40 70 50 60\nExplanation: Max element = 110, min = 10, \nsecond max = 100, second min = 20, and \nso on... Modified array is : \n110 10 100 20 90 30 80 40 70 50 60.\n"
},
{
"code": null,
"e": 1089,
"s": 920,
"text": "Your Task:\nThe task is to complete the function rearrange() which rearranges elements as explained above. Printing of the modified array will be handled by driver code."
},
{
"code": null,
"e": 1153,
"s": 1089,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1199,
"s": 1153,
"text": "Constraints:\n1 <= N <= 106\n1 <= arr[i] <= 107"
},
{
"code": null,
"e": 1201,
"s": 1199,
"text": "0"
},
{
"code": null,
"e": 1224,
"s": 1201,
"text": "prashanth742in 8 hours"
},
{
"code": null,
"e": 1401,
"s": 1224,
"text": "c#:public void rearrange(long[] arr, int n) { //code here var nArr=new long[n]; if(n%2==1) { nArr[n-1]=arr[n/2]; }"
},
{
"code": null,
"e": 1751,
"s": 1401,
"text": " int i=0; int ni=0; while(i<n/2) { nArr[ni]=arr[n-1-i]; nArr[ni+1]=arr[i]; i=i+1; ni=ni+2; } for(int j=0;j<n;j++) { arr[j]=nArr[j]; } } "
},
{
"code": null,
"e": 1753,
"s": 1751,
"text": "0"
},
{
"code": null,
"e": 1775,
"s": 1753,
"text": "shulabhgillin 5 hours"
},
{
"code": null,
"e": 2264,
"s": 1775,
"text": "class Solution{ // temp: input array // n: size of array //Function to rearrange the array elements alternately. public static void rearrange(long arr[], int n){ long a[] =new long[n]; int i=0 , j=n-1; boolean flag=false; int count=0; while(i<=j){ if(flag){ a[count++]=arr[i++]; flag=false; } else{ a[count++]=arr[j--]; flag=true; } } for(i =0;i<n;i++){ arr[i]=a[i]; }"
},
{
"code": null,
"e": 2285,
"s": 2264,
"text": " } } "
},
{
"code": null,
"e": 2287,
"s": 2285,
"text": "0"
},
{
"code": null,
"e": 2309,
"s": 2287,
"text": "shulabhgillin 5 hours"
},
{
"code": null,
"e": 2336,
"s": 2309,
"text": " System.out.println(a[0]);"
},
{
"code": null,
"e": 2338,
"s": 2336,
"text": "0"
},
{
"code": null,
"e": 2359,
"s": 2338,
"text": "mihirdhabe2 days ago"
},
{
"code": null,
"e": 2377,
"s": 2359,
"text": "Easy C++ Solution"
},
{
"code": null,
"e": 2763,
"s": 2377,
"text": "void rearrange(long long *arr, int n) { // Your code here vector<int>v; for(int i=0;i<n;i++) { v.push_back(arr[i]); } int i=0; int j=1; while(i<n) { arr[i]=v[v.size()-j]; i+=2; j++; } i=1; j=0; while(i<n) { arr[i]=v[j]; i+=2; j++; } }"
},
{
"code": null,
"e": 2765,
"s": 2763,
"text": "0"
},
{
"code": null,
"e": 2792,
"s": 2765,
"text": "bhavikkasundra551 week ago"
},
{
"code": null,
"e": 3119,
"s": 2792,
"text": "if(n==1)return ; vector<long long>v; long long left=0,right=n-1; int count=0; while(left<=right){ // cout<<arr[right]<<\" \"; v.push_back(arr[right]); right--; // cout<<arr[left]<<\" \"; v.push_back(arr[left]); left++; } for(long long i=0;i<n;i++){ arr[i] = v[i]; }"
},
{
"code": null,
"e": 3121,
"s": 3119,
"text": "0"
},
{
"code": null,
"e": 3144,
"s": 3121,
"text": "rishabh21cse1 week ago"
},
{
"code": null,
"e": 3179,
"s": 3144,
"text": "best c++ sol ---------------------"
},
{
"code": null,
"e": 3535,
"s": 3179,
"text": " void rearrange(long long *arr, int n) { // Your code here int i=0; int j = n-1; vector<int> v; while(i<=j){ if(i==j){ v.push_back(arr[j]); } v.push_back(arr[j]); v.push_back(arr[i]); i++; j--; } for(int i=0;i<v.size();i++){ arr[i]=v[i]; } }"
},
{
"code": null,
"e": 3538,
"s": 3535,
"text": "+1"
},
{
"code": null,
"e": 3557,
"s": 3538,
"text": "daniilb2 weeks ago"
},
{
"code": null,
"e": 5097,
"s": 3557,
"text": " void rearrange(long long *arr, int n) { // this approach is based on calculating the destination position // for a given element, moving it there, and repeating this // procedure for the just replaced element until all elements // are placed in their required positions. // To track that an element has been moved we change its sign //find mid point that will go to the end int mid = (n-1)/2; for (int i = 0; i < n; ++i) { if (arr[i] > 0) { int i_curr = i; int saved = arr[i_curr]; while (1) { // compute destination of the current element int i_next; if (i_curr == mid) { i_next = n-1; } else if (i_curr < mid) { i_next = 2*i_curr+1; } else { i_next = 2*(n-1-i_curr); } if (arr[i_next] < 0) { // found a loop break; } else { // move the current element to its destination // but save value at the destination beforehand int tmp = arr[i_next]; arr[i_next] = -saved; saved = tmp; i_curr = i_next; } } } } // flip all numbers back to being positive for (int i = 0; i < n; ++i) { arr[i] = -arr[i]; } }"
},
{
"code": null,
"e": 5100,
"s": 5097,
"text": "-1"
},
{
"code": null,
"e": 5129,
"s": 5100,
"text": "sachinsharma291112 weeks ago"
},
{
"code": null,
"e": 5663,
"s": 5129,
"text": "class Solution: ##Complete this function #Function to rearrange the array elements alternately. def rearrange(self,arr, n): ##Your code here max_index=n-1 min_index=0 maximum=arr[n-1]+1 for i in range(n): if (i%2==0): arr[i]=(arr[max_index]%maximum)*maximum+arr[i] max_index=max_index-1 else: arr[i]=(arr[min_index]%maximum)*maximum+arr[i] min_index=min_index+1 for i in range(n): arr[i]=arr[i]//maximum"
},
{
"code": null,
"e": 5665,
"s": 5663,
"text": "0"
},
{
"code": null,
"e": 5691,
"s": 5665,
"text": "mayank180919992 weeks ago"
},
{
"code": null,
"e": 6086,
"s": 5691,
"text": " void rearrange(long long *arr, int n) \n { \n \t\n \t// Your code here\n \tint i=0;\n \tint j=n-1;\n \tvector<int>nums;\n \twhile(i<=j){\n \t if(i==j){\n \t nums.push_back(arr[j]);\n \t }\n \t nums.push_back(arr[j]);\n \t nums.push_back(arr[i]);\n \t i++;\n \t j--;\n \t}\n \tfor(int i=0;i<nums.size();i++){\n \t arr[i]=nums[i];\n \t}\n \t \n }"
},
{
"code": null,
"e": 6088,
"s": 6086,
"text": "0"
},
{
"code": null,
"e": 6109,
"s": 6088,
"text": "user_990i2 weeks ago"
},
{
"code": null,
"e": 6672,
"s": 6109,
"text": "void rearrange(long long *arr, int n) { long long prime=1000000007; //prime*rearranged+original long long high=n-1,low=0; for(int i=0;i<n;i++){ long long l=(arr[low]%prime); long long h=(arr[high]%prime); if(i%2==0){ arr[i]=h*prime+arr[i]; high--; } else{ arr[i]=l*prime+arr[i]; low++; } } for(int i=0;i<n;i++){ arr[i]=arr[i]/prime; } }};"
},
{
"code": null,
"e": 6818,
"s": 6672,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6854,
"s": 6818,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6864,
"s": 6854,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6874,
"s": 6864,
"text": "\nContest\n"
},
{
"code": null,
"e": 6937,
"s": 6874,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7085,
"s": 6937,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 7293,
"s": 7085,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 7399,
"s": 7293,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
JDBC - Stored Procedure | We have learnt how to use Stored Procedures in JDBC while discussing the JDBC - Statements chapter. This chapter is similar to that section, but it would give you additional information about JDBC SQL escape syntax.
Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object, which would be used to execute a call to a database stored procedure.
Suppose, you need to execute the following Oracle stored procedure β
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;
NOTE β Above stored procedure has been written for Oracle, but we are working with MySQL database so, let us write same stored procedure for MySQL as follows to create it in EMP database.
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER ;
Three types of parameters exist β IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three.
Here are the definitions of each β
The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a CallableStatement object based on the preceding stored procedure β
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
The String variable SQL represents the stored procedure, with parameter placeholders.
Using CallableStatement objects is much like using PreparedStatement objects. You must bind values to all the parameters before executing the statement, or you will receive an SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are binding.
When you use OUT and INOUT parameters, you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the JDBC data type to the data type the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type.
Just as you close other Statement object, for the same reason you should also close the CallableStatement object.
A simple call to the close() method will do the job. If you close the Connection object first, it will close the CallableStatement object as well. However, you should always explicitly close the CallableStatement object to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
cstmt.close();
}
studyWe have studied more details in the Callable - Example Code.
The escape syntax gives you the flexibility to use database specific features unavailable to you by using standard JDBC methods and properties.
The general SQL escape syntax format is as follows β
{keyword 'parameters'}
Here are the following escape sequences, which you would find very useful while performing the JDBC programming β
They help identify date, time, and timestamp literals. As you know, no two DBMSs represent time and date the same way. This escape syntax tells the driver to render the date or time in the target database's format. For Example β
{d 'yyyy-mm-dd'}
Where yyyy = year, mm = month; dd = date. Using this syntax {d '2009-09-03'} is March 9, 2009.
Here is a simple example showing how to INSERT date in a table β
//Create a Statement object
stmt = conn.createStatement();
//Insert data ==> ID, First Name, Last Name, DOB
String sql="INSERT INTO STUDENTS VALUES" +
"(100,'Zara','Ali', {d '2001-12-16'})";
stmt.executeUpdate(sql);
Similarly, you can use one of the following two syntaxes, either t or ts β
{t 'hh:mm:ss'}
Where hh = hour; mm = minute; ss = second. Using this syntax {t '13:30:29'} is 1:30:29 PM.
{ts 'yyyy-mm-dd hh:mm:ss'}
This is combined syntax of the above two syntax for 'd' and 't' to represent timestamp.
This keyword identifies the escape character used in LIKE clauses. Useful when using the SQL wildcard %, which matches zero or more characters. For example β
String sql = "SELECT symbol FROM MathSymbols
WHERE symbol LIKE '\%' {escape '\'}";
stmt.execute(sql);
If you use the backslash character (\) as the escape character, you also have to use two backslash characters in your Java String literal, because the backslash is also a Java escape character.
This keyword represents scalar functions used in a DBMS. For example, you can use SQL function length to get the length of a string β
{fn length('Hello World')}
This returns 11, the length of the character string 'Hello World'.
This keyword is used to call the stored procedures. For example, for a stored procedure requiring an IN parameter, use the following syntax β
{call my_procedure(?)};
For a stored procedure requiring an IN parameter and returning an OUT parameter, use the following syntax β
{? = call my_procedure(?)};
This keyword is used to signify outer joins. The syntax is as follows β
{oj outer-join}
Where outer-join = table {LEFT|RIGHT|FULL} OUTERJOIN {table | outer-join} on search-condition. For example β
String sql = "SELECT Employees
FROM {oj ThisTable RIGHT
OUTER JOIN ThatTable on id = '100'}";
stmt.execute(sql);
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2378,
"s": 2162,
"text": "We have learnt how to use Stored Procedures in JDBC while discussing the JDBC - Statements chapter. This chapter is similar to that section, but it would give you additional information about JDBC SQL escape syntax."
},
{
"code": null,
"e": 2575,
"s": 2378,
"text": "Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object, which would be used to execute a call to a database stored procedure."
},
{
"code": null,
"e": 2644,
"s": 2575,
"text": "Suppose, you need to execute the following Oracle stored procedure β"
},
{
"code": null,
"e": 2814,
"s": 2644,
"text": "CREATE OR REPLACE PROCEDURE getEmpName \n (EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS\nBEGIN\n SELECT first INTO EMP_FIRST\n FROM Employees\n WHERE ID = EMP_ID;\nEND;"
},
{
"code": null,
"e": 3002,
"s": 2814,
"text": "NOTE β Above stored procedure has been written for Oracle, but we are working with MySQL database so, let us write same stored procedure for MySQL as follows to create it in EMP database."
},
{
"code": null,
"e": 3244,
"s": 3002,
"text": "DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$\nCREATE PROCEDURE `EMP`.`getEmpName` \n (IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))\nBEGIN\n SELECT first INTO EMP_FIRST\n FROM Employees\n WHERE ID = EMP_ID;\nEND $$\n\nDELIMITER ;"
},
{
"code": null,
"e": 3407,
"s": 3244,
"text": "Three types of parameters exist β IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all the three."
},
{
"code": null,
"e": 3442,
"s": 3407,
"text": "Here are the definitions of each β"
},
{
"code": null,
"e": 3609,
"s": 3442,
"text": "The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a CallableStatement object based on the preceding stored procedure β"
},
{
"code": null,
"e": 3794,
"s": 3609,
"text": "CallableStatement cstmt = null;\ntry {\n String SQL = \"{call getEmpName (?, ?)}\";\n cstmt = conn.prepareCall (SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n . . .\n}"
},
{
"code": null,
"e": 3880,
"s": 3794,
"text": "The String variable SQL represents the stored procedure, with parameter placeholders."
},
{
"code": null,
"e": 4070,
"s": 3880,
"text": "Using CallableStatement objects is much like using PreparedStatement objects. You must bind values to all the parameters before executing the statement, or you will receive an SQLException."
},
{
"code": null,
"e": 4261,
"s": 4070,
"text": "If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are binding."
},
{
"code": null,
"e": 4500,
"s": 4261,
"text": "When you use OUT and INOUT parameters, you must employ an additional CallableStatement method, registerOutParameter(). The registerOutParameter() method binds the JDBC data type to the data type the stored procedure is expected to return."
},
{
"code": null,
"e": 4692,
"s": 4500,
"text": "Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type."
},
{
"code": null,
"e": 4806,
"s": 4692,
"text": "Just as you close other Statement object, for the same reason you should also close the CallableStatement object."
},
{
"code": null,
"e": 5052,
"s": 4806,
"text": "A simple call to the close() method will do the job. If you close the Connection object first, it will close the CallableStatement object as well. However, you should always explicitly close the CallableStatement object to ensure proper cleanup."
},
{
"code": null,
"e": 5246,
"s": 5052,
"text": "CallableStatement cstmt = null;\ntry {\n String SQL = \"{call getEmpName (?, ?)}\";\n cstmt = conn.prepareCall (SQL);\n . . .\n}\ncatch (SQLException e) {\n . . .\n}\nfinally {\n cstmt.close();\n}"
},
{
"code": null,
"e": 5312,
"s": 5246,
"text": "studyWe have studied more details in the Callable - Example Code."
},
{
"code": null,
"e": 5456,
"s": 5312,
"text": "The escape syntax gives you the flexibility to use database specific features unavailable to you by using standard JDBC methods and properties."
},
{
"code": null,
"e": 5509,
"s": 5456,
"text": "The general SQL escape syntax format is as follows β"
},
{
"code": null,
"e": 5533,
"s": 5509,
"text": "{keyword 'parameters'}\n"
},
{
"code": null,
"e": 5647,
"s": 5533,
"text": "Here are the following escape sequences, which you would find very useful while performing the JDBC programming β"
},
{
"code": null,
"e": 5877,
"s": 5647,
"text": "They help identify date, time, and timestamp literals. As you know, no two DBMSs represent time and date the same way. This escape syntax tells the driver to render the date or time in the target database's format. For Example β"
},
{
"code": null,
"e": 5894,
"s": 5877,
"text": "{d 'yyyy-mm-dd'}"
},
{
"code": null,
"e": 5989,
"s": 5894,
"text": "Where yyyy = year, mm = month; dd = date. Using this syntax {d '2009-09-03'} is March 9, 2009."
},
{
"code": null,
"e": 6054,
"s": 5989,
"text": "Here is a simple example showing how to INSERT date in a table β"
},
{
"code": null,
"e": 6284,
"s": 6054,
"text": "//Create a Statement object\nstmt = conn.createStatement();\n//Insert data ==> ID, First Name, Last Name, DOB\nString sql=\"INSERT INTO STUDENTS VALUES\" +\n \"(100,'Zara','Ali', {d '2001-12-16'})\";\n\nstmt.executeUpdate(sql);"
},
{
"code": null,
"e": 6359,
"s": 6284,
"text": "Similarly, you can use one of the following two syntaxes, either t or ts β"
},
{
"code": null,
"e": 6375,
"s": 6359,
"text": "{t 'hh:mm:ss'}\n"
},
{
"code": null,
"e": 6466,
"s": 6375,
"text": "Where hh = hour; mm = minute; ss = second. Using this syntax {t '13:30:29'} is 1:30:29 PM."
},
{
"code": null,
"e": 6494,
"s": 6466,
"text": "{ts 'yyyy-mm-dd hh:mm:ss'}\n"
},
{
"code": null,
"e": 6582,
"s": 6494,
"text": "This is combined syntax of the above two syntax for 'd' and 't' to represent timestamp."
},
{
"code": null,
"e": 6740,
"s": 6582,
"text": "This keyword identifies the escape character used in LIKE clauses. Useful when using the SQL wildcard %, which matches zero or more characters. For example β"
},
{
"code": null,
"e": 6856,
"s": 6740,
"text": "String sql = \"SELECT symbol FROM MathSymbols\n WHERE symbol LIKE '\\%' {escape '\\'}\";\nstmt.execute(sql);"
},
{
"code": null,
"e": 7050,
"s": 6856,
"text": "If you use the backslash character (\\) as the escape character, you also have to use two backslash characters in your Java String literal, because the backslash is also a Java escape character."
},
{
"code": null,
"e": 7184,
"s": 7050,
"text": "This keyword represents scalar functions used in a DBMS. For example, you can use SQL function length to get the length of a string β"
},
{
"code": null,
"e": 7211,
"s": 7184,
"text": "{fn length('Hello World')}"
},
{
"code": null,
"e": 7278,
"s": 7211,
"text": "This returns 11, the length of the character string 'Hello World'."
},
{
"code": null,
"e": 7420,
"s": 7278,
"text": "This keyword is used to call the stored procedures. For example, for a stored procedure requiring an IN parameter, use the following syntax β"
},
{
"code": null,
"e": 7444,
"s": 7420,
"text": "{call my_procedure(?)};"
},
{
"code": null,
"e": 7552,
"s": 7444,
"text": "For a stored procedure requiring an IN parameter and returning an OUT parameter, use the following syntax β"
},
{
"code": null,
"e": 7581,
"s": 7552,
"text": "{? = call my_procedure(?)};\n"
},
{
"code": null,
"e": 7653,
"s": 7581,
"text": "This keyword is used to signify outer joins. The syntax is as follows β"
},
{
"code": null,
"e": 7670,
"s": 7653,
"text": "{oj outer-join}\n"
},
{
"code": null,
"e": 7779,
"s": 7670,
"text": "Where outer-join = table {LEFT|RIGHT|FULL} OUTERJOIN {table | outer-join} on search-condition. For example β"
},
{
"code": null,
"e": 7921,
"s": 7779,
"text": "String sql = \"SELECT Employees \n FROM {oj ThisTable RIGHT\n OUTER JOIN ThatTable on id = '100'}\";\nstmt.execute(sql);"
},
{
"code": null,
"e": 7954,
"s": 7921,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7970,
"s": 7954,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8003,
"s": 7970,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8019,
"s": 8003,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8054,
"s": 8019,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8068,
"s": 8054,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8102,
"s": 8068,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8116,
"s": 8102,
"text": " Tushar Kale"
},
{
"code": null,
"e": 8153,
"s": 8116,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8168,
"s": 8153,
"text": " Monica Mittal"
},
{
"code": null,
"e": 8201,
"s": 8168,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8220,
"s": 8201,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8227,
"s": 8220,
"text": " Print"
},
{
"code": null,
"e": 8238,
"s": 8227,
"text": " Add Notes"
}
] |
Format date with DateFormat.MEDIUM in Java | DateFormat.MEDIUM is a constant for medium style pattern.
Firstly, we will create date object β
Date dt = new Date();
DateFormat dateFormat;
Let us format date for different locale with DateFormat.MEDIUM β
// CHINESE
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINESE);
// CANADA
dateFormat = DateFormat.getDateInstance(DateFormat. MEDIUM, Locale.CANADA);
The following is an example β
Live Demo
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class Demo {
public static void main(String args[]) {
Date dt = new Date();
DateFormat dateFormat;
// Date Format MEDIUM constant
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.FRENCH);
System.out.println("Locale FRENCH = " + dateFormat.format(dt));
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMANY);
System.out.println("Locale GERMANY = " + dateFormat.format(dt));
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINESE);
System.out.println("Locale CHINESE = " + dateFormat.format(dt));
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CANADA);
System.out.println("Locale CANADA = " + dateFormat.format(dt));
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ITALY);
System.out.println("Locale ITALY = " + dateFormat.format(dt));
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.TAIWAN);
System.out.println("Locale TAIWAN = " + dateFormat.format(dt));
}
}
Locale FRENCH = 22 nov. 2018
Locale GERMANY = 22.11.2018
Locale CHINESE = 2018-11-22
Locale CANADA = 22-Nov-2018
Locale ITALY = 22-nov-2018
Locale TAIWAN = 2018/11/22 | [
{
"code": null,
"e": 1120,
"s": 1062,
"text": "DateFormat.MEDIUM is a constant for medium style pattern."
},
{
"code": null,
"e": 1158,
"s": 1120,
"text": "Firstly, we will create date object β"
},
{
"code": null,
"e": 1203,
"s": 1158,
"text": "Date dt = new Date();\nDateFormat dateFormat;"
},
{
"code": null,
"e": 1268,
"s": 1203,
"text": "Let us format date for different locale with DateFormat.MEDIUM β"
},
{
"code": null,
"e": 1441,
"s": 1268,
"text": "// CHINESE\ndateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINESE);\n// CANADA\ndateFormat = DateFormat.getDateInstance(DateFormat. MEDIUM, Locale.CANADA);"
},
{
"code": null,
"e": 1471,
"s": 1441,
"text": "The following is an example β"
},
{
"code": null,
"e": 1482,
"s": 1471,
"text": " Live Demo"
},
{
"code": null,
"e": 2632,
"s": 1482,
"text": "import java.text.DateFormat;\nimport java.util.Date;\nimport java.util.Locale;\npublic class Demo {\n public static void main(String args[]) {\n Date dt = new Date();\n DateFormat dateFormat;\n // Date Format MEDIUM constant\n dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.FRENCH);\n System.out.println(\"Locale FRENCH = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMANY);\n System.out.println(\"Locale GERMANY = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINESE);\n System.out.println(\"Locale CHINESE = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CANADA);\n System.out.println(\"Locale CANADA = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ITALY);\n System.out.println(\"Locale ITALY = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.TAIWAN);\n System.out.println(\"Locale TAIWAN = \" + dateFormat.format(dt));\n }\n}"
},
{
"code": null,
"e": 2799,
"s": 2632,
"text": "Locale FRENCH = 22 nov. 2018\nLocale GERMANY = 22.11.2018\nLocale CHINESE = 2018-11-22\nLocale CANADA = 22-Nov-2018\nLocale ITALY = 22-nov-2018\nLocale TAIWAN = 2018/11/22"
}
] |
Replace a specific duplicate record with a new value in MySQL | Let us first create a table β
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name varchar(50)
);
Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable;
This will produce the following output β
+----+--------+
| Id | Name |
+----+--------+
| 1 | Chris |
| 2 | Robert |
| 3 | Chris |
| 4 | David |
| 5 | Mike |
+----+--------+
5 rows in set (0.00 sec)
Here is the query to replace a specific duplicate record i.e. the name βChrisβ here with a new name β
mysql> update DemoTable set Name=replace(Name,'Chris','Adam Smith');
Query OK, 2 rows affected (0.17 sec)
Rows matched: 5 Changed: 2 Warnings: 0
Let us check the table records once again β
mysql> select *from DemoTable;
This will produce the following output β
+----+------------+
| Id | Name |
+----+------------+
| 1 | Adam Smith |
| 2 | Robert |
| 3 | Adam Smith |
| 4 | David |
| 5 | Mike |
+----+------------+
5 rows in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table β"
},
{
"code": null,
"e": 1231,
"s": 1092,
"text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Name varchar(50)\n);\nQuery OK, 0 rows affected (0.62 sec)"
},
{
"code": null,
"e": 1287,
"s": 1231,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1727,
"s": 1287,
"text": "mysql> insert into DemoTable(Name) values('Chris');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable(Name) values('Robert');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable(Name) values('Chris');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable(Name) values('David');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable(Name) values('Mike');\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1787,
"s": 1727,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1818,
"s": 1787,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1859,
"s": 1818,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2028,
"s": 1859,
"text": "+----+--------+\n| Id | Name |\n+----+--------+\n| 1 | Chris |\n| 2 | Robert |\n| 3 | Chris |\n| 4 | David |\n| 5 | Mike |\n+----+--------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2130,
"s": 2028,
"text": "Here is the query to replace a specific duplicate record i.e. the name βChrisβ here with a new name β"
},
{
"code": null,
"e": 2275,
"s": 2130,
"text": "mysql> update DemoTable set Name=replace(Name,'Chris','Adam Smith');\nQuery OK, 2 rows affected (0.17 sec)\nRows matched: 5 Changed: 2 Warnings: 0"
},
{
"code": null,
"e": 2319,
"s": 2275,
"text": "Let us check the table records once again β"
},
{
"code": null,
"e": 2350,
"s": 2319,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2391,
"s": 2350,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2596,
"s": 2391,
"text": "+----+------------+\n| Id | Name |\n+----+------------+\n| 1 | Adam Smith |\n| 2 | Robert |\n| 3 | Adam Smith |\n| 4 | David |\n| 5 | Mike |\n+----+------------+\n5 rows in set (0.00 sec)"
}
] |
ReactJS - Nested Components | As we learned earlier, React component is the building block of a React application. A React component is made up of the multiple individual components. React allows multiple components to be combined to create larger components. Also, React components can be nested to any arbitrary level. Let us see how React components can be composed in this chapter.
Let us create a component, FormattedMoney to format the amount to two decimal places before rendering.
Open our expense-manager application in your favorite editor.
Next, Create a FormattedMoney.js file in the src/components folder and, Import React library.
import React from 'react';
Next, create a class, FormattedMoney by extending React.Component.
class FormattedMoney extends React.Component {
}
Next, introduce construction function with argument props as shown below β
constructor(props) {
super(props);
}
Next, create a method format to format the amount.
format(amount) {
return parseFloat(amount).toFixed(2)
}
Next, create a method render to emit the formatted amount.
render() {
return (
<span>{this.format(this.props.value)}</span>
);
}
Here, we have used the format method by passing value attribute through this.props.
Next, specify the component as default export class.
export default FormattedMoney;
Now, we have successfully created our FormattedMoney React component.
import React from 'react';
class FormattedMoney extends React.Component {
constructor(props) {
super(props)
}
format(amount) {
return parseFloat(amount).toFixed(2)
}
render() {
return (
<span>{this.format(this.props.value)}</span>
);
}
}
export default FormattedMoney;
Let us create another component, FormattedDate to format and show the date and time of the expense.
Open our expense-manager application in your favorite editor.
Next, create a file, FormattedDate.js in the src/components folder.
Next, import React library.
import React from 'react';
Next, create a class by extending React.Component.
class FormattedDate extends React.Component {
}
Next, introduce construction function with argument props as shown below β
constructor(props) {
super(props);
}
Next, create a method format to format the date.
format(val) {
const months = ["JAN", "FEB", "MAR","APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
let parsed_date = new Date(Date.parse(val));
let formatted_date = parsed_date.getDate() +
"-" + months[parsed_date.getMonth()] +
"-" + parsed_date.getFullYear()
return formatted_date;
}
Create a method render to emit the formatted date.
render() { return ( <span>{this.format(this.props.value)}</span> ); }
Here, we have used the format method by passing value attribute through this.props.
Next, specify the component as default export class.
export default FormattedDate;
Now, we have successfully created our FormattedDate React component. The complete code is as follows β
import React from 'react';
class FormattedDate extends React.Component {
constructor(props) {
super(props)
}
format(val) {
const months = ["JAN", "FEB", "MAR","APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
let parsed_date = new Date(Date.parse(val));
let formatted_date = parsed_date.getDate() +
"-" + months[parsed_date.getMonth()] +
"-" + parsed_date.getFullYear()
return formatted_date;
}
render() {
return (
<span>{this.format(this.props.value)}</span>
);
}
}
export default FormattedDate;
20 Lectures
1.5 hours
Anadi Sharma
60 Lectures
4.5 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
63 Lectures
9.5 hours
TELCOMA Global
17 Lectures
2 hours
Mohd Raqif Warsi
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2389,
"s": 2033,
"text": "As we learned earlier, React component is the building block of a React application. A React component is made up of the multiple individual components. React allows multiple components to be combined to create larger components. Also, React components can be nested to any arbitrary level. Let us see how React components can be composed in this chapter."
},
{
"code": null,
"e": 2492,
"s": 2389,
"text": "Let us create a component, FormattedMoney to format the amount to two decimal places before rendering."
},
{
"code": null,
"e": 2554,
"s": 2492,
"text": "Open our expense-manager application in your favorite editor."
},
{
"code": null,
"e": 2648,
"s": 2554,
"text": "Next, Create a FormattedMoney.js file in the src/components folder and, Import React library."
},
{
"code": null,
"e": 2676,
"s": 2648,
"text": "import React from 'react';\n"
},
{
"code": null,
"e": 2743,
"s": 2676,
"text": "Next, create a class, FormattedMoney by extending React.Component."
},
{
"code": null,
"e": 2794,
"s": 2743,
"text": "class FormattedMoney extends React.Component { \n}\n"
},
{
"code": null,
"e": 2869,
"s": 2794,
"text": "Next, introduce construction function with argument props as shown below β"
},
{
"code": null,
"e": 2912,
"s": 2869,
"text": "constructor(props) { \n super(props); \n}\n"
},
{
"code": null,
"e": 2963,
"s": 2912,
"text": "Next, create a method format to format the amount."
},
{
"code": null,
"e": 3025,
"s": 2963,
"text": "format(amount) { \n return parseFloat(amount).toFixed(2) \n}\n"
},
{
"code": null,
"e": 3084,
"s": 3025,
"text": "Next, create a method render to emit the formatted amount."
},
{
"code": null,
"e": 3169,
"s": 3084,
"text": "render() {\n return (\n <span>{this.format(this.props.value)}</span> \n ); \n}\n"
},
{
"code": null,
"e": 3253,
"s": 3169,
"text": "Here, we have used the format method by passing value attribute through this.props."
},
{
"code": null,
"e": 3306,
"s": 3253,
"text": "Next, specify the component as default export class."
},
{
"code": null,
"e": 3338,
"s": 3306,
"text": "export default FormattedMoney;\n"
},
{
"code": null,
"e": 3408,
"s": 3338,
"text": "Now, we have successfully created our FormattedMoney React component."
},
{
"code": null,
"e": 3729,
"s": 3408,
"text": "import React from 'react';\n\nclass FormattedMoney extends React.Component {\n constructor(props) {\n super(props)\n }\n format(amount) {\n return parseFloat(amount).toFixed(2)\n }\n render() {\n return (\n <span>{this.format(this.props.value)}</span>\n );\n }\n}\nexport default FormattedMoney;"
},
{
"code": null,
"e": 3829,
"s": 3729,
"text": "Let us create another component, FormattedDate to format and show the date and time of the expense."
},
{
"code": null,
"e": 3891,
"s": 3829,
"text": "Open our expense-manager application in your favorite editor."
},
{
"code": null,
"e": 3959,
"s": 3891,
"text": "Next, create a file, FormattedDate.js in the src/components folder."
},
{
"code": null,
"e": 3987,
"s": 3959,
"text": "Next, import React library."
},
{
"code": null,
"e": 4015,
"s": 3987,
"text": "import React from 'react';\n"
},
{
"code": null,
"e": 4066,
"s": 4015,
"text": "Next, create a class by extending React.Component."
},
{
"code": null,
"e": 4116,
"s": 4066,
"text": "class FormattedDate extends React.Component { \n}\n"
},
{
"code": null,
"e": 4191,
"s": 4116,
"text": "Next, introduce construction function with argument props as shown below β"
},
{
"code": null,
"e": 4234,
"s": 4191,
"text": "constructor(props) { \n super(props); \n}\n"
},
{
"code": null,
"e": 4283,
"s": 4234,
"text": "Next, create a method format to format the date."
},
{
"code": null,
"e": 4609,
"s": 4283,
"text": "format(val) {\n const months = [\"JAN\", \"FEB\", \"MAR\",\"APR\", \"MAY\", \"JUN\", \"JUL\", \"AUG\", \"SEP\", \"OCT\", \"NOV\", \"DEC\"];\n let parsed_date = new Date(Date.parse(val));\n let formatted_date = parsed_date.getDate() + \n \"-\" + months[parsed_date.getMonth()] + \n \"-\" + parsed_date.getFullYear()\n return formatted_date;\n}"
},
{
"code": null,
"e": 4660,
"s": 4609,
"text": "Create a method render to emit the formatted date."
},
{
"code": null,
"e": 4731,
"s": 4660,
"text": "render() { return ( <span>{this.format(this.props.value)}</span> ); }\n"
},
{
"code": null,
"e": 4815,
"s": 4731,
"text": "Here, we have used the format method by passing value attribute through this.props."
},
{
"code": null,
"e": 4868,
"s": 4815,
"text": "Next, specify the component as default export class."
},
{
"code": null,
"e": 4899,
"s": 4868,
"text": "export default FormattedDate;\n"
},
{
"code": null,
"e": 5002,
"s": 4899,
"text": "Now, we have successfully created our FormattedDate React component. The complete code is as follows β"
},
{
"code": null,
"e": 5602,
"s": 5002,
"text": "import React from 'react';\nclass FormattedDate extends React.Component {\n constructor(props) {\n super(props)\n }\n format(val) {\n const months = [\"JAN\", \"FEB\", \"MAR\",\"APR\", \"MAY\", \"JUN\", \"JUL\", \"AUG\", \"SEP\", \"OCT\", \"NOV\", \"DEC\"];\n let parsed_date = new Date(Date.parse(val));\n let formatted_date = parsed_date.getDate() + \n \"-\" + months[parsed_date.getMonth()] + \n \"-\" + parsed_date.getFullYear()\n return formatted_date;\n }\n render() {\n return (\n <span>{this.format(this.props.value)}</span>\n );\n }\n}\nexport default FormattedDate;"
},
{
"code": null,
"e": 5637,
"s": 5602,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5651,
"s": 5637,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5686,
"s": 5651,
"text": "\n 60 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5706,
"s": 5686,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5741,
"s": 5706,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5764,
"s": 5741,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 5799,
"s": 5764,
"text": "\n 63 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 5815,
"s": 5799,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5848,
"s": 5815,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5866,
"s": 5848,
"text": " Mohd Raqif Warsi"
},
{
"code": null,
"e": 5873,
"s": 5866,
"text": " Print"
},
{
"code": null,
"e": 5884,
"s": 5873,
"text": " Add Notes"
}
] |
Ruby on Rails - File Uploading | You may have a requirement in which you want your site visitors to upload a file on your server. Rails makes it very easy to handle this requirement. Now we will proceed with a simple and small Rails project.
As usual, let's start off with a new Rails application called testfile. Let's create the basic structure of the application by using simple rails command.
tp> rails new testfile
Before starting application development, we should install gem files as shown below β
gem install carrierwave
gem install bootstrap-sass
Open up your gemfile and add the following two gems at the bottom as shown in the following image β
After adding gems in the gem file, we need to run the following command on the console β
bundle install
We need to create a model with two strings as name and attachment as shown below β
rails g model Resume name:string attachment:string
We need to create the database migration as shown below β
rake db:migrate
We need to generate the controller as shown below β
rails g controller Resumes index new create destroy
Great! Now we have the basic structure set up. Now we need to create an uploader. An Uploader came from carrierwave gem and it tells to carrierwave how to handle the files. In short, it contained all file processing functionalities. Run the command to create an uploader as shown below
rails g uploader attachment
Now open the resume model and call the uploader as shown below. Resume model has placed at app/models/resume.rb β
class Resume < ActiveRecord::Base
mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model.
validates :name, presence: true # Make sure the owner's name is present.
end
Before working on controller, we need to modify our config/routes.db as shown below β
CarrierWaveExample::Application.routes.draw do
resources :resumes, only: [:index, :new, :create, :destroy]
root "resumes#index"
end
Lets us edit the controller as shown below.
class ResumesController < ApplicationController
def index
@resumes = Resume.all
end
def new
@resume = Resume.new
end
def create
@resume = Resume.new(resume_params)
if @resume.save
redirect_to resumes_path, notice: "The resume #{@resume.name} has been uploaded."
else
render "new"
end
end
def destroy
@resume = Resume.find(params[:id])
@resume.destroy
redirect_to resumes_path, notice: "The resume #{@resume.name} has been deleted."
end
private
def resume_params
params.require(:resume).permit(:name, :attachment)
end
end
Let's add bootstrap implementation in css file.css file could be in app/assets/stylesheets/resumes.css.scss
@import "bootstrap";
Now open up app/views/layouts/application.html.erb and add codes as shown below β
<!DOCTYPE html>
<html>
<head>
<title>Tutorialspoint</title>
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
</head>
<body>
<div class = "container" style = "padding-top:20px;">
<%= yield %>
</div>
</body>
</html>
Now we need to set up index views as shown below β
<% if !flash[:notice].blank? %>
<div class = "alert alert-info">
<%= flash[:notice] %>
</div>
<% end %>
<br />
<%= link_to "New Resume", new_resume_path, class: "btn btn-primary" %>
<br />
<br />
<table class = "table table-bordered table-striped">
<thead>.
<tr>
<th>Name</th>
<th>Download Link</th>
<th> </th>
</tr>
</thead>
<tbody>
<% @resumes.each do |resume| %>
<tr>
<td><%= resume.name %></td>
<td><%= link_to "Download Resume", resume.attachment_url %></td>
<td><%= button_to "Delete", resume, method: :delete, class: "btn btn-danger", confirm: "Are you sure that you wish to delete #{resume.name}?" %></td>
</tr>
<% end %>
</tbody>
</table>
Now, lets edit new.html.erb and add our form code.
<% if [email protected]? %>
<div class = "alert alert-error">
<ul>
<% @resume.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class = "well">
<%= form_for @resume, html: { multipart: true } do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :attachment %>
<%= f.file_field :attachment %>
<%= f.submit "Save", class: "btn btn-primary" %>
<% end %>
</div>
Now start the server and visit http://localhost:3000. It will produce a screen similar to as follows β
One last thing we need to do is filter the list of allowed filetypes. For that we need add simple code as shown below at app/uploaders/attachment_uploader.rb
class AttachmentUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(pdf doc htm html docx)
end
end
Now start the server and visit http://localhost:3000. Now input a wrong format; it will generate a wrong message as shown below β
For a complete detail on File object, you need to go through the Ruby Reference Manual.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2312,
"s": 2103,
"text": "You may have a requirement in which you want your site visitors to upload a file on your server. Rails makes it very easy to handle this requirement. Now we will proceed with a simple and small Rails project."
},
{
"code": null,
"e": 2467,
"s": 2312,
"text": "As usual, let's start off with a new Rails application called testfile. Let's create the basic structure of the application by using simple rails command."
},
{
"code": null,
"e": 2491,
"s": 2467,
"text": "tp> rails new testfile\n"
},
{
"code": null,
"e": 2577,
"s": 2491,
"text": "Before starting application development, we should install gem files as shown below β"
},
{
"code": null,
"e": 2629,
"s": 2577,
"text": "gem install carrierwave\ngem install bootstrap-sass\n"
},
{
"code": null,
"e": 2729,
"s": 2629,
"text": "Open up your gemfile and add the following two gems at the bottom as shown in the following image β"
},
{
"code": null,
"e": 2818,
"s": 2729,
"text": "After adding gems in the gem file, we need to run the following command on the console β"
},
{
"code": null,
"e": 2834,
"s": 2818,
"text": "bundle install\n"
},
{
"code": null,
"e": 2917,
"s": 2834,
"text": "We need to create a model with two strings as name and attachment as shown below β"
},
{
"code": null,
"e": 2969,
"s": 2917,
"text": "rails g model Resume name:string attachment:string\n"
},
{
"code": null,
"e": 3027,
"s": 2969,
"text": "We need to create the database migration as shown below β"
},
{
"code": null,
"e": 3044,
"s": 3027,
"text": "rake db:migrate\n"
},
{
"code": null,
"e": 3096,
"s": 3044,
"text": "We need to generate the controller as shown below β"
},
{
"code": null,
"e": 3149,
"s": 3096,
"text": "rails g controller Resumes index new create destroy\n"
},
{
"code": null,
"e": 3435,
"s": 3149,
"text": "Great! Now we have the basic structure set up. Now we need to create an uploader. An Uploader came from carrierwave gem and it tells to carrierwave how to handle the files. In short, it contained all file processing functionalities. Run the command to create an uploader as shown below"
},
{
"code": null,
"e": 3464,
"s": 3435,
"text": "rails g uploader attachment\n"
},
{
"code": null,
"e": 3578,
"s": 3464,
"text": "Now open the resume model and call the uploader as shown below. Resume model has placed at app/models/resume.rb β"
},
{
"code": null,
"e": 3793,
"s": 3578,
"text": "class Resume < ActiveRecord::Base\n mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model.\n validates :name, presence: true # Make sure the owner's name is present.\nend"
},
{
"code": null,
"e": 3879,
"s": 3793,
"text": "Before working on controller, we need to modify our config/routes.db as shown below β"
},
{
"code": null,
"e": 4017,
"s": 3879,
"text": "CarrierWaveExample::Application.routes.draw do\n resources :resumes, only: [:index, :new, :create, :destroy]\n root \"resumes#index\"\nend"
},
{
"code": null,
"e": 4061,
"s": 4017,
"text": "Lets us edit the controller as shown below."
},
{
"code": null,
"e": 4731,
"s": 4061,
"text": "class ResumesController < ApplicationController\n def index\n @resumes = Resume.all\n end\n \n def new\n @resume = Resume.new\n end\n \n def create\n @resume = Resume.new(resume_params)\n \n if @resume.save\n redirect_to resumes_path, notice: \"The resume #{@resume.name} has been uploaded.\"\n else\n render \"new\"\n end\n \n end\n \n def destroy\n @resume = Resume.find(params[:id])\n @resume.destroy\n redirect_to resumes_path, notice: \"The resume #{@resume.name} has been deleted.\"\n end\n \n private\n def resume_params\n params.require(:resume).permit(:name, :attachment)\n end\n \nend"
},
{
"code": null,
"e": 4839,
"s": 4731,
"text": "Let's add bootstrap implementation in css file.css file could be in app/assets/stylesheets/resumes.css.scss"
},
{
"code": null,
"e": 4861,
"s": 4839,
"text": "@import \"bootstrap\";\n"
},
{
"code": null,
"e": 4943,
"s": 4861,
"text": "Now open up app/views/layouts/application.html.erb and add codes as shown below β"
},
{
"code": null,
"e": 5361,
"s": 4943,
"text": "<!DOCTYPE html>\n<html>\n \n <head>\n <title>Tutorialspoint</title>\n <%= stylesheet_link_tag \"application\", media: \"all\", \"data-turbolinks-track\" => true %>\n <%= javascript_include_tag \"application\", \"data-turbolinks-track\" => true %>\n <%= csrf_meta_tags %>\n </head>\n \n <body>\n <div class = \"container\" style = \"padding-top:20px;\">\n <%= yield %>\n </div>\n </body>\n\n</html>"
},
{
"code": null,
"e": 5412,
"s": 5361,
"text": "Now we need to set up index views as shown below β"
},
{
"code": null,
"e": 6221,
"s": 5412,
"text": "<% if !flash[:notice].blank? %>\n <div class = \"alert alert-info\">\n <%= flash[:notice] %>\n </div>\n<% end %>\n\n<br />\n\n<%= link_to \"New Resume\", new_resume_path, class: \"btn btn-primary\" %>\n<br />\n<br />\n\n<table class = \"table table-bordered table-striped\">\n <thead>.\n <tr>\n <th>Name</th>\n <th>Download Link</th>\n <th> </th>\n </tr>\n </thead>\n \n <tbody>\n <% @resumes.each do |resume| %>\n \n <tr>\n <td><%= resume.name %></td>\n <td><%= link_to \"Download Resume\", resume.attachment_url %></td>\n <td><%= button_to \"Delete\", resume, method: :delete, class: \"btn btn-danger\", confirm: \"Are you sure that you wish to delete #{resume.name}?\" %></td>\n </tr>\n \n <% end %>\n </tbody>\n \n</table>"
},
{
"code": null,
"e": 6272,
"s": 6221,
"text": "Now, lets edit new.html.erb and add our form code."
},
{
"code": null,
"e": 6795,
"s": 6272,
"text": "<% if [email protected]? %>\n <div class = \"alert alert-error\">\n \n <ul>\n <% @resume.errors.full_messages.each do |msg| %>\n <li><%= msg %></li>\n <% end %>\n </ul>\n \n </div>\n<% end %>\n\n<div class = \"well\">\n <%= form_for @resume, html: { multipart: true } do |f| %>\n <%= f.label :name %>\n <%= f.text_field :name %>\n <%= f.label :attachment %>\n <%= f.file_field :attachment %>\n <%= f.submit \"Save\", class: \"btn btn-primary\" %>\n <% end %>\n</div>"
},
{
"code": null,
"e": 6898,
"s": 6795,
"text": "Now start the server and visit http://localhost:3000. It will produce a screen similar to as follows β"
},
{
"code": null,
"e": 7056,
"s": 6898,
"text": "One last thing we need to do is filter the list of allowed filetypes. For that we need add simple code as shown below at app/uploaders/attachment_uploader.rb"
},
{
"code": null,
"e": 7304,
"s": 7056,
"text": "class AttachmentUploader < CarrierWave::Uploader::Base\n storage :file\n \n def store_dir\n \"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}\"\n end\n \n def extension_white_list\n %w(pdf doc htm html docx)\n end\nend"
},
{
"code": null,
"e": 7434,
"s": 7304,
"text": "Now start the server and visit http://localhost:3000. Now input a wrong format; it will generate a wrong message as shown below β"
},
{
"code": null,
"e": 7522,
"s": 7434,
"text": "For a complete detail on File object, you need to go through the Ruby Reference Manual."
},
{
"code": null,
"e": 7529,
"s": 7522,
"text": " Print"
},
{
"code": null,
"e": 7540,
"s": 7529,
"text": " Add Notes"
}
] |
Count the number of visible nodes in Binary Tree - GeeksforGeeks | 23 Jun, 2021
Given a Binary tree, the task is to find the number of visible nodes in the given binary tree. A node is a visible node if, in the path from the root to the node N, there is no node with greater value than Nβs, Examples:
Input:
5
/ \
3 10
/ \ /
20 21 1
Output: 4
Explanation:
There are 4 visible nodes.
They are:
5: In the path 5 -> 3, 5 is the highest node value.
20: In the path 5 -> 3 -> 20, 20 is the highest node value.
21: In the path 5 -> 3 -> 21, 21 is the highest node value.
10: In the path 5 -> 10 -> 1, 10 is the highest node value.
Input:
-1
\
-2
\
-3
Output: 1
Approach: The idea is to first traverse the tree. Since we need to see the maximum value in the given path, the pre-order traversal is used to traverse the given binary tree. While traversing the tree, we need to keep the track of the maximum value of the node that we have seen so far. If the current node is greater or equal to the max value, then increment the count of the visible node and update the max value with the current node value. Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to// count the number of// visible nodes in the// binary tree#include <bits/stdc++.h>using namespace std; // Node containing the// left and right child of// current node and the key valuestruct Node{ int data; Node *left, *right;}; /* Utility that allocates anew node with the given key andNULL left and right pointers. */struct Node* newnode(int data){ struct Node* node = new (struct Node); node->data = data; node->left = node->right = NULL; return (node);} // Variable to keep the track// of visible nodesint countNode = 0; // Function to perform the preorder traversal// for the given treevoid preOrder(Node* node, int mx){ // Base case if (node == NULL) { return; } // If the current node value is greater // or equal to the max value, // then update count variable // and also update max variable if (node->data >= mx) { countNode++; mx = max(node->data, mx); } // Traverse to the left preOrder(node->left, mx); // Traverse to the right preOrder(node->right, mx);} // Driver codeint main(){ struct Node* root = newnode(5); /* 5 / \ 3 10 / \ / 20 21 1*/ root->left = newnode(3); root->right = newnode(10); root->left->left = newnode(20); root->left->right = newnode(21); root->right->left = newnode(1); preOrder(root, INT_MIN); cout << countNode;} // This code is contributed by gauravrajput1
// Java implementation to count the// number of visible nodes in// the binary tree // Class containing the left and right// child of current node and the// key valueclass Node { int data; Node left, right; // Constructor of the class public Node(int item) { data = item; left = right = null; }} public class GFG { Node root; // Variable to keep the track // of visible nodes static int count; // Function to perform the preorder traversal // for the given tree static void preOrder(Node node, int max) { // Base case if (node == null) { return; } // If the current node value is greater // or equal to the max value, // then update count variable // and also update max variable if (node.data >= max) { count++; max = Math.max(node.data, max); } // Traverse to the left preOrder(node.left, max); // Traverse to the right preOrder(node.right, max); } // Driver code public static void main(String[] args) { GFG tree = new GFG(); /* 5 / \ 3 10 / \ / 20 21 1*/ tree.root = new Node(5); tree.root.left = new Node(3); tree.root.right = new Node(10); tree.root.left.left = new Node(20); tree.root.left.right = new Node(21); tree.root.right.left = new Node(1); count = 0; preOrder(tree.root, Integer.MIN_VALUE); System.out.println(count); }}
# Python 3 implementation to# count the number of# visible nodes in the# binary tree import sys# Node containing the# left and right child of# current node and the key value class newNode: def __init__(self, data): self.data = data self.left = None self.right = None ''' Utility that allocates anew node with the given key andNone left and right pointers. */''' # Variable to keep the track# of visible nodescountNode = 0 # Function to perform the# preorder traversal for the# given treedef preOrder(node, mx): global countNode # Base case if (node == None): return # If the current node value # is greater or equal to the # max value, then update count # variable and also update max # variable if (node.data >= mx): countNode += 1 mx = max(node.data, mx) # Traverse to the left preOrder(node.left, mx) # Traverse to the right preOrder(node.right, mx) # Driver codeif __name__ == '__main__': root = newNode(5) ''' /* 5 / \ 3 10 / / / 20 21 1 */ ''' root.left = newNode(3) root.right = newNode(10) root.left.left = newNode(20) root.left.right = newNode(21) root.right.left = newNode(1) preOrder(root, -sys.maxsize-1) print(countNode) # This code is contributed by SURENDRA_GANGWAR
// C# implementation to count the// number of visible nodes in// the binary treeusing System; // Class containing the left and right// child of current node and the// key valueclass Node{ public int data; public Node left, right; // Constructor of the class public Node(int item) { data = item; left = right = null; }} class GFG{ Node root; // Variable to keep the track// of visible nodesstatic int count; // Function to perform the preorder// traversal for the given treestatic void preOrder(Node node, int max){ // Base case if (node == null) { return; } // If the current node value is greater // or equal to the max value, // then update count variable // and also update max variable if (node.data >= max) { count++; max = Math.Max(node.data, max); } // Traverse to the left preOrder(node.left, max); // Traverse to the right preOrder(node.right, max);} // Driver codestatic public void Main(String[] args){ GFG tree = new GFG(); /* 5 / \ 3 10 / \ / 20 21 1*/ tree.root = new Node(5); tree.root.left = new Node(3); tree.root.right = new Node(10); tree.root.left.left = new Node(20); tree.root.left.right = new Node(21); tree.root.right.left = new Node(1); count = 0; preOrder(tree.root, int.MinValue); Console.WriteLine(count);}} // This code is contributed by Amit Katiyar
<script> // Javascript implementation to count the // number of visible nodes in the binary tree // Class containing the left and right // child of current node and the // key value class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let root; // Variable to keep the track // of visible nodes let count; // Function to perform the preorder traversal // for the given tree function preOrder(node, max) { // Base case if (node == null) { return; } // If the current node value is greater // or equal to the max value, // then update count variable // and also update max variable if (node.data >= max) { count++; max = Math.max(node.data, max); } // Traverse to the left preOrder(node.left, max); // Traverse to the right preOrder(node.right, max); } /* 5 / \ 3 10 / \ / 20 21 1 */ root = new Node(5); root.left = new Node(3); root.right = new Node(10); root.left.left = new Node(20); root.left.right = new Node(21); root.right.left = new Node(1); count = 0; preOrder(root, Number.MIN_VALUE); document.write(count); // This code is contributed by rameshtravel07.</script>
4
Complexity Analysis: Time Complexity: O(N) where N is a number of nodes in the Binary tree. Auxiliary Space: O(H) where H is the height of the Binary tree.
amit143katiyar
GauravRajput1
SURENDRA_GANGWAR
rameshtravel07
Binary Tree
Microsoft
Tree
Microsoft
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Tree Data Structure
DFS traversal of a tree using recursion
Threaded Binary Tree
Find maximum (or minimum) in Binary Tree
Iterative Postorder Traversal | Set 2 (Using One Stack)
Find the node with minimum value in a Binary Search Tree
Top 50 Tree Coding Problems for Interviews
Maximum Path Sum in a Binary Tree
Construct Complete Binary Tree from its Linked List Representation
Iterative Preorder Traversal | [
{
"code": null,
"e": 24938,
"s": 24910,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 25160,
"s": 24938,
"text": "Given a Binary tree, the task is to find the number of visible nodes in the given binary tree. A node is a visible node if, in the path from the root to the node N, there is no node with greater value than Nβs, Examples: "
},
{
"code": null,
"e": 25591,
"s": 25160,
"text": "Input:\n 5\n / \\\n 3 10\n / \\ /\n20 21 1\n\nOutput: 4 \nExplanation:\nThere are 4 visible nodes. \nThey are:\n5: In the path 5 -> 3, 5 is the highest node value.\n20: In the path 5 -> 3 -> 20, 20 is the highest node value.\n21: In the path 5 -> 3 -> 21, 21 is the highest node value.\n10: In the path 5 -> 10 -> 1, 10 is the highest node value. \n\nInput:\n -1\n \\\n -2\n \\\n -3\nOutput: 1"
},
{
"code": null,
"e": 26088,
"s": 25591,
"text": "Approach: The idea is to first traverse the tree. Since we need to see the maximum value in the given path, the pre-order traversal is used to traverse the given binary tree. While traversing the tree, we need to keep the track of the maximum value of the node that we have seen so far. If the current node is greater or equal to the max value, then increment the count of the visible node and update the max value with the current node value. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26092,
"s": 26088,
"text": "C++"
},
{
"code": null,
"e": 26097,
"s": 26092,
"text": "Java"
},
{
"code": null,
"e": 26105,
"s": 26097,
"text": "Python3"
},
{
"code": null,
"e": 26108,
"s": 26105,
"text": "C#"
},
{
"code": null,
"e": 26119,
"s": 26108,
"text": "Javascript"
},
{
"code": "// C++ implementation to// count the number of// visible nodes in the// binary tree#include <bits/stdc++.h>using namespace std; // Node containing the// left and right child of// current node and the key valuestruct Node{ int data; Node *left, *right;}; /* Utility that allocates anew node with the given key andNULL left and right pointers. */struct Node* newnode(int data){ struct Node* node = new (struct Node); node->data = data; node->left = node->right = NULL; return (node);} // Variable to keep the track// of visible nodesint countNode = 0; // Function to perform the preorder traversal// for the given treevoid preOrder(Node* node, int mx){ // Base case if (node == NULL) { return; } // If the current node value is greater // or equal to the max value, // then update count variable // and also update max variable if (node->data >= mx) { countNode++; mx = max(node->data, mx); } // Traverse to the left preOrder(node->left, mx); // Traverse to the right preOrder(node->right, mx);} // Driver codeint main(){ struct Node* root = newnode(5); /* 5 / \\ 3 10 / \\ / 20 21 1*/ root->left = newnode(3); root->right = newnode(10); root->left->left = newnode(20); root->left->right = newnode(21); root->right->left = newnode(1); preOrder(root, INT_MIN); cout << countNode;} // This code is contributed by gauravrajput1",
"e": 27614,
"s": 26119,
"text": null
},
{
"code": "// Java implementation to count the// number of visible nodes in// the binary tree // Class containing the left and right// child of current node and the// key valueclass Node { int data; Node left, right; // Constructor of the class public Node(int item) { data = item; left = right = null; }} public class GFG { Node root; // Variable to keep the track // of visible nodes static int count; // Function to perform the preorder traversal // for the given tree static void preOrder(Node node, int max) { // Base case if (node == null) { return; } // If the current node value is greater // or equal to the max value, // then update count variable // and also update max variable if (node.data >= max) { count++; max = Math.max(node.data, max); } // Traverse to the left preOrder(node.left, max); // Traverse to the right preOrder(node.right, max); } // Driver code public static void main(String[] args) { GFG tree = new GFG(); /* 5 / \\ 3 10 / \\ / 20 21 1*/ tree.root = new Node(5); tree.root.left = new Node(3); tree.root.right = new Node(10); tree.root.left.left = new Node(20); tree.root.left.right = new Node(21); tree.root.right.left = new Node(1); count = 0; preOrder(tree.root, Integer.MIN_VALUE); System.out.println(count); }}",
"e": 29207,
"s": 27614,
"text": null
},
{
"code": "# Python 3 implementation to# count the number of# visible nodes in the# binary tree import sys# Node containing the# left and right child of# current node and the key value class newNode: def __init__(self, data): self.data = data self.left = None self.right = None ''' Utility that allocates anew node with the given key andNone left and right pointers. */''' # Variable to keep the track# of visible nodescountNode = 0 # Function to perform the# preorder traversal for the# given treedef preOrder(node, mx): global countNode # Base case if (node == None): return # If the current node value # is greater or equal to the # max value, then update count # variable and also update max # variable if (node.data >= mx): countNode += 1 mx = max(node.data, mx) # Traverse to the left preOrder(node.left, mx) # Traverse to the right preOrder(node.right, mx) # Driver codeif __name__ == '__main__': root = newNode(5) ''' /* 5 / \\ 3 10 / / / 20 21 1 */ ''' root.left = newNode(3) root.right = newNode(10) root.left.left = newNode(20) root.left.right = newNode(21) root.right.left = newNode(1) preOrder(root, -sys.maxsize-1) print(countNode) # This code is contributed by SURENDRA_GANGWAR",
"e": 30586,
"s": 29207,
"text": null
},
{
"code": "// C# implementation to count the// number of visible nodes in// the binary treeusing System; // Class containing the left and right// child of current node and the// key valueclass Node{ public int data; public Node left, right; // Constructor of the class public Node(int item) { data = item; left = right = null; }} class GFG{ Node root; // Variable to keep the track// of visible nodesstatic int count; // Function to perform the preorder// traversal for the given treestatic void preOrder(Node node, int max){ // Base case if (node == null) { return; } // If the current node value is greater // or equal to the max value, // then update count variable // and also update max variable if (node.data >= max) { count++; max = Math.Max(node.data, max); } // Traverse to the left preOrder(node.left, max); // Traverse to the right preOrder(node.right, max);} // Driver codestatic public void Main(String[] args){ GFG tree = new GFG(); /* 5 / \\ 3 10 / \\ / 20 21 1*/ tree.root = new Node(5); tree.root.left = new Node(3); tree.root.right = new Node(10); tree.root.left.left = new Node(20); tree.root.left.right = new Node(21); tree.root.right.left = new Node(1); count = 0; preOrder(tree.root, int.MinValue); Console.WriteLine(count);}} // This code is contributed by Amit Katiyar",
"e": 32041,
"s": 30586,
"text": null
},
{
"code": "<script> // Javascript implementation to count the // number of visible nodes in the binary tree // Class containing the left and right // child of current node and the // key value class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let root; // Variable to keep the track // of visible nodes let count; // Function to perform the preorder traversal // for the given tree function preOrder(node, max) { // Base case if (node == null) { return; } // If the current node value is greater // or equal to the max value, // then update count variable // and also update max variable if (node.data >= max) { count++; max = Math.max(node.data, max); } // Traverse to the left preOrder(node.left, max); // Traverse to the right preOrder(node.right, max); } /* 5 / \\ 3 10 / \\ / 20 21 1 */ root = new Node(5); root.left = new Node(3); root.right = new Node(10); root.left.left = new Node(20); root.left.right = new Node(21); root.right.left = new Node(1); count = 0; preOrder(root, Number.MIN_VALUE); document.write(count); // This code is contributed by rameshtravel07.</script>",
"e": 33518,
"s": 32041,
"text": null
},
{
"code": null,
"e": 33520,
"s": 33518,
"text": "4"
},
{
"code": null,
"e": 33679,
"s": 33522,
"text": "Complexity Analysis: Time Complexity: O(N) where N is a number of nodes in the Binary tree. Auxiliary Space: O(H) where H is the height of the Binary tree. "
},
{
"code": null,
"e": 33694,
"s": 33679,
"text": "amit143katiyar"
},
{
"code": null,
"e": 33708,
"s": 33694,
"text": "GauravRajput1"
},
{
"code": null,
"e": 33725,
"s": 33708,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 33740,
"s": 33725,
"text": "rameshtravel07"
},
{
"code": null,
"e": 33752,
"s": 33740,
"text": "Binary Tree"
},
{
"code": null,
"e": 33762,
"s": 33752,
"text": "Microsoft"
},
{
"code": null,
"e": 33767,
"s": 33762,
"text": "Tree"
},
{
"code": null,
"e": 33777,
"s": 33767,
"text": "Microsoft"
},
{
"code": null,
"e": 33782,
"s": 33777,
"text": "Tree"
},
{
"code": null,
"e": 33880,
"s": 33782,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33889,
"s": 33880,
"text": "Comments"
},
{
"code": null,
"e": 33902,
"s": 33889,
"text": "Old Comments"
},
{
"code": null,
"e": 33938,
"s": 33902,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 33978,
"s": 33938,
"text": "DFS traversal of a tree using recursion"
},
{
"code": null,
"e": 33999,
"s": 33978,
"text": "Threaded Binary Tree"
},
{
"code": null,
"e": 34040,
"s": 33999,
"text": "Find maximum (or minimum) in Binary Tree"
},
{
"code": null,
"e": 34096,
"s": 34040,
"text": "Iterative Postorder Traversal | Set 2 (Using One Stack)"
},
{
"code": null,
"e": 34153,
"s": 34096,
"text": "Find the node with minimum value in a Binary Search Tree"
},
{
"code": null,
"e": 34196,
"s": 34153,
"text": "Top 50 Tree Coding Problems for Interviews"
},
{
"code": null,
"e": 34230,
"s": 34196,
"text": "Maximum Path Sum in a Binary Tree"
},
{
"code": null,
"e": 34297,
"s": 34230,
"text": "Construct Complete Binary Tree from its Linked List Representation"
}
] |
Societe Generale (SocGen) Virtual Interview Experience | 28 Aug, 2020
Round 1: Written test (Platform: Hirepro, No negative marks for MCQ)
The test had Aptitude, Verbal, Technical MCQ questions, and Coding. Every section had individual timings and you cannot use the remaining time of the previous section in the next section. You have to finish it in the allotted time. You have to be really quick in aptitude and verbal. I remember aptitude had only 15 minutes and verbal 4 minutes where there was a question on reading comprehension as well. Questions were moderate. I answered everything. Technical questions were mostly based on software engineering, testing, etc, (I am not able to remember them, but you can answer it easily with the basic concepts). It was all only theory questions (no output prediction), so time was more than enough. Questions were again moderate.
The next section is coding where I had 3 questions in 55 minutes.
Given a matrix, we have to find if it is a special matrix or not. The special matrix is one that has the same row sum and column sum for all the corresponding rows and columns. If it is a special matrix, Output should be Maxed (row sum) and the corresponding row number. If not a special matrix, then the output should be a max of all row_sums and col_sums considered.Given an undirected graph, input will be one of the nodes of the graph, the output should be all the possible unique nodes which can be visited with 2 hops max. Given a list of numbers, starting number and ending number as well, the output should be a sequence where there is only 1 digit change between every number and its previous number.
Given a matrix, we have to find if it is a special matrix or not. The special matrix is one that has the same row sum and column sum for all the corresponding rows and columns. If it is a special matrix, Output should be Maxed (row sum) and the corresponding row number. If not a special matrix, then the output should be a max of all row_sums and col_sums considered.
Given an undirected graph, input will be one of the nodes of the graph, the output should be all the possible unique nodes which can be visited with 2 hops max.
Given a list of numbers, starting number and ending number as well, the output should be a sequence where there is only 1 digit change between every number and its previous number.
Output example:
1234->1254->1253->1953
If such a sequence with a given list of numbers is not possible, then the output should be -1.
Round 2: (Duration 1 hr Technical Interview Skype call)
The interviewer made me feel comfortable by asking general questions about the college, course, online classes, and quarantine days. Then it was all technical questions that started from the languages mentioned in my resume. He asked me in which language I am most comfortable among the mentioned ones from my resume. I answered c++ and python. Then he asked me to choose 1 to dig deep down. I chose c++. So be thorough with all the concepts of at least 1 language. The questions were based on namespace, virtual pointer, virtual table, virtual functions, polymorphism, etc (basically all important oops concepts). Then he asked me the difference between a software engineer and DevOps engineer, and which would be my choice. Then there were questions on the project mentioned in the resume. Since I had a package based on MongoDB and Neo4j, he asked me to explain the project briefly and then why I used both these databases? Why not just one? Why not SQL? What is polyglot persistence? Basically you have to know the reason behind the technology you have used in your resume. I had mentioned in my resume that I attended a workshop in IIT Madras on Ethical Hacking. So he asked me about it? What is the difference between white hat hackers and black hat hackers? After that, he asked me if I had any questions for him.
Round 3: (Duration 1 hr Technical Interview Skype call)
In this round, there was a long discussion on my previous intern project which was data science-based. So following that I had questions like where I have applied data science in real life. He gave me situations like inroads, gardening, etc. Then following that he asked me the difference between mentoring and coaching. After hearing the answer, he said βwhat if I say it is exactly the oppositeβ. So basically this type of question is to check your thinking skills. You have to justify your answer giving proper reasons behind such an answer and you have to convey in the right manner that what you answered made sense. You should be able to convince him of your answer. Confidence is important. He was satisfied with my answer and said fair enough. Then he asked me if I have developed any application. I had a package which is basically a quiz game based on the inheritance concept. Since the role was a software engineer and my resume was predominantly based on data science because of my previous role being a data analyst he just made sure if I am comfortable with a software background. After that, he asked me if I had any questions for him.
Round 4: (Duration 30 minutes Technical Interview Skype call β Coding round)
This is a complete coding round after a brief introduction to my background. Again as I spoke bout the data science project, 1st question was based on model validation. Then he asked me to code a confusion matrix since I had used that in my project. Next, I was asked to write a code to merge 2 n-ary trees. Next, I was asked to write a code to detect a loop in the linked list. Before that, he asked me a few questions on the linked list.
I had the choice to choose any language, the code should be clean, explain the approach whenever possible. I was asked to screen share, so I felt itβs better to tell him the approach before coding so that he will be able to follow whatever you are coding.
Round 5: (Duration 1 hr Managerial Interview)
Requires good communication skills and spontaneity.
This was basically a stress interview where I was given situations and was asked how I would handle them. Few questions to list were the following:
What drives you to have an interest in data (since my resume was mostly data science-based). Were you shortlisted in any company? What is that and what did u miss there? Why didnβt you make it? So basically I said to him SocGen was the 4th company, and I was shortlisted for Cisco but couldnβt make it because I was nervous and tensed. Then the questions were based on handling stress. He was saying to me everybody in the company will not make you feel comfortable, etc. I agreed and justified my point and told him how I will handle such situations and come out of it.
What do you know about finance? What are the situations where you have shown your leadership? How flexible you are? Would you work in any shifts? Which place would you like to work in Bangalore or Chennai? What is your career aspiration? What kind of extracurricular activities do you do? After that, he asked me if I had any questions for him.
Round 6: (Duration 20 minutes HR Interview)
HR asked me what I know about the company and why SocGen. He asked about my 10th board, the percentage in 10th, 12th board, the percentage in 12th. Then he asked my overall GPA range and the current CGPA to check if there is consistency. He was happy with my marks overall since it was consistent. If it is not consistent, you need a valid reason. Then he asked whether I was flexible with the shifts and location. Then he started giving some information about how the work would be and other things about the company.
Finally, all rounds were done and got placed as a software engineer.
Tips:
The things which are of utmost importance are your confidence, in-depth knowledge on a resume, and coding skills since 1 round was completely based on that. Discuss the approach with the interviewer. Almost in all the rounds, they asked me why SocGen? And there was an interviewer who said everybody had 1st few points from Google, but you have a list of things. I feel that was a major advantage. I listened to the pre-placement talk and asked questions to the interviewers in all the rounds from the talk and the knowledge I had about SocGen. They will know that you have done the groundwork and you are interested in the company which is a plus.
ALL THE VERY BEST GUYS!! Donβt lose hope and put all your hard work ????
Marketing
Societe Generale
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1
Amazon Interview Experience SDE-2 (3 Years Experienced)
TCS Ninja Interview Experience (2020 batch)
Write It Up: Share Your Interview Experiences
Samsung RnD Coding Round Questions
Nagarro Interview Experience
Amazon Interview Experience for SDE-1
Nagarro Interview Experience | On-Campus 2021 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 97,
"s": 28,
"text": "Round 1: Written test (Platform: Hirepro, No negative marks for MCQ)"
},
{
"code": null,
"e": 834,
"s": 97,
"text": "The test had Aptitude, Verbal, Technical MCQ questions, and Coding. Every section had individual timings and you cannot use the remaining time of the previous section in the next section. You have to finish it in the allotted time. You have to be really quick in aptitude and verbal. I remember aptitude had only 15 minutes and verbal 4 minutes where there was a question on reading comprehension as well. Questions were moderate. I answered everything. Technical questions were mostly based on software engineering, testing, etc, (I am not able to remember them, but you can answer it easily with the basic concepts). It was all only theory questions (no output prediction), so time was more than enough. Questions were again moderate."
},
{
"code": null,
"e": 900,
"s": 834,
"text": "The next section is coding where I had 3 questions in 55 minutes."
},
{
"code": null,
"e": 1613,
"s": 900,
"text": "Given a matrix, we have to find if it is a special matrix or not. The special matrix is one that has the same row sum and column sum for all the corresponding rows and columns. If it is a special matrix, Output should be Maxed (row sum) and the corresponding row number. If not a special matrix, then the output should be a max of all row_sums and col_sums considered.Given an undirected graph, input will be one of the nodes of the graph, the output should be all the possible unique nodes which can be visited with 2 hops max. Given a list of numbers, starting number and ending number as well, the output should be a sequence where there is only 1 digit change between every number and its previous number. "
},
{
"code": null,
"e": 1982,
"s": 1613,
"text": "Given a matrix, we have to find if it is a special matrix or not. The special matrix is one that has the same row sum and column sum for all the corresponding rows and columns. If it is a special matrix, Output should be Maxed (row sum) and the corresponding row number. If not a special matrix, then the output should be a max of all row_sums and col_sums considered."
},
{
"code": null,
"e": 2145,
"s": 1982,
"text": "Given an undirected graph, input will be one of the nodes of the graph, the output should be all the possible unique nodes which can be visited with 2 hops max. "
},
{
"code": null,
"e": 2328,
"s": 2145,
"text": "Given a list of numbers, starting number and ending number as well, the output should be a sequence where there is only 1 digit change between every number and its previous number. "
},
{
"code": null,
"e": 2345,
"s": 2328,
"text": "Output example: "
},
{
"code": null,
"e": 2368,
"s": 2345,
"text": "1234->1254->1253->1953"
},
{
"code": null,
"e": 2463,
"s": 2368,
"text": "If such a sequence with a given list of numbers is not possible, then the output should be -1."
},
{
"code": null,
"e": 2519,
"s": 2463,
"text": "Round 2: (Duration 1 hr Technical Interview Skype call)"
},
{
"code": null,
"e": 3840,
"s": 2519,
"text": "The interviewer made me feel comfortable by asking general questions about the college, course, online classes, and quarantine days. Then it was all technical questions that started from the languages mentioned in my resume. He asked me in which language I am most comfortable among the mentioned ones from my resume. I answered c++ and python. Then he asked me to choose 1 to dig deep down. I chose c++. So be thorough with all the concepts of at least 1 language. The questions were based on namespace, virtual pointer, virtual table, virtual functions, polymorphism, etc (basically all important oops concepts). Then he asked me the difference between a software engineer and DevOps engineer, and which would be my choice. Then there were questions on the project mentioned in the resume. Since I had a package based on MongoDB and Neo4j, he asked me to explain the project briefly and then why I used both these databases? Why not just one? Why not SQL? What is polyglot persistence? Basically you have to know the reason behind the technology you have used in your resume. I had mentioned in my resume that I attended a workshop in IIT Madras on Ethical Hacking. So he asked me about it? What is the difference between white hat hackers and black hat hackers? After that, he asked me if I had any questions for him."
},
{
"code": null,
"e": 3896,
"s": 3840,
"text": "Round 3: (Duration 1 hr Technical Interview Skype call)"
},
{
"code": null,
"e": 5047,
"s": 3896,
"text": "In this round, there was a long discussion on my previous intern project which was data science-based. So following that I had questions like where I have applied data science in real life. He gave me situations like inroads, gardening, etc. Then following that he asked me the difference between mentoring and coaching. After hearing the answer, he said βwhat if I say it is exactly the oppositeβ. So basically this type of question is to check your thinking skills. You have to justify your answer giving proper reasons behind such an answer and you have to convey in the right manner that what you answered made sense. You should be able to convince him of your answer. Confidence is important. He was satisfied with my answer and said fair enough. Then he asked me if I have developed any application. I had a package which is basically a quiz game based on the inheritance concept. Since the role was a software engineer and my resume was predominantly based on data science because of my previous role being a data analyst he just made sure if I am comfortable with a software background. After that, he asked me if I had any questions for him."
},
{
"code": null,
"e": 5124,
"s": 5047,
"text": "Round 4: (Duration 30 minutes Technical Interview Skype call β Coding round)"
},
{
"code": null,
"e": 5564,
"s": 5124,
"text": "This is a complete coding round after a brief introduction to my background. Again as I spoke bout the data science project, 1st question was based on model validation. Then he asked me to code a confusion matrix since I had used that in my project. Next, I was asked to write a code to merge 2 n-ary trees. Next, I was asked to write a code to detect a loop in the linked list. Before that, he asked me a few questions on the linked list."
},
{
"code": null,
"e": 5820,
"s": 5564,
"text": "I had the choice to choose any language, the code should be clean, explain the approach whenever possible. I was asked to screen share, so I felt itβs better to tell him the approach before coding so that he will be able to follow whatever you are coding."
},
{
"code": null,
"e": 5866,
"s": 5820,
"text": "Round 5: (Duration 1 hr Managerial Interview)"
},
{
"code": null,
"e": 5918,
"s": 5866,
"text": "Requires good communication skills and spontaneity."
},
{
"code": null,
"e": 6066,
"s": 5918,
"text": "This was basically a stress interview where I was given situations and was asked how I would handle them. Few questions to list were the following:"
},
{
"code": null,
"e": 6639,
"s": 6066,
"text": "What drives you to have an interest in data (since my resume was mostly data science-based). Were you shortlisted in any company? What is that and what did u miss there? Why didnβt you make it? So basically I said to him SocGen was the 4th company, and I was shortlisted for Cisco but couldnβt make it because I was nervous and tensed. Then the questions were based on handling stress. He was saying to me everybody in the company will not make you feel comfortable, etc. I agreed and justified my point and told him how I will handle such situations and come out of it. "
},
{
"code": null,
"e": 6984,
"s": 6639,
"text": "What do you know about finance? What are the situations where you have shown your leadership? How flexible you are? Would you work in any shifts? Which place would you like to work in Bangalore or Chennai? What is your career aspiration? What kind of extracurricular activities do you do? After that, he asked me if I had any questions for him."
},
{
"code": null,
"e": 7028,
"s": 6984,
"text": "Round 6: (Duration 20 minutes HR Interview)"
},
{
"code": null,
"e": 7547,
"s": 7028,
"text": "HR asked me what I know about the company and why SocGen. He asked about my 10th board, the percentage in 10th, 12th board, the percentage in 12th. Then he asked my overall GPA range and the current CGPA to check if there is consistency. He was happy with my marks overall since it was consistent. If it is not consistent, you need a valid reason. Then he asked whether I was flexible with the shifts and location. Then he started giving some information about how the work would be and other things about the company."
},
{
"code": null,
"e": 7616,
"s": 7547,
"text": "Finally, all rounds were done and got placed as a software engineer."
},
{
"code": null,
"e": 7622,
"s": 7616,
"text": "Tips:"
},
{
"code": null,
"e": 8271,
"s": 7622,
"text": "The things which are of utmost importance are your confidence, in-depth knowledge on a resume, and coding skills since 1 round was completely based on that. Discuss the approach with the interviewer. Almost in all the rounds, they asked me why SocGen? And there was an interviewer who said everybody had 1st few points from Google, but you have a list of things. I feel that was a major advantage. I listened to the pre-placement talk and asked questions to the interviewers in all the rounds from the talk and the knowledge I had about SocGen. They will know that you have done the groundwork and you are interested in the company which is a plus."
},
{
"code": null,
"e": 8346,
"s": 8271,
"text": "ALL THE VERY BEST GUYS!! Donβt lose hope and put all your hard work ???? "
},
{
"code": null,
"e": 8356,
"s": 8346,
"text": "Marketing"
},
{
"code": null,
"e": 8373,
"s": 8356,
"text": "Societe Generale"
},
{
"code": null,
"e": 8395,
"s": 8373,
"text": "Interview Experiences"
},
{
"code": null,
"e": 8493,
"s": 8395,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8563,
"s": 8493,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 8636,
"s": 8563,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 8674,
"s": 8636,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 8730,
"s": 8674,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 8774,
"s": 8730,
"text": "TCS Ninja Interview Experience (2020 batch)"
},
{
"code": null,
"e": 8820,
"s": 8774,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 8855,
"s": 8820,
"text": "Samsung RnD Coding Round Questions"
},
{
"code": null,
"e": 8884,
"s": 8855,
"text": "Nagarro Interview Experience"
},
{
"code": null,
"e": 8922,
"s": 8884,
"text": "Amazon Interview Experience for SDE-1"
}
] |
Hornerβs Method for Polynomial Evaluation | 02 Nov, 2021
Given a polynomial of the form cnxn + cn-1xn-1 + cn-2xn-2 + ... + c1x + c0 and a value of x, find the value of polynomial for a given value of x. Here cn, cn-1, .. are integers (may be negative) and n is a positive integer.Input is in the form of an array say poly[] where poly[0] represents coefficient for xn and poly[1] represents coefficient for xn-1 and so on.Examples:
// Evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3
Input: poly[] = {2, -6, 2, -1}, x = 3
Output: 5
// Evaluate value of 2x3 + 3x + 1 for x = 2
Input: poly[] = {2, 0, 3, 1}, x = 2
Output: 23
A naive way to evaluate a polynomial is to one by one evaluate all terms. First calculate xn, multiply the value with cn, repeat the same steps for other terms and return the sum. Time complexity of this approach is O(n2) if we use a simple loop for evaluation of xn. Time complexity can be improved to O(nLogn) if we use O(Logn) approach for evaluation of xn.Hornerβs method can be used to evaluate polynomial in O(n) time. To understand the method, let us consider the example of 2x3 β 6x2 + 2x β 1. The polynomial can be evaluated as ((2x β 6)x + 2)x β 1. The idea is to initialize result as coefficient of xn which is 2 in this case, repeatedly multiply result with x and add next coefficient to result. Finally return result.Following is implementation of Hornerβs Method.
C++
Java
Python3
C#
PHP
Javascript
#include <iostream>using namespace std; // returns value of poly[0]x(n-1) + poly[1]x(n-2) + .. + poly[n-1]int horner(int poly[], int n, int x){ int result = poly[0]; // Initialize result // Evaluate value of polynomial using Horner's method for (int i=1; i<n; i++) result = result*x + poly[i]; return result;} // Driver program to test above function.int main(){ // Let us evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3 int poly[] = {2, -6, 2, -1}; int x = 3; int n = sizeof(poly)/sizeof(poly[0]); cout << "Value of polynomial is " << horner(poly, n, x); return 0;}
// Java program for implementation of Horner Method// for Polynomial Evaluationimport java.io.*; class HornerPolynomial{ // Function that returns value of poly[0]x(n-1) + // poly[1]x(n-2) + .. + poly[n-1] static int horner(int poly[], int n, int x) { // Initialize result int result = poly[0]; // Evaluate value of polynomial using Horner's method for (int i=1; i<n; i++) result = result*x + poly[i]; return result; } // Driver program public static void main (String[] args) { // Let us evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3 int[] poly = {2, -6, 2, -1}; int x = 3; int n = poly.length; System.out.println("Value of polynomial is " + horner(poly,n,x)); }} // Contributed by Pramod Kumar
# Python program for# implementation of Horner Method# for Polynomial Evaluation # returns value of poly[0]x(n-1)# + poly[1]x(n-2) + .. + poly[n-1]def horner(poly, n, x): # Initialize result result = poly[0] # Evaluate value of polynomial # using Horner's method for i in range(1, n): result = result*x + poly[i] return result # Driver program to# test above function. # Let us evaluate value of# 2x3 - 6x2 + 2x - 1 for x = 3poly = [2, -6, 2, -1]x = 3n = len(poly) print("Value of polynomial is " , horner(poly, n, x)) # This code is contributed# by Anant Agarwal.
// C# program for implementation of// Horner Method for Polynomial Evaluation.using System; class GFG{ // Function that returns value of poly[0]x(n-1) + // poly[1]x(n-2) + .. + poly[n-1] static int horner(int []poly, int n, int x) { // Initialize result int result = poly[0]; // Evaluate value of polynomial // using Horner's method for (int i = 1; i < n; i++) result = result * x + poly[i]; return result; } // Driver Code public static void Main() { // Let us evaluate value of // 2x3 - 6x2 + 2x - 1 for x = 3 int []poly = {2, -6, 2, -1}; int x = 3; int n = poly.Length; Console.Write("Value of polynomial is " + horner(poly,n,x)); }} // This code Contributed by nitin mittal.
<?php// PHP program for implementation// of Horner Method for Polynomial// Evaluation. // returns value of poly[0]x(n-1) +// poly[1]x(n-2) + .. + poly[n-1]function horner($poly, $n, $x){ // Initialize result $result = $poly[0]; // Evaluate value of polynomial // using Horner's method for ($i = 1; $i < $n; $i++) $result = $result * $x + $poly[$i]; return $result;} // Driver Code // Let us evaluate value of// 2x3 - 6x2 + 2x - 1 for x = 3$poly = array(2, -6, 2, -1);$x = 3;$n = sizeof($poly) / sizeof($poly[0]); echo "Value of polynomial is ". horner($poly, $n, $x); // This code is contributed by mits.?>
<script>// Javascript program for implementation// of Horner Method for Polynomial// Evaluation. // returns value of poly[0]x(n-1) +// poly[1]x(n-2) + .. + poly[n-1]function horner(poly, n, x){ // Initialize result let result = poly[0]; // Evaluate value of polynomial // using Horner's method for (let i = 1; i < n; i++) result = result * x + poly[i]; return result;} // Driver Code // Let us evaluate value of// 2x3 - 6x2 + 2x - 1 for x = 3let poly = new Array(2, -6, 2, -1);let x = 3;let n = poly.length document.write("Value of polynomial is " + horner(poly, n, x)); // This code is contributed by _saurabh_jaiswal.</script>
Output:
Value of polynomial is 5
Time Complexity: O(n)
Auxiliary Space: O(1)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
nitin mittal
Mithun Kumar
_saurabh_jaiswal
subhammahato348
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 428,
"s": 52,
"text": "Given a polynomial of the form cnxn + cn-1xn-1 + cn-2xn-2 + ... + c1x + c0 and a value of x, find the value of polynomial for a given value of x. Here cn, cn-1, .. are integers (may be negative) and n is a positive integer.Input is in the form of an array say poly[] where poly[0] represents coefficient for xn and poly[1] represents coefficient for xn-1 and so on.Examples: "
},
{
"code": null,
"e": 618,
"s": 428,
"text": "// Evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3\nInput: poly[] = {2, -6, 2, -1}, x = 3\nOutput: 5\n\n// Evaluate value of 2x3 + 3x + 1 for x = 2\nInput: poly[] = {2, 0, 3, 1}, x = 2\nOutput: 23"
},
{
"code": null,
"e": 1400,
"s": 620,
"text": "A naive way to evaluate a polynomial is to one by one evaluate all terms. First calculate xn, multiply the value with cn, repeat the same steps for other terms and return the sum. Time complexity of this approach is O(n2) if we use a simple loop for evaluation of xn. Time complexity can be improved to O(nLogn) if we use O(Logn) approach for evaluation of xn.Hornerβs method can be used to evaluate polynomial in O(n) time. To understand the method, let us consider the example of 2x3 β 6x2 + 2x β 1. The polynomial can be evaluated as ((2x β 6)x + 2)x β 1. The idea is to initialize result as coefficient of xn which is 2 in this case, repeatedly multiply result with x and add next coefficient to result. Finally return result.Following is implementation of Hornerβs Method. "
},
{
"code": null,
"e": 1404,
"s": 1400,
"text": "C++"
},
{
"code": null,
"e": 1409,
"s": 1404,
"text": "Java"
},
{
"code": null,
"e": 1417,
"s": 1409,
"text": "Python3"
},
{
"code": null,
"e": 1420,
"s": 1417,
"text": "C#"
},
{
"code": null,
"e": 1424,
"s": 1420,
"text": "PHP"
},
{
"code": null,
"e": 1435,
"s": 1424,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; // returns value of poly[0]x(n-1) + poly[1]x(n-2) + .. + poly[n-1]int horner(int poly[], int n, int x){ int result = poly[0]; // Initialize result // Evaluate value of polynomial using Horner's method for (int i=1; i<n; i++) result = result*x + poly[i]; return result;} // Driver program to test above function.int main(){ // Let us evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3 int poly[] = {2, -6, 2, -1}; int x = 3; int n = sizeof(poly)/sizeof(poly[0]); cout << \"Value of polynomial is \" << horner(poly, n, x); return 0;}",
"e": 2040,
"s": 1435,
"text": null
},
{
"code": "// Java program for implementation of Horner Method// for Polynomial Evaluationimport java.io.*; class HornerPolynomial{ // Function that returns value of poly[0]x(n-1) + // poly[1]x(n-2) + .. + poly[n-1] static int horner(int poly[], int n, int x) { // Initialize result int result = poly[0]; // Evaluate value of polynomial using Horner's method for (int i=1; i<n; i++) result = result*x + poly[i]; return result; } // Driver program public static void main (String[] args) { // Let us evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3 int[] poly = {2, -6, 2, -1}; int x = 3; int n = poly.length; System.out.println(\"Value of polynomial is \" + horner(poly,n,x)); }} // Contributed by Pramod Kumar",
"e": 2893,
"s": 2040,
"text": null
},
{
"code": "# Python program for# implementation of Horner Method# for Polynomial Evaluation # returns value of poly[0]x(n-1)# + poly[1]x(n-2) + .. + poly[n-1]def horner(poly, n, x): # Initialize result result = poly[0] # Evaluate value of polynomial # using Horner's method for i in range(1, n): result = result*x + poly[i] return result # Driver program to# test above function. # Let us evaluate value of# 2x3 - 6x2 + 2x - 1 for x = 3poly = [2, -6, 2, -1]x = 3n = len(poly) print(\"Value of polynomial is \" , horner(poly, n, x)) # This code is contributed# by Anant Agarwal.",
"e": 3491,
"s": 2893,
"text": null
},
{
"code": "// C# program for implementation of// Horner Method for Polynomial Evaluation.using System; class GFG{ // Function that returns value of poly[0]x(n-1) + // poly[1]x(n-2) + .. + poly[n-1] static int horner(int []poly, int n, int x) { // Initialize result int result = poly[0]; // Evaluate value of polynomial // using Horner's method for (int i = 1; i < n; i++) result = result * x + poly[i]; return result; } // Driver Code public static void Main() { // Let us evaluate value of // 2x3 - 6x2 + 2x - 1 for x = 3 int []poly = {2, -6, 2, -1}; int x = 3; int n = poly.Length; Console.Write(\"Value of polynomial is \" + horner(poly,n,x)); }} // This code Contributed by nitin mittal.",
"e": 4327,
"s": 3491,
"text": null
},
{
"code": "<?php// PHP program for implementation// of Horner Method for Polynomial// Evaluation. // returns value of poly[0]x(n-1) +// poly[1]x(n-2) + .. + poly[n-1]function horner($poly, $n, $x){ // Initialize result $result = $poly[0]; // Evaluate value of polynomial // using Horner's method for ($i = 1; $i < $n; $i++) $result = $result * $x + $poly[$i]; return $result;} // Driver Code // Let us evaluate value of// 2x3 - 6x2 + 2x - 1 for x = 3$poly = array(2, -6, 2, -1);$x = 3;$n = sizeof($poly) / sizeof($poly[0]); echo \"Value of polynomial is \". horner($poly, $n, $x); // This code is contributed by mits.?>",
"e": 4986,
"s": 4327,
"text": null
},
{
"code": "<script>// Javascript program for implementation// of Horner Method for Polynomial// Evaluation. // returns value of poly[0]x(n-1) +// poly[1]x(n-2) + .. + poly[n-1]function horner(poly, n, x){ // Initialize result let result = poly[0]; // Evaluate value of polynomial // using Horner's method for (let i = 1; i < n; i++) result = result * x + poly[i]; return result;} // Driver Code // Let us evaluate value of// 2x3 - 6x2 + 2x - 1 for x = 3let poly = new Array(2, -6, 2, -1);let x = 3;let n = poly.length document.write(\"Value of polynomial is \" + horner(poly, n, x)); // This code is contributed by _saurabh_jaiswal.</script>",
"e": 5668,
"s": 4986,
"text": null
},
{
"code": null,
"e": 5678,
"s": 5668,
"text": "Output: "
},
{
"code": null,
"e": 5703,
"s": 5678,
"text": "Value of polynomial is 5"
},
{
"code": null,
"e": 5725,
"s": 5703,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 5871,
"s": 5725,
"text": "Auxiliary Space: O(1)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 5884,
"s": 5871,
"text": "nitin mittal"
},
{
"code": null,
"e": 5897,
"s": 5884,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 5914,
"s": 5897,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 5930,
"s": 5914,
"text": "subhammahato348"
},
{
"code": null,
"e": 5943,
"s": 5930,
"text": "Mathematical"
},
{
"code": null,
"e": 5956,
"s": 5943,
"text": "Mathematical"
}
] |
Like instagram pictures using Selenium | Python | 30 Oct, 2020
In this article, we will learn how can we like all the pictures of a profile on Instagram without scrolling and manually clicking the buttons. We will be using Selenium to do this task.
Packages/Software needed:
1. Python 3 2. Chromedriver compatible with the existing chrome version (download chromedriver) 3. Google chrome 4. Selenium package (pip install selenium), bs4 package(pip install bs4)
Step #1: Importing modules and entering the login information along with the URL of the page.
Python3
from bs4 import BeautifulSoup as bsimport selenium.common.exceptionsfrom selenium import webdriverimport timefrom selenium.webdriver.common.keys import Keys print("enter username")username = input() print("enter password")password = input() print("enter the url")url = input()
Step #2: Function to enter the path where the chromedriver.exe file exists in your system
Python3
def path(): global chrome print("enter the driver path") exe_path = input() # starts a new chrome session chrome = webdriver.Chrome(executable_path = exe_path)
Step #3: Function to enter the URL of the page
Python3
def url_name(url): # the web page opens up chrome.get(url) # webdriver will wait for 4 sec before throwing a # NoSuchElement exception so that the element # is detected and not skipped. time.sleep(4)
Step #4: Function to enter your login information
Python3
def login(username, your_password): # finds the login button log_but = chrome.find_element_by_class_name("L3NKy") time.sleep(2) # clicks the login button log_but.click() time.sleep(4) # finds the username box usern = chrome.find_element_by_name("username") # sends the entered username usern.send_keys(username) # finds the password box passw = chrome.find_element_by_name("password") # sends the entered password passw.send_keys(your_password) passw.send_keys(Keys.RETURN) time.sleep(6) notn = chrome.find_element_by_class_name("yWX7d")# dont save info button notn.click()# click don't save button time.sleep(3)
Step #5: Function to open the first picture
Python3
def first_picture(): # finds the first picture pic = chrome.find_element_by_class_name("kIKUG") pic.click() # clicks on the first picture
Step #6: Function to like a picture
Python3
def like_pic(): time.sleep(2) like = chrome.find_element_by_class_name('fr66n') soup = bs(like.get_attribute('innerHTML'),'html.parser') if(soup.find('svg')['aria-label'] == 'Like'): like.click() time.sleep(2)
Step #7: Function to click on the Next button
Python3
def next_picture(): time.sleep(2) try: nex = chrome.find_element_by_class_name("coreSpriteRightPaginationArrow") time.sleep(1) return nex except selenium.common.exceptions.NoSuchElementException: return 0
Step #8: Function which continues liking pictures till it is not able to find the next button
Python3
def continue_liking(): while(True): next_el = next_picture() # if next button is there then if next_el != False: # click the next button next_el.click() time.sleep(2) # like the picture like_pic() time.sleep(2) else: print("not found") break
Step #9: Calling the functions
Python3
path()time.sleep(1) url_name(url) login(username, password) first_picture()like_pic() continue_liking()chrome.close()
There you go! The script will automatically like all the posts until the end of the page.
UnworthyProgrammer
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Oct, 2020"
},
{
"code": null,
"e": 240,
"s": 52,
"text": "In this article, we will learn how can we like all the pictures of a profile on Instagram without scrolling and manually clicking the buttons. We will be using Selenium to do this task. "
},
{
"code": null,
"e": 267,
"s": 240,
"text": "Packages/Software needed: "
},
{
"code": null,
"e": 453,
"s": 267,
"text": "1. Python 3 2. Chromedriver compatible with the existing chrome version (download chromedriver) 3. Google chrome 4. Selenium package (pip install selenium), bs4 package(pip install bs4)"
},
{
"code": null,
"e": 549,
"s": 453,
"text": "Step #1: Importing modules and entering the login information along with the URL of the page. "
},
{
"code": null,
"e": 557,
"s": 549,
"text": "Python3"
},
{
"code": "from bs4 import BeautifulSoup as bsimport selenium.common.exceptionsfrom selenium import webdriverimport timefrom selenium.webdriver.common.keys import Keys print(\"enter username\")username = input() print(\"enter password\")password = input() print(\"enter the url\")url = input()",
"e": 834,
"s": 557,
"text": null
},
{
"code": null,
"e": 926,
"s": 834,
"text": "Step #2: Function to enter the path where the chromedriver.exe file exists in your system "
},
{
"code": null,
"e": 934,
"s": 926,
"text": "Python3"
},
{
"code": "def path(): global chrome print(\"enter the driver path\") exe_path = input() # starts a new chrome session chrome = webdriver.Chrome(executable_path = exe_path)",
"e": 1111,
"s": 934,
"text": null
},
{
"code": null,
"e": 1160,
"s": 1111,
"text": "Step #3: Function to enter the URL of the page "
},
{
"code": null,
"e": 1168,
"s": 1160,
"text": "Python3"
},
{
"code": "def url_name(url): # the web page opens up chrome.get(url) # webdriver will wait for 4 sec before throwing a # NoSuchElement exception so that the element # is detected and not skipped. time.sleep(4)",
"e": 1392,
"s": 1168,
"text": null
},
{
"code": null,
"e": 1444,
"s": 1392,
"text": "Step #4: Function to enter your login information "
},
{
"code": null,
"e": 1452,
"s": 1444,
"text": "Python3"
},
{
"code": "def login(username, your_password): # finds the login button log_but = chrome.find_element_by_class_name(\"L3NKy\") time.sleep(2) # clicks the login button log_but.click() time.sleep(4) # finds the username box usern = chrome.find_element_by_name(\"username\") # sends the entered username usern.send_keys(username) # finds the password box passw = chrome.find_element_by_name(\"password\") # sends the entered password passw.send_keys(your_password) passw.send_keys(Keys.RETURN) time.sleep(6) notn = chrome.find_element_by_class_name(\"yWX7d\")# dont save info button notn.click()# click don't save button time.sleep(3)",
"e": 2148,
"s": 1452,
"text": null
},
{
"code": null,
"e": 2194,
"s": 2148,
"text": "Step #5: Function to open the first picture "
},
{
"code": null,
"e": 2202,
"s": 2194,
"text": "Python3"
},
{
"code": "def first_picture(): # finds the first picture pic = chrome.find_element_by_class_name(\"kIKUG\") pic.click() # clicks on the first picture",
"e": 2356,
"s": 2202,
"text": null
},
{
"code": null,
"e": 2394,
"s": 2356,
"text": "Step #6: Function to like a picture "
},
{
"code": null,
"e": 2402,
"s": 2394,
"text": "Python3"
},
{
"code": "def like_pic(): time.sleep(2) like = chrome.find_element_by_class_name('fr66n') soup = bs(like.get_attribute('innerHTML'),'html.parser') if(soup.find('svg')['aria-label'] == 'Like'): like.click() time.sleep(2)",
"e": 2636,
"s": 2402,
"text": null
},
{
"code": null,
"e": 2684,
"s": 2636,
"text": "Step #7: Function to click on the Next button "
},
{
"code": null,
"e": 2692,
"s": 2684,
"text": "Python3"
},
{
"code": "def next_picture(): time.sleep(2) try: nex = chrome.find_element_by_class_name(\"coreSpriteRightPaginationArrow\") time.sleep(1) return nex except selenium.common.exceptions.NoSuchElementException: return 0",
"e": 2934,
"s": 2692,
"text": null
},
{
"code": null,
"e": 3030,
"s": 2934,
"text": "Step #8: Function which continues liking pictures till it is not able to find the next button "
},
{
"code": null,
"e": 3038,
"s": 3030,
"text": "Python3"
},
{
"code": "def continue_liking(): while(True): next_el = next_picture() # if next button is there then if next_el != False: # click the next button next_el.click() time.sleep(2) # like the picture like_pic() time.sleep(2) else: print(\"not found\") break",
"e": 3402,
"s": 3038,
"text": null
},
{
"code": null,
"e": 3435,
"s": 3402,
"text": "Step #9: Calling the functions "
},
{
"code": null,
"e": 3443,
"s": 3435,
"text": "Python3"
},
{
"code": "path()time.sleep(1) url_name(url) login(username, password) first_picture()like_pic() continue_liking()chrome.close()",
"e": 3561,
"s": 3443,
"text": null
},
{
"code": null,
"e": 3652,
"s": 3561,
"text": "There you go! The script will automatically like all the posts until the end of the page. "
},
{
"code": null,
"e": 3671,
"s": 3652,
"text": "UnworthyProgrammer"
},
{
"code": null,
"e": 3679,
"s": 3671,
"text": "Project"
},
{
"code": null,
"e": 3686,
"s": 3679,
"text": "Python"
}
] |
C# | Command Line Arguments | 26 Feb, 2019
The arguments which are passed by the user or programmer to the Main() method is termed as Command-Line Arguments. Main() method is the entry point of execution of a program. Main() method accepts array of strings. But it never accepts parameters from any other method in the program. In C# the command line arguments are passed to the Main() methods by stating as follows:
static void Main(string[] args)
or
static int Main(string[] args)
Note : To enable command-line arguments in the Main method in a Windows Forms Application, one must manually modify the signature of Main in program.cs. Windows Forms designer generates code and creates Main without an input parameter. One can also use Environment.CommandLine or Environment.GetCommandLineArgs to access the command-line arguments from any point in a console or Windows application.
Example:
// C# program to illustrate the // Command Line Argumentsusing System; namespace ComLineArg { class Geeks { // Main Method which accepts the // command line arguments as // string type parameters static void Main(string[] args) { // To check the length of // Command line arguments if(args.Length > 0) { Console.WriteLine("Arguments Passed by the Programmer:"); // To print the command line // arguments using foreach loop foreach(Object obj in args) { Console.WriteLine(obj); } } else { Console.WriteLine("No command line arguments found."); } } }}
To Compile and execute the above program follow below commands :
Compile: csc Geeks.cs
Execute: Geeks.exe Welcome To GeeksforGeeks!
Output :
Arguments Passed by the Programmer:
Welcome
To
GeeksforGeeks!
In above program Length is used to find the number of command line arguments and command line arguments will store in args[] array. With the help of Convert class and parse methods, one can also convert string argument to numeric types. For examples:
long num = Int64.Parse(args[0]);
or
long num = long.Parse(args[0]);
This will changes the string to a long type by using the Parse method. It is also possible to use the C# type long, which aliases Int64. Similarly one can parse using predefined parsing methods in C#.
Reference:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/command-line-arguments
CSharp-Basics
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Lambda Expressions in C#
Partial Classes in C#
Hello World in C# | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Feb, 2019"
},
{
"code": null,
"e": 427,
"s": 53,
"text": "The arguments which are passed by the user or programmer to the Main() method is termed as Command-Line Arguments. Main() method is the entry point of execution of a program. Main() method accepts array of strings. But it never accepts parameters from any other method in the program. In C# the command line arguments are passed to the Main() methods by stating as follows:"
},
{
"code": null,
"e": 495,
"s": 427,
"text": "static void Main(string[] args)\nor \nstatic int Main(string[] args)\n"
},
{
"code": null,
"e": 895,
"s": 495,
"text": "Note : To enable command-line arguments in the Main method in a Windows Forms Application, one must manually modify the signature of Main in program.cs. Windows Forms designer generates code and creates Main without an input parameter. One can also use Environment.CommandLine or Environment.GetCommandLineArgs to access the command-line arguments from any point in a console or Windows application."
},
{
"code": null,
"e": 904,
"s": 895,
"text": "Example:"
},
{
"code": "// C# program to illustrate the // Command Line Argumentsusing System; namespace ComLineArg { class Geeks { // Main Method which accepts the // command line arguments as // string type parameters static void Main(string[] args) { // To check the length of // Command line arguments if(args.Length > 0) { Console.WriteLine(\"Arguments Passed by the Programmer:\"); // To print the command line // arguments using foreach loop foreach(Object obj in args) { Console.WriteLine(obj); } } else { Console.WriteLine(\"No command line arguments found.\"); } } }}",
"e": 1794,
"s": 904,
"text": null
},
{
"code": null,
"e": 1859,
"s": 1794,
"text": "To Compile and execute the above program follow below commands :"
},
{
"code": null,
"e": 1929,
"s": 1859,
"text": "Compile: csc Geeks.cs \nExecute: Geeks.exe Welcome To GeeksforGeeks!\n"
},
{
"code": null,
"e": 1938,
"s": 1929,
"text": "Output :"
},
{
"code": null,
"e": 2001,
"s": 1938,
"text": "Arguments Passed by the Programmer:\nWelcome\nTo\nGeeksforGeeks!\n"
},
{
"code": null,
"e": 2252,
"s": 2001,
"text": "In above program Length is used to find the number of command line arguments and command line arguments will store in args[] array. With the help of Convert class and parse methods, one can also convert string argument to numeric types. For examples:"
},
{
"code": null,
"e": 2321,
"s": 2252,
"text": "long num = Int64.Parse(args[0]);\nor\nlong num = long.Parse(args[0]);\n"
},
{
"code": null,
"e": 2522,
"s": 2321,
"text": "This will changes the string to a long type by using the Parse method. It is also possible to use the C# type long, which aliases Int64. Similarly one can parse using predefined parsing methods in C#."
},
{
"code": null,
"e": 2642,
"s": 2522,
"text": "Reference:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/command-line-arguments"
},
{
"code": null,
"e": 2656,
"s": 2642,
"text": "CSharp-Basics"
},
{
"code": null,
"e": 2659,
"s": 2656,
"text": "C#"
},
{
"code": null,
"e": 2757,
"s": 2659,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2800,
"s": 2757,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2849,
"s": 2800,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2872,
"s": 2849,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 2888,
"s": 2872,
"text": "C# | List Class"
},
{
"code": null,
"e": 2916,
"s": 2888,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 2977,
"s": 2916,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 3000,
"s": 2977,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 3025,
"s": 3000,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 3047,
"s": 3025,
"text": "Partial Classes in C#"
}
] |
Precision of floating point numbers in C++ (floor(), ceil(), trunc(), round() and setprecision()) | Precision of floating point numbers is the accuracy upto which a floating point number can hold the values after decimal.
For example 10/6 = 1.6666666... these have recurring decimals which can take infinite memory spaces to be stored.
So to avoid memory overflow in such cases the compiler set a precision limit to the number. For float values in C++ this precision is set to 6-7 digit after that if the decimal recurs it will discard the value.
So, to avoid any major losses when this discarding takes place there are methods and libraries that support the precision is float values. Here, we will discuss them,
floor() function is round down function that round the number to nearest integer values which is less than the number.
It always returns an integer value which is one less than the integer part of the float number.
Library: math.h
Live Demo
#include<iostream>
#include<math.h>
using namespace std;
int main() {
float number1 = 0.435 , number2 = 234.2342, number3 = -3.31132, number4 = -0.432;
cout<<"Values are : \n";
cout<<"Number 1 : "<<floor(number1)<<endl;
cout<<"Number 2 : "<<floor(number2)<<endl;
cout<<"Number 3 : "<<floor(number3)<<endl;
cout<<"Number 4 : "<<floor(number4)<<endl;
return 0;
}
Values are :
Number 1 : 0
Number 2 : 234
Number 3 : -4
Number 4 : -1
ceil() function is rounding function that rounds the number to nearest integer values which is greater than the number.
It always returns an integer value which is one more than the integer part of the float number.
Library: math.h
Live Demo
#include<iostream>
#include<math.h>
using namespace std;
int main() {
float number1 = 0.435 , number2 = 234.2342, number3 = -3.31132, number4 = -0.432;
cout<<"Values are : \n";
cout<<"Number 1 : "<<ceil(number1)<<endl;
cout<<"Number 2 : "<<ceil(number2)<<endl;
cout<<"Number 3 : "<<ceil(number3)<<endl;
cout<<"Number 4 : "<<ceil(number4)<<endl;
return 0;
}
Values are :
Number 1 : 1
Number 2 : 235
Number 3 : -3
Number 4 : -0
round() function is rounding function that rounds the number to nearest integer values which can be greater or smaller than the number.
It always returns an integer value which can one more/less than the integer part of the float number.
Library: math.h
Live Demo
#include<iostream>
#include<math.h>
using namespace std;
int main() {
float number1 = 0.435 , number2 = 234.5612, number3 = -3.31132, number4 = -0.9132;
cout<<"Values are : \n";
cout<<"Number 1 : "<<ceil(number1)<<endl;
cout<<"Number 2 : "<<ceil(number2)<<endl;
cout<<"Number 3 : "<<ceil(number3)<<endl;
cout<<"Number 4 : "<<ceil(number4)<<endl;
return 0;
}
Values are :
Number 1 : 1
Number 2 : 235
Number 3 : -3
Number 4 : -0
The setprecision() function returns the value of flaot which is correct upto n decimal places. N is the parameter passed to the setprecission function.
For the functioning, it uses fixed.
Library: iomanip
Live Demo
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
float number1 = 0.435 , number2 = 234.5612, number3 = -3.31132, number4 = -0.9132;
cout<<"Nubmer 1 correct upto 0 decimals "<<fixed<<setprecision(0)<<number1<<endl;
cout<<"Nubmer 2 correct upto 1 decimals "<<fixed<<setprecision(1)<<number2<<endl;
cout<<"Nubmer 3 correct upto 4 decimals "<<fixed<<setprecision(4)<<number3<<endl;
cout<<"Nubmer 4 correct upto 3 decimals "<<fixed<<setprecision(3)<<number4<<endl;
}
Nubmer 1 correct upto 0 decimals 0
Nubmer 2 correct upto 1 decimals 234.6
Nubmer 3 correct upto 4 decimals -3.3113
Nubmer 4 correct upto 3 decimals -0.913 | [
{
"code": null,
"e": 1309,
"s": 1187,
"text": "Precision of floating point numbers is the accuracy upto which a floating point number can hold the values after decimal."
},
{
"code": null,
"e": 1423,
"s": 1309,
"text": "For example 10/6 = 1.6666666... these have recurring decimals which can take infinite memory spaces to be stored."
},
{
"code": null,
"e": 1634,
"s": 1423,
"text": "So to avoid memory overflow in such cases the compiler set a precision limit to the number. For float values in C++ this precision is set to 6-7 digit after that if the decimal recurs it will discard the value."
},
{
"code": null,
"e": 1801,
"s": 1634,
"text": "So, to avoid any major losses when this discarding takes place there are methods and libraries that support the precision is float values. Here, we will discuss them,"
},
{
"code": null,
"e": 1920,
"s": 1801,
"text": "floor() function is round down function that round the number to nearest integer values which is less than the number."
},
{
"code": null,
"e": 2016,
"s": 1920,
"text": "It always returns an integer value which is one less than the integer part of the float number."
},
{
"code": null,
"e": 2032,
"s": 2016,
"text": "Library: math.h"
},
{
"code": null,
"e": 2043,
"s": 2032,
"text": " Live Demo"
},
{
"code": null,
"e": 2425,
"s": 2043,
"text": "#include<iostream>\n#include<math.h>\nusing namespace std;\nint main() {\n float number1 = 0.435 , number2 = 234.2342, number3 = -3.31132, number4 = -0.432;\n cout<<\"Values are : \\n\";\n cout<<\"Number 1 : \"<<floor(number1)<<endl;\n cout<<\"Number 2 : \"<<floor(number2)<<endl;\n cout<<\"Number 3 : \"<<floor(number3)<<endl;\n cout<<\"Number 4 : \"<<floor(number4)<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 2494,
"s": 2425,
"text": "Values are :\nNumber 1 : 0\nNumber 2 : 234\nNumber 3 : -4\nNumber 4 : -1"
},
{
"code": null,
"e": 2614,
"s": 2494,
"text": "ceil() function is rounding function that rounds the number to nearest integer values which is greater than the number."
},
{
"code": null,
"e": 2710,
"s": 2614,
"text": "It always returns an integer value which is one more than the integer part of the float number."
},
{
"code": null,
"e": 2726,
"s": 2710,
"text": "Library: math.h"
},
{
"code": null,
"e": 2737,
"s": 2726,
"text": " Live Demo"
},
{
"code": null,
"e": 3115,
"s": 2737,
"text": "#include<iostream>\n#include<math.h>\nusing namespace std;\nint main() {\n float number1 = 0.435 , number2 = 234.2342, number3 = -3.31132, number4 = -0.432;\n cout<<\"Values are : \\n\";\n cout<<\"Number 1 : \"<<ceil(number1)<<endl;\n cout<<\"Number 2 : \"<<ceil(number2)<<endl;\n cout<<\"Number 3 : \"<<ceil(number3)<<endl;\n cout<<\"Number 4 : \"<<ceil(number4)<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 3184,
"s": 3115,
"text": "Values are :\nNumber 1 : 1\nNumber 2 : 235\nNumber 3 : -3\nNumber 4 : -0"
},
{
"code": null,
"e": 3320,
"s": 3184,
"text": "round() function is rounding function that rounds the number to nearest integer values which can be greater or smaller than the number."
},
{
"code": null,
"e": 3422,
"s": 3320,
"text": "It always returns an integer value which can one more/less than the integer part of the float number."
},
{
"code": null,
"e": 3438,
"s": 3422,
"text": "Library: math.h"
},
{
"code": null,
"e": 3449,
"s": 3438,
"text": " Live Demo"
},
{
"code": null,
"e": 3828,
"s": 3449,
"text": "#include<iostream>\n#include<math.h>\nusing namespace std;\nint main() {\n float number1 = 0.435 , number2 = 234.5612, number3 = -3.31132, number4 = -0.9132;\n cout<<\"Values are : \\n\";\n cout<<\"Number 1 : \"<<ceil(number1)<<endl;\n cout<<\"Number 2 : \"<<ceil(number2)<<endl;\n cout<<\"Number 3 : \"<<ceil(number3)<<endl;\n cout<<\"Number 4 : \"<<ceil(number4)<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 3897,
"s": 3828,
"text": "Values are :\nNumber 1 : 1\nNumber 2 : 235\nNumber 3 : -3\nNumber 4 : -0"
},
{
"code": null,
"e": 4049,
"s": 3897,
"text": "The setprecision() function returns the value of flaot which is correct upto n decimal places. N is the parameter passed to the setprecission function."
},
{
"code": null,
"e": 4085,
"s": 4049,
"text": "For the functioning, it uses fixed."
},
{
"code": null,
"e": 4102,
"s": 4085,
"text": "Library: iomanip"
},
{
"code": null,
"e": 4113,
"s": 4102,
"text": " Live Demo"
},
{
"code": null,
"e": 4612,
"s": 4113,
"text": "#include<iostream>\n#include<iomanip>\nusing namespace std;\nint main() {\n float number1 = 0.435 , number2 = 234.5612, number3 = -3.31132, number4 = -0.9132;\n cout<<\"Nubmer 1 correct upto 0 decimals \"<<fixed<<setprecision(0)<<number1<<endl;\n cout<<\"Nubmer 2 correct upto 1 decimals \"<<fixed<<setprecision(1)<<number2<<endl;\n cout<<\"Nubmer 3 correct upto 4 decimals \"<<fixed<<setprecision(4)<<number3<<endl;\n cout<<\"Nubmer 4 correct upto 3 decimals \"<<fixed<<setprecision(3)<<number4<<endl;\n}"
},
{
"code": null,
"e": 4767,
"s": 4612,
"text": "Nubmer 1 correct upto 0 decimals 0\nNubmer 2 correct upto 1 decimals 234.6\nNubmer 3 correct upto 4 decimals -3.3113\nNubmer 4 correct upto 3 decimals -0.913"
}
] |
LocalDateTime compareTo() method in Java with Examples | 30 Nov, 2018
The compareTo() method of LocalDateTime class in Java is used to compare this date-time to the date-time passed as the parameter.
Syntax:
public int compareTo(ChronoLocalDateTime anotherDate)
Parameter: This method accepts a parameter anotherDate which specifies the other date-time to be compare to. It should not be null.
Returns: The function returns an integer value which is the comparator value after comparison.
Below programs illustrate the LocalDateTime.compareTo() method:
Program 1:
// Program to illustrate the compareTo() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDateTime dt1 = LocalDateTime .parse("2018-11-03T12:45:30"); // Prints the date System.out.println("Date 1: " + dt1); // Parses the date LocalDateTime dt2 = LocalDateTime .parse("2015-01-05T12:45:30"); // Prints the date System.out.println("Date 2: " + dt2); // Compares the date System.out.println("After comparison: " + dt2.compareTo(dt1)); }}
Date 1: 2018-11-03T12:45:30
Date 2: 2015-01-05T12:45:30
After comparison: -3
Program 2:
// Program to illustrate the compareTo() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDateTime dt1 = LocalDateTime .parse("2010-12-05T12:50:30"); // Prints the date System.out.println("Date 1: " + dt1); // Parses the date LocalDateTime dt2 = LocalDateTime .parse("2012-05-10T12:50:30"); // Prints the date System.out.println("Date 2: " + dt2); // Compares the date System.out.println("After comparison: " + dt2.compareTo(dt1)); }}
Date 1: 2010-12-05T12:50:30
Date 2: 2012-05-10T12:50:30
After comparison: 2
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#compareTo(java.time.chrono.ChronoLocalDateTime)
Java-Functions
Java-LocalDateTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Nov, 2018"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "The compareTo() method of LocalDateTime class in Java is used to compare this date-time to the date-time passed as the parameter."
},
{
"code": null,
"e": 166,
"s": 158,
"text": "Syntax:"
},
{
"code": null,
"e": 221,
"s": 166,
"text": "public int compareTo(ChronoLocalDateTime anotherDate)\n"
},
{
"code": null,
"e": 353,
"s": 221,
"text": "Parameter: This method accepts a parameter anotherDate which specifies the other date-time to be compare to. It should not be null."
},
{
"code": null,
"e": 448,
"s": 353,
"text": "Returns: The function returns an integer value which is the comparator value after comparison."
},
{
"code": null,
"e": 512,
"s": 448,
"text": "Below programs illustrate the LocalDateTime.compareTo() method:"
},
{
"code": null,
"e": 523,
"s": 512,
"text": "Program 1:"
},
{
"code": "// Program to illustrate the compareTo() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDateTime dt1 = LocalDateTime .parse(\"2018-11-03T12:45:30\"); // Prints the date System.out.println(\"Date 1: \" + dt1); // Parses the date LocalDateTime dt2 = LocalDateTime .parse(\"2015-01-05T12:45:30\"); // Prints the date System.out.println(\"Date 2: \" + dt2); // Compares the date System.out.println(\"After comparison: \" + dt2.compareTo(dt1)); }}",
"e": 1210,
"s": 523,
"text": null
},
{
"code": null,
"e": 1288,
"s": 1210,
"text": "Date 1: 2018-11-03T12:45:30\nDate 2: 2015-01-05T12:45:30\nAfter comparison: -3\n"
},
{
"code": null,
"e": 1299,
"s": 1288,
"text": "Program 2:"
},
{
"code": "// Program to illustrate the compareTo() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDateTime dt1 = LocalDateTime .parse(\"2010-12-05T12:50:30\"); // Prints the date System.out.println(\"Date 1: \" + dt1); // Parses the date LocalDateTime dt2 = LocalDateTime .parse(\"2012-05-10T12:50:30\"); // Prints the date System.out.println(\"Date 2: \" + dt2); // Compares the date System.out.println(\"After comparison: \" + dt2.compareTo(dt1)); }}",
"e": 1986,
"s": 1299,
"text": null
},
{
"code": null,
"e": 2063,
"s": 1986,
"text": "Date 1: 2010-12-05T12:50:30\nDate 2: 2012-05-10T12:50:30\nAfter comparison: 2\n"
},
{
"code": null,
"e": 2194,
"s": 2063,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#compareTo(java.time.chrono.ChronoLocalDateTime)"
},
{
"code": null,
"e": 2209,
"s": 2194,
"text": "Java-Functions"
},
{
"code": null,
"e": 2228,
"s": 2209,
"text": "Java-LocalDateTime"
},
{
"code": null,
"e": 2246,
"s": 2228,
"text": "Java-time package"
},
{
"code": null,
"e": 2251,
"s": 2246,
"text": "Java"
},
{
"code": null,
"e": 2256,
"s": 2251,
"text": "Java"
},
{
"code": null,
"e": 2354,
"s": 2256,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2405,
"s": 2354,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2436,
"s": 2405,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2455,
"s": 2436,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2485,
"s": 2455,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2500,
"s": 2485,
"text": "Stream In Java"
},
{
"code": null,
"e": 2518,
"s": 2500,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2538,
"s": 2518,
"text": "Collections in Java"
},
{
"code": null,
"e": 2562,
"s": 2538,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2594,
"s": 2562,
"text": "Multidimensional Arrays in Java"
}
] |
JavaScript Intl Methods | 27 Dec, 2021
Below is an example of the Intl method.
Example :
Javascript
<script>function func(){ // Original Array var arr = ['z', 's', 'l', 'm', 'c', 'a', 'b']; // Sorting Array var arr_sort = arr.sort(new Intl.Collator('en').compare) console.log(arr_sort);}func();</script>
Output:
['a', 'b', 'c', 'l', 'm', 's', 'z']
Intl Method: The Intl() method is used to format strings, numbers, dates, and times in local format with the help of constructors.
Syntax:
new Intl.constructors(locales, options);
Arguments:
locales argument: locales argument is used to determine the locale used in operation. locales may be :undefined: default locales are used.A locale: A locale is an identifier for the constructor to identify language or tags.A list of locales: It is a collection of a locale.
undefined: default locales are used.
A locale: A locale is an identifier for the constructor to identify language or tags.
A list of locales: It is a collection of a locale.
locales are divided by hyphens. Locales can be consists of :A language sub-tag.A region sub-tag.A subscript sub-tag.A private use extension syntax.One or more BCP 47 extension sequences.One or more variant sub-tag.
A language sub-tag.
A region sub-tag.
A subscript sub-tag.
A private use extension syntax.
One or more BCP 47 extension sequences.
One or more variant sub-tag.
Example : βhiβ: It is a language sub-tag for Hindi.βde-ATβ: The language tag for German and AT for the region tag for Austria.βzh-Hans-CNβ: Hans is the region tag for the china region.βen-emodengβ: en-emodeng is early modern English variant tag.
βhiβ: It is a language sub-tag for Hindi.
βde-ATβ: The language tag for German and AT for the region tag for Austria.
βzh-Hans-CNβ: Hans is the region tag for the china region.
βen-emodengβ: en-emodeng is early modern English variant tag.
Options arguments: The optionβs argument is an object with properties that vary with different constructors and functions. If the optionsβ argument is the undefined default value for all properties is used.
Example 1: Examples for a different constructor are provided below. In this example, Intl.Collator() create Intl.Collator object that helps to sort in language-sensitive sorting of any collection. Since we are sorting the array with the English language, so it is sorted in alphabetical order.
var l = new Intl.Collator('en').compare
console.log(['z', 'b', 'e', 'o', 'a'].sort(l));
Javascript
<script> // Javascript to illustrate Intl.Collator constructor function func() { // Creating object for which help in sorting var l = new Intl.Collator("en"); // Sorting array var array = ["z", "b", "e", "o", "a"]; var arr = array.sort(l.compare); console.log(arr); } func();</script>
Output:
['a', 'b', 'e', 'o', 'z']
Example 2: In this example, Intl.DateTimeFormat() constructor create an Intl.DateTimeFormat object that helps language-sensitive date-time formatting. Here sub-tag is βen-USβ so the date variable is the format in United Stateβs English.
const date = new Date(Date.UTC(2021, 06, 10, 10, 20, 30, 40));
console.log(new Intl.DateTimeFormat('en-US').format(date));
Javascript
<script> // Javascript to illustrate Intl.DateTimeFormat constructor function func() { // Creating Time variable const date = new Date(Date.UTC(2021, 06, 10, 10, 20, 30, 40)); // Creating object for which help in Formatting const ti = new Intl.DateTimeFormat("en-US"); // Formatting date const time = ti.format(date); console.log(time); } func();</script>
Output:
7/10/2021
Example 3: In this example, Intl.DisplayNames() constructor create an Intl.DisplayNames object that helps constructor in the translation of any language, region, and script display names. Here Intl translates βUNβ according to region based in English.
const rNames = new Intl.DisplayNames(['en'], { type: 'region' });
console.log(rNames.of('UN'));
Javascript
<script> // Javascript to illustrate Intl.DisplayNames constructor function func() { // Creating object for translation const rNames = new Intl.DisplayNames(["en"], { type: "region" }); // Translating into region language const a = rNames.of("UN"); console.log(a); } func();</script>
Output:
United Nations
Example 4: In this example, Intl.ListFormat() creates an intl.ListFormat object that help in list formatting. Here sub-tag is βenβ so it is in the English language and the style is long and the type in conjunction so the formatted list has some joining word.
const Names = ['Jack', 'Rahul', 'Bob'];
const format = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
console.log(format.format(Names));
Javascript
<script> // Javascript to illustrate Intl.ListFormat constructorfunction func(){ // Original list const Names = ['Jack', 'Rahul', 'Bob']; // Creating object for list formatting const format = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }); // Formatting list const list = format.format(Names); console.log(list);}func();</script>
Output:
Jack, Rahul, and Bob
Example 5: In this example, Intl.Locale() constructor creates a Locale identifier for region, language, and script. Here sub-tags are βen-USβ so it creates US English region language Locale identifier.
let us = new Intl.Locale('en-US');
console.log(us.baseName)
Javascript
<script> // Javascript to illustrate Intl.Locale // constructor function func() { // Creating locale Object identifier let us = new Intl.Locale("en-US"); // Printing baseName of identifier console.log(us.baseName); } func();</script>
Output:
en-US
Example 6: In this example, Intl.NumberFormat() constructor create Intl.NumberFormat object which helps in the formatting of numbers. The style is decimal, so the number is the format in decimal format.
let amount = 6000000;
let k = new Intl.NumberFormat('en-US', {style: 'decimal'});
console.log(k.format(amount))
Javascript
<script> // Javascript to illustrate Intl.NumberFormat constructor function func() { // Original Number let amount = 6000000; // Creating object to format Number let k = new Intl.NumberFormat("en-US", { style: "decimal" }); // Formatting Number let l = k.format(amount); console.log(l); } func();</script>
Output:
6,000,000
Example 7: In this example, the Intl.PluralRules() constructor creates an object that helps in plural sensitive formatting. It returns a string that indicates the plural rule used for number.
let l = new Intl.PluralRules().select(18);
console.log(l)
Javascript
<script> // Javascript to illustrate // Intl.PluralRules constructor function func() { // Creating object for plural-sensitive // formatting of Number let l = new Intl.PluralRules(); // selecting formatting for 18 let k = l.select(18); console.log(k); } func();</script>
Output:
other
Example 8: In this example, Intl.RelativeTimeFormat() constructor create an object Intl.RelativeTimeFormat helps relative time formatting. It is formatted according to the sub-tag provided to the constructor.
const relative = new Intl.RelativeTimeFormat('en', { style: 'narrow' });
console.log(relative.format(5, 'hours'));
Javascript
<script> // Javascript to illustrate Intl.RelativeTimeFormat constructorfunction func(){ // Creating object for formatting relative time const relative = new Intl.RelativeTimeFormat('en', { style: 'narrow' }); // Formatting relative time for 5 value and hours unit let l =relative.format(5, 'hours'); console.log(l)}func();</script>
Output:
in 5 hr.
kashishsoda
simmytarika5
sagartomar9927
simranarora5sos
JavaScript-Intl
JavaScript-Methods
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 68,
"s": 28,
"text": "Below is an example of the Intl method."
},
{
"code": null,
"e": 79,
"s": 68,
"text": "Example : "
},
{
"code": null,
"e": 90,
"s": 79,
"text": "Javascript"
},
{
"code": "<script>function func(){ // Original Array var arr = ['z', 's', 'l', 'm', 'c', 'a', 'b']; // Sorting Array var arr_sort = arr.sort(new Intl.Collator('en').compare) console.log(arr_sort);}func();</script>",
"e": 301,
"s": 90,
"text": null
},
{
"code": null,
"e": 310,
"s": 301,
"text": "Output: "
},
{
"code": null,
"e": 346,
"s": 310,
"text": "['a', 'b', 'c', 'l', 'm', 's', 'z']"
},
{
"code": null,
"e": 477,
"s": 346,
"text": "Intl Method: The Intl() method is used to format strings, numbers, dates, and times in local format with the help of constructors."
},
{
"code": null,
"e": 485,
"s": 477,
"text": "Syntax:"
},
{
"code": null,
"e": 526,
"s": 485,
"text": "new Intl.constructors(locales, options);"
},
{
"code": null,
"e": 539,
"s": 526,
"text": "Arguments: "
},
{
"code": null,
"e": 813,
"s": 539,
"text": "locales argument: locales argument is used to determine the locale used in operation. locales may be :undefined: default locales are used.A locale: A locale is an identifier for the constructor to identify language or tags.A list of locales: It is a collection of a locale."
},
{
"code": null,
"e": 850,
"s": 813,
"text": "undefined: default locales are used."
},
{
"code": null,
"e": 936,
"s": 850,
"text": "A locale: A locale is an identifier for the constructor to identify language or tags."
},
{
"code": null,
"e": 987,
"s": 936,
"text": "A list of locales: It is a collection of a locale."
},
{
"code": null,
"e": 1202,
"s": 987,
"text": "locales are divided by hyphens. Locales can be consists of :A language sub-tag.A region sub-tag.A subscript sub-tag.A private use extension syntax.One or more BCP 47 extension sequences.One or more variant sub-tag."
},
{
"code": null,
"e": 1222,
"s": 1202,
"text": "A language sub-tag."
},
{
"code": null,
"e": 1240,
"s": 1222,
"text": "A region sub-tag."
},
{
"code": null,
"e": 1261,
"s": 1240,
"text": "A subscript sub-tag."
},
{
"code": null,
"e": 1293,
"s": 1261,
"text": "A private use extension syntax."
},
{
"code": null,
"e": 1333,
"s": 1293,
"text": "One or more BCP 47 extension sequences."
},
{
"code": null,
"e": 1362,
"s": 1333,
"text": "One or more variant sub-tag."
},
{
"code": null,
"e": 1608,
"s": 1362,
"text": "Example : βhiβ: It is a language sub-tag for Hindi.βde-ATβ: The language tag for German and AT for the region tag for Austria.βzh-Hans-CNβ: Hans is the region tag for the china region.βen-emodengβ: en-emodeng is early modern English variant tag."
},
{
"code": null,
"e": 1650,
"s": 1608,
"text": "βhiβ: It is a language sub-tag for Hindi."
},
{
"code": null,
"e": 1726,
"s": 1650,
"text": "βde-ATβ: The language tag for German and AT for the region tag for Austria."
},
{
"code": null,
"e": 1785,
"s": 1726,
"text": "βzh-Hans-CNβ: Hans is the region tag for the china region."
},
{
"code": null,
"e": 1847,
"s": 1785,
"text": "βen-emodengβ: en-emodeng is early modern English variant tag."
},
{
"code": null,
"e": 2054,
"s": 1847,
"text": "Options arguments: The optionβs argument is an object with properties that vary with different constructors and functions. If the optionsβ argument is the undefined default value for all properties is used."
},
{
"code": null,
"e": 2349,
"s": 2054,
"text": "Example 1: Examples for a different constructor are provided below. In this example, Intl.Collator() create Intl.Collator object that helps to sort in language-sensitive sorting of any collection. Since we are sorting the array with the English language, so it is sorted in alphabetical order."
},
{
"code": null,
"e": 2438,
"s": 2349,
"text": "var l = new Intl.Collator('en').compare\nconsole.log(['z', 'b', 'e', 'o', 'a'].sort(l)); "
},
{
"code": null,
"e": 2449,
"s": 2438,
"text": "Javascript"
},
{
"code": "<script> // Javascript to illustrate Intl.Collator constructor function func() { // Creating object for which help in sorting var l = new Intl.Collator(\"en\"); // Sorting array var array = [\"z\", \"b\", \"e\", \"o\", \"a\"]; var arr = array.sort(l.compare); console.log(arr); } func();</script>",
"e": 2765,
"s": 2449,
"text": null
},
{
"code": null,
"e": 2773,
"s": 2765,
"text": "Output:"
},
{
"code": null,
"e": 2799,
"s": 2773,
"text": "['a', 'b', 'e', 'o', 'z']"
},
{
"code": null,
"e": 3037,
"s": 2799,
"text": "Example 2: In this example, Intl.DateTimeFormat() constructor create an Intl.DateTimeFormat object that helps language-sensitive date-time formatting. Here sub-tag is βen-USβ so the date variable is the format in United Stateβs English. "
},
{
"code": null,
"e": 3160,
"s": 3037,
"text": "const date = new Date(Date.UTC(2021, 06, 10, 10, 20, 30, 40));\nconsole.log(new Intl.DateTimeFormat('en-US').format(date));"
},
{
"code": null,
"e": 3171,
"s": 3160,
"text": "Javascript"
},
{
"code": "<script> // Javascript to illustrate Intl.DateTimeFormat constructor function func() { // Creating Time variable const date = new Date(Date.UTC(2021, 06, 10, 10, 20, 30, 40)); // Creating object for which help in Formatting const ti = new Intl.DateTimeFormat(\"en-US\"); // Formatting date const time = ti.format(date); console.log(time); } func();</script>",
"e": 3566,
"s": 3171,
"text": null
},
{
"code": null,
"e": 3575,
"s": 3566,
"text": "Output: "
},
{
"code": null,
"e": 3585,
"s": 3575,
"text": "7/10/2021"
},
{
"code": null,
"e": 3837,
"s": 3585,
"text": "Example 3: In this example, Intl.DisplayNames() constructor create an Intl.DisplayNames object that helps constructor in the translation of any language, region, and script display names. Here Intl translates βUNβ according to region based in English."
},
{
"code": null,
"e": 3933,
"s": 3837,
"text": "const rNames = new Intl.DisplayNames(['en'], { type: 'region' });\nconsole.log(rNames.of('UN'));"
},
{
"code": null,
"e": 3944,
"s": 3933,
"text": "Javascript"
},
{
"code": "<script> // Javascript to illustrate Intl.DisplayNames constructor function func() { // Creating object for translation const rNames = new Intl.DisplayNames([\"en\"], { type: \"region\" }); // Translating into region language const a = rNames.of(\"UN\"); console.log(a); } func();</script>",
"e": 4256,
"s": 3944,
"text": null
},
{
"code": null,
"e": 4265,
"s": 4256,
"text": "Output: "
},
{
"code": null,
"e": 4280,
"s": 4265,
"text": "United Nations"
},
{
"code": null,
"e": 4539,
"s": 4280,
"text": "Example 4: In this example, Intl.ListFormat() creates an intl.ListFormat object that help in list formatting. Here sub-tag is βenβ so it is in the English language and the style is long and the type in conjunction so the formatted list has some joining word."
},
{
"code": null,
"e": 4696,
"s": 4539,
"text": "const Names = ['Jack', 'Rahul', 'Bob'];\nconst format = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });\nconsole.log(format.format(Names));"
},
{
"code": null,
"e": 4707,
"s": 4696,
"text": "Javascript"
},
{
"code": "<script> // Javascript to illustrate Intl.ListFormat constructorfunction func(){ // Original list const Names = ['Jack', 'Rahul', 'Bob']; // Creating object for list formatting const format = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }); // Formatting list const list = format.format(Names); console.log(list);}func();</script>",
"e": 5069,
"s": 4707,
"text": null
},
{
"code": null,
"e": 5078,
"s": 5069,
"text": "Output: "
},
{
"code": null,
"e": 5099,
"s": 5078,
"text": "Jack, Rahul, and Bob"
},
{
"code": null,
"e": 5301,
"s": 5099,
"text": "Example 5: In this example, Intl.Locale() constructor creates a Locale identifier for region, language, and script. Here sub-tags are βen-USβ so it creates US English region language Locale identifier."
},
{
"code": null,
"e": 5361,
"s": 5301,
"text": "let us = new Intl.Locale('en-US');\nconsole.log(us.baseName)"
},
{
"code": null,
"e": 5372,
"s": 5361,
"text": "Javascript"
},
{
"code": "<script> // Javascript to illustrate Intl.Locale // constructor function func() { // Creating locale Object identifier let us = new Intl.Locale(\"en-US\"); // Printing baseName of identifier console.log(us.baseName); } func();</script>",
"e": 5632,
"s": 5372,
"text": null
},
{
"code": null,
"e": 5640,
"s": 5632,
"text": "Output:"
},
{
"code": null,
"e": 5647,
"s": 5640,
"text": "en-US "
},
{
"code": null,
"e": 5850,
"s": 5647,
"text": "Example 6: In this example, Intl.NumberFormat() constructor create Intl.NumberFormat object which helps in the formatting of numbers. The style is decimal, so the number is the format in decimal format."
},
{
"code": null,
"e": 5962,
"s": 5850,
"text": "let amount = 6000000;\nlet k = new Intl.NumberFormat('en-US', {style: 'decimal'});\nconsole.log(k.format(amount))"
},
{
"code": null,
"e": 5973,
"s": 5962,
"text": "Javascript"
},
{
"code": "<script> // Javascript to illustrate Intl.NumberFormat constructor function func() { // Original Number let amount = 6000000; // Creating object to format Number let k = new Intl.NumberFormat(\"en-US\", { style: \"decimal\" }); // Formatting Number let l = k.format(amount); console.log(l); } func();</script>",
"e": 6318,
"s": 5973,
"text": null
},
{
"code": null,
"e": 6327,
"s": 6318,
"text": "Output: "
},
{
"code": null,
"e": 6337,
"s": 6327,
"text": "6,000,000"
},
{
"code": null,
"e": 6529,
"s": 6337,
"text": "Example 7: In this example, the Intl.PluralRules() constructor creates an object that helps in plural sensitive formatting. It returns a string that indicates the plural rule used for number."
},
{
"code": null,
"e": 6587,
"s": 6529,
"text": "let l = new Intl.PluralRules().select(18);\nconsole.log(l)"
},
{
"code": null,
"e": 6598,
"s": 6587,
"text": "Javascript"
},
{
"code": "<script> // Javascript to illustrate // Intl.PluralRules constructor function func() { // Creating object for plural-sensitive // formatting of Number let l = new Intl.PluralRules(); // selecting formatting for 18 let k = l.select(18); console.log(k); } func();</script>",
"e": 6901,
"s": 6598,
"text": null
},
{
"code": null,
"e": 6909,
"s": 6901,
"text": "Output:"
},
{
"code": null,
"e": 6915,
"s": 6909,
"text": "other"
},
{
"code": null,
"e": 7125,
"s": 6915,
"text": "Example 8: In this example, Intl.RelativeTimeFormat() constructor create an object Intl.RelativeTimeFormat helps relative time formatting. It is formatted according to the sub-tag provided to the constructor. "
},
{
"code": null,
"e": 7240,
"s": 7125,
"text": "const relative = new Intl.RelativeTimeFormat('en', { style: 'narrow' });\nconsole.log(relative.format(5, 'hours'));"
},
{
"code": null,
"e": 7251,
"s": 7240,
"text": "Javascript"
},
{
"code": "<script> // Javascript to illustrate Intl.RelativeTimeFormat constructorfunction func(){ // Creating object for formatting relative time const relative = new Intl.RelativeTimeFormat('en', { style: 'narrow' }); // Formatting relative time for 5 value and hours unit let l =relative.format(5, 'hours'); console.log(l)}func();</script>",
"e": 7591,
"s": 7251,
"text": null
},
{
"code": null,
"e": 7599,
"s": 7591,
"text": "Output:"
},
{
"code": null,
"e": 7608,
"s": 7599,
"text": "in 5 hr."
},
{
"code": null,
"e": 7620,
"s": 7608,
"text": "kashishsoda"
},
{
"code": null,
"e": 7633,
"s": 7620,
"text": "simmytarika5"
},
{
"code": null,
"e": 7648,
"s": 7633,
"text": "sagartomar9927"
},
{
"code": null,
"e": 7664,
"s": 7648,
"text": "simranarora5sos"
},
{
"code": null,
"e": 7680,
"s": 7664,
"text": "JavaScript-Intl"
},
{
"code": null,
"e": 7699,
"s": 7680,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 7706,
"s": 7699,
"text": "Picked"
},
{
"code": null,
"e": 7717,
"s": 7706,
"text": "JavaScript"
},
{
"code": null,
"e": 7734,
"s": 7717,
"text": "Web Technologies"
},
{
"code": null,
"e": 7832,
"s": 7734,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7893,
"s": 7832,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 7933,
"s": 7893,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 7975,
"s": 7933,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 8016,
"s": 7975,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 8038,
"s": 8016,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 8071,
"s": 8038,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 8133,
"s": 8071,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 8194,
"s": 8133,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 8244,
"s": 8194,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to style social media buttons with CSS? | Following is the code to style social media buttons with CSS β
Live Demo
<!DOCTYPE html>
<html>
<head>
<link
href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
rel="stylesheet"
integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
crossorigin="anonymous"
/>
<style>
button {
margin: 0px;
border-radius: 50%;
width: 120px;
height: 120px;
border: none;
padding: 15px;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
font-weight: bold;
font-size: 40px;
border:1px solid black;
}
button:nth-of-type(1){
margin-left: 40%;
}
button:hover {
background: black;
box-shadow: 5px 10px 18px rgb(20, 20, 20);
}
</style>
</head>
<body>
<h1 style="text-align: center;">Social Media Buttons Example</h1>
<button><i class="fa fa-facebook-f" style="color:#3B5998"></i></button>
<button><i class="fa fa-hashtag" style="color:#55ACEE"></i></button>
<button><i class="fa fa-linkedin" style="color:#007bb5"></i></button>
</body>
</html>
The above code will produce the following output β
On hovering above any of the icons β | [
{
"code": null,
"e": 1250,
"s": 1187,
"text": "Following is the code to style social media buttons with CSS β"
},
{
"code": null,
"e": 1261,
"s": 1250,
"text": " Live Demo"
},
{
"code": null,
"e": 2221,
"s": 1261,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<link\nhref=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\"\nrel=\"stylesheet\"\nintegrity=\"sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN\"\ncrossorigin=\"anonymous\"\n/>\n<style>\nbutton {\n margin: 0px;\n border-radius: 50%;\n width: 120px;\n height: 120px;\n border: none;\n padding: 15px;\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n font-weight: bold;\n font-size: 40px;\n border:1px solid black;\n}\nbutton:nth-of-type(1){\n margin-left: 40%;\n}\nbutton:hover {\n background: black;\n box-shadow: 5px 10px 18px rgb(20, 20, 20);\n}\n</style>\n</head>\n<body>\n<h1 style=\"text-align: center;\">Social Media Buttons Example</h1>\n<button><i class=\"fa fa-facebook-f\" style=\"color:#3B5998\"></i></button>\n<button><i class=\"fa fa-hashtag\" style=\"color:#55ACEE\"></i></button>\n<button><i class=\"fa fa-linkedin\" style=\"color:#007bb5\"></i></button>\n</body>\n</html>"
},
{
"code": null,
"e": 2272,
"s": 2221,
"text": "The above code will produce the following output β"
},
{
"code": null,
"e": 2309,
"s": 2272,
"text": "On hovering above any of the icons β"
}
] |
Majority Element | Practice | GeeksforGeeks | Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.
Example 1:
Input:
N = 3
A[] = {1,2,3}
Output:
-1
Explanation:
Since, each element in
{1,2,3} appears only once so there
is no majority element.
Example 2:
Input:
N = 5
A[] = {3,1,3,3,2}
Output:
3
Explanation:
Since, 3 is present more
than N/2 times, so it is
the majority element.
Your Task:
The task is to complete the function majorityElement() which returns the majority element in the array. If no majority exists, return -1.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 β€ N β€ 107
0 β€ Ai β€ 106
+1
itsupk2 hours ago
Moore's Voting Algorithm:
int majorityElement(int arr[], int size)
{
int candidate=-1,vote=0;
for(int i=0;i<size;i++)
{
if(vote==0)
{
candidate=arr[i];
vote=1;
}
else if(arr[i]!=candidate)
vote--;
else vote++;
}
int cnt=0;
for(int i=0;i<size;i++)
{
if(arr[i]==candidate)
cnt++;
}
return cnt>(size/2)?candidate:-1;
}
-2
btwitssahil8 hours ago
int majorityElement(int a[], int size)
{
// your code here
int num;
unordered_map<int , int> m;
for(int i=0; i<size; i++){
m[a[i]]++;
}
for(auto i : m){
if(i.second > size/2){
return i.first;
}
}
return -1;
}
0
kaushaldeokar12 hours ago
int majorityElement(int a[], int n) { int maj=0,ct=1; for(int i=1;i<n;i++){ if(a[maj]==a[i])ct++; else ct--; if(ct==0){ maj=i; ct=1; } } ct=0; int cand=a[maj]; for(int i=0;i<n;i++)if(a[i]==cand)ct++; if(ct>n/2)return a[maj]; return -1; }
0
gitansh18saharan2 days ago
JAVA
class Solution{ static int majorityElement(int a[], int size) { // your code here int ans =0; int count =1; for(int i =0;i<a.length;i++){ if(a[ans] == a[i]){ count++; } else{ count--; } if(count == 0){ ans =i; count=1; } } // to check int c=0; for(int i =0 ; i< a.length ;i++){ if(a[ans]==a[i]){ c++; } } if(c > size/2 ){ return a[ans]; } else{ return -1; } }}
-3
soumyajitbiswas122 days ago
class Solution{ public: // Function to find majority element in the array // a: input array // size: size of input array int majorityElement(int a[], int size) { int c=size/2; unordered_map<int, int> mp; for(int i=0; i<size; i++) { mp[a[i]]++; } unordered_map<int, int>::iterator itr; for(itr=mp.begin(); itr!=mp.end(); itr++) { if(itr->second > c) return itr->first; } return -1; }};
+1
shikharkannojia22222 days ago
Please OPTIMIZE THIS CODE
C++
int max=-1; int count=0; int ans=0; for(int i=0;i<=size;i++){ count=0; for(int j=i+1;j<=size;j++){ if(a[i]==a[j]){ count++; } if(count>max && count>1 && count>=size/2){ max=count; ans=a[i]; } } }if(ans==0){ ans=-1; if(size==1){ ans=a[0]; } } return ans;
-3
ujjwaljaiswal90903 days ago
in cpp
int majorityElement(int a[], int size) { // your code here unordered_map<int,int>mp; for(int i=0;i<size;i++){ mp[a[i]]++; } for(int i=0;i<size;i++){ if(mp[a[i]]>size/2) return a[i]; } return -1; }
0
rushi21263 days ago
Simple Java Solution:-
static int majorityElement(int a[], int size) { // your code here int count=1; int maxIndex = 0; for(int i=1; i<size; i++) { if(a[i]==a[maxIndex]) { count++; } else { count--; } if(count==0) { maxIndex = i; count=1; } } int candidate = a[maxIndex]; int countCand = 0; for(int i=0; i<size; i++) { if(a[i]==candidate) { countCand++; } } if(countCand>size/2) { return candidate; } else { return -1; } }
-3
sakshisuman983 days ago
V.EASY C++ SOLUTION USING HASHING
int majorityElement(int arr[], int n)
{
unordered_map<int,int>majority;
for(int i=0;i<n;i++)
{
majority[arr[i]]++;
}
for(int i=0;i<n;i++)
{
if(majority[arr[i]]>n/2)
{
return arr[i];
}
}
return -1;
}
-3
aashishreddy853 days ago
int majorityElement(int a[], int size) { unordered_map<int,int> m; for(int i=0; i<size; i++) m[a[i]]++; for(auto e : m){ if(e.second>size/2) return e.first; } return -1; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 416,
"s": 238,
"text": "Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.\n "
},
{
"code": null,
"e": 427,
"s": 416,
"text": "Example 1:"
},
{
"code": null,
"e": 565,
"s": 427,
"text": "Input:\nN = 3 \nA[] = {1,2,3} \nOutput:\n-1\nExplanation:\nSince, each element in \n{1,2,3} appears only once so there \nis no majority element.\n"
},
{
"code": null,
"e": 576,
"s": 565,
"text": "Example 2:"
},
{
"code": null,
"e": 706,
"s": 576,
"text": "Input:\nN = 5 \nA[] = {3,1,3,3,2} \nOutput:\n3\nExplanation:\nSince, 3 is present more\nthan N/2 times, so it is \nthe majority element.\n"
},
{
"code": null,
"e": 858,
"s": 706,
"text": "\nYour Task:\nThe task is to complete the function majorityElement() which returns the majority element in the array. If no majority exists, return -1.\n "
},
{
"code": null,
"e": 924,
"s": 858,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n "
},
{
"code": null,
"e": 962,
"s": 924,
"text": "Constraints:\n1 β€ N β€ 107\n0 β€ Ai β€ 106"
},
{
"code": null,
"e": 965,
"s": 962,
"text": "+1"
},
{
"code": null,
"e": 983,
"s": 965,
"text": "itsupk2 hours ago"
},
{
"code": null,
"e": 1009,
"s": 983,
"text": "Moore's Voting Algorithm:"
},
{
"code": null,
"e": 1448,
"s": 1009,
"text": "int majorityElement(int arr[], int size)\n{\n int candidate=-1,vote=0;\n \n for(int i=0;i<size;i++)\n {\n if(vote==0)\n {\n candidate=arr[i];\n vote=1;\n }\n else if(arr[i]!=candidate)\n vote--;\n else vote++;\n }\n \n int cnt=0;\n \n for(int i=0;i<size;i++)\n {\n if(arr[i]==candidate)\n cnt++;\n }\n return cnt>(size/2)?candidate:-1;\n \n \n}"
},
{
"code": null,
"e": 1451,
"s": 1448,
"text": "-2"
},
{
"code": null,
"e": 1474,
"s": 1451,
"text": "btwitssahil8 hours ago"
},
{
"code": null,
"e": 1832,
"s": 1474,
"text": "int majorityElement(int a[], int size)\n {\n // your code here\n int num;\n unordered_map<int , int> m;\n for(int i=0; i<size; i++){\n m[a[i]]++;\n }\n for(auto i : m){\n if(i.second > size/2){\n \n return i.first;\n }\n }\n return -1;\n \n }"
},
{
"code": null,
"e": 1834,
"s": 1832,
"text": "0"
},
{
"code": null,
"e": 1860,
"s": 1834,
"text": "kaushaldeokar12 hours ago"
},
{
"code": null,
"e": 2221,
"s": 1860,
"text": "int majorityElement(int a[], int n) { int maj=0,ct=1; for(int i=1;i<n;i++){ if(a[maj]==a[i])ct++; else ct--; if(ct==0){ maj=i; ct=1; } } ct=0; int cand=a[maj]; for(int i=0;i<n;i++)if(a[i]==cand)ct++; if(ct>n/2)return a[maj]; return -1; }"
},
{
"code": null,
"e": 2223,
"s": 2221,
"text": "0"
},
{
"code": null,
"e": 2250,
"s": 2223,
"text": "gitansh18saharan2 days ago"
},
{
"code": null,
"e": 2255,
"s": 2250,
"text": "JAVA"
},
{
"code": null,
"e": 2916,
"s": 2257,
"text": "class Solution{ static int majorityElement(int a[], int size) { // your code here int ans =0; int count =1; for(int i =0;i<a.length;i++){ if(a[ans] == a[i]){ count++; } else{ count--; } if(count == 0){ ans =i; count=1; } } // to check int c=0; for(int i =0 ; i< a.length ;i++){ if(a[ans]==a[i]){ c++; } } if(c > size/2 ){ return a[ans]; } else{ return -1; } }}"
},
{
"code": null,
"e": 2919,
"s": 2916,
"text": "-3"
},
{
"code": null,
"e": 2947,
"s": 2919,
"text": "soumyajitbiswas122 days ago"
},
{
"code": null,
"e": 3403,
"s": 2947,
"text": "class Solution{ public: // Function to find majority element in the array // a: input array // size: size of input array int majorityElement(int a[], int size) { int c=size/2; unordered_map<int, int> mp; for(int i=0; i<size; i++) { mp[a[i]]++; } unordered_map<int, int>::iterator itr; for(itr=mp.begin(); itr!=mp.end(); itr++) { if(itr->second > c) return itr->first; } return -1; }};"
},
{
"code": null,
"e": 3406,
"s": 3403,
"text": "+1"
},
{
"code": null,
"e": 3436,
"s": 3406,
"text": "shikharkannojia22222 days ago"
},
{
"code": null,
"e": 3462,
"s": 3436,
"text": "Please OPTIMIZE THIS CODE"
},
{
"code": null,
"e": 3467,
"s": 3462,
"text": "C++ "
},
{
"code": null,
"e": 3959,
"s": 3469,
"text": "int max=-1; int count=0; int ans=0; for(int i=0;i<=size;i++){ count=0; for(int j=i+1;j<=size;j++){ if(a[i]==a[j]){ count++; } if(count>max && count>1 && count>=size/2){ max=count; ans=a[i]; } } }if(ans==0){ ans=-1; if(size==1){ ans=a[0]; } } return ans; "
},
{
"code": null,
"e": 3962,
"s": 3959,
"text": "-3"
},
{
"code": null,
"e": 3990,
"s": 3962,
"text": "ujjwaljaiswal90903 days ago"
},
{
"code": null,
"e": 3997,
"s": 3990,
"text": "in cpp"
},
{
"code": null,
"e": 4259,
"s": 3999,
"text": "int majorityElement(int a[], int size) { // your code here unordered_map<int,int>mp; for(int i=0;i<size;i++){ mp[a[i]]++; } for(int i=0;i<size;i++){ if(mp[a[i]]>size/2) return a[i]; } return -1; }"
},
{
"code": null,
"e": 4261,
"s": 4259,
"text": "0"
},
{
"code": null,
"e": 4281,
"s": 4261,
"text": "rushi21263 days ago"
},
{
"code": null,
"e": 4304,
"s": 4281,
"text": "Simple Java Solution:-"
},
{
"code": null,
"e": 5054,
"s": 4306,
"text": "static int majorityElement(int a[], int size) { // your code here int count=1; int maxIndex = 0; for(int i=1; i<size; i++) { if(a[i]==a[maxIndex]) { count++; } else { count--; } if(count==0) { maxIndex = i; count=1; } } int candidate = a[maxIndex]; int countCand = 0; for(int i=0; i<size; i++) { if(a[i]==candidate) { countCand++; } } if(countCand>size/2) { return candidate; } else { return -1; } }"
},
{
"code": null,
"e": 5057,
"s": 5054,
"text": "-3"
},
{
"code": null,
"e": 5081,
"s": 5057,
"text": "sakshisuman983 days ago"
},
{
"code": null,
"e": 5115,
"s": 5081,
"text": "V.EASY C++ SOLUTION USING HASHING"
},
{
"code": null,
"e": 5470,
"s": 5115,
"text": " int majorityElement(int arr[], int n)\n {\n \n unordered_map<int,int>majority;\n for(int i=0;i<n;i++)\n {\n majority[arr[i]]++;\n }\n for(int i=0;i<n;i++)\n {\n if(majority[arr[i]]>n/2)\n {\n return arr[i];\n }\n }\n \n return -1; \n }"
},
{
"code": null,
"e": 5473,
"s": 5470,
"text": "-3"
},
{
"code": null,
"e": 5498,
"s": 5473,
"text": "aashishreddy853 days ago"
},
{
"code": null,
"e": 5746,
"s": 5498,
"text": "int majorityElement(int a[], int size) { unordered_map<int,int> m; for(int i=0; i<size; i++) m[a[i]]++; for(auto e : m){ if(e.second>size/2) return e.first; } return -1; }"
},
{
"code": null,
"e": 5892,
"s": 5746,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5928,
"s": 5892,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5938,
"s": 5928,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5948,
"s": 5938,
"text": "\nContest\n"
},
{
"code": null,
"e": 6011,
"s": 5948,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6196,
"s": 6011,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6480,
"s": 6196,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 6626,
"s": 6480,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 6703,
"s": 6626,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 6744,
"s": 6703,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 6772,
"s": 6744,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 6843,
"s": 6772,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 7030,
"s": 6843,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
How to Sort a Set of Values in Python? | 16 Jun, 2021
Sorting means arranging the set of values in either an increasing or decreasing manner. There are various methods to sort values in Python. We can store a set or group of values using various data structures such as list, tuples, dictionaries which depends on the data we are storing. So, in this article, we will discuss some methods and criteria to sort the data in Python.
This is a pre-defined method in python which sorts any kind of object.
Syntax:
sorted(iterable, key, reverse)
In this method, we pass 3 parameters, out of which 2 (key and reverse) are optional and the first parameter i.e. iterable can be any iterable object This method returns a sorted list but does not change the original data structure.
Example 1:
Python3
# Listlist_of_items = ['g', 'e', 'e', 'k', 's']print(sorted(list_of_items)) # Tupletuple_of_items = ('g', 'e', 'e', 'k', 's')print(sorted(tuple_of_items)) # String-sorted based on ASCII# translationsstring = "geeks"print(sorted(string)) # Dictionarydictionary = {'g': 1, 'e': 2, 'k': 3, 's': 4}print(sorted(dictionary)) # Setset_of_values = {'g', 'e', 'e', 'k', 's'}print(sorted(set_of_values)) # Frozen Setfrozen_set = frozenset(('g', 'e', 'e', 'k', 's'))print(sorted(frozen_set))
['e', 'e', 'g', 'k', 's']
['e', 'e', 'g', 'k', 's']
['e', 'e', 'g', 'k', 's']
['e', 'g', 'k', 's']
['e', 'g', 'k', 's']
['e', 'g', 'k', 's']
Example 2:
Using predefined function as key-parameter. So the second parameter i.e. key is used to sort the given data structure by some predefined function such as len() or some user-defined function. It sorts the values in the data structure based on the function passed to the key parameter.
Python3
# using key parameter with pre-defined# function i.e. len() list_of_items = ["apple", "ball", "cat", "dog"] print("Sorting without key parameter:", sorted(list_of_items))print("Sorting with len as key parameter:", sorted(list_of_items, key=len))
Sorting without key parameter: ['apple', 'ball', 'cat', 'dog']
Sorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']
Example 3:
Using the user-defined function for the key parameter.
Python3
# using key parameter with user-defined# function i.e. by_name# using key parameter with user-defined# function i.e. by_marks # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [("Ramesh",56),("Reka",54),("Lasya",32),("Amar",89)] # defining a user-defined function which returns# the first item(name)def by_name(ele): return ele[0] # defining a user-defined function which returns# the second item(marks)def by_marks(ele): return ele[1] print("Sorting without key parameter:", sorted(list_of_items)) print("Sorting with by_name as key parameter:", sorted(list_of_items, key=by_name)) print("Sorting with by_marks as key parameter:", sorted(list_of_items, key=by_marks))
Output
Sorting without key parameter: [(βAmarβ, 89), (βLasyaβ, 32), (βRameshβ, 56), (βRekaβ, 54)]
Sorting with by_name as key parameter: [(βAmarβ, 89), (βLasyaβ, 32), (βRameshβ, 56), (βRekaβ, 54)]
Sorting with by_marks as key parameter: [(βLasyaβ, 32), (βRekaβ, 54), (βRameshβ, 56), (βAmarβ, 89)]
Example 4:
So the 3rd parameter is reverse which is used to sort the iterable in descending or decreasing order.
Python3
# using key parameter reverse list_of_items = ["geeks","for","geeks"] print("Sorting without key parameter:", sorted(list_of_items)) print("Sorting with len as key parameter:", sorted(list_of_items, reverse=True))
Sorting without key parameter: ['for', 'geeks', 'geeks']
Sorting with len as key parameter: ['geeks', 'geeks', 'for']
Example 5:
Using all the three parameters
Python3
# using by_name and by_marks as key parameter# and making reverse parameter true # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [("Ramesh", 56), ("Reka", 54), ("Lasya", 32), ("Amar", 89)] # defining a user-defined function which# returns the first item(name)def by_name(ele): return ele[0] # defining a user-defined function which# returns the second item(marks)def by_marks(ele): return ele[1] print("Sorting without key and reverse:", sorted(list_of_items)) print("Sorting with by_name as key parameter and reverse parameter as False:", sorted(list_of_items, key=by_name, reverse=False))print("Sorting with by_name as key parameter and reverse parameter as True:", sorted(list_of_items, key=by_name, reverse=True)) print("Sorting with by_marks as key parameter and reverse parameter as False:", sorted(list_of_items, key=by_marks, reverse=False))print("Sorting with by_marks as key parameter and reverse parameter as True:", sorted(list_of_items, key=by_marks, reverse=True))
Output
Sorting without key and reverse: [(βAmarβ, 89), (βLasyaβ, 32), (βRameshβ, 56), (βRekaβ, 54)]
Sorting with by_name as key parameter and reverse parameter as False: [(βAmarβ, 89), (βLasyaβ, 32), (βRameshβ, 56), (βRekaβ, 54)]
Sorting with by_name as key parameter and reverse parameter as True: [(βRekaβ, 54), (βRameshβ, 56), (βLasyaβ, 32), (βAmarβ, 89)]
Sorting with by_marks as key parameter and reverse parameter as False: [(βLasyaβ, 32), (βRekaβ, 54), (βRameshβ, 56), (βAmarβ, 89)]
Sorting with by_marks as key parameter and reverse parameter as True: [(βAmarβ, 89), (βRameshβ, 56), (βRekaβ, 54), (βLasyaβ, 32)]
This method sorts the list in ascending order by default, and we can use the reverse parameter to sort in descending order. This method changes the original list and doesnβt return anything.
Example 1:
Python3
# creating a list of itemslist_of_items = ["geeks", "for", "geeks"]print("Original list:", list_of_items) # using the sort method to sort# the itemslist_of_items.sort() # displaying the listprint("Sorted list:", list_of_items)
Original list: ['geeks', 'for', 'geeks']
Sorted list: ['for', 'geeks', 'geeks']
Example 2:
Using a predefined function as the key parameter
Python3
# using key parameter with pre-defined# function i.e. len() list_of_items = ["apple", "ball", "cat", "dog"] print("Original List:", list_of_items) # using the len() as key parameter and# sorting the listlist_of_items.sort(key=len)print("Sorting with len as key parameter:", list_of_items)
Original List: ['apple', 'ball', 'cat', 'dog']
Sorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']
Example 3:
Using a user-defined function as the key parameter
Python3
# using key parameter with user-defined# function i.e. by_name# using key parameter with user-defined# function i.e. by_marks # defining a user-defined function which# returns the first item(name)def by_name(ele): return ele[0] # defining a user-defined function which# returns the second item(marks)def by_marks(ele): return ele[1] # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [("Ramesh", 56), ("Reka", 54), ("Lasya", 32), ("Amar", 89)]print("original list:", list_of_items) # sorting by key value as by_name functionlist_of_items.sort(key=by_name)print("Sorting with by_name as key parameter:", list_of_items) # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [("Ramesh", 56), ("Reka", 54), ("Lasya", 32), ("Amar", 89)]print("original list:", list_of_items) # sorting by key value as by_marks functionlist_of_items.sort(key=by_marks)print("Sorting with by_marks as key parameter:", list_of_items)
Output
original list: [(βRameshβ, 56), (βRekaβ, 54), (βLasyaβ, 32), (βAmarβ, 89)]
Sorting with by_name as key parameter: [(βAmarβ, 89), (βLasyaβ, 32), (βRameshβ, 56), (βRekaβ, 54)]
original list: [(βRameshβ, 56), (βRekaβ, 54), (βLasyaβ, 32), (βAmarβ, 89)]
Sorting with by_marks as key parameter: [(βLasyaβ, 32), (βRekaβ, 54), (βRameshβ, 56), (βAmarβ, 89)]
Example 4:
Using reverse parameter
Python3
# using key parameter reverse list_of_items = ["geeks", "for", "geeks"] print("original list:", list_of_items) list_of_items.sort(reverse=True)print("sorting with reverse parameter", list_of_items)
original list: ['geeks', 'for', 'geeks']
sorting with reverse parameter ['geeks', 'geeks', 'for']
simranarora5sos
Picked
Python
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jun, 2021"
},
{
"code": null,
"e": 404,
"s": 28,
"text": "Sorting means arranging the set of values in either an increasing or decreasing manner. There are various methods to sort values in Python. We can store a set or group of values using various data structures such as list, tuples, dictionaries which depends on the data we are storing. So, in this article, we will discuss some methods and criteria to sort the data in Python."
},
{
"code": null,
"e": 475,
"s": 404,
"text": "This is a pre-defined method in python which sorts any kind of object."
},
{
"code": null,
"e": 483,
"s": 475,
"text": "Syntax:"
},
{
"code": null,
"e": 514,
"s": 483,
"text": "sorted(iterable, key, reverse)"
},
{
"code": null,
"e": 746,
"s": 514,
"text": "In this method, we pass 3 parameters, out of which 2 (key and reverse) are optional and the first parameter i.e. iterable can be any iterable object This method returns a sorted list but does not change the original data structure."
},
{
"code": null,
"e": 757,
"s": 746,
"text": "Example 1:"
},
{
"code": null,
"e": 765,
"s": 757,
"text": "Python3"
},
{
"code": "# Listlist_of_items = ['g', 'e', 'e', 'k', 's']print(sorted(list_of_items)) # Tupletuple_of_items = ('g', 'e', 'e', 'k', 's')print(sorted(tuple_of_items)) # String-sorted based on ASCII# translationsstring = \"geeks\"print(sorted(string)) # Dictionarydictionary = {'g': 1, 'e': 2, 'k': 3, 's': 4}print(sorted(dictionary)) # Setset_of_values = {'g', 'e', 'e', 'k', 's'}print(sorted(set_of_values)) # Frozen Setfrozen_set = frozenset(('g', 'e', 'e', 'k', 's'))print(sorted(frozen_set))",
"e": 1247,
"s": 765,
"text": null
},
{
"code": null,
"e": 1391,
"s": 1250,
"text": "['e', 'e', 'g', 'k', 's']\n['e', 'e', 'g', 'k', 's']\n['e', 'e', 'g', 'k', 's']\n['e', 'g', 'k', 's']\n['e', 'g', 'k', 's']\n['e', 'g', 'k', 's']"
},
{
"code": null,
"e": 1404,
"s": 1393,
"text": "Example 2:"
},
{
"code": null,
"e": 1690,
"s": 1406,
"text": "Using predefined function as key-parameter. So the second parameter i.e. key is used to sort the given data structure by some predefined function such as len() or some user-defined function. It sorts the values in the data structure based on the function passed to the key parameter."
},
{
"code": null,
"e": 1700,
"s": 1692,
"text": "Python3"
},
{
"code": "# using key parameter with pre-defined# function i.e. len() list_of_items = [\"apple\", \"ball\", \"cat\", \"dog\"] print(\"Sorting without key parameter:\", sorted(list_of_items))print(\"Sorting with len as key parameter:\", sorted(list_of_items, key=len))",
"e": 1946,
"s": 1700,
"text": null
},
{
"code": null,
"e": 2076,
"s": 1946,
"text": "Sorting without key parameter: ['apple', 'ball', 'cat', 'dog']\nSorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']"
},
{
"code": null,
"e": 2087,
"s": 2076,
"text": "Example 3:"
},
{
"code": null,
"e": 2142,
"s": 2087,
"text": "Using the user-defined function for the key parameter."
},
{
"code": null,
"e": 2150,
"s": 2142,
"text": "Python3"
},
{
"code": "# using key parameter with user-defined# function i.e. by_name# using key parameter with user-defined# function i.e. by_marks # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [(\"Ramesh\",56),(\"Reka\",54),(\"Lasya\",32),(\"Amar\",89)] # defining a user-defined function which returns# the first item(name)def by_name(ele): return ele[0] # defining a user-defined function which returns# the second item(marks)def by_marks(ele): return ele[1] print(\"Sorting without key parameter:\", sorted(list_of_items)) print(\"Sorting with by_name as key parameter:\", sorted(list_of_items, key=by_name)) print(\"Sorting with by_marks as key parameter:\", sorted(list_of_items, key=by_marks))",
"e": 2912,
"s": 2150,
"text": null
},
{
"code": null,
"e": 2919,
"s": 2912,
"text": "Output"
},
{
"code": null,
"e": 3010,
"s": 2919,
"text": "Sorting without key parameter: [(βAmarβ, 89), (βLasyaβ, 32), (βRameshβ, 56), (βRekaβ, 54)]"
},
{
"code": null,
"e": 3109,
"s": 3010,
"text": "Sorting with by_name as key parameter: [(βAmarβ, 89), (βLasyaβ, 32), (βRameshβ, 56), (βRekaβ, 54)]"
},
{
"code": null,
"e": 3209,
"s": 3109,
"text": "Sorting with by_marks as key parameter: [(βLasyaβ, 32), (βRekaβ, 54), (βRameshβ, 56), (βAmarβ, 89)]"
},
{
"code": null,
"e": 3220,
"s": 3209,
"text": "Example 4:"
},
{
"code": null,
"e": 3322,
"s": 3220,
"text": "So the 3rd parameter is reverse which is used to sort the iterable in descending or decreasing order."
},
{
"code": null,
"e": 3330,
"s": 3322,
"text": "Python3"
},
{
"code": "# using key parameter reverse list_of_items = [\"geeks\",\"for\",\"geeks\"] print(\"Sorting without key parameter:\", sorted(list_of_items)) print(\"Sorting with len as key parameter:\", sorted(list_of_items, reverse=True))",
"e": 3554,
"s": 3330,
"text": null
},
{
"code": null,
"e": 3672,
"s": 3554,
"text": "Sorting without key parameter: ['for', 'geeks', 'geeks']\nSorting with len as key parameter: ['geeks', 'geeks', 'for']"
},
{
"code": null,
"e": 3683,
"s": 3672,
"text": "Example 5:"
},
{
"code": null,
"e": 3714,
"s": 3683,
"text": "Using all the three parameters"
},
{
"code": null,
"e": 3722,
"s": 3714,
"text": "Python3"
},
{
"code": "# using by_name and by_marks as key parameter# and making reverse parameter true # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [(\"Ramesh\", 56), (\"Reka\", 54), (\"Lasya\", 32), (\"Amar\", 89)] # defining a user-defined function which# returns the first item(name)def by_name(ele): return ele[0] # defining a user-defined function which# returns the second item(marks)def by_marks(ele): return ele[1] print(\"Sorting without key and reverse:\", sorted(list_of_items)) print(\"Sorting with by_name as key parameter and reverse parameter as False:\", sorted(list_of_items, key=by_name, reverse=False))print(\"Sorting with by_name as key parameter and reverse parameter as True:\", sorted(list_of_items, key=by_name, reverse=True)) print(\"Sorting with by_marks as key parameter and reverse parameter as False:\", sorted(list_of_items, key=by_marks, reverse=False))print(\"Sorting with by_marks as key parameter and reverse parameter as True:\", sorted(list_of_items, key=by_marks, reverse=True))",
"e": 4826,
"s": 3722,
"text": null
},
{
"code": null,
"e": 4833,
"s": 4826,
"text": "Output"
},
{
"code": null,
"e": 4926,
"s": 4833,
"text": "Sorting without key and reverse: [(βAmarβ, 89), (βLasyaβ, 32), (βRameshβ, 56), (βRekaβ, 54)]"
},
{
"code": null,
"e": 5056,
"s": 4926,
"text": "Sorting with by_name as key parameter and reverse parameter as False: [(βAmarβ, 89), (βLasyaβ, 32), (βRameshβ, 56), (βRekaβ, 54)]"
},
{
"code": null,
"e": 5185,
"s": 5056,
"text": "Sorting with by_name as key parameter and reverse parameter as True: [(βRekaβ, 54), (βRameshβ, 56), (βLasyaβ, 32), (βAmarβ, 89)]"
},
{
"code": null,
"e": 5316,
"s": 5185,
"text": "Sorting with by_marks as key parameter and reverse parameter as False: [(βLasyaβ, 32), (βRekaβ, 54), (βRameshβ, 56), (βAmarβ, 89)]"
},
{
"code": null,
"e": 5446,
"s": 5316,
"text": "Sorting with by_marks as key parameter and reverse parameter as True: [(βAmarβ, 89), (βRameshβ, 56), (βRekaβ, 54), (βLasyaβ, 32)]"
},
{
"code": null,
"e": 5638,
"s": 5446,
"text": "This method sorts the list in ascending order by default, and we can use the reverse parameter to sort in descending order. This method changes the original list and doesnβt return anything. "
},
{
"code": null,
"e": 5649,
"s": 5638,
"text": "Example 1:"
},
{
"code": null,
"e": 5657,
"s": 5649,
"text": "Python3"
},
{
"code": "# creating a list of itemslist_of_items = [\"geeks\", \"for\", \"geeks\"]print(\"Original list:\", list_of_items) # using the sort method to sort# the itemslist_of_items.sort() # displaying the listprint(\"Sorted list:\", list_of_items)",
"e": 5884,
"s": 5657,
"text": null
},
{
"code": null,
"e": 5964,
"s": 5884,
"text": "Original list: ['geeks', 'for', 'geeks']\nSorted list: ['for', 'geeks', 'geeks']"
},
{
"code": null,
"e": 5975,
"s": 5964,
"text": "Example 2:"
},
{
"code": null,
"e": 6024,
"s": 5975,
"text": "Using a predefined function as the key parameter"
},
{
"code": null,
"e": 6032,
"s": 6024,
"text": "Python3"
},
{
"code": "# using key parameter with pre-defined# function i.e. len() list_of_items = [\"apple\", \"ball\", \"cat\", \"dog\"] print(\"Original List:\", list_of_items) # using the len() as key parameter and# sorting the listlist_of_items.sort(key=len)print(\"Sorting with len as key parameter:\", list_of_items)",
"e": 6321,
"s": 6032,
"text": null
},
{
"code": null,
"e": 6436,
"s": 6321,
"text": "Original List: ['apple', 'ball', 'cat', 'dog']\nSorting with len as key parameter: ['cat', 'dog', 'ball', 'apple']\n"
},
{
"code": null,
"e": 6447,
"s": 6436,
"text": "Example 3:"
},
{
"code": null,
"e": 6498,
"s": 6447,
"text": "Using a user-defined function as the key parameter"
},
{
"code": null,
"e": 6506,
"s": 6498,
"text": "Python3"
},
{
"code": "# using key parameter with user-defined# function i.e. by_name# using key parameter with user-defined# function i.e. by_marks # defining a user-defined function which# returns the first item(name)def by_name(ele): return ele[0] # defining a user-defined function which# returns the second item(marks)def by_marks(ele): return ele[1] # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [(\"Ramesh\", 56), (\"Reka\", 54), (\"Lasya\", 32), (\"Amar\", 89)]print(\"original list:\", list_of_items) # sorting by key value as by_name functionlist_of_items.sort(key=by_name)print(\"Sorting with by_name as key parameter:\", list_of_items) # here is a list_of_tuples where the first# item in tuple is the student name and the# second item is his/her markslist_of_items = [(\"Ramesh\", 56), (\"Reka\", 54), (\"Lasya\", 32), (\"Amar\", 89)]print(\"original list:\", list_of_items) # sorting by key value as by_marks functionlist_of_items.sort(key=by_marks)print(\"Sorting with by_marks as key parameter:\", list_of_items)",
"e": 7611,
"s": 6506,
"text": null
},
{
"code": null,
"e": 7618,
"s": 7611,
"text": "Output"
},
{
"code": null,
"e": 7693,
"s": 7618,
"text": "original list: [(βRameshβ, 56), (βRekaβ, 54), (βLasyaβ, 32), (βAmarβ, 89)]"
},
{
"code": null,
"e": 7792,
"s": 7693,
"text": "Sorting with by_name as key parameter: [(βAmarβ, 89), (βLasyaβ, 32), (βRameshβ, 56), (βRekaβ, 54)]"
},
{
"code": null,
"e": 7867,
"s": 7792,
"text": "original list: [(βRameshβ, 56), (βRekaβ, 54), (βLasyaβ, 32), (βAmarβ, 89)]"
},
{
"code": null,
"e": 7967,
"s": 7867,
"text": "Sorting with by_marks as key parameter: [(βLasyaβ, 32), (βRekaβ, 54), (βRameshβ, 56), (βAmarβ, 89)]"
},
{
"code": null,
"e": 7978,
"s": 7967,
"text": "Example 4:"
},
{
"code": null,
"e": 8002,
"s": 7978,
"text": "Using reverse parameter"
},
{
"code": null,
"e": 8010,
"s": 8002,
"text": "Python3"
},
{
"code": "# using key parameter reverse list_of_items = [\"geeks\", \"for\", \"geeks\"] print(\"original list:\", list_of_items) list_of_items.sort(reverse=True)print(\"sorting with reverse parameter\", list_of_items)",
"e": 8208,
"s": 8010,
"text": null
},
{
"code": null,
"e": 8306,
"s": 8208,
"text": "original list: ['geeks', 'for', 'geeks']\nsorting with reverse parameter ['geeks', 'geeks', 'for']"
},
{
"code": null,
"e": 8322,
"s": 8306,
"text": "simranarora5sos"
},
{
"code": null,
"e": 8329,
"s": 8322,
"text": "Picked"
},
{
"code": null,
"e": 8336,
"s": 8329,
"text": "Python"
},
{
"code": null,
"e": 8344,
"s": 8336,
"text": "Sorting"
},
{
"code": null,
"e": 8352,
"s": 8344,
"text": "Sorting"
},
{
"code": null,
"e": 8450,
"s": 8352,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8482,
"s": 8450,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8509,
"s": 8482,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8530,
"s": 8509,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 8553,
"s": 8530,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 8584,
"s": 8553,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 8595,
"s": 8584,
"text": "Merge Sort"
},
{
"code": null,
"e": 8617,
"s": 8595,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 8627,
"s": 8617,
"text": "QuickSort"
},
{
"code": null,
"e": 8642,
"s": 8627,
"text": "Insertion Sort"
}
] |
Python | Converting list string to dictionary | 28 Apr, 2019
Yet another problem regarding the interconversion between data types is conversion of string of list to a dictionary of keys and values. This particular problem can occur at the places where we need huge amount of string data to be converted to dictionary for preprocessing in Machine Learning domain. Letβs discuss certain ways in which this task can be done.
Method #1 : Using dictionary comprehension + split()Dictionary comprehension can be used for construction of dictionary and split function can be used to perform the necessary splits in list to get the valid key and value pair for dictionary.
# Python3 code to demonstrate# Converting list string to dictionary # Using dictionary comprehsion + split() # initializing stringtest_string = '[Nikhil:1, Akshat:2, Akash:3]' # printing original stringprint("The original string : " + str(test_string)) # using dictionary comprehsion + split()# Converting list string to dictionary res = {sub.split(":")[0]: sub.split(":")[1] for sub in test_string[1:-1].split(", ")} # print resultprint("The dictionary after extraction is : " + str(res))
The original string : [Nikhil:1, Akshat:2, Akash:3]
The dictionary after extraction is : {'Nikhil': '1', 'Akash': '3', 'Akshat': '2'}
Method #2 : Using eval() + replace()This particular task can also be performed using the combination of above two functions, the eval and replace functions. In this method, eval function performs like dictionary comprehension, constructing the dictionary and replace function performs the necessary replaces. This function is used when keys and values has to be converted to integer.
# Python3 code to demonstrate# Converting list string to dictionary # Using eval() + replace() # initializing stringtest_string = '[120:1, 190:2, 140:3]' # printing original stringprint("The original string : " + str(test_string)) # using eval() + replace()# Converting list string to dictionary res = eval(test_string.replace("[", "{").replace("]", "}")) # print resultprint("The dictionary after extraction is : " + str(res))
The original string : [120:1, 190:2, 140:3]
The dictionary after extraction is : {120: 1, 140: 3, 190: 2}
Python list-programs
python-list
python-string
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Apr, 2019"
},
{
"code": null,
"e": 389,
"s": 28,
"text": "Yet another problem regarding the interconversion between data types is conversion of string of list to a dictionary of keys and values. This particular problem can occur at the places where we need huge amount of string data to be converted to dictionary for preprocessing in Machine Learning domain. Letβs discuss certain ways in which this task can be done."
},
{
"code": null,
"e": 632,
"s": 389,
"text": "Method #1 : Using dictionary comprehension + split()Dictionary comprehension can be used for construction of dictionary and split function can be used to perform the necessary splits in list to get the valid key and value pair for dictionary."
},
{
"code": "# Python3 code to demonstrate# Converting list string to dictionary # Using dictionary comprehsion + split() # initializing stringtest_string = '[Nikhil:1, Akshat:2, Akash:3]' # printing original stringprint(\"The original string : \" + str(test_string)) # using dictionary comprehsion + split()# Converting list string to dictionary res = {sub.split(\":\")[0]: sub.split(\":\")[1] for sub in test_string[1:-1].split(\", \")} # print resultprint(\"The dictionary after extraction is : \" + str(res))",
"e": 1126,
"s": 632,
"text": null
},
{
"code": null,
"e": 1261,
"s": 1126,
"text": "The original string : [Nikhil:1, Akshat:2, Akash:3]\nThe dictionary after extraction is : {'Nikhil': '1', 'Akash': '3', 'Akshat': '2'}\n"
},
{
"code": null,
"e": 1647,
"s": 1263,
"text": "Method #2 : Using eval() + replace()This particular task can also be performed using the combination of above two functions, the eval and replace functions. In this method, eval function performs like dictionary comprehension, constructing the dictionary and replace function performs the necessary replaces. This function is used when keys and values has to be converted to integer."
},
{
"code": "# Python3 code to demonstrate# Converting list string to dictionary # Using eval() + replace() # initializing stringtest_string = '[120:1, 190:2, 140:3]' # printing original stringprint(\"The original string : \" + str(test_string)) # using eval() + replace()# Converting list string to dictionary res = eval(test_string.replace(\"[\", \"{\").replace(\"]\", \"}\")) # print resultprint(\"The dictionary after extraction is : \" + str(res))",
"e": 2079,
"s": 1647,
"text": null
},
{
"code": null,
"e": 2186,
"s": 2079,
"text": "The original string : [120:1, 190:2, 140:3]\nThe dictionary after extraction is : {120: 1, 140: 3, 190: 2}\n"
},
{
"code": null,
"e": 2207,
"s": 2186,
"text": "Python list-programs"
},
{
"code": null,
"e": 2219,
"s": 2207,
"text": "python-list"
},
{
"code": null,
"e": 2233,
"s": 2219,
"text": "python-string"
},
{
"code": null,
"e": 2240,
"s": 2233,
"text": "Python"
},
{
"code": null,
"e": 2252,
"s": 2240,
"text": "python-list"
},
{
"code": null,
"e": 2350,
"s": 2252,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2392,
"s": 2350,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2414,
"s": 2392,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2440,
"s": 2414,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2472,
"s": 2440,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2501,
"s": 2472,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2528,
"s": 2501,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2558,
"s": 2528,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2579,
"s": 2558,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2602,
"s": 2579,
"text": "Introduction To PYTHON"
}
] |
How to Create a Histogram in Excel? | 19 Apr, 2021
A histogram is one of the most common data analysis tools in the business world. It is a graphical representation of data that clubs all the data that fall under specific regions.
The numbers on the X-axis represent bins
Note: Weβre using Microsoft Excel 2010 for this article, but the steps shown further will be applicable for all later versions of Excel.
Step 1: So the first step is to set up your table. For this article, Iβm taking a table that shows the studentsβ names and the marks they obtained in their exams.
Step 2: Now, we need to set up the Bins/Ranges for our marks. This will help us to choose the bins for our histogram chart.
So, once that is done, we must calculate our data frequencies for our bins. Let us make another column titled, βFrequenciesβ
We can calculate these frequencies easily by using the Excel function, βFREQUENCYβJust go to the first cell of the Frequencies column and type the following β
=FREQUENCY(Start_cell_of_data_column: end_cell_of_data_column,
Start_cell_of_bins_column: end_cell_of_bins_column)
And press Ctrl + L-Shift + Enter.
In our case, it will look like this: =FREQUENCY(B2:B15, E2:E5)
Now that the first frequency of the frequencies column has been successfully calculated, we can apply the same formula to the entire column by selecting that cell and dragging the cursor till the end of the column. The final result is as follows:
Step 3: Let us create the chart now. First, select the Bins and the Frequencies columns. Then go to the Insert section and select the Clustered Column from the Column dropdown under the Charts sub-sections
The final result will look something like this
Now, we donβt want the Bins to be displayed like this. Instead, we want them to be displayed under the X-axis. So, let us go ahead and delete it by clicking in the blue bars and pressing the Delete key.
Then, click on values on the X-axis and select them. Go to the Data section and click on βSelect Dataβ. The following box will appear.
Now Click on Edit and wait for the following box to appear.
Now click on the small icon at the end of the dialog box and then select the Bins column from the first number till last and press Enter.
Your Histogram is finally ready!
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2021"
},
{
"code": null,
"e": 208,
"s": 28,
"text": "A histogram is one of the most common data analysis tools in the business world. It is a graphical representation of data that clubs all the data that fall under specific regions."
},
{
"code": null,
"e": 249,
"s": 208,
"text": "The numbers on the X-axis represent bins"
},
{
"code": null,
"e": 386,
"s": 249,
"text": "Note: Weβre using Microsoft Excel 2010 for this article, but the steps shown further will be applicable for all later versions of Excel."
},
{
"code": null,
"e": 549,
"s": 386,
"text": "Step 1: So the first step is to set up your table. For this article, Iβm taking a table that shows the studentsβ names and the marks they obtained in their exams."
},
{
"code": null,
"e": 674,
"s": 549,
"text": "Step 2: Now, we need to set up the Bins/Ranges for our marks. This will help us to choose the bins for our histogram chart. "
},
{
"code": null,
"e": 799,
"s": 674,
"text": "So, once that is done, we must calculate our data frequencies for our bins. Let us make another column titled, βFrequenciesβ"
},
{
"code": null,
"e": 958,
"s": 799,
"text": "We can calculate these frequencies easily by using the Excel function, βFREQUENCYβJust go to the first cell of the Frequencies column and type the following β"
},
{
"code": null,
"e": 1113,
"s": 958,
"text": "=FREQUENCY(Start_cell_of_data_column: end_cell_of_data_column, \n Start_cell_of_bins_column: end_cell_of_bins_column) "
},
{
"code": null,
"e": 1147,
"s": 1113,
"text": "And press Ctrl + L-Shift + Enter."
},
{
"code": null,
"e": 1211,
"s": 1147,
"text": "In our case, it will look like this: =FREQUENCY(B2:B15, E2:E5) "
},
{
"code": null,
"e": 1458,
"s": 1211,
"text": "Now that the first frequency of the frequencies column has been successfully calculated, we can apply the same formula to the entire column by selecting that cell and dragging the cursor till the end of the column. The final result is as follows:"
},
{
"code": null,
"e": 1664,
"s": 1458,
"text": "Step 3: Let us create the chart now. First, select the Bins and the Frequencies columns. Then go to the Insert section and select the Clustered Column from the Column dropdown under the Charts sub-sections"
},
{
"code": null,
"e": 1711,
"s": 1664,
"text": "The final result will look something like this"
},
{
"code": null,
"e": 1914,
"s": 1711,
"text": "Now, we donβt want the Bins to be displayed like this. Instead, we want them to be displayed under the X-axis. So, let us go ahead and delete it by clicking in the blue bars and pressing the Delete key."
},
{
"code": null,
"e": 2049,
"s": 1914,
"text": "Then, click on values on the X-axis and select them. Go to the Data section and click on βSelect Dataβ. The following box will appear."
},
{
"code": null,
"e": 2109,
"s": 2049,
"text": "Now Click on Edit and wait for the following box to appear."
},
{
"code": null,
"e": 2247,
"s": 2109,
"text": "Now click on the small icon at the end of the dialog box and then select the Bins column from the first number till last and press Enter."
},
{
"code": null,
"e": 2280,
"s": 2247,
"text": "Your Histogram is finally ready!"
},
{
"code": null,
"e": 2287,
"s": 2280,
"text": "Picked"
},
{
"code": null,
"e": 2293,
"s": 2287,
"text": "Excel"
}
] |
Stream filter() in Java with examples | 03 May, 2022
Stream filter(Predicate predicate) returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation. These operations are always lazy i.e, executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.
Syntax:
Stream<T> filter(Predicate<? super T> predicate)
Where Stream is an interface and T is the type of the input to the predicate.
Return Type: A new stream.
Implementation:
Filtering out the elements divisible by some specific number ranging between 0 to 10.Filtering out the elements with an upperCase letter at any specific index.Filtering out the elements ending with custom alphabetical letters.
Filtering out the elements divisible by some specific number ranging between 0 to 10.
Filtering out the elements with an upperCase letter at any specific index.
Filtering out the elements ending with custom alphabetical letters.
Example 1: filter() method with the operation of filtering out the elements divisible by 5.
Java
// Java Program to get a Stream Consisting of the Elements// of Stream that Matches Given Predicate for Stream filter// (Predicate predicate) // Importing required classesimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a list of Integers List<Integer> list = Arrays.asList(3, 4, 6, 12, 20); // Getting a stream consisting of the // elements that are divisible by 5 // Using Stream filter(Predicate predicate) list.stream() .filter(num -> num % 5 == 0) .forEach(System.out::println); }}
20
Example 2: filter() method with the operation of filtering out the elements with an upperCase letter at index 1.
Java
// Java Program to Get Stream Consisting of Elements// of Stream that Matches Given Predicate// for Stream Filter (Predicate predicate) // Importing required classesimport java.util.stream.Stream; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a stream of strings Stream<String> stream = Stream.of( "Geeks", "fOr", "GEEKSQUIZ", "GeeksforGeeks"); // Getting a stream consisting of the // elements having UpperCase Character // at custom index say be it '1' // using Stream filter(Predicate predicate) stream .filter( str -> Character.isUpperCase(str.charAt(1))) .forEach(System.out::println); }}
fOr
GEEKSQUIZ
Example 3: filter() method with the operation of filtering out the elements ending with custom alphabetically letter say it be βsβ for implementation purposes.
Java
// Java Program to Get a Stream Consisting ofElements// of Stream that Matches Given predicate// for Stream filter (Predicate predicate) // Importing required classesimport java.util.stream.Stream; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a stream of strings Stream<String> stream = Stream.of( "Geeks", "foR", "GeEksQuiz", "GeeksforGeeks"); // Getting a stream consisting of the // elements ending with 's' // using Stream filter(Predicate predicate) stream.filter(str -> str.endsWith("s")) .forEach(System.out::println); }}
Geeks
GeeksforGeeks
solankimayank
Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 May, 2022"
},
{
"code": null,
"e": 479,
"s": 54,
"text": "Stream filter(Predicate predicate) returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation. These operations are always lazy i.e, executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. "
},
{
"code": null,
"e": 487,
"s": 479,
"text": "Syntax:"
},
{
"code": null,
"e": 536,
"s": 487,
"text": "Stream<T> filter(Predicate<? super T> predicate)"
},
{
"code": null,
"e": 614,
"s": 536,
"text": "Where Stream is an interface and T is the type of the input to the predicate."
},
{
"code": null,
"e": 641,
"s": 614,
"text": "Return Type: A new stream."
},
{
"code": null,
"e": 657,
"s": 641,
"text": "Implementation:"
},
{
"code": null,
"e": 884,
"s": 657,
"text": "Filtering out the elements divisible by some specific number ranging between 0 to 10.Filtering out the elements with an upperCase letter at any specific index.Filtering out the elements ending with custom alphabetical letters."
},
{
"code": null,
"e": 970,
"s": 884,
"text": "Filtering out the elements divisible by some specific number ranging between 0 to 10."
},
{
"code": null,
"e": 1045,
"s": 970,
"text": "Filtering out the elements with an upperCase letter at any specific index."
},
{
"code": null,
"e": 1113,
"s": 1045,
"text": "Filtering out the elements ending with custom alphabetical letters."
},
{
"code": null,
"e": 1205,
"s": 1113,
"text": "Example 1: filter() method with the operation of filtering out the elements divisible by 5."
},
{
"code": null,
"e": 1210,
"s": 1205,
"text": "Java"
},
{
"code": "// Java Program to get a Stream Consisting of the Elements// of Stream that Matches Given Predicate for Stream filter// (Predicate predicate) // Importing required classesimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a list of Integers List<Integer> list = Arrays.asList(3, 4, 6, 12, 20); // Getting a stream consisting of the // elements that are divisible by 5 // Using Stream filter(Predicate predicate) list.stream() .filter(num -> num % 5 == 0) .forEach(System.out::println); }}",
"e": 1847,
"s": 1210,
"text": null
},
{
"code": null,
"e": 1850,
"s": 1847,
"text": "20"
},
{
"code": null,
"e": 1964,
"s": 1850,
"text": "Example 2: filter() method with the operation of filtering out the elements with an upperCase letter at index 1. "
},
{
"code": null,
"e": 1969,
"s": 1964,
"text": "Java"
},
{
"code": "// Java Program to Get Stream Consisting of Elements// of Stream that Matches Given Predicate// for Stream Filter (Predicate predicate) // Importing required classesimport java.util.stream.Stream; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a stream of strings Stream<String> stream = Stream.of( \"Geeks\", \"fOr\", \"GEEKSQUIZ\", \"GeeksforGeeks\"); // Getting a stream consisting of the // elements having UpperCase Character // at custom index say be it '1' // using Stream filter(Predicate predicate) stream .filter( str -> Character.isUpperCase(str.charAt(1))) .forEach(System.out::println); }}",
"e": 2727,
"s": 1969,
"text": null
},
{
"code": null,
"e": 2741,
"s": 2727,
"text": "fOr\nGEEKSQUIZ"
},
{
"code": null,
"e": 2902,
"s": 2741,
"text": "Example 3: filter() method with the operation of filtering out the elements ending with custom alphabetically letter say it be βsβ for implementation purposes. "
},
{
"code": null,
"e": 2907,
"s": 2902,
"text": "Java"
},
{
"code": "// Java Program to Get a Stream Consisting ofElements// of Stream that Matches Given predicate// for Stream filter (Predicate predicate) // Importing required classesimport java.util.stream.Stream; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating a stream of strings Stream<String> stream = Stream.of( \"Geeks\", \"foR\", \"GeEksQuiz\", \"GeeksforGeeks\"); // Getting a stream consisting of the // elements ending with 's' // using Stream filter(Predicate predicate) stream.filter(str -> str.endsWith(\"s\")) .forEach(System.out::println); }}",
"e": 3571,
"s": 2907,
"text": null
},
{
"code": null,
"e": 3591,
"s": 3571,
"text": "Geeks\nGeeksforGeeks"
},
{
"code": null,
"e": 3605,
"s": 3591,
"text": "solankimayank"
},
{
"code": null,
"e": 3625,
"s": 3605,
"text": "Java - util package"
},
{
"code": null,
"e": 3640,
"s": 3625,
"text": "Java-Functions"
},
{
"code": null,
"e": 3652,
"s": 3640,
"text": "java-stream"
},
{
"code": null,
"e": 3674,
"s": 3652,
"text": "Java-Stream interface"
},
{
"code": null,
"e": 3679,
"s": 3674,
"text": "Java"
},
{
"code": null,
"e": 3684,
"s": 3679,
"text": "Java"
}
] |
Working with Strings in Python 3 | 05 Sep, 2020
In Python, sequences of characters are referred to as Strings. It used in Python to record text information, such as names. Python strings are βimmutableβ which means they cannot be changed after they are created.
Strings can be created using single quotes, double quotes, or even triple quotes. Python treats single quotes the same as double-quotes.
Python3
# creating string# with single QuotesString = 'Hello Geek'print("Creating string with single quotes :", String) # Creating String# with double QuotesString = "yes, I am Geek"print("Creating String with double quotes :", String) # Creating String# with triple QuotesString = '''yes, I am Geek'''print("Creating String with triple quotes :", String)
Creating string with single quotes : Hello Geek
Creating String with double quotes : yes, I am Geek
Creating String with triple quotes : yes, I am Geek
Note: Be careful with quotes!
Python3
# creating string# with single quotesString = 'Yes' I am geek'print(String)
Output
File "<ipython-input-10-794636cfedda>", line 3
String = 'Yes' I am geek'
^
SyntaxError: invalid syntax
The reason for the error above is the single quote in Yesβ I stopped the string. If you want to print βWithQuotesβ in python, this canβt be done with only single (or double) quotes alone, it requires simultaneous use of both. The best way to avoid this error use double-quotes.
Example:
Python3
# this code prints the output within quotes. # print WithQuotes within single quotes print("'WithQuotes'") print("Hello 'Python'") # print WithQuotes within single quotes print('"WithQuotes"') print('Hello "Python"')
'WithQuotes'
Hello 'Python'
"WithQuotes"
Hello "Python"
Note: For more information, refer Single and Double Quotes | Python
Strings are a sequence of characters, which means Python can use indexes to call parts of the sequence. There are two ways of indexing.
Positive Indexing
Negative Indexing
Positive indexing
Python3
# creating a stringString = "GEEK" # Show first element in stringprint("The 1st element is : ", String[0]) # Show 2nd element in stringprint("The 2nd element is : ", String[1]) print("The 3rd element is : ", String[2])print("The 4th element is : ", String[3])
The 1st element is : G
The 2nd element is : E
The 3rd element is : E
The 4th element is : K
Negative indexing
Python3
# creating a stringString = "GEEK" # Show last element in stringprint("The 4th element is : ", String[-1]) # Show all element in stringprint("The 3rd element is : ", String[-2]) print("The 2nd element is : ", String[-3])print("The 1th element is : ", String[-4])
The 4th element is : K
The 3rd element is : E
The 2nd element is : E
The 1th element is : G
In Python, Updation or deletion of characters from a string is not allowed. This will cause an error because item assignment or item deletion from a String is not supported. Python can allow you to reassign a new string to an existing one string.
Python3
# Creating string String = "Geeks" # assign new characterString[0] = "Hi!, Geeks"
Output
Traceback (most recent call last): File β/home/b298782a4e04df4950426bf4bd5bee99.pyβ, line 5, in <module> String[0] = βHi!, GeeksβTypeError: βstrβ object does not support item assignment
Updating the entire String
Python3
# Creating stringString = "Hello Geeks"print("Before updating : ", String) # updating entire stringString = "Geeksforgeeks"print("After updating : ", String) # Update with indexingString = 'Hello World!'print("Updated String :- ", String[:6] + 'Python')
Before updating : Hello Geeks
After updating : Geeksforgeeks
Updated String :- Hello Python
Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end.Python slicing can be done in two ways.
slice() Constructor
Extending Indexing
Python3
# Creating a StringString = "Geekforgeeks" s1 = slice(3) # print everything except the first elementprint(String[s1]) # print everything UP TO the 6th indexprint(String[:6]) # print everything between both indexprint(String[1:7])
Gee
Geekfo
eekfor
Slicing with negative Index.
Python3
# Creating a StringString = "Geekforgeeks" s1 = slice(-1) # print everything except the last elementprint(String[s1]) # print everything between both indexprint(String[0:-3])
Geekforgeek
Geekforge
We can use [ : : ] for specifying the frequency to print elements. It specifies the step after which every element will be printed starting from the given index. If nothing is given then it starts from the 0th index.
Python3
# Creating a StringString = "Geekforgeeks" # print everything with step 1print(String[::1]) # print everything with step 2print(String[2::2]) # print a string backwardsprint(String[::-1])
Geekforgeeks
efrek
skeegrofkeeG
Note: For more information, refer String Slicing in Python
str.format() and f-strings methods are used to add formatted objects to printed string statements. The string format() method formats the given string. It allows for multiple substitutions and value formatting.
Python3
# using format option in a simple stringString = 'Geeksforgeeks'print("{}, A computer science portal for geeks." .format(String)) String = 'Geeks'print("Hello {}, How are you ?".format(String)) # formatting a string using a numeric constantval = 2print("I want {} Burgers! ".format(val))
Geeksforgeeks, A computer science portal for geeks.
Hello Geeks, How are you ?
I want 2 Burgers!
Note: For more information, refer Python | format() function
Formatted f-string literals are prefixed with βfβ and curly braces { } containing expressions that will be replaced with their values.
Python3
# Creating stringString = 'GeekForGeeks'print(f"{String}: A Computer Science portal for geeks") # Creating stringString = 'Geek'print(f"Yes, I am {String}") # Manuplating int within {}bags = 3book_in_bag = 12print(f'There are total {bags * book_in_bag} books') # work with dictionaries in f-stringsDic = {'Portal': 'Geeksforgeeks', 'for': 'Geeks'}print(f"{Dic['Portal']} is a computer science portal for {Dic['for']}")
GeekForGeeks: A Computer Science portal for geeks
Yes, I am Geek
There are total 36 books
Geeksforgeeks is a computer science portal for Geeks
Note: For more information, refer f-strings in Python 3 β Formatted string literals
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "In Python, sequences of characters are referred to as Strings. It used in Python to record text information, such as names. Python strings are βimmutableβ which means they cannot be changed after they are created."
},
{
"code": null,
"e": 379,
"s": 242,
"text": "Strings can be created using single quotes, double quotes, or even triple quotes. Python treats single quotes the same as double-quotes."
},
{
"code": null,
"e": 387,
"s": 379,
"text": "Python3"
},
{
"code": "# creating string# with single QuotesString = 'Hello Geek'print(\"Creating string with single quotes :\", String) # Creating String# with double QuotesString = \"yes, I am Geek\"print(\"Creating String with double quotes :\", String) # Creating String# with triple QuotesString = '''yes, I am Geek'''print(\"Creating String with triple quotes :\", String)",
"e": 737,
"s": 387,
"text": null
},
{
"code": null,
"e": 890,
"s": 737,
"text": "Creating string with single quotes : Hello Geek\nCreating String with double quotes : yes, I am Geek\nCreating String with triple quotes : yes, I am Geek\n"
},
{
"code": null,
"e": 920,
"s": 890,
"text": "Note: Be careful with quotes!"
},
{
"code": null,
"e": 928,
"s": 920,
"text": "Python3"
},
{
"code": "# creating string# with single quotesString = 'Yes' I am geek'print(String)",
"e": 1004,
"s": 928,
"text": null
},
{
"code": null,
"e": 1011,
"s": 1004,
"text": "Output"
},
{
"code": null,
"e": 1140,
"s": 1011,
"text": " File \"<ipython-input-10-794636cfedda>\", line 3\n String = 'Yes' I am geek'\n ^\nSyntaxError: invalid syntax\n"
},
{
"code": null,
"e": 1419,
"s": 1140,
"text": "The reason for the error above is the single quote in Yesβ I stopped the string. If you want to print βWithQuotesβ in python, this canβt be done with only single (or double) quotes alone, it requires simultaneous use of both. The best way to avoid this error use double-quotes. "
},
{
"code": null,
"e": 1428,
"s": 1419,
"text": "Example:"
},
{
"code": null,
"e": 1436,
"s": 1428,
"text": "Python3"
},
{
"code": "# this code prints the output within quotes. # print WithQuotes within single quotes print(\"'WithQuotes'\") print(\"Hello 'Python'\") # print WithQuotes within single quotes print('\"WithQuotes\"') print('Hello \"Python\"')",
"e": 1657,
"s": 1436,
"text": null
},
{
"code": null,
"e": 1714,
"s": 1657,
"text": "'WithQuotes'\nHello 'Python'\n\"WithQuotes\"\nHello \"Python\"\n"
},
{
"code": null,
"e": 1782,
"s": 1714,
"text": "Note: For more information, refer Single and Double Quotes | Python"
},
{
"code": null,
"e": 1919,
"s": 1782,
"text": " Strings are a sequence of characters, which means Python can use indexes to call parts of the sequence. There are two ways of indexing."
},
{
"code": null,
"e": 1937,
"s": 1919,
"text": "Positive Indexing"
},
{
"code": null,
"e": 1955,
"s": 1937,
"text": "Negative Indexing"
},
{
"code": null,
"e": 1973,
"s": 1955,
"text": "Positive indexing"
},
{
"code": null,
"e": 1981,
"s": 1973,
"text": "Python3"
},
{
"code": "# creating a stringString = \"GEEK\" # Show first element in stringprint(\"The 1st element is : \", String[0]) # Show 2nd element in stringprint(\"The 2nd element is : \", String[1]) print(\"The 3rd element is : \", String[2])print(\"The 4th element is : \", String[3])",
"e": 2244,
"s": 1981,
"text": null
},
{
"code": null,
"e": 2341,
"s": 2244,
"text": "The 1st element is : G\nThe 2nd element is : E\nThe 3rd element is : E\nThe 4th element is : K\n"
},
{
"code": null,
"e": 2359,
"s": 2341,
"text": "Negative indexing"
},
{
"code": null,
"e": 2367,
"s": 2359,
"text": "Python3"
},
{
"code": "# creating a stringString = \"GEEK\" # Show last element in stringprint(\"The 4th element is : \", String[-1]) # Show all element in stringprint(\"The 3rd element is : \", String[-2]) print(\"The 2nd element is : \", String[-3])print(\"The 1th element is : \", String[-4])",
"e": 2633,
"s": 2367,
"text": null
},
{
"code": null,
"e": 2730,
"s": 2633,
"text": "The 4th element is : K\nThe 3rd element is : E\nThe 2nd element is : E\nThe 1th element is : G\n"
},
{
"code": null,
"e": 2977,
"s": 2730,
"text": "In Python, Updation or deletion of characters from a string is not allowed. This will cause an error because item assignment or item deletion from a String is not supported. Python can allow you to reassign a new string to an existing one string."
},
{
"code": null,
"e": 2985,
"s": 2977,
"text": "Python3"
},
{
"code": "# Creating string String = \"Geeks\" # assign new characterString[0] = \"Hi!, Geeks\"",
"e": 3068,
"s": 2985,
"text": null
},
{
"code": null,
"e": 3075,
"s": 3068,
"text": "Output"
},
{
"code": null,
"e": 3263,
"s": 3075,
"text": "Traceback (most recent call last): File β/home/b298782a4e04df4950426bf4bd5bee99.pyβ, line 5, in <module> String[0] = βHi!, GeeksβTypeError: βstrβ object does not support item assignment"
},
{
"code": null,
"e": 3290,
"s": 3263,
"text": "Updating the entire String"
},
{
"code": null,
"e": 3298,
"s": 3290,
"text": "Python3"
},
{
"code": "# Creating stringString = \"Hello Geeks\"print(\"Before updating : \", String) # updating entire stringString = \"Geeksforgeeks\"print(\"After updating : \", String) # Update with indexingString = 'Hello World!'print(\"Updated String :- \", String[:6] + 'Python')",
"e": 3554,
"s": 3298,
"text": null
},
{
"code": null,
"e": 3650,
"s": 3554,
"text": "Before updating : Hello Geeks\nAfter updating : Geeksforgeeks\nUpdated String :- Hello Python\n"
},
{
"code": null,
"e": 3804,
"s": 3650,
"text": "Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end.Python slicing can be done in two ways."
},
{
"code": null,
"e": 3824,
"s": 3804,
"text": "slice() Constructor"
},
{
"code": null,
"e": 3843,
"s": 3824,
"text": "Extending Indexing"
},
{
"code": null,
"e": 3851,
"s": 3843,
"text": "Python3"
},
{
"code": "# Creating a StringString = \"Geekforgeeks\" s1 = slice(3) # print everything except the first elementprint(String[s1]) # print everything UP TO the 6th indexprint(String[:6]) # print everything between both indexprint(String[1:7])",
"e": 4085,
"s": 3851,
"text": null
},
{
"code": null,
"e": 4104,
"s": 4085,
"text": "Gee\nGeekfo\neekfor\n"
},
{
"code": null,
"e": 4133,
"s": 4104,
"text": "Slicing with negative Index."
},
{
"code": null,
"e": 4141,
"s": 4133,
"text": "Python3"
},
{
"code": "# Creating a StringString = \"Geekforgeeks\" s1 = slice(-1) # print everything except the last elementprint(String[s1]) # print everything between both indexprint(String[0:-3])",
"e": 4319,
"s": 4141,
"text": null
},
{
"code": null,
"e": 4342,
"s": 4319,
"text": "Geekforgeek\nGeekforge\n"
},
{
"code": null,
"e": 4561,
"s": 4342,
"text": " We can use [ : : ] for specifying the frequency to print elements. It specifies the step after which every element will be printed starting from the given index. If nothing is given then it starts from the 0th index."
},
{
"code": null,
"e": 4569,
"s": 4561,
"text": "Python3"
},
{
"code": "# Creating a StringString = \"Geekforgeeks\" # print everything with step 1print(String[::1]) # print everything with step 2print(String[2::2]) # print a string backwardsprint(String[::-1])",
"e": 4760,
"s": 4569,
"text": null
},
{
"code": null,
"e": 4793,
"s": 4760,
"text": "Geekforgeeks\nefrek\nskeegrofkeeG\n"
},
{
"code": null,
"e": 4852,
"s": 4793,
"text": "Note: For more information, refer String Slicing in Python"
},
{
"code": null,
"e": 5063,
"s": 4852,
"text": "str.format() and f-strings methods are used to add formatted objects to printed string statements. The string format() method formats the given string. It allows for multiple substitutions and value formatting."
},
{
"code": null,
"e": 5071,
"s": 5063,
"text": "Python3"
},
{
"code": "# using format option in a simple stringString = 'Geeksforgeeks'print(\"{}, A computer science portal for geeks.\" .format(String)) String = 'Geeks'print(\"Hello {}, How are you ?\".format(String)) # formatting a string using a numeric constantval = 2print(\"I want {} Burgers! \".format(val))",
"e": 5366,
"s": 5071,
"text": null
},
{
"code": null,
"e": 5465,
"s": 5366,
"text": "Geeksforgeeks, A computer science portal for geeks.\nHello Geeks, How are you ?\nI want 2 Burgers! \n"
},
{
"code": null,
"e": 5526,
"s": 5465,
"text": "Note: For more information, refer Python | format() function"
},
{
"code": null,
"e": 5661,
"s": 5526,
"text": "Formatted f-string literals are prefixed with βfβ and curly braces { } containing expressions that will be replaced with their values."
},
{
"code": null,
"e": 5669,
"s": 5661,
"text": "Python3"
},
{
"code": "# Creating stringString = 'GeekForGeeks'print(f\"{String}: A Computer Science portal for geeks\") # Creating stringString = 'Geek'print(f\"Yes, I am {String}\") # Manuplating int within {}bags = 3book_in_bag = 12print(f'There are total {bags * book_in_bag} books') # work with dictionaries in f-stringsDic = {'Portal': 'Geeksforgeeks', 'for': 'Geeks'}print(f\"{Dic['Portal']} is a computer science portal for {Dic['for']}\")",
"e": 6091,
"s": 5669,
"text": null
},
{
"code": null,
"e": 6235,
"s": 6091,
"text": "GeekForGeeks: A Computer Science portal for geeks\nYes, I am Geek\nThere are total 36 books\nGeeksforgeeks is a computer science portal for Geeks\n"
},
{
"code": null,
"e": 6319,
"s": 6235,
"text": "Note: For more information, refer f-strings in Python 3 β Formatted string literals"
},
{
"code": null,
"e": 6333,
"s": 6319,
"text": "python-string"
},
{
"code": null,
"e": 6340,
"s": 6333,
"text": "Python"
}
] |
Implement Phone Directory using Hashing | 26 Jun, 2020
Hashing is a technique that uses fewer key comparisons and searches the element in O(n) time in the worst case and in O(1) time in the average case.
The task is to implement all functions of phone directory:create_recorddisplay_recorddelete_recordsearch_recordupdate_record
create_record
display_record
delete_record
search_record
update_record
Following data will be taken from the client:
ID, Name, Telephone number
Approach:We are creating a hash table, and inserting records. For deleting, searching, or updating an entity, the client ID is asked and on the basis of equality operator, details are displayed or processed. If the record is not found, then an appropriate message is displayed.
Collision is the major problem in the hashing technique. In open addressing (closed hashing), all collisions are resolved in the prime area i.e., the area that contains all of the home addresses.
When a collision occurs, the prime area addresses are searched for an open or unoccupied element using linear probing.Steps for inserting entities in a hash table:1. If the location is empty, directly insert the entity.2. If mapped location is occupied then keep probing until an empty slot is found. Once an empty slot is found, insert the entity.
Create Record: This method takes details from the user like ID, Name and Telephone number and create new record in the hashtable.Display Record: This function is created to display all the record of the diary.Delete Record: This method takes the key of the record to be deleted. Then, it searches in hash table if record id matches with the key. Then, that record is deleted.Search Record: This method takes the key of the record to be searched. Then, it traverses the hash table, if record id matches with the key it displays the record detail.Update Record: This method takes the key of the record to be searched. Then, it traverses the hash table, if record id matches with the key then it displays the record detail.
Create Record: This method takes details from the user like ID, Name and Telephone number and create new record in the hashtable.
Display Record: This function is created to display all the record of the diary.
Delete Record: This method takes the key of the record to be deleted. Then, it searches in hash table if record id matches with the key. Then, that record is deleted.
Search Record: This method takes the key of the record to be searched. Then, it traverses the hash table, if record id matches with the key it displays the record detail.
Update Record: This method takes the key of the record to be searched. Then, it traverses the hash table, if record id matches with the key then it displays the record detail.
Below is the implementation of the above approach:
C++
#include <iostream>using namespace std; // Class to store contact// detailsclass node { string name; long int tel; int id; public: node() { tel = 0; id = 0; } friend class hashing;}; class hashing { // Maximum size of // directory is 100 node data[100]; string n; long int t; int i, index; public: hashing() { i = 0; t = 0; } // This method takes details // from the user like ID, // Name and Telephone number // and create new record in // the hashtable. void create_record(int size) { // Enter ID i = 4; // Enter Name n = "XYZ Gupta"; // Enter telephone number t = 23451234; cout << "\nEnter id :"; cout << " \t\t\t" << i; cout << "\nEnter name :"; cout << " \t\t\t " << n; cout << "\nEnter telephone"; cout << " number :\t" << t; index = i % size; // Inserting record using linear // probing in case of collision for (int j = 0; j < size; j++) { if (data[index].id == 0) { data[index].id = i; data[index].name = n; data[index].tel = t; break; } else index = (index + 1) % size; } } // This method takes the key of // the record to be searched. // Then, it traverses the hash // table, if record id matches // with the key it displays the // record detail. void search_record(int size) { int index1, key, flag = 0; key = 4; cout << "\nEnter record"; cout << " id to search : " << key; index1 = key % size; // Traversing the directory // linearly inorder to search // record detail for (int a = 0; a < size; a++) { if (data[index1].id == key) { flag = 1; cout << "\nRecord found:"; cout << "\n\tID "; cout << "\tNAME "; cout << "\t\tTELEPHONE "; cout << "\n\t" << data[index1].id << " \t" << data[index1].name << " \t" << data[index1].tel; break; } else index1 = (index1 + 1) % size; } if (flag == 0) cout << "\nRecord"; cout << " not found"; } // This method takes the key // of the record to be deleted. // Then, it searches in hash // table if record id matches // with the key. Then, that // record is deleted. void delete_record(int size) { int index1, key, flag = 0; key = 4; cout << "\nEnter record"; cout << " id to delete : " << key << "\n "; index1 = key % size; // Traversing the directory // linearly inorder to delete // the record detail for (int a = 0; a < size; a++) { if (data[index1].id == key) { flag = 1; data[index1].id = 0; data[index1].name = " "; data[index1].tel = 0; cout << "\nRecord"; cout << " deleted"; cout << " successfully"; break; } else index1 = (index1 + 1) % size; } if (flag == 0) cout << "\nRecord"; cout << " not found"; } // This method takes the key // of the record to be searched. // Then, it traverses the hash table, // if record id matches with the // key then it displays the record // detail. void update_record(int size) { int index1, key, flag = 0; key = 4; cout << "\nEnter record"; cout << " id to update : " << key; index1 = key % size; // Traversing the directory // linearly inorder to search // record detail for (int a = 0; a < size; a++) { if (data[index1].id == key) { flag = 1; break; } else index1 = (index1 + 1) % size; } // If the record is found // the details are updated if (flag == 1) { n = "XYZ Agarwal"; t = 23413421; data[index1].name = n; data[index1].tel = t; cout << "\nEnter"; cout << " name: \t\t\t" << n; cout << "\nEnter"; cout << " telephone number: \t" << t; cout << "\nDetails updated: "; cout << "\n\tID \tNAME"; cout << " \t\tTELEPHONE "; cout << "\n\t" << data[index1].id << " \t" << data[index1].name << " \t" << data[index1].tel; } } // This function is created to // display all the record of // the diary. void display_record(int size) { cout << "\n\tID \tNAME"; cout << " \t\tTELEPHONE "; // Displaying the details of // all records of the directory. for (int a = 0; a < size; a++) { if (data[a].id != 0) { cout << "\n\t" << data[a].id << " \t" << data[a].name << " \t" << data[a].tel; } } }}; // Driver codeint main(){ // size of directory int size; // creating object of hashing // class hashing s; size = 20; // Creating a record in // directory cout << "\n1.CREATE record "; s.create_record(size); // Display available // record details cout << "\n\n\n\n2.DISPLAY"; cout << " record "; s.display_record(size); // Searching a record detail // in the directory cout << "\n\n\n\n3.SEARCH"; cout << " record"; s.search_record(size); // Updating the existing // details of a record cout << "\n\n\n\n4.UPDATE"; cout << " record "; s.update_record(size); // Removing specified // existing record // from dictionary cout << "\n\n\n\n5.DELETE"; cout << " record "; s.delete_record(size); return 0;}
Hash
Project
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Jun, 2020"
},
{
"code": null,
"e": 201,
"s": 52,
"text": "Hashing is a technique that uses fewer key comparisons and searches the element in O(n) time in the worst case and in O(1) time in the average case."
},
{
"code": null,
"e": 326,
"s": 201,
"text": "The task is to implement all functions of phone directory:create_recorddisplay_recorddelete_recordsearch_recordupdate_record"
},
{
"code": null,
"e": 340,
"s": 326,
"text": "create_record"
},
{
"code": null,
"e": 355,
"s": 340,
"text": "display_record"
},
{
"code": null,
"e": 369,
"s": 355,
"text": "delete_record"
},
{
"code": null,
"e": 383,
"s": 369,
"text": "search_record"
},
{
"code": null,
"e": 397,
"s": 383,
"text": "update_record"
},
{
"code": null,
"e": 443,
"s": 397,
"text": "Following data will be taken from the client:"
},
{
"code": null,
"e": 470,
"s": 443,
"text": "ID, Name, Telephone number"
},
{
"code": null,
"e": 748,
"s": 470,
"text": "Approach:We are creating a hash table, and inserting records. For deleting, searching, or updating an entity, the client ID is asked and on the basis of equality operator, details are displayed or processed. If the record is not found, then an appropriate message is displayed."
},
{
"code": null,
"e": 944,
"s": 748,
"text": "Collision is the major problem in the hashing technique. In open addressing (closed hashing), all collisions are resolved in the prime area i.e., the area that contains all of the home addresses."
},
{
"code": null,
"e": 1293,
"s": 944,
"text": "When a collision occurs, the prime area addresses are searched for an open or unoccupied element using linear probing.Steps for inserting entities in a hash table:1. If the location is empty, directly insert the entity.2. If mapped location is occupied then keep probing until an empty slot is found. Once an empty slot is found, insert the entity."
},
{
"code": null,
"e": 2014,
"s": 1293,
"text": "Create Record: This method takes details from the user like ID, Name and Telephone number and create new record in the hashtable.Display Record: This function is created to display all the record of the diary.Delete Record: This method takes the key of the record to be deleted. Then, it searches in hash table if record id matches with the key. Then, that record is deleted.Search Record: This method takes the key of the record to be searched. Then, it traverses the hash table, if record id matches with the key it displays the record detail.Update Record: This method takes the key of the record to be searched. Then, it traverses the hash table, if record id matches with the key then it displays the record detail."
},
{
"code": null,
"e": 2144,
"s": 2014,
"text": "Create Record: This method takes details from the user like ID, Name and Telephone number and create new record in the hashtable."
},
{
"code": null,
"e": 2225,
"s": 2144,
"text": "Display Record: This function is created to display all the record of the diary."
},
{
"code": null,
"e": 2392,
"s": 2225,
"text": "Delete Record: This method takes the key of the record to be deleted. Then, it searches in hash table if record id matches with the key. Then, that record is deleted."
},
{
"code": null,
"e": 2563,
"s": 2392,
"text": "Search Record: This method takes the key of the record to be searched. Then, it traverses the hash table, if record id matches with the key it displays the record detail."
},
{
"code": null,
"e": 2739,
"s": 2563,
"text": "Update Record: This method takes the key of the record to be searched. Then, it traverses the hash table, if record id matches with the key then it displays the record detail."
},
{
"code": null,
"e": 2790,
"s": 2739,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2794,
"s": 2790,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; // Class to store contact// detailsclass node { string name; long int tel; int id; public: node() { tel = 0; id = 0; } friend class hashing;}; class hashing { // Maximum size of // directory is 100 node data[100]; string n; long int t; int i, index; public: hashing() { i = 0; t = 0; } // This method takes details // from the user like ID, // Name and Telephone number // and create new record in // the hashtable. void create_record(int size) { // Enter ID i = 4; // Enter Name n = \"XYZ Gupta\"; // Enter telephone number t = 23451234; cout << \"\\nEnter id :\"; cout << \" \\t\\t\\t\" << i; cout << \"\\nEnter name :\"; cout << \" \\t\\t\\t \" << n; cout << \"\\nEnter telephone\"; cout << \" number :\\t\" << t; index = i % size; // Inserting record using linear // probing in case of collision for (int j = 0; j < size; j++) { if (data[index].id == 0) { data[index].id = i; data[index].name = n; data[index].tel = t; break; } else index = (index + 1) % size; } } // This method takes the key of // the record to be searched. // Then, it traverses the hash // table, if record id matches // with the key it displays the // record detail. void search_record(int size) { int index1, key, flag = 0; key = 4; cout << \"\\nEnter record\"; cout << \" id to search : \" << key; index1 = key % size; // Traversing the directory // linearly inorder to search // record detail for (int a = 0; a < size; a++) { if (data[index1].id == key) { flag = 1; cout << \"\\nRecord found:\"; cout << \"\\n\\tID \"; cout << \"\\tNAME \"; cout << \"\\t\\tTELEPHONE \"; cout << \"\\n\\t\" << data[index1].id << \" \\t\" << data[index1].name << \" \\t\" << data[index1].tel; break; } else index1 = (index1 + 1) % size; } if (flag == 0) cout << \"\\nRecord\"; cout << \" not found\"; } // This method takes the key // of the record to be deleted. // Then, it searches in hash // table if record id matches // with the key. Then, that // record is deleted. void delete_record(int size) { int index1, key, flag = 0; key = 4; cout << \"\\nEnter record\"; cout << \" id to delete : \" << key << \"\\n \"; index1 = key % size; // Traversing the directory // linearly inorder to delete // the record detail for (int a = 0; a < size; a++) { if (data[index1].id == key) { flag = 1; data[index1].id = 0; data[index1].name = \" \"; data[index1].tel = 0; cout << \"\\nRecord\"; cout << \" deleted\"; cout << \" successfully\"; break; } else index1 = (index1 + 1) % size; } if (flag == 0) cout << \"\\nRecord\"; cout << \" not found\"; } // This method takes the key // of the record to be searched. // Then, it traverses the hash table, // if record id matches with the // key then it displays the record // detail. void update_record(int size) { int index1, key, flag = 0; key = 4; cout << \"\\nEnter record\"; cout << \" id to update : \" << key; index1 = key % size; // Traversing the directory // linearly inorder to search // record detail for (int a = 0; a < size; a++) { if (data[index1].id == key) { flag = 1; break; } else index1 = (index1 + 1) % size; } // If the record is found // the details are updated if (flag == 1) { n = \"XYZ Agarwal\"; t = 23413421; data[index1].name = n; data[index1].tel = t; cout << \"\\nEnter\"; cout << \" name: \\t\\t\\t\" << n; cout << \"\\nEnter\"; cout << \" telephone number: \\t\" << t; cout << \"\\nDetails updated: \"; cout << \"\\n\\tID \\tNAME\"; cout << \" \\t\\tTELEPHONE \"; cout << \"\\n\\t\" << data[index1].id << \" \\t\" << data[index1].name << \" \\t\" << data[index1].tel; } } // This function is created to // display all the record of // the diary. void display_record(int size) { cout << \"\\n\\tID \\tNAME\"; cout << \" \\t\\tTELEPHONE \"; // Displaying the details of // all records of the directory. for (int a = 0; a < size; a++) { if (data[a].id != 0) { cout << \"\\n\\t\" << data[a].id << \" \\t\" << data[a].name << \" \\t\" << data[a].tel; } } }}; // Driver codeint main(){ // size of directory int size; // creating object of hashing // class hashing s; size = 20; // Creating a record in // directory cout << \"\\n1.CREATE record \"; s.create_record(size); // Display available // record details cout << \"\\n\\n\\n\\n2.DISPLAY\"; cout << \" record \"; s.display_record(size); // Searching a record detail // in the directory cout << \"\\n\\n\\n\\n3.SEARCH\"; cout << \" record\"; s.search_record(size); // Updating the existing // details of a record cout << \"\\n\\n\\n\\n4.UPDATE\"; cout << \" record \"; s.update_record(size); // Removing specified // existing record // from dictionary cout << \"\\n\\n\\n\\n5.DELETE\"; cout << \" record \"; s.delete_record(size); return 0;}",
"e": 9226,
"s": 2794,
"text": null
},
{
"code": null,
"e": 9231,
"s": 9226,
"text": "Hash"
},
{
"code": null,
"e": 9239,
"s": 9231,
"text": "Project"
},
{
"code": null,
"e": 9244,
"s": 9239,
"text": "Hash"
}
] |
HTML | DOM Style display Property | 05 Jun, 2022
The Style display property in HTML DOM is used to set or return the display type of an element. It is similar to the visibility property, which display or hide the element. With a slight difference of display: none, hiding the entire element, while visibility: hidden meaning only the contents of the element will be invisible, but the element will remain in its original position and size.
Syntax:
It returns the display property.
object.style.display
It sets the display property.
object.style.display = value;
Property Values:
inline: It is the default value. It renders the element as an inline element.
block: It renders the element as a block-level element.
compact: It renders the element as a block-level or inline, depending on the context.
flex: It renders the element as a block-level flex box.
inline-block: It renders the element as a block box inside an inline box.
inline-flex: It renders the element as an inline-level flex box.
inline-table: It renders the element as an inline table.
list-item: It renders the element as a list.
marker: It sets content before or after the box as a marker.
none: It will not display any element.
run-in: It renders the element as block-level or inline, depending on the context.
table: It renders the element as a block table, with a line break before and after the table.
table-caption: It renders the element as a table caption.
table-cell: It renders the element as a table cell.
table-column: It renders the element as a column of cells.
table-column-group: It renders the element as a group of one or more columns.
table-footer-group: It renders the element as a table footer row.
table-header-group: It renders the element as a table header row.
table-row: It renders the element as a table row.
table-row-group: Element is rendered as a group of one or more rows.
initial: It sets the display property to its default value.
inherit: It inherits the display property values from its parent element.
Return Value: It returns a string, representing the display type of the element.
Example 1: This example describes the inline property value.
html
<!DOCTYPE html><html> <head> <title> HTML DOM Style display Property </title></head> <body> <h2> HTML DOM Display Property </h2> <p> Click on the button to set display property </p> <div id = "GFG"> Geeks for Geeks </div> <button onclick="myGeeks()"> Press </button> <!-- script to set display property --> <script> function myGeeks() { document.getElementById("GFG").style.display = "inline"; } </script></body> </html>
Output: Before click on the button:
After click on the button:
Example 2: This example describes the none property value.
html
<!DOCTYPE html><html> <head> <title> HTML DOM Style display Property </title></head> <body> <h2> HTML DOM Display Property </h2> <p> Click on the button to set display property </p> <div id = "GFG"> Geeks for Geeks </div> <button onclick="myGeeks()"> Press </button> <!-- script to set display property --> <script> function myGeeks() { document.getElementById("GFG").style.display = "none"; } </script></body> </html>
Output: Before click on the button:
After click on the button:
Example 3: This example describes the table-caption property value.
html
<!DOCTYPE html><html> <head> <title> HTML DOM Style display Property </title></head> <body> <h2> HTML DOM Display Property </h2> <p> Click on the button to set display property </p> <div id = "GFG"> Geeks for Geeks </div> <button onclick="myGeeks()"> Press </button> <!-- script to set display property --> <script> function myGeeks() { document.getElementById("GFG").style.display = "table-caption"; } </script></body> </html>
Output: Before click on the button:
After click on the button:
Example 4: This example describes the block property value.
html
<!DOCTYPE html><html> <head> <title> HTML DOM Style display Property </title></head> <body> <h2> HTML DOM Display Property </h2> <p> Click on the button to set display property </p> <div id = "GFG"> Geeks for Geeks </div> <button onclick="myGeeks()"> Press </button> <!-- script to set display property --> <script> function myGeeks() { document.getElementById("GFG").style.display = "block"; } </script></body> </html>
Output: Before click on the button:
After click on the button:
Supported Browsers: The browser supported by DOM style display property are listed below:
Google Chrome 1 and above
Edge 12 and above
Internet Explorer 4 and above
Firefox 1 and above
Opera 7 and above
Safari 1 and above
kumargaurav97520
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jun, 2022"
},
{
"code": null,
"e": 420,
"s": 28,
"text": "The Style display property in HTML DOM is used to set or return the display type of an element. It is similar to the visibility property, which display or hide the element. With a slight difference of display: none, hiding the entire element, while visibility: hidden meaning only the contents of the element will be invisible, but the element will remain in its original position and size. "
},
{
"code": null,
"e": 428,
"s": 420,
"text": "Syntax:"
},
{
"code": null,
"e": 461,
"s": 428,
"text": "It returns the display property."
},
{
"code": null,
"e": 482,
"s": 461,
"text": "object.style.display"
},
{
"code": null,
"e": 512,
"s": 482,
"text": "It sets the display property."
},
{
"code": null,
"e": 542,
"s": 512,
"text": "object.style.display = value;"
},
{
"code": null,
"e": 559,
"s": 542,
"text": "Property Values:"
},
{
"code": null,
"e": 637,
"s": 559,
"text": "inline: It is the default value. It renders the element as an inline element."
},
{
"code": null,
"e": 693,
"s": 637,
"text": "block: It renders the element as a block-level element."
},
{
"code": null,
"e": 779,
"s": 693,
"text": "compact: It renders the element as a block-level or inline, depending on the context."
},
{
"code": null,
"e": 835,
"s": 779,
"text": "flex: It renders the element as a block-level flex box."
},
{
"code": null,
"e": 909,
"s": 835,
"text": "inline-block: It renders the element as a block box inside an inline box."
},
{
"code": null,
"e": 974,
"s": 909,
"text": "inline-flex: It renders the element as an inline-level flex box."
},
{
"code": null,
"e": 1031,
"s": 974,
"text": "inline-table: It renders the element as an inline table."
},
{
"code": null,
"e": 1076,
"s": 1031,
"text": "list-item: It renders the element as a list."
},
{
"code": null,
"e": 1137,
"s": 1076,
"text": "marker: It sets content before or after the box as a marker."
},
{
"code": null,
"e": 1176,
"s": 1137,
"text": "none: It will not display any element."
},
{
"code": null,
"e": 1259,
"s": 1176,
"text": "run-in: It renders the element as block-level or inline, depending on the context."
},
{
"code": null,
"e": 1353,
"s": 1259,
"text": "table: It renders the element as a block table, with a line break before and after the table."
},
{
"code": null,
"e": 1411,
"s": 1353,
"text": "table-caption: It renders the element as a table caption."
},
{
"code": null,
"e": 1463,
"s": 1411,
"text": "table-cell: It renders the element as a table cell."
},
{
"code": null,
"e": 1522,
"s": 1463,
"text": "table-column: It renders the element as a column of cells."
},
{
"code": null,
"e": 1600,
"s": 1522,
"text": "table-column-group: It renders the element as a group of one or more columns."
},
{
"code": null,
"e": 1666,
"s": 1600,
"text": "table-footer-group: It renders the element as a table footer row."
},
{
"code": null,
"e": 1732,
"s": 1666,
"text": "table-header-group: It renders the element as a table header row."
},
{
"code": null,
"e": 1782,
"s": 1732,
"text": "table-row: It renders the element as a table row."
},
{
"code": null,
"e": 1851,
"s": 1782,
"text": "table-row-group: Element is rendered as a group of one or more rows."
},
{
"code": null,
"e": 1911,
"s": 1851,
"text": "initial: It sets the display property to its default value."
},
{
"code": null,
"e": 1985,
"s": 1911,
"text": "inherit: It inherits the display property values from its parent element."
},
{
"code": null,
"e": 2067,
"s": 1985,
"text": "Return Value: It returns a string, representing the display type of the element. "
},
{
"code": null,
"e": 2129,
"s": 2067,
"text": "Example 1: This example describes the inline property value. "
},
{
"code": null,
"e": 2134,
"s": 2129,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML DOM Style display Property </title></head> <body> <h2> HTML DOM Display Property </h2> <p> Click on the button to set display property </p> <div id = \"GFG\"> Geeks for Geeks </div> <button onclick=\"myGeeks()\"> Press </button> <!-- script to set display property --> <script> function myGeeks() { document.getElementById(\"GFG\").style.display = \"inline\"; } </script></body> </html> ",
"e": 2719,
"s": 2134,
"text": null
},
{
"code": null,
"e": 2755,
"s": 2719,
"text": "Output: Before click on the button:"
},
{
"code": null,
"e": 2785,
"s": 2758,
"text": "After click on the button:"
},
{
"code": null,
"e": 2848,
"s": 2788,
"text": "Example 2: This example describes the none property value. "
},
{
"code": null,
"e": 2853,
"s": 2848,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML DOM Style display Property </title></head> <body> <h2> HTML DOM Display Property </h2> <p> Click on the button to set display property </p> <div id = \"GFG\"> Geeks for Geeks </div> <button onclick=\"myGeeks()\"> Press </button> <!-- script to set display property --> <script> function myGeeks() { document.getElementById(\"GFG\").style.display = \"none\"; } </script></body> </html> ",
"e": 3436,
"s": 2853,
"text": null
},
{
"code": null,
"e": 3472,
"s": 3436,
"text": "Output: Before click on the button:"
},
{
"code": null,
"e": 3502,
"s": 3475,
"text": "After click on the button:"
},
{
"code": null,
"e": 3574,
"s": 3505,
"text": "Example 3: This example describes the table-caption property value. "
},
{
"code": null,
"e": 3579,
"s": 3574,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML DOM Style display Property </title></head> <body> <h2> HTML DOM Display Property </h2> <p> Click on the button to set display property </p> <div id = \"GFG\"> Geeks for Geeks </div> <button onclick=\"myGeeks()\"> Press </button> <!-- script to set display property --> <script> function myGeeks() { document.getElementById(\"GFG\").style.display = \"table-caption\"; } </script></body> </html> ",
"e": 4171,
"s": 3579,
"text": null
},
{
"code": null,
"e": 4207,
"s": 4171,
"text": "Output: Before click on the button:"
},
{
"code": null,
"e": 4237,
"s": 4210,
"text": "After click on the button:"
},
{
"code": null,
"e": 4301,
"s": 4240,
"text": "Example 4: This example describes the block property value. "
},
{
"code": null,
"e": 4306,
"s": 4301,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML DOM Style display Property </title></head> <body> <h2> HTML DOM Display Property </h2> <p> Click on the button to set display property </p> <div id = \"GFG\"> Geeks for Geeks </div> <button onclick=\"myGeeks()\"> Press </button> <!-- script to set display property --> <script> function myGeeks() { document.getElementById(\"GFG\").style.display = \"block\"; } </script></body> </html> ",
"e": 4890,
"s": 4306,
"text": null
},
{
"code": null,
"e": 4926,
"s": 4890,
"text": "Output: Before click on the button:"
},
{
"code": null,
"e": 4956,
"s": 4929,
"text": "After click on the button:"
},
{
"code": null,
"e": 5049,
"s": 4959,
"text": "Supported Browsers: The browser supported by DOM style display property are listed below:"
},
{
"code": null,
"e": 5075,
"s": 5049,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 5093,
"s": 5075,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 5123,
"s": 5093,
"text": "Internet Explorer 4 and above"
},
{
"code": null,
"e": 5143,
"s": 5123,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 5161,
"s": 5143,
"text": "Opera 7 and above"
},
{
"code": null,
"e": 5180,
"s": 5161,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 5197,
"s": 5180,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 5206,
"s": 5197,
"text": "HTML-DOM"
},
{
"code": null,
"e": 5213,
"s": 5206,
"text": "Picked"
},
{
"code": null,
"e": 5218,
"s": 5213,
"text": "HTML"
},
{
"code": null,
"e": 5235,
"s": 5218,
"text": "Web Technologies"
},
{
"code": null,
"e": 5240,
"s": 5235,
"text": "HTML"
}
] |
Types of Locks in Concurrency Control | 11 Jan, 2022
Commercial demands for ensuring smooth functionality and highly efficient run-time servers, make it highly prime for Database Designers to work out systems and code which cleverly avoid any kinds of inconsistencies in multi-user transactions, if not doubt the standard of memory management in read-heavy, write-heavy and all such commercial databases. This article shall give an adequate introduction to the classic locking architecture that was proposed and implemented for the database developer community.
We should try to overlook the techniques of locking in general, i.e., based on the granularity or level of the database. This is so we may deal with it separately when looking at the feasibility of the types of locks.
Definition :The formal definition of a lock is as follows:
A Lock is a variable assigned to any data item in order to keep track of the status of that data item so that isolation and non-interference is ensured during concurrent transactions.
At its basic, a database lock exists to prevent two or more database users from performing any change on the same data item at the very same time. Therefore, it is correct to interpret this technique as a means of synchronizing access, which is in stark contrast to other sets of protocols such as those using timestamps and multiversion timestamps. In laymanβs terms, this may be further simplified to the metaphorical βlockβ that is put on a data item so that no other user may unlock the ability to perform any update query.
Case 1: Simultaneous access to transactions is not permitted. Case 2: putting a lock on other transactions is feasible
In Case 2, which has been portrayed above, if the user/session on the right attempts an update, it will be met with a LOCK WAIT state or otherwise be STALLED until access to the data item is unlocked. In some situations β if the stall exceeds a time limit β the session is terminated and an error statement is returned.
We shall look at the multiple ways these locks have been introduced in the industry as solutions to concurrency in transactions.
Binary Locks :Remember that a lock is fundamentally a variable which holds a value. A binary lock is a variable capable of holding only 2 possible values, i.e., a 1 (depicting a locked state) or a 0 (depicting an unlocked state). This lock is usually associated with every data item in the database ( maybe at table level, row level or even the entire database level).
Should item X be unlocked, then a corresponding object lock(X) would return the value 0. So, the instant a user/session begins updating the contents of item X, lock(X) is set to a value of 1. Due to this, for as long as the update query lasts, no other user may access the item X β even read or write to it!
There are 2 operations used to implement binary locks. They are lock_data( ) and unlock_data( ). The algorithms have been discussed below (only algorithms have been entertained due to the diversity in DBMS scripts):
The locking operation :
lock_data(X):
label: if lock(X) == 0
{
then lock(X) = 1;
}
else //when lock(X) == 1 or item X is locked
{
wait (until item is unlocked or lock(X)=0) //wait for the user to finish the update query
go to label
}
Note that βlabel:β is literally a label for the line which can be referred to at a later step to transfer execution to. The βwaitβ command in the else block basically puts all other transactions wanting to access X in a queue. Since it monitors or keeps other transactions scheduled until access to the item is unlocked, it is often taken to be outside the lock_data(X) operation i.e., defined outside.
The unlocking operation :
unlock_data(X):
lock(X) = 0 //we unlock access to item X
if (transactions are in queue)
{
then grant access or 'wake' the next transaction in line;
}
Merits of Binary Locks :
They are simple to implement since they are effectively mutually exclusive and establish isolation perfectly.
Binary Locks demand less from the system since the system must only keep a record of the locked items. The system is the lock manager subsystem which is a feature of all DBMSs today.
Drawbacks of Binary Locks :
Binary locks are highly restrictive.
They do not even permit reading of the contents of item X. As a result, they are not used commercially.
Shared or Exclusive Locks :The incentive governing these types of locks is the restrictive nature of binary locks. Here we look at locks which permit other transactions to make read queries since a READ query is non-conflicting. However, if a transaction demands a write query on item X, then that transaction must be given exclusive access to item X. Ergo, we require a kind of multi-mode lock which is what shared/exclusive locks are. They are also known as Read/Write locks.
Unlike binary locks, Read/Write locks may be set to 3 values, i.e., SHARED, EXCLUSIVE or UNLOCKED. Hence, our lock, i.e., lock(X), may reflect either of the following values:
READ-LOCKED βIf a transaction only requires to read the contents of item X and the lock only permits reading. This is also known as a shared lock.WRITE-LOCKED βIf a transaction needs to update or write to item X, the lock must restrict all other transactions and provide exclusive access to the current transaction. Thus, these locks are also known as exclusive locks.UNLOCKED βOnce a transaction has completed its read or update operations, no lock is held and the data item is unlocked. In this state, the item may be accessed by any queued transactions.
READ-LOCKED βIf a transaction only requires to read the contents of item X and the lock only permits reading. This is also known as a shared lock.
WRITE-LOCKED βIf a transaction needs to update or write to item X, the lock must restrict all other transactions and provide exclusive access to the current transaction. Thus, these locks are also known as exclusive locks.
UNLOCKED βOnce a transaction has completed its read or update operations, no lock is held and the data item is unlocked. In this state, the item may be accessed by any queued transactions.
A Shared/Exclusive lock may hold any of the 3 states.
The most popular way of implementing these locks is by introducing a LOCK-TABLE which keeps track of the number of read-locks on the data items and the transactions with write-locks on different items. The table has been described below.
Note that if an item is write-locked, it is logically supposed to have no reads on account of the fact that it is now exclusive. As a result, the βLocking Transactionβ column holds only one value β the transaction ID of the current transaction. If an item is read-locked, it is shared by multiple transactions and therefore, the βLocking Transactionβ column lists the transaction IDs of all the transactions. Since there are 3 states that the lock may hold, there must be 3 operations which would execute the change to those states. These are as follows :
The read_lock operation β
read_lock(X):
label: if lock(X) = "unlocked"
{
then lock(X) = "read-locked";
no_of_reads = 1; //since only the first transaction in queue is now able to read item X
}
else if lock(X) = "read-locked"
{
then no_of_reads +=1; //simply increment as a new transaction is now reading the item X
}
else //lock(X) write-locked
{
wait (until lock(X) is "unlocked");//transactions observe a LOCK WAIT during this time
go to label;
}
When the lock(X) is set to βwrite-lockedβ (in the final else clause), the item is exclusively being accessed by a transaction. In order for other transactions to access it, the LOCK WAIT must end (updating process must finish) and lock(X) = βunlockedβ. This is what we wait for in the next line.
The write_lock operation β
write_lock(X):
label: if lock(X) = "unlocked"
{
then lock(X) = "write-locked"
}
else //if a read-lock is issued to item X
{
wait (until lock(X) is "unlocked"); //so that the lock manager may wake up the next transaction
go to label;
}
If an item is unlocked, we simply write-lock it to grant exclusive access to the current transaction. Now the lock manager system must put all other transactions in a queue. If the item is in a read-lock state, the write-lock may NOT be directly issued. The item must first be unlocked before it can be write-locked. In doing so, the lock manager system also wakes up the queued transactions.
The unlock operation β
unlock(X):
if lock(X) = "write-locked"
{
then lock(X) = "unlocked";
//the transactions in queue, if any, may now access item X in the manner they demand
}
else if lock(X) = "read-locked"
{
then
no_of_reads-=1; //the transaction is done reading.
if no_of_reads == 0 //no transactions reading the item
{
lock(X) = "unlocked";
//transactions in queue, if any, may now access item X in the manner they demand
}
}
The first case is straightforward enough. However, in the second case, we must check for the condition that there are no more current transactions sharing or reading item X. If item X is being read, we leave the situation and simply decrement the no_of_reads as the last transaction has terminated. The point here is that an item may be βunlocked only if:
the βwriteβ operation terminates or is completed
all βreadβ operations terminate or are completed
Here are a few rules that Shared/Exclusive Locks must obey:
A transaction T MUST issue the unlock(X) operation after all read and write operations have finished.A transaction T may NOT issue a read_lock(X) or write_lock(X) operation on an item which already has a read or write-lock issued to itself.A transaction T is NOT allowed to issue the unlock(X) operation unless it has been issued with a read_lock(X) or write_lock(X) operation.
A transaction T MUST issue the unlock(X) operation after all read and write operations have finished.
A transaction T may NOT issue a read_lock(X) or write_lock(X) operation on an item which already has a read or write-lock issued to itself.
A transaction T is NOT allowed to issue the unlock(X) operation unless it has been issued with a read_lock(X) or write_lock(X) operation.
When we relax these rules, a new dimension of interchanging the status of locks on items can be introduced. This has been explained in the following article: Lock Based Concurrency Control Protocol in DBMS
Drawbacks of Shared/Exclusive Locks :
Do not guarantee serializability of schedules on their own. A separate protocol must be followed to ensure this.
Commercially not optimized for speedy transactions; not the best solution due to lock contention issues.
Performance overhead is not negligible.
Certify Locks :The motivation behind introducing certify locks is the failure of previously mentioned locks to deliver an efficient and promising architecture which does not compromise on speed of processing transactions. Here we briefly look at a form of multiple-mode locking scheme which allows for the lock to be characterized by 3 locked states and 1 unlocked state.
Transactions may issue any of 3 locked states or 1 unlocked state
The states an item may be issued are :
READ-LOCKED β same as the read-locked state explained earlier for Shared/Exclusive LocksWRITE-LOCKED β same as the write-locked state explained earlier for Shared/Exclusive LocksCERTIFY-LOCKED β This is an exclusive lock. This is used when 2 different transactions must be read and write respectively, to item X. In order for this to happen, a committed and a local version of the data item is created. The committed version is used by all transactions which have a read-lock issued to X. The local version of X is accessed by T only when a write-lock has been acquired by T. Once the writing or updating operation has been carried out by T on item X, T must obtain a certify-lock so that the committed version of data item X may be updated to the local versionβs contents and the local version may be discarded.UNLOCKED β same as the write-locked state explained earlier for Shared/Exclusive Locks
READ-LOCKED β same as the read-locked state explained earlier for Shared/Exclusive Locks
WRITE-LOCKED β same as the write-locked state explained earlier for Shared/Exclusive Locks
CERTIFY-LOCKED β This is an exclusive lock. This is used when 2 different transactions must be read and write respectively, to item X. In order for this to happen, a committed and a local version of the data item is created. The committed version is used by all transactions which have a read-lock issued to X. The local version of X is accessed by T only when a write-lock has been acquired by T. Once the writing or updating operation has been carried out by T on item X, T must obtain a certify-lock so that the committed version of data item X may be updated to the local versionβs contents and the local version may be discarded.
UNLOCKED β same as the write-locked state explained earlier for Shared/Exclusive Locks
Here is how a certify lock is used in multi-version concurrency control techniques:
In Step 2, two versions of Item X are created i.e., the committed and local versions.In Step 4, the transaction must issue a certify lock on all writes it has made. Only then can we proceed to the next step. The updates on Local version are now final.
Step 5
In order for multiple transactions to access the contents of data item X, a compatibility table must be drawn so that any collision or error is not returned, which may delay the process.
Locks on X
Yes
Yes
No
Yes
No
No
No
No
No
The correct way of interpreting this table is as follows. Consider two transactions, T and Tβ. Assign transaction T to either the rows or the columns. Do the exact opposite for Tβ. Now the compatibility between locks issued to an item X by T and Tβ can be cross-referenced. For example, assign T to rows and Tβ to the columns. If T issues a read-lock on X and Tβ issues a write-lock on X, the result is a βYesβ β this scenario is feasible. However, if T intends a write-lock on X and Tβ intends a certify-lock on X, the result is a βNoβ β implying an impossible scenario.
There are further topics which look at developing better and advanced techniques to handle concurrency control, such as timestamps, multiversion models of data items and snapshot isolation. However, comprehending the basicity of the idea is key when it comes to building a clear understanding of concepts which may be as complex as concurrency control.
gulshankumarar231
DBMS-Transactions and Concurrency Control
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 538,
"s": 28,
"text": "Commercial demands for ensuring smooth functionality and highly efficient run-time servers, make it highly prime for Database Designers to work out systems and code which cleverly avoid any kinds of inconsistencies in multi-user transactions, if not doubt the standard of memory management in read-heavy, write-heavy and all such commercial databases. This article shall give an adequate introduction to the classic locking architecture that was proposed and implemented for the database developer community. "
},
{
"code": null,
"e": 756,
"s": 538,
"text": "We should try to overlook the techniques of locking in general, i.e., based on the granularity or level of the database. This is so we may deal with it separately when looking at the feasibility of the types of locks."
},
{
"code": null,
"e": 816,
"s": 756,
"text": "Definition :The formal definition of a lock is as follows: "
},
{
"code": null,
"e": 1000,
"s": 816,
"text": "A Lock is a variable assigned to any data item in order to keep track of the status of that data item so that isolation and non-interference is ensured during concurrent transactions."
},
{
"code": null,
"e": 1528,
"s": 1000,
"text": "At its basic, a database lock exists to prevent two or more database users from performing any change on the same data item at the very same time. Therefore, it is correct to interpret this technique as a means of synchronizing access, which is in stark contrast to other sets of protocols such as those using timestamps and multiversion timestamps. In laymanβs terms, this may be further simplified to the metaphorical βlockβ that is put on a data item so that no other user may unlock the ability to perform any update query."
},
{
"code": null,
"e": 1647,
"s": 1528,
"text": "Case 1: Simultaneous access to transactions is not permitted. Case 2: putting a lock on other transactions is feasible"
},
{
"code": null,
"e": 1967,
"s": 1647,
"text": "In Case 2, which has been portrayed above, if the user/session on the right attempts an update, it will be met with a LOCK WAIT state or otherwise be STALLED until access to the data item is unlocked. In some situations β if the stall exceeds a time limit β the session is terminated and an error statement is returned."
},
{
"code": null,
"e": 2096,
"s": 1967,
"text": "We shall look at the multiple ways these locks have been introduced in the industry as solutions to concurrency in transactions."
},
{
"code": null,
"e": 2466,
"s": 2096,
"text": "Binary Locks :Remember that a lock is fundamentally a variable which holds a value. A binary lock is a variable capable of holding only 2 possible values, i.e., a 1 (depicting a locked state) or a 0 (depicting an unlocked state). This lock is usually associated with every data item in the database ( maybe at table level, row level or even the entire database level). "
},
{
"code": null,
"e": 2775,
"s": 2466,
"text": "Should item X be unlocked, then a corresponding object lock(X) would return the value 0. So, the instant a user/session begins updating the contents of item X, lock(X) is set to a value of 1. Due to this, for as long as the update query lasts, no other user may access the item X β even read or write to it! "
},
{
"code": null,
"e": 2991,
"s": 2775,
"text": "There are 2 operations used to implement binary locks. They are lock_data( ) and unlock_data( ). The algorithms have been discussed below (only algorithms have been entertained due to the diversity in DBMS scripts):"
},
{
"code": null,
"e": 3015,
"s": 2991,
"text": "The locking operation :"
},
{
"code": null,
"e": 3316,
"s": 3015,
"text": "lock_data(X):\nlabel: if lock(X) == 0\n {\n then lock(X) = 1;\n }\n else //when lock(X) == 1 or item X is locked\n { \n wait (until item is unlocked or lock(X)=0) //wait for the user to finish the update query\n go to label\n }"
},
{
"code": null,
"e": 3719,
"s": 3316,
"text": "Note that βlabel:β is literally a label for the line which can be referred to at a later step to transfer execution to. The βwaitβ command in the else block basically puts all other transactions wanting to access X in a queue. Since it monitors or keeps other transactions scheduled until access to the item is unlocked, it is often taken to be outside the lock_data(X) operation i.e., defined outside."
},
{
"code": null,
"e": 3746,
"s": 3719,
"text": " The unlocking operation :"
},
{
"code": null,
"e": 3924,
"s": 3746,
"text": "unlock_data(X):\n lock(X) = 0 //we unlock access to item X\n if (transactions are in queue)\n { \n then grant access or 'wake' the next transaction in line;\n }"
},
{
"code": null,
"e": 3949,
"s": 3924,
"text": "Merits of Binary Locks :"
},
{
"code": null,
"e": 4059,
"s": 3949,
"text": "They are simple to implement since they are effectively mutually exclusive and establish isolation perfectly."
},
{
"code": null,
"e": 4242,
"s": 4059,
"text": "Binary Locks demand less from the system since the system must only keep a record of the locked items. The system is the lock manager subsystem which is a feature of all DBMSs today."
},
{
"code": null,
"e": 4270,
"s": 4242,
"text": "Drawbacks of Binary Locks :"
},
{
"code": null,
"e": 4307,
"s": 4270,
"text": "Binary locks are highly restrictive."
},
{
"code": null,
"e": 4411,
"s": 4307,
"text": "They do not even permit reading of the contents of item X. As a result, they are not used commercially."
},
{
"code": null,
"e": 4889,
"s": 4411,
"text": "Shared or Exclusive Locks :The incentive governing these types of locks is the restrictive nature of binary locks. Here we look at locks which permit other transactions to make read queries since a READ query is non-conflicting. However, if a transaction demands a write query on item X, then that transaction must be given exclusive access to item X. Ergo, we require a kind of multi-mode lock which is what shared/exclusive locks are. They are also known as Read/Write locks."
},
{
"code": null,
"e": 5064,
"s": 4889,
"text": "Unlike binary locks, Read/Write locks may be set to 3 values, i.e., SHARED, EXCLUSIVE or UNLOCKED. Hence, our lock, i.e., lock(X), may reflect either of the following values:"
},
{
"code": null,
"e": 5621,
"s": 5064,
"text": "READ-LOCKED βIf a transaction only requires to read the contents of item X and the lock only permits reading. This is also known as a shared lock.WRITE-LOCKED βIf a transaction needs to update or write to item X, the lock must restrict all other transactions and provide exclusive access to the current transaction. Thus, these locks are also known as exclusive locks.UNLOCKED βOnce a transaction has completed its read or update operations, no lock is held and the data item is unlocked. In this state, the item may be accessed by any queued transactions."
},
{
"code": null,
"e": 5768,
"s": 5621,
"text": "READ-LOCKED βIf a transaction only requires to read the contents of item X and the lock only permits reading. This is also known as a shared lock."
},
{
"code": null,
"e": 5991,
"s": 5768,
"text": "WRITE-LOCKED βIf a transaction needs to update or write to item X, the lock must restrict all other transactions and provide exclusive access to the current transaction. Thus, these locks are also known as exclusive locks."
},
{
"code": null,
"e": 6180,
"s": 5991,
"text": "UNLOCKED βOnce a transaction has completed its read or update operations, no lock is held and the data item is unlocked. In this state, the item may be accessed by any queued transactions."
},
{
"code": null,
"e": 6234,
"s": 6180,
"text": "A Shared/Exclusive lock may hold any of the 3 states."
},
{
"code": null,
"e": 6472,
"s": 6234,
"text": "The most popular way of implementing these locks is by introducing a LOCK-TABLE which keeps track of the number of read-locks on the data items and the transactions with write-locks on different items. The table has been described below."
},
{
"code": null,
"e": 7028,
"s": 6472,
"text": "Note that if an item is write-locked, it is logically supposed to have no reads on account of the fact that it is now exclusive. As a result, the βLocking Transactionβ column holds only one value β the transaction ID of the current transaction. If an item is read-locked, it is shared by multiple transactions and therefore, the βLocking Transactionβ column lists the transaction IDs of all the transactions. Since there are 3 states that the lock may hold, there must be 3 operations which would execute the change to those states. These are as follows :"
},
{
"code": null,
"e": 7054,
"s": 7028,
"text": "The read_lock operation β"
},
{
"code": null,
"e": 7602,
"s": 7054,
"text": "read_lock(X):\nlabel: if lock(X) = \"unlocked\"\n {\n then lock(X) = \"read-locked\";\n no_of_reads = 1; //since only the first transaction in queue is now able to read item X\n }\n else if lock(X) = \"read-locked\"\n {\n then no_of_reads +=1; //simply increment as a new transaction is now reading the item X\n }\n else //lock(X) write-locked\n {\n wait (until lock(X) is \"unlocked\");//transactions observe a LOCK WAIT during this time\n go to label;\n }"
},
{
"code": null,
"e": 7898,
"s": 7602,
"text": "When the lock(X) is set to βwrite-lockedβ (in the final else clause), the item is exclusively being accessed by a transaction. In order for other transactions to access it, the LOCK WAIT must end (updating process must finish) and lock(X) = βunlockedβ. This is what we wait for in the next line."
},
{
"code": null,
"e": 7925,
"s": 7898,
"text": "The write_lock operation β"
},
{
"code": null,
"e": 8237,
"s": 7925,
"text": "write_lock(X):\nlabel: if lock(X) = \"unlocked\"\n {\n then lock(X) = \"write-locked\"\n }\n else //if a read-lock is issued to item X\n {\n wait (until lock(X) is \"unlocked\"); //so that the lock manager may wake up the next transaction\n go to label;\n }"
},
{
"code": null,
"e": 8630,
"s": 8237,
"text": "If an item is unlocked, we simply write-lock it to grant exclusive access to the current transaction. Now the lock manager system must put all other transactions in a queue. If the item is in a read-lock state, the write-lock may NOT be directly issued. The item must first be unlocked before it can be write-locked. In doing so, the lock manager system also wakes up the queued transactions."
},
{
"code": null,
"e": 8653,
"s": 8630,
"text": "The unlock operation β"
},
{
"code": null,
"e": 9190,
"s": 8653,
"text": "unlock(X):\n if lock(X) = \"write-locked\"\n {\n then lock(X) = \"unlocked\";\n //the transactions in queue, if any, may now access item X in the manner they demand\n }\n else if lock(X) = \"read-locked\"\n {\n then\n no_of_reads-=1; //the transaction is done reading.\n if no_of_reads == 0 //no transactions reading the item\n {\n lock(X) = \"unlocked\";\n //transactions in queue, if any, may now access item X in the manner they demand\n }\n }"
},
{
"code": null,
"e": 9546,
"s": 9190,
"text": "The first case is straightforward enough. However, in the second case, we must check for the condition that there are no more current transactions sharing or reading item X. If item X is being read, we leave the situation and simply decrement the no_of_reads as the last transaction has terminated. The point here is that an item may be βunlocked only if:"
},
{
"code": null,
"e": 9595,
"s": 9546,
"text": "the βwriteβ operation terminates or is completed"
},
{
"code": null,
"e": 9644,
"s": 9595,
"text": "all βreadβ operations terminate or are completed"
},
{
"code": null,
"e": 9704,
"s": 9644,
"text": "Here are a few rules that Shared/Exclusive Locks must obey:"
},
{
"code": null,
"e": 10082,
"s": 9704,
"text": "A transaction T MUST issue the unlock(X) operation after all read and write operations have finished.A transaction T may NOT issue a read_lock(X) or write_lock(X) operation on an item which already has a read or write-lock issued to itself.A transaction T is NOT allowed to issue the unlock(X) operation unless it has been issued with a read_lock(X) or write_lock(X) operation."
},
{
"code": null,
"e": 10184,
"s": 10082,
"text": "A transaction T MUST issue the unlock(X) operation after all read and write operations have finished."
},
{
"code": null,
"e": 10324,
"s": 10184,
"text": "A transaction T may NOT issue a read_lock(X) or write_lock(X) operation on an item which already has a read or write-lock issued to itself."
},
{
"code": null,
"e": 10462,
"s": 10324,
"text": "A transaction T is NOT allowed to issue the unlock(X) operation unless it has been issued with a read_lock(X) or write_lock(X) operation."
},
{
"code": null,
"e": 10668,
"s": 10462,
"text": "When we relax these rules, a new dimension of interchanging the status of locks on items can be introduced. This has been explained in the following article: Lock Based Concurrency Control Protocol in DBMS"
},
{
"code": null,
"e": 10706,
"s": 10668,
"text": "Drawbacks of Shared/Exclusive Locks :"
},
{
"code": null,
"e": 10819,
"s": 10706,
"text": "Do not guarantee serializability of schedules on their own. A separate protocol must be followed to ensure this."
},
{
"code": null,
"e": 10924,
"s": 10819,
"text": "Commercially not optimized for speedy transactions; not the best solution due to lock contention issues."
},
{
"code": null,
"e": 10964,
"s": 10924,
"text": "Performance overhead is not negligible."
},
{
"code": null,
"e": 11337,
"s": 10964,
"text": "Certify Locks :The motivation behind introducing certify locks is the failure of previously mentioned locks to deliver an efficient and promising architecture which does not compromise on speed of processing transactions. Here we briefly look at a form of multiple-mode locking scheme which allows for the lock to be characterized by 3 locked states and 1 unlocked state. "
},
{
"code": null,
"e": 11403,
"s": 11337,
"text": "Transactions may issue any of 3 locked states or 1 unlocked state"
},
{
"code": null,
"e": 11442,
"s": 11403,
"text": "The states an item may be issued are :"
},
{
"code": null,
"e": 12341,
"s": 11442,
"text": "READ-LOCKED β same as the read-locked state explained earlier for Shared/Exclusive LocksWRITE-LOCKED β same as the write-locked state explained earlier for Shared/Exclusive LocksCERTIFY-LOCKED β This is an exclusive lock. This is used when 2 different transactions must be read and write respectively, to item X. In order for this to happen, a committed and a local version of the data item is created. The committed version is used by all transactions which have a read-lock issued to X. The local version of X is accessed by T only when a write-lock has been acquired by T. Once the writing or updating operation has been carried out by T on item X, T must obtain a certify-lock so that the committed version of data item X may be updated to the local versionβs contents and the local version may be discarded.UNLOCKED β same as the write-locked state explained earlier for Shared/Exclusive Locks"
},
{
"code": null,
"e": 12430,
"s": 12341,
"text": "READ-LOCKED β same as the read-locked state explained earlier for Shared/Exclusive Locks"
},
{
"code": null,
"e": 12521,
"s": 12430,
"text": "WRITE-LOCKED β same as the write-locked state explained earlier for Shared/Exclusive Locks"
},
{
"code": null,
"e": 13156,
"s": 12521,
"text": "CERTIFY-LOCKED β This is an exclusive lock. This is used when 2 different transactions must be read and write respectively, to item X. In order for this to happen, a committed and a local version of the data item is created. The committed version is used by all transactions which have a read-lock issued to X. The local version of X is accessed by T only when a write-lock has been acquired by T. Once the writing or updating operation has been carried out by T on item X, T must obtain a certify-lock so that the committed version of data item X may be updated to the local versionβs contents and the local version may be discarded."
},
{
"code": null,
"e": 13243,
"s": 13156,
"text": "UNLOCKED β same as the write-locked state explained earlier for Shared/Exclusive Locks"
},
{
"code": null,
"e": 13327,
"s": 13243,
"text": "Here is how a certify lock is used in multi-version concurrency control techniques:"
},
{
"code": null,
"e": 13579,
"s": 13327,
"text": "In Step 2, two versions of Item X are created i.e., the committed and local versions.In Step 4, the transaction must issue a certify lock on all writes it has made. Only then can we proceed to the next step. The updates on Local version are now final."
},
{
"code": null,
"e": 13586,
"s": 13579,
"text": "Step 5"
},
{
"code": null,
"e": 13774,
"s": 13586,
"text": "In order for multiple transactions to access the contents of data item X, a compatibility table must be drawn so that any collision or error is not returned, which may delay the process. "
},
{
"code": null,
"e": 13785,
"s": 13774,
"text": "Locks on X"
},
{
"code": null,
"e": 13789,
"s": 13785,
"text": "Yes"
},
{
"code": null,
"e": 13793,
"s": 13789,
"text": "Yes"
},
{
"code": null,
"e": 13796,
"s": 13793,
"text": "No"
},
{
"code": null,
"e": 13800,
"s": 13796,
"text": "Yes"
},
{
"code": null,
"e": 13803,
"s": 13800,
"text": "No"
},
{
"code": null,
"e": 13806,
"s": 13803,
"text": "No"
},
{
"code": null,
"e": 13809,
"s": 13806,
"text": "No"
},
{
"code": null,
"e": 13812,
"s": 13809,
"text": "No"
},
{
"code": null,
"e": 13815,
"s": 13812,
"text": "No"
},
{
"code": null,
"e": 14387,
"s": 13815,
"text": "The correct way of interpreting this table is as follows. Consider two transactions, T and Tβ. Assign transaction T to either the rows or the columns. Do the exact opposite for Tβ. Now the compatibility between locks issued to an item X by T and Tβ can be cross-referenced. For example, assign T to rows and Tβ to the columns. If T issues a read-lock on X and Tβ issues a write-lock on X, the result is a βYesβ β this scenario is feasible. However, if T intends a write-lock on X and Tβ intends a certify-lock on X, the result is a βNoβ β implying an impossible scenario."
},
{
"code": null,
"e": 14740,
"s": 14387,
"text": "There are further topics which look at developing better and advanced techniques to handle concurrency control, such as timestamps, multiversion models of data items and snapshot isolation. However, comprehending the basicity of the idea is key when it comes to building a clear understanding of concepts which may be as complex as concurrency control."
},
{
"code": null,
"e": 14758,
"s": 14740,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 14800,
"s": 14758,
"text": "DBMS-Transactions and Concurrency Control"
},
{
"code": null,
"e": 14805,
"s": 14800,
"text": "DBMS"
},
{
"code": null,
"e": 14810,
"s": 14805,
"text": "DBMS"
}
] |
Iterating over each index of array in Julia β eachindex() Method | 26 Mar, 2020
The eachindex() is an inbuilt function in julia which is used to create an iterable object for visiting each index of the specified array.
Syntax:eachindex(A...)
Parameters:
A: Specified array.
Returns: It returns an iterable object for visiting each index of the specified array.
Example 1:
# Julia program to illustrate # the use of Array eachindex() method # Accessing each index of 1D array A = [1, 2, 3, 4]; # linear indexingfor i in eachindex(A) println(i)end # Accessing each index of 2D array B = [2 4; 6 8]; # linear indexingfor i in eachindex(B) println(i)end # Accessing each index of 3D array C = cat([1 2; 3 4], [5 6; 7 8], [2 2; 3 4], dims = 3); # linear indexingfor i in eachindex(C) println(i)end
Output: Example 2:
# Julia program to illustrate # the use of Array eachindex() method # Accessing each index of 1D array A = [1, 2, 3, 4]; # Cartesian indexingfor i in eachindex(view(A, 1:2, 1:1)) println(i)end # Accessing each index of 2D array B = [2 4; 6 8]; # Cartesian indexingfor i in eachindex(view(B, :, 1)) println(i)end # Accessing each index of 3D array C = cat([1 2; 3 4], [5 6; 7 8], [2 2; 3 4], dims = 3); # Cartesian indexingfor i in eachindex(view(C, :, :, 1)) println(i)end
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Reshaping array dimensions in Julia | Array reshape() Method
Storing Output on a File in Julia
Manipulating matrices in Julia
Exception handling in Julia
Formatting of Strings in Julia
while loop in Julia
Creating array with repeated elements in Julia - repeat() Method
Tuples in Julia | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "The eachindex() is an inbuilt function in julia which is used to create an iterable object for visiting each index of the specified array."
},
{
"code": null,
"e": 190,
"s": 167,
"text": "Syntax:eachindex(A...)"
},
{
"code": null,
"e": 202,
"s": 190,
"text": "Parameters:"
},
{
"code": null,
"e": 222,
"s": 202,
"text": "A: Specified array."
},
{
"code": null,
"e": 309,
"s": 222,
"text": "Returns: It returns an iterable object for visiting each index of the specified array."
},
{
"code": null,
"e": 320,
"s": 309,
"text": "Example 1:"
},
{
"code": "# Julia program to illustrate # the use of Array eachindex() method # Accessing each index of 1D array A = [1, 2, 3, 4]; # linear indexingfor i in eachindex(A) println(i)end # Accessing each index of 2D array B = [2 4; 6 8]; # linear indexingfor i in eachindex(B) println(i)end # Accessing each index of 3D array C = cat([1 2; 3 4], [5 6; 7 8], [2 2; 3 4], dims = 3); # linear indexingfor i in eachindex(C) println(i)end",
"e": 756,
"s": 320,
"text": null
},
{
"code": null,
"e": 775,
"s": 756,
"text": "Output: Example 2:"
},
{
"code": "# Julia program to illustrate # the use of Array eachindex() method # Accessing each index of 1D array A = [1, 2, 3, 4]; # Cartesian indexingfor i in eachindex(view(A, 1:2, 1:1)) println(i)end # Accessing each index of 2D array B = [2 4; 6 8]; # Cartesian indexingfor i in eachindex(view(B, :, 1)) println(i)end # Accessing each index of 3D array C = cat([1 2; 3 4], [5 6; 7 8], [2 2; 3 4], dims = 3); # Cartesian indexingfor i in eachindex(view(C, :, :, 1)) println(i)end",
"e": 1266,
"s": 775,
"text": null
},
{
"code": null,
"e": 1274,
"s": 1266,
"text": "Output:"
},
{
"code": null,
"e": 1280,
"s": 1274,
"text": "Julia"
},
{
"code": null,
"e": 1378,
"s": 1280,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1395,
"s": 1378,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 1455,
"s": 1395,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 1516,
"s": 1455,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 1550,
"s": 1516,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 1581,
"s": 1550,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 1609,
"s": 1581,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 1640,
"s": 1609,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 1660,
"s": 1640,
"text": "while loop in Julia"
},
{
"code": null,
"e": 1725,
"s": 1660,
"text": "Creating array with repeated elements in Julia - repeat() Method"
}
] |
Python | Splitting list on empty string | 01 Jul, 2020
Sometimes, we may face an issue in which we require to split a list to list of list on the blank character sent as deliminator. This kind of problem can be used to send messages or can be used in cases where it is desired to have list of list of native list. Letβs discuss certain ways in which this can be done.
Method #1 : Using index() and list slicingThe list slicing can be used to get the sublists from the native list and index function can be used to check for the empty string which can potentially act as a separator. The drawback of this is that it only works for a single split i.e can only divide a list to 2 sublists.
# Python3 code to demonstrate# divide list to siblist on deliminator# using index() + list slicing # initializing list test_list = ['Geeks', 'for', '', 'Geeks', 1, 2] # printing original listprint("The original list : " + str(test_list)) # using index() + list slicing# divide list to siblist on deliminatortemp_idx = test_list.index('')res = [test_list[: temp_idx], test_list[temp_idx + 1: ]] # print resultprint("The list of sublist after separation : " + str(res))
The original list : [βGeeksβ, βforβ, β, βGeeksβ, 1, 2]The list of sublist after separation : [[βGeeksβ, βforβ], [βGeeksβ, 1, 2]]
Method #2 : Using itertools.groupby() + list comprehensionThe problem of the above proposed method can be solved using the groupby function which could divide on all the list breaks given by the empty strings.
# Python3 code to demonstrate# divide list to siblist on deliminator# using itertools.groupby() + list comprehensionfrom itertools import groupby # initializing list test_list = ['Geeks', '', 'for', '', 4, 5, '', 'Geeks', 'CS', '', 'Portal'] # printing original listprint("The original list : " + str(test_list)) # using itertools.groupby() + list comprehension# divide list to siblist on deliminatorres = [list(sub) for ele, sub in groupby(test_list, key = bool) if ele] # print resultprint("The list of sublist after separation : " + str(res))
The original list : [βGeeksβ, β, βforβ, β, 4, 5, β, βGeeksβ, βCSβ, β, βPortalβ]The list of sublist after separation : [[βGeeksβ], [βforβ], [4, 5], [βGeeksβ, βCSβ], [βPortalβ]]
nidhi_biet
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jul, 2020"
},
{
"code": null,
"e": 341,
"s": 28,
"text": "Sometimes, we may face an issue in which we require to split a list to list of list on the blank character sent as deliminator. This kind of problem can be used to send messages or can be used in cases where it is desired to have list of list of native list. Letβs discuss certain ways in which this can be done."
},
{
"code": null,
"e": 660,
"s": 341,
"text": "Method #1 : Using index() and list slicingThe list slicing can be used to get the sublists from the native list and index function can be used to check for the empty string which can potentially act as a separator. The drawback of this is that it only works for a single split i.e can only divide a list to 2 sublists."
},
{
"code": "# Python3 code to demonstrate# divide list to siblist on deliminator# using index() + list slicing # initializing list test_list = ['Geeks', 'for', '', 'Geeks', 1, 2] # printing original listprint(\"The original list : \" + str(test_list)) # using index() + list slicing# divide list to siblist on deliminatortemp_idx = test_list.index('')res = [test_list[: temp_idx], test_list[temp_idx + 1: ]] # print resultprint(\"The list of sublist after separation : \" + str(res))",
"e": 1133,
"s": 660,
"text": null
},
{
"code": null,
"e": 1262,
"s": 1133,
"text": "The original list : [βGeeksβ, βforβ, β, βGeeksβ, 1, 2]The list of sublist after separation : [[βGeeksβ, βforβ], [βGeeksβ, 1, 2]]"
},
{
"code": null,
"e": 1474,
"s": 1264,
"text": "Method #2 : Using itertools.groupby() + list comprehensionThe problem of the above proposed method can be solved using the groupby function which could divide on all the list breaks given by the empty strings."
},
{
"code": "# Python3 code to demonstrate# divide list to siblist on deliminator# using itertools.groupby() + list comprehensionfrom itertools import groupby # initializing list test_list = ['Geeks', '', 'for', '', 4, 5, '', 'Geeks', 'CS', '', 'Portal'] # printing original listprint(\"The original list : \" + str(test_list)) # using itertools.groupby() + list comprehension# divide list to siblist on deliminatorres = [list(sub) for ele, sub in groupby(test_list, key = bool) if ele] # print resultprint(\"The list of sublist after separation : \" + str(res))",
"e": 2041,
"s": 1474,
"text": null
},
{
"code": null,
"e": 2217,
"s": 2041,
"text": "The original list : [βGeeksβ, β, βforβ, β, 4, 5, β, βGeeksβ, βCSβ, β, βPortalβ]The list of sublist after separation : [[βGeeksβ], [βforβ], [4, 5], [βGeeksβ, βCSβ], [βPortalβ]]"
},
{
"code": null,
"e": 2228,
"s": 2217,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2249,
"s": 2228,
"text": "Python list-programs"
},
{
"code": null,
"e": 2256,
"s": 2249,
"text": "Python"
},
{
"code": null,
"e": 2272,
"s": 2256,
"text": "Python Programs"
}
] |
PyQt5 β QDoubleSpinBox | 14 Jul, 2020
QDoubleSpinBox allows the user to choose a value by clicking the up and down buttons or by pressing Up or Down on the keyboard to increase or decrease the value currently displayed. The user can also type the value in manually. The spin box supports double values but can be extended to use different strings. Below is how the double spin box looks like
Example :A window having a Double Spinbox and a label, when value changes a message will appear in the label displaying the current value.
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating double spin box d_spin = QDoubleSpinBox(self) # setting geometry to the double spin box d_spin.setGeometry(100, 100, 150, 40) # adding action to the double spin box d_spin.valueChanged.connect(lambda: spin_method()) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) def spin_method(): # getting current value of double spin box value = d_spin.value() # setting text to the label label.setText("Current Value : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QDoubleSpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Iterate over a list in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 382,
"s": 28,
"text": "QDoubleSpinBox allows the user to choose a value by clicking the up and down buttons or by pressing Up or Down on the keyboard to increase or decrease the value currently displayed. The user can also type the value in manually. The spin box supports double values but can be extended to use different strings. Below is how the double spin box looks like"
},
{
"code": null,
"e": 521,
"s": 382,
"text": "Example :A window having a Double Spinbox and a label, when value changes a message will appear in the label displaying the current value."
},
{
"code": null,
"e": 549,
"s": 521,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating double spin box d_spin = QDoubleSpinBox(self) # setting geometry to the double spin box d_spin.setGeometry(100, 100, 150, 40) # adding action to the double spin box d_spin.valueChanged.connect(lambda: spin_method()) # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) def spin_method(): # getting current value of double spin box value = d_spin.value() # setting text to the label label.setText(\"Current Value : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1936,
"s": 549,
"text": null
},
{
"code": null,
"e": 1945,
"s": 1936,
"text": "Output :"
},
{
"code": null,
"e": 1972,
"s": 1945,
"text": "Python PyQt-QDoubleSpinBox"
},
{
"code": null,
"e": 1983,
"s": 1972,
"text": "Python-gui"
},
{
"code": null,
"e": 1995,
"s": 1983,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2002,
"s": 1995,
"text": "Python"
},
{
"code": null,
"e": 2100,
"s": 2002,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2142,
"s": 2100,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2164,
"s": 2142,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2199,
"s": 2164,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2225,
"s": 2199,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2257,
"s": 2225,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2286,
"s": 2257,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2313,
"s": 2286,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2334,
"s": 2313,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2357,
"s": 2334,
"text": "Introduction To PYTHON"
}
] |
LSTM β Derivation of Back propagation through time | 27 Dec, 2021
LSTM (Long short term Memory ) is a type of RNN(Recurrent neural network), which is a famous deep learning algorithm that is well suited for making predictions and classification with a flavour of the time. In this article, we will derive the algorithm backpropagation through time and find the gradient value for all the weights at a particular timestamp. As the name suggests backpropagation through time is similar to backpropagation in DNN(deep neural network) but due to the dependency of time in RNN and LSTM, we will have to apply the chain rule with time dependency.
Let the input at time t in the LSTM cell be xt, the cell state from time t-1 and t be ct-1 and ct and the output for time t-1 and t be ht-1 and ht . The initial value of ct and ht at t = 0 will be zero.
Step 1 : Initialization of the weights .
Weights for different gates are :
Input gate : wxi, wxg, bi, whj, wg , bg
Forget gate : wxf, bf, whf
Output gate : wxo, bo, who
Step 2 : Passing through different gates .
Inputs: xt and ht-i , ct-1 are given to the LSTM cell
Passing through input gate:
Zg = wxg *x + whg * ht-1 + bg
g = tanh(Zg)
Zj = wxi * x + whi * ht-1 + bi
i = sigmoid(Zi)
Input_gate_out = g*i
Passing through forget gate:
Zf = wxf * x + whf *ht-1 + bf
f = sigmoid(Zf)
Forget_gate_out = f
Passing through the output gate:
Zo = wxo*x + who * ht-1 + bo
o = sigmoid(zO)
Out_gate_out = o
Step 3 : Calculating the output ht and current cell state ct.
Calculating the current cell state ct :
ct = (ct-1 * forget_gate_out) + input_gate_out
Calculating the output gate ht:
ht=out_gate_out * tanh(ct)
Step 4 : Calculating the gradient through back propagation through time at time stamp t using the chain rule.
Let the gradient pass down by the above cell be:
E_delta = dE/dht
If we are using MSE (mean square error)for error then,
E_delta=(y-h(x))
Here y is the original value and h(x) is the predicted value.
Gradient with respect to output gate
dE/do = (dE/dht ) * (dht /do) = E_delta * ( dht / do)
dE/do = E_delta * tanh(ct)
Gradient with respect to ct
dE/dct = (dE / dht )*(dht /dct)= E_delta *(dht /dct)
dE/dct = E_delta * o * (1-tanh2 (ct))
Gradient with respect to input gate dE/di, dE/dg
dE/di = (dE/di ) * (dct / di)
dE/di = E_delta * o * (1-tanh2 (ct)) * g
Similarly,
dE/dg = E_delta * o * (1-tanh2 (ct)) * i
Gradient with respect to forget gate
dE/df = E_delta * (dE/dct ) * (dct / dt) t
dE/df = E_delta * o * (1-tanh2 (ct)) * ct-1
Gradient with respect to ct-1
dE/dct = E_delta * (dE/dct ) * (dct / dct-1)
dE/dct = E_delta * o * (1-tanh2 (ct)) * f
Gradient with respect to output gate weights:
dE/dwxo = dE/do *(do/dwxo) = E_delta * tanh(ct) * sigmoid(zo) * (1-sigmoid(zo) * xt
dE/dwho = dE/do *(do/dwho) = E_delta * tanh(ct) * sigmoid(zo) * (1-sigmoid(zo) * ht-1
dE/dbo = dE/do *(do/dbo) = E_delta * tanh(ct) * sigmoid(zo) * (1-sigmoid(zo)
Gradient with respect to forget gate weights:
dE/dwxf = dE/df *(df/dwxf) = E_delta * o * (1-tanh2 (ct)) * ct-1 * sigmoid(zf) * (1-sigmoid(zf) * xt
dE/dwhf = dE/df *(df/dwhf) = E_delta * o * (1-tanh2 (ct)) * ct-1 * sigmoid(zf) * (1-sigmoid(zf) * ht-1
dE/dbo = dE/df *(df/dbo) = E_delta * o * (1-tanh2 (ct)) * ct-1 * sigmoid(zf) * (1-sigmoid(zf)
Gradient with respect to input gate weights:
dE/dwxi = dE/di *(di/dwxi) = E_delta * o * (1-tanh2 (ct)) * g * sigmoid(zi) * (1-sigmoid(zi) * xt
dE/dwhi = dE/di *(di/dwhi) = E_delta * o * (1-tanh2 (ct)) * g * sigmoid(zi) * (1-sigmoid(zi) * ht-1
dE/dbi = dE/di *(di/dbi) = E_delta * o * (1-tanh2 (ct)) * g * sigmoid(zi) * (1-sigmoid(zi)
dE/dwxg = dE/dg *(dg/dwxg) = E_delta * o * (1-tanh2 (ct)) * i * (1?tanh2(zg))*xt
dE/dwhg = dE/dg *(dg/dwhg) = E_delta * o * (1-tanh2 (ct)) * i * (1?tanh2(zg))*ht-1
dE/dbg = dE/dg *(dg/dbg) = E_delta * o * (1-tanh2 (ct)) * i * (1?tanh2(zg))
Finally the gradients associated with the weights are,
Using all gradient, we can easily update the weights associated with input gate, output gate, and forget gate
nnr223442
Deep-Learning
Machine Learning
Mathematical
Mathematical
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 628,
"s": 52,
"text": "LSTM (Long short term Memory ) is a type of RNN(Recurrent neural network), which is a famous deep learning algorithm that is well suited for making predictions and classification with a flavour of the time. In this article, we will derive the algorithm backpropagation through time and find the gradient value for all the weights at a particular timestamp. As the name suggests backpropagation through time is similar to backpropagation in DNN(deep neural network) but due to the dependency of time in RNN and LSTM, we will have to apply the chain rule with time dependency. "
},
{
"code": null,
"e": 833,
"s": 628,
"text": "Let the input at time t in the LSTM cell be xt, the cell state from time t-1 and t be ct-1 and ct and the output for time t-1 and t be ht-1 and ht . The initial value of ct and ht at t = 0 will be zero. "
},
{
"code": null,
"e": 875,
"s": 833,
"text": "Step 1 : Initialization of the weights . "
},
{
"code": null,
"e": 1007,
"s": 875,
"text": "Weights for different gates are : \nInput gate : wxi, wxg, bi, whj, wg , bg\n\nForget gate : wxf, bf, whf \n\nOutput gate : wxo, bo, who"
},
{
"code": null,
"e": 1051,
"s": 1007,
"text": "Step 2 : Passing through different gates . "
},
{
"code": null,
"e": 1654,
"s": 1051,
"text": " \nInputs: xt and ht-i , ct-1 are given to the LSTM cell \n Passing through input gate: \n \n Zg = wxg *x + whg * ht-1 + bg \n g = tanh(Zg)\n Zj = wxi * x + whi * ht-1 + bi \n i = sigmoid(Zi) \n \n Input_gate_out = g*i \n \n Passing through forget gate: \n \n Zf = wxf * x + whf *ht-1 + bf \n f = sigmoid(Zf) \n \n Forget_gate_out = f \n \n Passing through the output gate: \n \n Zo = wxo*x + who * ht-1 + bo \n o = sigmoid(zO) \n \n Out_gate_out = o"
},
{
"code": null,
"e": 1717,
"s": 1654,
"text": "Step 3 : Calculating the output ht and current cell state ct. "
},
{
"code": null,
"e": 1887,
"s": 1717,
"text": " Calculating the current cell state ct :\n ct = (ct-1 * forget_gate_out) + input_gate_out \n\nCalculating the output gate ht:\n ht=out_gate_out * tanh(ct)"
},
{
"code": null,
"e": 1998,
"s": 1887,
"text": "Step 4 : Calculating the gradient through back propagation through time at time stamp t using the chain rule. "
},
{
"code": null,
"e": 4486,
"s": 1998,
"text": " Let the gradient pass down by the above cell be: \n E_delta = dE/dht \n \n If we are using MSE (mean square error)for error then,\n E_delta=(y-h(x))\n Here y is the original value and h(x) is the predicted value. \n \n Gradient with respect to output gate \n \n dE/do = (dE/dht ) * (dht /do) = E_delta * ( dht / do) \n dE/do = E_delta * tanh(ct) \n \n Gradient with respect to ct \n dE/dct = (dE / dht )*(dht /dct)= E_delta *(dht /dct) \n dE/dct = E_delta * o * (1-tanh2 (ct)) \n\n Gradient with respect to input gate dE/di, dE/dg \n \n dE/di = (dE/di ) * (dct / di) \n dE/di = E_delta * o * (1-tanh2 (ct)) * g \n Similarly, \n dE/dg = E_delta * o * (1-tanh2 (ct)) * i \n \n Gradient with respect to forget gate \n \n dE/df = E_delta * (dE/dct ) * (dct / dt) t\n dE/df = E_delta * o * (1-tanh2 (ct)) * ct-1 \n\n Gradient with respect to ct-1 \n \n dE/dct = E_delta * (dE/dct ) * (dct / dct-1) \n dE/dct = E_delta * o * (1-tanh2 (ct)) * f \n \n Gradient with respect to output gate weights:\n \n dE/dwxo = dE/do *(do/dwxo) = E_delta * tanh(ct) * sigmoid(zo) * (1-sigmoid(zo) * xt\n dE/dwho = dE/do *(do/dwho) = E_delta * tanh(ct) * sigmoid(zo) * (1-sigmoid(zo) * ht-1\n dE/dbo = dE/do *(do/dbo) = E_delta * tanh(ct) * sigmoid(zo) * (1-sigmoid(zo)\n\n Gradient with respect to forget gate weights:\n \n dE/dwxf = dE/df *(df/dwxf) = E_delta * o * (1-tanh2 (ct)) * ct-1 * sigmoid(zf) * (1-sigmoid(zf) * xt\n dE/dwhf = dE/df *(df/dwhf) = E_delta * o * (1-tanh2 (ct)) * ct-1 * sigmoid(zf) * (1-sigmoid(zf) * ht-1\n dE/dbo = dE/df *(df/dbo) = E_delta * o * (1-tanh2 (ct)) * ct-1 * sigmoid(zf) * (1-sigmoid(zf) \n\n Gradient with respect to input gate weights:\n \n dE/dwxi = dE/di *(di/dwxi) = E_delta * o * (1-tanh2 (ct)) * g * sigmoid(zi) * (1-sigmoid(zi) * xt\n dE/dwhi = dE/di *(di/dwhi) = E_delta * o * (1-tanh2 (ct)) * g * sigmoid(zi) * (1-sigmoid(zi) * ht-1\n dE/dbi = dE/di *(di/dbi) = E_delta * o * (1-tanh2 (ct)) * g * sigmoid(zi) * (1-sigmoid(zi)\n \n dE/dwxg = dE/dg *(dg/dwxg) = E_delta * o * (1-tanh2 (ct)) * i * (1?tanh2(zg))*xt\n dE/dwhg = dE/dg *(dg/dwhg) = E_delta * o * (1-tanh2 (ct)) * i * (1?tanh2(zg))*ht-1\n dE/dbg = dE/dg *(dg/dbg) = E_delta * o * (1-tanh2 (ct)) * i * (1?tanh2(zg))"
},
{
"code": null,
"e": 4542,
"s": 4486,
"text": "Finally the gradients associated with the weights are, "
},
{
"code": null,
"e": 4654,
"s": 4542,
"text": "Using all gradient, we can easily update the weights associated with input gate, output gate, and forget gate "
},
{
"code": null,
"e": 4664,
"s": 4654,
"text": "nnr223442"
},
{
"code": null,
"e": 4678,
"s": 4664,
"text": "Deep-Learning"
},
{
"code": null,
"e": 4695,
"s": 4678,
"text": "Machine Learning"
},
{
"code": null,
"e": 4708,
"s": 4695,
"text": "Mathematical"
},
{
"code": null,
"e": 4721,
"s": 4708,
"text": "Mathematical"
},
{
"code": null,
"e": 4738,
"s": 4721,
"text": "Machine Learning"
}
] |
Perl | Array Slices | 26 Nov, 2019
In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable.Arrays can store any type of data and that data can be accessed in multiple ways. These values can be extracted by placing $ sign before the array and storing the index value of the element to be accessed within the square brackets.For Example:
# Define an array@arr = (1, 2, 3); # Accessing and printing first # element of an arrayprint "$arr[0]\n"; # Accessing and printing second# element of an arrayprint "$arr[1]\n";
This method of extracting array elements can be used only to extract one element at a time, which might become confusing when there is a long list of elements to be accessed. For Example, if the list contains 100 elements and we need to extract 20 elements from Index βaβ to Index βbβ, then this method will create a confusion. In order to avoid such kind of situation, Perl provides a method of array slicing. This can be used to access a range of array elements.
Array slicing is done to access a range of elements in an array in order to ease the process of accessing a multiple number of elements from the array. This can be done in two ways:
Passing multiple index values
Using range operator
Passing multiple Index values:Array slicing can be done by passing multiple index values from the array whose values are to be accessed. These values are passed to the array name as the argument. Perl will access these values on the specified indices and perform the required action on these values.Example:
#!/usr/bin/perl # Perl program to implement the use of Array Slice@array = ('Geeks', 'for', 'Geek'); # Using slicing method@extracted_elements = @array[1, 2]; # Printing the extracted elementsprint"Extracted elements: ". "@extracted_elements";
Extracted elements: for Geek
This method of passing multiple indexes becomes a bit complicated when a large number of values are to be accessed.
Using Range OperatorRange operator[..] can also be used to perform the slicing method in an array by accessing a range of elements whose starting and ending index are given within the square brackets separated by range operator(..). This method is more feasible as it can print elements within a long range of elements, as compared to passing multiple parameters.Example:
#!/usr/bin/perl # Perl program to implement the use of Array Slice@array = ('Geeks', 'for', 'Geek', 'Welcomes', 'You'); # Using range operator for slicing method@extracted_elements = @array[1..3]; # Printing the extracted elementsprint"Extracted elements: ". "@extracted_elements";
Extracted elements: for Geek Welcomes
This method of slicing the Array to access elements is used widely to perform multiple operations on the array. Operations like, pushing elements, printing elements of array, deleting elements, etc.
shubham_singh
Perl-Arrays
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | split() Function
Perl | push() Function
Perl | chomp() Function
Perl | substr() function
Perl | grep() Function
Perl | exists() Function
Perl Tutorial - Learn Perl With Examples
Perl | length() Function
Perl | Subroutines or Functions
Use of print() and say() in Perl | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Nov, 2019"
},
{
"code": null,
"e": 538,
"s": 53,
"text": "In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable.Arrays can store any type of data and that data can be accessed in multiple ways. These values can be extracted by placing $ sign before the array and storing the index value of the element to be accessed within the square brackets.For Example:"
},
{
"code": "# Define an array@arr = (1, 2, 3); # Accessing and printing first # element of an arrayprint \"$arr[0]\\n\"; # Accessing and printing second# element of an arrayprint \"$arr[1]\\n\";",
"e": 717,
"s": 538,
"text": null
},
{
"code": null,
"e": 1182,
"s": 717,
"text": "This method of extracting array elements can be used only to extract one element at a time, which might become confusing when there is a long list of elements to be accessed. For Example, if the list contains 100 elements and we need to extract 20 elements from Index βaβ to Index βbβ, then this method will create a confusion. In order to avoid such kind of situation, Perl provides a method of array slicing. This can be used to access a range of array elements."
},
{
"code": null,
"e": 1364,
"s": 1182,
"text": "Array slicing is done to access a range of elements in an array in order to ease the process of accessing a multiple number of elements from the array. This can be done in two ways:"
},
{
"code": null,
"e": 1394,
"s": 1364,
"text": "Passing multiple index values"
},
{
"code": null,
"e": 1415,
"s": 1394,
"text": "Using range operator"
},
{
"code": null,
"e": 1723,
"s": 1415,
"text": "Passing multiple Index values:Array slicing can be done by passing multiple index values from the array whose values are to be accessed. These values are passed to the array name as the argument. Perl will access these values on the specified indices and perform the required action on these values.Example:"
},
{
"code": "#!/usr/bin/perl # Perl program to implement the use of Array Slice@array = ('Geeks', 'for', 'Geek'); # Using slicing method@extracted_elements = @array[1, 2]; # Printing the extracted elementsprint\"Extracted elements: \". \"@extracted_elements\";",
"e": 1975,
"s": 1723,
"text": null
},
{
"code": null,
"e": 2005,
"s": 1975,
"text": "Extracted elements: for Geek\n"
},
{
"code": null,
"e": 2121,
"s": 2005,
"text": "This method of passing multiple indexes becomes a bit complicated when a large number of values are to be accessed."
},
{
"code": null,
"e": 2493,
"s": 2121,
"text": "Using Range OperatorRange operator[..] can also be used to perform the slicing method in an array by accessing a range of elements whose starting and ending index are given within the square brackets separated by range operator(..). This method is more feasible as it can print elements within a long range of elements, as compared to passing multiple parameters.Example:"
},
{
"code": "#!/usr/bin/perl # Perl program to implement the use of Array Slice@array = ('Geeks', 'for', 'Geek', 'Welcomes', 'You'); # Using range operator for slicing method@extracted_elements = @array[1..3]; # Printing the extracted elementsprint\"Extracted elements: \". \"@extracted_elements\";",
"e": 2783,
"s": 2493,
"text": null
},
{
"code": null,
"e": 2822,
"s": 2783,
"text": "Extracted elements: for Geek Welcomes\n"
},
{
"code": null,
"e": 3021,
"s": 2822,
"text": "This method of slicing the Array to access elements is used widely to perform multiple operations on the array. Operations like, pushing elements, printing elements of array, deleting elements, etc."
},
{
"code": null,
"e": 3035,
"s": 3021,
"text": "shubham_singh"
},
{
"code": null,
"e": 3047,
"s": 3035,
"text": "Perl-Arrays"
},
{
"code": null,
"e": 3052,
"s": 3047,
"text": "Perl"
},
{
"code": null,
"e": 3057,
"s": 3052,
"text": "Perl"
},
{
"code": null,
"e": 3155,
"s": 3057,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3179,
"s": 3155,
"text": "Perl | split() Function"
},
{
"code": null,
"e": 3202,
"s": 3179,
"text": "Perl | push() Function"
},
{
"code": null,
"e": 3226,
"s": 3202,
"text": "Perl | chomp() Function"
},
{
"code": null,
"e": 3251,
"s": 3226,
"text": "Perl | substr() function"
},
{
"code": null,
"e": 3274,
"s": 3251,
"text": "Perl | grep() Function"
},
{
"code": null,
"e": 3299,
"s": 3274,
"text": "Perl | exists() Function"
},
{
"code": null,
"e": 3340,
"s": 3299,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 3365,
"s": 3340,
"text": "Perl | length() Function"
},
{
"code": null,
"e": 3397,
"s": 3365,
"text": "Perl | Subroutines or Functions"
}
] |
std::fstream::close() in C++ | 24 Feb, 2022
Files play an important role in programming. It allows storage of data permanently. The C++ language provides a mechanism to store the output of a program in a file and browse from a file on the disk. This mechanism is termed file handling. In order to perform file handling, some general functions which are used are as follows:
open(): This function helps to create a file and open the file in different modes, like input operations, output operations, binary mode, etc.
close(): This function helps to close an existing file.
get(): This function helps to read a single character from the file.
put(): This function helps to write a single character in the file.
read(): This function helps to read data from a file.
write(): This function helps us to write data into a file.
A stream is an abstraction that represents a tool on which operations of input and output are performed. A stream is often represented as a source or destination of characters of indefinite length, counting on its usage. So far, the header file which provides functions cin and cout is used to require input from the console and write output to a console respectively. In C++ there is a group of file handling methods. These include ifstream, ofstream, and fstream. These classes are obtained from fstreambase and from the corresponding iostream class. These classes are designed such that they are able to manage the disk files, declared in fstream, and thus this file must be included in any program that uses files.
fstream Library: Fstream is a library that consists of both, ofstream and ifstream which means it can create files, write information to files, and read information from files. This header file is generally used as a data type that represents the file stream. Which is used while describing the syntax to open, read, take input and close the file, etc.
How To Close File? In order to use a disk file for storing data, the following parameters need to be decided about the file and its intended use. The parameters that are to be noted are as follows:
A name for the file.
Data type and structure of the file.
Purpose (reading, writing data).
Opening method.
Closing the file after use.
This article focuses on closing the file. In a case, if a C++ program terminates, then it automatically flushes out all the streams, releases all the allocated memory, and closes all the opened files. Therefore, it is a good alternative to use the close() function to close the file-related streams, and it is a member of ifsream, ofstream, and fstream objects.
Syntax:
close()
Properties:
Return value: The close() function provides no return value which means that if the operation fails, including if no file was open before the call, the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions.
Exception handling: When the function is provided with an exception and the stream is in a valid state, then any exception thrown by an internal operation is caught by the function and rethrown after closing the file. It throws an exception to member type failure only if the function fails (setting the failbit state flag) and member exceptions are set to throw for that state.
It modifies the fstream object. Concurrent access to an equivalent stream may introduce data races.
Below is the C++ program to implement the close() function:
C++
// C++ program to implement close() function#include <fstream>#include <iostream>using namespace std; // Driver Codeint main(){ char data[100]; // Open a file in write // mode. ofstream outfile; outfile.open("gfg.data"); cout << "Writing to the file" << endl; cout << "Enter your name: "; // This function will take the entire // the user enters and will store in // the "data" array declare above cin.getline(data, 100); // Write inputted data into // the file. outfile << data << endl; // Here we make use of the close() // function to close the opened file outfile.close(); // Open a file in read mode ifstream infile; infile.open("gfg.data"); cout << "Reading from the file" << endl; infile >> data; // Write the data at the screen cout << data << endl; // Close the opened file infile.close(); return 0;}
Output:
manikarora059
varshagumber28
CPP-Functions
Articles
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 358,
"s": 28,
"text": "Files play an important role in programming. It allows storage of data permanently. The C++ language provides a mechanism to store the output of a program in a file and browse from a file on the disk. This mechanism is termed file handling. In order to perform file handling, some general functions which are used are as follows:"
},
{
"code": null,
"e": 501,
"s": 358,
"text": "open(): This function helps to create a file and open the file in different modes, like input operations, output operations, binary mode, etc."
},
{
"code": null,
"e": 557,
"s": 501,
"text": "close(): This function helps to close an existing file."
},
{
"code": null,
"e": 626,
"s": 557,
"text": "get(): This function helps to read a single character from the file."
},
{
"code": null,
"e": 694,
"s": 626,
"text": "put(): This function helps to write a single character in the file."
},
{
"code": null,
"e": 748,
"s": 694,
"text": "read(): This function helps to read data from a file."
},
{
"code": null,
"e": 807,
"s": 748,
"text": "write(): This function helps us to write data into a file."
},
{
"code": null,
"e": 1526,
"s": 807,
"text": "A stream is an abstraction that represents a tool on which operations of input and output are performed. A stream is often represented as a source or destination of characters of indefinite length, counting on its usage. So far, the header file which provides functions cin and cout is used to require input from the console and write output to a console respectively. In C++ there is a group of file handling methods. These include ifstream, ofstream, and fstream. These classes are obtained from fstreambase and from the corresponding iostream class. These classes are designed such that they are able to manage the disk files, declared in fstream, and thus this file must be included in any program that uses files."
},
{
"code": null,
"e": 1879,
"s": 1526,
"text": "fstream Library: Fstream is a library that consists of both, ofstream and ifstream which means it can create files, write information to files, and read information from files. This header file is generally used as a data type that represents the file stream. Which is used while describing the syntax to open, read, take input and close the file, etc."
},
{
"code": null,
"e": 2077,
"s": 1879,
"text": "How To Close File? In order to use a disk file for storing data, the following parameters need to be decided about the file and its intended use. The parameters that are to be noted are as follows:"
},
{
"code": null,
"e": 2098,
"s": 2077,
"text": "A name for the file."
},
{
"code": null,
"e": 2135,
"s": 2098,
"text": "Data type and structure of the file."
},
{
"code": null,
"e": 2168,
"s": 2135,
"text": "Purpose (reading, writing data)."
},
{
"code": null,
"e": 2184,
"s": 2168,
"text": "Opening method."
},
{
"code": null,
"e": 2212,
"s": 2184,
"text": "Closing the file after use."
},
{
"code": null,
"e": 2575,
"s": 2212,
"text": "This article focuses on closing the file. In a case, if a C++ program terminates, then it automatically flushes out all the streams, releases all the allocated memory, and closes all the opened files. Therefore, it is a good alternative to use the close() function to close the file-related streams, and it is a member of ifsream, ofstream, and fstream objects. "
},
{
"code": null,
"e": 2583,
"s": 2575,
"text": "Syntax:"
},
{
"code": null,
"e": 2591,
"s": 2583,
"text": "close()"
},
{
"code": null,
"e": 2603,
"s": 2591,
"text": "Properties:"
},
{
"code": null,
"e": 2890,
"s": 2603,
"text": "Return value: The close() function provides no return value which means that if the operation fails, including if no file was open before the call, the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions."
},
{
"code": null,
"e": 3269,
"s": 2890,
"text": "Exception handling: When the function is provided with an exception and the stream is in a valid state, then any exception thrown by an internal operation is caught by the function and rethrown after closing the file. It throws an exception to member type failure only if the function fails (setting the failbit state flag) and member exceptions are set to throw for that state."
},
{
"code": null,
"e": 3369,
"s": 3269,
"text": "It modifies the fstream object. Concurrent access to an equivalent stream may introduce data races."
},
{
"code": null,
"e": 3429,
"s": 3369,
"text": "Below is the C++ program to implement the close() function:"
},
{
"code": null,
"e": 3433,
"s": 3429,
"text": "C++"
},
{
"code": "// C++ program to implement close() function#include <fstream>#include <iostream>using namespace std; // Driver Codeint main(){ char data[100]; // Open a file in write // mode. ofstream outfile; outfile.open(\"gfg.data\"); cout << \"Writing to the file\" << endl; cout << \"Enter your name: \"; // This function will take the entire // the user enters and will store in // the \"data\" array declare above cin.getline(data, 100); // Write inputted data into // the file. outfile << data << endl; // Here we make use of the close() // function to close the opened file outfile.close(); // Open a file in read mode ifstream infile; infile.open(\"gfg.data\"); cout << \"Reading from the file\" << endl; infile >> data; // Write the data at the screen cout << data << endl; // Close the opened file infile.close(); return 0;}",
"e": 4342,
"s": 3433,
"text": null
},
{
"code": null,
"e": 4350,
"s": 4342,
"text": "Output:"
},
{
"code": null,
"e": 4364,
"s": 4350,
"text": "manikarora059"
},
{
"code": null,
"e": 4379,
"s": 4364,
"text": "varshagumber28"
},
{
"code": null,
"e": 4393,
"s": 4379,
"text": "CPP-Functions"
},
{
"code": null,
"e": 4402,
"s": 4393,
"text": "Articles"
},
{
"code": null,
"e": 4406,
"s": 4402,
"text": "C++"
},
{
"code": null,
"e": 4419,
"s": 4406,
"text": "C++ Programs"
},
{
"code": null,
"e": 4423,
"s": 4419,
"text": "CPP"
}
] |
Best Coding Practices For Rest API Design | 19 Apr, 2022
JSON, Endpoints, Postman, CRUD, Curl, HTTP, Status Code, Request, Response, Authentication,
All these words are familiar to you if you are in backend development and you have worked on API (Application Programming Interface). Being a developer you might have worked on some kind of APIs (especially those who are experienced developers). Maybe a payment gateway API, Google Maps API, Sending Email APIs, or any other kind of APIs depending on the type of application and the requirements.
Many times it happens that developers read the documentation part of the API, implement it, but they do not focus on building a clean, understandable, and scalable architecture when they are implementing any kind of API in their application. These things impact a system a lot when the application grows with time.
Consider a scenario that you have built an application and now you need to expose the interface to the user. Do you really think that both of you will be at the same table? Do you think that they will understand the same thing that youβre trying to depict in your system?
When youβre building a Restful API it is important to design it properly to avoid any bug or issue in your application. You need to take care of the performance, security, and ease of use for API consumers. It is good to follow some good conventions to build an API that is clean, understandable, and easy to work with.
There are so many aspects you need to consider when youβre building a Restful API in your application. In this blog, we will highlight those aspects in detail. Letβs discuss the best coding convention to build the REST API in your application.
Being a backend developer you might have been familiar with the various HTTP request methods to perform CRUD actions in your application especially the ones, which are common such as GET, POST, PUT, DELETE, and PATCH. In case you are not familiar with these methods then read the blog HTTP Request Methods.
When youβre implementing an API make sure that the name of the endpoints linked with the resources go along with the HTTP method related to the actions youβre using in your application. Look at the example given below for reference...
- GET /get_customers
- POST /insert_customers
- PUT /modify_customers
- DELETE /delete_customers
+ GET /customers
+ POST /customers
+ PUT /customers
+ DELETE /customers
While implementing an API the endpoints return the result that whether the action is successful or not. The result is always associated with some status code. For example: if you get the status 200 (ok) then it means the result is successful and if you get the status code 400 (bad request) then the result is failed (You can check the response using some tools like Postman to get to know the status code for the actions you perform in your application).
Handle the errors gracefully and return the HTTP response code to indicate what kind of error is generated. This is helpful for API maintainers to understand the issues and troubleshoot them.
Make sure that you know the existing status code to identify the case you need to apply each one of them. Sometimes it happens that the return message does not match with the status code and that creates confusion for the developers as well as for the consumers who are using that REST API. This is really harmful to the application. So itβs good to take care of the status code for the actions you perform in your application. Below is one of the examples...
// Bad, status code 200 (Success)
// associated with an error object
{
"status": 200,
"error": {...}
}// Good
{
"status": 200,
"data": [...]
}
Some common error codes are given below...
400 Bad Request β Client-side input fails validation.
401 Unauthorized β User isnβt authorized to access a resource. It usually returns when the user isnβt authenticated.
403 Forbidden β User is authenticated, but itβs not allowed to access a resource.
404 Not Found β Resource is not found.
500 Internal server error β Generic server error. It probably shouldnβt be thrown explicitly.
502 Bad Gateway β This indicates an invalid response from an upstream server.
503 Service Unavailable β Something unexpected happened on the server-side (It can be anything like server overload, some parts of the system failed, etc.).
How would your server react if you implement an API in your application and the endpoints return the results in millions....???
Your server will be down and itβs really going to cry in front of you...(jokes apart...)
Many times it happens that we only need to consume some specific or fewer resources from our server. The reason could be anything. It can be the performance of the system, search system, or the massive amount of information that is not needed to return all at once. You can use a filter to return some specific item based on the condition. If you want to return a few results at a time then use pagination in your API.
These concepts will help you to display only a specific type of information and it will increase the performance of your system by consuming fewer resources. Examples are given below...
Filter: filter the customer with the following properties... the last name is Smith and the age is 30.GET /customers?last_name=Smith&age=30
Pagination: Return 20 rows starting from 0GET /customers?limit=20&offset=0
Sort: Return rows sorted by email in the ascendant.GET /customers?sort_by=asc(email)
If you have implemented any kind of API in your application then you might have come across a question that whether the endpoint name should be singular or plural. Remember that you need to maintain consistency throughout your application. So itβs good to build the endpoints in the plural to be consistent in your database.
Itβs not necessary that you will always get a single item. You can have many items in a table but even if you consider the scenario of getting the result only one and you place it singular everywhere then you wonβt be able to maintain the consistency in the name of your routes.
- GET /article
- GET /article/:id
+ GET /articles
+ GET /articles/:id
While implementing an API you need to take care of the path for the endpoints. The path of the endpoint deal with the nested resources. To create this path treat the nested resource as the name of the path and append it after the parent resource. Make sure that the nested resource matches the table you have stored in your database else it will create confusion for you.
If you donβt get the above point then understand this in a way that you have a list of students in your database. Each one of them has chosen the subjects they are interested in. Treat the βsubjectβ table as a child of a βstudentβ table in your database.
Now, if you want to create the endpoint for the subjects associated with the student then append the /subjects path to the end of the /student path. If youβre using the GET method then an example of the endpoint path will look something like the given below...
β/students/:studentId/subjectsβ
We get subjects on the students identified by studentId and then the response will be returned. Here, students are the parentβs resources and the subject is the childβs resources of the student. So as discussed, we are adding subjects after the β/students/:studentIdβ. Each student has their own subject. The same kind of nesting structure will be applied to other methods as well such as POST, PUT and DELETE endpoints.
When youβre implementing an API make sure that the communication between the client and the server is private because you often send and receive private information. For security purposes, you can use SSL/TLS.
Using the SSL certificate isnβt too difficult. You can easily load it onto the server and the cost of an SSL certificate is also free and very low. Donβt make your REST API open. It should communicate over secure channels.
When a user is accessing the information, they shouldnβt be able to access more data they have requested. Being a user you are not allowed to access the information of another user or the data of admins.
To implement the principle of the least privilege, add role checks for a single role or more granular roles for each user. If you want to group users into a few roles then they should be allowed to cover all they need and no more.
For each feature that users have access to if you have more granular permission then make sure that the admins can easily add and remove those features for each user accordingly. Add some preset roles that can be applied to group users. You wonβt have to do this for every user manually.
You might have used caching during the implementation of some features in your application. Caching is really a powerful tool to speed up the performance of your application. Using caching you will get faster results and you wonβt have to extract the data from the database multiple times for the same query.
Use caching during the implementation of your API. It will speed up the performance of your application and it will reduce the consumption of the resources. Itβs good to cache the data instead of running the same query and asking the database to give the same result (your database will start crying in front of you....lolzzz).
One of the precautions you need to take care is that you donβt get outdated data. Due to the old data, something wrong can happen and your system can generate a lot of bugs in a production environment. Do not keep the information for a long period of time in the cache. It is good to keep the data for a short period of time in the cache.
Depending on the needs you can change the way data is cached. One of the great services to implement caching is Redis
Keeping the different versions of your API will help you to track the changes and it will help you to restore the previous version in case if something goes wrong with the latest one. Consider a scenario that you implemented an API, deploy it and a lot of clients start using it. Now at some point, you want to make some changes and you added or removed the data from a resource.
Chances are there that it will generate bugs on the external services that consume the interface. This is the reason you should keep the different versions of your API. From the previous version, you can get the backup and work on it further.
Versioning can be done according to the semantic version. Donβt force everyone to work on the same version at the same time, you can gradually remove the old versions of your API once you see that itβs not required anymore. Most of the time versioning is done with /v1/, /v2/, etc. added at the start of the API path.
GET /v1/customers
GET /v2/students
JSON, SSL/TLS, HTTP Status codes are the standard building blocks of the modern web app API. TO design a high-quality Restful API follow the best conventions we have discussed above.
Being a backend developer your job is not just to implement the features you are asked to do. You also need to take care of doing it in the best possible way. Apply the best principle when youβre implementing an API so that people who consume and work on it as it.
wksmbfw0zqhot9aok45r04hq8ew63s5sfvvzysl9
GBlog
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 145,
"s": 52,
"text": "JSON, Endpoints, Postman, CRUD, Curl, HTTP, Status Code, Request, Response, Authentication, "
},
{
"code": null,
"e": 543,
"s": 145,
"text": "All these words are familiar to you if you are in backend development and you have worked on API (Application Programming Interface). Being a developer you might have worked on some kind of APIs (especially those who are experienced developers). Maybe a payment gateway API, Google Maps API, Sending Email APIs, or any other kind of APIs depending on the type of application and the requirements. "
},
{
"code": null,
"e": 859,
"s": 543,
"text": "Many times it happens that developers read the documentation part of the API, implement it, but they do not focus on building a clean, understandable, and scalable architecture when they are implementing any kind of API in their application. These things impact a system a lot when the application grows with time. "
},
{
"code": null,
"e": 1132,
"s": 859,
"text": "Consider a scenario that you have built an application and now you need to expose the interface to the user. Do you really think that both of you will be at the same table? Do you think that they will understand the same thing that youβre trying to depict in your system? "
},
{
"code": null,
"e": 1453,
"s": 1132,
"text": "When youβre building a Restful API it is important to design it properly to avoid any bug or issue in your application. You need to take care of the performance, security, and ease of use for API consumers. It is good to follow some good conventions to build an API that is clean, understandable, and easy to work with. "
},
{
"code": null,
"e": 1698,
"s": 1453,
"text": "There are so many aspects you need to consider when youβre building a Restful API in your application. In this blog, we will highlight those aspects in detail. Letβs discuss the best coding convention to build the REST API in your application. "
},
{
"code": null,
"e": 2006,
"s": 1698,
"text": "Being a backend developer you might have been familiar with the various HTTP request methods to perform CRUD actions in your application especially the ones, which are common such as GET, POST, PUT, DELETE, and PATCH. In case you are not familiar with these methods then read the blog HTTP Request Methods. "
},
{
"code": null,
"e": 2241,
"s": 2006,
"text": "When youβre implementing an API make sure that the name of the endpoints linked with the resources go along with the HTTP method related to the actions youβre using in your application. Look at the example given below for reference..."
},
{
"code": null,
"e": 2410,
"s": 2241,
"text": "- GET /get_customers\n- POST /insert_customers\n- PUT /modify_customers\n- DELETE /delete_customers\n+ GET /customers\n+ POST /customers\n+ PUT /customers\n+ DELETE /customers"
},
{
"code": null,
"e": 2866,
"s": 2410,
"text": "While implementing an API the endpoints return the result that whether the action is successful or not. The result is always associated with some status code. For example: if you get the status 200 (ok) then it means the result is successful and if you get the status code 400 (bad request) then the result is failed (You can check the response using some tools like Postman to get to know the status code for the actions you perform in your application)."
},
{
"code": null,
"e": 3059,
"s": 2866,
"text": "Handle the errors gracefully and return the HTTP response code to indicate what kind of error is generated. This is helpful for API maintainers to understand the issues and troubleshoot them. "
},
{
"code": null,
"e": 3519,
"s": 3059,
"text": "Make sure that you know the existing status code to identify the case you need to apply each one of them. Sometimes it happens that the return message does not match with the status code and that creates confusion for the developers as well as for the consumers who are using that REST API. This is really harmful to the application. So itβs good to take care of the status code for the actions you perform in your application. Below is one of the examples..."
},
{
"code": null,
"e": 3678,
"s": 3519,
"text": "// Bad, status code 200 (Success)\n// associated with an error object\n{\n \"status\": 200,\n \"error\": {...}\n}// Good\n{\n \"status\": 200,\n \"data\": [...]\n}"
},
{
"code": null,
"e": 3721,
"s": 3678,
"text": "Some common error codes are given below..."
},
{
"code": null,
"e": 3775,
"s": 3721,
"text": "400 Bad Request β Client-side input fails validation."
},
{
"code": null,
"e": 3892,
"s": 3775,
"text": "401 Unauthorized β User isnβt authorized to access a resource. It usually returns when the user isnβt authenticated."
},
{
"code": null,
"e": 3974,
"s": 3892,
"text": "403 Forbidden β User is authenticated, but itβs not allowed to access a resource."
},
{
"code": null,
"e": 4013,
"s": 3974,
"text": "404 Not Found β Resource is not found."
},
{
"code": null,
"e": 4107,
"s": 4013,
"text": "500 Internal server error β Generic server error. It probably shouldnβt be thrown explicitly."
},
{
"code": null,
"e": 4185,
"s": 4107,
"text": "502 Bad Gateway β This indicates an invalid response from an upstream server."
},
{
"code": null,
"e": 4342,
"s": 4185,
"text": "503 Service Unavailable β Something unexpected happened on the server-side (It can be anything like server overload, some parts of the system failed, etc.)."
},
{
"code": null,
"e": 4470,
"s": 4342,
"text": "How would your server react if you implement an API in your application and the endpoints return the results in millions....???"
},
{
"code": null,
"e": 4559,
"s": 4470,
"text": "Your server will be down and itβs really going to cry in front of you...(jokes apart...)"
},
{
"code": null,
"e": 4979,
"s": 4559,
"text": "Many times it happens that we only need to consume some specific or fewer resources from our server. The reason could be anything. It can be the performance of the system, search system, or the massive amount of information that is not needed to return all at once. You can use a filter to return some specific item based on the condition. If you want to return a few results at a time then use pagination in your API. "
},
{
"code": null,
"e": 5165,
"s": 4979,
"text": "These concepts will help you to display only a specific type of information and it will increase the performance of your system by consuming fewer resources. Examples are given below..."
},
{
"code": null,
"e": 5305,
"s": 5165,
"text": "Filter: filter the customer with the following properties... the last name is Smith and the age is 30.GET /customers?last_name=Smith&age=30"
},
{
"code": null,
"e": 5380,
"s": 5305,
"text": "Pagination: Return 20 rows starting from 0GET /customers?limit=20&offset=0"
},
{
"code": null,
"e": 5465,
"s": 5380,
"text": "Sort: Return rows sorted by email in the ascendant.GET /customers?sort_by=asc(email)"
},
{
"code": null,
"e": 5791,
"s": 5465,
"text": "If you have implemented any kind of API in your application then you might have come across a question that whether the endpoint name should be singular or plural. Remember that you need to maintain consistency throughout your application. So itβs good to build the endpoints in the plural to be consistent in your database. "
},
{
"code": null,
"e": 6071,
"s": 5791,
"text": "Itβs not necessary that you will always get a single item. You can have many items in a table but even if you consider the scenario of getting the result only one and you place it singular everywhere then you wonβt be able to maintain the consistency in the name of your routes. "
},
{
"code": null,
"e": 6141,
"s": 6071,
"text": "- GET /article\n- GET /article/:id\n+ GET /articles\n+ GET /articles/:id"
},
{
"code": null,
"e": 6514,
"s": 6141,
"text": "While implementing an API you need to take care of the path for the endpoints. The path of the endpoint deal with the nested resources. To create this path treat the nested resource as the name of the path and append it after the parent resource. Make sure that the nested resource matches the table you have stored in your database else it will create confusion for you. "
},
{
"code": null,
"e": 6770,
"s": 6514,
"text": "If you donβt get the above point then understand this in a way that you have a list of students in your database. Each one of them has chosen the subjects they are interested in. Treat the βsubjectβ table as a child of a βstudentβ table in your database. "
},
{
"code": null,
"e": 7031,
"s": 6770,
"text": "Now, if you want to create the endpoint for the subjects associated with the student then append the /subjects path to the end of the /student path. If youβre using the GET method then an example of the endpoint path will look something like the given below..."
},
{
"code": null,
"e": 7063,
"s": 7031,
"text": "β/students/:studentId/subjectsβ"
},
{
"code": null,
"e": 7485,
"s": 7063,
"text": "We get subjects on the students identified by studentId and then the response will be returned. Here, students are the parentβs resources and the subject is the childβs resources of the student. So as discussed, we are adding subjects after the β/students/:studentIdβ. Each student has their own subject. The same kind of nesting structure will be applied to other methods as well such as POST, PUT and DELETE endpoints."
},
{
"code": null,
"e": 7695,
"s": 7485,
"text": "When youβre implementing an API make sure that the communication between the client and the server is private because you often send and receive private information. For security purposes, you can use SSL/TLS."
},
{
"code": null,
"e": 7918,
"s": 7695,
"text": "Using the SSL certificate isnβt too difficult. You can easily load it onto the server and the cost of an SSL certificate is also free and very low. Donβt make your REST API open. It should communicate over secure channels."
},
{
"code": null,
"e": 8123,
"s": 7918,
"text": "When a user is accessing the information, they shouldnβt be able to access more data they have requested. Being a user you are not allowed to access the information of another user or the data of admins. "
},
{
"code": null,
"e": 8355,
"s": 8123,
"text": "To implement the principle of the least privilege, add role checks for a single role or more granular roles for each user. If you want to group users into a few roles then they should be allowed to cover all they need and no more. "
},
{
"code": null,
"e": 8644,
"s": 8355,
"text": "For each feature that users have access to if you have more granular permission then make sure that the admins can easily add and remove those features for each user accordingly. Add some preset roles that can be applied to group users. You wonβt have to do this for every user manually. "
},
{
"code": null,
"e": 8954,
"s": 8644,
"text": "You might have used caching during the implementation of some features in your application. Caching is really a powerful tool to speed up the performance of your application. Using caching you will get faster results and you wonβt have to extract the data from the database multiple times for the same query. "
},
{
"code": null,
"e": 9283,
"s": 8954,
"text": "Use caching during the implementation of your API. It will speed up the performance of your application and it will reduce the consumption of the resources. Itβs good to cache the data instead of running the same query and asking the database to give the same result (your database will start crying in front of you....lolzzz). "
},
{
"code": null,
"e": 9623,
"s": 9283,
"text": "One of the precautions you need to take care is that you donβt get outdated data. Due to the old data, something wrong can happen and your system can generate a lot of bugs in a production environment. Do not keep the information for a long period of time in the cache. It is good to keep the data for a short period of time in the cache. "
},
{
"code": null,
"e": 9741,
"s": 9623,
"text": "Depending on the needs you can change the way data is cached. One of the great services to implement caching is Redis"
},
{
"code": null,
"e": 10122,
"s": 9741,
"text": "Keeping the different versions of your API will help you to track the changes and it will help you to restore the previous version in case if something goes wrong with the latest one. Consider a scenario that you implemented an API, deploy it and a lot of clients start using it. Now at some point, you want to make some changes and you added or removed the data from a resource. "
},
{
"code": null,
"e": 10366,
"s": 10122,
"text": "Chances are there that it will generate bugs on the external services that consume the interface. This is the reason you should keep the different versions of your API. From the previous version, you can get the backup and work on it further. "
},
{
"code": null,
"e": 10684,
"s": 10366,
"text": "Versioning can be done according to the semantic version. Donβt force everyone to work on the same version at the same time, you can gradually remove the old versions of your API once you see that itβs not required anymore. Most of the time versioning is done with /v1/, /v2/, etc. added at the start of the API path."
},
{
"code": null,
"e": 10719,
"s": 10684,
"text": "GET /v1/customers\nGET /v2/students"
},
{
"code": null,
"e": 10903,
"s": 10719,
"text": "JSON, SSL/TLS, HTTP Status codes are the standard building blocks of the modern web app API. TO design a high-quality Restful API follow the best conventions we have discussed above. "
},
{
"code": null,
"e": 11168,
"s": 10903,
"text": "Being a backend developer your job is not just to implement the features you are asked to do. You also need to take care of doing it in the best possible way. Apply the best principle when youβre implementing an API so that people who consume and work on it as it."
},
{
"code": null,
"e": 11209,
"s": 11168,
"text": "wksmbfw0zqhot9aok45r04hq8ew63s5sfvvzysl9"
},
{
"code": null,
"e": 11215,
"s": 11209,
"text": "GBlog"
},
{
"code": null,
"e": 11232,
"s": 11215,
"text": "Web Technologies"
}
] |
HTTP headers | Cookie | 30 Oct, 2019
HTTP headers are used to pass additional information with HTTP response or HTTP requests. A cookie is an HTTP request header i.e. used in the requests sent by the user to the server. It contains the cookies previously sent by the server using set-cookies. It is an optional header.
Syntax:
Cookie: <cookie-list>
In case of single cookie syntax is as follow:
Cookie: name=value
In case of multiple cookies syntax is as follow:
Cookie: name=value; name=value; name=value
Directives: This header accept a single directive mentioned above and described below:
<cookie-list> It is the list of name=value pair separated by ; and space i.e β;β.
Example 1:
Cookie: user=Bob
Example 2:
Cookie: user=Bob; age=28; csrftoken=u12t4o8tb9ee73
To check this Cookie in action go to Inspect Element -> Network check the request header for Cookie like below, Cookie is highlighted you can see.
Supported Browsers: The browsers are supported by HTTP Cookie header are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
How to set input type date in dd-mm-yyyy format using HTML ?
Difference Between PUT and PATCH Request | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Oct, 2019"
},
{
"code": null,
"e": 310,
"s": 28,
"text": "HTTP headers are used to pass additional information with HTTP response or HTTP requests. A cookie is an HTTP request header i.e. used in the requests sent by the user to the server. It contains the cookies previously sent by the server using set-cookies. It is an optional header."
},
{
"code": null,
"e": 318,
"s": 310,
"text": "Syntax:"
},
{
"code": null,
"e": 340,
"s": 318,
"text": "Cookie: <cookie-list>"
},
{
"code": null,
"e": 386,
"s": 340,
"text": "In case of single cookie syntax is as follow:"
},
{
"code": null,
"e": 405,
"s": 386,
"text": "Cookie: name=value"
},
{
"code": null,
"e": 454,
"s": 405,
"text": "In case of multiple cookies syntax is as follow:"
},
{
"code": null,
"e": 497,
"s": 454,
"text": "Cookie: name=value; name=value; name=value"
},
{
"code": null,
"e": 584,
"s": 497,
"text": "Directives: This header accept a single directive mentioned above and described below:"
},
{
"code": null,
"e": 666,
"s": 584,
"text": "<cookie-list> It is the list of name=value pair separated by ; and space i.e β;β."
},
{
"code": null,
"e": 677,
"s": 666,
"text": "Example 1:"
},
{
"code": null,
"e": 694,
"s": 677,
"text": "Cookie: user=Bob"
},
{
"code": null,
"e": 705,
"s": 694,
"text": "Example 2:"
},
{
"code": null,
"e": 756,
"s": 705,
"text": "Cookie: user=Bob; age=28; csrftoken=u12t4o8tb9ee73"
},
{
"code": null,
"e": 903,
"s": 756,
"text": "To check this Cookie in action go to Inspect Element -> Network check the request header for Cookie like below, Cookie is highlighted you can see."
},
{
"code": null,
"e": 990,
"s": 903,
"text": "Supported Browsers: The browsers are supported by HTTP Cookie header are listed below:"
},
{
"code": null,
"e": 1004,
"s": 990,
"text": "Google Chrome"
},
{
"code": null,
"e": 1022,
"s": 1004,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1030,
"s": 1022,
"text": "Firefox"
},
{
"code": null,
"e": 1043,
"s": 1030,
"text": "Apple Safari"
},
{
"code": null,
"e": 1049,
"s": 1043,
"text": "Opera"
},
{
"code": null,
"e": 1062,
"s": 1049,
"text": "HTTP-headers"
},
{
"code": null,
"e": 1069,
"s": 1062,
"text": "Picked"
},
{
"code": null,
"e": 1086,
"s": 1069,
"text": "Web Technologies"
},
{
"code": null,
"e": 1184,
"s": 1086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1245,
"s": 1184,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1288,
"s": 1245,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1360,
"s": 1288,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1400,
"s": 1360,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1424,
"s": 1400,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1457,
"s": 1424,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 1517,
"s": 1457,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 1575,
"s": 1517,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 1636,
"s": 1575,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
LocalDate toEpochSecond() method in Java with Examples | 17 Dec, 2018
The toEpochSecond() method of a LocalDate class is used to convert this LocalDate to the number of seconds since the epoch of 1970-01-01T00:00:00Z. The method combines this local date with the specified time and offsets passed as parameters to calculate the epoch-second value, which is the number of elapsed seconds from 1970-01-01T00:00:00Z. Instants on the timeline after the epoch are positive, earlier are negative.
Syntax:
public long toEpochSecond(LocalTime time,
ZoneOffset offset)
Parameters: This method accepts two parameters time and offset which are the local time and the zone offset.
Return value: This method returns long which is the number of seconds since the epoch of 1970-01-01T00:00:00Z, may be negative.
Below programs illustrate the toEpochSecond() method:
Program 1:
// Java program to demonstrate// LocalDate.toEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate localD = LocalDate.parse("2018-12-06"); // print LocalDate System.out.println("LocalDate: " + localD); // create a LocalTime object LocalTime time = LocalTime.parse("20:12:32"); // print Instant System.out.println("Passed LocalTime: " + time); // create ZoneId ZoneOffset zone = ZoneOffset.of("Z"); // print ZoneId System.out.println("Passed ZoneOffset: " + zone); // print result System.out.println("Epoch Second: " + localD.toEpochSecond(time, zone)); }}
Output:
LocalDate: 2018-12-06
Passed LocalTime: 20:12:32
Passed ZoneOffset: Z
Epoch Second: 1544127152
Program 2:
// Java program to demonstrate// LocalDate.toEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate localD = LocalDate.parse("2019-01-01"); // print LocalDate System.out.println("LocalDate: " + localD); // create a LocalTime object LocalTime time = LocalTime.parse("00:00:00"); // print Instant System.out.println("Passed LocalTime: " + time); // create ZoneId ZoneOffset zone = ZoneOffset.of("Z"); // print ZoneId System.out.println("Passed ZoneOffset: " + zone); // print result System.out.println("Epoch Second: " + localD.toEpochSecond(time, zone)); }}
Output:
LocalDate: 2019-01-01
Passed LocalTime: 00:00
Passed ZoneOffset: Z
Epoch Second: 1546300800
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#toEpochSecond(java.time.LocalTime, java.time.ZoneOffset)
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2018"
},
{
"code": null,
"e": 449,
"s": 28,
"text": "The toEpochSecond() method of a LocalDate class is used to convert this LocalDate to the number of seconds since the epoch of 1970-01-01T00:00:00Z. The method combines this local date with the specified time and offsets passed as parameters to calculate the epoch-second value, which is the number of elapsed seconds from 1970-01-01T00:00:00Z. Instants on the timeline after the epoch are positive, earlier are negative."
},
{
"code": null,
"e": 457,
"s": 449,
"text": "Syntax:"
},
{
"code": null,
"e": 545,
"s": 457,
"text": "public long toEpochSecond(LocalTime time,\n ZoneOffset offset)\n"
},
{
"code": null,
"e": 654,
"s": 545,
"text": "Parameters: This method accepts two parameters time and offset which are the local time and the zone offset."
},
{
"code": null,
"e": 782,
"s": 654,
"text": "Return value: This method returns long which is the number of seconds since the epoch of 1970-01-01T00:00:00Z, may be negative."
},
{
"code": null,
"e": 836,
"s": 782,
"text": "Below programs illustrate the toEpochSecond() method:"
},
{
"code": null,
"e": 847,
"s": 836,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// LocalDate.toEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate localD = LocalDate.parse(\"2018-12-06\"); // print LocalDate System.out.println(\"LocalDate: \" + localD); // create a LocalTime object LocalTime time = LocalTime.parse(\"20:12:32\"); // print Instant System.out.println(\"Passed LocalTime: \" + time); // create ZoneId ZoneOffset zone = ZoneOffset.of(\"Z\"); // print ZoneId System.out.println(\"Passed ZoneOffset: \" + zone); // print result System.out.println(\"Epoch Second: \" + localD.toEpochSecond(time, zone)); }}",
"e": 1738,
"s": 847,
"text": null
},
{
"code": null,
"e": 1746,
"s": 1738,
"text": "Output:"
},
{
"code": null,
"e": 1842,
"s": 1746,
"text": "LocalDate: 2018-12-06\nPassed LocalTime: 20:12:32\nPassed ZoneOffset: Z\nEpoch Second: 1544127152\n"
},
{
"code": null,
"e": 1853,
"s": 1842,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// LocalDate.toEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate localD = LocalDate.parse(\"2019-01-01\"); // print LocalDate System.out.println(\"LocalDate: \" + localD); // create a LocalTime object LocalTime time = LocalTime.parse(\"00:00:00\"); // print Instant System.out.println(\"Passed LocalTime: \" + time); // create ZoneId ZoneOffset zone = ZoneOffset.of(\"Z\"); // print ZoneId System.out.println(\"Passed ZoneOffset: \" + zone); // print result System.out.println(\"Epoch Second: \" + localD.toEpochSecond(time, zone)); }}",
"e": 2744,
"s": 1853,
"text": null
},
{
"code": null,
"e": 2752,
"s": 2744,
"text": "Output:"
},
{
"code": null,
"e": 2845,
"s": 2752,
"text": "LocalDate: 2019-01-01\nPassed LocalTime: 00:00\nPassed ZoneOffset: Z\nEpoch Second: 1546300800\n"
},
{
"code": null,
"e": 2981,
"s": 2845,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#toEpochSecond(java.time.LocalTime, java.time.ZoneOffset)"
},
{
"code": null,
"e": 2996,
"s": 2981,
"text": "Java-Functions"
},
{
"code": null,
"e": 3011,
"s": 2996,
"text": "Java-LocalDate"
},
{
"code": null,
"e": 3029,
"s": 3011,
"text": "Java-time package"
},
{
"code": null,
"e": 3034,
"s": 3029,
"text": "Java"
},
{
"code": null,
"e": 3039,
"s": 3034,
"text": "Java"
},
{
"code": null,
"e": 3137,
"s": 3039,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3188,
"s": 3137,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3219,
"s": 3188,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3249,
"s": 3219,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3267,
"s": 3249,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3282,
"s": 3267,
"text": "Stream In Java"
},
{
"code": null,
"e": 3302,
"s": 3282,
"text": "Collections in Java"
},
{
"code": null,
"e": 3326,
"s": 3302,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3358,
"s": 3326,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3370,
"s": 3358,
"text": "Set in Java"
}
] |
Maximum value of unsigned int in C++ | 18 Jan, 2021
In this article, we will discuss the maximum value of unsigned int in C++.
Unsigned int data type in C++ is used to store 32-bit integers.
The keyword unsigned is a data type specifier, which only represents non-negative integers i.e. positive numbers and zero.
Some properties of the unsigned int data type are:
An unsigned data type can only store positive values.
It takes a size of 32 bits.
A maximum integer value that can be stored in an unsigned int data type is typically 4, 294, 967, 295, around 232 β 1(but is compiler dependent).
The maximum value that can be stored in unsigned int is stored as a constant in the <climits> header file. whose value can be used as UINT_MAX.
A minimum integer value that can be stored in an unsigned int data type is typically 0.
In case of overflow or underflow of data type, the value is wrapped around.
For example, if 0 is stored in an int data type and 1 is subtracted from it, the value in that variable will become equal to 4, 294, 967, 295. Similarly, in the case of overflow, the value will round back to 0.
Below is the program to get the highest value that can be stored in unsigned int in C++:
C++
// C++ program to obtain the maximum// value stored in unsigned int#include <climits>#include <iostream>using namespace std; // Function that prints the maximum// value stored in unsigned intvoid maxUnsignedInt(){ // From the constant of climits // header file unsigned int valueFromLimits = UINT_MAX; cout << "Value from climits constant : " << valueFromLimits << "\n"; // Using the wrap around property // of data types // Initialize a variable with 0 unsigned int value = 0; // Subtract 1 from value since // unsigned data type cannot store // negative number, the value will // wrap around and store the // maximum value in it value = value - 1; cout << "Value using the wrap" << " around property : " << value << "\n";} // Driver Codeint main(){ // Function call maxUnsignedInt(); return 0;}
Value from climits constant : 4294967295
Value using the wrap around property : 4294967295
C Basics
CPP-Basics
Data Types
C++
C++ Programs
Programming Language
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 129,
"s": 54,
"text": "In this article, we will discuss the maximum value of unsigned int in C++."
},
{
"code": null,
"e": 193,
"s": 129,
"text": "Unsigned int data type in C++ is used to store 32-bit integers."
},
{
"code": null,
"e": 317,
"s": 193,
"text": "The keyword unsigned is a data type specifier, which only represents non-negative integers i.e. positive numbers and zero. "
},
{
"code": null,
"e": 368,
"s": 317,
"text": "Some properties of the unsigned int data type are:"
},
{
"code": null,
"e": 422,
"s": 368,
"text": "An unsigned data type can only store positive values."
},
{
"code": null,
"e": 450,
"s": 422,
"text": "It takes a size of 32 bits."
},
{
"code": null,
"e": 596,
"s": 450,
"text": "A maximum integer value that can be stored in an unsigned int data type is typically 4, 294, 967, 295, around 232 β 1(but is compiler dependent)."
},
{
"code": null,
"e": 740,
"s": 596,
"text": "The maximum value that can be stored in unsigned int is stored as a constant in the <climits> header file. whose value can be used as UINT_MAX."
},
{
"code": null,
"e": 828,
"s": 740,
"text": "A minimum integer value that can be stored in an unsigned int data type is typically 0."
},
{
"code": null,
"e": 904,
"s": 828,
"text": "In case of overflow or underflow of data type, the value is wrapped around."
},
{
"code": null,
"e": 1115,
"s": 904,
"text": "For example, if 0 is stored in an int data type and 1 is subtracted from it, the value in that variable will become equal to 4, 294, 967, 295. Similarly, in the case of overflow, the value will round back to 0."
},
{
"code": null,
"e": 1204,
"s": 1115,
"text": "Below is the program to get the highest value that can be stored in unsigned int in C++:"
},
{
"code": null,
"e": 1208,
"s": 1204,
"text": "C++"
},
{
"code": "// C++ program to obtain the maximum// value stored in unsigned int#include <climits>#include <iostream>using namespace std; // Function that prints the maximum// value stored in unsigned intvoid maxUnsignedInt(){ // From the constant of climits // header file unsigned int valueFromLimits = UINT_MAX; cout << \"Value from climits constant : \" << valueFromLimits << \"\\n\"; // Using the wrap around property // of data types // Initialize a variable with 0 unsigned int value = 0; // Subtract 1 from value since // unsigned data type cannot store // negative number, the value will // wrap around and store the // maximum value in it value = value - 1; cout << \"Value using the wrap\" << \" around property : \" << value << \"\\n\";} // Driver Codeint main(){ // Function call maxUnsignedInt(); return 0;}",
"e": 2097,
"s": 1208,
"text": null
},
{
"code": null,
"e": 2189,
"s": 2097,
"text": "Value from climits constant : 4294967295\nValue using the wrap around property : 4294967295\n"
},
{
"code": null,
"e": 2198,
"s": 2189,
"text": "C Basics"
},
{
"code": null,
"e": 2209,
"s": 2198,
"text": "CPP-Basics"
},
{
"code": null,
"e": 2220,
"s": 2209,
"text": "Data Types"
},
{
"code": null,
"e": 2224,
"s": 2220,
"text": "C++"
},
{
"code": null,
"e": 2237,
"s": 2224,
"text": "C++ Programs"
},
{
"code": null,
"e": 2258,
"s": 2237,
"text": "Programming Language"
},
{
"code": null,
"e": 2262,
"s": 2258,
"text": "CPP"
},
{
"code": null,
"e": 2360,
"s": 2262,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2384,
"s": 2360,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2404,
"s": 2384,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2437,
"s": 2404,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2481,
"s": 2437,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2506,
"s": 2481,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2541,
"s": 2506,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 2575,
"s": 2541,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 2619,
"s": 2575,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 2678,
"s": 2619,
"text": "How to return multiple values from a function in C or C++?"
}
] |
How to get the IIS Application Pool names using PowerShell? | To get the IIS application pool names using PowerShell, you need to use the IIS PSDrive but for that, we need the IIS PowerShell module WebAdministration or IISAdministration on the server we are running the command.
If the WebAdministration module is already installed, use the below command to import the module.
Import-Module WebAdministration -Verbose
Once you Import the above module, you can see the IIS PSDrive will be activated in the current session.
To get all the application Pools run the below command,
Get-ChildItem IIS:\AppPools\
Name State Applications
---- ----- ------------
.NET v2.0 Started
.NET v2.0 Classic Started
.NET v4.5 Started
.NET v4.5 Classic Started
Classic .NET AppPool Started
DefaultAppPool Started Default Web Site
To retrieve the particular app pool name use the Get-Item command,
Get-Item IIS:\AppPools\DefaultAppPool
Name State Applications
---- ----- ------------
DefaultAppPool Started Default Web Site
Another simple method is by using the Get-IISAppPool command of the IISAdministration module.
Import-Module IISAdministration -Verbose
Use the Get-IISAppPool command.
Name Status CLR Ver Pipeline Mode Start Mode
---- ------ ------- ------------- ----------
DefaultAppPool Started v4.0 Integrated OnDemand
Classic .NET AppPool Started v2.0 Classic OnDemand
.NET v2.0 Classic Started v2.0 Classic OnDemand
.NET v2.0 Started v2.0 Integrated OnDemand
.NET v4.5 Classic Started v4.0 Classic OnDemand
.NET v4.5 Started v4.0 Integrated OnDemand
For the particular app pool use the -Name property,
Get-IISAppPool -Name DefaultAppPool | [
{
"code": null,
"e": 1404,
"s": 1187,
"text": "To get the IIS application pool names using PowerShell, you need to use the IIS PSDrive but for that, we need the IIS PowerShell module WebAdministration or IISAdministration on the server we are running the command."
},
{
"code": null,
"e": 1502,
"s": 1404,
"text": "If the WebAdministration module is already installed, use the below command to import the module."
},
{
"code": null,
"e": 1543,
"s": 1502,
"text": "Import-Module WebAdministration -Verbose"
},
{
"code": null,
"e": 1647,
"s": 1543,
"text": "Once you Import the above module, you can see the IIS PSDrive will be activated in the current session."
},
{
"code": null,
"e": 1703,
"s": 1647,
"text": "To get all the application Pools run the below command,"
},
{
"code": null,
"e": 1732,
"s": 1703,
"text": "Get-ChildItem IIS:\\AppPools\\"
},
{
"code": null,
"e": 2054,
"s": 1732,
"text": "Name State Applications\n---- ----- ------------\n.NET v2.0 Started\n.NET v2.0 Classic Started\n.NET v4.5 Started\n.NET v4.5 Classic Started\nClassic .NET AppPool Started\nDefaultAppPool Started Default Web Site"
},
{
"code": null,
"e": 2121,
"s": 2054,
"text": "To retrieve the particular app pool name use the Get-Item command,"
},
{
"code": null,
"e": 2159,
"s": 2121,
"text": "Get-Item IIS:\\AppPools\\DefaultAppPool"
},
{
"code": null,
"e": 2316,
"s": 2159,
"text": "Name State Applications\n---- ----- ------------\nDefaultAppPool Started Default Web Site"
},
{
"code": null,
"e": 2410,
"s": 2316,
"text": "Another simple method is by using the Get-IISAppPool command of the IISAdministration module."
},
{
"code": null,
"e": 2451,
"s": 2410,
"text": "Import-Module IISAdministration -Verbose"
},
{
"code": null,
"e": 2483,
"s": 2451,
"text": "Use the Get-IISAppPool command."
},
{
"code": null,
"e": 3023,
"s": 2483,
"text": "Name Status CLR Ver Pipeline Mode Start Mode\n---- ------ ------- ------------- ----------\nDefaultAppPool Started v4.0 Integrated OnDemand\nClassic .NET AppPool Started v2.0 Classic OnDemand\n.NET v2.0 Classic Started v2.0 Classic OnDemand\n.NET v2.0 Started v2.0 Integrated OnDemand\n.NET v4.5 Classic Started v4.0 Classic OnDemand\n.NET v4.5 Started v4.0 Integrated OnDemand"
},
{
"code": null,
"e": 3075,
"s": 3023,
"text": "For the particular app pool use the -Name property,"
},
{
"code": null,
"e": 3111,
"s": 3075,
"text": "Get-IISAppPool -Name DefaultAppPool"
}
] |
NPDA for accepting the language L = {wwR | w β (a,b)*} | 20 Jan, 2022
Prerequisite β Pushdown Automata, Pushdown Automata Acceptance by Final State
Design a non deterministic PDA for accepting the language L = {wwR w β (a, b)*}, i.e.,
L = {aa, bb, abba, aabbaa, abaaba, ......}
In this type of input string, one input has more than one transition states, hence it is called non-deterministic PDA, and the input string contain any order of βaβ and βbβ. Each input alphabet has more than one possibility to move next state. And finally when the stack is empty then the string is accepted by the NPDA. In this NPDA we used some symbols which are given below:
Ξ = { a, b, z }
Where, Ξ = set of all the stack alphabet z = stack start symbol a = input alphabet b = input alphabet
As we want to design an NPDA, thus every times βaβ or βbβ comes then either push into the stack or move into the next state. It is dependent on a string. When we see the input alphabet which is equal to the top of the stack then that time pop operation applies on the stack and move to the next step. So, in the end, if the stack becomes empty then we can say that the string is accepted by the PDA.
(q0, a, z) (q0, az)
(q0, a, a) (q0, aa)
(q0, b, z) (q0, bz)
(q0, b, b) (q0, bb)
(q0, a, b) (q0, ab)
(q0, b, a) (q0, ba)
(q0, a, a) (q1, β)
(q0, b, b) (q1, β)
(q1, a, a) (q1, β)
(q1, b, b) (q1, β)
(q1, β, z) (qf, z)
Where, q0 = Initial state qf = Final state β = indicates pop operation
So, this is our required non-deterministic PDA for accepting the language L = {wwR w β (a, b)*}
We will take one input string: βabbbbaβ.
Scan string from left to right
The first input is βaβ and follows the rule:
on input βaβ and STACK alphabet Z, push the two βaβs into STACK as: (a, Z/aZ) and state will be q0
on input βbβ and STACK alphabet βaβ, push the βbβ into STACK as: (b, a/ba) and state will be q0
on input βbβ and STACK alphabet βbβ, push the βbβ into STACK as: (b, b/bb) and state will be q0
on input βbβ and STACK alphabet βbβ (state is q1), pop one βbβ from STACK as: (b, b/β) and state will be q1
on input βbβ and STACK alphabet βbβ (state is q1), pop one βbβ from STACK as: (b, b/β) and state will be q1
on input βaβ and STACK alphabet βaβ and state q1, pop one βaβ from STACK as: (a, a/β) and state will remain q1
on input β and STACK alphabet Z, go to the final state(qf) as : (β, Z/Z)
So, at the end the stack becomes empty then we can say that the string is accepted by the PDA.
NOTE: This DPDA will not accept the empty language.
Design a deterministic PDA for accepting the language L = { wcwR w β (a, b)*}, i.e.,
{aca, bcb, abcba, abacaba, aacaa, bbcbb, .......}
In each string, the substring which is present on the left side of c is the reverse of the substring which is the present right side of c.
Here we need to maintain string in such a way that, the substring which is present on the left side of c is exactly the reverse substring which is the right side of c. For doing this we used a stack. In string βaβ and βbβ are present any order and βcβ come only one time. When βcβ comes then the pop operation is started into the stack. And when a stack is empty then language is accepted.
Ξ = {a, b, z}
Where, Ξ = set of all the stack alphabet z = stack start symbol a = input alphabet b = input alphabet
As we want to design PDA In every time when βaβ or βbβ comes we push into the stack and stay on the same state q0. And when βcβ comes then we move to the next state q1 without pushing βcβ into the stack. And after when comes an input which is the same as the top of the stack then pop from the stack and stay on the same state. POP operation is performed until the input string is ended. Finally when the input is β, then move to the final state qf. When if the stack will become empty then the language is accepted.
Where, q0 = Initial state qf = Final state z = stack start symbol β= indicates pop operation
(q0, a, z) (q0, az)
(q0, a, a) (q0, aa)
(q0, b, z) (q0, bz)
(q0, b, b) (q0, bb)
(q0, a, b) (q0, ab)
(q0, b, a) (q0, ba)
(q0, c, a) (q1, a)
(q0, c, b) (q1, b)
(q1, a, a) (q1, β)
(q1, b, b) (q1, β)
(q1, β, z) (qf, z)
Where, q0 = Initial state qf = Final state β = indicates pop operation
So, this is our required deterministic PDA for accepting the language,
L = { wcwR w β (a, b)*}
akshaysingh98088
anikaseth98
myskersaiprem1409
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 133,
"s": 54,
"text": "Prerequisite β Pushdown Automata, Pushdown Automata Acceptance by Final State "
},
{
"code": null,
"e": 221,
"s": 133,
"text": "Design a non deterministic PDA for accepting the language L = {wwR w β (a, b)*}, i.e., "
},
{
"code": null,
"e": 265,
"s": 221,
"text": "L = {aa, bb, abba, aabbaa, abaaba, ......} "
},
{
"code": null,
"e": 644,
"s": 265,
"text": "In this type of input string, one input has more than one transition states, hence it is called non-deterministic PDA, and the input string contain any order of βaβ and βbβ. Each input alphabet has more than one possibility to move next state. And finally when the stack is empty then the string is accepted by the NPDA. In this NPDA we used some symbols which are given below: "
},
{
"code": null,
"e": 660,
"s": 644,
"text": "Ξ = { a, b, z }"
},
{
"code": null,
"e": 763,
"s": 660,
"text": "Where, Ξ = set of all the stack alphabet z = stack start symbol a = input alphabet b = input alphabet "
},
{
"code": null,
"e": 1164,
"s": 763,
"text": "As we want to design an NPDA, thus every times βaβ or βbβ comes then either push into the stack or move into the next state. It is dependent on a string. When we see the input alphabet which is equal to the top of the stack then that time pop operation applies on the stack and move to the next step. So, in the end, if the stack becomes empty then we can say that the string is accepted by the PDA. "
},
{
"code": null,
"e": 1402,
"s": 1164,
"text": "(q0, a, z) (q0, az)\n\n(q0, a, a) (q0, aa)\n\n(q0, b, z) (q0, bz)\n\n(q0, b, b) (q0, bb)\n\n(q0, a, b) (q0, ab)\n\n(q0, b, a) (q0, ba)\n\n\n(q0, a, a) (q1, β)\n\n(q0, b, b) (q1, β)\n\n(q1, a, a) (q1, β)\n\n(q1, b, b) (q1, β)\n\n\n(q1, β, z) (qf, z)"
},
{
"code": null,
"e": 1474,
"s": 1402,
"text": "Where, q0 = Initial state qf = Final state β = indicates pop operation "
},
{
"code": null,
"e": 1571,
"s": 1474,
"text": "So, this is our required non-deterministic PDA for accepting the language L = {wwR w β (a, b)*} "
},
{
"code": null,
"e": 1613,
"s": 1571,
"text": "We will take one input string: βabbbbaβ. "
},
{
"code": null,
"e": 1644,
"s": 1613,
"text": "Scan string from left to right"
},
{
"code": null,
"e": 1689,
"s": 1644,
"text": "The first input is βaβ and follows the rule:"
},
{
"code": null,
"e": 1788,
"s": 1689,
"text": "on input βaβ and STACK alphabet Z, push the two βaβs into STACK as: (a, Z/aZ) and state will be q0"
},
{
"code": null,
"e": 1884,
"s": 1788,
"text": "on input βbβ and STACK alphabet βaβ, push the βbβ into STACK as: (b, a/ba) and state will be q0"
},
{
"code": null,
"e": 1980,
"s": 1884,
"text": "on input βbβ and STACK alphabet βbβ, push the βbβ into STACK as: (b, b/bb) and state will be q0"
},
{
"code": null,
"e": 2088,
"s": 1980,
"text": "on input βbβ and STACK alphabet βbβ (state is q1), pop one βbβ from STACK as: (b, b/β) and state will be q1"
},
{
"code": null,
"e": 2196,
"s": 2088,
"text": "on input βbβ and STACK alphabet βbβ (state is q1), pop one βbβ from STACK as: (b, b/β) and state will be q1"
},
{
"code": null,
"e": 2307,
"s": 2196,
"text": "on input βaβ and STACK alphabet βaβ and state q1, pop one βaβ from STACK as: (a, a/β) and state will remain q1"
},
{
"code": null,
"e": 2380,
"s": 2307,
"text": "on input β and STACK alphabet Z, go to the final state(qf) as : (β, Z/Z)"
},
{
"code": null,
"e": 2476,
"s": 2380,
"text": "So, at the end the stack becomes empty then we can say that the string is accepted by the PDA. "
},
{
"code": null,
"e": 2528,
"s": 2476,
"text": "NOTE: This DPDA will not accept the empty language."
},
{
"code": null,
"e": 2614,
"s": 2528,
"text": "Design a deterministic PDA for accepting the language L = { wcwR w β (a, b)*}, i.e., "
},
{
"code": null,
"e": 2664,
"s": 2614,
"text": "{aca, bcb, abcba, abacaba, aacaa, bbcbb, .......}"
},
{
"code": null,
"e": 2804,
"s": 2664,
"text": "In each string, the substring which is present on the left side of c is the reverse of the substring which is the present right side of c. "
},
{
"code": null,
"e": 3195,
"s": 2804,
"text": "Here we need to maintain string in such a way that, the substring which is present on the left side of c is exactly the reverse substring which is the right side of c. For doing this we used a stack. In string βaβ and βbβ are present any order and βcβ come only one time. When βcβ comes then the pop operation is started into the stack. And when a stack is empty then language is accepted. "
},
{
"code": null,
"e": 3210,
"s": 3195,
"text": "Ξ = {a, b, z} "
},
{
"code": null,
"e": 3313,
"s": 3210,
"text": "Where, Ξ = set of all the stack alphabet z = stack start symbol a = input alphabet b = input alphabet "
},
{
"code": null,
"e": 3831,
"s": 3313,
"text": "As we want to design PDA In every time when βaβ or βbβ comes we push into the stack and stay on the same state q0. And when βcβ comes then we move to the next state q1 without pushing βcβ into the stack. And after when comes an input which is the same as the top of the stack then pop from the stack and stay on the same state. POP operation is performed until the input string is ended. Finally when the input is β, then move to the final state qf. When if the stack will become empty then the language is accepted. "
},
{
"code": null,
"e": 3925,
"s": 3831,
"text": "Where, q0 = Initial state qf = Final state z = stack start symbol β= indicates pop operation "
},
{
"code": null,
"e": 4165,
"s": 3925,
"text": "(q0, a, z) (q0, az)\n\n(q0, a, a) (q0, aa)\n\n(q0, b, z) (q0, bz)\n\n(q0, b, b) (q0, bb)\n\n(q0, a, b) (q0, ab)\n\n(q0, b, a) (q0, ba)\n\n\n(q0, c, a) (q1, a)\n\n(q0, c, b) (q1, b)\n\n(q1, a, a) (q1, β)\n\n(q1, b, b) (q1, β)\n \n\n(q1, β, z) (qf, z) "
},
{
"code": null,
"e": 4238,
"s": 4165,
"text": "Where, q0 = Initial state qf = Final state β = indicates pop operation "
},
{
"code": null,
"e": 4310,
"s": 4238,
"text": "So, this is our required deterministic PDA for accepting the language, "
},
{
"code": null,
"e": 4335,
"s": 4310,
"text": "L = { wcwR w β (a, b)*} "
},
{
"code": null,
"e": 4352,
"s": 4335,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 4364,
"s": 4352,
"text": "anikaseth98"
},
{
"code": null,
"e": 4382,
"s": 4364,
"text": "myskersaiprem1409"
},
{
"code": null,
"e": 4390,
"s": 4382,
"text": "GATE CS"
},
{
"code": null,
"e": 4423,
"s": 4390,
"text": "Theory of Computation & Automata"
}
] |
HTML <section> Tag | 17 Mar, 2022
Section tag defines the section of documents such as chapters, headers, footers or any other sections. The section tag divides the content into section and subsections. The section tag is used when requirements of two headers or footers or any other section of documents needed. Section tag grouped the generic block of related contents. The main advantage of the section tag is, it is a semantic element, which describes its meaning to both browser and developer.Syntax:
<section> Section Contents </section>
Section tag is used to distribute the content i.e, it distributes the sections and subsections. Example:
HTML
<!DOCTYPE html><html> <body> <!-- html section tag is used here --> <section> <h1>Geeksforgeeek: Section 1</h1> <p>Content of section 1</p> </section> <section> <h1>GeeksforGeeks: Section 2</h1> <p>Content of section 2</p> </section> <section> <h1>GeeksforGeeks: Section 3</h1> <p>Content of section 3</p> </section> </body></html>
Output:
Nested Section tag: The section tag can be nested. The font size of subsection is smaller then section tag if the text contains the same font property. The subsection tag is used for organizing complex documents. A rule of thumb is that section should logically appear in outline of the document. Example:
HTML
<!DOCTYPE html><html> <body> <!-- html section tag is used here --> <section> <h1>Geeksforgeeek: Section 1</h1> <p>Content of section 1</p> <section> <h1>Subsection</h1> <h1>Subsection</h1> </section> </section> <section> <h1>GeeksforGeeks: Section 2</h1> <p>Content of section 2</p> <section> <h1>Subsection</h1> <h1>Subsection</h1> </section> </section> </body></html>
Output:
Supported Browsers:
Google Chrome 6.0 and above
Internet Explorer 9.0 and above
Mozilla 4.0 and above
Opera 11.1 and above
Safari 5.0 and above
Akanksha_Rai
shubhamyadav4
HTML-Tags
HTML5
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 527,
"s": 53,
"text": "Section tag defines the section of documents such as chapters, headers, footers or any other sections. The section tag divides the content into section and subsections. The section tag is used when requirements of two headers or footers or any other section of documents needed. Section tag grouped the generic block of related contents. The main advantage of the section tag is, it is a semantic element, which describes its meaning to both browser and developer.Syntax: "
},
{
"code": null,
"e": 565,
"s": 527,
"text": "<section> Section Contents </section>"
},
{
"code": null,
"e": 672,
"s": 565,
"text": "Section tag is used to distribute the content i.e, it distributes the sections and subsections. Example: "
},
{
"code": null,
"e": 677,
"s": 672,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <!-- html section tag is used here --> <section> <h1>Geeksforgeeek: Section 1</h1> <p>Content of section 1</p> </section> <section> <h1>GeeksforGeeks: Section 2</h1> <p>Content of section 2</p> </section> <section> <h1>GeeksforGeeks: Section 3</h1> <p>Content of section 3</p> </section> </body></html> ",
"e": 1155,
"s": 677,
"text": null
},
{
"code": null,
"e": 1165,
"s": 1155,
"text": "Output: "
},
{
"code": null,
"e": 1473,
"s": 1165,
"text": "Nested Section tag: The section tag can be nested. The font size of subsection is smaller then section tag if the text contains the same font property. The subsection tag is used for organizing complex documents. A rule of thumb is that section should logically appear in outline of the document. Example: "
},
{
"code": null,
"e": 1478,
"s": 1473,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <!-- html section tag is used here --> <section> <h1>Geeksforgeeek: Section 1</h1> <p>Content of section 1</p> <section> <h1>Subsection</h1> <h1>Subsection</h1> </section> </section> <section> <h1>GeeksforGeeks: Section 2</h1> <p>Content of section 2</p> <section> <h1>Subsection</h1> <h1>Subsection</h1> </section> </section> </body></html> ",
"e": 2061,
"s": 1478,
"text": null
},
{
"code": null,
"e": 2071,
"s": 2061,
"text": "Output: "
},
{
"code": null,
"e": 2093,
"s": 2071,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 2121,
"s": 2093,
"text": "Google Chrome 6.0 and above"
},
{
"code": null,
"e": 2153,
"s": 2121,
"text": "Internet Explorer 9.0 and above"
},
{
"code": null,
"e": 2175,
"s": 2153,
"text": "Mozilla 4.0 and above"
},
{
"code": null,
"e": 2196,
"s": 2175,
"text": "Opera 11.1 and above"
},
{
"code": null,
"e": 2217,
"s": 2196,
"text": "Safari 5.0 and above"
},
{
"code": null,
"e": 2232,
"s": 2219,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2246,
"s": 2232,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 2256,
"s": 2246,
"text": "HTML-Tags"
},
{
"code": null,
"e": 2262,
"s": 2256,
"text": "HTML5"
},
{
"code": null,
"e": 2267,
"s": 2262,
"text": "HTML"
},
{
"code": null,
"e": 2272,
"s": 2267,
"text": "HTML"
},
{
"code": null,
"e": 2370,
"s": 2272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2418,
"s": 2370,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2480,
"s": 2418,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2530,
"s": 2480,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2554,
"s": 2530,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2607,
"s": 2554,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2667,
"s": 2607,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2728,
"s": 2667,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 2778,
"s": 2728,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 2815,
"s": 2778,
"text": "Types of CSS (Cascading Style Sheet)"
}
] |
Python | Min/Max value in float string list | 22 Jan, 2021
Sometimes, while working with a Python list, we can have a problem in which we need to find min/max value in the list. But sometimes, we donβt have a natural number but a floating-point number in string format. This problem can occur while working with data, both in web development and Data Science domain. Letβs discuss a way in which this problem can be solved. Method : Using min()/max() + float() This problem can be solved using the min or max function in which we first convert the strings into float and then pass this logic in functions in respective min/max function.
Python3
# Python3 code to demonstrate working of# Min / Max value in float string list# using min()/max() + float() + generator # initialize liststest_list = ['4.5', '7.8', '9.8', '10.3'] # printing original listprint("The original list is : " + str(test_list)) # Min / Max value in float string list# using min()/max() +float + lambda functionres_min = min(test_list,key=lambda x:float(x))res_max = max(test_list,key=lambda x:float(x)) # printing resultprint("The min value of list : " + str(res_min))print("The max value of list : " + str(res_max))
The original list is : ['4.5', '7.8', '9.8', '10.3']
The min value of list : 4.5
The max value of list : 10.3
mrmechanical26052000
Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 607,
"s": 28,
"text": "Sometimes, while working with a Python list, we can have a problem in which we need to find min/max value in the list. But sometimes, we donβt have a natural number but a floating-point number in string format. This problem can occur while working with data, both in web development and Data Science domain. Letβs discuss a way in which this problem can be solved. Method : Using min()/max() + float() This problem can be solved using the min or max function in which we first convert the strings into float and then pass this logic in functions in respective min/max function. "
},
{
"code": null,
"e": 615,
"s": 607,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Min / Max value in float string list# using min()/max() + float() + generator # initialize liststest_list = ['4.5', '7.8', '9.8', '10.3'] # printing original listprint(\"The original list is : \" + str(test_list)) # Min / Max value in float string list# using min()/max() +float + lambda functionres_min = min(test_list,key=lambda x:float(x))res_max = max(test_list,key=lambda x:float(x)) # printing resultprint(\"The min value of list : \" + str(res_min))print(\"The max value of list : \" + str(res_max))",
"e": 1158,
"s": 615,
"text": null
},
{
"code": null,
"e": 1269,
"s": 1158,
"text": "The original list is : ['4.5', '7.8', '9.8', '10.3']\nThe min value of list : 4.5\nThe max value of list : 10.3\n"
},
{
"code": null,
"e": 1290,
"s": 1269,
"text": "mrmechanical26052000"
},
{
"code": null,
"e": 1311,
"s": 1290,
"text": "Python list-programs"
},
{
"code": null,
"e": 1318,
"s": 1311,
"text": "Python"
},
{
"code": null,
"e": 1416,
"s": 1318,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1448,
"s": 1416,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1475,
"s": 1448,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1496,
"s": 1475,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1519,
"s": 1496,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1575,
"s": 1519,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1606,
"s": 1575,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1648,
"s": 1606,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1690,
"s": 1648,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1729,
"s": 1690,
"text": "Python | Get unique values from a list"
}
] |
The new age of Jupyter widgets. What if you could use your NPM goodies... | by Dimitris Poulopoulos | Towards Data Science | Notebooks have always been a tool for the incremental development of software ideas. Data scientists use Jupyter to journal their work, explore and experiment with novel algorithms, quickly sketch new approaches and immediately observe the outcomes.
This interactivity is what makes Jupyter so appealing. To take it one step further, Data Scientists use Jupyter widgets to visualize their results or create mini web apps that facilitate navigating through the content or encourage user interaction.
However, IPyWidgets are not always easy to work with. They do not follow the declarative design principles pioneered by front-end developers, and the resulting components cannot be transferred as is in a browser environment. Also, the developers created these libraries mostly to cover the visualization needs of Data Scientists. Thus, they fall short of features that popular front-end frameworks like React and Vue bring to the table.
It is time to take the next step; This story introduces IDOM: a set of libraries for defining and controlling interactive webpages or create visual Jupyter components. We will discuss the latter.
Learning Rate is a newsletter for those who are curious about the world of AI and MLOps. Youβll hear from me every Friday with updates and thoughts on the latest AI news and articles. Subscribe here!
So, letβs get started with IDOM. For those familiar with React, youβll find many similarities in the way IDOM does things.
We will create a simple TODO application inside Jupyter. Yes, I donβt know how this would help a Data Scientist, but what Iβm trying to do is showcase IDOMβs capabilities. If you find any Data Science use cases, please leave them in the comments!
First, the code. Then, we will walk through one line at a time to understand how it works.
The idom.component decorator creates a Component constructor. This component is rendered in the screen using the function below it (e.g., todo()). Then, to display it, we need to call this function and create an instance of this component at the end.
Now, letβs get into what this function does. First, The use_state() function is a Hook. Calling this method returns two things: a current state value and a function that we can use to update this state. In our case, the current state is just an empty list.
Then, we can use the update function inside an add_new_task() method to do whatever we want. This function takes an event and checks if the event was produced by hitting your keyboard's Enterkey. If thatβs true, it retrieves the event's value and appends it to the list of tasks.
To store the tasks that the user creates, we append their name in a separate tasks Python list, alongside a simple delete button. The delete button, when pressed, calls the remove_task() function, which updates the state just like the add_new_task() function. However, instead of adding a new item to the current state, it removes the selected one.
Finally, we create an input element to create TODO tasks and an HTML table element to hold them. In the last step, we render them using a div HTML tag.
So far, so good. However, the power that IDOM gives us is not limited to displaying HTML elements. The real power of IDOM comes from its ability to install and use any React ecosystem components seamlessly.
In this example, let's use victory, a set of React components for modular charting and data visualization. To install victory, we can use the IDOM CLI:
!idom install victory
Then, letβs use it in our code:
Congrats! Youβve just created a Pie chart with victory in a Jupyter Notebook! Of course, it is also straightforward to import and use your existing JavaScript modules. See how in the documentation.
Data Scientists use Jupyter widgets to visualize their results or create mini web apps that facilitate navigating through the content or encourage user interaction.
However, IPyWidgets are not always easy to work with. They also have some drawbacks: they do not follow declarative design principles, and the resulting components cannot be transferred as is in a browser environment.
It is time to take the next step; This story examined IDOM: a set of libraries for defining and controlling interactive webpages or create visual Jupyter components.
The IDOM API is described more exhaustively in the documentation. Also, you can play with idom-jupyter on Binder, before installing.
My name is Dimitris Poulopoulos, and Iβm a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA.
If you are interested in reading more posts about Machine Learning, Deep Learning, Data Science, and DataOps, follow me on Medium, LinkedIn, or @james2pl on Twitter. Also, visit the resources page on my website, a place for great books and top-rated courses, to start building your own Data Science curriculum! | [
{
"code": null,
"e": 422,
"s": 172,
"text": "Notebooks have always been a tool for the incremental development of software ideas. Data scientists use Jupyter to journal their work, explore and experiment with novel algorithms, quickly sketch new approaches and immediately observe the outcomes."
},
{
"code": null,
"e": 671,
"s": 422,
"text": "This interactivity is what makes Jupyter so appealing. To take it one step further, Data Scientists use Jupyter widgets to visualize their results or create mini web apps that facilitate navigating through the content or encourage user interaction."
},
{
"code": null,
"e": 1108,
"s": 671,
"text": "However, IPyWidgets are not always easy to work with. They do not follow the declarative design principles pioneered by front-end developers, and the resulting components cannot be transferred as is in a browser environment. Also, the developers created these libraries mostly to cover the visualization needs of Data Scientists. Thus, they fall short of features that popular front-end frameworks like React and Vue bring to the table."
},
{
"code": null,
"e": 1304,
"s": 1108,
"text": "It is time to take the next step; This story introduces IDOM: a set of libraries for defining and controlling interactive webpages or create visual Jupyter components. We will discuss the latter."
},
{
"code": null,
"e": 1504,
"s": 1304,
"text": "Learning Rate is a newsletter for those who are curious about the world of AI and MLOps. Youβll hear from me every Friday with updates and thoughts on the latest AI news and articles. Subscribe here!"
},
{
"code": null,
"e": 1627,
"s": 1504,
"text": "So, letβs get started with IDOM. For those familiar with React, youβll find many similarities in the way IDOM does things."
},
{
"code": null,
"e": 1874,
"s": 1627,
"text": "We will create a simple TODO application inside Jupyter. Yes, I donβt know how this would help a Data Scientist, but what Iβm trying to do is showcase IDOMβs capabilities. If you find any Data Science use cases, please leave them in the comments!"
},
{
"code": null,
"e": 1965,
"s": 1874,
"text": "First, the code. Then, we will walk through one line at a time to understand how it works."
},
{
"code": null,
"e": 2216,
"s": 1965,
"text": "The idom.component decorator creates a Component constructor. This component is rendered in the screen using the function below it (e.g., todo()). Then, to display it, we need to call this function and create an instance of this component at the end."
},
{
"code": null,
"e": 2473,
"s": 2216,
"text": "Now, letβs get into what this function does. First, The use_state() function is a Hook. Calling this method returns two things: a current state value and a function that we can use to update this state. In our case, the current state is just an empty list."
},
{
"code": null,
"e": 2753,
"s": 2473,
"text": "Then, we can use the update function inside an add_new_task() method to do whatever we want. This function takes an event and checks if the event was produced by hitting your keyboard's Enterkey. If thatβs true, it retrieves the event's value and appends it to the list of tasks."
},
{
"code": null,
"e": 3102,
"s": 2753,
"text": "To store the tasks that the user creates, we append their name in a separate tasks Python list, alongside a simple delete button. The delete button, when pressed, calls the remove_task() function, which updates the state just like the add_new_task() function. However, instead of adding a new item to the current state, it removes the selected one."
},
{
"code": null,
"e": 3254,
"s": 3102,
"text": "Finally, we create an input element to create TODO tasks and an HTML table element to hold them. In the last step, we render them using a div HTML tag."
},
{
"code": null,
"e": 3461,
"s": 3254,
"text": "So far, so good. However, the power that IDOM gives us is not limited to displaying HTML elements. The real power of IDOM comes from its ability to install and use any React ecosystem components seamlessly."
},
{
"code": null,
"e": 3613,
"s": 3461,
"text": "In this example, let's use victory, a set of React components for modular charting and data visualization. To install victory, we can use the IDOM CLI:"
},
{
"code": null,
"e": 3635,
"s": 3613,
"text": "!idom install victory"
},
{
"code": null,
"e": 3667,
"s": 3635,
"text": "Then, letβs use it in our code:"
},
{
"code": null,
"e": 3865,
"s": 3667,
"text": "Congrats! Youβve just created a Pie chart with victory in a Jupyter Notebook! Of course, it is also straightforward to import and use your existing JavaScript modules. See how in the documentation."
},
{
"code": null,
"e": 4030,
"s": 3865,
"text": "Data Scientists use Jupyter widgets to visualize their results or create mini web apps that facilitate navigating through the content or encourage user interaction."
},
{
"code": null,
"e": 4248,
"s": 4030,
"text": "However, IPyWidgets are not always easy to work with. They also have some drawbacks: they do not follow declarative design principles, and the resulting components cannot be transferred as is in a browser environment."
},
{
"code": null,
"e": 4414,
"s": 4248,
"text": "It is time to take the next step; This story examined IDOM: a set of libraries for defining and controlling interactive webpages or create visual Jupyter components."
},
{
"code": null,
"e": 4547,
"s": 4414,
"text": "The IDOM API is described more exhaustively in the documentation. Also, you can play with idom-jupyter on Binder, before installing."
},
{
"code": null,
"e": 4804,
"s": 4547,
"text": "My name is Dimitris Poulopoulos, and Iβm a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA."
}
] |
Fortran - Dynamic Arrays | A dynamic array is an array, the size of which is not known at compile time, but will be known at execution time.
Dynamic arrays are declared with the attribute allocatable.
For example,
real, dimension (:,:), allocatable :: darray
The rank of the array, i.e., the dimensions has to be mentioned however, to allocate memory to such an array, you use the allocate function.
allocate ( darray(s1,s2) )
After the array is used, in the program, the memory created should be freed using the deallocate function
deallocate (darray)
The following example demonstrates the concepts discussed above.
program dynamic_array
implicit none
!rank is 2, but size not known
real, dimension (:,:), allocatable :: darray
integer :: s1, s2
integer :: i, j
print*, "Enter the size of the array:"
read*, s1, s2
! allocate memory
allocate ( darray(s1,s2) )
do i = 1, s1
do j = 1, s2
darray(i,j) = i*j
print*, "darray(",i,",",j,") = ", darray(i,j)
end do
end do
deallocate (darray)
end program dynamic_array
When the above code is compiled and executed, it produces the following result β
Enter the size of the array: 3,4
darray( 1 , 1 ) = 1.00000000
darray( 1 , 2 ) = 2.00000000
darray( 1 , 3 ) = 3.00000000
darray( 1 , 4 ) = 4.00000000
darray( 2 , 1 ) = 2.00000000
darray( 2 , 2 ) = 4.00000000
darray( 2 , 3 ) = 6.00000000
darray( 2 , 4 ) = 8.00000000
darray( 3 , 1 ) = 3.00000000
darray( 3 , 2 ) = 6.00000000
darray( 3 , 3 ) = 9.00000000
darray( 3 , 4 ) = 12.0000000
The data statement can be used for initialising more than one array, or for array section initialisation.
The syntax of data statement is β
data variable / list / ...
The following example demonstrates the concept β
program dataStatement
implicit none
integer :: a(5), b(3,3), c(10),i, j
data a /7,8,9,10,11/
data b(1,:) /1,1,1/
data b(2,:)/2,2,2/
data b(3,:)/3,3,3/
data (c(i),i = 1,10,2) /4,5,6,7,8/
data (c(i),i = 2,10,2)/5*2/
Print *, 'The A array:'
do j = 1, 5
print*, a(j)
end do
Print *, 'The B array:'
do i = lbound(b,1), ubound(b,1)
write(*,*) (b(i,j), j = lbound(b,2), ubound(b,2))
end do
Print *, 'The C array:'
do j = 1, 10
print*, c(j)
end do
end program dataStatement
When the above code is compiled and executed, it produces the following result β
The A array:
7
8
9
10
11
The B array:
1 1 1
2 2 2
3 3 3
The C array:
4
2
5
2
6
2
7
2
8
2
The where statement allows you to use some elements of an array in an expression, depending on the outcome of some logical condition. It allows the execution of the expression, on an element, if the given condition is true.
The following example demonstrates the concept β
program whereStatement
implicit none
integer :: a(3,5), i , j
do i = 1,3
do j = 1, 5
a(i,j) = j-i
end do
end do
Print *, 'The A array:'
do i = lbound(a,1), ubound(a,1)
write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
end do
where( a<0 )
a = 1
elsewhere
a = 5
end where
Print *, 'The A array:'
do i = lbound(a,1), ubound(a,1)
write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
end do
end program whereStatement
When the above code is compiled and executed, it produces the following result β
The A array:
0 1 2 3 4
-1 0 1 2 3
-2 -1 0 1 2
The A array:
5 5 5 5 5
1 5 5 5 5
1 1 5 5 5
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2260,
"s": 2146,
"text": "A dynamic array is an array, the size of which is not known at compile time, but will be known at execution time."
},
{
"code": null,
"e": 2320,
"s": 2260,
"text": "Dynamic arrays are declared with the attribute allocatable."
},
{
"code": null,
"e": 2333,
"s": 2320,
"text": "For example,"
},
{
"code": null,
"e": 2382,
"s": 2333,
"text": "real, dimension (:,:), allocatable :: darray "
},
{
"code": null,
"e": 2523,
"s": 2382,
"text": "The rank of the array, i.e., the dimensions has to be mentioned however, to allocate memory to such an array, you use the allocate function."
},
{
"code": null,
"e": 2556,
"s": 2523,
"text": "allocate ( darray(s1,s2) ) "
},
{
"code": null,
"e": 2662,
"s": 2556,
"text": "After the array is used, in the program, the memory created should be freed using the deallocate function"
},
{
"code": null,
"e": 2684,
"s": 2662,
"text": "deallocate (darray) "
},
{
"code": null,
"e": 2749,
"s": 2684,
"text": "The following example demonstrates the concepts discussed above."
},
{
"code": null,
"e": 3332,
"s": 2749,
"text": "program dynamic_array \nimplicit none \n\n !rank is 2, but size not known \n real, dimension (:,:), allocatable :: darray \n integer :: s1, s2 \n integer :: i, j \n \n print*, \"Enter the size of the array:\" \n read*, s1, s2 \n \n ! allocate memory \n allocate ( darray(s1,s2) ) \n \n do i = 1, s1 \n do j = 1, s2 \n darray(i,j) = i*j \n print*, \"darray(\",i,\",\",j,\") = \", darray(i,j) \n end do \n end do \n \n deallocate (darray) \nend program dynamic_array"
},
{
"code": null,
"e": 3413,
"s": 3332,
"text": "When the above code is compiled and executed, it produces the following result β"
},
{
"code": null,
"e": 3842,
"s": 3413,
"text": "Enter the size of the array: 3,4\ndarray( 1 , 1 ) = 1.00000000 \ndarray( 1 , 2 ) = 2.00000000 \ndarray( 1 , 3 ) = 3.00000000 \ndarray( 1 , 4 ) = 4.00000000 \ndarray( 2 , 1 ) = 2.00000000 \ndarray( 2 , 2 ) = 4.00000000 \ndarray( 2 , 3 ) = 6.00000000 \ndarray( 2 , 4 ) = 8.00000000 \ndarray( 3 , 1 ) = 3.00000000 \ndarray( 3 , 2 ) = 6.00000000 \ndarray( 3 , 3 ) = 9.00000000 \ndarray( 3 , 4 ) = 12.0000000 \n"
},
{
"code": null,
"e": 3948,
"s": 3842,
"text": "The data statement can be used for initialising more than one array, or for array section initialisation."
},
{
"code": null,
"e": 3982,
"s": 3948,
"text": "The syntax of data statement is β"
},
{
"code": null,
"e": 4010,
"s": 3982,
"text": "data variable / list / ...\n"
},
{
"code": null,
"e": 4059,
"s": 4010,
"text": "The following example demonstrates the concept β"
},
{
"code": null,
"e": 4676,
"s": 4059,
"text": "program dataStatement\nimplicit none\n\n integer :: a(5), b(3,3), c(10),i, j\n data a /7,8,9,10,11/ \n \n data b(1,:) /1,1,1/ \n data b(2,:)/2,2,2/ \n data b(3,:)/3,3,3/ \n data (c(i),i = 1,10,2) /4,5,6,7,8/ \n data (c(i),i = 2,10,2)/5*2/\n \n Print *, 'The A array:'\n do j = 1, 5 \n print*, a(j) \n end do \n \n Print *, 'The B array:'\n do i = lbound(b,1), ubound(b,1)\n write(*,*) (b(i,j), j = lbound(b,2), ubound(b,2))\n end do\n\n Print *, 'The C array:' \n do j = 1, 10 \n print*, c(j) \n end do \n \nend program dataStatement"
},
{
"code": null,
"e": 4757,
"s": 4676,
"text": "When the above code is compiled and executed, it produces the following result β"
},
{
"code": null,
"e": 5106,
"s": 4757,
"text": " The A array:\n 7\n 8\n 9\n 10\n 11\n The B array:\n 1 1 1\n 2 2 2\n 3 3 3\n The C array:\n 4\n 2\n 5\n 2\n 6\n 2\n 7\n 2\n 8\n 2\n"
},
{
"code": null,
"e": 5330,
"s": 5106,
"text": "The where statement allows you to use some elements of an array in an expression, depending on the outcome of some logical condition. It allows the execution of the expression, on an element, if the given condition is true."
},
{
"code": null,
"e": 5379,
"s": 5330,
"text": "The following example demonstrates the concept β"
},
{
"code": null,
"e": 5926,
"s": 5379,
"text": "program whereStatement\nimplicit none\n\n integer :: a(3,5), i , j\n \n do i = 1,3\n do j = 1, 5 \n a(i,j) = j-i \n end do \n end do\n \n Print *, 'The A array:'\n \n do i = lbound(a,1), ubound(a,1)\n write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))\n end do\n \n where( a<0 ) \n a = 1 \n elsewhere\n a = 5\n end where\n \n Print *, 'The A array:'\n do i = lbound(a,1), ubound(a,1)\n write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))\n end do \n \nend program whereStatement"
},
{
"code": null,
"e": 6007,
"s": 5926,
"text": "When the above code is compiled and executed, it produces the following result β"
},
{
"code": null,
"e": 6402,
"s": 6007,
"text": " The A array:\n 0 1 2 3 4\n -1 0 1 2 3\n -2 -1 0 1 2\n The A array:\n 5 5 5 5 5\n 1 5 5 5 5\n 1 1 5 5 5\n"
},
{
"code": null,
"e": 6409,
"s": 6402,
"text": " Print"
},
{
"code": null,
"e": 6420,
"s": 6409,
"text": " Add Notes"
}
] |
How to stop training a neural-network using callback? | by Supratim Haldar | Towards Data Science | Often, when training a very deep neural network, we want to stop training once the training accuracy reaches a certain desired threshold. Thus, we can achieve what we want (optimal model weights) and avoid wastage of resources (time and computation power).
In this brief tutorial, letβs learn how to achieve this in Tensorflow and Keras, using the callback approach, in 4 simple steps.
# Import tensorflowimport tensorflow as tf
First, set the accuracy threshold till which you want to train your model.
First, set the accuracy threshold till which you want to train your model.
ACCURACY_THRESHOLD = 0.95
2. Now, implement callback class and function to stop training when accuracy reaches ACCURACY_THRESHOLD.
# Implement callback function to stop training# when accuracy reaches e.g. ACCURACY_THRESHOLD = 0.95class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if(logs.get('acc') > ACCURACY_THRESHOLD): print("\nReached %2.2f%% accuracy, so stopping training!!" %(ACCURACY_THRESHOLD*100)) self.model.stop_training = True
What exactly is going on here? We are creating new class by extending tf.keras.callbacks.Callback, and implementing the on_epoch_end() method. This is invoked at the end of each epoch. Next, we are fetching the value of accuracy at the end of that epoch, and if it is greater than our threshold, we are setting the stop_training of model to True.
3. Instantiate an object of myCallback class.
callbacks = myCallback()
Next, build a DNN or Conv-Net model following the normal steps of TensorFlow or Keras. The callback that we have built above will be used while training the model using fit() method.
4. Simply pass an argument as callbacks=[<the newly instantiated object of myCallback class>] to fit() method.
model.fit(x_train, y_train, epochs=20, callbacks=[callbacks])
And thatβs all! While training, as soon as accuracy reaches the value set in ACCURACY_THRESHOLD, training will be stopped.
To tie it all together, hereβs a complete code snippet.
With our imagination this approach can be used in varied creative ways, especially when we want to run quick PoCs to test and validate multiple DNN architectures. What other interesting usages can you think of? Please share your thoughts in the comments section below. | [
{
"code": null,
"e": 429,
"s": 172,
"text": "Often, when training a very deep neural network, we want to stop training once the training accuracy reaches a certain desired threshold. Thus, we can achieve what we want (optimal model weights) and avoid wastage of resources (time and computation power)."
},
{
"code": null,
"e": 558,
"s": 429,
"text": "In this brief tutorial, letβs learn how to achieve this in Tensorflow and Keras, using the callback approach, in 4 simple steps."
},
{
"code": null,
"e": 601,
"s": 558,
"text": "# Import tensorflowimport tensorflow as tf"
},
{
"code": null,
"e": 676,
"s": 601,
"text": "First, set the accuracy threshold till which you want to train your model."
},
{
"code": null,
"e": 751,
"s": 676,
"text": "First, set the accuracy threshold till which you want to train your model."
},
{
"code": null,
"e": 777,
"s": 751,
"text": "ACCURACY_THRESHOLD = 0.95"
},
{
"code": null,
"e": 882,
"s": 777,
"text": "2. Now, implement callback class and function to stop training when accuracy reaches ACCURACY_THRESHOLD."
},
{
"code": null,
"e": 1261,
"s": 882,
"text": "# Implement callback function to stop training# when accuracy reaches e.g. ACCURACY_THRESHOLD = 0.95class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if(logs.get('acc') > ACCURACY_THRESHOLD): print(\"\\nReached %2.2f%% accuracy, so stopping training!!\" %(ACCURACY_THRESHOLD*100)) self.model.stop_training = True"
},
{
"code": null,
"e": 1608,
"s": 1261,
"text": "What exactly is going on here? We are creating new class by extending tf.keras.callbacks.Callback, and implementing the on_epoch_end() method. This is invoked at the end of each epoch. Next, we are fetching the value of accuracy at the end of that epoch, and if it is greater than our threshold, we are setting the stop_training of model to True."
},
{
"code": null,
"e": 1654,
"s": 1608,
"text": "3. Instantiate an object of myCallback class."
},
{
"code": null,
"e": 1679,
"s": 1654,
"text": "callbacks = myCallback()"
},
{
"code": null,
"e": 1862,
"s": 1679,
"text": "Next, build a DNN or Conv-Net model following the normal steps of TensorFlow or Keras. The callback that we have built above will be used while training the model using fit() method."
},
{
"code": null,
"e": 1973,
"s": 1862,
"text": "4. Simply pass an argument as callbacks=[<the newly instantiated object of myCallback class>] to fit() method."
},
{
"code": null,
"e": 2035,
"s": 1973,
"text": "model.fit(x_train, y_train, epochs=20, callbacks=[callbacks])"
},
{
"code": null,
"e": 2158,
"s": 2035,
"text": "And thatβs all! While training, as soon as accuracy reaches the value set in ACCURACY_THRESHOLD, training will be stopped."
},
{
"code": null,
"e": 2214,
"s": 2158,
"text": "To tie it all together, hereβs a complete code snippet."
}
] |
Installing a Python Based Machine Learning Environment in Windows 10 | by Frank Ceballos | Towards Data Science | Purpose: To install a Python based environment for machine learning.
The following set of instructions were compiled from across the web and written for a Windows 10 OS. Last tested on 02/09/2019.
When I first got into machine learning it took me a few hours to figure how to properly set my Python environment. Out of frustration, I decided to write this post to help anyone going through the process. We will start by installing Anaconda Navigator which will allow us to create independent environments, this will come really handy. Additionally, with Anaconda we can easily install compatible Python modules with very simple commands. Finally, we can use Anaconda to get Spyder β a scientific Python development environment. If you follow the step-by-step procedure shown below, you will have installed Tensorflow, Keras, and Scikit-learn in no time.
In order to start building your machine learning (ML) models with Python, we will start by installing Anaconda Navigator. Anaconda provides an efficient and easy way to install Python modules on your machine. So letβs get started.
Download and install the latest version of Anaconda Navigator for your operating system.
Download and install the latest version of Anaconda Navigator for your operating system.
2. Proceed with the installation wizard but skip the step where you need to download and install VS, we will do this later. Additionally, make sure to install Anaconda Navigator for a single user β installing Anaconda for All Users might lead to problems. For example, you wonβt be able to install any modules because Anaconda wonβt have the necessary privileges.
3. Launch Anaconda Navigator and select the Home Tab, it should be selected by default. Find the VS Code Panel and click on the Install button. This will take a minute or two.
Now that we have installed Anaconda, letβs get Keras and Tensorflow in our machine.
4. Close Anaconda Navigator and launch Anaconda Prompt. Launch Anaconda prompt by searching for it in the windows search bar. The following terminal should open. Notice that this will open on the base Anaconda environment.
5. Downgrade Python to a Keras & Tensorflow compatible version. Anaconda will start to look for all the compatible modules for Python 3.6. This might take a few minutes. To downgrade to Python 3.6 use the following command:
conda install python=3.6
6. Create a new conda environment where we will install our modules to built our models using the GPU. To do so, execute the following command:
conda create --name PythonGPU
Note: Ensure that you have a NVIDIA graphics card. If you donβt, install the CPU version of Keras.
If you want to use your CPU instead, execute the following command:
conda create --name PythonCPU
Follow the instructions displayed on the terminal. Conda environments give the user the liberty to install very specific modules that are independent habitats. Personally, I created two environments. One where I can built my models using the CPU and the other where I can built my models using the GPU. For more information about conda environments, I suggest you take a look at the official documentation.
7. To activate the conda environment that was just created use:
activate PythonGPU or activate PythonCPU
To deactivate the environment use:
conda deactivate
Do not deactivate the environment yet, we are about to install all the good stuff.
8. To install Keras & Tensorflow GPU versions, the modules that are necessary to create our models with our GPU, execute the following command:
conda install -c anaconda keras-gpu
If you want to use your CPU to built models, execute the following command instead:
conda install -c anaconda keras
A lot of computer stuff will start happening. Once the madness stops, we can move on. Donβt close anything yet.
Now you might want some piece of software to write and execute your Python scrips. You can always use Vim to write and edit your Python scrips and have another terminal open to execute them. However, you will be missing out on all the cool features Spyder haves to offer.
9. Install Spyder.
conda install spyder
10. Install Pandas. Pandas is a library that is extremely powerful and allows you to easily read, manipulate, and visualize data.
conda install -c anaconda pandas
If you want to read Excel files with Pandas, execute the following commands:
conda install -c anaconda xlrd
conda install -c anaconda xlwt
11. Install the Seaborn library. Seaborn is an amazing library that allows you to easily visualize your data.
conda install -c anaconda seaborn
12. To install scikit-learn.
conda install -c anaconda scikit-learn
13. Install Pillow to handle images
conda install pillow
By now you should feel comfortable installing modules using the conda command. If you need a specific module, simply Google something along the following lines:
Anaconda LibraryNameYouWant Install
If you encounter any problems search the web. Is most likely that youβre not the first person to encounter a given error.
To launch Spyder, first activate the conda environment you want (PythonCPU or PythonGPU) and execute the following command:
spyder
To ensure everything was installed correctly, execute the following lines of code on the python console:
import numpy as np # For numerical fast numerical calculationsimport matplotlib.pyplot as plt # For making plotsimport pandas as pd # Deals with dataimport seaborn as sns # Makes beautiful plotsfrom sklearn.preprocessing import StandardScaler # Testing sklearnimport tensorflow # Imports tensorflowimport keras # Imports keras
If you see no ModuleImport errors, youβre now ready to start building machine learning based models using Keras, Tensorflow, and Scikit-Learn.
You can find me in LinkedIn or visit my personal blog. | [
{
"code": null,
"e": 241,
"s": 172,
"text": "Purpose: To install a Python based environment for machine learning."
},
{
"code": null,
"e": 369,
"s": 241,
"text": "The following set of instructions were compiled from across the web and written for a Windows 10 OS. Last tested on 02/09/2019."
},
{
"code": null,
"e": 1026,
"s": 369,
"text": "When I first got into machine learning it took me a few hours to figure how to properly set my Python environment. Out of frustration, I decided to write this post to help anyone going through the process. We will start by installing Anaconda Navigator which will allow us to create independent environments, this will come really handy. Additionally, with Anaconda we can easily install compatible Python modules with very simple commands. Finally, we can use Anaconda to get Spyder β a scientific Python development environment. If you follow the step-by-step procedure shown below, you will have installed Tensorflow, Keras, and Scikit-learn in no time."
},
{
"code": null,
"e": 1257,
"s": 1026,
"text": "In order to start building your machine learning (ML) models with Python, we will start by installing Anaconda Navigator. Anaconda provides an efficient and easy way to install Python modules on your machine. So letβs get started."
},
{
"code": null,
"e": 1346,
"s": 1257,
"text": "Download and install the latest version of Anaconda Navigator for your operating system."
},
{
"code": null,
"e": 1435,
"s": 1346,
"text": "Download and install the latest version of Anaconda Navigator for your operating system."
},
{
"code": null,
"e": 1799,
"s": 1435,
"text": "2. Proceed with the installation wizard but skip the step where you need to download and install VS, we will do this later. Additionally, make sure to install Anaconda Navigator for a single user β installing Anaconda for All Users might lead to problems. For example, you wonβt be able to install any modules because Anaconda wonβt have the necessary privileges."
},
{
"code": null,
"e": 1975,
"s": 1799,
"text": "3. Launch Anaconda Navigator and select the Home Tab, it should be selected by default. Find the VS Code Panel and click on the Install button. This will take a minute or two."
},
{
"code": null,
"e": 2059,
"s": 1975,
"text": "Now that we have installed Anaconda, letβs get Keras and Tensorflow in our machine."
},
{
"code": null,
"e": 2282,
"s": 2059,
"text": "4. Close Anaconda Navigator and launch Anaconda Prompt. Launch Anaconda prompt by searching for it in the windows search bar. The following terminal should open. Notice that this will open on the base Anaconda environment."
},
{
"code": null,
"e": 2506,
"s": 2282,
"text": "5. Downgrade Python to a Keras & Tensorflow compatible version. Anaconda will start to look for all the compatible modules for Python 3.6. This might take a few minutes. To downgrade to Python 3.6 use the following command:"
},
{
"code": null,
"e": 2531,
"s": 2506,
"text": "conda install python=3.6"
},
{
"code": null,
"e": 2675,
"s": 2531,
"text": "6. Create a new conda environment where we will install our modules to built our models using the GPU. To do so, execute the following command:"
},
{
"code": null,
"e": 2705,
"s": 2675,
"text": "conda create --name PythonGPU"
},
{
"code": null,
"e": 2804,
"s": 2705,
"text": "Note: Ensure that you have a NVIDIA graphics card. If you donβt, install the CPU version of Keras."
},
{
"code": null,
"e": 2872,
"s": 2804,
"text": "If you want to use your CPU instead, execute the following command:"
},
{
"code": null,
"e": 2902,
"s": 2872,
"text": "conda create --name PythonCPU"
},
{
"code": null,
"e": 3309,
"s": 2902,
"text": "Follow the instructions displayed on the terminal. Conda environments give the user the liberty to install very specific modules that are independent habitats. Personally, I created two environments. One where I can built my models using the CPU and the other where I can built my models using the GPU. For more information about conda environments, I suggest you take a look at the official documentation."
},
{
"code": null,
"e": 3373,
"s": 3309,
"text": "7. To activate the conda environment that was just created use:"
},
{
"code": null,
"e": 3414,
"s": 3373,
"text": "activate PythonGPU or activate PythonCPU"
},
{
"code": null,
"e": 3449,
"s": 3414,
"text": "To deactivate the environment use:"
},
{
"code": null,
"e": 3466,
"s": 3449,
"text": "conda deactivate"
},
{
"code": null,
"e": 3549,
"s": 3466,
"text": "Do not deactivate the environment yet, we are about to install all the good stuff."
},
{
"code": null,
"e": 3693,
"s": 3549,
"text": "8. To install Keras & Tensorflow GPU versions, the modules that are necessary to create our models with our GPU, execute the following command:"
},
{
"code": null,
"e": 3729,
"s": 3693,
"text": "conda install -c anaconda keras-gpu"
},
{
"code": null,
"e": 3813,
"s": 3729,
"text": "If you want to use your CPU to built models, execute the following command instead:"
},
{
"code": null,
"e": 3845,
"s": 3813,
"text": "conda install -c anaconda keras"
},
{
"code": null,
"e": 3957,
"s": 3845,
"text": "A lot of computer stuff will start happening. Once the madness stops, we can move on. Donβt close anything yet."
},
{
"code": null,
"e": 4229,
"s": 3957,
"text": "Now you might want some piece of software to write and execute your Python scrips. You can always use Vim to write and edit your Python scrips and have another terminal open to execute them. However, you will be missing out on all the cool features Spyder haves to offer."
},
{
"code": null,
"e": 4248,
"s": 4229,
"text": "9. Install Spyder."
},
{
"code": null,
"e": 4269,
"s": 4248,
"text": "conda install spyder"
},
{
"code": null,
"e": 4399,
"s": 4269,
"text": "10. Install Pandas. Pandas is a library that is extremely powerful and allows you to easily read, manipulate, and visualize data."
},
{
"code": null,
"e": 4432,
"s": 4399,
"text": "conda install -c anaconda pandas"
},
{
"code": null,
"e": 4509,
"s": 4432,
"text": "If you want to read Excel files with Pandas, execute the following commands:"
},
{
"code": null,
"e": 4540,
"s": 4509,
"text": "conda install -c anaconda xlrd"
},
{
"code": null,
"e": 4571,
"s": 4540,
"text": "conda install -c anaconda xlwt"
},
{
"code": null,
"e": 4681,
"s": 4571,
"text": "11. Install the Seaborn library. Seaborn is an amazing library that allows you to easily visualize your data."
},
{
"code": null,
"e": 4715,
"s": 4681,
"text": "conda install -c anaconda seaborn"
},
{
"code": null,
"e": 4744,
"s": 4715,
"text": "12. To install scikit-learn."
},
{
"code": null,
"e": 4783,
"s": 4744,
"text": "conda install -c anaconda scikit-learn"
},
{
"code": null,
"e": 4819,
"s": 4783,
"text": "13. Install Pillow to handle images"
},
{
"code": null,
"e": 4840,
"s": 4819,
"text": "conda install pillow"
},
{
"code": null,
"e": 5001,
"s": 4840,
"text": "By now you should feel comfortable installing modules using the conda command. If you need a specific module, simply Google something along the following lines:"
},
{
"code": null,
"e": 5037,
"s": 5001,
"text": "Anaconda LibraryNameYouWant Install"
},
{
"code": null,
"e": 5159,
"s": 5037,
"text": "If you encounter any problems search the web. Is most likely that youβre not the first person to encounter a given error."
},
{
"code": null,
"e": 5283,
"s": 5159,
"text": "To launch Spyder, first activate the conda environment you want (PythonCPU or PythonGPU) and execute the following command:"
},
{
"code": null,
"e": 5290,
"s": 5283,
"text": "spyder"
},
{
"code": null,
"e": 5395,
"s": 5290,
"text": "To ensure everything was installed correctly, execute the following lines of code on the python console:"
},
{
"code": null,
"e": 5722,
"s": 5395,
"text": "import numpy as np # For numerical fast numerical calculationsimport matplotlib.pyplot as plt # For making plotsimport pandas as pd # Deals with dataimport seaborn as sns # Makes beautiful plotsfrom sklearn.preprocessing import StandardScaler # Testing sklearnimport tensorflow # Imports tensorflowimport keras # Imports keras"
},
{
"code": null,
"e": 5865,
"s": 5722,
"text": "If you see no ModuleImport errors, youβre now ready to start building machine learning based models using Keras, Tensorflow, and Scikit-Learn."
}
] |
How to read all the coming notifications in android? | This example demonstrate about How to read all the coming notifications in android
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to src/MyListener.java
public interface MyListener {
void setValue (String packageName) ;
}
Step 3 β Add the following code to src/MyListener.java
package app.tutorialspoint.com.notifyme ;
import android.content.Context ;
import android.service.notification.NotificationListenerService ;
import android.service.notification.StatusBarNotification ;
import android.util.Log ;
public class NotificationService extends NotificationListenerService {
private String TAG = this .getClass().getSimpleName() ;
Context context ;
static MyListener myListener ;
@Override
public void onCreate () {
super .onCreate() ;
context = getApplicationContext() ;
}
@Override
public void onNotificationPosted (StatusBarNotification sbn) {
Log. i ( TAG , "********** onNotificationPosted" ) ;
Log. i ( TAG , "ID :" + sbn.getId() + " \t " + sbn.getNotification(). tickerText + " \t " + sbn.getPackageName()) ;
myListener .setValue( "Post: " + sbn.getPackageName()) ;
}
@Override
public void onNotificationRemoved (StatusBarNotification sbn) {
Log. i ( TAG , "********** onNotificationRemoved" ) ;
Log. i ( TAG , "ID :" + sbn.getId() + " \t " + sbn.getNotification(). tickerText + " \t " + sbn.getPackageName()) ;
myListener .setValue( "Remove: " + sbn.getPackageName()) ;
}
public void setListener (MyListener myListener) {
NotificationService. myListener = myListener ;
}
}
Step 4 β Add the following code to res/menu/menu_main.xml.
<?xml version = "1.0" encoding = "utf-8" ?>
<menu 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"
tools :context = ".MainActivity" >
<item
android :id = "@+id/action_settings"
android :orderInCategory = "100"
android :title = "Settings"
app :showAsAction = "never" />
</menu>
Step 5 β Add the following code to res/layout/activity_main.xml.
<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width = "match_parent"
android :layout_height = "match_parent"
android :padding = "16dp"
tools :context = ".MainActivity" >
<Button
android :id = "@+id/btnCreateNotification"
android :layout_width = "wrap_content"
android :layout_height = "wrap_content"
android :layout_alignParentStart = "true"
android :layout_alignParentTop = "true"
android :layout_alignParentEnd = "true"
android :text = "Create Notification" />
<ScrollView
android :layout_width = "match_parent"
android :layout_height = "match_parent"
android :layout_below = "@+id/btnCreateNotification"
android :layout_alignStart = "@+id/btnCreateNotification"
android :layout_alignEnd = "@+id/btnCreateNotification"
android :layout_alignParentBottom = "true" >
<TextView
android :id = "@+id/textView"
android :layout_width = "match_parent"
android :layout_height = "wrap_content"
android :text = "NotificationListenerService Example"
android :textAppearance = "?android:attr/textAppearanceMedium" />
</ScrollView>
</RelativeLayout>
Step 6 β Add the following code to src/MainActivity.java
package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.content.Intent ;
import android.os.Bundle ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.view.Menu ;
import android.view.MenuItem ;
import android.view.View ;
import android.widget.Button ;
import android.widget.TextView ;
public class MainActivity extends AppCompatActivity implements MyListener {
private TextView txtView ;
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
new NotificationService().setListener( this ) ;
txtView = findViewById(R.id. textView ) ;
Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ;
btnCreateNotification.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick (View v) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;
mBuilder.setContentTitle( "My Notification" ) ;
mBuilder.setContentText( "Notification Listener Service Example" ) ;
mBuilder.setTicker( "Notification Listener Service Example" ) ;
mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
mBuilder.setAutoCancel( true ) ;
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel) ;
}
assert mNotificationManager != null;
mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;
}
}) ;
}
@Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu. menu_main , menu) ; //Menu Resource, Menu
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item) {
switch (item.getItemId()) {
case R.id. action_settings :
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS" ) ;
startActivity(intent) ;
return true;
default :
return super .onOptionsItemSelected(item) ;
}
}
@Override
public void setValue (String packageName) {
txtView .append( " \n " + packageName) ;
}
}
Step 7 β Add the following code to AndroidManifest.xml
<? xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package = "app.tutorialspoint.com.notifyme" >
<uses-permission android :name = "android.permission.VIBRATE" />
<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>
<service
android :name = ".NotificationService"
android :label = "@string/app_name"
android :permission = "android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
<intent-filter>
<action
android :name = "android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</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 | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "This example demonstrate about How to read all the coming notifications in android"
},
{
"code": null,
"e": 1274,
"s": 1145,
"text": "Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1329,
"s": 1274,
"text": "Step 2 β Add the following code to src/MyListener.java"
},
{
"code": null,
"e": 1401,
"s": 1329,
"text": "public interface MyListener {\n void setValue (String packageName) ;\n}"
},
{
"code": null,
"e": 1456,
"s": 1401,
"text": "Step 3 β Add the following code to src/MyListener.java"
},
{
"code": null,
"e": 2756,
"s": 1456,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.content.Context ;\nimport android.service.notification.NotificationListenerService ;\nimport android.service.notification.StatusBarNotification ;\nimport android.util.Log ;\npublic class NotificationService extends NotificationListenerService {\n private String TAG = this .getClass().getSimpleName() ;\n Context context ;\n static MyListener myListener ;\n @Override\n public void onCreate () {\n super .onCreate() ;\n context = getApplicationContext() ;\n }\n @Override\n public void onNotificationPosted (StatusBarNotification sbn) {\n Log. i ( TAG , \"********** onNotificationPosted\" ) ;\n Log. i ( TAG , \"ID :\" + sbn.getId() + \" \\t \" + sbn.getNotification(). tickerText + \" \\t \" + sbn.getPackageName()) ;\n myListener .setValue( \"Post: \" + sbn.getPackageName()) ;\n }\n @Override\n public void onNotificationRemoved (StatusBarNotification sbn) {\n Log. i ( TAG , \"********** onNotificationRemoved\" ) ;\n Log. i ( TAG , \"ID :\" + sbn.getId() + \" \\t \" + sbn.getNotification(). tickerText + \" \\t \" + sbn.getPackageName()) ;\n myListener .setValue( \"Remove: \" + sbn.getPackageName()) ;\n }\n public void setListener (MyListener myListener) {\n NotificationService. myListener = myListener ;\n }\n}"
},
{
"code": null,
"e": 2815,
"s": 2756,
"text": "Step 4 β Add the following code to res/menu/menu_main.xml."
},
{
"code": null,
"e": 3246,
"s": 2815,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?>\n<menu xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: app = \"http://schemas.android.com/apk/res-auto\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n tools :context = \".MainActivity\" >\n <item\n android :id = \"@+id/action_settings\"\n android :orderInCategory = \"100\"\n android :title = \"Settings\"\n app :showAsAction = \"never\" />\n</menu>"
},
{
"code": null,
"e": 3311,
"s": 3246,
"text": "Step 5 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 4644,
"s": 3311,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :padding = \"16dp\"\n tools :context = \".MainActivity\" >\n <Button\n android :id = \"@+id/btnCreateNotification\"\n android :layout_width = \"wrap_content\"\n android :layout_height = \"wrap_content\"\n android :layout_alignParentStart = \"true\"\n android :layout_alignParentTop = \"true\"\n android :layout_alignParentEnd = \"true\"\n android :text = \"Create Notification\" />\n <ScrollView\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :layout_below = \"@+id/btnCreateNotification\"\n android :layout_alignStart = \"@+id/btnCreateNotification\"\n android :layout_alignEnd = \"@+id/btnCreateNotification\"\n android :layout_alignParentBottom = \"true\" >\n <TextView\n android :id = \"@+id/textView\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :text = \"NotificationListenerService Example\"\n android :textAppearance = \"?android:attr/textAppearanceMedium\" />\n </ScrollView>\n</RelativeLayout>"
},
{
"code": null,
"e": 4701,
"s": 4644,
"text": "Step 6 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 7841,
"s": 4701,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.Menu ;\nimport android.view.MenuItem ;\nimport android.view.View ;\nimport android.widget.Button ;\nimport android.widget.TextView ;\npublic class MainActivity extends AppCompatActivity implements MyListener {\n private TextView txtView ;\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n new NotificationService().setListener( this ) ;\n txtView = findViewById(R.id. textView ) ;\n Button btnCreateNotification = findViewById(R.id. btnCreateNotification ) ;\n btnCreateNotification.setOnClickListener( new View.OnClickListener() {\n @Override\n public void onClick (View v) {\n NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"My Notification\" ) ;\n mBuilder.setContentText( \"Notification Listener Service Example\" ) ;\n mBuilder.setTicker( \"Notification Listener Service Example\" ) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;\n }\n }) ;\n }\n @Override\n public boolean onCreateOptionsMenu (Menu menu) {\n getMenuInflater().inflate(R.menu. menu_main , menu) ; //Menu Resource, Menu\n return true;\n }\n @Override\n public boolean onOptionsItemSelected (MenuItem item) {\n switch (item.getItemId()) {\n case R.id. action_settings :\n Intent intent = new Intent(\"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS\" ) ;\n startActivity(intent) ;\n return true;\n default :\n return super .onOptionsItemSelected(item) ;\n }\n }\n @Override\n public void setValue (String packageName) {\n txtView .append( \" \\n \" + packageName) ;\n }\n}"
},
{
"code": null,
"e": 7896,
"s": 7841,
"text": "Step 7 β Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 9073,
"s": 7896,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\n <application\n android :allowBackup = \"true\"\n android :icon = \"@mipmap/ic_launcher\"\n android :label = \"@string/app_name\"\n android :roundIcon = \"@mipmap/ic_launcher_round\"\n android :supportsRtl = \"true\"\n android :theme = \"@style/AppTheme\" >\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service\n android :name = \".NotificationService\"\n android :label = \"@string/app_name\"\n android :permission = \"android.permission.BIND_NOTIFICATION_LISTENER_SERVICE\" >\n <intent-filter>\n <action\n android :name = \"android.service.notification.NotificationListenerService\" />\n </intent-filter>\n </service>\n </application>\n</manifest>"
},
{
"code": null,
"e": 9420,
"s": 9073,
"text": "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 β"
},
{
"code": null,
"e": 9462,
"s": 9420,
"text": "Click here to download the project code"
}
] |
CSS | Combine background image with gradient overlay - GeeksforGeeks | 19 Feb, 2020
CSS gradients allow us to display smooth transitions between two or more colors. They can be added on top of the background image by simply combining background-image url and gradient properties.Syntax:
For linear-gradient on top of the Background Image:element {
background-image: linear-gradient(direction,
color-stop1, color-stop2, ...), url('url');
}
element {
background-image: linear-gradient(direction,
color-stop1, color-stop2, ...), url('url');
}
For radial-gradient on top of the Background Image:element {
background-image: radial-gradient(direction,
color-stop1, color-stop2, ...), url('url');
}
element {
background-image: radial-gradient(direction,
color-stop1, color-stop2, ...), url('url');
}
Below examples illustrate the above approach:Example 1: Background image with Linear gradient.
<!DOCTYPE html><html lang="en"> <head> <title>Background Image with Gradient</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <style> .my_bg { background-image: linear-gradient(45deg, rgba( 145, 146, 122, 0.62), rgba( 217, 91, 132, 0.58)), url('https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png'); width: 100%; height: 280px; text-align: center; } </style></head> <body> <div class="my_bg"> This is my background! </div></body> </html>
Output:
Example 2: Background image with Radial gradient.
<!DOCTYPE html><html lang="en"> <head> <title>Background Image with Gradient</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <style> .my_bg { background-image: radial-gradient(rgba( 145, 146, 122, 0.62), rgba(217, 91, 132, 0.58)), url('https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png'); width: 100%; height: 200px; text-align: center; } </style></head> <body> <div class="my_bg"> This is my background! </div></body> </html>
Output:
CSS-Misc
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of CSS (Cascading Style Sheet)
How to create footer to stay at the bottom of a Web page?
Design a web page using HTML and CSS
How to Upload Image into Database and Display it using PHP ?
Create a Responsive Navbar using ReactJS
Express.js express.Router() Function
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 25011,
"s": 24983,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 25214,
"s": 25011,
"text": "CSS gradients allow us to display smooth transitions between two or more colors. They can be added on top of the background image by simply combining background-image url and gradient properties.Syntax:"
},
{
"code": null,
"e": 25376,
"s": 25214,
"text": "For linear-gradient on top of the Background Image:element {\n background-image: linear-gradient(direction, \n color-stop1, color-stop2, ...), url('url');\n}"
},
{
"code": null,
"e": 25487,
"s": 25376,
"text": "element {\n background-image: linear-gradient(direction, \n color-stop1, color-stop2, ...), url('url');\n}"
},
{
"code": null,
"e": 25648,
"s": 25487,
"text": "For radial-gradient on top of the Background Image:element {\n background-image: radial-gradient(direction, \n color-stop1, color-stop2, ...), url('url');\n}"
},
{
"code": null,
"e": 25758,
"s": 25648,
"text": "element {\n background-image: radial-gradient(direction, \n color-stop1, color-stop2, ...), url('url');\n}"
},
{
"code": null,
"e": 25853,
"s": 25758,
"text": "Below examples illustrate the above approach:Example 1: Background image with Linear gradient."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Background Image with Gradient</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <style> .my_bg { background-image: linear-gradient(45deg, rgba( 145, 146, 122, 0.62), rgba( 217, 91, 132, 0.58)), url('https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png'); width: 100%; height: 280px; text-align: center; } </style></head> <body> <div class=\"my_bg\"> This is my background! </div></body> </html>",
"e": 26631,
"s": 25853,
"text": null
},
{
"code": null,
"e": 26639,
"s": 26631,
"text": "Output:"
},
{
"code": null,
"e": 26689,
"s": 26639,
"text": "Example 2: Background image with Radial gradient."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Background Image with Gradient</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <style> .my_bg { background-image: radial-gradient(rgba( 145, 146, 122, 0.62), rgba(217, 91, 132, 0.58)), url('https://media.geeksforgeeks.org/wp-content/uploads/20200120152724/gfg_icon.png'); width: 100%; height: 200px; text-align: center; } </style></head> <body> <div class=\"my_bg\"> This is my background! </div></body> </html>",
"e": 27423,
"s": 26689,
"text": null
},
{
"code": null,
"e": 27431,
"s": 27423,
"text": "Output:"
},
{
"code": null,
"e": 27440,
"s": 27431,
"text": "CSS-Misc"
},
{
"code": null,
"e": 27447,
"s": 27440,
"text": "Picked"
},
{
"code": null,
"e": 27451,
"s": 27447,
"text": "CSS"
},
{
"code": null,
"e": 27468,
"s": 27451,
"text": "Web Technologies"
},
{
"code": null,
"e": 27566,
"s": 27468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27575,
"s": 27566,
"text": "Comments"
},
{
"code": null,
"e": 27588,
"s": 27575,
"text": "Old Comments"
},
{
"code": null,
"e": 27625,
"s": 27588,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27683,
"s": 27625,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27720,
"s": 27683,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27781,
"s": 27720,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 27822,
"s": 27781,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 27859,
"s": 27822,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 27892,
"s": 27859,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27935,
"s": 27892,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27996,
"s": 27935,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
11 Practical Tips You Need to Know to Personalize Jupyter Notebook | by Rizky Maulana N | Towards Data Science | Are you a python programmer who is using Jupyter Notebook as your compiler? If you want to try a new taste in running your python code in Jupyter Notebook (hereafter; Jupyter), you can change and personalize it by your favorite color, font family. You can apply 11 practical tips I recommend to build your Jupyter user interface.
The default Jupyter you might see when you open it is shown in Figure 1.
At the end of this story, I will personalize my Jupyter into my themes, as shown in Figure 2.
This story is the follow-up story for applying the landing page into Jupyter. I reuse some codes in that story and give some additional CSS customization from Rodrigo Silveiraβs story. He builds unique Jupyter themes using CSS. I try to explain the meaning of each CSS code I use.
To customize it using CSS, you need to check a file named custom.css in the directory ~/.jupyter/custom. If you have it, you can add some CSS code to it. But, if you have not had it, you need to create the file in the mentioned directory. If the directory is not available, you need to create the directory. You can see the file I mentioned in Figure 3.
The directory I mean is in Linux. If you use a different OS, you need to find the directory for whom Jupyter is installed. For Windows users, I think it is in the following directory.
C:\Users\YourUsername\Anaconda3\Lib\site-packages\notebook\static\custom\custom.css
But, I have not checked it.
When you open Jupyter, you will be directed to the default Jupyter home page, http://localhost:8888/tree. The interface of the default home page is shown in Figure 4.
To customize the title of the Jupyter home page, you need to add this code in custom.css file
#ipython_notebook::before{ content:"Welcome to my Jupyter Notebook"}#ipython_notebook img{ display:none;}
After adding the code above, you need to save the file and refresh your Jupyter page. The interface after you refresh it is shown in Figure 5.
The title page is changed from the Jupyter logo to the text βWelcome to my Jupyter Notebook.β You are free to change the text by writing down your desired title in the custom.css file. The update custom.css file is shown in Figure 6.
You can change the font used in Jupyter, including title font, toolbar font, and cell font. To change the title font, you need to define what font you use, as shown in the following CSS
#ipython_notebook::before{ content:"Welcome to my Jupyter Notebook"; font-family: Verdana; font-weight: 700; color: orange;}
I change the title default font to Verdana with a weight of 700, and the color is orange. If you add the CSS above in custom.css, save it, and refresh the Jupyter page, you will see the updated interface of your Jupyter, as shown in Figure 7.
If you want to change the font used in the body, you can add this CSS
@import url(https://fonts.googleapis.com/css?family=Open+Sans);body{ font-family: 'Open Sans'; font-weight: 600;}
I change the body font to Open Sans. Firstly, I need to import it from font.googleapis.com. You can also change the weight using a similar CSS with the previous one. The updated interface is shown in Figure 8.
If you want to import the font from a file you have, you can use this CSS
@font-face { font-family: roboto-regular; src: url('../font/Roboto-Regular.ttf'); }
Here is the CSS to change the Jupyterβs interface as shown in Figure 8.
#ipython_notebook::before{ content:"Welcome to my Jupyter Notebook"; font-family: Verdana; font-weight: 700; color: orange;}#ipython_notebook img{ display:none;}@import url(https://fonts.googleapis.com/css?family=Open+Sans);body{ font-family: 'Open Sans'; font-weight: 600;}
I love font Lato, so I use it for my Jupyter themes. I use Verdana (serif) to make it different from the default font (sans-serif).
You can change the Jupyterβs title with your logo. In this story, I will use my favorite logo, as shown in Figure 9.
To apply it into Jupyter page, you can use this CSS
#ipython_notebook img{ display:block; background: url("logo.png") no-repeat; background-size: contain; width: 100px; height: 30px; padding-left: 100px; padding-right: 50px; -moz-box-sizing: border-box; box-sizing: border-box;}
I place my logo in a similar directory of custom.css, so I declare my logo name, logo.png. You can change the width, height, and other CSS to place your logo precisely. The result is shown in Figure 10.
If you check the python page, you will see the updated interface, as shown in Figure 11.
If you change all of the fonts into Verdana with 700 values in width, you can see the difference, as shown in Figure 12.
Now, we are focusing on how to customize the interface of the Python page in Jupyter. I want to change all elements above the body elementβs background color to have a similar color with my logo background (blue, in the hex color index of #78abd2). I use this CSS to change it
body > #header { background: #78abd2;}
You can see the result in Figure 13.
Next is change the background color of the Navigation bar (File, Edit, View, etc.). To change it, you can use the following CSS.
#notebook_name { font-weight: 500; color: white;}
With the CSS above, I change the font color into white and make it bolder. The result is shown in Figure 14.
Then, I will change the font color of Last Checkpoint using this CSS
.checkpoint_status,.autosave_status { color: white;}
The result is shown in Figure 15.
Next is change the background color of Navigation bar (File, Edit, View, etc). To change it, you can use the following CSS.
.navbar-default { background: none; border: none;}
I remove the Navigation barβs background color, so it has a similar color with the header background color (blue). I also remove the border of each Navigation option. The result is shown in Figure 16.
Next is change the font color in the Navigation bar and add the animation using this CSS.
.navbar-default .navbar-nav > li > a, #kernel_indicator { color: white; transition: all 0.25s;}
The result is shown in Figure 17.
The animation I mentioned is when you move the cursor into one of the Navigation bar options, for example, file, the color of the file will change into black.
The other animation you can add is showing the underlined for a selected Navigation bar. To add it, you can use this CSS
.navbar-default .navbar-nav > li > a:hover, #kernel_indicator:hover{ border-bottom: 2px solid #fff; color: white;}
The result is shown in Figure 18.
When I move my cursor into Navigate, the animation will show the underline under the Navigate. It will disappear when you click in the other place.
After we customize the header elements, we will customize the body elements. First, I will change the background color of the body element into white color. To change it, you can use this CSS.
.notebook_app { background: white !important;}
The result is shown in Figure 19.
To change the cell width, you can use this CSS
.container { width: 95% !important;}
The result is shown in Figure 20.
Next is hiding the border between cell. To hide it, you can use this CSS
div.input_area { border: none; border-radius: 0; background: #f7f7f7; line-height: 1.5em; margin: 0.5em 0; padding: 0;}#notebook-container{ box-shadow: none !important; background-color: white;}
The result is shown in Figure 21.
You can add the animation so the selected cell will be zoomed-in and have shadow effect. To apply it, you can use the following CSS
div.cell { transition: all 0.25s; border: none; position: relative; top: 0;}div.cell.selected, div.cell.selected.jupyter-soft-selected { border: none; background: transparent; box-shadow: 0 6px 18px #aaa; z-index: 10; top: -10px;}
The result is shown in Figure 22.
By default, the output cell is left-aligned, as shown in Figure 23.
To change it, you can use this CSS
.output { align-items: center;}
The result is shown in Figure 24.
You can customize the background, alignment, and padding of a data frame in Jupyter. The default setting is shown in Figure 25 (after centering the output).
You can use this CSS to customize it.
.dataframe { /* dataframe atau table */ background: white; box-shadow: 0px 1px 2px #bbb;}.dataframe thead th, .dataframe tbody td { text-align: center; padding: 1em;}
I set the background color into white, right-aligned, and adjust the box-shadow and padding. The result is shown in Figure 26.
The last, if you want to remove the line box, you can use this CSS
div.prompt,div.tooltiptext pre { display:none}
The result is shown in Figure 27.
I did not apply this custom to my Jupyter. I let the line cell is visible. If you prefer to hide it, you can use the CSS above.
To conclude, I will share the CSS customization for my Jupyter in the following CSS.
Here is the captured result.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Thatβs all. Thanks for reading this story. Comment and share if you like it. I also recommend you follow my account to get a notification when I post my new story. | [
{
"code": null,
"e": 501,
"s": 171,
"text": "Are you a python programmer who is using Jupyter Notebook as your compiler? If you want to try a new taste in running your python code in Jupyter Notebook (hereafter; Jupyter), you can change and personalize it by your favorite color, font family. You can apply 11 practical tips I recommend to build your Jupyter user interface."
},
{
"code": null,
"e": 574,
"s": 501,
"text": "The default Jupyter you might see when you open it is shown in Figure 1."
},
{
"code": null,
"e": 668,
"s": 574,
"text": "At the end of this story, I will personalize my Jupyter into my themes, as shown in Figure 2."
},
{
"code": null,
"e": 949,
"s": 668,
"text": "This story is the follow-up story for applying the landing page into Jupyter. I reuse some codes in that story and give some additional CSS customization from Rodrigo Silveiraβs story. He builds unique Jupyter themes using CSS. I try to explain the meaning of each CSS code I use."
},
{
"code": null,
"e": 1303,
"s": 949,
"text": "To customize it using CSS, you need to check a file named custom.css in the directory ~/.jupyter/custom. If you have it, you can add some CSS code to it. But, if you have not had it, you need to create the file in the mentioned directory. If the directory is not available, you need to create the directory. You can see the file I mentioned in Figure 3."
},
{
"code": null,
"e": 1487,
"s": 1303,
"text": "The directory I mean is in Linux. If you use a different OS, you need to find the directory for whom Jupyter is installed. For Windows users, I think it is in the following directory."
},
{
"code": null,
"e": 1571,
"s": 1487,
"text": "C:\\Users\\YourUsername\\Anaconda3\\Lib\\site-packages\\notebook\\static\\custom\\custom.css"
},
{
"code": null,
"e": 1599,
"s": 1571,
"text": "But, I have not checked it."
},
{
"code": null,
"e": 1766,
"s": 1599,
"text": "When you open Jupyter, you will be directed to the default Jupyter home page, http://localhost:8888/tree. The interface of the default home page is shown in Figure 4."
},
{
"code": null,
"e": 1860,
"s": 1766,
"text": "To customize the title of the Jupyter home page, you need to add this code in custom.css file"
},
{
"code": null,
"e": 1966,
"s": 1860,
"text": "#ipython_notebook::before{ content:\"Welcome to my Jupyter Notebook\"}#ipython_notebook img{ display:none;}"
},
{
"code": null,
"e": 2109,
"s": 1966,
"text": "After adding the code above, you need to save the file and refresh your Jupyter page. The interface after you refresh it is shown in Figure 5."
},
{
"code": null,
"e": 2343,
"s": 2109,
"text": "The title page is changed from the Jupyter logo to the text βWelcome to my Jupyter Notebook.β You are free to change the text by writing down your desired title in the custom.css file. The update custom.css file is shown in Figure 6."
},
{
"code": null,
"e": 2529,
"s": 2343,
"text": "You can change the font used in Jupyter, including title font, toolbar font, and cell font. To change the title font, you need to define what font you use, as shown in the following CSS"
},
{
"code": null,
"e": 2654,
"s": 2529,
"text": "#ipython_notebook::before{ content:\"Welcome to my Jupyter Notebook\"; font-family: Verdana; font-weight: 700; color: orange;}"
},
{
"code": null,
"e": 2897,
"s": 2654,
"text": "I change the title default font to Verdana with a weight of 700, and the color is orange. If you add the CSS above in custom.css, save it, and refresh the Jupyter page, you will see the updated interface of your Jupyter, as shown in Figure 7."
},
{
"code": null,
"e": 2967,
"s": 2897,
"text": "If you want to change the font used in the body, you can add this CSS"
},
{
"code": null,
"e": 3085,
"s": 2967,
"text": "@import url(https://fonts.googleapis.com/css?family=Open+Sans);body{ font-family: 'Open Sans'; font-weight: 600;}"
},
{
"code": null,
"e": 3295,
"s": 3085,
"text": "I change the body font to Open Sans. Firstly, I need to import it from font.googleapis.com. You can also change the weight using a similar CSS with the previous one. The updated interface is shown in Figure 8."
},
{
"code": null,
"e": 3369,
"s": 3295,
"text": "If you want to import the font from a file you have, you can use this CSS"
},
{
"code": null,
"e": 3457,
"s": 3369,
"text": "@font-face { font-family: roboto-regular; \t\t\t src: url('../font/Roboto-Regular.ttf'); }"
},
{
"code": null,
"e": 3529,
"s": 3457,
"text": "Here is the CSS to change the Jupyterβs interface as shown in Figure 8."
},
{
"code": null,
"e": 3808,
"s": 3529,
"text": "#ipython_notebook::before{ content:\"Welcome to my Jupyter Notebook\"; font-family: Verdana; font-weight: 700; color: orange;}#ipython_notebook img{ display:none;}@import url(https://fonts.googleapis.com/css?family=Open+Sans);body{ font-family: 'Open Sans'; font-weight: 600;}"
},
{
"code": null,
"e": 3940,
"s": 3808,
"text": "I love font Lato, so I use it for my Jupyter themes. I use Verdana (serif) to make it different from the default font (sans-serif)."
},
{
"code": null,
"e": 4057,
"s": 3940,
"text": "You can change the Jupyterβs title with your logo. In this story, I will use my favorite logo, as shown in Figure 9."
},
{
"code": null,
"e": 4109,
"s": 4057,
"text": "To apply it into Jupyter page, you can use this CSS"
},
{
"code": null,
"e": 4452,
"s": 4109,
"text": "#ipython_notebook img{ display:block; background: url(\"logo.png\") no-repeat; background-size: contain; width: 100px; height: 30px; padding-left: 100px; padding-right: 50px; -moz-box-sizing: border-box; box-sizing: border-box;}"
},
{
"code": null,
"e": 4655,
"s": 4452,
"text": "I place my logo in a similar directory of custom.css, so I declare my logo name, logo.png. You can change the width, height, and other CSS to place your logo precisely. The result is shown in Figure 10."
},
{
"code": null,
"e": 4744,
"s": 4655,
"text": "If you check the python page, you will see the updated interface, as shown in Figure 11."
},
{
"code": null,
"e": 4865,
"s": 4744,
"text": "If you change all of the fonts into Verdana with 700 values in width, you can see the difference, as shown in Figure 12."
},
{
"code": null,
"e": 5142,
"s": 4865,
"text": "Now, we are focusing on how to customize the interface of the Python page in Jupyter. I want to change all elements above the body elementβs background color to have a similar color with my logo background (blue, in the hex color index of #78abd2). I use this CSS to change it"
},
{
"code": null,
"e": 5184,
"s": 5142,
"text": "body > #header { background: #78abd2;}"
},
{
"code": null,
"e": 5221,
"s": 5184,
"text": "You can see the result in Figure 13."
},
{
"code": null,
"e": 5350,
"s": 5221,
"text": "Next is change the background color of the Navigation bar (File, Edit, View, etc.). To change it, you can use the following CSS."
},
{
"code": null,
"e": 5406,
"s": 5350,
"text": "#notebook_name { font-weight: 500; color: white;}"
},
{
"code": null,
"e": 5515,
"s": 5406,
"text": "With the CSS above, I change the font color into white and make it bolder. The result is shown in Figure 14."
},
{
"code": null,
"e": 5584,
"s": 5515,
"text": "Then, I will change the font color of Last Checkpoint using this CSS"
},
{
"code": null,
"e": 5640,
"s": 5584,
"text": ".checkpoint_status,.autosave_status { color: white;}"
},
{
"code": null,
"e": 5674,
"s": 5640,
"text": "The result is shown in Figure 15."
},
{
"code": null,
"e": 5798,
"s": 5674,
"text": "Next is change the background color of Navigation bar (File, Edit, View, etc). To change it, you can use the following CSS."
},
{
"code": null,
"e": 5855,
"s": 5798,
"text": ".navbar-default { background: none; border: none;}"
},
{
"code": null,
"e": 6056,
"s": 5855,
"text": "I remove the Navigation barβs background color, so it has a similar color with the header background color (blue). I also remove the border of each Navigation option. The result is shown in Figure 16."
},
{
"code": null,
"e": 6146,
"s": 6056,
"text": "Next is change the font color in the Navigation bar and add the animation using this CSS."
},
{
"code": null,
"e": 6248,
"s": 6146,
"text": ".navbar-default .navbar-nav > li > a, #kernel_indicator { color: white; transition: all 0.25s;}"
},
{
"code": null,
"e": 6282,
"s": 6248,
"text": "The result is shown in Figure 17."
},
{
"code": null,
"e": 6441,
"s": 6282,
"text": "The animation I mentioned is when you move the cursor into one of the Navigation bar options, for example, file, the color of the file will change into black."
},
{
"code": null,
"e": 6562,
"s": 6441,
"text": "The other animation you can add is showing the underlined for a selected Navigation bar. To add it, you can use this CSS"
},
{
"code": null,
"e": 6683,
"s": 6562,
"text": ".navbar-default .navbar-nav > li > a:hover, #kernel_indicator:hover{ border-bottom: 2px solid #fff; color: white;}"
},
{
"code": null,
"e": 6717,
"s": 6683,
"text": "The result is shown in Figure 18."
},
{
"code": null,
"e": 6865,
"s": 6717,
"text": "When I move my cursor into Navigate, the animation will show the underline under the Navigate. It will disappear when you click in the other place."
},
{
"code": null,
"e": 7058,
"s": 6865,
"text": "After we customize the header elements, we will customize the body elements. First, I will change the background color of the body element into white color. To change it, you can use this CSS."
},
{
"code": null,
"e": 7108,
"s": 7058,
"text": ".notebook_app { background: white !important;}"
},
{
"code": null,
"e": 7142,
"s": 7108,
"text": "The result is shown in Figure 19."
},
{
"code": null,
"e": 7189,
"s": 7142,
"text": "To change the cell width, you can use this CSS"
},
{
"code": null,
"e": 7229,
"s": 7189,
"text": ".container { width: 95% !important;}"
},
{
"code": null,
"e": 7263,
"s": 7229,
"text": "The result is shown in Figure 20."
},
{
"code": null,
"e": 7336,
"s": 7263,
"text": "Next is hiding the border between cell. To hide it, you can use this CSS"
},
{
"code": null,
"e": 7555,
"s": 7336,
"text": "div.input_area { border: none; border-radius: 0; background: #f7f7f7; line-height: 1.5em; margin: 0.5em 0; padding: 0;}#notebook-container{ box-shadow: none !important; background-color: white;}"
},
{
"code": null,
"e": 7589,
"s": 7555,
"text": "The result is shown in Figure 21."
},
{
"code": null,
"e": 7721,
"s": 7589,
"text": "You can add the animation so the selected cell will be zoomed-in and have shadow effect. To apply it, you can use the following CSS"
},
{
"code": null,
"e": 7979,
"s": 7721,
"text": "div.cell { transition: all 0.25s; border: none; position: relative; top: 0;}div.cell.selected, div.cell.selected.jupyter-soft-selected { border: none; background: transparent; box-shadow: 0 6px 18px #aaa; z-index: 10; top: -10px;}"
},
{
"code": null,
"e": 8013,
"s": 7979,
"text": "The result is shown in Figure 22."
},
{
"code": null,
"e": 8081,
"s": 8013,
"text": "By default, the output cell is left-aligned, as shown in Figure 23."
},
{
"code": null,
"e": 8116,
"s": 8081,
"text": "To change it, you can use this CSS"
},
{
"code": null,
"e": 8151,
"s": 8116,
"text": ".output { align-items: center;}"
},
{
"code": null,
"e": 8185,
"s": 8151,
"text": "The result is shown in Figure 24."
},
{
"code": null,
"e": 8342,
"s": 8185,
"text": "You can customize the background, alignment, and padding of a data frame in Jupyter. The default setting is shown in Figure 25 (after centering the output)."
},
{
"code": null,
"e": 8380,
"s": 8342,
"text": "You can use this CSS to customize it."
},
{
"code": null,
"e": 8559,
"s": 8380,
"text": ".dataframe { /* dataframe atau table */ background: white; box-shadow: 0px 1px 2px #bbb;}.dataframe thead th, .dataframe tbody td { text-align: center; padding: 1em;}"
},
{
"code": null,
"e": 8686,
"s": 8559,
"text": "I set the background color into white, right-aligned, and adjust the box-shadow and padding. The result is shown in Figure 26."
},
{
"code": null,
"e": 8753,
"s": 8686,
"text": "The last, if you want to remove the line box, you can use this CSS"
},
{
"code": null,
"e": 8803,
"s": 8753,
"text": "div.prompt,div.tooltiptext pre { display:none}"
},
{
"code": null,
"e": 8837,
"s": 8803,
"text": "The result is shown in Figure 27."
},
{
"code": null,
"e": 8965,
"s": 8837,
"text": "I did not apply this custom to my Jupyter. I let the line cell is visible. If you prefer to hide it, you can use the CSS above."
},
{
"code": null,
"e": 9050,
"s": 8965,
"text": "To conclude, I will share the CSS customization for my Jupyter in the following CSS."
},
{
"code": null,
"e": 9079,
"s": 9050,
"text": "Here is the captured result."
},
{
"code": null,
"e": 9102,
"s": 9079,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9125,
"s": 9102,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9148,
"s": 9125,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9171,
"s": 9148,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9194,
"s": 9171,
"text": "towardsdatascience.com"
}
] |
Materialize - Dropdowns | Materialize provides dropdown CSS class to make a ul element as a dropdown and add the id of the ul element to the data-activates attribute of the button or anchor element. The following table mentions the available classes and their effects.
dropdown-content
Identifies ul as a materialize dropdown component. Required for ul element.
data-activates
id of the dropdown ul element.
Following is an example of using a dropdown.
<!DOCTYPE html>
<html>
<head>
<title>The Materialize Dropdowns Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
</head>
<body class="container">
<h3>Drop Down Demo</h3>
<ul id="dropdown" class="dropdown-content">
<li><a href="#">Inbox<span class="badge">12</span></a></li>
<li><a href="#!">Unread<span class="new badge">4</span></a></li>
<li><a href="#">Sent</a></li>
<li class="divider"></li>
<li><a href="#">Outbox<span class="badge">14</span></a></li>
</ul>
<a class="btn dropdown-button" href="#" data-activates="dropdown">Mail Box<i class="mdi-navigation-arrow-drop-down right"></i></a>
</body>
</html>
Verify the output.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2430,
"s": 2187,
"text": "Materialize provides dropdown CSS class to make a ul element as a dropdown and add the id of the ul element to the data-activates attribute of the button or anchor element. The following table mentions the available classes and their effects."
},
{
"code": null,
"e": 2447,
"s": 2430,
"text": "dropdown-content"
},
{
"code": null,
"e": 2523,
"s": 2447,
"text": "Identifies ul as a materialize dropdown component. Required for ul element."
},
{
"code": null,
"e": 2538,
"s": 2523,
"text": "data-activates"
},
{
"code": null,
"e": 2569,
"s": 2538,
"text": "id of the dropdown ul element."
},
{
"code": null,
"e": 2614,
"s": 2569,
"text": "Following is an example of using a dropdown."
},
{
"code": null,
"e": 3786,
"s": 2614,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>The Materialize Dropdowns Example</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css\">\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js\"></script>\n </head>\n <body class=\"container\">\n <h3>Drop Down Demo</h3>\n <ul id=\"dropdown\" class=\"dropdown-content\">\n <li><a href=\"#\">Inbox<span class=\"badge\">12</span></a></li>\n <li><a href=\"#!\">Unread<span class=\"new badge\">4</span></a></li>\n <li><a href=\"#\">Sent</a></li>\n <li class=\"divider\"></li> \n <li><a href=\"#\">Outbox<span class=\"badge\">14</span></a></li>\n </ul>\n <a class=\"btn dropdown-button\" href=\"#\" data-activates=\"dropdown\">Mail Box<i class=\"mdi-navigation-arrow-drop-down right\"></i></a>\n </body>\n</html>"
},
{
"code": null,
"e": 3805,
"s": 3786,
"text": "Verify the output."
},
{
"code": null,
"e": 3812,
"s": 3805,
"text": " Print"
},
{
"code": null,
"e": 3823,
"s": 3812,
"text": " Add Notes"
}
] |
MySQL Tryit Editor v1.0 | SELECT * FROM Customers LIMIT 3;
β
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. | [
{
"code": null,
"e": 33,
"s": 0,
"text": "SELECT * FROM Customers LIMIT 3;"
},
{
"code": null,
"e": 35,
"s": 33,
"text": "β"
},
{
"code": null,
"e": 107,
"s": 44,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 167,
"s": 107,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 235,
"s": 167,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 273,
"s": 235,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 358,
"s": 273,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 532,
"s": 358,
"text": "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."
},
{
"code": null,
"e": 583,
"s": 532,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 651,
"s": 583,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 822,
"s": 651,
"text": "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."
},
{
"code": null,
"e": 922,
"s": 822,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 972,
"s": 922,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
] |
Create global variable in jQuery outside document.ready function? | To create a global variable, you need to place variable inside the <script> </script> tag.
Following is the code β
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<button
onclick="createGlobalVariable()">checkGlobalVariable</button>
<script>
var globalVariable;
$(document).ready(function() {
function initializeGlobalVariable() {
globalVariable = [{
"name":"John",
"age":23
}];
}
initializeGlobalVariable();
});
function createGlobalVariable() {
if (globalVariable.length) {
console.log('The Global variable name
is='+globalVariable[0].name+" The Global variable age is="+globalVariable[0].age);
}
}
</script>
</body>
</html>
To run the above program, save the file name βanyName.html(index.html)β and right click on the
file. Select the option βOpen with Live Serverβ in VS Code editor.
This will produce the following output β
When you click on the button checkGlobalvariable, the following output will be visible β | [
{
"code": null,
"e": 1177,
"s": 1062,
"text": "To create a global variable, you need to place variable inside the <script> </script> tag.\nFollowing is the code β"
},
{
"code": null,
"e": 1188,
"s": 1177,
"text": " Live Demo"
},
{
"code": null,
"e": 2150,
"s": 1188,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<button\nonclick=\"createGlobalVariable()\">checkGlobalVariable</button>\n<script>\n var globalVariable;\n $(document).ready(function() {\n function initializeGlobalVariable() {\n globalVariable = [{\n \"name\":\"John\",\n \"age\":23\n }];\n }\n initializeGlobalVariable();\n });\n function createGlobalVariable() {\n if (globalVariable.length) {\n console.log('The Global variable name\n is='+globalVariable[0].name+\" The Global variable age is=\"+globalVariable[0].age);\n }\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2312,
"s": 2150,
"text": "To run the above program, save the file name βanyName.html(index.html)β and right click on the\nfile. Select the option βOpen with Live Serverβ in VS Code editor."
},
{
"code": null,
"e": 2353,
"s": 2312,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2442,
"s": 2353,
"text": "When you click on the button checkGlobalvariable, the following output will be visible β"
}
] |
How to format Java LocalDateTime as ISO_DATE_TIME format | At first, set the date:
LocalDateTime dateTime = LocalDateTime.of(2019, Month.JULY, 9, 10, 20);
Now, format the datetime as ISO_DATE_TIME format:
String str = dateTime.format(DateTimeFormatter.ISO_DATE_TIME);
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
public class Demo {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.of(2019, Month.JULY, 9, 10, 20);
System.out.println("DateTime = "+dateTime);
String str = dateTime.format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println("Formatted date = "+str);
}
}
DateTime = 2019-07-09T10:20
Formatted date = 2019-07-09T10:20:00 | [
{
"code": null,
"e": 1086,
"s": 1062,
"text": "At first, set the date:"
},
{
"code": null,
"e": 1158,
"s": 1086,
"text": "LocalDateTime dateTime = LocalDateTime.of(2019, Month.JULY, 9, 10, 20);"
},
{
"code": null,
"e": 1208,
"s": 1158,
"text": "Now, format the datetime as ISO_DATE_TIME format:"
},
{
"code": null,
"e": 1271,
"s": 1208,
"text": "String str = dateTime.format(DateTimeFormatter.ISO_DATE_TIME);"
},
{
"code": null,
"e": 1689,
"s": 1271,
"text": "import java.time.LocalDateTime;\nimport java.time.Month;\nimport java.time.format.DateTimeFormatter;\npublic class Demo {\n public static void main(String[] args) {\n LocalDateTime dateTime = LocalDateTime.of(2019, Month.JULY, 9, 10, 20);\n System.out.println(\"DateTime = \"+dateTime);\n String str = dateTime.format(DateTimeFormatter.ISO_DATE_TIME);\n System.out.println(\"Formatted date = \"+str);\n }\n}"
},
{
"code": null,
"e": 1754,
"s": 1689,
"text": "DateTime = 2019-07-09T10:20\nFormatted date = 2019-07-09T10:20:00"
}
] |
Machine Learning in Tableau with PyCaret | by Andrew Cowan-Nagora | Towards Data Science | PyCaret is a recently released open source machine learning library in Python that trains and deploys machine learning models in a low-code environment. To learn more about PyCaret, read this announcement.
This article will demonstrate how PyCaret can be integrated with Tableau Desktop and Tableau Prep which opens new avenues for analysts and data scientists to add a layer of machine learning to their dashboards, reports and visualizations. By reducing the time required to code as well as the need to purchase additional software, rapid prototyping is now possible in environments that are already familiar and available to analysts throughout the organization.
Train a supervised machine learning model and create a ML pipeline in PyCaret
Load a trained ML pipeline into Tableau Desktop and Tableau Prep
Create a dashboard that communicates insights from the model
Understand how the model can be deployed into production with Tableau
The example here will focus on how to setup a basic direct marketing propensity model that uses a classification algorithm to predict which customers are most likely to initiate a visit after receiving an offer via text or email.
A dashboard will then be created that can take the trained model and predict how successful new campaigns are likely to be which is valuable for marketers who are designing promotional plans.
By using PyCaret and Tableau, the business can quickly setup reporting products that continuously generate predictive views using existing software and minimal up front development time.
The software that will be required to follow along:
1 β Tableau Desktop
Tableau Desktop is a visual analytics tool that is used to connect to data, build interactive dashboards and share insights across the organization.
2 β Tableau Prep
Tableau Prep provides a visual interface to combine, clean and shape data by setting up flows and schedules.
3 β Python 3.7 or greater
Anaconda is a free, open-source distribution of the Python programming language for data science. If you havenβt used it before, you can download it here.
4 β PyCaret Python Library
To install the PyCaret library use the following code in Jupyter notebook or Anaconda prompt.
pip install pycaret
This may take up to 15 minutes. If any problems are encountered please see the project GitHub page for known issues.
5 β TabPy Python Library
TabPy is the Tableau supported library that is required run python scripts.
From the GitHub page:
TabPy (the Tableau Python Server) is an Analytics Extension implementation which expands Tableauβs capabilities by allowing users to execute Python scripts and saved functions via Tableauβs table calculations.
To install TabPy use the following code in Anaconda prompt or terminal.
pip install tabpy
Once installed use the following code to start up a local server using default settings.
tabpy
To connect Tableau to the TabPy server go to Help > Settings and Performance > Manage Analytics Extension Connection. Select TabPy and enter localhost, port 9004 (default) and test connection.
Python scripts can now be run in Tableau through calculated fields that output as table calculations.
Please refer to the TabPy GitHub page for custom server options. Running TabPy on external servers and/or clouds and configuring Tableau Server will not be covered in this post but please look here for more information.
The data set that will be used contains information on various marketing offers that were sent to customers through text and email. It contains 64000 records organized into an ID column, 10 features that relate to the customer or message sent and a binary target that indicates if a visit occurred. The data can be downloaded here.
While it is possible to perform the model training process inside Tableau, this is generally not the preferred approach since every time the data is refreshed or the user interacts with the view the script will re-run. This is problematic because:
When the model is retrained with new data, the prediction may change unexpectedly.
Constantly re-running a script will impact the performance of the dashboard.
A more appropriate approach is to use a pre-trained model in Tableau to generate predictions on new data. Jupyter notebook will be used in this example to demonstrate how PyCaret is used to make this process straight forward.
Running the following code in Jupyter Notebook will train a Naive Bayes classification model and create a ML pipeline that is saved as a pickle file.
Notice that setting up and saving the model is accomplished in 4 lines of code. A complete notebook can be downloaded here.
The unseen data will be used to simulate a list of new customers that have not yet been sent an offer. When the dashboard is deployed in production, it would be connected to a database containing the information for new customers.
Note that in the setup phase PyCaret performs automatic pre-processing which in this case expanded the number of features from 10 to 39 via one hot encoding.
This is only scratching the surface of PyCaretβs built in functionality thus it is strongly recommended to look at the classification module and tutorials on the PyCaret website. The specific details of the selected model will not be covered here.
The unseen data will now be passed to the trained model and labelled in Tableau Desktop.
Instructions:
1) Open Tableau and connect to the text file new_customer.csv that was created in the above code. This simply serves as an example but ideally the new or unlabelled customer data would reside in a database.
2) On a new sheet select analysis > create calculated field or simply right click in the data pane. Enter the following code:
SCRIPT_INT("import pandas as pdimport pycaret.classificationnb = pycaret.classification.load_model('C:/Users/owner/Desktop/nb_direct')X_pred = pd.DataFrame({'recency':_arg1, 'history_segment':_arg2, 'history':_arg3, 'mens':_arg4, 'womens':_arg5,'zip_code':_arg6, 'newbie':_arg7, 'channel':_arg8, 'segment':_arg9, 'DM_category':_arg10}) pred = pycaret.classification.predict_model(nb, X_pred)return pred['Label'].tolist()",SUM([recency]),ATTR([history_segment]),SUM([history]),SUM([mens]),SUM([womens]),ATTR([zip_code]),SUM([newbie]),ATTR([channel]),ATTR([segment]),SUM([DM_category]))
The script function specifies the type of data that will be returned from the calculation. In this case it is the binary predicted label for visit.
The load_model() function from PyCaret loads the previously saved model and transformation pipeline that was saved as a pickle file.
X_pred is a dataframe that will map the data connected to Tableau as inputs through the _arg1, _arg2, _arg3... notation. The fields are listed at the end of the script.
predict_model() takes the trained model and predicts against the new data input. Note that the new data is passed through the transformation pipeline created in the PyCaret setup phase (encoding).
The labels are then returned as a list that can be viewed in Tableau.
3) By dragging the ID and Label columns into the view it is possible to see the model predictions.
It is important to understand that the output is a table calculation which has some limitations:
The script will only run when pulled into the view.
It cannot be used as a base for further calculations unless both are in the view.
The python generated data cannot be appended to Tableau extracts.
The script runs each time the view is changed which can lead to long wait times.
These drawbacks are quite significant as dashboard options become limited when each record must be contained in the view and the script takes around 4 minutes to run with 3200 records in this case.
Viable applications would include generating scored lists that could be exported or summary views such as the one below.
An example insight from this could be that higher spend customers are the most likely to visit which makes sense business wise but could perhaps be an indicator of unnecessary discounting.
A great alternative to get around the limitations of running scripts directly in Tableau Desktop is to use Tableau Prep. New data can be connected and then passed to the model with the difference this time being that the predicted labels are appended to the output. When connected to Tableau, the new columns can be used normally rather than as table calculations.
Instructions:
1) Open Tableau Prep and connect to the text file new_customer.csv that was created in the above code.
2) Select the β+β button next to the file in the flow pane and add the script option. Like in Tableau Desktop, connect to the TabPy server that should still be running in the background using localhost and 9004.
3) Next, the following python script will need to be created and connected to prep using the browse option. It can be downloaded here.
A function is created that loads the pickle file which holds the saved model and transformation pipeline. The data loaded into prep is automatically held in the df object and is passed to the model.
The PyCaret output will return the initial data set and two new appended columns; Label (prediction) and Score (probability of prediction). The output schema ensures that the columns and data types are correctly read into prep.
The function name must then be entered into prep.
4) Select the β+β sign next to the script icon and choose output. It is possible to publish as a .tde or .hyper file to Tableau Server which would be the preferred method in a production environment but for this example a .csv file will be sent to the desktop.
Notice how the label and score columns are now appended to the original data set. Select βrun flowβ to generate the output. The flow file can be downloaded here.
In a server environment it is possible to schedule when a flow runs and automate the scoring process before the data reaches the actual Tableau dashboard.
The newly labelled data can now be connected to Tableau Desktop without the table calculation limitations and slow downs.
Aggregations and any other desired calculations can be created to design a summary dashboard that displays various predictive metrics:
Once the data and ML pipeline is established, marketers and executives would quickly be able to track how upcoming campaigns could potentially perform with minimal intervention required. The Tableau file that contains the example dashboard and earlier script can be downloaded here.
This article has demonstrated how PyCaret can be integrated with Tableau Desktop and Tableau Prep to quickly add a layer of machine learning into existing workflows.
By using tools that are familiar to the organization and the PyCaret library, entire ML pipelines can be established in minutes which enables predictive analytics prototyping to get off the ground quickly.
PyCaret
PyCaret: User guide and documentation | [
{
"code": null,
"e": 378,
"s": 172,
"text": "PyCaret is a recently released open source machine learning library in Python that trains and deploys machine learning models in a low-code environment. To learn more about PyCaret, read this announcement."
},
{
"code": null,
"e": 839,
"s": 378,
"text": "This article will demonstrate how PyCaret can be integrated with Tableau Desktop and Tableau Prep which opens new avenues for analysts and data scientists to add a layer of machine learning to their dashboards, reports and visualizations. By reducing the time required to code as well as the need to purchase additional software, rapid prototyping is now possible in environments that are already familiar and available to analysts throughout the organization."
},
{
"code": null,
"e": 917,
"s": 839,
"text": "Train a supervised machine learning model and create a ML pipeline in PyCaret"
},
{
"code": null,
"e": 982,
"s": 917,
"text": "Load a trained ML pipeline into Tableau Desktop and Tableau Prep"
},
{
"code": null,
"e": 1043,
"s": 982,
"text": "Create a dashboard that communicates insights from the model"
},
{
"code": null,
"e": 1113,
"s": 1043,
"text": "Understand how the model can be deployed into production with Tableau"
},
{
"code": null,
"e": 1343,
"s": 1113,
"text": "The example here will focus on how to setup a basic direct marketing propensity model that uses a classification algorithm to predict which customers are most likely to initiate a visit after receiving an offer via text or email."
},
{
"code": null,
"e": 1535,
"s": 1343,
"text": "A dashboard will then be created that can take the trained model and predict how successful new campaigns are likely to be which is valuable for marketers who are designing promotional plans."
},
{
"code": null,
"e": 1722,
"s": 1535,
"text": "By using PyCaret and Tableau, the business can quickly setup reporting products that continuously generate predictive views using existing software and minimal up front development time."
},
{
"code": null,
"e": 1774,
"s": 1722,
"text": "The software that will be required to follow along:"
},
{
"code": null,
"e": 1794,
"s": 1774,
"text": "1 β Tableau Desktop"
},
{
"code": null,
"e": 1943,
"s": 1794,
"text": "Tableau Desktop is a visual analytics tool that is used to connect to data, build interactive dashboards and share insights across the organization."
},
{
"code": null,
"e": 1960,
"s": 1943,
"text": "2 β Tableau Prep"
},
{
"code": null,
"e": 2069,
"s": 1960,
"text": "Tableau Prep provides a visual interface to combine, clean and shape data by setting up flows and schedules."
},
{
"code": null,
"e": 2095,
"s": 2069,
"text": "3 β Python 3.7 or greater"
},
{
"code": null,
"e": 2250,
"s": 2095,
"text": "Anaconda is a free, open-source distribution of the Python programming language for data science. If you havenβt used it before, you can download it here."
},
{
"code": null,
"e": 2277,
"s": 2250,
"text": "4 β PyCaret Python Library"
},
{
"code": null,
"e": 2371,
"s": 2277,
"text": "To install the PyCaret library use the following code in Jupyter notebook or Anaconda prompt."
},
{
"code": null,
"e": 2391,
"s": 2371,
"text": "pip install pycaret"
},
{
"code": null,
"e": 2508,
"s": 2391,
"text": "This may take up to 15 minutes. If any problems are encountered please see the project GitHub page for known issues."
},
{
"code": null,
"e": 2533,
"s": 2508,
"text": "5 β TabPy Python Library"
},
{
"code": null,
"e": 2609,
"s": 2533,
"text": "TabPy is the Tableau supported library that is required run python scripts."
},
{
"code": null,
"e": 2631,
"s": 2609,
"text": "From the GitHub page:"
},
{
"code": null,
"e": 2841,
"s": 2631,
"text": "TabPy (the Tableau Python Server) is an Analytics Extension implementation which expands Tableauβs capabilities by allowing users to execute Python scripts and saved functions via Tableauβs table calculations."
},
{
"code": null,
"e": 2913,
"s": 2841,
"text": "To install TabPy use the following code in Anaconda prompt or terminal."
},
{
"code": null,
"e": 2931,
"s": 2913,
"text": "pip install tabpy"
},
{
"code": null,
"e": 3020,
"s": 2931,
"text": "Once installed use the following code to start up a local server using default settings."
},
{
"code": null,
"e": 3026,
"s": 3020,
"text": "tabpy"
},
{
"code": null,
"e": 3219,
"s": 3026,
"text": "To connect Tableau to the TabPy server go to Help > Settings and Performance > Manage Analytics Extension Connection. Select TabPy and enter localhost, port 9004 (default) and test connection."
},
{
"code": null,
"e": 3321,
"s": 3219,
"text": "Python scripts can now be run in Tableau through calculated fields that output as table calculations."
},
{
"code": null,
"e": 3541,
"s": 3321,
"text": "Please refer to the TabPy GitHub page for custom server options. Running TabPy on external servers and/or clouds and configuring Tableau Server will not be covered in this post but please look here for more information."
},
{
"code": null,
"e": 3873,
"s": 3541,
"text": "The data set that will be used contains information on various marketing offers that were sent to customers through text and email. It contains 64000 records organized into an ID column, 10 features that relate to the customer or message sent and a binary target that indicates if a visit occurred. The data can be downloaded here."
},
{
"code": null,
"e": 4121,
"s": 3873,
"text": "While it is possible to perform the model training process inside Tableau, this is generally not the preferred approach since every time the data is refreshed or the user interacts with the view the script will re-run. This is problematic because:"
},
{
"code": null,
"e": 4204,
"s": 4121,
"text": "When the model is retrained with new data, the prediction may change unexpectedly."
},
{
"code": null,
"e": 4281,
"s": 4204,
"text": "Constantly re-running a script will impact the performance of the dashboard."
},
{
"code": null,
"e": 4507,
"s": 4281,
"text": "A more appropriate approach is to use a pre-trained model in Tableau to generate predictions on new data. Jupyter notebook will be used in this example to demonstrate how PyCaret is used to make this process straight forward."
},
{
"code": null,
"e": 4657,
"s": 4507,
"text": "Running the following code in Jupyter Notebook will train a Naive Bayes classification model and create a ML pipeline that is saved as a pickle file."
},
{
"code": null,
"e": 4781,
"s": 4657,
"text": "Notice that setting up and saving the model is accomplished in 4 lines of code. A complete notebook can be downloaded here."
},
{
"code": null,
"e": 5012,
"s": 4781,
"text": "The unseen data will be used to simulate a list of new customers that have not yet been sent an offer. When the dashboard is deployed in production, it would be connected to a database containing the information for new customers."
},
{
"code": null,
"e": 5170,
"s": 5012,
"text": "Note that in the setup phase PyCaret performs automatic pre-processing which in this case expanded the number of features from 10 to 39 via one hot encoding."
},
{
"code": null,
"e": 5418,
"s": 5170,
"text": "This is only scratching the surface of PyCaretβs built in functionality thus it is strongly recommended to look at the classification module and tutorials on the PyCaret website. The specific details of the selected model will not be covered here."
},
{
"code": null,
"e": 5507,
"s": 5418,
"text": "The unseen data will now be passed to the trained model and labelled in Tableau Desktop."
},
{
"code": null,
"e": 5521,
"s": 5507,
"text": "Instructions:"
},
{
"code": null,
"e": 5728,
"s": 5521,
"text": "1) Open Tableau and connect to the text file new_customer.csv that was created in the above code. This simply serves as an example but ideally the new or unlabelled customer data would reside in a database."
},
{
"code": null,
"e": 5854,
"s": 5728,
"text": "2) On a new sheet select analysis > create calculated field or simply right click in the data pane. Enter the following code:"
},
{
"code": null,
"e": 6462,
"s": 5854,
"text": "SCRIPT_INT(\"import pandas as pdimport pycaret.classificationnb = pycaret.classification.load_model('C:/Users/owner/Desktop/nb_direct')X_pred = pd.DataFrame({'recency':_arg1, 'history_segment':_arg2, 'history':_arg3, 'mens':_arg4, 'womens':_arg5,'zip_code':_arg6, 'newbie':_arg7, 'channel':_arg8, 'segment':_arg9, 'DM_category':_arg10}) pred = pycaret.classification.predict_model(nb, X_pred)return pred['Label'].tolist()\",SUM([recency]),ATTR([history_segment]),SUM([history]),SUM([mens]),SUM([womens]),ATTR([zip_code]),SUM([newbie]),ATTR([channel]),ATTR([segment]),SUM([DM_category]))"
},
{
"code": null,
"e": 6610,
"s": 6462,
"text": "The script function specifies the type of data that will be returned from the calculation. In this case it is the binary predicted label for visit."
},
{
"code": null,
"e": 6743,
"s": 6610,
"text": "The load_model() function from PyCaret loads the previously saved model and transformation pipeline that was saved as a pickle file."
},
{
"code": null,
"e": 6912,
"s": 6743,
"text": "X_pred is a dataframe that will map the data connected to Tableau as inputs through the _arg1, _arg2, _arg3... notation. The fields are listed at the end of the script."
},
{
"code": null,
"e": 7109,
"s": 6912,
"text": "predict_model() takes the trained model and predicts against the new data input. Note that the new data is passed through the transformation pipeline created in the PyCaret setup phase (encoding)."
},
{
"code": null,
"e": 7179,
"s": 7109,
"text": "The labels are then returned as a list that can be viewed in Tableau."
},
{
"code": null,
"e": 7278,
"s": 7179,
"text": "3) By dragging the ID and Label columns into the view it is possible to see the model predictions."
},
{
"code": null,
"e": 7375,
"s": 7278,
"text": "It is important to understand that the output is a table calculation which has some limitations:"
},
{
"code": null,
"e": 7427,
"s": 7375,
"text": "The script will only run when pulled into the view."
},
{
"code": null,
"e": 7509,
"s": 7427,
"text": "It cannot be used as a base for further calculations unless both are in the view."
},
{
"code": null,
"e": 7575,
"s": 7509,
"text": "The python generated data cannot be appended to Tableau extracts."
},
{
"code": null,
"e": 7656,
"s": 7575,
"text": "The script runs each time the view is changed which can lead to long wait times."
},
{
"code": null,
"e": 7854,
"s": 7656,
"text": "These drawbacks are quite significant as dashboard options become limited when each record must be contained in the view and the script takes around 4 minutes to run with 3200 records in this case."
},
{
"code": null,
"e": 7975,
"s": 7854,
"text": "Viable applications would include generating scored lists that could be exported or summary views such as the one below."
},
{
"code": null,
"e": 8164,
"s": 7975,
"text": "An example insight from this could be that higher spend customers are the most likely to visit which makes sense business wise but could perhaps be an indicator of unnecessary discounting."
},
{
"code": null,
"e": 8529,
"s": 8164,
"text": "A great alternative to get around the limitations of running scripts directly in Tableau Desktop is to use Tableau Prep. New data can be connected and then passed to the model with the difference this time being that the predicted labels are appended to the output. When connected to Tableau, the new columns can be used normally rather than as table calculations."
},
{
"code": null,
"e": 8543,
"s": 8529,
"text": "Instructions:"
},
{
"code": null,
"e": 8646,
"s": 8543,
"text": "1) Open Tableau Prep and connect to the text file new_customer.csv that was created in the above code."
},
{
"code": null,
"e": 8858,
"s": 8646,
"text": "2) Select the β+β button next to the file in the flow pane and add the script option. Like in Tableau Desktop, connect to the TabPy server that should still be running in the background using localhost and 9004."
},
{
"code": null,
"e": 8993,
"s": 8858,
"text": "3) Next, the following python script will need to be created and connected to prep using the browse option. It can be downloaded here."
},
{
"code": null,
"e": 9192,
"s": 8993,
"text": "A function is created that loads the pickle file which holds the saved model and transformation pipeline. The data loaded into prep is automatically held in the df object and is passed to the model."
},
{
"code": null,
"e": 9420,
"s": 9192,
"text": "The PyCaret output will return the initial data set and two new appended columns; Label (prediction) and Score (probability of prediction). The output schema ensures that the columns and data types are correctly read into prep."
},
{
"code": null,
"e": 9470,
"s": 9420,
"text": "The function name must then be entered into prep."
},
{
"code": null,
"e": 9731,
"s": 9470,
"text": "4) Select the β+β sign next to the script icon and choose output. It is possible to publish as a .tde or .hyper file to Tableau Server which would be the preferred method in a production environment but for this example a .csv file will be sent to the desktop."
},
{
"code": null,
"e": 9893,
"s": 9731,
"text": "Notice how the label and score columns are now appended to the original data set. Select βrun flowβ to generate the output. The flow file can be downloaded here."
},
{
"code": null,
"e": 10048,
"s": 9893,
"text": "In a server environment it is possible to schedule when a flow runs and automate the scoring process before the data reaches the actual Tableau dashboard."
},
{
"code": null,
"e": 10170,
"s": 10048,
"text": "The newly labelled data can now be connected to Tableau Desktop without the table calculation limitations and slow downs."
},
{
"code": null,
"e": 10305,
"s": 10170,
"text": "Aggregations and any other desired calculations can be created to design a summary dashboard that displays various predictive metrics:"
},
{
"code": null,
"e": 10588,
"s": 10305,
"text": "Once the data and ML pipeline is established, marketers and executives would quickly be able to track how upcoming campaigns could potentially perform with minimal intervention required. The Tableau file that contains the example dashboard and earlier script can be downloaded here."
},
{
"code": null,
"e": 10754,
"s": 10588,
"text": "This article has demonstrated how PyCaret can be integrated with Tableau Desktop and Tableau Prep to quickly add a layer of machine learning into existing workflows."
},
{
"code": null,
"e": 10960,
"s": 10754,
"text": "By using tools that are familiar to the organization and the PyCaret library, entire ML pipelines can be established in minutes which enables predictive analytics prototyping to get off the ground quickly."
},
{
"code": null,
"e": 10968,
"s": 10960,
"text": "PyCaret"
}
] |
How to add a unique id for an element in HTML? | Use the id attribute in HTML to add the unique id of an element.
You can try to run the following code to implement id attribute β
<html>
<body>
<h1>Tutorialspoint</h1>
<p id = "myid">We provide Tutorials!</p>
<button onclick = "display()">More...</button>
<script>
function display() {
document.getElementById("myid").innerHTML = "We provide learning videos as well";
}
</script>
</body>
</html> | [
{
"code": null,
"e": 1127,
"s": 1062,
"text": "Use the id attribute in HTML to add the unique id of an element."
},
{
"code": null,
"e": 1193,
"s": 1127,
"text": "You can try to run the following code to implement id attribute β"
},
{
"code": null,
"e": 1526,
"s": 1193,
"text": "<html>\n <body>\n <h1>Tutorialspoint</h1>\n <p id = \"myid\">We provide Tutorials!</p>\n <button onclick = \"display()\">More...</button>\n\n <script>\n function display() {\n document.getElementById(\"myid\").innerHTML = \"We provide learning videos as well\";\n }\n </script>\n </body>\n</html>"
}
] |
Minimum circular rotations to obtain a given numeric string by avoiding a set of given strings - GeeksforGeeks | 15 Feb, 2021
Given a numeric string target of length N and a set of numeric strings blocked, each of length N, the task is to find the minimum number of circular rotations required to convert an initial string consisting of only 0βs to target by avoiding any of the strings present in blocked at any step. If not possible, print -1.Note: A single rotation involves increasing or decreasing a value at particular index by 1 unit. As rotations are circular, 0 can be converted to 9 or a 9 can be converted to 0.Examples:
Input: target = β7531β, blocked = {β1543β, β7434β, β7300β, β7321β, β2427β } Output: 12 Explanation: β0000β -> β9000β -> β8000β -> β7000β -> β7100β -> β7200β -> β7210β -> β7310β -> β7410β -> β7510β -> β7520β -> β7530β -> β7531βInput: target = β4231β, blocked = { β1243β, β4444β, β1256β, β5321β, β2222β } Output: 10
Approach: In order to solve this problem, we are using the following BFS approach:
Create a string start of length N consisting of only 0βs. Push it to queue. The queue is created to store the next valid combination possible by increasing or decreasing a character by an unit.
Create an unordered set avoid, and add all the blocked strings in it.
If start or target is present in avoid, the required target cannot be reached.
Pop start from queue and traverse all the characters of start. Increase and decrease each character by an unit keeping the remaining constant and check if the string is present in avoid. If not and the new combination is not equal to target, push it to the queue and insert into avoid to prevent repeating the same combination in future.
Once the entire length of start is traversed, repeat the above steps for the next level, which are the the valid strings obtained from start and are currently present in the queue.
Keep repeating the above steps until target is reached or there are no further combinations left and the queue has become empty.
At any instant, if the string formed is equal to target, return the value of count which keeps a count of the number of levels of BFS traversals. The value of count is the minimum number of circular rotations required.
If no further state can be obtained and the queue is empty, print βNot Possibleβ.
Below is the implementation of the above logic:
C++
Java
// C++ Program to count the minimum// number of circular rotations required// to obtain a given numeric strings// avoiding a set of blocked strings #include <bits/stdc++.h>using namespace std; int minCircularRotations( string target, vector<string>& blocked, int N){ string start = ""; for (int i = 0; i < N; i++) { start += '0'; } unordered_set<string> avoid; for (int i = 0; i < blocked.size(); i++) avoid.insert(blocked[i]); // If the starting string needs // to be avoided if (avoid.find(start) != avoid.end()) return -1; // If the final string needs // to be avoided if (avoid.find(target) != avoid.end()) return -1; queue<string> qu; qu.push(start); // Variable to store count of rotations int count = 0; // BFS Approach while (!qu.empty()) { count++; // Store the current size // of the queue int size = qu.size(); for (int j = 0; j < size; j++) { string st = qu.front(); qu.pop(); // Traverse the string for (int i = 0; i < N; i++) { char ch = st[i]; // Increase the // current character st[i]++; // Circular rotation if (st[i] > '9') st[i] = '0'; // If target is reached if (st == target) return count; // If the string formed // is not one to be avoided if (avoid.find(st) == avoid.end()) qu.push(st); // Add it to the list of // strings to be avoided // to prevent visiting // already visited states avoid.insert(st); // Decrease the current // value by 1 and repeat // the similar checkings st[i] = ch - 1; if (st[i] < '0') st[i] = '9'; if (st == target) return count; if (avoid.find(st) == avoid.end()) qu.push(st); avoid.insert(st); // Restore the original // character st[i] = ch; } } } return -1;} // Driver codeint main(){ int N = 4; string target = "7531"; vector<string> blocked = { "1543", "7434", "7300", "7321", "2427" }; cout << minCircularRotations( target, blocked, N) << endl; return 0;}
// Java Program to count the minimum// number of circular rotations required// to obtain a given numeric Strings// avoiding a set of blocked Stringsimport java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.LinkedList;import java.util.Queue; class GFG{ static int minCircularRotations(String target, ArrayList<String> blocked, int N) { String start = ""; for (int i = 0; i < N; i++) { start += '0'; } HashSet<String> avoid = new HashSet<>(); for (int i = 0; i < blocked.size(); i++) avoid.add(blocked.get(i)); // If the starting String needs // to be avoided if (avoid.contains(start)) return -1; // If the final String needs // to be avoided if (avoid.contains(target)) return -1; Queue<String> qu = new LinkedList<>(); qu.add(start); // Variable to store count of rotations int count = 0; // BFS Approach while (!qu.isEmpty()) { count++; // Store the current size // of the queue int size = qu.size(); for (int j = 0; j < size; j++) { StringBuilder st = new StringBuilder(qu.poll()); // Traverse the String for (int i = 0; i < N; i++) { char ch = st.charAt(i); // Increase the // current character st.setCharAt(i, (char) (st.charAt(i) + 1)); // Circular rotation if (st.charAt(i) > '9') st.setCharAt(i, '0'); // If target is reached if (st.toString().equals(target)) return count; // If the String formed // is not one to be avoided if (!avoid.contains(st.toString())) qu.add(st.toString()); // Add it to the list of // Strings to be avoided // to prevent visiting // already visited states avoid.add(st.toString()); // Decrease the current // value by 1 and repeat // the similar checkings st.setCharAt(i, (char) (ch - 1)); if (st.charAt(i) < '0') st.setCharAt(i, '9'); if (st.toString().equals(target)) return count; if (!avoid.contains(st.toString())) qu.add(st.toString()); avoid.add(st.toString()); // Restore the original // character st.setCharAt(i, ch); } } } return -1; } // Driver code public static void main(String[] args) { int N = 4; String target = "7531"; ArrayList<String> blocked = new ArrayList<>(Arrays.asList("1543", "7434", "7300", "7321", "2427")); System.out.println(minCircularRotations(target, blocked, N)); }} // This code is contributed by sanjeev2552
12
sanjeev2552
BFS
rotation
Competitive Programming
Mathematical
Queue
Strings
Strings
Mathematical
Queue
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo 10^9+7 (1000000007)
Bits manipulation (Important tactics)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Formatted output in Java
Algorithm Library | C++ Magicians STL Algorithm
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers | [
{
"code": null,
"e": 25602,
"s": 25574,
"text": "\n15 Feb, 2021"
},
{
"code": null,
"e": 26110,
"s": 25602,
"text": "Given a numeric string target of length N and a set of numeric strings blocked, each of length N, the task is to find the minimum number of circular rotations required to convert an initial string consisting of only 0βs to target by avoiding any of the strings present in blocked at any step. If not possible, print -1.Note: A single rotation involves increasing or decreasing a value at particular index by 1 unit. As rotations are circular, 0 can be converted to 9 or a 9 can be converted to 0.Examples: "
},
{
"code": null,
"e": 26426,
"s": 26110,
"text": "Input: target = β7531β, blocked = {β1543β, β7434β, β7300β, β7321β, β2427β } Output: 12 Explanation: β0000β -> β9000β -> β8000β -> β7000β -> β7100β -> β7200β -> β7210β -> β7310β -> β7410β -> β7510β -> β7520β -> β7530β -> β7531βInput: target = β4231β, blocked = { β1243β, β4444β, β1256β, β5321β, β2222β } Output: 10 "
},
{
"code": null,
"e": 26513,
"s": 26428,
"text": "Approach: In order to solve this problem, we are using the following BFS approach: "
},
{
"code": null,
"e": 26707,
"s": 26513,
"text": "Create a string start of length N consisting of only 0βs. Push it to queue. The queue is created to store the next valid combination possible by increasing or decreasing a character by an unit."
},
{
"code": null,
"e": 26777,
"s": 26707,
"text": "Create an unordered set avoid, and add all the blocked strings in it."
},
{
"code": null,
"e": 26856,
"s": 26777,
"text": "If start or target is present in avoid, the required target cannot be reached."
},
{
"code": null,
"e": 27194,
"s": 26856,
"text": "Pop start from queue and traverse all the characters of start. Increase and decrease each character by an unit keeping the remaining constant and check if the string is present in avoid. If not and the new combination is not equal to target, push it to the queue and insert into avoid to prevent repeating the same combination in future."
},
{
"code": null,
"e": 27375,
"s": 27194,
"text": "Once the entire length of start is traversed, repeat the above steps for the next level, which are the the valid strings obtained from start and are currently present in the queue."
},
{
"code": null,
"e": 27504,
"s": 27375,
"text": "Keep repeating the above steps until target is reached or there are no further combinations left and the queue has become empty."
},
{
"code": null,
"e": 27723,
"s": 27504,
"text": "At any instant, if the string formed is equal to target, return the value of count which keeps a count of the number of levels of BFS traversals. The value of count is the minimum number of circular rotations required."
},
{
"code": null,
"e": 27805,
"s": 27723,
"text": "If no further state can be obtained and the queue is empty, print βNot Possibleβ."
},
{
"code": null,
"e": 27854,
"s": 27805,
"text": "Below is the implementation of the above logic: "
},
{
"code": null,
"e": 27858,
"s": 27854,
"text": "C++"
},
{
"code": null,
"e": 27863,
"s": 27858,
"text": "Java"
},
{
"code": "// C++ Program to count the minimum// number of circular rotations required// to obtain a given numeric strings// avoiding a set of blocked strings #include <bits/stdc++.h>using namespace std; int minCircularRotations( string target, vector<string>& blocked, int N){ string start = \"\"; for (int i = 0; i < N; i++) { start += '0'; } unordered_set<string> avoid; for (int i = 0; i < blocked.size(); i++) avoid.insert(blocked[i]); // If the starting string needs // to be avoided if (avoid.find(start) != avoid.end()) return -1; // If the final string needs // to be avoided if (avoid.find(target) != avoid.end()) return -1; queue<string> qu; qu.push(start); // Variable to store count of rotations int count = 0; // BFS Approach while (!qu.empty()) { count++; // Store the current size // of the queue int size = qu.size(); for (int j = 0; j < size; j++) { string st = qu.front(); qu.pop(); // Traverse the string for (int i = 0; i < N; i++) { char ch = st[i]; // Increase the // current character st[i]++; // Circular rotation if (st[i] > '9') st[i] = '0'; // If target is reached if (st == target) return count; // If the string formed // is not one to be avoided if (avoid.find(st) == avoid.end()) qu.push(st); // Add it to the list of // strings to be avoided // to prevent visiting // already visited states avoid.insert(st); // Decrease the current // value by 1 and repeat // the similar checkings st[i] = ch - 1; if (st[i] < '0') st[i] = '9'; if (st == target) return count; if (avoid.find(st) == avoid.end()) qu.push(st); avoid.insert(st); // Restore the original // character st[i] = ch; } } } return -1;} // Driver codeint main(){ int N = 4; string target = \"7531\"; vector<string> blocked = { \"1543\", \"7434\", \"7300\", \"7321\", \"2427\" }; cout << minCircularRotations( target, blocked, N) << endl; return 0;}",
"e": 30553,
"s": 27863,
"text": null
},
{
"code": "// Java Program to count the minimum// number of circular rotations required// to obtain a given numeric Strings// avoiding a set of blocked Stringsimport java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.LinkedList;import java.util.Queue; class GFG{ static int minCircularRotations(String target, ArrayList<String> blocked, int N) { String start = \"\"; for (int i = 0; i < N; i++) { start += '0'; } HashSet<String> avoid = new HashSet<>(); for (int i = 0; i < blocked.size(); i++) avoid.add(blocked.get(i)); // If the starting String needs // to be avoided if (avoid.contains(start)) return -1; // If the final String needs // to be avoided if (avoid.contains(target)) return -1; Queue<String> qu = new LinkedList<>(); qu.add(start); // Variable to store count of rotations int count = 0; // BFS Approach while (!qu.isEmpty()) { count++; // Store the current size // of the queue int size = qu.size(); for (int j = 0; j < size; j++) { StringBuilder st = new StringBuilder(qu.poll()); // Traverse the String for (int i = 0; i < N; i++) { char ch = st.charAt(i); // Increase the // current character st.setCharAt(i, (char) (st.charAt(i) + 1)); // Circular rotation if (st.charAt(i) > '9') st.setCharAt(i, '0'); // If target is reached if (st.toString().equals(target)) return count; // If the String formed // is not one to be avoided if (!avoid.contains(st.toString())) qu.add(st.toString()); // Add it to the list of // Strings to be avoided // to prevent visiting // already visited states avoid.add(st.toString()); // Decrease the current // value by 1 and repeat // the similar checkings st.setCharAt(i, (char) (ch - 1)); if (st.charAt(i) < '0') st.setCharAt(i, '9'); if (st.toString().equals(target)) return count; if (!avoid.contains(st.toString())) qu.add(st.toString()); avoid.add(st.toString()); // Restore the original // character st.setCharAt(i, ch); } } } return -1; } // Driver code public static void main(String[] args) { int N = 4; String target = \"7531\"; ArrayList<String> blocked = new ArrayList<>(Arrays.asList(\"1543\", \"7434\", \"7300\", \"7321\", \"2427\")); System.out.println(minCircularRotations(target, blocked, N)); }} // This code is contributed by sanjeev2552",
"e": 33456,
"s": 30553,
"text": null
},
{
"code": null,
"e": 33459,
"s": 33456,
"text": "12"
},
{
"code": null,
"e": 33473,
"s": 33461,
"text": "sanjeev2552"
},
{
"code": null,
"e": 33477,
"s": 33473,
"text": "BFS"
},
{
"code": null,
"e": 33486,
"s": 33477,
"text": "rotation"
},
{
"code": null,
"e": 33510,
"s": 33486,
"text": "Competitive Programming"
},
{
"code": null,
"e": 33523,
"s": 33510,
"text": "Mathematical"
},
{
"code": null,
"e": 33529,
"s": 33523,
"text": "Queue"
},
{
"code": null,
"e": 33537,
"s": 33529,
"text": "Strings"
},
{
"code": null,
"e": 33545,
"s": 33537,
"text": "Strings"
},
{
"code": null,
"e": 33558,
"s": 33545,
"text": "Mathematical"
},
{
"code": null,
"e": 33564,
"s": 33558,
"text": "Queue"
},
{
"code": null,
"e": 33568,
"s": 33564,
"text": "BFS"
},
{
"code": null,
"e": 33666,
"s": 33568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33675,
"s": 33666,
"text": "Comments"
},
{
"code": null,
"e": 33688,
"s": 33675,
"text": "Old Comments"
},
{
"code": null,
"e": 33715,
"s": 33688,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 33753,
"s": 33715,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 33831,
"s": 33753,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 33856,
"s": 33831,
"text": "Formatted output in Java"
},
{
"code": null,
"e": 33904,
"s": 33856,
"text": "Algorithm Library | C++ Magicians STL Algorithm"
},
{
"code": null,
"e": 33934,
"s": 33904,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33949,
"s": 33934,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34009,
"s": 33949,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34052,
"s": 34009,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Checkbox in Android using Jetpack Compose - GeeksforGeeks | 25 Feb, 2021
The checkbox is a composable function that is used to represent two states of any item in Android. It is used to differentiate an item from the list of items. In this article, we will take a look at the implementation of Simple Checkbox in Android using Jetpack Compose.
Attributes
Uses
Step 1: Create a New Project
To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.
Step 2: Working with the MainActivity.kt file
Navigate to the app > java > your appβs package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.graphics.drawable.shapes.Shapeimport android.media.Imageimport android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.compose.foundation.*import androidx.compose.foundation.Textimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material.*import androidx.compose.material.Iconimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.AccountCircleimport androidx.compose.material.icons.filled.Infoimport androidx.compose.material.icons.filled.Menuimport androidx.compose.material.icons.filled.Phoneimport androidx.compose.runtime.*import androidx.compose.runtime.savedinstancestate.savedInstanceStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.setContentimport androidx.compose.ui.res.imageResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.gfgapp.ui.GFGAppThemeimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.platform.ContextAmbientimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.res.colorResourceimport androidx.compose.ui.semantics.SemanticsProperties.ToggleableStateimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.input.*import androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.TextUnit class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Column { // in below line we are // calling a checkbox method. SimpleCheckboxComponent() } } }} @Preview(showBackground = true)@Composablefun DefaultPreview() { GFGAppTheme { SimpleCheckboxComponent(); }} @Composablefun SimpleCheckboxComponent() { // in below line we are setting // the state of our checkbox. val checkedState = remember { mutableStateOf(true) } // in below line we are displaying a row // and we are creating a checkbox in a row. Row { Checkbox( // below line we are setting // the state of checkbox. checked = checkedState.value, // below line is use to add padding // to our checkbox. modifier = Modifier.padding(16.dp), // below line is use to add on check // change to our checkbox. onCheckedChange = { checkedState.value = it }, ) // below line is use to add text to our check box and we are // adding padding to our text of checkbox Text(text = "Checkbox Example", modifier = Modifier.padding(16.dp)) }}
Now run your app and see the output of the app.
Android-Jetpack
Technical Scripter 2020
Android
Kotlin
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters | [
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 24997,
"s": 24725,
"text": "The checkbox is a composable function that is used to represent two states of any item in Android. It is used to differentiate an item from the list of items. In this article, we will take a look at the implementation of Simple Checkbox in Android using Jetpack Compose. "
},
{
"code": null,
"e": 25008,
"s": 24997,
"text": "Attributes"
},
{
"code": null,
"e": 25013,
"s": 25008,
"text": "Uses"
},
{
"code": null,
"e": 25042,
"s": 25013,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25202,
"s": 25042,
"text": "To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose."
},
{
"code": null,
"e": 25248,
"s": 25202,
"text": "Step 2: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 25453,
"s": 25248,
"text": "Navigate to the app > java > your appβs package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 25460,
"s": 25453,
"text": "Kotlin"
},
{
"code": "import android.graphics.drawable.shapes.Shapeimport android.media.Imageimport android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.compose.foundation.*import androidx.compose.foundation.Textimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material.*import androidx.compose.material.Iconimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.AccountCircleimport androidx.compose.material.icons.filled.Infoimport androidx.compose.material.icons.filled.Menuimport androidx.compose.material.icons.filled.Phoneimport androidx.compose.runtime.*import androidx.compose.runtime.savedinstancestate.savedInstanceStateimport androidx.compose.ui.Alignmentimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.setContentimport androidx.compose.ui.res.imageResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.unit.dpimport com.example.gfgapp.ui.GFGAppThemeimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.platform.ContextAmbientimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.res.colorResourceimport androidx.compose.ui.semantics.SemanticsProperties.ToggleableStateimport androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.input.*import androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.TextUnit class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Column { // in below line we are // calling a checkbox method. SimpleCheckboxComponent() } } }} @Preview(showBackground = true)@Composablefun DefaultPreview() { GFGAppTheme { SimpleCheckboxComponent(); }} @Composablefun SimpleCheckboxComponent() { // in below line we are setting // the state of our checkbox. val checkedState = remember { mutableStateOf(true) } // in below line we are displaying a row // and we are creating a checkbox in a row. Row { Checkbox( // below line we are setting // the state of checkbox. checked = checkedState.value, // below line is use to add padding // to our checkbox. modifier = Modifier.padding(16.dp), // below line is use to add on check // change to our checkbox. onCheckedChange = { checkedState.value = it }, ) // below line is use to add text to our check box and we are // adding padding to our text of checkbox Text(text = \"Checkbox Example\", modifier = Modifier.padding(16.dp)) }}",
"e": 28564,
"s": 25460,
"text": null
},
{
"code": null,
"e": 28612,
"s": 28564,
"text": "Now run your app and see the output of the app."
},
{
"code": null,
"e": 28628,
"s": 28612,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 28652,
"s": 28628,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28660,
"s": 28652,
"text": "Android"
},
{
"code": null,
"e": 28667,
"s": 28660,
"text": "Kotlin"
},
{
"code": null,
"e": 28686,
"s": 28667,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28694,
"s": 28686,
"text": "Android"
},
{
"code": null,
"e": 28792,
"s": 28694,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28801,
"s": 28792,
"text": "Comments"
},
{
"code": null,
"e": 28814,
"s": 28801,
"text": "Old Comments"
},
{
"code": null,
"e": 28853,
"s": 28814,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28903,
"s": 28853,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 28941,
"s": 28903,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 28992,
"s": 28941,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 29034,
"s": 28992,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29053,
"s": 29034,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 29066,
"s": 29053,
"text": "Kotlin Array"
},
{
"code": null,
"e": 29108,
"s": 29066,
"text": "Retrofit with Kotlin Coroutine in Android"
}
] |
How to verify color of a web element in Selenium Webdriver? | We can verify the color of a webelement in Selenium webdriver using the getCssValue method and then pass color as a parameter to it. This returnsthe color in rgba() format.
Next, we have to use the class Color to convert the rgba() format to Hex. Let us obtain the color an element highlighted in the below image. The corresponding color for the element is available under the Styles tab in Chrome browser.
The color of the element is also provided in the hex code #797979.
WebElement t = driver.findElement(By.tagName("h1"));
String s = t.getCssValue("color");
String c = Color.fromString(s).asHex();
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.Color;
public VerifyColor{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// identify text
WebElement t = driver.findElement(By.tagName("h1"));
//obtain color in rgba
String s = t.getCssValue("color");
// convert rgba to hex
String c = Color.fromString(s).asHex();
System.out.println("Color is :" + s);
System.out.println("Hex code for color:" + c);
driver.quit();
}
} | [
{
"code": null,
"e": 1235,
"s": 1062,
"text": "We can verify the color of a webelement in Selenium webdriver using the getCssValue method and then pass color as a parameter to it. This returnsthe color in rgba() format."
},
{
"code": null,
"e": 1469,
"s": 1235,
"text": "Next, we have to use the class Color to convert the rgba() format to Hex. Let us obtain the color an element highlighted in the below image. The corresponding color for the element is available under the Styles tab in Chrome browser."
},
{
"code": null,
"e": 1536,
"s": 1469,
"text": "The color of the element is also provided in the hex code #797979."
},
{
"code": null,
"e": 1664,
"s": 1536,
"text": "WebElement t = driver.findElement(By.tagName(\"h1\"));\nString s = t.getCssValue(\"color\");\nString c = Color.fromString(s).asHex();"
},
{
"code": null,
"e": 2545,
"s": 1664,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.support.Color;\npublic VerifyColor{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify text\n WebElement t = driver.findElement(By.tagName(\"h1\"));\n //obtain color in rgba\n String s = t.getCssValue(\"color\");\n // convert rgba to hex\n String c = Color.fromString(s).asHex();\n System.out.println(\"Color is :\" + s);\n System.out.println(\"Hex code for color:\" + c);\n driver.quit();\n }\n}"
}
] |
Difference between the largest and the smallest primes in an array - GeeksforGeeks | 06 May, 2021
Given an array of integers where all the elements are less than 10^6. The task is to find the difference between the largest and the smallest prime numbers in the array.Examples:
Input : Array = 1, 2, 3, 5
Output : Difference is 3
Explanation :
The largest prime number in the array is 5 and the smallest is 2
So, the difference is 3
Input : Array = 3, 5, 11, 17
Output : Difference is 14
A Simple approach: In the basic approach, we will check every element of the array whether it is prime or not. Then, select the largest and the smallest prime numbers and print the difference.Efficient approach: The efficient approach is much similar to the basic approach. We will try to reduce the time for checking the number against prime by creating a Sieve of Eratosthenes to check whether the number is prime or not in O(1) time. And then, we will select the largest and the smallest prime numbers and print the difference.Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define MAX 1000000bool prime[MAX + 1]; void SieveOfEratosthenes(){ // Create a boolean array "prime[0..n]" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. memset(prime, true, sizeof(prime)); // 1 is not prime prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} int findDiff(int arr[], int n){ // initial min max value int min = MAX + 2, max = -1; for (int i = 0; i < n; i++) { // check if the number is prime or not if (prime[arr[i]] == true) { // set the max and min values if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } } return (max == -1) ? -1 : (max - min);} // Driver codeint main(){ // create the sieve SieveOfEratosthenes(); int n = 4; int arr[n] = { 1, 2, 3, 5 }; int res = findDiff(arr, n); if (res == -1) cout << "No prime numbers" << endl; else cout << "Difference is " << res << endl; return 0;}
// java implementation of the approach import java.io.*;class GFG {static int MAX = 1000000; static boolean prime[] = new boolean[MAX + 1]; static void SieveOfEratosthenes(){ // Create a boolean array "prime[0..n]" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. //memset(prime, true, sizeof(prime)); for(int i=0;i<MAX+1;i++) prime[i] =true; // 1 is not prime prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} static int findDiff(int arr[], int n){ // initial min max value int min = MAX + 2, max = -1; for (int i = 0; i < n; i++) { // check if the number is prime or not if (prime[arr[i]] == true) { // set the max and min values if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } } return (max == -1)? -1 : (max - min);} // Driver code public static void main (String[] args) { // create the sieve SieveOfEratosthenes(); int n = 4; int arr[] = { 1, 2, 3, 5 }; int res = findDiff(arr, n); if (res == -1) System.out.print( "No prime numbers") ; else System.out.println( "Difference is " + res); }} // This code is contributed by inder_verma..
# Python 3 implementation of the approachMAX = 1000000 # Create a boolean array "prime[0..n]" and initialize# all the entries as true. A value in prime[i] will# finally be false if 'i' is Not a prime, else trueprime = [True]*(MAX+1) def SieveOfEratosthenes(): # 1 is not prime prime[1] = False p = 2 c=0 while (p * p <= MAX) : c+= 1 # If prime[p] is not changed, then it is a prime if (prime[p] == True) : # Update all multiples of p for i in range( p * 2, MAX+1 , p): prime[i] = False p += 1 def findDiff(arr, n): # initial min max value min = MAX + 2 max = -1 for i in range(n) : # check if the number is prime or not if (prime[arr[i]] == True) : # set the max and min values #print("arra ",arr[i]) #print("MAX ",max) #print(" MIN ",min) if (arr[i] > max): max = arr[i] if (arr[i] < min): min = arr[i] #print(" max ",max) return -1 if (max == -1) else (max - min) # Driver codeif __name__ == "__main__": # create the sieve SieveOfEratosthenes() n = 4 arr = [ 1, 2, 3, 5 ] res = findDiff(arr, n) if (res == -1): print("No prime numbers") else: print("Difference is " ,res ) # this code is contributed by# ChitraNayal
// C# implementation of the approachusing System; class GFG{static int MAX = 1000000; static bool []prime = new bool[MAX + 1]; static void SieveOfEratosthenes(){ // Create a boolean array "prime[0..n]" // and initialize all the entries as // true. A value in prime[i] will // finally be false if 'i' is Not a // prime, else true. // memset(prime, true, sizeof(prime)); for(int i = 0; i < MAX + 1; i++) prime[i] = true; // 1 is not prime prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} static int findDiff(int []arr, int n){ // initial min max value int min = MAX + 2, max = -1; for (int i = 0; i < n; i++) { // check if the number is prime or not if (prime[arr[i]] == true) { // set the max and min values if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } } return (max == -1) ? -1 : (max - min);} // Driver codepublic static void Main (){ // create the sieve SieveOfEratosthenes(); int n = 4; int []arr = { 1, 2, 3, 5 }; int res = findDiff(arr, n); if (res == -1) Console.WriteLine( "No prime numbers") ; else Console.WriteLine( "Difference is " + res);}} // This code is contributed by inder_verma
<script>// Javascript implementation of above approachMAX = 1000000;prime = new Array(MAX + 1);function SieveOfEratosthenes(){ // Create a boolean array "prime[0..n]" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. prime.fill(true); // 1 is not prime prime[1] = false; for (var p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (var i = p * 2; i <= MAX; i += p) prime[i] = false; } }} function findDiff(arr, n){ // initial min max value var min = MAX + 2, max = -1; for (var i = 0; i < n; i++) { // check if the number is prime or not if (prime[arr[i]] == true) { // set the max and min values if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } } return (max == -1)? -1 : (max - min);} SieveOfEratosthenes();var n = 4;var arr = [ 1, 2, 3, 5 ]; var res = findDiff(arr, n); if (res == -1) document.write( "No prime numbers" + "<br>" );else document.write( "Difference is " + res + "<br>" ); // This code is contributed by SoumikMondal</script>
Difference is 3
inderDuMCA
ukasp
SoumikMondal
Prime Number
sieve
Arrays
Competitive Programming
Arrays
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Program to find sum of elements in a given array
Building Heap from Array
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Top 10 Algorithms and Data Structures for Competitive Programming
Bits manipulation (Important tactics) | [
{
"code": null,
"e": 24821,
"s": 24793,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 25002,
"s": 24821,
"text": "Given an array of integers where all the elements are less than 10^6. The task is to find the difference between the largest and the smallest prime numbers in the array.Examples: "
},
{
"code": null,
"e": 25214,
"s": 25002,
"text": "Input : Array = 1, 2, 3, 5\nOutput : Difference is 3\nExplanation :\nThe largest prime number in the array is 5 and the smallest is 2\nSo, the difference is 3\n \nInput : Array = 3, 5, 11, 17\nOutput : Difference is 14"
},
{
"code": null,
"e": 25799,
"s": 25216,
"text": "A Simple approach: In the basic approach, we will check every element of the array whether it is prime or not. Then, select the largest and the smallest prime numbers and print the difference.Efficient approach: The efficient approach is much similar to the basic approach. We will try to reduce the time for checking the number against prime by creating a Sieve of Eratosthenes to check whether the number is prime or not in O(1) time. And then, we will select the largest and the smallest prime numbers and print the difference.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25803,
"s": 25799,
"text": "C++"
},
{
"code": null,
"e": 25808,
"s": 25803,
"text": "Java"
},
{
"code": null,
"e": 25817,
"s": 25808,
"text": "Python 3"
},
{
"code": null,
"e": 25820,
"s": 25817,
"text": "C#"
},
{
"code": null,
"e": 25831,
"s": 25820,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define MAX 1000000bool prime[MAX + 1]; void SieveOfEratosthenes(){ // Create a boolean array \"prime[0..n]\" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. memset(prime, true, sizeof(prime)); // 1 is not prime prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} int findDiff(int arr[], int n){ // initial min max value int min = MAX + 2, max = -1; for (int i = 0; i < n; i++) { // check if the number is prime or not if (prime[arr[i]] == true) { // set the max and min values if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } } return (max == -1) ? -1 : (max - min);} // Driver codeint main(){ // create the sieve SieveOfEratosthenes(); int n = 4; int arr[n] = { 1, 2, 3, 5 }; int res = findDiff(arr, n); if (res == -1) cout << \"No prime numbers\" << endl; else cout << \"Difference is \" << res << endl; return 0;}",
"e": 27211,
"s": 25831,
"text": null
},
{
"code": "// java implementation of the approach import java.io.*;class GFG {static int MAX = 1000000; static boolean prime[] = new boolean[MAX + 1]; static void SieveOfEratosthenes(){ // Create a boolean array \"prime[0..n]\" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. //memset(prime, true, sizeof(prime)); for(int i=0;i<MAX+1;i++) prime[i] =true; // 1 is not prime prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} static int findDiff(int arr[], int n){ // initial min max value int min = MAX + 2, max = -1; for (int i = 0; i < n; i++) { // check if the number is prime or not if (prime[arr[i]] == true) { // set the max and min values if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } } return (max == -1)? -1 : (max - min);} // Driver code public static void main (String[] args) { // create the sieve SieveOfEratosthenes(); int n = 4; int arr[] = { 1, 2, 3, 5 }; int res = findDiff(arr, n); if (res == -1) System.out.print( \"No prime numbers\") ; else System.out.println( \"Difference is \" + res); }} // This code is contributed by inder_verma..",
"e": 28756,
"s": 27211,
"text": null
},
{
"code": "# Python 3 implementation of the approachMAX = 1000000 # Create a boolean array \"prime[0..n]\" and initialize# all the entries as true. A value in prime[i] will# finally be false if 'i' is Not a prime, else trueprime = [True]*(MAX+1) def SieveOfEratosthenes(): # 1 is not prime prime[1] = False p = 2 c=0 while (p * p <= MAX) : c+= 1 # If prime[p] is not changed, then it is a prime if (prime[p] == True) : # Update all multiples of p for i in range( p * 2, MAX+1 , p): prime[i] = False p += 1 def findDiff(arr, n): # initial min max value min = MAX + 2 max = -1 for i in range(n) : # check if the number is prime or not if (prime[arr[i]] == True) : # set the max and min values #print(\"arra \",arr[i]) #print(\"MAX \",max) #print(\" MIN \",min) if (arr[i] > max): max = arr[i] if (arr[i] < min): min = arr[i] #print(\" max \",max) return -1 if (max == -1) else (max - min) # Driver codeif __name__ == \"__main__\": # create the sieve SieveOfEratosthenes() n = 4 arr = [ 1, 2, 3, 5 ] res = findDiff(arr, n) if (res == -1): print(\"No prime numbers\") else: print(\"Difference is \" ,res ) # this code is contributed by# ChitraNayal",
"e": 30192,
"s": 28756,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{static int MAX = 1000000; static bool []prime = new bool[MAX + 1]; static void SieveOfEratosthenes(){ // Create a boolean array \"prime[0..n]\" // and initialize all the entries as // true. A value in prime[i] will // finally be false if 'i' is Not a // prime, else true. // memset(prime, true, sizeof(prime)); for(int i = 0; i < MAX + 1; i++) prime[i] = true; // 1 is not prime prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } }} static int findDiff(int []arr, int n){ // initial min max value int min = MAX + 2, max = -1; for (int i = 0; i < n; i++) { // check if the number is prime or not if (prime[arr[i]] == true) { // set the max and min values if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } } return (max == -1) ? -1 : (max - min);} // Driver codepublic static void Main (){ // create the sieve SieveOfEratosthenes(); int n = 4; int []arr = { 1, 2, 3, 5 }; int res = findDiff(arr, n); if (res == -1) Console.WriteLine( \"No prime numbers\") ; else Console.WriteLine( \"Difference is \" + res);}} // This code is contributed by inder_verma",
"e": 31755,
"s": 30192,
"text": null
},
{
"code": "<script>// Javascript implementation of above approachMAX = 1000000;prime = new Array(MAX + 1);function SieveOfEratosthenes(){ // Create a boolean array \"prime[0..n]\" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. prime.fill(true); // 1 is not prime prime[1] = false; for (var p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (var i = p * 2; i <= MAX; i += p) prime[i] = false; } }} function findDiff(arr, n){ // initial min max value var min = MAX + 2, max = -1; for (var i = 0; i < n; i++) { // check if the number is prime or not if (prime[arr[i]] == true) { // set the max and min values if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } } return (max == -1)? -1 : (max - min);} SieveOfEratosthenes();var n = 4;var arr = [ 1, 2, 3, 5 ]; var res = findDiff(arr, n); if (res == -1) document.write( \"No prime numbers\" + \"<br>\" );else document.write( \"Difference is \" + res + \"<br>\" ); // This code is contributed by SoumikMondal</script>",
"e": 33085,
"s": 31755,
"text": null
},
{
"code": null,
"e": 33101,
"s": 33085,
"text": "Difference is 3"
},
{
"code": null,
"e": 33114,
"s": 33103,
"text": "inderDuMCA"
},
{
"code": null,
"e": 33120,
"s": 33114,
"text": "ukasp"
},
{
"code": null,
"e": 33133,
"s": 33120,
"text": "SoumikMondal"
},
{
"code": null,
"e": 33146,
"s": 33133,
"text": "Prime Number"
},
{
"code": null,
"e": 33152,
"s": 33146,
"text": "sieve"
},
{
"code": null,
"e": 33159,
"s": 33152,
"text": "Arrays"
},
{
"code": null,
"e": 33183,
"s": 33159,
"text": "Competitive Programming"
},
{
"code": null,
"e": 33190,
"s": 33183,
"text": "Arrays"
},
{
"code": null,
"e": 33203,
"s": 33190,
"text": "Prime Number"
},
{
"code": null,
"e": 33209,
"s": 33203,
"text": "sieve"
},
{
"code": null,
"e": 33307,
"s": 33209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33332,
"s": 33307,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33352,
"s": 33332,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 33390,
"s": 33352,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 33439,
"s": 33390,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33464,
"s": 33439,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 33507,
"s": 33464,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 33550,
"s": 33507,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 33591,
"s": 33550,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 33657,
"s": 33591,
"text": "Top 10 Algorithms and Data Structures for Competitive Programming"
}
] |
Convert a list of multiple integers into a single integer in Python | Sometimes we may have a list whose elements are integers. There may be a need to combine all these elements and create a single integer out of it. In this article we will explore the ways to do that.
The join method can Join all items in a tuple into a string. So we will use it to join each element of the list by iterating through them through a for loop.
Live Demo
listA = [22,11,34]
# Given list
print("Given list A: ", listA)
# Use
res = int("".join([str(i) for i in listA]))
# Result
print("The integer is : ",res)
Running the above code gives us the following result β
Given list A: [22, 11, 34]
The integer is : 221134
We can apply the map function to convert each element of the list into a string and then join each of them to form a final list. Applying the int function makes the final result an integer.
Live Demo
listA = [22,11,34]
# Given list
print("Given list A: ", listA)
# Use
res = int("".join(map(str, listA)))
# Result
print("The integer is : ",res)
Running the above code gives us the following result β
Given list A: [22, 11, 34]
The integer is : 221134 | [
{
"code": null,
"e": 1262,
"s": 1062,
"text": "Sometimes we may have a list whose elements are integers. There may be a need to combine all these elements and create a single integer out of it. In this article we will explore the ways to do that."
},
{
"code": null,
"e": 1420,
"s": 1262,
"text": "The join method can Join all items in a tuple into a string. So we will use it to join each element of the list by iterating through them through a for loop."
},
{
"code": null,
"e": 1431,
"s": 1420,
"text": " Live Demo"
},
{
"code": null,
"e": 1584,
"s": 1431,
"text": "listA = [22,11,34]\n# Given list\nprint(\"Given list A: \", listA)\n# Use\nres = int(\"\".join([str(i) for i in listA]))\n# Result\nprint(\"The integer is : \",res)"
},
{
"code": null,
"e": 1639,
"s": 1584,
"text": "Running the above code gives us the following result β"
},
{
"code": null,
"e": 1690,
"s": 1639,
"text": "Given list A: [22, 11, 34]\nThe integer is : 221134"
},
{
"code": null,
"e": 1880,
"s": 1690,
"text": "We can apply the map function to convert each element of the list into a string and then join each of them to form a final list. Applying the int function makes the final result an integer."
},
{
"code": null,
"e": 1891,
"s": 1880,
"text": " Live Demo"
},
{
"code": null,
"e": 2036,
"s": 1891,
"text": "listA = [22,11,34]\n# Given list\nprint(\"Given list A: \", listA)\n# Use\nres = int(\"\".join(map(str, listA)))\n# Result\nprint(\"The integer is : \",res)"
},
{
"code": null,
"e": 2091,
"s": 2036,
"text": "Running the above code gives us the following result β"
},
{
"code": null,
"e": 2142,
"s": 2091,
"text": "Given list A: [22, 11, 34]\nThe integer is : 221134"
}
] |
Plot multiple columns of Pandas DataFrame using Seaborn | To plot multiple columns of Pandas DataFrame using Seaborn, we can take the following steps β
Make a dataframe using Pandas.
Make a dataframe using Pandas.
Plot a bar using Seaborn's barplot() method.
Plot a bar using Seaborn's barplot() method.
Rotate the xticks label by 45 angle.
Rotate the xticks label by 45 angle.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas
import matplotlib.pylab as plt
import seaborn as sns
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pandas.DataFrame({"X-Axis": [np.random.randint(10) for i in range(10)], "YAxis": [i for i in range(10)]})
bar_plot = sns.barplot(x='X-Axis', y='Y-Axis', data=df)
plt.xticks(rotation=45)
plt.show() | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "To plot multiple columns of Pandas DataFrame using Seaborn, we can take the following steps β"
},
{
"code": null,
"e": 1187,
"s": 1156,
"text": "Make a dataframe using Pandas."
},
{
"code": null,
"e": 1218,
"s": 1187,
"text": "Make a dataframe using Pandas."
},
{
"code": null,
"e": 1263,
"s": 1218,
"text": "Plot a bar using Seaborn's barplot() method."
},
{
"code": null,
"e": 1308,
"s": 1263,
"text": "Plot a bar using Seaborn's barplot() method."
},
{
"code": null,
"e": 1345,
"s": 1308,
"text": "Rotate the xticks label by 45 angle."
},
{
"code": null,
"e": 1382,
"s": 1345,
"text": "Rotate the xticks label by 45 angle."
},
{
"code": null,
"e": 1424,
"s": 1382,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1466,
"s": 1424,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1841,
"s": 1466,
"text": "import pandas\nimport matplotlib.pylab as plt\nimport seaborn as sns\nimport numpy as np\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndf = pandas.DataFrame({\"X-Axis\": [np.random.randint(10) for i in range(10)], \"YAxis\": [i for i in range(10)]})\nbar_plot = sns.barplot(x='X-Axis', y='Y-Axis', data=df)\nplt.xticks(rotation=45)\nplt.show()"
}
] |
How do I import all the submodules of a Python namespace package? | The "from module import *" statement is used to import all submodules from a Python package/module. For example, if you want to import all modules from your module(say nyModule) and do not want to prefix "myModule." while calling them, you can do it as follows:
>>> from myModule import *
Note that for any reasonable large set of code, if you import * you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use the import any more but it's extremely difficult to be sure. It basically clutters the namespace and leaves you with lesser options to name things in your module. | [
{
"code": null,
"e": 1324,
"s": 1062,
"text": "The \"from module import *\" statement is used to import all submodules from a Python package/module. For example, if you want to import all modules from your module(say nyModule) and do not want to prefix \"myModule.\" while calling them, you can do it as follows:"
},
{
"code": null,
"e": 1351,
"s": 1324,
"text": ">>> from myModule import *"
},
{
"code": null,
"e": 1813,
"s": 1351,
"text": "Note that for any reasonable large set of code, if you import * you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use the import any more but it's extremely difficult to be sure. It basically clutters the namespace and leaves you with lesser options to name things in your module."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.