title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Stream builder() in Java with Examples
|
06 Dec, 2018
Stream builder() returns a builder for a Stream.
Syntax :
static <T> Stream.Builder<T> builder()
where, T is the type of elements.
Return Value : A stream builder.
Example 1 :
// Java code for Stream builder()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add("Geeks").build(); // Displaying the elements in the stream stream.forEach(System.out::println); }}
Output :
Geeks
Example 2 :
// Java code for Stream builder()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add("Geeks") .add("for") .add("Geeks") .add("GeeksQuiz") .build(); // Displaying the elements in the stream stream.forEach(System.out::println); }}
Output :
Geeks
for
Geeks
GeeksQuiz
Example 3 :
// Java code for Stream builder()import java.util.*;import java.util.stream.Stream;import java.util.stream.Collectors; class GFG { // Driver code public static void main(String[] args) { // Using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add("GEEKS") .add("for") .add("Geeks") .add("GeEKSQuiz") .build(); // Converting elements to Lower Case // and storing them in List list List<String> list = stream.map(String::toLowerCase) .collect(Collectors.toList()); // Displaying the elements in list System.out.println(list); }}
Output :
[geeks, for, geeks, geeksquiz]
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": 53,
"s": 25,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 102,
"s": 53,
"text": "Stream builder() returns a builder for a Stream."
},
{
"code": null,
"e": 111,
"s": 102,
"text": "Syntax :"
},
{
"code": null,
"e": 186,
"s": 111,
"text": "static <T> Stream.Builder<T> builder()\n\nwhere, T is the type of elements.\n"
},
{
"code": null,
"e": 219,
"s": 186,
"text": "Return Value : A stream builder."
},
{
"code": null,
"e": 231,
"s": 219,
"text": "Example 1 :"
},
{
"code": "// Java code for Stream builder()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add(\"Geeks\").build(); // Displaying the elements in the stream stream.forEach(System.out::println); }}",
"e": 700,
"s": 231,
"text": null
},
{
"code": null,
"e": 709,
"s": 700,
"text": "Output :"
},
{
"code": null,
"e": 716,
"s": 709,
"text": "Geeks\n"
},
{
"code": null,
"e": 728,
"s": 716,
"text": "Example 2 :"
},
{
"code": "// Java code for Stream builder()import java.util.*;import java.util.stream.Stream; class GFG { // Driver code public static void main(String[] args) { // Using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add(\"Geeks\") .add(\"for\") .add(\"Geeks\") .add(\"GeeksQuiz\") .build(); // Displaying the elements in the stream stream.forEach(System.out::println); }}",
"e": 1382,
"s": 728,
"text": null
},
{
"code": null,
"e": 1391,
"s": 1382,
"text": "Output :"
},
{
"code": null,
"e": 1418,
"s": 1391,
"text": "Geeks\nfor\nGeeks\nGeeksQuiz\n"
},
{
"code": null,
"e": 1430,
"s": 1418,
"text": "Example 3 :"
},
{
"code": "// Java code for Stream builder()import java.util.*;import java.util.stream.Stream;import java.util.stream.Collectors; class GFG { // Driver code public static void main(String[] args) { // Using Stream builder() Stream.Builder<String> builder = Stream.builder(); // Adding elements in the stream of Strings Stream<String> stream = builder.add(\"GEEKS\") .add(\"for\") .add(\"Geeks\") .add(\"GeEKSQuiz\") .build(); // Converting elements to Lower Case // and storing them in List list List<String> list = stream.map(String::toLowerCase) .collect(Collectors.toList()); // Displaying the elements in list System.out.println(list); }}",
"e": 2309,
"s": 1430,
"text": null
},
{
"code": null,
"e": 2318,
"s": 2309,
"text": "Output :"
},
{
"code": null,
"e": 2350,
"s": 2318,
"text": "[geeks, for, geeks, geeksquiz]\n"
},
{
"code": null,
"e": 2370,
"s": 2350,
"text": "Java - util package"
},
{
"code": null,
"e": 2385,
"s": 2370,
"text": "Java-Functions"
},
{
"code": null,
"e": 2397,
"s": 2385,
"text": "java-stream"
},
{
"code": null,
"e": 2419,
"s": 2397,
"text": "Java-Stream interface"
},
{
"code": null,
"e": 2424,
"s": 2419,
"text": "Java"
},
{
"code": null,
"e": 2429,
"s": 2424,
"text": "Java"
}
] |
Practice | GeeksforGeeks | A computer science portal for geeks
|
Popular Company Tags
Amazon
Microsoft
Oracle
Samsung
Adobe
Synopsys
Infosys
Cisco
Wipro
Ola-Cabs
Morgan-Stanley
Goldman-Sachs
show more
Amazon
Microsoft
Oracle
Samsung
Adobe
Synopsys
Infosys
Cisco
Wipro
Ola-Cabs
Morgan-Stanley
Goldman-Sachs
Popular Topic Tags
Maths
Array
Dynamic-Programming
Greedy-Algorithm
Hashing
Tree
Bit-Algorithm
Matrix
Backtracking
Operating System
Linked-List
Graph
show more
Maths
Array
Dynamic-Programming
Greedy-Algorithm
Hashing
Tree
Bit-Algorithm
Matrix
Backtracking
Operating System
Linked-List
Graph
Home
Aman Chauhan 1
Subjective Answers
Home
Aman Chauhan 1
Subjective Answers
A formalized set of software calls and routines that can be referenced by an application program in order to access supporting system or network services.
Verifying a product is accessible to the people having disabilities (deaf, blind, mentally disabled etc.).
A set of activities conducted with the intent of finding errors in software.
There are two tasks with specially distinguished process IDs: swapper or sched has process ID 0 and is responsible for paging, and is actually part of the kernel rather than a normal user-mode process. Process ID 1 is usually the init process primarily responsible for starting and shutting down the system.
Job scheduling is the process of allocating system resources to many different tasks by an operating system (OS). The system handles prioritized job queues that are awaiting CPU time and it should determine which job to be taken from which queue and the amount of time to be allocated for the job.
A scheduler may aim at one of many goals, for example, maximizing throughput (the total amount of work completed per time unit), minimizing response time (time from work becoming enabled until the first point it begins execution on resources), or minimizing latency (the time between work becoming enabled and its subsequent completion),maximizing fairness (equal CPU time to each process, or more generally appropriate times according to the priority and workload of each process). In practice, these goals often conflict
In computing, a web application or web app is a client–server software application in which the client (or user interface) runs in a web browser. Common web applications include webmail, online retail sales, online auctions, wikis, instant messaging services and many other functions.
Security testing is a process intended to reveal flaws in the security mechanisms of an information system that protect data and maintain functionality as intended.
Creating a REST API sesssion is similar to logging in to using a web browser. The only difference is that a web browser (in the typical sense) is never used. Instead, you need an application capable of sending and receiving HTTP requests—a REST client. REST clients are different than web browsers, although some REST clients are built on-top of web browsers like Chromium because they share interchangeable parts.
Event Viewer is a component of Microsoft's Windows NT line of operating systems that lets administrators and users view the event logs on a local or remote machine. In Windows Vista, Microsoft overhauled the event system.
Database tests are typically a three-step process:
Setup the test. You need to put your database into a known state before running tests against it. ...
Run the test. Using a database regression testing tool, run your database tests just like you would run your application tests.
Check the results.
Setup the test. You need to put your database into a known state before running tests against it. ...
Run the test. Using a database regression testing tool, run your database tests just like you would run your application tests.
Check the results.
Each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.
The prefixes of right sentential forms that can appear on the stack of a shift-reduce parser are called viable prefixes. By definition, a viable prefix is a prefix of a right sentential form that does not continue past the right end of the rightmost handle of that sentential form.
In computer science, an operator precedence parser is a bottom-up parser that interprets an operator-precedence grammar. ... Edger Dijkstra's shunting yard algorithm is commonly used to implement operator precedence parsers.
A “handle” of a string is a substring that matches the RHS of a production and whose reduction to the non-terminal (on the LHS of the production) represents one step along the reverse of a rightmost derivation toward reducing to the start symbol.
Early Binding and Late binding. The compiler performs a process called binding when an object is assigned to an object variable. The early binding (static binding) refers to compile time binding and late binding (dynamic binding) refers to runtime binding.
RecyclerView was created as a ListView improvement, so yes, you can create an attached list with ListView control, but using RecyclerView is easier as it:
Reuses cells while scrolling up/down - this is possible with implementing View Holder in the listView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.
Decouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.
Reuses cells while scrolling up/down - this is possible with implementing View Holder in the listView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.
Reuses cells while scrolling up/down - this is possible with implementing View Holder in the listView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.
Decouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.
Decouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.
singleTask :- A new task will always be created and a new instance will be pushed to the task as the root. However, if any activity instance exists in any tasks, the system routes the intent to that activity instance through the onNewIntent() method call. In this mode, activity instances can be pushed to the same task. This mode is useful for activities that act as the entry points.
single Top:- Same as singleTask, except that the no activities instance can be pushed into the same task of the single Top. Accordingly, the activity with launch mode is always in a single activity instance task. This is a very specialized mode and should only be used in applications that are implemented entirely as one activity.
Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.
Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.
Pragma is used inside the servlets in the header with a certain value. The value is of no-cache that tells that a servlets is acting as a proxy and it has to forward request. Pragma directives allow the compiler to use machine and operating system features while keeping the overall functionality with the Java language. These are different for different compilers.
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. For example, closing a opened file, closing a opened database Connection.
Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.
It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server.
A Translation lookaside buffer (TLB) is a memory cache that is used to reduce the time taken to access a user memory location. It is a part of the chip's memory-management unit (MMU). The TLB stores the recent translations of virtual memory to physical memory and can be called an address-translation cache.
NSLOOKUP is a program to query Internet domain name servers (DNS). NSLOOKUP or Reverse DNS (rDNS) is a method of resolving an IP address into a domain name, just as the domain name system (DNS) resolves domain names into associated IP addresses.
The Domain Name System (aka DNS) is used to resolve human-readable hostnames like www.Dyn.com into machine-readable IP addresses like 204.13.248.115. DNS also provides other information about domain names, such as mail services.
The hash function is used to index the original value or key and then used later each time the data associated with the value or key is to be retrieved. Thus, hashing is always a one-way operation. There's no need to "reverse engineer" the hash function by analyzing the hashed values.
Text files contain data that can easily be understood by humans. It includes letters, numbers and other characters. On the other hand, binary files contain 1s and 0s that only computers can interpret.
Dynamic data structure provides a means for storing data more efficiently into memory. Using dynamic memory allocation, your program will access memory spaces as needed. This is in contrast to static data structure, wherein the programmer has to indicate a fix number of memory space to be used in the program.
It is used to convert any letter to its upper case mode. Toupper() function prototype is declared in . Note that this function will only convert a single character, and not an entire string.
It is the process of transferring data to an alternative output source other than the display screen. Output redirection allows a program to have its output saved to a file. For example, if you have a program named COMPUTE, typing this on the command line as COMPUTE >DATA can accept input from the user, perform certain computations, then have the output redirected to a file named DATA, instead of showing it on the screen.
Reserved words are words that are part of the standard C language library. This means that reserved words have special meaning and therefore cannot be used for purposes other than what it is originally intended for. Examples of reserved words are int, void, and return.
It is referred to as a terminating null character, and is used primarily to show the end of a string value.
Spaghetti programming refers to codes that tend to get tangled and overlapped throughout the program. This unstructured approach to coding is usually attributed to lack of experience on the part of the programmer. Spaghetti programming makes a program complex and analyzing the codes difficult, and so must be avoided as much as possible.
Merging is the sorting algorithm which combines two or more sorted sequences into a single sorted sequence. It is a divide and conquer algorithm, an O(n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, meaning that the implementation preserves the input order of equal elements in the sorted output.
It is an algorithm that considers systematically all possible outcomes for each decision. Examples of backtracking algorithms are the eight queens problem or generating permutations of a given sequence.
If software misses some feature or function from what is there in requirement it is called as defect.
The Socket is a Combination of Ip address and Port Number (in pairs)
Session is a Logical Connectivity between the source and destination .
The inverted page table scheme uses a page table that contains an entry for each physical frame, not for each logical page. This ensures that the table occupies a fixed fraction of memory. The size is proportional to physical memory, not the virtual address space.
The Heterogeneous Services data dictionary views, whose names all begin with the HS_ prefix, can be divided into the following categories:
General views
General views
Views used for the transaction service
Views used for the transaction service
Views used for the SQL service .
Views used for the SQL service .
A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
exec is a functionality of an operating system that runs an executable file in the context of an already existing process, replacing the previous executable. This act is also referred to as an overlay. It is especially important in Unix-like systems, although exists elsewhere.
for detail :http://www.geeksforgeeks.org/exec-family-of-functions-in-c/
System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork().
Demand paging (as opposed to anticipatory paging) is a method of virtual memory management. It follows that a process begins execution with none of its pages in physical memory, and many page faults will occur until most of a process's working set of pages is located in physical memory.
Address registers - contain main memory addresses of data and instructions or they contain a portion of the address that is used in the calculation of the complete addresses.
Data registers - can be assigned to a variety of functions by the programmer.
They can be used with any machine instruction that performs operations on data.
Paging is solution to external fragmentation problem which is to permit the logical address space of a process to be non contiguous, thus allowing a process to be allocating physical memory wherever the latter is available.
1NF is the First Normal Form. It is the simplest type of normalization that you can implement in a database. The main objectives of 1NF are to:
Remove duplicate columns from the same table
Create separate tables for each group of related data and identify each row with a unique column
Extension: Extension is the number of tuples present in a table at any instance. This is time dependent.
Intension: Intension is a constant value that gives the name, structure of table and the constraints laid on it.
Relational Calculus is a Non-procedural Query Language which uses mathematical predicate calculus instead of algebra.
Interface is a blueprint of a class that have static constants and abstract methods.It can be used to achieve fully abstraction and multiple inheritance.
The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
The shutdown hook is basically a thread i.e. invoked implicitly before JVM shuts down. So we can use it perform clean up resource.
The thread executing this method, obtains one lock at a time. First, copies the state of the given person object into local variables using one lock. It then, uses these variables to transfer the state to the current object using another lock. This approach mitigated deadlocks by removing lock overlapping.
A thread pool is a software design pattern for achieving concurrency of execution in a computer program. Often also called a replicated workers or worker-crew model, a thread pool maintains multiple threads waiting for tasks to be allocated for concurrent execution by the supervising program.
Static methods cannot be overridden because method overriding only occurs in the context of dynamic (i.e. runtime) lookup of methods. Static methods (by their name) are looked up statically (i.e. at compile-time). Method overriding happens in the type of subtype polymorphism that exists in languages like Java and C++.
for detail refers:http://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/
Fail-Fast iterators, returned by most of the collection types, doesn’t tolerate any structural modifications to a collection while iterating over it. (Structural modifications means add, remove or updating an element in the collection) They throw ConcurrentModificationException if a collection is structurally modified while iteration is going on the collection.
In systems design, a fail-fast system is one which immediately reports at its interface any condition that is likely to indicate a failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly flawed process. Such designs often check the system's state at several points in an operation, so any failures can be detected early. A fail-fast module passes the responsibility for handling errors, but not detecting them, to the next-highest level of the system.
A connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required. Connection pools are used to enhance the performance of executing commands on a database.
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.
Performance testing focused on ensuring the application under test gracefully handles increases in work load.
A standard of measurement. Software metrics are the statistics describing the structure or content of a program. A metric should be a real objective measurement of something such as number of bugs per lines of code.
A device, computer program, or system that accepts the same inputs and produces the same outputs as a given system.
DNS uses UDP for communication between servers. It is a better choice than TCP because of the improved speed a connectionless protocol offers. Of course, transmission reliability suffers with UDP.
In concurrent programming, a monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become true. Monitors also have a mechanism for signaling other threads that their condition has been met.
for detail :http://www.geeksforgeeks.org/monitors/
Stock market prediction is the act of trying to determine the future value of a company stock or other financial instrument traded on an exchange. The successful prediction of a stock's future price could yield significant profit. The efficient-market hypothesis suggests that stock prices reflect all currently available information and any price changes that are not based on newly revealed information thus are inherently unpredictable. Others disagree and those with this viewpoint possess myriad methods and technologies which purportedly allow them to gain future price information.
SQL NOT NULL Constraint. By default, a column can hold NULL values. The NOTNULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.
A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table. The unique key and primary key both provide a guarantee for uniqueness for a column or a set of columns. There is an automatically defined unique key constraint within a primary key constraint.
This is a primary file organization technique that provides very fast access to records on certain search conditions.
The description of a data base is called the database schema , which is specified during database design and is not expected to change frequently . A displayed schema is called schema diagram .We call each object in the schema as schema construct.
This is another recursion procedure which is the number of times the procedure is called recursively in the process of enlarging a given argument or arguments. Usually this quantity is not obvious except in the case of extremely simple recursive functions, such as FACTORIAL (N), for which the depth is N.
a semaphore is a variable or abstract data type used to control access to a common resource by multiple processes in a concurrent system such as a multiprogramming operating system.
Semaphores are widely used to control access to files and shared memory. The three basic functionalities associated with semaphores are set, check and wait until it clears to set it again. |
Semaphores are used to address benchmark synchronization problems.
In system programming, an interrupt is a signal to the processor emitted by hardware or software indicating an event that needs immediate attention. An interrupt alerts the processor to a high-priority condition requiring the interruption of the current code the processor is executing.
A memory management unit (MMU), sometimes called paged memory management unit (PMMU), is a computer hardware unit having all memory references passed through itself, primarily performing the translation of virtual memory addresses to physical addresses.
Thread safety is a computer programming concept applicable to multi-threaded code.Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfil their design specifications without unintended interaction.
A function is reentrant if it can be invoked while already in the process of executing. That is, a function is reentrant if it can be interrupted in the middle of execution (for example, by a signal or interrupt) and invoked again before the interrupted execution completes.
A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior.
for detail:http://www.geeksforgeeks.org/function-pointer-in-c/
In computer science, a smart pointer is an abstract data type that simulates a pointer while providing added features, such as automatic memory management or bounds checking. Such features are intended to reduce bugs caused by the misuse ofpointers, while retaining efficiency.
Lambda Expressions.
Automatic Type Deduction and decltype.
Uniform Initialization Syntax.
Deleted and Defaulted Functions.
nullptr.
Delegating Constructors.
Rvalue References.
C++11 Standard Library. etc
A bitset stores bits (elements with only two possible values: 0 or 1, true or false).The class emulates an array of bool elements, but optimized for space allocation: generally, each element occupies only one bit (which, on most systems, is eight times less than the smallest elemental type: char ).
Mutual Exclusion: There is s resource that cannot be shared.
Hold and Wait: A process is holding at least one resource and waiting for another resource which is with some other process.
No Preemption: The operating system is not allowed to take a resource back from a process until process gives it back.
Circular Wait: A set of processes are waiting for each other in circular form.
The set of dispatchable processes is in a safe state if there exists at least one temporal order in which all processes can be run to completion without resulting in a deadlock.
Dynamic Ram stores the data in the form of Capacitance, and Static RAM stores the data in Voltages.
Array is static in size while ArrayList is dynamic
Primitive Data Type: ArrayList cannot contain primitive data types while Array can contain both primitive objects as well as data types
Length: Length of ArrayList is defined by size() method while that of Array has variable length .
Length of the ArrayList is provided by the size() method while Each array object has the length variable which returns the length of the array.
Array is static in size while ArrayList is dynamic
Primitive Data Type: ArrayList cannot contain primitive data types while Array can contain both primitive objects as well as data types
Length: Length of ArrayList is defined by size() method while that of Array has variable length .
Length of the ArrayList is provided by the size() method while Each array object has the length variable which returns the length of the array.
The ArrayList class extends Abstract List and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.
Hashmaps and hashtables are data structures (like arrays and lists), that use hashing to store data. In a hashtable, a hash is produced (either from a provided key, or from the object itself) that determines where in the table the object is stored.
for detail :http://www.geeksforgeeks.org/hashmap-treemap-java/
Type safe languages (like C++) have the advantage that many errors are found at compile time (as opposed to run-time). That means using Qt.grey (note the e) would fail to compile because the type is not defined.
Better performance and less memory. Behind the scenes Qt.gray is a number, and number operations are much faster than strings.
Type safe languages (like C++) have the advantage that many errors are found at compile time (as opposed to run-time). That means using Qt.grey (note the e) would fail to compile because the type is not defined.
Type safe languages (like C++) have the advantage that many errors are found at compile time (as opposed to run-time). That means using Qt.grey (note the e) would fail to compile because the type is not defined.
Better performance and less memory. Behind the scenes Qt.gray is a number, and number operations are much faster than strings.
Better performance and less memory. Behind the scenes Qt.gray is a number, and number operations are much faster than strings.
A data type, in programming, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error. A string, for example, is a data type that is used to classify text and an integer is a data type used to classify whole numbers.
Reduce the redundancy.
A large amount added bendable database design.
Better overall database association.
Data uniformity inside the database.
External sorting is a term for a class of sorting algorithms that can handle massive amounts of data.External sorting is required when the data being sorted do not fit into the main memory of a computing device (usually RAM) and instead they must reside in the slower external memory (usually a hard drive).
Image map facilitates you link many different web pages using a single image. You can define shapes in images that you want to make part of an image mapping.
Semantic HTML is a coding style. It is the use of HTML markup to reinforce the semantics or meaning of the content. For example: In semantic HTML <b> </b> tag is not used for bold statement as well as <i> </i> tag is used for italic. Instead of these we use <strong></strong> and <em></em> tags.
For indexes to improve the performance of selections, the index expression must match the selection condition exactly. For example, if you have created an index whose expression is last_name, the following Select statement uses the index:
SELECT * FROM emp WHERE last_name = 'Smith'
As long as your query is "covered" by a leading edge of an index, it will be efficient. Database indexes are typically implemented as B-Trees and the structure of the B-Tree dictates that the search must be done in a certain order, which is why the order of fields in the composite index matters.
A secondary index is a data structure that contains a subset of attributes from a table, along with an alternate key to support Query operations. You can retrieve data from the index using a Query , in much the same way as you use Query with a table.
A primary index is an index on a set of fields that includes the unique primary key for the field and is guaranteed not to contain duplicates. Also Called a Clustered index.
eg. Employee ID .
Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit characteristics and features from more than one parent object or parent class.
Proactive behavior aims at identification and exploitation of opportunities and in taking preemptory action against potential problems and threats, whereas reactive behavior focuses on fighting a fire or solving a problem after it occurs.
Different phases are
1.) Analysis phase,
2.) Redo Phase,
3.) Undo phase.
This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are described in a database by a set of attributes.
The are three levels of abstraction:
Physical level: The lowest level of abstraction describes how data are stored.
Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data.
View level: The highest level of abstraction describes only part of entire database.
Physical level: The lowest level of abstraction describes how data are stored.
Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data.
View level: The highest level of abstraction describes only part of entire database.
Redundancy is controlled.
Unauthorised access is restricted.
Providing multiple user interfaces.
Enforcing integrity constraints.
Providing backup and recovery.
Redundancy is controlled.
Unauthorised access is restricted.
Providing multiple user interfaces.
Enforcing integrity constraints.
Providing backup and recovery.
Assume that a relation R with set of functional dependencies F. If R is decomposed into relations R1 and R2, then this decomposition is said to be lossless decomposition (or lossless-join decomposition) if and only if at least one of the following functional dependencies holds in the closure of set of functional dependencies F+;
R1 ∩ R2 → R1
R1 ∩ R2 → R2
R1 ∩ R2 should be a determinant that determines all the attributes of one of relations R1 and R2.
for detail :http://www.geeksforgeeks.org/lossless-join-and-dependency-preserving-decomposition/
"The decompositio of relation R into R1 and R2 is lossy when the join of R1 and R2 does not yield the same relation as in R."
One of the disadvantages of decomposition into two or more relational schemes (or tables) is that some information is lost during retrieval of original relation or table.
First normal form enforces these criteria:
Eliminate repeating groups in individual tables.
Create a separate table for each set of related data.
Identify each set of related data with a primary key .
WhatsApp or most of the other messaging apps rarely work on a peer to peer basis. So it wouldn't open a connection (from your device) to each of your friends' devices. WhatsApp will use that connection to send them your messages. If their app is "offline" then they might choose to send them a push notification instead.
Loose coupling is an approach to interconnecting the components in a system or network so that those components, also called elements, depend on each other to the least extent practicable. Coupling refers to the degree of direct knowledge that one element has of another.
The Travelling Salesman Problem (often called TSP) is a classic algorithmic problem in the field of computer science. It is focused on optimization. In this context better solution often means a solution that is cheaper. TSP is a mathematical problem.
the travelling salesperson problem, asks the following question: "Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city .
Solution of a travelling salesman problem: the black line shows the shortest possible loop that connects every red dot .
Abstraction .
Abstraction .
Encapsulation .
Encapsulation .
Polymorphism .
Polymorphism .
Inheritance .
Inheritance .
Data hiding is a software development technique specifically used in object-oriented programming (OOP) to hide internal object details (data members). Data hiding ensures exclusive data access to class members and protects object integrity by preventing unintended or intended changes.
Search: ArrayList search operation is pretty fast compared to the LinkedList search operation. get(int index) in ArrayList gives the performance of O(1) while LinkedList performance is O(n).
The time complexity comparison is as follows:
The time complexity comparison is as follows:
ArrayList class can act as a list only because it implements List only.LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
ArrayList class can act as a list only because it implements List only.LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
ArrayList is better for storing and accessing data.LinkedList is better for manipulating data.
ArrayList is better for storing and accessing data.LinkedList is better for manipulating data.
Responsive web design (RWD) is an approach to web design aimed at allowing desktop webpages to be viewed in response to the size of the screen or web browser one is viewing with.
The web server locates and then sends the information to the web browser, which displays the results. When web browsers contact servers, they're asking to be sent pages built with Hypertext Markup Language (HTML). Browsers interpret those pages and display them on your computer.
A server is a computer program that provides services to other computer programs (and their users) in the same or other computers. Servers are used to manage network resources. For example, a user may setup a server to control access to a network, send/receive e-mail, manage print jobs, or host a website.
A client is a computer that retrieves information from or uses resources provided by the server or main computer. Many corporate networks are comprised of a client computer at each of the employees' desks.
A web application is a computer program that utilizes web browsers and web technology to perform tasks over the Internet.
Interfaces are contracts between two disparate pieces of code. The exchange can be between software, computer hardware, peripheral devices, humans and combinations of these. Some computer hardware devices, such as a touchscreen, can both send and receive data through the interface.
Ternery search tree requires O(log(n)+k) comparisons where n is number of strings and k is the length of the string to be searched and binary search tree requires log(n) comparisons.
for detail :http://www.geeksforgeeks.org/binary-search-preferred-ternary-search/
select top 1 * from
(
select top 3 * from
(
select distinct emp_sal from employee order by asc emp_sal
) d orderby desc emp_sal
)
Creation of Sockets:
socket()
|
bind()
|
recvfrom()
|
(wait for a sendto request from some client)
|
(process the sendto request)
|
sendto (in reply to the request from the client...for example, send an HTML file)
Sockets are commonly used for client/server interaction. Typical system configuration places the server on one machine, with the clients on other machines. The clients connect to the server, exchange information, and then disconnect .
A server may create several concurrently established TCP sockets with the same local port number and local IP address, each mapped to its own server-child process, serving its own client process.
The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible.
An undirected graph is tree if it has following properties.
1) There is no cycle.
2) The graph is connected.
For an undirected graph we can either use BFS or DFS to detect above two properties.
for detail :http://www.geeksforgeeks.org/check-given-graph-tree/
Process State :
To measure the demand paging, the effective access time for a demand –paged
memory is calculated by:
Effective access time = (1 – p) x ma + p x page fault time
Where p: The probability of page fault, 0 < p < 1;
To improve both the utilization of the CPU and the speed of its response to users.
A jigsaw puzzle is a tiling puzzle that requires the assembly of often oddly shaped interlocking and tessellating pieces. Each piece usually has a small part of a picture on it; when complete, a jigsaw puzzle produces a complete picture. In some cases more advanced types have appeared on the market, such as spherical jigsaws and puzzles showing optical illusions.
During recent years, a range of jigsaw puzzle accessories including boards, cases, frames and roll-up mats has become available that are designed to assist jigsaw puzzle enthusiasts.
print 1, 2, 3, 4, 5, 6, 7.
for more detail refers :http://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/
The worst case complexity looks like O(nLogn), upper bound of time complexity is O(n).
Max heap is a specialized full binary tree in which every parent node contains greater or equal value than its child nodes. And last leaf node can be alone .
Example :
A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to Min Heap.
Examples of Min Heap:
10 10
/ \ / \
20 100 15 30
/ / \ / \
30 40 50 100 40
C follows the procedural programming. Java is platform independent language
Java is an Interpreted language while C is a compiled language
C uses the top-down approach while JAVA uses the bottom-up approach.
Java is a high-level language and C is a low-level language.
Another minor difference regarding boolean is that in C, stands for false and all the other numbers are considered true. Whereas in Java, they are represented literally by ‘true’ and ‘false'.
C uses the top-down {sharp & smooth} approach while JAVA uses the bottom-up {on the rocks} approach.
Exception Handling in JAVA And the errors & crashes in C.
JAVA supports Method Overloading while C does not support overloading at all.
Database Normalization, or simply normalization, is the process of organizing the columns (attributes) and tables(relations) of a relational database to reduce data redundancy and improve data integrity.
data normalization rules tend to increase the duplication of data, it does not introduce data redundancy, which is unnecessary duplication.
Normalization can also be thought of as a trade-off between data redundancy and performance. Normalizing a relation reduces data redundancy but introduces the need for joins when all of the data is required by an application such as a report query.
To find out if your computer is running a 32-bit or 64-bit version of Windows in Windows 7 or Windows Vista, do the following:
1. Open System by clicking the Start button , right-clicking Computer, and then clicking Properties.
2. Under System, you can view the system type.
A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number.
Process Synchronization means sharing system resources by processes in a such a way that, Concurrent access to shared data is handled thereby minimizing the chance of inconsistent data. Maintaining data consistency demands mechanisms to ensure synchronized execution of cooperating processes.
for detail refers :http://www.geeksforgeeks.org/process-synchronization-set-1/
A directory is a file system cataloging structure which contains references to other computer files, and possibly other directories. On many computers, directories are known as folders, or drawers to provide some relevancy to a workbench or the traditional office file cabinet.
Files are organized by storing related files in the same directory. In a hierarchical file system (that is, one in which files and directories are organized in a manner that resembles a tree), a directory contained inside another directory is called a sub directory.
file system or file system is used to control how data is stored and retrieved. Without a file system, information placed in a storage medium would be one large body of data with no way to tell where one piece of information stops and the next begins. By separating the data into pieces and giving each piece a name, the information is easily isolated and identified. Taking its name from the way paper-based information systems are named, each group of data is called a "file".
File systems can be used on numerous different types of storage devices that use different kinds of media. The most common storage device in use today is a hard disk drive. Other kinds of media that are used include flash memory,magnetic tapes, and optical discs
Insertion sort is faster for small n because Quick Sort has extra overhead from the recursive function calls.
Insertion sort is also more stable than Quick sort and requires less memory.
Best case of insertion sort is O(n).Best case of quick sort is O(nlogn).
Examples:
20
/ \
8 22
/ \ \
5 3 25
/ \
10 14
For the above tree the output should be 5, 10, 3, 14, 25.
for detail refers :http://www.geeksforgeeks.org/bottom-view-binary-tree/
An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails .A service is a component that runs in the background to perform long-running operations or to perform work for remote processes.
Activity is a GUI and service is non-gui thread which can run in the background .
An activity represents a single screen with a user interface.
A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface.
An activity represents a single screen with a user interface.
A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface.
By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error. Tip. Although the __autoload() function can also be used forautoloading classes and interfaces, it's preferred to use the spl_autoload_register() function.
PHP provides a number of 'magic' methods that allow you to do some pretty neat tricks in object oriented programming. These methods, identified by a two underscore prefix (__), function as interceptors that are automatically called when certain conditions are met.
Singleton class means you can create only one object for the given class. You can create a singleton class by making its constructor as private, so that you can restrict the creation of the object. Provide a static method to get instance of the object, wherein you can handle the object creation inside the class only.
We close a resource inside the try block. However this is not a good practice, because if an exception is thrown before our close statement is reached, then it will not be executed and resources might thus leak. We could add the close statement in the catch block, which leads to code duplication. If we have several catch blocks, this means we have to add the close statement there. Whenever we need to add a new catch block, we must also remember to put the close statement there.
Arithmetic Exception.
ArrayIndexOutOfBoundException .
ClassNotFoundException .
FileNotFoundException .
InterruptedException .
RuntimeException .
StringIndexOutOfBoundsException . etc
for detail :http://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions.
for detail :http://www.geeksforgeeks.org/exceptions-in-java/
Multithreading is a type of execution model that allows multiple threads to exist within the context of a process such that they execute independently but share their process resources.This approach differs from multiprocessing, as with multithreading the processes and threads share the resources of a single or multiple cores: the computing units, the CPU caches, and the translation lookaside buffer (TLB).
For example, a multithreaded operating system may run several background tasks, such as logging file changes, indexing data, and managing windows at the same time.
Dynamic-link library (or DLL) is Microsoft's implementation of the shared library concept in the Microsoft Windows and OS/2 operating systems. These libraries usually have the file extension DLL, OCX (for libraries containing ActiveX controls), or DRV(for legacy system drivers).
For example, several different programs might all call upon the very useful.dll file (I made that up, of course) to find the free space on a hard drive, locate a file in a particular directory, and print a test page to the default printer.
When the CPU gets to that instruction, and executes the int3 , this causes the CPU to generate a debug exception. The OS receives this interrupt, realizes the process is being debugged, and notifies the debugger process that the breakpoint was hit.
Any class type (whether declared with class-key class or struct) may be declared as derived from one or more base classes which, in turn, may be derived from their own base classes, forming an inheritance hierarchy.
Syntax:
struct Base {
int a, b, c;
};
// every object of type Derived includes Base as a subobject
struct Derived : Base {
int b;
};
// every object of type Derived2 includes Derived and Base as subobjects
struct Derived2 : Derived {
int c;
};
The best way to think about space complexity of recursive functions is (# of stack frames)*(space per stack frame). In your case, you have n stack frames f(n), f(n-1), f(n-2), ..., f(1) and O(1) space per stack frame (to store the argument n).
but there are fibonnaci(n) recursive calls so Space Complexity O(n).
/* a[] is the array, p is starting index, that is 0,
and r is the last index of array. */
void quicksort(int a[], int p, int r)
{
if(p < r)
{
int q;
q = partition(a, p, r);
quicksort(a, p, q);
quicksort(a, q+1, r);
}
}
int partition(int a[], int p, int r)
{
int i, j, pivot, temp;
pivot = a[p];
i = p;
j = r;
while(1)
{
while(a[i] < pivot && a[i] != pivot)
i++;
while(a[j] > pivot && a[j] != pivot)
j--;
if(i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else
{
return j;
}
}
}
for detail refer :http://www.geeksforgeeks.org/quick-sort/
INSERTION-SORT (A)
1 for j <- 2 to length[A]
2 do key <- A[j]
3 Insert A[j] into the sorted sequence A[1 . . j - 1].
4 i <- j - 1
5 while i > 0 and A[i] > key
6 do A[i + 1] <- A[i]
7 i <- i - 1
8 A[i + 1] <- key
for detail refers :http://www.geeksforgeeks.org/insertion-sort/
a heap is a specialized tree-based data structure that satisfies the heap property: if P is a parent node of C, then the key (the value) of node P is ordered with respect to the key of node C with the same ordering applying across the heap. A heap can be classified further as either a "max heap" or a "min heap".
for detail refers :http://www.geeksforgeeks.org/binary-heap/
perform a simple inorder traversal and keep the previous value of the node. If the current node is smaller than the previous node then it is not a binary search tree. You use constant additional space (for the previous value) apart from the recursion stack.
for detail refers :http://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/
In database management an aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurement such as a set, a bag or a list.
Common aggregate functions include :
Average() (i.e., arithmetic mean)
Count()
Maximum() etc.
for detail refers :http://www.geeksforgeeks.org/database-management-system-aggregate-functions/
The keyword struct is used to define a structure while keyword union is used to define a union.
In Structure, the address of each member will be in ascending order This indicates that memory for each member will start at different offset values while in unions the address is same for all the members of a union. This indicates that every member begins at the same offset value.
A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter.
In case of structure, each member have their own memory space but In union, one block is used by all the member of the union.
for detail refers:http://www.geeksforgeeks.org/difference-structure-union-c/
A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.
How to create a structure?
‘struct’ keyword is used to create a structure. Following is an example.
struct addrress
{
char name[50];
char street[100];
char city[50];
char state[20]
int pin;
};
for detail :http://www.geeksforgeeks.org/structures-c/
Demultiplex (DEMUX) is the reverse of the multiplex (MUX) process – combining multiple unrelated analog or digital signal streams into one signal over a single shared medium, such as a single conductor of copper wire or fiber optic cable.
Multiplexing (sometimes contracted to muxing) is a method by which multiple analog or digital signals are combined into one signal over a shared medium.
Multiplexing is done by using a device called multiplexer (MUX) that combines n input lines to generate one output line i.e. (many to one). Therefore multiplexer (MUX) has several inputs and one output.
Networking company almost all data structures are being used, some of them are followings
Stack
Queue
List
Tree ( AVL, BST, n-ary)
Graph ( MST, dijkstra algorithm etc )
Trie ( prefix tree: Route lookup)
Stack
Queue
List
Tree ( AVL, BST, n-ary)
Graph ( MST, dijkstra algorithm etc )
Trie ( prefix tree: Route lookup)
Constants provide some level of guarantee that code can't change the underlying value. This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors.
Constants are also inherently static - you can declare the constant and its value in a header file, and not have to worry about defining it exactly one place.
The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal
pointer, using the void keyword as the pointer's type:
void *ptr; // ptr is a void pointer.
for detail refers:http://www.geeksforgeeks.org/void-pointer-c/
an automatic variable is a local variable which is allocated and deal located automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or block in which available is defined.
for detail refers:http://www.geeksforgeeks.org/storage-classes-in-c/
a "default constructor" refers to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class. The default constructor implicitly calls the superclass's nullary constructor, then executes an empty body.
for detail refers :http://www.geeksforgeeks.org/c-internals-default-constructors-set-1/
DELETE :Command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed.
DROP :Drop command will delete the entire row also the structure.But truncate will delete the contents only not the structure, so no need to give specifications for another table creation.
TRUNCATE :TRUNCATE command is DDL command. It removes all the information of the table. Regarding performance if you have to delete all the rows of a table you should perform TRUNCATE command with DROP STORAGE option.
Suppose a pointer (say ptr) is pointing to a memory of 10 int on heap allocated usingmalloc as below.
int * ptr = (int*)malloc(10*sizeof(int));
You want to increase the size of memory pointed to by ptr from 10 to 20, without loosing the contents of already allocated memory. In this case you can call the realloc function. Signature of realloc is:
void *realloc(void *ptr, size_t size);
malloc() allocates memory block of given size (in bytes) and returns a pointer to the beginning of the block.
void * malloc( size_t size );
malloc() doesn’t initialize the allocated memory.
calloc() allocates the memory and also initializes the allocates memory to zero.
void * calloc( size_t num, size_t size );
calloc() takes two arguments: 1) number of blocks to be allocated 2) size of each block.
We can achieve same functionality as calloc() by using malloc() followed by memset(),
ptr = malloc(size);
memset(ptr, 0, size);
he Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower and sometimes pluralized) is a mathematical game or puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
No disk may be placed on top of a smaller disk.
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
No disk may be placed on top of a smaller disk.
With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2^n − 1, where n is the number of disks.
for detail refers :http://www.geeksforgeeks.org/iterative-tower-of-hanoi/
Function to insert node in the beginning of the List,
struct Node *addBegin(struct Node *last, int data)
{
if (last == NULL)
return addToEmpty(last, data);
// Creating a node dynamically.
struct Node *temp
= (struct Node *)malloc(sizeof(struct Node));
// Assigning the data.
temp -> data = data;
// Adjusting the links.
temp -> next = last -> next;
last -> next = temp;
return last;
}
for detail refers :http://www.geeksforgeeks.org/circular-singly-linked-list-insertion/
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates.Other way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.
for detail refers :http://www.geeksforgeeks.org/encapsulation-in-java/
Static binding is being used for overloaded methods and dynamic binding is being used for overridden/overriding methods.
Method overloading is used to increase the readability of the program.
Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
Argument list should be different while doing method overloading. Argument list should be same in method Overriding.
In Method Overloading, methods have same name different signatures but in the same class.In Method Overriding, methods have same name and same signature but in the different class.
It may or may not need inheritance in Method Overloading.It always requires inheritance in Method Overriding.
A memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. In object-oriented programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code.
for detail refers :http://www.geeksforgeeks.org/what-is-memory-leak-how-can-we-avoid/
Python provides a lot of inbuilt functionality and is a very powerful language. It is more closer to the English language as compared to most other languages. Therefore it becomes easier to focus more on the logic of the program rather than the syntax ( especially if it is the first language that you learn )
Python works with the very little code the way most common “use cases” require, reserving lengthy explicit coding for outliers and exceptions .
Python is highly approachable by complete beginners, and yet still powerful enough for pros to use as “shortcut-glue” in enterprise-class apps.
We can execute a stored procedure whenever we want with the help of the exec command, but a trigger can only be executed whenever an event (insert, delete, and update) is fired on the table on which the trigger is defined.
Stored procedures can return values but a trigger cannot return a value.
We can call a stored procedure from the front end (.asp files, .aspx files, .ascx files, etc.) but we can't call a trigger from these files.
Stored procedure can take input parameters, but we can't pass parameters as input to a trigger.
All the objects which are created dynamically (using new in C++ and Java) are allocated memory in the heap. If we go on creating objects we might get Out Of Memory error, since it is not possible to allocate heap memory to objects. So we need to clear heap memory by releasing memory for all those objects which are no longer referenced by the program (or the unreachable objects) so that the space is made available for subsequent new objects. This memory can be released by the programmer itself but it seems to be an overhead for the programmer, here garbage collection comes to our rescue, and it automatically releases the heap memory for all the unreferenced objects .
for detail refers :http://www.geeksforgeeks.org/mark-and-sweep-garbage-collection-algorithm/
“Garbage Collection” as the name suggests is used to remove the objects that are no longer needed by the Java application. The Java Garbage Collector will identify those objects and remove those from the memory thereby freeing the memory for the new objects .
for detail refers :http://www.geeksforgeeks.org/garbage-collection-java/
binary search trees (BST), sometimes called orderedor sorted binary trees, are a particular type of container: data structures that store "items" (such as numbers, names etc.) in memory. They allow fast lookup, addition and removal of items, and can be used to implement either dynamic sets of items, or lookup tables that allow finding an item by its key(e.g., finding the phone number of a person by name).
Example :
for detail refers :http://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/
A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly.
for detail refers :http://www.geeksforgeeks.org/pure-virtual-functions-and-abstract-classes/
Abstract classes are classes that contain one or more abstract methods. Anabstract method is a method that is declared, but contains no implementation.Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods .
for detail refers :http://www.geeksforgeeks.org/abstract-classes-in-java/
Exit controlled loop - The loop which keeps on executing until a particular condition is satisfied and when the condition is satisfied according to the criteria the loop exits, this is known as exit controlled loop.
EX-
While loop (during polling)
While loop (during polling)
The loop which has a condition check at the entrance of the loop, the loop executes only and only if the condition is satisfied is called as entry control loop.
EX-
while loop
For loop
while loop
For loop
Solution to the problem of external fragmentation is compaction. The process is to shuffle the memory contents so that all free memory is placed together in one large block. It is only possible if relocation is dynamic and done only at run time.
Example:Compaction Algorithm .
External fragmentation arises when free memory is separated into small blocks and is interspersed by allocated memory. It is a weakness of certain storage allocation algorithms, when they fail to order memory used by programs efficiently.
For example, consider a situation wherein a program allocates 3 continuous blocks of memory and then frees the middle block. The memory allocator can use this free block of memory for future allocations. However, it cannot use this block if the memory to be allocated is larger in size than this free block.
External fragmentation also occurs in file systems as many files of different sizes are created, change size, and are deleted. The effect is even worse if a file which is divided into many small pieces is deleted, because this leaves similarly small regions of free spaces .
Internal fragmentation is the space wasted inside of allocated memory blocks because of restriction on the allowed sizes of allocated blocks.Allocated memory may be slightly larger than requested memory; this size difference is memory internal to a partition, but not being used .
For example, memory can only be provided to programs in chunks divisible by 4, 8 or 16, and as a result if a program requests perhaps 23 bytes, it will actually get a chunk of 32 bytes. When this happens, the excess memory goes to waste. In this scenario, the unusable memory is contained within an allocated region.
The degree of multiprogramming describes the maximum number of processes that a single-processor system can accommodate efficiently
The primary factor affecting the degree of multiprogramming is the amount of memory available to be allocated to executing processes.
The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called.
Advantages
Function call overhead doesn’t occur.
It also saves the overhead of push/pop variables on the stack when function is called.
It also saves overhead of a return call from a function.
detail refers :http://www.geeksforgeeks.org/inline-functions-cpp/
A signal as referred to in communication systems, signal processing, and electrical engineering is a function that "conveys information about the behavior or attributes of some phenomenon".The simplest form of signal is a direct current (DC) that is switched on and off .
The keyword ‘register’ instructs the compiler to persist the variable that is being declared , in a CPU register.
Ex: register int number;
The persistence of register variables in CPU register is to optimize the access. Even the optimization is turned off; the register variables are forced to store in CPU register.
Read more on http://www.geeksforgeeks.org/understanding-register-keyword/
Huge pointer is the pointer that can point to the whole memory of the RAM and that can access all the segments that are present in a program. The normalization can be done depending on the microprocessor of the system. The physical memory of the system is represented in 20 bit and then there is a conversion of 4 byte or 32 bit address. The increment of the huge pointer will also affect the offset and segment address. Through the huge pointer the access and modification of device driver memory, video memory, etc. Huge pointer manages the overall system of the memory model and also normalizes the overall use of the pointers.
Invalid pointer arithmetic include:
(i) Adding, dividing and multiplying two pointers
(ii) Adding double or float to pointer
(iii) Masking or shifting pointer
(iv) Assigning a pointer of one type to another type of pointer.
ftell() function is used to get the current file referred by the file pointer.
ftell(fp); returns a long integer value referring the current location of the file pointed by the file pointer fp.
If there's an error, it will return -1.
"Far" and "Near" - non-standard qualifiers available in x86 systems only.
Near pointer - Refers to an address in known segment only.
Far pointer - Compound value containing a segment number and offset into that segment .
There is nothing like total generic pointer type, only void* holds the object (i.e. data) pointers. Converting function pointer to type void* is not a portable and it is not appropriate to convert it also. You can use any function type like int*() or void*(), these pointers can be treated as a generic function pointer. The best way to have the portability, is to use void* and a generic pointer combination.
- The terminate() is a library function which by default aborts the program.
- It is called whenever the exception handling mechanism cannot find a handler for a thrown exception.
- The unexpected() is called when a function with an exception specification throws an exception of a type that is not listed in the exception specification for the function
- A function declaration without a specification like throw(char*) may throw any type of exception, and one with throw() is not allowed to throw exceptions at all.
- By default unexpected() calls terminate().
Model transformations involve multiple models that are used to define different views of a system. It provides different level of granularity that it doesn’t use either the top-down approach or the bottom-up approach to implement the basic functionality of the system. It is used to integrate the library components used that involves the iteration of the model that needs to be constructed. It also involves the analysis of the model so that the process can be made automated by using the construction tools. The compilation made the progress by improving the code that is written in high level language and the code generator produce the code that is required for the machine language .
Prototype of the function used to create a child process is pid_t fork(void);
Fork is the system call that is used to create a child process. It takes no arguments and returns a value of type pid_t.
If the function succeeds it returns the pid of the child process created to its parent and child receives a zero value indicating its successful creation.
On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set.
- The child process normally performs all its operations in its parents context but each process independently of one nother and also inherits some of the important attributes from it such as UID, current directory, root directory and so on.
Critical section allows the process to run in an area that is defined by that process only. It is a sequence of instructions that can be corrupted if any other process tries to interrupt it. This process allow the operating system to give the synchronization objects that are used to monitor the processes that are up and running so that no other process will get executed till the critical region consists of a process that is already running. The example includes removal of the data from a queue running in a critical section and if not protected then it can be interrupted and the data have chances of getting corrupted. The processes exit from the critical section as soon as they finish the execution so that the chances can be given to other processes that are waiting for their chance to come .
- Damage of memory devices due to transient current and static discharges.
- Malfunctioning of address lines due to a short in the circuit.
- Malfunctioning of Data lines.
- Some memory locations being inaccessible in storage due to garbage or errors.
- Improper insertion of Memory devices into the memory slots.
- Faulty control signals.
Direct memory access is mainly used to overcome the disadvantages of interrupt and progam controlled I/O.
DMA modules usually take the control over from the processor and perform the memory operations and this is mainly because to counteract the mismatch in the processing speeds of I/O units and the procesor. This is comparatively faster.
It is an important part of any embedded systems,and the reason for their use is that they can be used for bursty data transfers instead of single byte approaches.
It has to wait for the systems resources such as the system bus in case it is already in control of it.
Cloud computing consists of 3 layers in the hierarchy and these are as follows:
1. Infrastructure as a Service (IaaS) provides cloud infrastructure in terms of hardware like memory, processor speed etc.
2. Platform as a Service (PaaS) provides cloud application platform for the developers.
3. Software as a Service (SaaS) provides cloud applications which are used by the user directly without installing anything on the system. The application remains on the cloud and it can be saved and edited in there only.
Cloud computing is a metaphor used for internet. It provides on-demand access to virtualized IT resources that can be shared by others or subscribed by you. It provides an easy way to provide configurable resources by taking it from a shared pool. The pool consists of networks, servers, storage, applications and services.
Utility computing allow the user to pay per use means whatever they are using only for that they have to pay. It is a plug in that needs to be managed by the organizations on deciding what type of services has to be deployed from the cloud. Utility computing allows the user to think and implement the services according to them. Most organizations go for hybrid strategy that combines internal delivered services that are hosted or outsourced services.
VPN stands for virtual private network; it is a private cloud which manages the security of the data during the transport in the cloud environment. VPN allows an organization to make a public network as private network and use it to transfer files and other resources on a network.
Cloud computing provides the services to the organizations so they can run their applications and install them on the cloud. Virtualization is used to deploy the cloud computing models as it provides a hidden layer between the user and the physical layer of the system. The cloud services are measured in terms of use. Pay as much as you use that can be on the basis of hours or months or years. Cloud services allow users to pay for only what they use and according to the demand the charges or the prices gets increased.
- Table Scan - Iterating over the table rows .
- Index Scan - Iterating over the index items .
During the process of distributed deadlock detection, sometime a delay occurs while propagating local information and this leads to deadlock detection algorithms pointing to deadlocks that do not actually occur.
- These deadlocks are referred to as phantom deadlocks, as they do not really exist.
- Phantom deadlock lead to unnecessary abortions.
- Materialized views are disk based views.
- Materialized views get updated periodically based on the interval specified in the query.
- Materialized views can be indexed.
Clustered Index -
- A clustered index reorders the way records in the table are physically stored.
- There can be only one clustered index per table.
- It makes data retrieval faster.
Non-clustered Index
- A non-clustered index does not make any changes to the way the records were stored but creates a completely separate object inside the table.
- This makes the insert and update command work faster .
Database partitioning refers to dividing the large database into small logical units. It helps in improving the management, availability & performance of the system.
The advantages of database partitioning are:
i.) It improves and speeds up the performance of queries
ii.) You can easily bigger parts of a partition
There are various translation phases that can be used in C language. These are as follows:
a) The first stage of the translation phase is to check the tri-graph and allow it to be used with the system.
b) The second stage is to identify the type of program that has to be written for that, the identification of identifiers and others are figured out.
c) The third stage is the important stage where the translation from comments to the space takes place. The space is not being seen in the case of strings or character constant. And multiple white spaces may be combined in one.
d) The last stage involves the complete translation of the program.
Volatile variables are like other variables except that the values might be changed at any given point of time only by ‘some external resources’.
Ex:
volatile int number;
The value may be altered by some external factor, though if it does not appear to the left of the assignment statement. The compiler will keep track of these volatile variables .
- #include<...> means that the directories other than the current one will be searched for the header file.
- #include "..." means that the current directory will be searched for the header file before any other directories.
Enumerated types allow the programmers to use more meaningful words as values to a variable.
Each item in the enumerated type variable is actually associated with a numeric code. For an enumerated type variable named Months can be created. Its values can be January, February,....December.
Both functions accept a character input value from the user.
When getch() is used, the key that was pressed will not appear on the screen. It is automatically captured and assigned to a variable.
While when getche() is used, the key that was pressed by the user appears on the screen and is assigned to a variable.
for detail refers :http://www.geeksforgeeks.org/difference-getchar-getch-getc-getche/
It is done for parsing process and compilation of the code.
A semicolon acts as a delimiter. This tells the compiler where each statement ends, and can proceed to divide the statement into smaller elements for checking the syntax.
A newline escape sequence is represented by the \n character.
It is used to insert a new line while displaying the output data.
To add more spaces you can use more \n characters.
Spaghetti programming refers to codes that tend to get tangled and overlapped throughout the program.
It makes a program complex and analyzing the code becomes difficult. It usually happens due to the lack of work experience on developer's part.
for detail :http://www.geeksforgeeks.org/g-fact-87/
Declaring all header files in every program would lead to increase in the overall file size and load of the program. It is not a good programming.
The choice of header files that you want to declare in the program depends on the commands/functions you want to use in the program. Each header file contains different commands and functions. So we use only the files relevant to our program
- While writing programs that store and retrieve data in a file, it is possible to designate that file into different forms.
- A sequential access file is such that data are saved in sequential order: one data is placed into the file after another.
- If you want to access a particular data within the sequential access file, data has to be read - one data at a time, until you reach the data you want.
- JAXM messaging models has two types of messaging model, synchronous and asynchronous.
1. Synchronous messaging model :
- In this type of model, client directly interacts with the source. The client sends a request and waits for the response.
2. Asynchronous messaging model :
- In this model, client sends message to the messaging provider and returns back. Messaging provider then performs the routing of message to the end source.
- JAX-RPC uses SOAP to call remote procedures.
- It enables JAX-RPC clients to invoke web services developed across heterogeneous platform.
- It is an Application Program Interface(API).
- It is easier for the web services to call other applications.
- It provides a programming model for the development of SOAP .
- It is the service called as distributed lock manager.
- In cluster systems to avoid file sharing the distributed systems must provide the access control and file locking.
- This ensures that no conflicting operations occur in the system.
- Here the distributed file systems are not general purpose therefore it requires locking.
- These systems are also called as the distributed systems.
- It consist of collection of processors that do not share memory or clock.
- The processors communicate through high speed buses or telephone lines.
- It can be a centralized system where the server responds to client requests.
- It can also be a peer to peer system.
- It is the ability to continue providing service proportional to level of hardware.
- Systems designed for graceful degradation are called fault tolerant.
- If we have several processors connected together, then failure of one would not stop the system.
- Then the entire system runs only 10% slower.
- This leads to increased reliability of the system .
The VFS layer also known as the virtual file system functions in many ways similar to object oriented programming techniques. It acts like an abstraction layer on top of a more specific file system. The VFS layer enables the OS to make system calls independent of the file system type used. Any file system that is used gives its function calls used and the data structures to the layer of VFS. The VFS layer translates a system call into the correct specific functions for the targeted file system. The program that is used for calling does not have a file system specific code also the system call structures used in upper levels are file system independent. The VFS layer translation translates the non-file system specific calls into a file system specific operation.The VFS layer also known as the virtual file system functions in many ways similar to object oriented programming techniques. It acts like an abstraction layer on top of a more specific file system. The VFS layer enables the OS to make system calls independent of the file system type used. Any file system that is used gives its function calls used and the data structures to the layer of VFS. The VFS layer translates a system call into the correct specific functions for the targeted file system. The program that is used for calling does not have a file system specific code also the system call structures used in upper levels are file system independent. The VFS layer translation translates the non-file system specific calls into a file system specific operation.
The Belady's anomaly is a situation in which the number of page faults increases when additional physical memory is added to a system. This anomaly arises in some algorithms that implement virtual memory. The virtual memory allows programs larger than the physical memory space to execute. An algorithm suffers from this problem when it cannot guarantee that a page will be kept when a small number of frames are available. An optimal algorithm would not suffer from this problem as it replaces the page not to be used for the longest time. The anomaly occurs when the page replacement algorithm will remove a page that will be needed in the immediate future. An optimal algorithm will not select such a page that will be required immediately. This anomaly is also stated to be unbounded .
Read - write locks provide simultaneous read access to many threads while the write access stays with one thread at a time. They are especially useful in protecting the data that is not frequently written but read simultaneously by many threads.
- They are slower than mutexes.
for detail :http://www.geeksforgeeks.org/readers-writers-problem-set-1-introduction-and-readers-preference-solution/
- A traditional pipe is unnamed and can be used only for the communication of related process. If unrelated processes are required to communicate - named pipes are required.
- It is a pipe whose access point is a file available on the file system. When this file is opened for reading, a process is granted access to the reading end of the pipe. Similarly, when the file is opened for writing, the process is granted access to writing end of the pipe.
- A named pipe is also referred to as FIFO or named FIFO.
- Kernel is the part of OS which handles all details of sharing resources and device handling.
- It can be considered as the core of OS which manages the core features of an OS.
- Its purpose is to handle the communication between software and hardware
- Its services are used through system calls.
- A layer of software called shell wraps around the Kernel .
LEFT JOIN: This join returns all the rows of the table on the left side of the join and matching rows for the table on the right side of join. The rows for which there is no matching row on right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables .
for detail refers :http://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/
RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join and matching rows for the table on the left side of join. The rows for which there is no matching row on left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables .
for detail refers :http://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/
FULL JOIN: FULL JOIN creates the result-set by combining result of both LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from both the tables. The rows for which there is no matching, the result-set will contain NULL values.Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
for detail :http://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as long as the condition satisfies. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
for detail refer :http://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/
You can configure whether and how sessions use cookies in the following ways:
You can configure the session-properties for the entire web container:
To use the Administration interface, select Containers and then Web Container under your server instance. Then click on the Properties button under Session Configuration Properties. After editing the properties, click on OK, then Save.
You can also edit the session-properties element in the server.xml file, which is the same as the corresponding element in the sun-web.xml file. For details, see the Sun Java System Application Server Administrator’s Configuration File Reference.
You can configure the session-properties and cookie-properties elements in the sun-web.xml file for an individual web application.
A cookie (called an Internet or Web cookie) is the term given to describe a type of message that is given to a Web browser by a Web server. The main purpose of a cookie is to identify users and possibly prepare customized Web pages or to save site login information for you.
When you enter a Web site using cookies, you may be asked to fill out a form providing personal information; like your name, e-mail address, and interests. This information is packaged into a cookie and sent to your Web browser, which then stores the information for later use. The next time you go to the same Web site, your browser will send the cookie to the Web server. The message is sent back to the server each time the browser requests a page from the server .
Phrase level error recovery is implemented by filling in the blank entries in the predictive parsing table with pointers to error routines. These routines may change, insert, or delete symbols on the input and issue appropriate error messages. They may also pop from the stack.
A handle of a string is a substring that matches the right side of a production, and whose reduction to the nonterminal on the left side of the production represents one step along the reverse of a rightmost derivation.
A handle of a right – sentential form γ is a production A→β and a position of γ where the string β may be found and replaced by A to produce the previous right-sentential form in a rightmost derivation of γ. That is , if S =>αAw =>αβw,then A→β in the position following α is a handle of αβw.
· Tokens- Sequence of characters that have a collective meaning.
· Patterns- There is a set of strings in the input for which the same token is produced as output. This set of strings is described by a rule called a pattern associated with the token
· Lexeme- A sequence of characters in the source program that is matched by the pattern for a token.
Analysis and Synthesis are the two parts of compilation.
The analysis part breaks up the source program into constituent pieces and creates an intermediate representation of the source program.
The synthesis part constructs the desired target program from the intermediate representation.
A compiler is a program that reads a program written in one language –the source language and translates it into an equivalent program in another language-the target language. The compiler reports to its user the presence of errors in the source program.
Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack, the only element that can be removed is the element that was at the top of the stack, just like a pile of objects.
Basic features of Stack
Stack is an ordered list of similar data type.
Stack is a LIFO structure. (Last in First out).
push() function is used to insert new elements into the Stack and pop() is used to delete an element from the stack. Both insertion and deletion are allowed at only one end of Stack called Top.
Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state if it is completely empty.
Stack is an ordered list of similar data type.
Stack is a LIFO structure. (Last in First out).
push() function is used to insert new elements into the Stack and pop() is used to delete an element from the stack. Both insertion and deletion are allowed at only one end of Stack called Top.
Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state if it is completely empty.
for detail refer :http://www.geeksforgeeks.org/stack-data-structure/
Polish and Reverse Polish notations.
Operating System | Paging
Paging is a memory management scheme that eliminates the need for contiguous allocation of physical memory. This scheme permits the physical address space of a process to be non – contiguous.
Logical Address or Virtual Address (represented in bits): An address generated by the CPU
Logical Address Space or Virtual Address Space( represented in words or bytes): The set of all logical addresses generated by a program
Physical Address (represented in bits): An address actually available on memory unit
Physical Address Space (represented in words or bytes): The set of all physical addresses corresponding to the logical addresses .
for detail :http://www.geeksforgeeks.org/operating-system-paging/
Network security combines multiple layers of defenses at the edge and in the network. Each network security layer implements policies and controls. Authorized users gain access to network resources, but malicious actors are blocked from carrying out exploits and threats .
HTTP is Hyper Text Transfer protocol that is used in networking. Whenever basically you type a website in the browser, its is this protocol which by default listens at port 80 on server side and helps you to see the webpage on your machine.
HTTPS : This is Hyper text Transfer protocol with added security layer in place in form on TLS/SSL. Servers and clients communicate with each other exactly same as HTTP but over a secure channel.
HTTP URL begins with “http://” .
HTTPS URL begins with “https://” .
HTTP Operate in Operates at Application Layer.
HTTPS Operates at Transport Layer .
HTTP No certificates required .
HTTPs certificates required .
he automotive differential is designed to drive a pair of wheels while allowing them to rotate at different speeds. In vehicles without a differential, such as karts, both driving wheels are forced to rotate at the same speed, usually on a common axle driven by a simple chain-drive mechanism.
Unix is more flexible and can be installed on many different types of machines, including main-frame computers, super computers and micro-computers.
- Unix is more stable and does not go down as often as Windows does, therefore requires less administration and maintenance.
- Unix has greater built-in security and permissions features than Windows.
- Unix possesses much greater processing power than Windows.
- Unix is the leader in serving the Web. About 90% of the Internet relies on Unix operating systems running Apache, the world's most widely used Web server.
- Software upgrades from Microsoft often require the user to purchase new or more hardware or prerequisite software. That is not the case with Unix .
The “Core 2 Duo” is a name given to series of Processors of Intel. The name is specific to that range only and not any other. These processors had only two cores as the “Duo” the term says. Similary, there was a series of Intel Proecessors named “Core 2 Quad” whose processors had four Cores as the term “Quad” applies.
The term “Dual Core” obviously means that the referenced processor would have two cores. However, this term was mainly used in non-mainstream processor. These were meant for budget class, or more power-efficiency than performance. So, basically a Core 2 Duo Processor would perform better that a Dual Core stated Processor, but there are few more things to look at when comparing and there are few exceptions.
The smallest value that can be measured by the measuring instrument is called its least count. Measured values are good only up to this value. The least count error is the error associated with the resolution of the instrument .
COBOL (Common Business Oriented Language) was the first widely-used high-level programming language for business applications.
While the language has been updated over the years, COBOL programs are generally viewed as being outdated. Today, however, a majority of payroll, accounting and other business application programs still use COBOL despite the growing popularity of more modern programming languages such as Java, C++ and .NET. In fact, there are more existing lines of programming code still in use written in COBOL than in any other programming language.
The Pentium 4 570 processor is a 3.8GHz chip with 1Mbytes of Level 2 cache that will feature the fastest clock speed of any Pentium 4 processor for an indefinite period of time.
Linear programming (LP) (also called linear optimization) is a method to achieve the best outcome (such as maximum profit or lowest cost) in a mathematical model whose requirements are represented by linear relationships. Linear programming is a special case of mathematical programming (mathematical optimization) .
Grid computing is the collection of computer resources from multiple locations to reach a common goal. The grid can be thought of as a distributed system with non-interactive workloads that involve a large number of files .
for detail refers :http://www.geeksforgeeks.org/mpi-distributed-computing-made-easy/
1) Data stored in normalized schema in OLTP systems can have hundreds to thousands of tables for an enterprise. OLTP systems have a probability, that a portion of these tables can be often less descriptive due to lack of self relevant naming conventions. This makes designing queries harder for reporting purposes.
2) As normalised schema has a lot of tables, a single piece of related information is split and stored into various tables with referential integrity constraints. This means that reading this data requires creating joins with many tables. For reporting and analysis purposes over a very huge dataset spanning thousands to millions of records of historical data, such queries would perform very poorly.
3) OLTP systems tend to archive data time to time on a scheduled basis. It might be in the form of hard / soft delete. Lack of historical data can limit the level of analysis that can be performed on the data.
4) OLTP systems tend to store most updated version of data only. For ex employee address, product name, martial status etc. Generally history for such attributes would not be preserved, which results in loss of historical data. Lack of history for such attributes can limit the level of analysis that can be performed on the data .
image processing is processing of images using mathematical operations by using any form of signal processing for which the input is an image, a series of images, or a video, such as a photograph or video frame; the output of image processing may be either an image or a set of characteristics or parameters related to the image.
The abacus (plural abaci or abacuses), also called a counting frame, is a calculating tool that was in use in Europe, China and Russia, centuries before the adoption of the written Hindu–Arabic numeral system and is still used by merchants, traders and clerks in some parts of Eastern Europe, Russia, China and Africa .
PageRank (PR) is an algorithm used by Google Search to rank websites in their search engine results. PageRank was named after Larry Page, one of the founders of Google. PageRank is a way of measuring the importance of website pages.
A decision support system (DSS) is a computerized information system used to support decision-making in an organization or a business. A DSS lets users sift through and analyze massive reams of data and compile information that can be used to solve problems and make better decisions.
A 64-bit processor is a microprocessor with a word size of 64 bits, a requirement for memory and data intensive applications such as computer-aided design (CAD) applications, database management systems, technical and scientific applications, and high-performance servers.
genetic programming (GP) is a technique whereby computer programs are encoded as a set of genes that are then modified (evolved) using an evolutionary algorithm (often a genetic algorithm, "GA") – it is an application of (for example) genetic algorithms where the space of solutions consists of computer programs.
SAP stands for Systems Applications and Products in Data Processing.
SAP by definition is also named of the ERP (Enterprise Resource Planning) software as well the name of the company.
SAP Software was Founded in 1972 by Wellenreuther, Hopp, Hector, Plattner and Tschira.
SAP system consists of a number of fully integrated modules, which covers virtually every aspect of the business management.
SAP is #1 in the ERP market. As of 2010, SAP has more than 140,000 installations worldwide, over 25 industry-specific business solutions and more than 75,000 customers in 120 countries
Other Competitive products of SAP Software in the market are Oracle, Microsoft Dynamics etc
A collection of wires through which data is transmitted from one part of a computer to another. You can think of a bus as a highway on which data travels within a computer. When used in reference to personal computers, the term bus usually refers to internal bus
Embedded software is computer software, written to control machines or devices that are not typically thought of as computers. It is typically specialized for the particular hardware that it runs on and has time and memory constraints.
Operations research (OR) is an analytical method of problem-solving and decision-making that is useful in the management of organizations. In operations research, problems are broken down into basic components and then solved in defined steps by mathematical analysis.
The JVM uses locks in conjunction with monitors. A monitor is basically a guardian that watches over a sequence of synchronized code and ensuring that only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. The thread is not allowed to execute the code until it obtains the lock.
for detail refers :http://www.geeksforgeeks.org/process-synchronization-set-1/
Java API provides several convenient methods to split string based upon any delimiter e.g. comma, semi colon or colon. You can even use regular expression to split a big string into several smaller strings.
SSL and SSH both are special encryption and protocol technologies used to connect two computers
• SSH: SSH stands for “Secure Shell” which commonly uses port 22 to connect your system on another system via internet. It is often used by network administrators as a remote login or remote control to manage their business servers.
• SSL: SSL stands for “Secure Sockets Layer” it commonly uses port 443 to connect your system to a secure system on the Internet. It is often used for transmitting information like tax, banking, credit card, personal information to a business server somewhere.
Software Metrics provide measures for various aspects of software process and software product. They are divided into –
Requirement metrics : Length requirements, completeness
Product metrics :Lines of Code, Object oriented metrics, design and test metrics
Process metrics: Evaluate and track budget, schedule, human resource.
Baseline is a measurement that defines completeness of a phase. After all activities associated with a particular phase are accomplished, the phase is complete and acts as a baseline for next phase.
This is the most obvious question accurued in mind that if the cloud data is secure; To ensure that, check that there is no data leak with the encryption key implemented with the data you sending while the data moves from point A to point B in cloud.
Scalability is a characteristic of cloud computing which is used to handle the increasing workload by increasing in proportion amount of resource capacity. By the use of scalability, the architecture provides on demand resources if the requirement is being raised by the traffic. Whereas, Elasticity is a characteristic which provides the concept of commissioning and decommissioning of large amount of resource capacity dynamically. It is measured by the speed by which the resources are coming on demand and the usage of the resources.
Synchronicity is used to bind the client to the execution of the service. In synchronous invocations, the client blocks and waits for the service to complete its operation before continuing. On the other hand, synchronous operations facilitate a client to invoke a service and then execute other functions.
Interoperability: By the help of web services, an application can communicate with other application developed in any language.
Reusability: We can expose the web service so that other applications can use it.
Modularity: By the help of web service, we can create a service for a specific task such as tax calculation etc.
Benchmarking testing is the process of comparing application performance with respect to industry standard given by some other organization.
It is a standard testing which specifies where our application stands with respect to others.
In Baseline testing, a set of tests is run to capture performance information. Baseline testing improves performance and capabilities of the application by using the information collected and make the changes in the application. Baseline compares present performance of application with its own previous performance.
The "netstat" is a command line utility program. It gives useful information about the current TCP/IP setting of a connection.
NOS stands for Network Operating System. It is specialized software which is used to provide network connectivity to a computer to make communication possible with other computers and connected devices.
A list of predefined exceptions in PL/SQL:
DUP_VAL_ON_INDEX
ZERO_DIVIDE
NO_DATA_FOUND
TOO_MANY_ROWS
CURSOR_ALREADY_OPEN
INVALID_NUMBER
INVALID_CURSOR
PROGRAM_ERROR
TIMEOUT _ON_RESOURCE
STORAGE_ERROR
LOGON_DENIED
VALUE_ERROR
etc.
Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
Boxing:Implicit conversion of a value type (integer, character etc.) to a reference type (object) is called boxing. In boxing process a value type(which generally stores on stack) is being allocated on the heap rather than the stack.
Unboxing:explicit conversion of that same reference type (which is created by boxing process) back to a value type is known as unboxing. In unboxing process boxed value type is unboxed from the heap and allocated on the stack.
SQL Server is DBMS system provided by Microsoft. Sometimes it is mistakenly referred as SQL but both are totally different, as SQL is a language whereas SQL Server is a Microsoft product that supports SQL.
ORM is an acronym for Object/Relational mapping. It is a programming strategy to map object with the data stored in the database. It simplifies data creation, data manipulation and data access.
Hibernate is an open-source and lightweight ORM tool that is used to store, manipulate and retrieve data from the database.
Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones.
strstr() returns part of a given string from the first occurrence of a given substring to the end of the string.
For example:strstr("user@example.com","@") will return "@example.com".
stristr() is idential to strstr() except that it is case insensitive.
Answer: 5,20,1
Answer : 5794
The major difference between B-tree and binary tres is that B-tree is a external data structure and binary tree is a main memory data structure. The computational complexity of binary tree is counted by the number of comparison operations at each node, while the computational complexity of B-tree is determined by the disk I/O, that is, the number of node that will be loaded from disk to main memory. The comparision of the different values in one node is not counted .
CTS is the component of CLR through which .NET Framework provides support for multiple languages because it contains a type system that is common across all the languages. Two CTS-compliant languages do not require type conversion when calling the code written in one language from within the code written in another language. CTS provide a base set of data types for all the languages supported by.NET Framework. This means that the size of integer and long variables is same across all .NET-compliant programming languages. However, each language uses aliases for the base data types provided by CTS. For example, CTS uses the data type system. int32 to represent a 4 byte integer value; however, Visual Basic uses the alias integer for the same; whereas, C# uses the alias int. This is done for the sake of clarity and simplicity.
Managed extensibility framework (MEF) is a new library that is introduced as a part of .NET 4.0 and Silverlight 4. It helps in extending your application by providing greater reuse of applications and components. MEF provides a way for host application to consume external extensions without any configuration requirement.
Code contracts help you to express the code assumptions and statements stating the behavior of your code in a language-neutral way. The contracts are included in the form of pre-conditions, post-conditions and object-invariants. The contracts help you to improve-testing by enabling run-time checking, static contract verification, and documentation generation .
Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following things
Version of assembly.
Security identity.
Scope of the assembly.
Resolve references to resources and classes.
The assembly manifest can be stored in a PE file either (an .exe or) .dll with Microsoft
intermediate language (MSIL code with Microsoft intermediate language (MSIL) code or in a
stand-alone PE file, that contains only assembly manifest information
Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code is compiled to IL. IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.
struct ABC{
int a;
float b;
char c;
};
int main(){
struct ABC *ptr=(struct ABC *)0;
ptr++;
printf("Size of structure is: %d",*ptr);
return 0;
Merits:
(a) We can easily access each element of array.
(b) Not necessity to declare too many variables.
(c) Array elements are stored in continuous memory location.
Demerit:
(a) Wastage of memory space. We cannot change size of array at the run time.
(b) It can store only similar type of data.
You can modify constant variable with the help of pointers. For example:
#include<stdio.h>
int main(){
int i=10;
int *ptr=&i;
*ptr=(int *)20;
printf("%d",i);
return 0;
}
Output: 20
In c we can pass the parameters in a function in two different ways.
(a)Pass by value: In this approach we pass copy of actual variables in function as a parameter. Hence any modification on parameters inside the function will not reflect in the actual variable. For example:
#include<stdio.h>
int main(){
int a=5,b=10;
swap(a,b);
printf("%d %d",a,b);
return 0;
}
void swap(int a,int b){
int temp;
temp =a;
a=b;
b=temp;
}
Output: 5 10
(b)Pass by reference: In this approach we pass memory address actual variables in function as a parameter. Hence any modification on parameters inside the function will reflect in the actual variable. For example:
#incude<stdio.h>
int main(){
int a=5,b=10;
swap(&a,&b);
printf("%d %d",a,b);
return 0;
}
void swap(int *a,int *b){
int *temp;
*temp =*a;
*a=*b;
*b=*temp;
}
Output: 10 5
A pointer in c which has not been initialized is known as wild pointer.
Example:
int main(){
int *ptr;
printf("%u\n",ptr);
printf("%d",*ptr);
return 0;
}
Output: Any address
Garbage value
Here ptr is wild pointer because it has not been initialized. There is difference between the NULL pointer and wild pointer. Null pointer points the base address of segment while wild pointer doesn’t point any specific memory location.
for details refers :http://www.geeksforgeeks.org/dangling-void-null-wild-pointers/
If one or a few processes have a high access rate to data on one track of a storage disk, then they may monopolize the device by repeated requests to that track. This generally happens with most common device scheduling algorithms (LIFO, SSTF, C-SCAN, etc). High-density multisurface disks are more likely to be affected by this than low density ones.
VFS, or Virtual File System, separates file system generic operations from their implementation by defining a clean VFS interface. It is also based on a file-representation structure known as vnode, which contains a numerical designator needed to support network file systems.
Overlays are used to enable a process to be larger than the amount of memory allocated to it. The basic idea of this is that only instructions and data that are needed at any given time are kept in memory.
Mutual Exclusion: Only one process may use a critical resource at a time.
Hold & Wait: A process may be allocated some resources while waiting for others.
No Pre-emption: No resource can be forcible removed from a process holding it.
Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain.
Mutual Exclusion: Only one process may use a critical resource at a time.
Hold & Wait: A process may be allocated some resources while waiting for others.
No Pre-emption: No resource can be forcible removed from a process holding it.
Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain.
It is a useful, memory-saving technique for multiprogrammed timesharing systems. A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program code cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Each execution instance is called activation. It executes the code in the permanent part, but has its own copy of local variables/parameters. The temporary part associated with each activation is the activation record. Generally, the activation record is kept on the stack.
Two important pieces of RDBMS architecture are the kernel, which is the software, and the data dictionary, which consists of the system-level data structures used by the kernel to manage the database You might think of an RDBMS as an operating system (or set of subsystems), designed specifically for controlling data access; its primary functions are storing, retrieving, and securing data. An RDBMS maintains its own list of authorized users and their associated privileges; manages memory caches and paging; controls locking for concurrent resource usage; dispatches and schedules user requests; and manages space usage within its table-space structures .
Proactive Update: The updates that are applied to database before it becomes effective in real world.
Retroactive Update: The updates that are applied to database after it becomes effective in real world.
Simulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world.
Proactive Update: The updates that are applied to database before it becomes effective in real world.
Retroactive Update: The updates that are applied to database after it becomes effective in real world.
Simulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world.
Cold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy. If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost.
Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option.
Cold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy. If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost.
Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option.
Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These types of procedures are not available for reference from other Oracle tools. Another limitation of stand-alone procedures is that they are compiled at run time, which slows execution.
Advantages:
1. Views don't store data in a physical location.
2. The view can be used to hide some of the columns
from the table.
3. Views can provide Access Restriction,
since data insertion, update and deletion
is not possible with the view.
Disadvantages:
1. When a table is dropped, associated view become irrelevant.
2. Since the view is created when a query
requesting data from view is triggered,
its a bit slow.
3. When views are created for large tables,
it occupies more memory.
Default gateways provide means for the local networks to connect to the external network. The default gateway for connecting to the external network is usually the address of the external router port .
Traceroute is a widely used command line utility available in almost all operating systems. It shows you the complete route to a destination address. It also shows the time taken (or delays) between intermediate routers. Isn’t it great? Below is an example on Windows operating System.
for detail refers :http://www.geeksforgeeks.org/computer-networks-traceroute/
DoS, or Denial-of-Service attack, is an attempt to prevent users from being able to access the internet or any other network services. Such attacks may come in different forms and are done by a group of perpetuators. One common method of doing this is to overload the system server so it cannot anymore process legitimate traffic and will be forced to reset.
NOS, or Network Operating System, is specialized software whose main task is to provide network connectivity to a computer in order for it to be able to communicate with other computers and connected devices.
RIP, short for Routing Information Protocol is used by routers to send data from one network to another. It efficiently manages routing data by broadcasting its routing table to all other routers within the network. It determines the network distance in units of hops.
Gray box testing, also called gray box analysis, is a strategy for software debugging in which the tester has limited knowledge of the internal details of the program. A gray box is a device, program or system whose workings are partially understood.
The Capability Maturity Model (CMM) is a methodology used to develop and refine an organization's software development process. The model describes a five-level evolutionary path of increasingly organized and systematically more mature processes.
In Windows NT a mutant provides kernel mode or user mode mutual exclusion with the notion of ownership.
Load Sharing: Processes are not assigned to a particular processor. A global queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis.
Gang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads / processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy.
Dedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool.
Dynamic scheduling: The number of thread in a program can be altered during the course of execution .
Load Sharing: Processes are not assigned to a particular processor. A global queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis.
Gang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads / processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy.
Dedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool.
Dynamic scheduling: The number of thread in a program can be altered during the course of execution .
The activation record is a block of memory used for managing the information needed by a single execution of a procedure. Various fields f activation record are:
· Temporary variables
· Local variables
· Saved machine registers
· Control link
· Access link
· Actual parameters
· Return values
Directed acyclic graph(DAG) is a useful data structure for implementing transformations on basic blocks.
DAG is used in
· Determining the common sub-expressions.
· Determining which names are used inside the block and computed outside the block.
· Determining which statements of the block could have their computed value outside the block.
· Simplifying the list of quadruples by eliminating the common su-expressions and not performing the assignment of the form x := y unless and until it is a must.
The following are the problems associated with top down parsing:
· Backtracking
· Left recursion
· Left factoring
· Ambiguity
The most important point to remember is REDO is not the opposite of UNDO. Whenever a DML transaction happens in database, the data to be updated goes to the DATABASE BUFFER CACHE. From here the data is written to REDO BUFFER and then to REDO Logs. These logs are saved for future use. Future ROLLBACK and DATA RECOVERY operations require these logs. Without these logs it is impossible to do DATA RECOVERY. If ARCHIVING is enabled then these logs are bundled or archived and stored.
Branch coverage is a testing method, which aims to ensure that each one of the possible branch from each decision point is executed at least once and thereby ensuring that all reachable code is executed. That is, every branch taken each way, true and false.
This results in the index that is automatically generated being placed in the users default tablespace. Since this will usually be the same tablespace as the table is being created in, this can cause serious performance problems.
Thrashing can be solved by one or combination of the below :
1) Allocating the memory required by the program before executing.
2) If sufficient memory is not available, effective replacement algorithms for memory allocating should be used
3) One more way is to reduce the number of programs running currently.
4) From developers point of view, Large programs in memory can be replaced by small programs.
After receiving a Software build with the minor issues fixes in code or functionality, Sanity testing is carry out to check whether the bugs reported in previous build are fixed & there is regression introduced due to these fixes i.e. not breaking any previously working functionality. The main aim of Sanity testing to check the planned functionality is working as expected. Instead of doing whole regression testing the Sanity testing is perform.
To increase lookup performance. For a unique key to guarantee the uniqueness of the values for a column on a table.
The Join statement combines data from more that two tables .
Code-division multiple access (CDMA) is a channel access method used by various radio communication technologies.
CDMA is an example of multiple access, where several transmitters can send information simultaneously over a single communication channel.
Techniques generally used are direct sequence spread spectrum modulation (DS-CDMA), frequency hopping or mixed CDMA detection (JDCDMA). Here, a signal is generated which extends over a wide bandwidth. A code called spreading code is used to perform this action. Using a group of codes, which are orthogonal to each other, it is possible to select a signal with a given code in the presence of many other signals with different orthogonal codes.
Advantages of CDMA
CDMA has a soft capacity. The greater the number of codes, the more the number of users. It has the following advantages −
CDMA requires a tight power control, as it suffers from near-far effect. In other words, a user near the base station transmitting with the same power will drown the signal latter. All signals must have more or less equal power at the receiver
CDMA requires a tight power control, as it suffers from near-far effect. In other words, a user near the base station transmitting with the same power will drown the signal latter. All signals must have more or less equal power at the receiver
Rake receivers can be used to improve signal reception. Delayed versions of time (a chip or later) of the signal (multipath signals) can be collected and used to make decisions at the bit level.
Rake receivers can be used to improve signal reception. Delayed versions of time (a chip or later) of the signal (multipath signals) can be collected and used to make decisions at the bit level.
Primary Key constraint does not allow null values to be inserted while it is legal in case of Unique key.
n(n - 1) / 2
A mesh network is a fully connected network with every node (or computer/device) connected to every other node. The number of links is n(n - 1) / 2 which can be proved mathematically.
The issues are
i) Length of time required by the programmer in coding a particular sorting program
ii) Amount of machine time necessary for running the particular program
iii)The amount of space necessary for the particular program .
1.Prefix Notation: ^ – * +ABC – DE + FG
2.Postfix Notation: AB + C * DE – – FG + ^
The number of comparisons depends on where the record with the argument key appears in the table
If it appears at first position then one comparison
If it appears at last position then n comparisons
Average=(n+1)/2 comparisons
Unsuccessful search n comparisons Number of comparisons in any case is O (n).
A cross compiler is a compiler capable of creating executable code for a platform other than the one on which the compiler is running. For example, a compiler that runs on a Windows 7 PC but generates code that runs on Android smartphone is a cross compiler
A control flow graph (CFG) in computer science is a representation, using graph notation, of all paths that might be traversed through a program during its execution .
The term daemon is a UNIX term, though many other operating systems provide support for daemons, though they're sometimes called other names. Windows, for example, refers to daemons as System Agents and services.
Typical daemon processes include print spoolers, e-mail handlers, and other programs that perform administrative tasks for the operating system. The term comes from Greek mythology, where daemons were guardian spirits
The Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call, and to be called by, native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly .
They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a 0-argument constructor, and allows access to properties using getter and setter methods .
The java.util.SortedSet interface is a subtype of the java.util.Set interface. It behaves like a normal set with the exception that the elements are sorted internally. This means that when you iterate the elements of a SortedSet the elements are returned in thesorted order.
The elements can be sorted in two ways. One way is to use the Comparable interface. Objects can be compared using the compareTo() method. This approach is referred to as a natural order.
The other way is to specify a comparator for the elements in the set if the class doesn't implement the Comparable interface, or you don’t want to use the compareTo() method in the class that implements the Comparable interface. This approach is referred to as order by comparator .
When you do a shallow copy, all the fields of the source object is copied to target object as it is. That means, if there is a dynamically created field in the source object, shallow copy will copy the same pointer to target object. So you will have two objects with fields that are pointing to same memory location which is not what you usually want.
In case of deep copy, instead of copying the pointer, the object itself is copied to target. In this case if you modify the target object, it will not affect the source. By default copy constructors and assignment operators do shallow copy. To make it as deep copy, you need to create a custom copy constructor and override assignment operator.
Tool Selection – List down the automation tools compatible, depending on whether the application is Desktop / Web based, language used for software development etc
Scope of Automation – List down the scenarios and functionality which are repetitive and automatable
Planning – Design a framework, Schedule the scripting and execution of the same
iDevelopment – Scripting the scenarios to be tested with inputs(Test Data) and expected output
Execution – Running/Executing the scripts and reporting the results
vMaintenance – Update the scripts in accordance to the latest changes with the software under test .
Group policy provides the stream line access to all the users in the network, it can be used to define the users security and networking policies. By group policy you can keep control over certain function like not allowing the users to shut down the system or using the control panel or running the command. Group policy is applicable on active directory container like OU, site and Domain.
VPN means Virtual Private Network. It is a private communications network often used by companies or organizations to communicate confidentially over a public network. This is used by the mobile users in the network.
RAS means Remote Access Server. It allows operating the tool or information that typically resides on a network or IT devices through combination of hardware and software, for example connecting to printer or file. It is usually used for mobile users who are in the network. It uses telephone line to provide connectivity to its users. It can also connect two or more than two offices in the network.
A Blue Screen of Death (or just a Blue Screen Error) is an indication of a Critical System Problem wherein the Computer freezes altogether and does not respond to anything.
In distributed deadlock detection, the delay in propagating local information might cause the deadlock detection algorithms to identify deadlocks that do not really exist. Such situations are called phantom deadlocks and they lead to unnecessary aborts.
Shadowing is either through scope or through inheritance. Shadowing through inheritance is hiding a method of a base class and providing a new implementation for the same. This is the default when a derived class writes an implementation of a method of base class which is not declared as overridden in the base class. This also serves the purpose of protecting an implementation of a new method against subsequent addition of a method with the same name in the base class.’shadows’ keyword is recommended although not necessary since it is the default.
The Portable Executable (PE) format is a file format for executables, object code, DLLs, FON Font files, and others used in 32-bit and 64-bit versions of Windows operating systems.
IEEE 802 : LAN/MAN
IEEE 802.1 : Standards for LAN/MAN bridging and management and remote media access control bridging.
IEEE 802.2 : Standards for Logical Link Control (LLC) standards for connectivity.
IEEE 802.3 : Ethernet Standards for Carrier Sense Multiple Access with Collision Detection (CSMA/CD).
IEEE 802.4 : Standards for token passing bus access.
IEEE 802.5 : Standards for token ring access and for communications between LANs and MANs
IEEE 802.6 : Standards for information exchange between systems.
IEEE 802.7 : Standards for broadband LAN cabling.
IEEE 802.8 : Fiber optic connection.
IEEE 802.9 : Standards for integrated services, like voice and data.
IEEE 802.10 : Standards for LAN/MAN security implementations.
IEEE 802.11 : Wireless Networking "WiFi".
IEEE 802.12 : Standards for demand priority access method.
IEEE 802.14 : Standards for cable television broadband communications.
IEEE 802.15.1 : Bluetooth
IEEE 802.15.4 : Wireless Sensor/Control Networks "ZigBee"
IEEE 802.16 : Wireless Networking "WiMAX"
IEEE 802 : LAN/MAN
IEEE 802 : LAN/MAN
IEEE 802.1 : Standards for LAN/MAN bridging and management and remote media access control bridging.
IEEE 802.1 : Standards for LAN/MAN bridging and management and remote media access control bridging.
IEEE 802.2 : Standards for Logical Link Control (LLC) standards for connectivity.
IEEE 802.2 : Standards for Logical Link Control (LLC) standards for connectivity.
IEEE 802.3 : Ethernet Standards for Carrier Sense Multiple Access with Collision Detection (CSMA/CD).
IEEE 802.3 : Ethernet Standards for Carrier Sense Multiple Access with Collision Detection (CSMA/CD).
IEEE 802.4 : Standards for token passing bus access.
IEEE 802.4 : Standards for token passing bus access.
IEEE 802.5 : Standards for token ring access and for communications between LANs and MANs
IEEE 802.5 : Standards for token ring access and for communications between LANs and MANs
IEEE 802.6 : Standards for information exchange between systems.
IEEE 802.6 : Standards for information exchange between systems.
IEEE 802.7 : Standards for broadband LAN cabling.
IEEE 802.7 : Standards for broadband LAN cabling.
IEEE 802.8 : Fiber optic connection.
IEEE 802.8 : Fiber optic connection.
IEEE 802.9 : Standards for integrated services, like voice and data.
IEEE 802.9 : Standards for integrated services, like voice and data.
IEEE 802.10 : Standards for LAN/MAN security implementations.
IEEE 802.10 : Standards for LAN/MAN security implementations.
IEEE 802.11 : Wireless Networking "WiFi".
IEEE 802.11 : Wireless Networking "WiFi".
IEEE 802.12 : Standards for demand priority access method.
IEEE 802.12 : Standards for demand priority access method.
IEEE 802.14 : Standards for cable television broadband communications.
IEEE 802.14 : Standards for cable television broadband communications.
IEEE 802.15.1 : Bluetooth
IEEE 802.15.1 : Bluetooth
IEEE 802.15.4 : Wireless Sensor/Control Networks "ZigBee"
IEEE 802.15.4 : Wireless Sensor/Control Networks "ZigBee"
IEEE 802.16 : Wireless Networking "WiMAX"
IEEE 802.16 : Wireless Networking "WiMAX"
Three ranges of IP addresses have been reserved for private address and they are not valid for use on the Internet. If you want to access internet with these address you must have to use proxy server or NAT server (on normal cases the role of proxy server is played by your ISP.).If you do decide to implement a private IP address range, you can use IP addresses from any of the following classes:
Class A : 10.0.0.0 10.255.255.255
Class B : 172.16.0.0 172.31.255.255
Class C : 192.168.0.0 192.168.255.255
Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created. A very simple immutable object is an object without any field .
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference.
It is a feature in C++ to minimize name collisions in the global name space. This namespace keyword assigns a distinct name to a library that allows other libraries to use the same identifier names without creating any name collisions. Furthermore, the compiler uses the namespace signature for differentiating the definitions.
Union is a collection of data items of different data types.
It can hold data of only one member at a time though it has members of different data types.
If a union has two members of different data types, they are allocated the same memory. The memory allocated is equal to maximum size of the members. The data is interpreted in bytes depending on which member is being accessed.
Example:
union pen {
char name;
float point;
};
Here name and point are union members. Out of these two variables, point is larger variable which is of float data type and it would need 4 bytes of memory. Therefore 4 bytes space is allocated for both the variables. Both the variables have the same memory location. They are accessed according to their type.
Union is efficient when members of it are not required to be accessed at the same time
The file positioning of a stream describes where in the file the stream is currently reading or writing. I/O on the stream advances the file position through the file. On GNU systems, the file position is represented as an integer, which counts the number of bytes from the beginning of the file.
A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.
De-normalization is the process of attempting to optimize the performance of a database by adding redundant data. It is sometimes necessary because current DBMSs implement the relational model poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while providing physical storage of data that is tuned for high performance. De-normalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access.
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused.
A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
Float is used when you want to make an element of your page (usually an image) be pushed to the right or left and make other elements wrap around it.
his can be tricky and the best way to keep in your head is to memorise because if you try to relate java script null to other languages, it will get more confusing.
In java script, null is an object with no value and undefined is a type.
typeof null; // "object"
typeof undefined; // "undefined"
var a;
var b = null;
a == b; // "true" because their values are the same
a === b; // "false". they have different types
There are several technical differences between these two types of requests, regarding length limitation, security, caching and a few others. But if someone asks you WHEN would you use it, I'd say one of the most important points that any front-end developer should take into account is that we should only use GET foridempotent requests, it means requests that don't make significant changes in the backend system or database but if you do need to make inserts, updates or deletes in a database, trigger emails or any other major action, POST is recommended.
That's pretty much it that I wanted to share according to my recent interviews and I believe you'll come across some of these questions or a variation of them in your next technical interview.
XHTML is an HTML that follows the XML rules, which means a XHTML document must have well-formed markups in order to be rendered properly in all web browsers. Differently from XHTML, the HTML document can be rendered in most of the browsers even with markup errors such as no closing tags or wrong nested tags.
And how do I create a XHTML document?
XHTML is basically a HTML document with some rules that need to be applied. Have a look at these examples below and spot the differences.
<head>
<title>This is head</title>
</head>
<BODY>
This is the body of the document with body tag in capital letters
Notice that there's no close body tag and no tag as well.
This HTML document above can be opened with no problems in Chrome, even containing many markup errors because most browsers can fix them for you automatically.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
</body>
</html>
The code above is a well-formed XHTML document and that's the minimum you must have in order to render it. Notice the declaration of the doctype at the top of the document and the namespace (xmlns) attribute in html open tag. These elements are mandatory as well as all the tags in lowercase.
Stack. Because of its LIFO (Last In First Out) property it remembers its 'caller' so knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls.
Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used.
The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events raised by ASP.NET or by HttpModules. The Global.asax file resides in the root directory of an ASP.NET-based application.
A link is a second name (not a file) for a file. Links can be used to assign more than one name to a file, but cannot be used to assign a directory more than one name or link filenames on different computers.
Symbolic link 'is' a file that only contains the name of another file.Operation on the symbolic link is directed to the file pointed by the it.Both the limitations of links are eliminated in symbolic links.
Commands for linking files are:
Link "ln filename1 filename2"
Symbolic link "ln -s filename1 filename2"
Interpolation search is an algorithm for searching for a given key in an indexed array that has been ordered by numerical values assigned to the keys (key values). It parallels how humans search through a telephone book for a particular name, the key value by which the book's entries are ordered.
SCSI - Small computer systems interface is a type of interface used for computer components such as hard drives, optical drives, scanners and tape drives. It is a competing technology to standard IDE (Integrated Drive Electronics).
To achieve maximum efficiency and reliability a mode of operation known as symmetric multiprocessing is used. In essence, with SMP any process or threads can be assigned to any processor.
The process that allows a network to self-repair networks problems. The stations on the network notify the other stations on the ring when they are not receiving the transmissions. Beaconing is used in Token ring and FDDI networks.
APIPA. (Automatic Private IP Addressing) The Windows function that provides DHCP autoconfiguration addressing. APIPA assigns a class B IP address from 169.254.0.0 to 169.254.255.255 to the client when a DHCP server is either permanently or temporarily unavailable.
The LMHOSTS file is a static method of resolving NetBIOS names to IP addresses in the same way that the HOSTS file is a static method of resolving domain names into IP addresses. An LMHOSTS file is a text file that maps NetBIOS names to IP addresses; it must be manually configured and updated.
POP3 stands for Post Office Protocol Version3 (Current Version). POP is a protocol which listens on port 110 and is responsible for accessing the mail service on a client machine. POP3 works in two modes such as Delete Mode and Keep Mode.
a) Delete Mode: A mail is deleted from the mailbox after successful retrieval.
b) Keep Mode: The Mail remains Intact in the mailbox after successful retrieval.
A network Reliability is measured on following factors.
a) Downtime: The time it takes to recover.
b) Failure Frequency: The frequency when it fails to work the way it is intended.
An object-relational database (ORD), or object-relational database management system (ORDBMS), is a database management system (DBMS) similar to a relational database, but with an object-oriented database model: objects, classes and inheritance are directly supported in database schemas and in the query language. In addition, just as with proper relational systems, it supports extension of the data model with custom data-types and methods.
The terms EXE and DLL are very common in programming. When coding, you can either export your final project to either a DLL or an EXE. The term EXE is a shortened version of the word executable as it identifies the file as a program. On the other hand, DLL stands for Dynamic Link Library, which commonly contains functions and procedures that can be used by other programs .
A DLL is a library and therefore can not be executed. If you try to run it you'll get an error about a missing entry point. An EXE is a program that can be executed. It has an entry point. A flag inside the PE header indicates which file type it is (irrelevant of file extension).
.A DLL would share the same process and memory space of the calling application while an EXE creates its separate process and memory space.
A data source name (DSN) is a data structure that contains the information about a specific database that an Open Database Connectivity ( ODBC ) driver needs in order to connect to it. DSNs also exist for JDBC and for other data access mechanisms. The term often overlaps with "connection string". Most systems do not make a distinction between DSNs or connection strings and the term can often be used interchangeably.
Types of DSN
There are three types of DSNs:
System DSN -- can be used by anyone who has access to the machine. DSN info is stored in the registry.
User DSN -- created for a specific user. Also stored in the registry.
File DSN-- DSN info is stored in a text file with .DSN extension.
There is also what is known as a "DSN-less connection." Instead of using a DSN to connect to a database, the developer specifies the necessary information right in the application.
The term "schema" refers to the organization of data as a blueprint of how the database is constructed (divided into database tables in the case of relational databases). The formal definition of a database schema is a set of formulas (sentences) called integrity constraints imposed on a database .
Null pointer is a special reserved value of a pointer. Apointer of any type has such a reserved value. Formally, each specific pointer type ( int * , char * etc.) has its own dedicated null-pointer value. Conceptually, when a pointer has that null value it is not pointing anywhere.
Example :
int * pInt = NULL;
Waiting (Device) Queues: The set of processes waiting for allocation of certain I/Odevices is kept in the waiting (device) queue. The short-term scheduler (also known as CPU scheduling) selects a process from the ready queue and yields control of the CPU to the process
marshalling is the process of gathering data from one or more application s or non-contiguous sources in computer storage, putting the data pieces into a message buffer , and organizing or converting the data into a format that is prescribed for a particular receiver or programming interface.
Trapdoor is a secret undocumented entry point into a program used to grant access without normal methods of access authentication. A trap is a software interrupt, usually the result of an error condition.
When a software testing performed without proper planning and documentation, it is said to be Adhoc Testing. Such kind of tests are executed only once unless we uncover the defects.
The tests are intended to be run only once, unless a defect is discovered. Adhoc testing is the least formal test method. As such, it has been criticized because it is not structured and hence defects found using this method may be harder to reproduce (since there are no written test cases). However, the strength of adhoc testing is that important defects can be found quickly.
Boundary testing or boundary value analysis, is where test cases are generated using the extremes of the input domain, e.g. maximum, minimum, just inside/outside boundaries, typical values, and error values. It is similar to Equivalence Partitioning but focuses on "corner cases" .
Redundant array of inexpensive (or independent) disks. The main goal of raid technology is to even out the widely different rates of performance improvement of disks against those in memory and microprocessor. Raid technology employs the technique of data striping to achieve higher transfer rates.
DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.
The general strategy in a Markov Algorithm is to take as input a string x and, through a number of steps in the algorithm, transform x to an output string y. this transformation process is generally performed in computers for text editing or program compilation.
These are the following arguments which are present in pattern matching Algorithms.
1) Subject,
2) Pattern
3) Cursor
4) MATCH_STR
5) REPLACE_STR
6) REPLACE_FLAG
Packages are schema objects that groups logically related PL/SQL types, variables, and subprograms.
A package will have two mandatory parts −
Package specification
Package body or definition .
Package Specification
CREATE PACKAGE cust_sal AS
PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/
Package Body
CREATE OR REPLACE PACKAGE BODY cust_sal AS
PROCEDURE find_sal(c_id customers.id%TYPE) IS
c_sal customers.salary%TYPE;
BEGIN
SELECT salary INTO c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line('Salary: '|| c_sal);
END find_sal;
END cust_sal;
/
Grep is an amazing utility on command line. Every one might have heard of grep. It's a great tool to search for a pattern with in a directory or in a file. On searching for a pattern using grep, the default result will print the pattern along with the line number at which the pattern is found. Grep is one of those handy commands on bash that are often used.
Pre requisites for grep
Grep comes installed with an ubuntu machine, if it is not installed, it could be done using,
sudo apt-get grep install;
grep and egrep
I have played around with grep for a while, at some point I have noticed egrep. grep and egrep does the same function, but the way they interpret the pattern is the only difference.
Grep stands for "Global Regular Expressions Print", were as Egrep for "Extended Global Regular Expressions Print". The pattern often treated as a regular expression, for which e in egrep stands for "Extended Regular Expressions" abbreviated 'ERE' is enabled in egrep.
grep -E is same as egrep
In egrep, +, ?, |, (, and ), treated as meta characters. Where as in grep, they are rather treated as pattern instead of meta characters. By including 'backslash' followed by meta character can let the grep to treat it as meta characters like \?, \+, \{, \|, \(, and \).
ls | grep '.txt|.php
With the help of Apache Commons Net API, it is easy to write Java code for downloading a file from a remote FTP server to local computer.
Http Handlers:
Http handlers are component developed by asp.net developers to work as end point to asp.net pipeline. It has to implement System.Web.IHttpHandler interface and this will act as target for asp.net requests. Handlers can be act as ISAPI dlls the only difference between ISAPI dlls and HTTP Handlers are Handlers can be called directly URL as compare to ISAPI Dlls.
Http Modules:
Http modules are objects which also participate in the asp.net request pipeline but it does job after and before HTTP Handlers complete its work. For example it will associate a session and cache with asp.net request. It implements System.Web.IHttpModule interface.
HTTP Handler implement following Methods and Properties
Process Request: This method is called when processing asp.net requests. Here you can perform all the things related to processing request.
IsReusable: This property is to determine whether same instance of HTTP Handler can be used to fulfill another request of same type.
Process Request: This method is called when processing asp.net requests. Here you can perform all the things related to processing request.
IsReusable: This property is to determine whether same instance of HTTP Handler can be used to fulfill another request of same type.
Typical uses for custom HTTP handlers include the following:
RSS feeds To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.
RSS feeds To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.
Image server If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler's response.
Image server If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler's response.
Typical uses for HTTP modules include the following:
Security Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application.
Security Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application.
Statistics and logging Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.
Statistics and logging Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.
Custom headers or footers Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.
Custom headers or footers Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.
Features
HTTP handler and module features include the following:
The IHttpHandler and IHttpModule interfaces are the starting point for developing handlers and modules.
The IHttpHandler and IHttpModule interfaces are the starting point for developing handlers and modules.
The IHttpAsyncHandler interface is the starting point for developing asynchronous handlers.
The IHttpAsyncHandler interface is the starting point for developing asynchronous handlers.
Custom handler and module source code can be put in the App_Code folder of an application, or it can be compiled and put in the Bin folder of an application.
Custom handler and module source code can be put in the App_Code folder of an application, or it can be compiled and put in the Bin folder of an application.
Handlers and modules developed for use in IIS 6.0 can be used in IIS 7.0 with little or no change.
Handlers and modules developed for use in IIS 6.0 can be used in IIS 7.0 with little or no change.
LockObjects always starts with character 'E'
The static identifier is used for initializing only once, and the value retains during the life time of the program / application. A separate memory is allocated for static variables. This value can be used between function calls. The default value of an un initialized static variable is zero. A function can also be defined as a static function, which has the same scope of the static variable .
Most of the times when we are developing an application in java, we often feel a need to create and throw our own exceptions. These exceptions are known as User defined or Custom exceptions.
Let's see a simple example of java custom exception.
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
There are 5 operators which cannot be overloaded :
.* - class member access operator
:: - scope resolution operator
. - dot operator
?:: - conditional operator
Sizeof() - operator
Macro execution is faster than function execution because in function, much of time is used to take control from function call to called function and much of time is spent in this process. Whereas in macro expression are directly replaced in the source code.Much of time is spent in the binding of the function to the caller function.
The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.The DOM provides a representation of the document as a structured group of nodes and objects that have properties and methods. Essentially, it connects web pages to scripts or programming languages.
Microsoft SQL Server Profiler is a graphical user interface to SQL Trace for monitoring an instance of the Database Engine or Analysis Services. You can capture and save data about each event to a file or table to analyze later .
SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as which SQL Scripts are running, failed jobs etc.
SQL> delete from table_name where rowid not in (select max(rowid) from table group by duplicate_values_field_name);
structure :- In structure have a by default public.
In class have a by default private.
Structure cannot be inherited. But class can be
inherit.
There is no data hiding features comes with
structures. Classes do, private, protected and public.
When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.
For example program 3 fails in compilation and program 4 works fine.
// Program 3
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // is equilalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // compiler error becuase inheritance is private
getchar();
return 0;
}
When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.
For example program 3 fails in compilation and program 4 works fine.
// Program 3
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // is equilalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // compiler error becuase inheritance is private
getchar();
return 0;
}
Stack unwinding is a process of calling all destructors for all automatic objects constructed at run time when an exception is thrown. Destructors are called between the places where the exception was thrown and where it is caught.
for detail :http://www.geeksforgeeks.org/stack-unwinding-in-c/
XML is case sensitive when uppercase and lowercase characters are treated differently.
Element type names, Attribute names, Attribute values, All general and parameter entity names, and data content (text), are case-sensitive.
Project plan, Requirements, Design, Coding, Testing, Re-coding and design, Development, Maintenance.
An Internet Protocol address (IP address) is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication.An IP address serves two principal functions: host or network interface identification and location addressing .
Portability focuses on adaptation of software in various OS, by recompiling the source to make the binary compatible with the target OS and not necessarily modifying the source. If the source code strictly follows POSIX standard less likely one end up modifying it.
Platform independence focuses on ability of software to run on VIRTUAL hardware that inturn interfaces with the PHYSICAL hardware. Examples of cross-platform or platform independent languages are Python, JavaScript, Java etc
An interrupt is a signal from a device attached to a computer or from a program within the computer that requires the operating system to stop and figure out what to do next.
The processor responds by suspending its current activities, saving its state, and executing a function called an interrupt handler (or an interrupt service routine, ISR) to deal with the event. This interruption is temporary, and, after the interrupt handler finishes, the processor resumes normal activities.
Static is an access qualifier. If a variable is declared as static inside a function, the scope is limited to the function,but it will exists for the life time of the program. Values will be persisted between successive
calls to a function .
For example :
#include<stdio.h>
int fun()
{
static int count = 0;
count++;
return count;
}
int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}
Output:
1 2
An enumeration is a user-defined data type that consists of integral constants. To define an enumeration, keyword enum is used.
enum flag { const1, const2, ..., constN };
Garbage collection is the systematic recovery of pooled computer storage that is being used by a program when that program no longer needs the storage. This frees the storage for use by other programs
(or processes within a program). It also ensures that a program using increasing amounts of pooled storage does not reach its quota (in which case it may no longer be able to function).
Garbage collection is an automatic memory management feature in many modern programming languages, such as Java and languages in the .NET framework. Languages that use garbage collection are often interpreted or run within a virtual machine like the JVM. In each case, the environment that runs the code is also responsible for garbage collection.
A spanning tree is a subset of Graph G, which has all the vertices covered with minimum possible number of edges. Hence, a spanning tree does not have cycles and it cannot be disconnected.. By this definition, we can draw a conclusion that every connected and undirected Graph G has at least one spanning tree
A friend function for a class is used in object-oriented programming to allow access to public, private, or protected data in the class from the outside.
Normally, a function that is not a member of a class cannot access such information; neither can an external class. Occasionally, such access will be advantageous for the programmer. Under these circumstances, the function or external class can be declared as a friend of the class using the friend keyword .
ifdef means "if the following is defined" while ifndef means "if the following is not defined". So:
#define one
#ifdef one printf("one is defined ");
#endif #ifndef one printf("one is not defined ");
#endif. is equivalent to: printf("one is defined ");
The keyword delete is used to destroy the single variable memory created dynamically which is pointed by single pointer variable.
Eg: int *r=new(int)
the memory pointed by r can be deleted by delete r.
delete [] is used to destroy array of memory pointed by single pointer variable.
Eg:int *r=new(int a[10])
The memory pointed by r can be deleted by delete [].
Alignment refers to the arrangement of data in memory, and specifically deals with the issue of accessing data as proper units of information from main memory.
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.
A Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a Java program. There are three notions of the JVM: specification, implementation, and instance. ... An instance of a JVM is an implementation running in a process that executes a computer program compiled into Java bytecode.
A debugger is a computer program used by programmers to test and debug a target program. Debuggers may use instruction-set simulators, rather than running a program directly on the processor to achieve a higher level of control over its execution.
Getting the arguments from command prompt in c is known as command line arguments. In c main function has three arguments.They are:
Argument counter
Argument vector
Environment vector
The two types of integrity rules are referential integrity rules and entity integrity rules. Referential integrity rules dictate that a database does not contain orphan foreign key values. This means that
A primary key value cannot be modified if the value is used as a foreign key in a child table. Entity integrity dictates that the primary key value cannot be Null.
inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.
A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look like when they are used.
Example :
#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)
int main()
{
int radius;
float area;
printf("Enter the radius: ");
scanf("%d", &radius);
area = circleArea(radius);
printf("Area = %.2f", area);
return 0;
%p in printf to print the address.
Product based company : company/group which makes some product may it software, hardware or any other. Also it's not compulsive that, company sell their product. Only requirement is that company should make product.
Service based company : company which ability/offer services to their clients. They don't make anything. Just provide services. For example printer service they don't make printer not cartige nor ink but offer service to customers of refilling cartige, ink etc.
Project can be anything. On anything.
Deadlines are mostly defined by clients.
Less innovation and flexibility.
More strictness and mutil tasking.
Client will be dissatisfied mostly.
You would get expert on the language u are working. But you cannot learn new. Because u dont have time.
In case of small scale, company might fire you on the basis of no new projects or clients saying of ur performance
Project can be anything. On anything.
Deadlines are mostly defined by clients.
Less innovation and flexibility.
More strictness and mutil tasking.
Client will be dissatisfied mostly.
You would get expert on the language u are working. But you cannot learn new. Because u dont have time.
In case of small scale, company might fire you on the basis of no new projects or clients saying of ur performance
The third normal form (3NF) is a normal form used in database normalization. ... Codd's definition states that a table is in 3NF
if and only if both of the following conditions hold:
The relation R (table) is in second normal form (2NF)
Every non-prime attribute of R is non-transitively dependent on every key of R.
For example, in the following table – the street name, city and the state are unbreakably bound to their zip code.
CREATE TABLE CUSTOMERS(
CUST_ID INT NOT NULL,
CUST_NAME VARCHAR (20) NOT NULL,
DOB DATE,
STREET VARCHAR(200),
CITY VARCHAR(100),
STATE VARCHAR(100),
ZIP VARCHAR(12),
EMAIL_ID VARCHAR(256),
PRIMARY KEY (CUST_ID)
);
The dependency between the zip code and the address is called as a transitive dependency. To comply with the third normal form, all you need to do is to move the Street, City and the State fields into their own table, which you can call as the Zip Code table. −
CREATE TABLE ADDRESS(
ZIP VARCHAR(12),
STREET VARCHAR(200),
CITY VARCHAR(100),
STATE VARCHAR(100),
PRIMARY KEY (ZIP)
);
JSP is a webpage scripting language that can generate dynamic content while Servlets are Java programs that are already compiled which also creates dynamic web content
Servlets run faster compared to JSP .
JSP is a technology that allows you to write dynamic HTTP response with static data mixed with dynamic data with special tags.
Servlet is a technology that allows you to write dynamic HTTP response with a Java class.
Servlet will accept all protocol request but JSP only accept http protocol request.
Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages through the use of servlets, small programs that are specified in the Web page and run on the Web server to modify the Web page before it is sent to the user who requested it.
A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing Java Beans components, passing control between pages, and sharing information between requests, pages etc.
Following diagram shows the position of JSP container and JSP files in a Web application.
Servlet technology is used to create web application (resides at server side and generates dynamic web page).
A servlet is a Web component that is managed by a container and generates dynamic content. Servlets are Java classes that are compiled to byte code that can be loaded dynamically into and run by a Java technology-enabled Web server or Servlet container
Servlet can be described in many ways, depending on the context.
Servlet is a technology i.e. used to create web application.
Servlet is an API that provides many interfaces and classes including documentations.
Servlet is an interface that must be implemented for creating any servlet.
Encoding:
Encoding is the process of converting data into various formats in which to be used on a different device or system. The encoding process uses publicly available methods in which to transform data. An encoding method could be used to convert Base 10 (binary) data into Base 16 (hex).
Example: Changing data type from ASCII to UTF.
Encryption:
Encryption is the process of scrambling data to make it decipherable only by the intended recipients. Typically, the recipients who are authorized to view the data are provided a matching key string in which the data was encrypted with, they then apply the secret key to the scrambled data and convert it back into clear text.
Example: Sending sensitive information over public medium.
Encoding is for maintaining data usability and can be reversed by employing the same algorithm that encoded the content, i.e. no key is used.
Encryption is for maintaining data confidentiality and requires the use of a key (kept secret) in order to return to plain text.
A software requirements specification (SRS) is a description of a software system to be developed. It lays out functional and non-functional requirements, and may include a set of use cases that describe user interactions that the software must provide .
This document lays a foundation for software engineering activities and is created when entire requirements are elicited and analyzed.
Advantages
Software SRS establishes the basic for agreement between the client and the supplier on what the software product will do.
1. A SRS provides a reference for validation of the final product.
2. A high-quality SRS is a prerequisite to high-quality software.
3. A high-quality SRS reduces the development cost.
Characteristics of an SRS
1. Correct
2. Complete
3. Unambiguous
4. Verifiable
5. Consistent
6. Ranked for importance and/or stability
7. Modifiable
8. Traceable
WHERE clause introduces a condition on individual rows; HAVING clause introduces a condition on aggregations, i.e. results of selection where a single result, such as count, average, min, max, or sum, has been produced from multiple rows.
Apart from SELECT queries, you can use WHERE clause with UPDATE and DELETE clause but HAVING clause can only be used with SELECT query. For example following query, which involve WHERE clause will work but other which uses HAVING clause will not work .
A WHERE clause is used is filter records from a result. The filter occurs before any groupings are made.
A HAVING clause is used to filter values from a group.
WHERE is used to filter records before any groupings take place.
HAVING is used to filter values after they have been groups. Only columns or expression in the group can be included in the HAVING clause’s conditions..
Computer data interchange format used mainly as a datastorage and network transfer format in the MongoDB database. It is a binary form for representing simple data structures, associative arrays (called objects or documents in MongoDB), and various data types of specific interest to MongoDB .
Normalization is a database design technique which organizes tables in a manner that reduces redundancy and dependency of data .
Normalization is a process of organizing the data in database to avoid data redundancy, insertion anomaly, update anomaly & deletion anomaly.
Normalization in DBMS: 1NF, 2NF, 3NF and BCNF in Database. Normalization is a process of organizing the data in database to avoid data redundancy, insertion anomaly, update anomaly & deletion anomaly.
In computing, the star schema is the simplest style of data mart schema and is the approach most widely used to develop data warehouses and dimensional data marts. The star schema consists of one or more fact tables referencing any number of dimension tables.
GET method sends the data in the form of key-value pairs in the URL. This is a serious security flaw as anyone can then send data to your server by just typing out the URL in the address bar and altering data in the server, unless you have extra security measures like CSRF tokens, cookies etc.
POST method does not send the data through the URLs. Therefore, web requests cannot be spoofed through the URLs.
Hence, it is a better practice to use GET over POST.
maintainability is defined as the degree to which an application is understood, repaired, or enhanced. ... Understanding software maintainability allows organizations to identify improvement areas as well as determine the value supplied by current applications or during development changes .
compatibility (countable and uncountable, plural compatibilities) The state of being compatible; in which two or more things are able to exist or work together in combination without problems or conflict.
Modularity is the degree to which a system's components may be separated and recombined. The meaning of the word, however, can vary somewhat by context. In biology,modularity is the concept that organisms or metabolic pathways are composed of modules .
A public key infrastructure (PKI) supports the distribution and identification of public encryption keys, enabling users and computers to both securely exchange data over networks such as the Internet and verify the identity of the other party.
The purpose of a PKI is to facilitate the secure electronic transfer of information for a range of network activities such as e-commerce, internet banking and confidential email.
A typical PKI includes the following key elements:
A trusted party, called a certificate authority (CA), acts as the root of trust and provides services that authenticate the identity of individuals, computers and other entities
A registration authority, often called a subordinate CA, certified by a root CA to issue certificates for specific uses permitted by the root
A certificate database, which stores certificate requests and issues and revokes certificates .
Load balancing is dividing the amount of work that a computer has to do between two or more computers so that more work gets done in the same amount of time and, in general, all users get served faster. Load balancing can be implemented with hardware, software, or a combination of both.
A load balancer acts as the “traffic cop” sitting in front of your servers and routing client requests across all servers capable of fulfilling those requests in a manner that maximizes speed and capacity utilization and ensures that no one server is overworked, which could degrade performance.
Load balancing usually involves dedicated software or hardware, such as a multilayer switch or a Domain Name System server process.
a load balancer performs the following functions:
Distributes client requests or network load efficiently across multiple servers
Ensures high availability and reliability by sending requests only to servers that are online
Black-box testing is a method of software testing that examines the functionality of an application without peering into its internal structures or workings. This method of test can be applied virtually to every level of software testing: unit, integration, system and acceptance .
This method of test can be applied virtually to every level of software testing: unit, integration,system and acceptance. It typically comprises most if not all higher level testing, but can also embody unit testing .
his method is named so because the software program, in the eyes of the tester, is like a black box; inside which one cannot see. This method attempts to find errors in the following categories:
Incorrect or missing functions
Interface errors
Errors in data structures or external database access
Behavior or performance errors .
Behavioural Testing Techniques:
There are different techniques involved in Black Box testing.
Equivalence Class
Equivalence Class
Boundary Value Analysis
Boundary Value Analysis
Domain Tests
Domain Tests
Orthogonal Arrays
Orthogonal Arrays
Decision Tables
Decision Tables
State Models
State Models
White-box testing (also known as clear box testing, glass box testing, transparent box testing, and structural testing) is a method of testing software that tests internal structures or workings of an application, as opposed to its functionality (i.e. black-box testing).
In white-box testing an internal perspective of the system, as well as programming skills, are used to design test cases. The tester chooses inputs to exercise paths through the code and determine the appropriate outputs .
Typically such method are used at Unit Testing of the code but this different as Unit testing done by the developer & White Box Testing done by the testers, this is learning the part of the code & finding out the weakness in the software program under test .
White Box Testing Techniques:
Statement Coverage - This technique is aimed at exercising all programming statements with minimal tests.
Statement Coverage - This technique is aimed at exercising all programming statements with minimal tests.
Branch Coverage - This technique is running a series of tests to ensure that all branches are tested at least once.
Branch Coverage - This technique is running a series of tests to ensure that all branches are tested at least once.
Path Coverage - This technique corresponds to testing all possible paths which means that each statement and branch is covered.
Path Coverage - This technique corresponds to testing all possible paths which means that each statement and branch is covered.
IPv4 and IPv6 are two generations of Internet Protocols where IPv4 stands for Internet Protocol version 4 and IPv6 for Internet Protocol version 6.
IPv6 is more advanced and has better features compared to IPv4. It has the capability to provide an infinite number of addresses. It is replacing IPv4 to accommodate the growing number of networks worldwide and help solve the IP address exhaustion problem. IPv6 was developed by the Internet Engineering Task Force (IETF) .
One of the main difference between IPv4 and IPv6 is their address space. As we already said the size of an address in IPv4 is 32-bits. Where IPv6 address fields are 128-bits.
Checksum field is available in IPv4 header.No checksum field in IPv6 header.
IPv4 Internet Group Management Protocol (IGMP) is used to manage multicast group membership.IPv6 IGMP is replaced with Multicast Listener Discovery (MLD) messages.
Advantages of IPv6 over IPv4
IPv6 simplified the router’s task compared to IPv4.
IPv6 is more compatible to mobile networks than IPv4.
IPv6 allows for bigger payloads than what is allowed in IPv4.
IPv6 is used by less than 1% of the networks, while IPv4 is still in use by the remaining 99%.
Network Address Translation (NAT) is the process where a network device, usually a firewall, assigns a public address to a computer (or group of computers) inside a private network. The main use of NAT is to limit the number of public IP addresses an organization or company must use, for both economy and security purposes.
NAT conserves the number of globally valid IP addresses a company needs, and in combination with Classless Inter-Domain Routing (CIDR) has done a lot to extend the useful life of IPv4 as a result .
The Purpose of NAT
NAT serves three main purposes:
Provides a type of firewall hiding internal IP addresses
Enables a company to use more internal IP addresses. Since they're used internally only, there's no possibility of conflict with IP addresses used by other companies and organizations.
Allows a company to combine multiple ISDN connections into a single Internet connection .
A race condition is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time, but because of the nature of the device or system, the operations must be done in the proper sequence to be done correctly .
A Job scheduling system allows one process to use the CPU while another is waiting for I/O, thereby making full use of otherwise lost CPU cycles.
The challenge is to make the overall system as "efficient" and "fair" as possible, subject to varying and often dynamic conditions, and where "efficient" and "fair" are somewhat subjective terms, often subject to shifting priority policy .
A Job scheduling is the method by which work specified by some means is assigned to resources that complete the work. The work may be virtual computation elements such as threads, processes or data flows, which are in turn scheduled onto hardware resources such as processors, network links or expansion cards.
Eavesdropping :the majority of network communications occur in an unsecured or "clear text" format, which allows an attacker who has gained access to data paths in your network to "listen in" or interpret (read) the traffic.
Denial-of-Service Attack :Randomize the attention of your internal Information Systems staff so that they do not see the intrusion immediately, which allows the attacker to make more attacks during the diversion.
Denial-of-Service Attack :Randomize the attention of your internal Information Systems staff so that they do not see the intrusion immediately, which allows the attacker to make more attacks during the diversion.
Modification Attacks Changing Information
Modification Attacks Changing Information
Example: We just modified your HomePage!
Trojan Horses :A Trojan horse or Trojan is a file or e-mail attachment disguised as a friendly, legitimate file. When executed though, the file corrupts data and can even install a backdoor that hackers can utilize to access the network.
Trojan Horses :A Trojan horse or Trojan is a file or e-mail attachment disguised as a friendly, legitimate file. When executed though, the file corrupts data and can even install a backdoor that hackers can utilize to access the network.
Man-in-the-Middle Attack :As the name indicates, a man-in-the-middle attack occurs when someone between you and the person with whom you are communicating is actively monitoring, capturing, and controlling your communication transparently.
Man-in-the-Middle Attack :As the name indicates, a man-in-the-middle attack occurs when someone between you and the person with whom you are communicating is actively monitoring, capturing, and controlling your communication transparently.
DDoS is short for Distributed Denial of Service. DDoS is a type of DOS attack where multiple compromised systems, which are often infected with a Trojan, are used to target a single system causing a Denial of Service (DoS) attack.
DDoS threats come in many flavors, with some directly targeting the underlying server infrastructure. Others exploit vulnerabilities in application and communication protocols.
The DDoS attack uses multiple computers and Internet connections to flood the targeted resource. DDoS attacks are often global attacks, distributed via botnets.
Types of DDoS Attacks
Traffic attacks: Traffic flooding attacks send a huge volume of TCP, UDP and ICPM packets to the target. Legitimate requests get lost and these attacks may be accompanied by malware exploitation.
Bandwidth attacks: This DDos attack overloads the target with massive amounts of junk data. This results in a loss of network bandwidth and equipment resources and can lead to a complete denial of service.
They can be either network- or host-based. A host-based intrusion detection system is installed on the client computer, while a network-based intrusion detection system resides on the network. intrusion detection systems work by either looking for signatures of known attacks or deviations of normal activity.
intrusion detection systems work by either looking for signatures of known attacks or deviations of normal activity. These deviations or anomalies are pushed up the stack and examined at the protocol and application layer. They can effectively detect things such as Xmas tree scans, DNS poisonings, and other malformed packets.
IPS or intrusion prevention system, is definitely the next level of security technology with its capability to provide security at all system levels from the operating system kernel to network data packets. It provides policies and rules for network traffic along with an IDS for alerting system or network administrators to suspicious traffic, but allows the administrator to provide the action upon being alerted. Where IDS informs of a potential attack, an IPS makes attempts to stop it.
These security measures are available as intrusion detection systems (IDS) and intrusion prevention systems (IPS), which become part of your network to detect and stop potential incidents.
Signature-Based Detection compares signatures against observed events to identify possible incidents. This is the simplest detection method because it compares only the current unit of activity (such as a packet or a log entry, to a list of signatures) using string comparison operations.
Micro kernel is a kernel which run services those are minimal for operating system performance. In this kernel all other operations are performed by processor. Macro Kernel is a combination of micro and monolithic kernel. In monolithic kernel all operating system code is in single executable image.
Micro kernel is a kernel which run services those are minimal for operating system performance. In this kernel all other operations are performed by processor. Macro Kernel is a combination of micro and monolithic kernel. In monolithic kernel all operating system code is in single executable image.
Monolithic kernels are faster than microkernels. The first microkernel Mach was 50% slower than Monolithic kernel, while later version like L4 were only 2% or 4% slower than the Monolithic kernel .
Monolithic kernels are faster than microkernels. The first microkernel Mach was 50% slower than Monolithic kernel, while later version like L4 were only 2% or 4% slower than the Monolithic kernel .
Adding a new feature to a monolithic system means recompiling the whole kernel, whereas with microkernels you can add new features or patches without recompiling.
Adding a new feature to a monolithic system means recompiling the whole kernel, whereas with microkernels you can add new features or patches without recompiling.
Monolithic kernels use signals and sockets to ensure IPC, microkernel approach uses message queues. 1st gen microkernels poorly implemented IPC so were slow on context switches.
Monolithic kernels use signals and sockets to ensure IPC, microkernel approach uses message queues. 1st gen microkernels poorly implemented IPC so were slow on context switches.
To write a microkernel, more code is required.To write a monolithic kernel, less code is required.
To write a microkernel, more code is required.To write a monolithic kernel, less code is required.
Parameters are temporary variable names within functions. The argument can be thought of as the value that is assigned to that temporary variable .
An argument in context with functions is the actual value that is passed to the function ( as input) ,when it is called. However parameter refers to the variables that are used in the function declaration/definition to represent those arguments that were send to the function during the function call .
The major difference between actual and formal arguments is that actual arguments are the source of information; calling programs pass actual arguments to called functions. The called functions access the information using corresponding formal arguments.
The arguments passed to the functions while the function is called is known as the actual arguments, whereas the arguments declared in the function header is called as formal arguments.
Cross-site Scripting (XSS) refers to client-side code injection attack wherein an attacker can execute malicious scripts (also commonly referred to as a malicious payload) into a legitimate website or web application .
Cross-site scripting carried out on websites accounted for roughly 84% of all security vulnerabilities documented by Symantec as of 2007.
Example :Let us imagine, a hacker has discovered XSS vulnerability in Gmail and inject malicious script. When a user visit the site, it will execute the malicious script. The malicious code can be used to redirect users to fake gmail page or capture cookies. Using this stolen cookies, he can login into your account and change password.
ageing is a scheduling technique used to avoid starvation. Fixed priority scheduling is a scheduling discipline, in which tasks queued for utilizing a system resource are assigned a priority each.
Basically Aging is a technique of gradually increasing the priority of processes that wait in the system for a long period of time.
Python is easy to learn for even a novice developer. Its code is easy to read and you can do a lot of things just by looking at it. Also, you can execute a lot of complex functionalities with ease, thanks to the standard library.
Python is easy to learn for even a novice developer. Its code is easy to read and you can do a lot of things just by looking at it. Also, you can execute a lot of complex functionalities with ease, thanks to the standard library.
Supports multiple systems and platforms.
Supports multiple systems and platforms.
python code is executed in n interpreter which makes slow execution of the code.
python code is executed in n interpreter which makes slow execution of the code.
Python allows for a more productive coding environment than massive languages like C# and Java. Experienced coders tend to stay more organized and productive when working with Python, as well .
Python allows for a more productive coding environment than massive languages like C# and Java. Experienced coders tend to stay more organized and productive when working with Python, as well .
"Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers,"
"Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers,"
Retail Industry : Data Mining has its great application in Retail Industry because it collects large amount of data from on sales, customer purchasing history, goods transportation, consumption and services.
Retail Industry : Data Mining has its great application in Retail Industry because it collects large amount of data from on sales, customer purchasing history, goods transportation, consumption and services.
Credit card spending by customer groups can be identified by using data mining.
The hidden correlation’s between different financial indicators can be discovered by using data mining.
Intrusion Detection : Any action that will compromise the integrity and confidentiality of a resource is an intrusion. The defensive measures to avoid an intrusion includes user authentication, avoid programming errors, and information protection.
Intrusion Detection : Any action that will compromise the integrity and confidentiality of a resource is an intrusion. The defensive measures to avoid an intrusion includes user authentication, avoid programming errors, and information protection.
Telecommunication Industry :Today the telecommunication industry is one of the most emerging industries providing various services such as fax, pager, cellular phone, internet messenger, images, e-mail, web data transmission, etc
Telecommunication Industry :Today the telecommunication industry is one of the most emerging industries providing various services such as fax, pager, cellular phone, internet messenger, images, e-mail, web data transmission, etc
Concurrent programming is a form of computing in which several computations are executed during overlapping time periods—concurrently—instead of sequentially (one completing before the next starts).
Concurrent programming is characterized by programming with more than one process.Concurrent programming involves the notations for expressing potential parallelism so that operations may be executed in parallel and the techniques for solving the resulting synchronization and communication problems.
Quality assurance (QA) is a way of preventing mistakes or defects in manufactured products and avoiding problems when delivering solutions or services to customers.The methods by which this is accomplished are many and varied, and may include ensuring conformance to one or more standards, such as ISO 9000 or a model such as CMMI.
Quality assurance includes two principles: "Fit for purpose" (the product should be suitable for the intended purpose); and "right first time" (mistakes should be eliminated).
Agile software development methodology is an process for developing software (like other software development methodologies –Waterfall model, V-Model, Iterative model etc.) however Agile development model is also a type of Incremental model. Software is developed in incremental, rapid cycles. This results in small incremental releases with each release building on previous functionality.
The addresses of an object's polymorphic methods is stored in a method table in the object. When invoking some polymorphic method at run time the method name is looked up in this table to get the address. A method table contains the names and addresses of the object's dynamically bound (polymorphic) methods. The method table is the same for all objects belonging to the same class, so is stored in the Class object (for the object's type, here Integer or Double). (In other languages method tables are called vtables.)
Example :
#include<iostream>
using namespace std;
class A
{
public:
int i;
A(){i=100;}
};
class B : public A
{
public:
int j;
B(){i = -1; j = 99;}
};
void func(A& myA)
{
cout<<myA.i << endl;
}
int main()
{
B b;
A* a = new B();
func(*a);
func(b);
delete a;
return 0;
}
Virtual Table is a lookup table of function pointers used to dynamically bind the virtual functions to objects at run time. It is not intended to be used directly by the program, and as such there is no standardized way to access it.
Virtual Table is created even for classes that have virtual base classes. In this case, the vtable has pointer to the shared instance of the base class along with the pointers to the classe's virtual functions if any.
_vptr :
This vtable pointer or _vptr, is a hidden pointer added by the Compiler to the base class. And this pointer is pointing to the virtual table of that particular class.
Expalnation :
Here in function main b pointer gets assigned to D1's _vptr and now starts pointing to D1's vtable. Then calling to a function1(), makes it's _vptr startightway calls D1's vtable function1() and so in turn calls D1's method i.e. function1() as D1 has it's own function1()defined it's class.
Where as pointer b calling to a function2(), makes it's _vptr points to D1's vatble which in-turn pointing to Base class's vtablefunction2 () as shown in the diagram (as D1 class does not have it's own definition or function2()).
Register are used to quickly accept, store, and transfer data and instructions that are being used immediately by the CPU, there are various types of Registers those are used for various purpose. Among of the some Mostly used Registers named as AC or Accumulator, Data Register or DR, the AR or Address Register, program counter(PC), Memory Data Register (MDR) ,Index register,Memory Buffer Register.
With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.
With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indexes, although each new index will increase the time it takes to write new records.
With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.
With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indexes, although each new index will increase the time it takes to write new records.
The real difference [between clustered and unclustered indexes] is that a clustered index will reorder the records on disk, whereas an unclustered index will not.
The real difference [between clustered and unclustered indexes] is that a clustered index will reorder the records on disk, whereas an unclustered index will not.
A clustered index alters the way that the rows are stored. When you create a clustered index on a column (or a number of columns), SQL server sorts the table’s rows by that column(s). It is like a dictionary, where all words are sorted in alphabetical order in the entire book.
A non-clustered index, on the other hand, does not alter the way the rows are stored in the table. It creates a completely different object within the table that contains the column(s) selected for indexing and a pointer back to the table’s rows containing the data. It is like an index in the last pages of a book, where keywords are sorted and contain the page number to the material of the book for faster reference.
A clustered index alters the way that the rows are stored. When you create a clustered index on a column (or a number of columns), SQL server sorts the table’s rows by that column(s). It is like a dictionary, where all words are sorted in alphabetical order in the entire book.
A non-clustered index, on the other hand, does not alter the way the rows are stored in the table. It creates a completely different object within the table that contains the column(s) selected for indexing and a pointer back to the table’s rows containing the data. It is like an index in the last pages of a book, where keywords are sorted and contain the page number to the material of the book for faster reference.
The inode is a data structure in a Unix-style file system that describes a file system object such as a file or a directory. Each inode stores the attributes and disk block location(s) of the object's data.
When a file is created inside a directory then the file-name and Inode number are assigned to file. These two entries are associated with every file in a directory. The user might think that the directory contains the complete file and all the extra information related to it but this might not be the case always.
File system object attributes may include metadata (times of last change,access, modification), as well as owner and permission data.
A red–black tree is a kind of self-balancing binary search tree. Each node of the binary tree has an extra bit, and that bit is often interpreted as the color (red or black) of the node. These color bits are used to ensure the tree remains approximately balanced during insertions and deletions .
1) Every node has a color either red or black.
2) Root of tree is always black.
3) There are no two adjacent red nodes (A red node cannot have a red parent or red child).
4) Every path from root to a NULL node has same number of black nodes.
struct t_red_black_node {
enum { red, black } colour;
void *item;
struct t_red_black_node *left,
*right,
*parent;
}
Example
Super Block: Each filesystem has one super block (+ duplicate super block) it contains info about
1. type of filesystem (ext2, ext3...)
2. the block size
3. pointers to a list of free blocks
4. the inode number of the root directory
a boot block located in the first few sectors of a file system. The boot block contains the initial bootstrap program used to load the operating system. Typically, the first sector contains a bootstrap program that reads in a larger bootstrap program from the next few sectors, and so forth.
The two phase commit protocol is a distributed algorithm which lets all sites in a distributed system agree to commit or rollback a transaction based upon consensus of all participating sites.If any database server is unable to commit its portion of the transaction, all database servers participating in the transaction must be prevented from committing their work.
Hadoop File System was developed using distributed file system design. It is run on commodity hardware. Unlike other distributed systems, HDFS is highly fault tolerant and designed using low-cost hardware.
According to The Apache Software Foundation, the primary objective of HDFS is to store data reliably even in the presence of failures including Name Node failures, Data Node failures and network partitions. The Name Node is a single point of failure for the HDFS cluster and a Data Node stores data in the Hadoop file management system.
HDFS uses a master/slave architecture in which one device (the master) controls one or more other devices (the slaves).
Features of HDFS
It is suitable for the distributed storage and processing.
Hadoop provides a command interface to interact with HDFS.
The built-in servers of namenode and datanode help users to easily check the status of cluster.
Streaming access to file system data.
Lex is a program designed to generate scanners, also known as tokenizers, which recognize lexical patterns in text. Lex is an acronym that stands for "lexical analyzer generator."
Lex is short for "lexical analysis". Lex takes an input file containing a set of lexical analysis rules or regular expressions. For output, Lex produces a C function which when invoked, finds the next match in the input stream.
Yacc (for "yet another compiler compiler." ) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc
The input subroutine produced by Yacc calls a user-supplied routine to return the next basic input item. Thus, the user can specify his input in terms of individual input characters, or in terms of higher level constructs such as names and numbers. The user-supplied routine may also handle idiomatic features such as comment and continuation conventions, which typically defy easy grammatical specification.
Yacc has also been used for less conventional languages, including a phototypesetter language, several desk calculator languages, a document retrieval system, and a Fortran debugging system.
Difference between LL parsing and LR parsing is that LL parser begin at the start symbol and try to apply productions to arrive at the target string, whereas LR parser begin at the target string and try to arrive back at the start symbol.
LL parsing, also known as top-down parsing and LR parsing, also known as bottom-up parsing .
LL starts with only the root non terminal on the stack, LR ends with only the root non terminal on the stack .
LL uses grammar rules in an order which corresponds to pre-order traversal of the parse tree, LR does a post-order traversal.
LL continuously pops a non terminal off the stack, and pushes a corresponding right hand side; LR tries to recognize a right hand side on the stack, pops it, and pushes the corresponding non terminal .
LL reads terminal when it pops one off the stack, LR reads terminals while it pushes them on the stack .
map uses a red-black tree as the data structure, so the elements you put in there are sorted, and insert/delete is O(log(n)). The elements need to implement at least operator<.
hash map uses a hash, so elements are unsorted, insert/delete is O(1). Elements need to implement at least operator== and you need a hash function.
The main difference otherwise is a difference in the speed at which you can access individual elements. Maps are usually stored as binary trees and hash maps are stored as hash tables. This means that if you have N elements in your container, then accessing an element in a map requires O(log(N)) time and the same operation in a hash map is O(1). So hash maps are faster, in general than maps.
use a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key.
map is implemented as a balanced binary search tree (usually a red/black tree).
use a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key.
map is implemented as a balanced binary search tree (usually a red/black tree).
A polyphase merge sort is an algorithm which decreases the number of runs at every iteration of the main loop by merging runs into larger runs. It is used for external sorting.
In this type of sort, the tapes being merged, and the tape to which the merged sub files are written, vary continuously throughout the sort. In this technique, the concept of a pass through records is not as clear-cut as in the straight or the natural merge.
Example :
Select Operation : This operation is used to select rows from a table (relation) that specifies a given logic, which is called as a predicate. The predicate is a user defined condition to select rows of user's choice.
Project Operation : If the user is interested in selecting the values of a few attributes, rather than selection all attributes of the Table (Relation), then one should go for PROJECT Operation.
Example : Selection
Notation uses lower case sigma:
σcondition(relation)
Example :Projection
A hub is the most basic networking device that connects multiple computers or other network devices together.In a hub, a frame is passed along or "broadcast" to every one of its ports. It doesn't matter that the frame is only destined for one port. they use protocols such as ICMP to communicate with each other and configure the best route between any two hosts.
Arcesium is a post-trade technology and professional services firm. We offer a new way for hedge fund managers to scale their business while maintaining control of critical non-investment activities. Arcesium in terms of software development would be either at par with Shaw or gonna be better since the higher management is from Shaw .
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types.
A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.
Templates are often used in larger code bbase for the purpose of code reusability and flexibility of the programs.
The concept of templates can be used in two different ways:
Templates are often used in larger code bbase for the purpose of code reusability and flexibility of the programs.
The concept of templates can be used in two different ways:
Function Templates
Class Templates
Function Template
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list) {
// body of function
}
Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.
for detail :http://www.geeksforgeeks.org/template-specialization-c/
A heap overflow is a type of buffer overflow that occurs in the heap data area. Heap overflows are exploitable in a different manner to that of stack-based overflows. Memory on the heap is dynamically allocated by the application at run-time and typically contains program data.
The heap overflow is very small, and hard to detect.
The canonical heap overflow technique overwrites dynamic memory allocation linkage (such as malloc meta data) and uses the resulting pointer exchange to overwrite a program function pointer.
Heap overflows actually include a class of exploits that are more complicated than those explained in this tutorial. Some of these exploits attack vulnerabilities in memory allocating functions such as malloc in lib-c.
A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).
Segmentation faults are a common class of error in programs written in languages like C that provide low-level memory access.
Segmentation fault is raised by hardware when any program attempts to access the memory location which is not allow to access, or attempts to access in wrong manner.
Newer programming languages may employ mechanisms designed to avoid segmentation faults and improve memory safety. For example, the Rust programming language employs an 'Ownership' based model to ensure memory safety.
Information about files(data) are sometimes called metadata. So you can even say it in another way, "An inode is metadata of the data."
Inode : Its a complex data-structure that contains all the necessary information to specify a file. It includes the memory layout of the file on disk, file permissions, access time, number of different links to the file etc.
Global File table : It contains information that is global to the kernel e.g. the byte offset in the file where the user's next read/write will start and the access rights allowed to the opening process.
Process file descriptor table : maintained by the kernel, that in turn indexes into a system-wide table of filesopened by all processes, called the file table .
stdio.h> searches in standard C library locations, whereas "stdio.h" searches in the current directory as well. ... You use #include "double quoted" when you want to say: "look for a file with this name in my own application's include directory; however, if it can't be found, look in the system's include directory".
Thrashing is a state in which our CPU perform 'productive' work less and 'swapping' more. CPU is busy in swapping pages, so much that it can not respond to user program as much as required. Thrashing can potentially result in total collapse of the hard drive of the computer.
When thrashing occurs you will notice the computer hard drive always working and a decrease in system performance. Thrashing is bad on the hard drive because of the amount of work the hard drive has to do and if left unfixed can cause an early hard drive failure.
A dangling pointer is one that has a value (not NULL) which refers to some memory which is not valid for the type of object you expect. For example if you set a pointer to an object then overwrote that memory with something else unrelated or freed the memory if it was dynamically allocated.
Dangling pointer
A TCP connection controls its transmission rate by limiting its number of transmitted-but-yet-to-be-acknowledged segments.
TCP’s congestion control scheme is based on a congestion window. The current value of the congestion window (cwnd) is stored in the TCB of each TCP connection and the window that can be used by the sender is constrained by min(cwnd,rwin,swin)min(cwnd,rwin,swin) where swinswin is the current sending window and rwinrwin the last received receive window. The Additive Increase part of the TCP congestion control increments the congestion window by MSS bytes every round-trip-time. In the TCP literature, this phase is often called the congestion avoidance phase. The Multiplicative Decrease part of the TCP congestion control divides the current value of the congestion window once congestion has been detected.
A socket consists of three things:
An IP address
A transport protocol
A port number
An IP address
A transport protocol
A port number
A port is a number between 1 and 65535 inclusive that signifies a logical gate in a device. Every connection between a client and server requires a unique socket.
For example:
1030 is a port.
(10.1.1.2 , TCP , port 1030) is a socket.
A port is one half of a protocol demuxing namespace. Typically we use TCP or UDP ports, where each port represents a single service. A server process listens on a port and accepts incoming connections (TCP) or incoming packets (UDP). The client allocates a local port number for initiating the connection.
For socket:
An ip address with port is know as socket.
Socket is the API's abstraction for a IP-port pair. It handles the network and transfer layer of communication. It can be thought of as a application's interface to the network.
A port on the other hand is the destination/origin of a packet. A IP address is further divided into ports so that applications can share the network without conflict.
Socket is the API's abstraction for a IP-port pair. It handles the network and transfer layer of communication. It can be thought of as a application's interface to the network.
A port on the other hand is the destination/origin of a packet. A IP address is further divided into ports so that applications can share the network without conflict.
The basic function that any switch is supposed to perform is to receive information from any source connected to it and dispatch that information to the appropriate destination only. This thing differentiates switches from hubs. Hub gets the information and forwards that to every other device in the network.
const int *p
1. => int const *
2. => pointer to a const int
so the pointer "points" to an int that can't be changed
int * const
2. => const pointer to int
so the pointer "points" to an int that can be changed,
but the pointer can't change
A cursor is the position indicator on a computer display screen where a user can enter text. In an operating system with a graphical user interface (GUI), the cursor is also a visible and moving pointer that the user controls with a mouse, touch pad, or similar input device. A cursor library is software, often implemented as a part of a database system or a data access API, that is used to manage attributes of data returned from a data source (a result set).
SQL is a Structured Query Language used to issue a single query or execute a single insert/update/delete.
PL-SQL is a programming language SQL, used to write full programs using variables, loops,operators etc. to carry out multiple selects/inserts/updates/deletes.
SQL is a Structured Query Language used to issue a single query or execute a single insert/update/delete.
PL-SQL is a programming language SQL, used to write full programs using variables, loops,operators etc. to carry out multiple selects/inserts/updates/deletes.
SQL is a data oriented language used to select and manipulate sets of data.
PL/SQL is a procedural language used to create applications.
SQL is a data oriented language used to select and manipulate sets of data.
PL/SQL is a procedural language used to create applications.
SQL you can execute only one query at a time, where in PL/SQL you can execute an number of queries in one block and get executed all there queues at one command .
SQL you can execute only one query at a time, where in PL/SQL you can execute an number of queries in one block and get executed all there queues at one command .
SQL is used to code queries, DML and DDL statements. PL/SQL is used to code program blocks, triggers, functions, procedures and packages.
SQL is used to code queries, DML and DDL statements. PL/SQL is used to code program blocks, triggers, functions, procedures and packages.
We can embed SQL in a PL/SQL program, but we cannot embed PL/SQL within a SQL statement .
We can embed SQL in a PL/SQL program, but we cannot embed PL/SQL within a SQL statement .
A trigger (from the Dutch trekken, meaning to pull) is a lever which, when pulled by the finger, releases the hammer on a firearm. In a database, a trigger is a set of Structured Query Language (SQL) statements that automatically "fires off" an action when a specific operation, such as changing data in a table, occurs.
For example, when a new record (representing a new worker) is added to the employees table, new records should also be created in the tables of the taxes, vacations and salaries.
Trigger is used :
Automatically generate derived column values .
Prevent invalid transactions .
Enforce complex security authorizations .
Enforce referential integrity across nodes in a distributed database .
Enforce complex business rules.
Linux is based upon the UNIX philosophy and supports the standard POSIX system call interface. Windows on the other hand only provides for POSIX using an emulation layer.
Windows requires it's users to purchase a license to use the software (often the license cost is included in the price of a new computer). Linux is licensed such that it's freely distributable at no cost.
Flexibility: It is used for high performance applications, desktop applications and embedded applications. You can save disk space by installing components required for a particular use. You can restrict specific computers instead of all computers.
Windows exposes partitions and devices at drive letters. Whether you have multiple hard drives, multiple partitions on the same hard drive, or removable devices connected, each file system is available under its own drive letter.
Linux doesn’t have drive letters. Instead, it makes other file systems accessible at arbitrary directories. (Windows can do this too, but this isn’t how it works out of the box.)
Linux doesn’t have drive letters. Instead, it makes other file systems accessible at arbitrary directories. (Windows can do this too, but this isn’t how it works out of the box.)
The proc file-system (proc fs) is a special filesystem in Unix-like operating systems that presents information about processes and other system information in a hierarchical file-like structure, providing a more convenient and standardized method for dynamically accessing process data held in the kernel than traditional tracing methods or direct access to kernel memory.
Within the /proc/ directory, one can find a wealth of information detailing the system hardware and any processes currently running. In addition, some of the files within the /proc/ directory tree can be manipulated by users and applications to communicate configuration changes to the kernel.
The /proc file system is nicely documented in the proc man page. You can access this document by running the below command on a linux system.
The proc filesystem provides a method of communication between kernel space and user space. For example, the GNU version of the process reporting utility ps uses the proc file system to obtain its data, without using any specialized system calls.
A scripting language is a programming language that employs a high-level construct to interpret and execute one command at a time. In general, scripting languages are easier to learn and faster to code in than more structured and compiled languages such as C and C++ .
A scripting language can be viewed as a domain-specific language for a particular environment; in the case of scripting an application, this is also known as an extension language.
Scripting languages came about largely because of the development of the Internet as a communications tool.JavaScript, ASP, JSP, PHP, Perl, Tcl and Python are examples of scripting languages.
Scripting languages like JavaScript are often used to facilitate enhanced features of websites.
OS makes a DNS lookup and replies the IP address to the browser. browser opens a TCP connection to server (this step is much more complex with HTTPS) browser sends the HTTP request through TCP connection. ... browser renders response, or offers a download dialog for unrecognized types.
When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.
for detail :http://www.geeksforgeeks.org/references-in-c/
Generics are a facility of generic programming that were added to the Java programming language in 2004 within the official version J2SE 5.0. They were designed to extend Java's type system to allow “a type or method to operate on objects of various types while providing compile-time type safety.”
CMOS (complementary metal-oxide-semiconductor) is the term usually used to describe the small amount of memory on a computer motherboard that stores the BIOS settings. Some of these BIOS settings include the system time and date as well as hardware settings .
CMOS is also sometimes referred to as complementary-symmetry metal–oxide–semiconductor (or COS-MOS) .
Like most RAM chips, the chip that stores your BIOS settings is manufactured using the CMOS process. It holds a small amount of data, usually 256 bytes. The information on the CMOS chip includes what types of disk drives are installed on your computer, the current date and time of your system clock, and your computer's boot sequence.
CMOS is used in static RAM, digital logic circuits, microprocessors, micro controllers, image sensors, and the conversion of computer data from one file format to another.
The Basic Input Output System, usually referred to as BIOS, is software stored on a small memory chip on the motherboard.
It also manages data flow between the computer's operating system and attached devices such as the hard disk,video adapter, keyboard, mouse and printer.
The BIOS includes instructions on how to load basic computer hardware and includes a test referred to as a POST (Power On Self Test) that helps verify the computer meets requirements to boot up properly. If the computer does not pass the POST, you will receive a combination of beeps indicating what is malfunctioning within the computer.
The BIOS additionally provides an abstraction layer for the hardware, i.e., a consistent way for application programs and operating systems to interact with the keyboard, display, and other input/output (I/O) devices.
There are possibly of many IP connection between two system (identified by their IP address) for different application on each end . UDP "Source Port" field identified the associated application in the source system and "Destination Port" the associated application in the destination system .
The key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it.
So if you're going to need to change the values use a List.
The key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it.
So if you're going to need to change the values use a List.
Tuples can be used as keys for dicts and properly implement __hash__(), lists do not, and are not hashable.
Tuples have structure, lists have order.
The literal syntax of tuples is shown by parentheses whereas the literal syntax of lists is shown by square brackets .
Tuples are heterogeneous while lists are homogeneous. One has to deal individually with the items.
Dynamic (run time) polymorphism is the polymorphism existed at run-time. Here, Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at run-time. Method overloading and method overriding using instance methods are the examples for dynamic polymorphism.
Dynamic (run time) polymorphism is the polymorphism existed at run-time. Here, Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at run-time. Method overloading and method overriding using instance methods are the examples for dynamic polymorphism.
Whenever we call the method on to the object based on the object corresponding class method will be executed dynamically.
Example :
public class DynamicTest {
public static void main(String args[]) {
Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
vehicle.start(); //Car's start called because start() is overridden method
}
}
class Vehicle {
public void start() {
System.out.println("Inside start method of Vehicle");
}
}
class Car extends Vehicle {
@Override
public void start() {
System.out.println("Inside start method of Car");
}
}
A UNIX shell script is a human-readable text file containing a group of commands that could also be manually executed one-by-one at the UNIX operating system command prompt and these command sequences in order to make ones life at the shell easier and more productive.
The following is an example of a basic shell script:
echo "Text Line 1"
print "Text Line 2"
exit 0
AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related technologies like JavaScript, DOM, XML, HTML, CSS etc.
the Ajax model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions.
Although X in Ajax stands for XML, JSON is used more than XML nowadays because of its many advantages such as being lighter and a part of JavaScript. Both JSON and XML are used for packaging information in Ajax model.
MongoDB is an open-source document database and leading NoSQL database. MongoDB is written in C++. This tutorial will give you great understanding on MongoDB concepts needed to create and deploy a highly scalable and performance-oriented database.
MongoDB supports field, range queries, regular expression searches. Queries can return specific fields of documents and also include user-defined JavaScript functions. Queries can also be configured to return a random sample of results of a given size.
MongoDB scales horizontally using sharding The user chooses a shard key, which determines how the data in a collection will be distributed .
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. Squarespace uses JSON to store and organize site content created with the CMS.
Example
var myJSON = '{ "name":"John", "age":31, "city":"New York" }';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
The primary difference between a div and a span is their default behavior. By default, a <div> is a block level element and a <span> is an inline element.
While a span allows you to separate things from the other elements around them on a page or within a document, it does not cause a line break. This is why it is perfect for in-line styling, like coloring a single word in a sentence to draw more attention to it.
But a div, by default, creates a line break because it is used to make separate containers or boxes within a page or document, hence the name division. So the proper way to use a div is as a containing element, rather than an inline styling element.
While a span allows you to separate things from the other elements around them on a page or within a document, it does not cause a line break. This is why it is perfect for in-line styling, like coloring a single word in a sentence to draw more attention to it.
But a div, by default, creates a line break because it is used to make separate containers or boxes within a page or document, hence the name division. So the proper way to use a div is as a containing element, rather than an inline styling element.
Example of a HTML <span> tag
Example text that is red text and an example of a span tag.
HTML code:
<p>Example text that is <span style="color:red;">red text</span> and an example of a span tag.</p>
Example of a HTML <div> tag
An example of a div tag that has a maximum width of 200 pixels and a silver background.
HTML code:
<div style="width: 200px; background-color:#E5E4E2;padding:10px;margin-bottom:2em;">
<p>An example of a div tag that has a maximum width of 200 pixels and a silver background.</p>
</div>
Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies.
The goal of android project is to create a successful real-world product that improves the mobile experience for end users.
Android Inc was founded in Palo Alto of California, U.S. by Andy Rubin, Rich miner, Nick sears and Chris White in 2003. Later Android Inc. was acquired by Google in 2005. After original release there have been number of updates in the original version of Android.
Versions usually come with a numerical code and a name that’s so far been themed after sweets and desserts, running in alphabetical order.
Android 1.5 Cupcake
Android 1.6 Donut
Android 2.1 Eclair
Android 2.2 Froyo
Android 2.3 Gingerbread
Android 3.2 Honeycomb - The first OS design specifically for tablets, launching on the Motorola Xoom
Android 4.0 Ice Cream Sandwich: The first OS to run on smartphones and tablets, ending the 2.X naming convention.
Android 4.1 Jelly Bean: Launched on the Google Nexus 7 tablet by Asus
Android 4.2 Jelly Bean: Arrived on the LG Nexus 4
Android 4.3 Jelly Bean
Android 4.4 KitKat: Launched on the LG Nexus 5
Android 5.0 Lollipop: Launched on the Motorola Nexus 6 and HTC Nexus 9
Android 6.0 Marshmallow: Launched on the LG Nexus 5X and Huawei Nexus 6P
Android 7.0 Nougat
Android 7.1 Nougat: Launched on the HTC-made Google Pixel and Pixel XL
Android 8.0 O: Currently in beta form, only available for developers (and the curious)
Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites.XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user.
A cross-site scripting vulnerability may be used by attackers to bypass access control such as the same origin policy.
A successful cross site scripting attack can have devastating consequences for an online business's reputation and its relationship with its clients.
In order for an XSS attack to take place the vulnerable website needs to directly include user input in its pages. An attacker can then insert a string that will be used within the web page and treated as code by the victim’s browser.
The following server-side pseudo-code is used to display the most recent comment on a web page.
print "<html>"
print "<h1>Most recent comment</h1>"
print database.latestComment
print "</html>"
In order for an XSS attack to take place the vulnerable website needs to directly include user input in its pages. An attacker can then insert a string that will be used within the web page and treated as code by the victim’s browser.
The following server-side pseudo-code is used to display the most recent comment on a web page.
print "<html>"
print "<h1>Most recent comment</h1>"
print database.latestComment
print "</html>"
The transient keyword may be used as a property modifier in Java and is directly related with serialization. In short the properties declared as transient are not serialized by the default serialization mechanism.
transient keyword is used along with instance variable to exclude them from serialization process.
The transient access modifier is used at the time of object serialization in order not to serialize the instance variable value.
In the following code snippet, the content of the variable “nopersist” would not be saved. The content of the variable “number” would be saved.
class SampleSerialize
{
transient int nopersist; // will not persist
int number; // will persist
......
......
}
class SampleSerialize
{
transient int nopersist; // will not persist
int number; // will persist
......
......
}
Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
A class must implement Serializable interface present in java.io package in order to serialize its object successfully.
Example :
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
As per the Second Normal Form there must not be any partial dependency of any column on primary key. It means that for a table that has concatenated primary key, each column in the table that is not part of the primary key must depend upon the entire concatenated key for its existence.
A database is in second normal form if it satisfies the following conditions:
It is in first normal form
All non-key attributes are fully functional dependent on the primary key
A hypervisor is one of the most important components of comprehensive, server-based, distributed manufacturing automation systems. This abstraction allows the underlying host machine hardware to independently operate one or more virtual machine as guests, allowing multiple guest VMs to effectively share the system's physical compute resources, such as procesor cycles, memory space, network bandwidth and so on.
Secure Socket Shell, is a network protocol that provides administrators with a secure way to access a remote computer.
SSH provides a secure channel over an unsecured network in a client-server architecture, connecting an SSH client application with an SSH sever.
The SSH client drives the connection setup process and uses public key cryptography to verify the identity of the SSH server.
SSH is widely used by network administrators for managing systems and applications remotely, allowing them to log in to another computer over a network, execute commands and move files from one computer to another.
Telnet is a protocol that allows you to connect to remote computers (called hosts) over a TCP/IP network (such as the Internet). For example, typing telnet hostname would connect a user to a host named hostname.
The term telnet is also used to refer to the software that implements the client part of the protocol. Telnet client applications are available for virtually all computer platform.
Telnet is used most often for remote management but also sometimes for the initial setup for some devices .
The tlntadmn commands allow you to remotely manage a computer running Telnet Server. These commands are run from the command prompt. Used without parameters, tlntadmn displays local server settings.
volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time-without any action being taken by the code the compiler finds nearby.
This keyword prevents an optimizing compiler from optimizing away subsequent reads or writes and thus incorrectly reusing a stale value or omitting writes.
Syntax
volatile int foo;
int volatile foo;
This automatically precludes it being a member function! An object has to EXISTbefore it has a "this" pointer and thus a Vitale. ... Constructor can not be virtual, because when constructor of a class is executed there is no Vitale in the memory, means no virtual pointer defined yet.
TcpEndpoint objects allow you to easily establish and communicate over TCP/IP network connections between client and server processes, possibly residing on different hosts .
The TcpEndpoint class follows a telephone-like model of networking: clients "call" servers and servers "answer" clients. Once a network connection is established between a client and a server, the two can "talk" to each other by reading from and writing to the connection:
Client <----------------------> Server
The TcpEndpoint class follows a telephone-like model of networking: clients "call" servers and servers "answer" clients. Once a network connection is established between a client and a server, the two can "talk" to each other by reading from and writing to the connection:
Client <----------------------> Server
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r = 3, c = 4;
int *arr = (int *)malloc(r * c * sizeof(int));
int i, j, count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
*(arr + i*c + j) = ++count;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf("%d ", *(arr + i*c + j));
/* Code for further processing and free the
dynamically allocated memory */
return 0;
}
output :
1 2 3 4
5 6 7 8
9 10 11 12
ARP (Address Resolution Protocol) converts an Internet protocol(IP) address to its corresponding physical network address.
The protocol operates below the network layer as a part of the interface between the OSI network and OSI link layer.
ARP provides the protocol rules for making this correlation and providing address conversion in both directions.
The purpose of Address Resolution Protocol (ARP) is to find out the MAC address of a device in your Local Area Network, for the corresponding IPv4 address, which network application is trying to communicate.
It is used by network devices, including routers, to send error messages and operational information indicating, for example, that a requested service is not available or that a host or router could not be reached.
ICMP helps you gather information about a network. ICMP is an IP packet with an added header to define the ICMP protocol .
When two or more objects are derived from a common base class, we can prevent multiple copies of the base class being present in an object derived from those objects by declaring the base class as virtual when it is being inherited. Such a base class is known as virtual base class.
Virtual base classes, used in virtual inheritance, is a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritance.
Node.js is a very powerful JavaScript-based framework/platform built on Google Chrome's JavaScript V8 Engine.
Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36.
Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications.
Node.js enables JavaScript to be used for sever side scripting, and runs scripts server-side to produce dynamic web page content before the page is sent to the user's web browser.
Node.js connects the ease of a scripting language (JavaScript) with the power of Unix network programming .
Like linear search and binary search, ternary search is a searching technique that is used to determine the position of a specific value in an array.
A ternary search determines either that the minimum or maximum cannot be in the first third of the domain or that it cannot be in the last third of the domain, then repeats on the remaining two-thirds.
A ternary search is an example of a divide and conquer algorithm .
Stock market prediction is the act of trying to determine the future value of a company stock or other financial instrument traded on an exchange. The successful prediction of a stock's future price could yield significant profit.
The efficient market hypothesis suggests that stock prices reflect all currently available information and any price changes that are not based on newly revealed information thus are inherently unpredictable.
Primary Key is used to identify a row (record) in a table, whereas Unique-key is to prevent duplicate values in a column (with the exception of a null entry).
PRIMARY KEY is always not null but columns with unique constraint can hold NULL values .
When you create a UNIQUE constraint, the database automatically creates a UNIQUE index. For MS SQL Server databases, a PRIMARY KEY will generate a unique CLUSTERED INDEX. A UNIQUE constraint will generate a unique NON-CLUSTERED INDEX.
There will be only one primary key in a table whereas More than one unique key will be there in a table.
Every primary is a unique but every unique is not primary .
Pseudocode:
curNodePtr := FirstNode
if curNodePtr == NULL
return 'Less Nodes in the List'
forever:
tmpPtr := curNodePtr
count := 0
forever:
if tmpPtr == NULL || count == N
break
tmpPtr := tmpPtr.NEXT
count++
if tmpPtr == NULL
if count == n
return curNodePtr
else
return 'Less Nodes in the List'
curNodePtr := curNodePtr.NEXT
Complexity:
Time Complexity: O(n^2) - For traversing each node after curNode.
Space Complexity: O(1)
In graph theory and computer science, the lowest common ancestor (LCA) of two nodes v and w in a tree or directed acyclic graph (DAG) T is the lowest (i.e. deepest) node that has both v and w as descendants, where we define each node to be a descendant of itself (so if v has a direct connection from w, w is the lowest common ancestor).
Example :
In this tree, the lowest common ancestor of the nodes x and y is marked in dark green. Other common ancestors are shown in light green.
Message passing is a type of communication between process or objects in computer science.
Message passing is used ubiquitously in modern computer software. It is used as a way for the objects that make up a program to work with each other and as a means for objects and systems running on different computers (e.g., the Internet) to interact.
An Interface is basically a kind of class like class Interface contain method and variable but with a measure difference in it contain a abstract method and final fields.
This means that Interface do not specify or to Implement for these method and data field contain only constant.
Syntax for declaring the Interface :
[access specifier] interface <interface name>
{
return type method name1(Parameter list);
return type method name2(Parameter list);
------------------------------------------------------
return type method nameN(Parameter list);
Final constant value 1;
Final constant value 2;
-----------------
--------------
Final constant value N;
}
Example :
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
output :
Hello
An Abstract class is a class just opposite to final modifier .An abstract class is a class that does not have body of the method that means we declare the method only not implemented .
Syntax For Abstract Class :
We used Abstract Keyword for declare the class and declaration of the method .
abstract class <class name>
{
abstract method Name1(Parameter list);
abstract method Name2(Parameter list);
-----------------
return type method name3(Parameter list)
{
body of the method
}
}
An abstract class cannot be instanced.
An abstract method of an abstract class must be define in is sub class .It can be used to create object reference because java approach to run time polymorphism is implemented to super .class references .
Example :
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Most differences between the features of the two languages arise due to the use of different programming paradigm. C breaks down to functions while JAVA breaks down to Objects. C is more procedure-oriented while JAVA is data-oriented.
Java uses a “Garbage Collector” which manages memory automatically so the programmer doesn’t have to handle that.
Java doesn't support the enum keyword used in C to define types that consist of fixed sets of named values. This is surprising for a strongly typed language like Java, but there are ways to simulate this feature with object constants.
Java doesn't support C struct and union types. A Java class can be thought of as an enhanced struct, however.
Operator overloading in C is an important feature which is not supported in Java language.
In computer science, a self-balancing (or height-balanced) binary search tree is any node-based binary search tree that automatically keeps its height (maximal number of levels below the root) small in the face of arbitrary item insertions and deletions .
AVL trees are used for performing search operations on high dimension external data storage. For example, a phone call list may generate a huge database which may be recorded only on external hard drives, hard-disks or other storage devices .
The structure of the nodes of a balanced tree can be represented like:
struct NodeAVL{
int key;
int ech;
node *left, *right;
};
Where:
- key represents the tag of the node(integer number),
- ech represents the balancing factor
- left and right represent pointers to the left and right children.
Example :
AVL tree with balance factors
Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor.
for detail review :http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors
Windows Azure, which was later renamed as Microsoft Azure in 2014, is a cloud computing platform, designed by Microsoft to successfully build, deploy, and manage applications and services through a global network of data centers.
Microsoft Azure is widely considered both a Platform as Service (PaaS) and Infrastructure as a Service (IaaS) offering.
C++ supports both procedural and object oriented programming paradigms; therefore C++ is also called a hybrid language.
C++ allows the declaration of variable anywhere in the scope i.e at time of its First use.
C++ supports Exception Handling while C does not.
C++ provides Boolean or String data types. It supports both user-defined and built-in data types.
Data is hidden in C++ and is not accessible to external functions. Hence, is more secure .
C++ program file is saved with .CPP extension.
C++ does provide references too. It considers them as aliases to another variable or object. They are safer than pointers where they can be used.
Bing is a web search engine owned and operated by Microsoft. The service has its origins in Microsoft's previous search engines: MSN Search, Windows Live Search and later Live Search. Bing provides a variety of search services, including web, video, image and map search products.
Benefits of Bing :
Search for cash with Bing Rewards .
Search quality: as good or better than Google's .
Search quality: as good or better than Google's .
Bing gets the picture .
Bing gets the picture .
Bing gives more auto complete suggestions than Google does in most cases.
Bing gives more auto complete suggestions than Google does in most cases.
Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
Example :
Public class EncapsulationDemo{
private int ssn;
private String empName;
private int empAge;
//Getter and Setter methods
public int getEmpSSN(){
return ssn;
}
public String getEmpName(){
return empName;
}
public int getEmpAge(){
return empAge;
}
public void setEmpAge(int newValue){
empAge = newValue;
}
public void setEmpName(String newValue){
empName = newValue;
}
public void setEmpSSN(int newValue){
ssn = newValue;
}
}
public class EncapsTest{
public static void main(String args[]){
EncapsulationDemo obj = new EncapsulationDemo();
obj.setEmpName("Mario");
obj.setEmpAge(32);
obj.setEmpSSN(112233);
System.out.println("Employee Name: " + obj.getEmpName());
System.out.println("Employee SSN: " + obj.getEmpSSN());
System.out.println("Employee Age: " + obj.getEmpAge());
}
}
Output:
Employee Name: Mario
Employee SSN: 112233
Employee Age: 32
Cloud computing is a general term for the delivery of hosted services over the internet.
Simply put, cloud computing is the delivery of computing services—servers, storage, databases, networking, software, analytics and more—over the Internet (“the cloud”) .
Examples of cloud services include online data storage and backup solutions, Web-based e-mail services, hosted office suites and document collaboration services, database processing, managed technical support services and more.
Pseudo Code :
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
A load balancer is a device that acts as a reverse proxy and distributes network or application traffic across a number of servers.
Load Balancers that optimize the performance of servers delivering important content to in house users as well as co-workers form other companies or the general public.
Load balancing usually involves dedicated software or hardware, such as a multilayer Switch or a Domain Name Service server process .
Software as a service (or SaaS) is a way of delivering applications over the Internet—as a service. Instead of installing and maintaining software, you simply access it via the Internet, freeing yourself from complex software and hardware management.
SaaS is typically accessed by users using a thin client via a web browser.
Examples of where SaaS can be used by enterprises:
Accounting and invoicing
Tracking sales
Planning
Performance monitoring
Communications (including web mail and messaging)
The registry is a single place for keeping such information as what hardware is attached, what system options have been selected, how computer memory is set up, and what application programs are to be present when the operating system is started.
The Windows Registry is meant to solve that problem by providing a single place for all settings across all applications.
Java is platform independent because of the machine independent code also called "Byte Code". Which make java a purely platform independent.
Which can be once complied, can be run anywhere on any platform. Only necessity is the availability of Java Run-time Environment (JVM) .
A memory leak is the gradual loss of available computer memory when a program (an application or part of the operating system) repeatedly fails to return memory that it has obtained for temporary use.
Memory leak occurs when programmers create a memory in heap and forget to delete it.
A memory leak is also known as a space leak.
A transient event is a short-lived burst of energy in a system caused by a sudden change of state.
The transient is the behavior of the circuit (for example) after a certain action, and this behavior didn't last for a long time. After this transient period the steady state behavior dominate, i.e. the steady state solution is at t tends to infinity.
An example of transient oscillation can be found in digital (pulse) signals in computer networks .
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement .
Synchronized methods :
Example:
Public synchronized void increment()
{
X++;
}
Synchronize statement :
Example:
public void run()
{
synchronized(p1)
{ //synchronize statement. P1 here is an object of some class P
p1.display(s1);
}
}
Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
class HelloTest extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
HelloTest t1=new HelloTest();
t1.run();//fine, but does not start a separate call stack
}
}
Output :
class HelloTest extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
HelloTest t1=new HelloTest();
t1.run();//fine, but does not start a separate call stack
}
}
Output :
running...
A package is a name space that organizes a set of related classes and interfaces.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and namespace management.
Using package it becomes easier to locate the related classes.
In java there are already many predefined packages that we use while programming.
For example: java.lang, java.io, java.util etc.
Defining a Package:
This statement should be used in the beginning of the program to include that program in that particular package.
package <package name> .
Example:
package hello;
public class Trap {
public void id ()
{
System.out.println ("Trap");
}
}
The C library function void *realloc(void *ptr, size_t size)attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.
Declaration
Following is the declaration for realloc() function.
void *realloc(void *ptr, size_t size)
for detail review : http://www.geeksforgeeks.org/g-fact-66/
Pseudo Code :
Important Fact :
S1: Stack 1
S2: Stack 2
x: Data (A,B,etc)
Enqueue(S1,x){
push(S1,x);
}
Dequeue(S1,S2)
{
if(S2 is not empty)
return(pop(s2));
}
else {
while(S1 is not empty)
{
x=pop(S1);
push(S2,x);
}
return(pop(s2))
}
Time Complexity :
Best case: O(1)
Average case: O(1)
Worst case: O(n)
Windows 8 doesn’t have a Start Menu. Instead, it has a ‘Charms Bar’ (see right) which is where you go to shut down and use other tools such as ‘Search’.
Traditionally, users type in passwords in order to gain access to their locked computers. Windows 8 adds the picture password. When logging in, users are presented with a picture and by touching features in the photo in the right order they can unlock the device.
Windows 8 includes hundreds of small features. For instance, faster boot times, Airplane mode, enhanced copy/move/paste operations, native antivirus program (Windows Defender now includes all features of Microsoft Security Essential), fully customizable lock screen, custom refresh image and better multi-monitor support.
Windows 8 includes hundreds of small features. For instance, faster boot times, Airplane mode, enhanced copy/move/paste operations, native antivirus program (Windows Defender now includes all features of Microsoft Security Essential), fully customizable lock screen, custom refresh image and better multi-monitor support.
Compatibility is always an issue when talking about operating systems. Luckily, they are both compatible with almost all applications and programs. The only key difference is that Windows 8 was developed at a later time, giving it an edge for troubleshooting current compatibility issues .
For Windows 8, a clean install also contains the extended Windows Defender technology, which, for the first time incorporates complete anti malware functionality – also optimized for memory and resource use. (This functionality does not exist on a clean install of Windows 7 where we would recommend that you add security software) .
Addition/Deletion of an element from the list at any index which is an O(1) operation in Lists as compared to Arrays.
Arrays are good for random access and good for sequential access (both are in constant time). Linked lists on the other hand are constant for sequential, but linear for random access.
As the linked list doesn't have a size limit, we can go on adding new nodes (elements) and increasing the size of the list to any extent.
Data structures such as stack and queues can be easily implemented using linked list.
An important advantage of linked lists over arrays is that the linked list uses exactly as much memory as it needs, and can be made to expand to fill all available memory locations if needed.
It is not necessary to know in advance the number of elements to be stored in the list and therefore, need not allocate. d as and when necessary.
A makefile is used with the Unix make utility to determine which portions of a program to compile.
Make provides most help when the program consists of many component files.
Makefiles are special format files that together with the make utility will help you to automagically build and manage your projects .
The make utility
make
this program will look for a file named makefile in your directory, and then execute it.
If you have several makefiles, then you can execute them with the command:
make -f MyMakefile
Extern :
The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere else.
An external variable may also be declared inside a function. In this case the extern keyword must be used, otherwise the compiler will consider it a definition of a local .
A variable that is explicitly declared to be external cannot be redefined since it is declared in another source file nor any additional storage tp be allocated to it.An external declaration merely serves to declare for the remainder of that source such that a variable exists and has been created earlier.
Example :
int num = 75 ;
void display();
void main()
{
extern int num ;
printf("nNum : %d",num);
display();
}
void display()
{
extern int num ;
printf("nNum : %d",num);
}
Output :
Num : 75
Num : 75
Static Variable :
int num = 75 ;
void display();
void main()
{
extern int num ;
printf("nNum : %d",num);
display();
}
void display()
{
extern int num ;
printf("nNum : %d",num);
}
Output :
Num : 75
Num : 75
Static Variable :
Static variables have a property of preserving their value even after they are out of their scope . Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.
Static variables have a property of preserving their value even after they are out of their scope . Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.
Default initial value of static integral type variables are zero otherwise null.
Default initial value of static integral type variables are zero otherwise null.
Static variables may be initialized in their declarations; however, the initializes must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable.
Static variables may be initialized in their declarations; however, the initializes must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable.
Example :
#include <stdio.h>
static int i=10;
int main(){
i=5;
for(i=0;i<5;i++){
static int a=10; //This statement will execute
//only time.
printf("%d",a++);//This statement will execute
//five times.
}
return 0;
}
Output: 10 11 12 13 14
Virtual Memory is a space where large programs can store themselves in form of pages while their execution and only the required pages or portions of processes are loaded into the main memory .
The operating system manages virtual address spaces and the assignment of real memory to virtual memory.
The purpose of virtual memory is to enlarge the address space, the set of addresses a program can utilize. For example, virtual memory might contain twice as many addresses as main memory.
Hashing is one simple option for this. We can put all words in a hash table .But
the worst case running time would be O(n) where n would be the total number of elements in dictionary .
so we have used Trie which have
Worst case time taken in case of Trie is O(m) where m is the length of string .
for detail review :http://www.geeksforgeeks.org/data-structure-dictionary-spell-checker/
A stack frame is a memory management strategy used to create and destroy temporary (automatic) variables in some programming languages .
The stack frame is a procedure contains all necessary information to save and restore the state of a procedure.
Each stack frame contains space for actual parameter, local variables, temporary locations etc .
The stack frames are allocated in a region of memory called the call stack .
Threads can directly communicate with other threads of its process; processes must use inter process communication to communicate with sibling processes.
Both process and threads are independent path of execution but one process can have multiple Threads.
Each process has its own code, data and kernel context (VM structures, descriptor table, etc). While the threads of a process, they share the same code, data and kernel context.
New threads are easily created. However the creation of new processes require duplication of the parent process.
Processes are heavily dependent on system resources available while threads require minimal amounts of resource, so a process is considered as heavyweight while a thread is termed as a lightweight process.
Defragmentation is the process of locating the non contiguous fragments of data into which a computer file may be divided as it is stored on a hard disk, and rearranging the fragments and restoring them into fewer fragments or into the whole file.
It also attempts to create larger regions of free space using compaction to impede the return of fragmentation .
Defragmentation works by locating file fragments that are scattered and putting them back together. The purpose is to decrease file access times and increase space on the hard-drive.
An access code is a password you use to access course content online. The content you access depends on the course, but can include things such as practice exam questions, interactive videos to help you understand course concepts, and course assignments.
Access code may refer to:
In authentication:
Password, a secret word
Personal Identification Number (PIN), a secret numeric code .
Cookie is a piece of code that are transmitted by a server to the client browser .
Cookies were designed to be a reliable mechanism for websites to remember stateful information .
Cookies may also be called a web cookie, Internet cookie,browser cookie or HTTP cookie.
Advantage :
Authorization .
Faster response .
Pseudo code :
c=0 s1=Head;
while(Head!=0)
{
c=c+1;
s1=s1->next;
}
c=ceil(c/2);
while(c!=1){
c=c-1;
Head=Head->next;
}
return(Head);
In level order traversal, we visit the nodes level by level from left to right.
AVL tree is a self-balancing Binary Search Tree (BST) where the height of the two child sub trees of any node differ by at most one .
If at any time they differ by more than one, rebalancing is done to restore this property. Lookup, insertion, and deletion .
Example :
The above tree is AVL because differences between heights of left and right subtrees for every node is less than or equal to 1.
for detail refer : http://www.geeksforgeeks.org/avl-tree-set-1-insertion/
XML file validated by compile the XML file with a XML compiler (DTD or XML schema) .
DTD contain he pre-defined XML structure to cover the possible errors in the developed XML file .
XML file is valid if and only if its satisfy the following constraints .
Every opening tag must contain the corresponding closing tag .
No-overlapping tag in a XML file .
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators .
Syntax :
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
HashMap is similar to Hash table with two exceptions .Basically HashMap methods are unsynchronized and it can allow null key and also null value which cannot allow in Hash table .HashMap maintain the key and value pairs <Key,Value> .
It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. It neither does any kind of sorting to the stored keys and Values.
Create and add objects in Hash-map in Java
HashMap<String, Integer> cache = new HashMap<String, Integer>();
Trie is an ordered tree data structure that uses strings as keys. Unlike Binary Trees, Tries store keys associated with the node. The key is actually determined based on the position of the node on the tree.All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string .
Since this data structure is a prefix tree, trie is commonly used in Dictionaries, Phone Directories and matching algorithms.
A trie for keys "A","to", "tea", "ted", "ten", "i", "in", and "inn".
Optimization using dynamic programming :
#include<iostream>
using namespace std;
#define tiff(i,n) for(int i=0;i<n;i++)
struct ds{
int zero;
int ones;
};
typedef struct ds solution;
solution arr[10000];
solution easyopti(int n){
if(n<0)
{
solution tmp ;
tmp.zero =0;
tmp.ones =0;
return tmp;
}
arr[0].zero=1;
arr[0].ones=0;
arr[1].zero=1;
arr[1].ones=1;
arr[2].zero=2;
arr[2].ones=1;
arr[3].zero=4;
arr[3].ones=2;
if(n==0)return arr[0];
else if(n==1)return arr[1];
else if(n==2)return arr[2];
else if(n==3)return arr[3];
else{
for(int i = 4;i<=n;i++){
arr[i].zero = arr[i-1].zero+arr[i-2].zero+arr[i-3].zero;
arr[i].ones = arr[i-1].ones+arr[i-2].ones+arr[i-3].ones;
}
}
return arr[n];
}
int main(){
solution a= easyopti(10);
cout<<a.zero<<" "<<a.ones<<endl;
}
Post order are tree traversal are given below .
Traverse the left sub tree of R in post order.
Traverse the right sub tree of R in post order.
Process the root R.
Traverse the left sub tree of R in post order.
Traverse the right sub tree of R in post order.
Process the root R.
/* Recursive function to print the elements of a binary tree
with postorder traversal*/
void postorder(struct btreenode *node)
{
if (node != NULL)
{
postorder(node->left);
postorder(node->right);
printf("%d", node->data);
}
}
Example :
Post-order: A, C, E, D, B, H, I, G, F.
Inorder are tree traversal are given below
Traverse the left subtree of R in inorder.
Process the root R.
Traverse the right subtree of R in inorder.
Traverse the left subtree of R in inorder.
Process the root R.
Traverse the right subtree of R in inorder.
/* Recursive function to print the elements of a binary tree with
inorder traversal*/
void inorder(struct btreenode *node)
{
if (node != NULL)
{
inorder(node->left);
printf("%d", node->data);
inorder(node->right);
}
}
Example :
In-order: A, B, C, D, E, F, G, H, I.
Preorder are tree traversal are given below
Process the root R.
Traverse the left subtree of R in preorder.
Traverse the right subtree of R in preorder.
Process the root R.
Traverse the left subtree of R in preorder.
Traverse the right subtree of R in preorder.
/* Recursive function to print the elements
of a binary tree with preorder traversal*/
void preorder(struct btreenode *node)
{
if (node != NULL)
{
printf("%d", node->data);
preorder(node->left);
preorder(node->right);
}
}
Example :
Pre-order: F, B, A, D, C, E, G, I, H.
Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j .
Example:
The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).
code :
for(i=0 to n-2 )
{
for(j=i+1 to n-1)
if(a[i] > a[j])
count++;
}
Time-complexity = O(n^2)
By merge-sort- it is O(n logn)
for detail review refer: http://www.geeksforgeeks.org/counting-inversions/
A stack is an abstract data type which operate basically two fundamental principals
push() − Pushing (storing) an element on the stack.
push() − Pushing (storing) an element on the stack.
pop() − Removing (accessing) an element from the stack.
pop() − Removing (accessing) an element from the stack.
The order in which elements come off a stack gives rise to its alternative name, LIFO (for last in, first out).
Implementation of stack :Using Array
Pseudo Code :
Push(S,N,x,top)
{
if(top+1==N)
{
print("Stack is overflow");
}
else
{
top++;
S[top]=x;
}
}
POP(S,N,top)
{
if(top==-1)
{
print("Stack is underflow");
exit(1);
}
else
{
y=S[top];
top--;
return(y);
}
}
Uses of Stack :
Expression evaluation and syntax parsing .
Backtracking .
Backtracking .
Parsing .
Parsing .
Recursive Function .
New state : Initially process will be in New state . It means process is under creation or process is being created .
Ready state : Once the process is created it will be moved on to ready state . In the ready state there will be multiple number of process .
Running state : One of the process will be selected from the ready state and dispatched on to the running state .When the process in the running state it occupied the CPU and executing the instruction of the process and performing CPU time .In the running state one process at any point of the time .
Wait or Block state : If the running process required any input output then it will come to wait state .In the wait state there will be multiple number of process .It means multiple process will perform input output operation simultaneously .
Suspended Ready : If the resources are not sufficient to maintain the process in the ready state the some of the process will suspended and they will be moved on to suspended ready state . If the process in the suspended ready state it is reside in the backing store (Secondary memory) .
Suspend wait or Block state : If the resources are not sufficient to maintain the process in the wait or block state then some of the process (Low priority) will be suspended and they will be moved to the suspended waiting or block state. In this process is reside in the backing store .
Cycle Detection (Single Instance)
If all the resources are of Single Instance Type then the Cycle in the Resource Allocation Graph is necessary and sufficient condition for occurring of deadlock .
If all the resources of a not single instance type then cycle in the resource allocation graph is just a necessary condition but not sufficient condition for occurring of deadlock ..
Monitors is a programming language compiler support type of solution achieved synchronization .
The Monitors is collection of variables , conditional variable and procedure combine together in a special kind of module and package .
The processes running outside the monitor cannot directly access the internal variables of the monitor but how ever they can call procedure of the Monitor .
Monitor has important property that only one process can be active inside the monitor at any point of time .
Monitors is a programming language compiler support type of solution achieved synchronization .
The Monitors is collection of variables , conditional variable and procedure combine together in a special kind of module and package .
The processes running outside the monitor cannot directly access the internal variables of the monitor but how ever they can call procedure of the Monitor .
Monitor has important property that only one process can be active inside the monitor at any point of time .
Syntax of Monitor :
Pseudo code
Fibo(n)
{
if(n==0)
return(0) ;
if(n==1)
return(1);
else
return(fibo(n-1)+fibo(n-2));
}
Recurrence relation
Example :
Time Complexity :
fibo(n)
||
n-level-Complete Binary tree [upper bound]
||
2^n -1 nodes
||
2^n function calls
||
O(2^n)
Pseudo code
Reverse(head)
{
r=head,p=q=null ;
while(r)
{
p=q;
q=r;
r=r->next;
q->next=p;
}
head=q;
return(head);
}
Image Acquisition : This is the first step or process of the fundamental steps of digital image processing. Image acquisition could be as simple as being given an image that is already in digital form. Generally, the image acquisition stage involves pre processing, such as scaling etc.
Image Enhancement : Image enhancement is among the simplest and most appealing areas of digital image processing. Basically, the idea behind enhancement techniques is to bring out detail that is obscured, or simply to highlight certain features of interest in an image. Such as, changing brightness & contrast etc.
Image Restoration : Image restoration is an area that also deals with improving the appearance of an image. However, unlike enhancement, which is subjective, image restoration is objective, in the sense that restoration techniques tend to be based on mathematical or probabilistic models of image degradation.
Color Image Processing : Color image processing is an area that has been gaining its importance because of the significant increase in the use of digital images over the Internet. This may include color modeling and processing in a digital domain etc.
Wavelets and Multiresolution Processing : Wavelets are the foundation for representing images in various degrees of resolution. Images subdivision successively into smaller regions for data compression and for pyramidal representation.
Compression : Compression deals with techniques for reducing the storage required to save an image or the bandwidth to transmit it. Particularly in the uses of internet it is very much necessary to compress data.
Image Acquisition : This is the first step or process of the fundamental steps of digital image processing. Image acquisition could be as simple as being given an image that is already in digital form. Generally, the image acquisition stage involves pre processing, such as scaling etc.
Image Enhancement : Image enhancement is among the simplest and most appealing areas of digital image processing. Basically, the idea behind enhancement techniques is to bring out detail that is obscured, or simply to highlight certain features of interest in an image. Such as, changing brightness & contrast etc.
Image Restoration : Image restoration is an area that also deals with improving the appearance of an image. However, unlike enhancement, which is subjective, image restoration is objective, in the sense that restoration techniques tend to be based on mathematical or probabilistic models of image degradation.
Color Image Processing : Color image processing is an area that has been gaining its importance because of the significant increase in the use of digital images over the Internet. This may include color modeling and processing in a digital domain etc.
Wavelets and Multiresolution Processing : Wavelets are the foundation for representing images in various degrees of resolution. Images subdivision successively into smaller regions for data compression and for pyramidal representation.
Compression : Compression deals with techniques for reducing the storage required to save an image or the bandwidth to transmit it. Particularly in the uses of internet it is very much necessary to compress data.
Face detection can be regarded as a specific case of object-class detection. In object-class detection, the task is to find the locations and sizes of all objects in an image that belong to a given class. Examples include upper torsos, pedestrians, and cars.
Face-detection algorithms focus on the detection of frontal human faces. It is analogous to image detection in which the image of a person is matched bit by bit. Image matches with the image stores in database. Any facial feature changes in the database will invalidate the matching process.
refers :https://en.wikipedia.org/wiki/Face_detection
Edge detection includes a variety of mathematical methods that aim at identifying points in a digital image at which the image brightness changes sharply or, more formally, has discontinuities. The points at which image brightness changes sharply are typically organized into a set of curved line segments termed edges. The same problem of finding discontinuities in one-dimensional signals is known as step detection and the problem of finding signal discontinuities over time is known as change detection. Edge detection is a fundamental tool in image processing, machine vision and computer vision, particularly in the areas of feature detection and feature extraction .
refers : https://en.wikipedia.org/wiki/Edge_detection
Searching a key :
To search a given key in Binary Search Tree, we first compare it with root, if the key is present at root, we return root. If key is greater than root’s key, we recur for right sub tree of root node. Otherwise we recur for left sub tree.
// C function to search a given key in a given BST
struct node* search(struct node* root, int key)
{
// Base Cases: root is null or key is present at root
if (root == NULL || root->key == key)
return root;
// Key is greater than root's key
if (root->key < key)
return search(root->right, key);
// Key is smaller than root's key
return search(root->left, key);
}
Insertion of a key :
A new key is always inserted at leaf. We start searching a key from root till we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf node.
100 100
/ \ Insert 40 / \
20 500 ---------> 20 500
/ \ / \
10 30 10 30
\
40
// C program to demonstrate insert operation in binary search tree
#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left, *right;
};
// A utility function to create a new BST node
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d \n", root->key);
inorder(root->right);
}
}
/* A utility function to insert a new node with given key in BST */
struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
/* return the (unchanged) node pointer */
return node;
}
// Driver Program to test above functions
int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
struct node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
// print inoder traversal of the BST
inorder(root);
return 0;
}
Time Complexity: The worst case time complexity of search and insert operations is O(h) where h is height of Binary Search Tree. In worst case, we may have to travel from root to the deepest leaf node. The height of a skewed tree may become n and the time complexity of search and insert operation may become O(n).
for detail refer as :http://quiz.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/
In order to find common node of two linked lists we need to consider one of the important factor - length of linked list. If length of both linked list is same then it is just a cake walk, iterate both linked list with same frequency(one node at a time) and check whether both linked list reference same node at any point, if intersection node exist we will find it, else reaches at end of list. However, problem is all about two linked list of different length.Refer following diagram, length of first linked list is 4 and 3 for second one. We will start with brute force approach followed by some time efficient ways.
Brute force approach- Iterate any given linked list for every node of another linked list and compare if both nodes are equals or not, if at any moment nodes passes equals() test that nodde is common node, otherwise no common node exist. Time and space complexity :- Suppose length of linked lists are p and q respectively then, time complexity is O(pq) and space complexity is O(1).
/* Find common node, intersection of two Linked list- brute force approach */
private static Node getCommonNodeBruteForce(Node head1, Node head2) {
Node commonNode = null;
Node current = head2;
if (head1 != null && head2 != null)
/*For each node of linked list 1, traverse linked list 2*/
while (head1 != null) {
while (current != null) {
if (current.equals(head1)) {
commonNode = current;
break;
}
current = current.next;
}
/*If commonNode is not null, it means we have found common node*/
if (commonNode != null) {
break;
}
/* Move linked list 1 head and reset current
* to head2 (for each node of linked list 1, traverse linked list 2)
* */
head1 = head1.next;
current = head2;
}
return commonNode;
}
Method 2(Using difference of node counts)
1) Get count of the nodes in first list, let count be c1.
2) Get count of the nodes in second list, let count be c2.
3) Get the difference of counts d = abs(c1 – c2)
4) Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes.
5) Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes)
for Detail refer this link :http://www.geeksforgeeks.org/write-a-function-to-get-the-intersection-point-of-two-linked-lists/
Virtual Function is a function in base class, which is override in the derived class, and which tells the compiler to perform Late Binding on this function.Virtual Keyword is used to make a member function of the base class Virtual.
Example :
Definitions :
Overloading occurs when two or more methods in one class have the same method name but different parameters.
Overloading occurs when two or more methods in one class have the same method name but different parameters.
Overriding means having two methods with the same method name and parameters (i.e., method signature). One of the methods is in the parent class and the other is in the child class. Overriding allows a child class to provide a specific implementation of a method that is already provided its parent class .
Overriding means having two methods with the same method name and parameters (i.e., method signature). One of the methods is in the parent class and the other is in the child class. Overriding allows a child class to provide a specific implementation of a method that is already provided its parent class .
Overriding vs. Overloading
Here are some important facts about Overriding and Overloading:
When a method by an object is called, Java matches up the method name first and then the number and data type of parameters to decide which one of the overloaded methods to execute. i.e., compiler decides which method is to be called depending upon the number of parameters .
A subclass will override the method by facilitating its own functionality to it ( by using @override) .
Access modifier & Non access modifier can also be changed in overloading .
but in overriding Non access modifier – final :if a method can contain final keyword in a parent class we cannot override. static:if a method can contain static keyword child cannot override parent class methods but hide (child).
Polymorphism applies to overriding, not to overloading.
Overriding is a run-time concept while overloading is a compile-time concept .
An Example of Overriding
class Cat{
public void hello(){
System.out.println("woof ");
}
}
class Help extends Cat{
public void sniff(){
System.out.println("sniff ");
}
public void hello(){
System.out.println("bowl");
}
}
public class OverridingTen{
public static void main(String [] args){
Cat cat = new Help();
Cat.hello();
}
}
In the example above, the cat variable is declared to be a Cat. During compile time, the compiler checks if the Cat class has the bark() method. As long as the Cat class has the bark() method, the code compilers. At run-time, a Help is created and assigned to cat. The JVM knows that cat is referring to the object of Help, so it calls the bark() method of Help. This is called Dynamic Polymorphism .
Output :
bowl
An Example of Overloading :
class Cat{
public void Test(){
System.out.println("woofing ");
}
//overloading method
public void Test(int num){
for(int i=0; i<num; i++)
System.out.println("woofing ");
}
}
In this overloading example, the two Test method can be invoked by using different parameters. Compiler know they are different because they have different method signature (method name and method parameter list).
output :
woofing
If the pivot divides the array into two pieces of roughly the same size each time, then Quicksort behaves like Mergesort with log n splits of the array. More precisely,
T(n) = f(n) + T(n/2) + T(n/2)
where f(n) is the time taken by Partition. Since Partition compares every key in
A[0 .. (n - 1)]
to the pivot x, the running time for partition is linear, with time complexity f(n) = n. So Quicksort has a time complexity function T given by
T(1) = 1 T(n) = 2T(n/2) + n
which, like mergesort, has the solution
T(n) = n log n + n and so is Θ(n log n).
But this is if the pivot divides the array in a balanced way.
Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.
Example:
The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Logn).
source :http://quiz.geeksforgeeks.org/binary-search/
The solution uses a two pointers (traversing the list two items at a time) If there is a loop, then the one pointer will go around the loop twice as fast as the another pointer. At one point, these two pointers will point to the same item. Here’s some code to make this clearer.
bool hasLoop( Node *p )
{
Node *p, *q;
p = q = headNode;
while( p && q && q->next )
{
if( p == q->next || p== q->next->next )
{
return true;
}
p = p->next;
q = q->next->next;
}
return false;
}
To implement DFS we are using Stack data structure .
Time Complexity : O(V+E) .
Space Complexity : O(V+E) .
In DFT (Depth first traversal ) is printed and if adjacent is not present then using backtracking we print adjacent .
To implement DFS we are using Stack data structure .
Time Complexity : O(V+E) .
Space Complexity : O(V+E) .
In DFT (Depth first traversal ) is printed and if adjacent is not present then using backtracking we print adjacent .
Application of DFS :
Using DFT we can check given graph is connected or not .
Using DFT we can find out number of connected component in a given graph .
Using DFT we can check given graph contain cycle or not .
Using DFT we can check given directed graph is strongly connected or not.
Find out Biconnected Component and Euler path .
Compute number of path between two vertex .
Using DFT we can check a vertex in Articulation point or not .
Using DFT we can check given graph is connected or not .
Using DFT we can find out number of connected component in a given graph .
Using DFT we can check given graph contain cycle or not .
Using DFT we can check given directed graph is strongly connected or not.
Find out Biconnected Component and Euler path .
Compute number of path between two vertex .
Using DFT we can check a vertex in Articulation point or not .
A vertex in a given graph is said to be articulation point iff by deleting that vertex together its edges then resulting graph is disconnected .
DFS Pseudo code :
To implement BFT (Breadth first traversal) we are using Queue data structure .
BFT is also known as level order traversal .
In BFT all adjacent are printed .
Time Complexity : O(V+E) .
Space Complexity : O(V+E) .
To implement BFT (Breadth first traversal) we are using Queue data structure .
BFT is also known as level order traversal .
In BFT all adjacent are printed .
Time Complexity : O(V+E) .
Space Complexity : O(V+E) .
Application :
Using BFT we can check given graph is connected or not.
Using BFT we can find out connected component in given graph .
Using BFT we can check given graph contain cycle or not .
Using BFT we can find out shortest path from given source to every vertex in a given unweighted graph (Dijkstra Algorithm) .
Using BFT we can check given graph is bipartite graph or not .
Queue and Greedy Technique .
Using for Topology sort and Dijkstra algorithm .
Find Transitive closure of a graph .
Using BFT we can check given graph is connected or not.
Using BFT we can find out connected component in given graph .
Using BFT we can check given graph contain cycle or not .
Using BFT we can find out shortest path from given source to every vertex in a given unweighted graph (Dijkstra Algorithm) .
Using BFT we can check given graph is bipartite graph or not .
Queue and Greedy Technique .
Using for Topology sort and Dijkstra algorithm .
Find Transitive closure of a graph .
Bridge is LAN device and its operation is based on MAC protocol .
Bridge is used to connecting similar LAN.
Initially the Bridge table of the Bridge will be empty .
Bridge is LAN device and its operation is based on MAC protocol .
Bridge is used to connecting similar LAN.
Initially the Bridge table of the Bridge will be empty .
Whenever frame reaches to the Bridge it will store in a buffer and a Dummy frame is created with destination address of the frame and is broadcast on the other LAN .
If their is reply then Bridge will update the table with destination address this is known as Learning .
Now the data that is stored in a buffer of the Bridge is transmitted to the other side of the LAN this is known as Forwarding.
When the data is transmitted to the same side of the LAN it is known as Blocking .
When Bridge known the complete information of the network its is Stable and Converse .
Router is WAN device an its operation is based on IP address .
Router is used for connecting different classes of networks .
By default Router is Broadcast Domain Separator .
Router is used for connecting different networks (Bus topology , Ring topology) .
Router is not a multi-protocol convertor because it cannot convert one model of the packet to another .
By default Router is a Collision Domain Separator .
Router is WAN device an its operation is based on IP address .
Router is used for connecting different classes of networks .
By default Router is Broadcast Domain Separator .
Router is used for connecting different networks (Bus topology , Ring topology) .
Router is not a multi-protocol convertor because it cannot convert one model of the packet to another .
By default Router is a Collision Domain Separator .
Text Based Protocol
By default SMTP is text based protocol but we can send Graphical data with the help of MIME (Multi-media Internet Mail Extension)
SMTP uses port 25.
SMTP is a Post protocol it is used for sending the mail into mail server.
POP3 or (IMAP4) are known for the Pull protocol because they are used for retrieving the mail from mail server .
SMTP combine with POP3 or IMAP4 is client to client protocol with mediation done by mail server .
SMTP used TCP as a transport layer protocol.
SMTP is an asynchronies because the clocks of both clients need not synchronize.
SMTP follows store and forward technique with the respect of server .
Priority to the mail is provided by IMAP4 where as POP3 is considered all mail are equal.
IMAP4 providing security for the file mare are attached but this facility not available on POP3.
Text Based Protocol
By default SMTP is text based protocol but we can send Graphical data with the help of MIME (Multi-media Internet Mail Extension)
By default SMTP is text based protocol but we can send Graphical data with the help of MIME (Multi-media Internet Mail Extension)
SMTP uses port 25.
SMTP uses port 25.
SMTP is a Post protocol it is used for sending the mail into mail server.
SMTP is a Post protocol it is used for sending the mail into mail server.
POP3 or (IMAP4) are known for the Pull protocol because they are used for retrieving the mail from mail server .
POP3 or (IMAP4) are known for the Pull protocol because they are used for retrieving the mail from mail server .
SMTP combine with POP3 or IMAP4 is client to client protocol with mediation done by mail server .
SMTP combine with POP3 or IMAP4 is client to client protocol with mediation done by mail server .
SMTP used TCP as a transport layer protocol.
SMTP used TCP as a transport layer protocol.
SMTP is an asynchronies because the clocks of both clients need not synchronize.
SMTP is an asynchronies because the clocks of both clients need not synchronize.
SMTP follows store and forward technique with the respect of server .
SMTP follows store and forward technique with the respect of server .
Priority to the mail is provided by IMAP4 where as POP3 is considered all mail are equal.
Priority to the mail is provided by IMAP4 where as POP3 is considered all mail are equal.
IMAP4 providing security for the file mare are attached but this facility not available on POP3.
IMAP4 providing security for the file mare are attached but this facility not available on POP3.
Weekly
Monthly
Overall
Error
Content Related Issue
Software Related Issue
|
[
{
"code": null,
"e": 310,
"s": 169,
"text": "\nPopular Company Tags\n\nAmazon\nMicrosoft\nOracle\nSamsung\nAdobe\nSynopsys\nInfosys\nCisco\nWipro\nOla-Cabs\nMorgan-Stanley\nGoldman-Sachs\nshow more\n\n"
},
{
"code": null,
"e": 317,
"s": 310,
"text": "Amazon"
},
{
"code": null,
"e": 327,
"s": 317,
"text": "Microsoft"
},
{
"code": null,
"e": 334,
"s": 327,
"text": "Oracle"
},
{
"code": null,
"e": 342,
"s": 334,
"text": "Samsung"
},
{
"code": null,
"e": 348,
"s": 342,
"text": "Adobe"
},
{
"code": null,
"e": 357,
"s": 348,
"text": "Synopsys"
},
{
"code": null,
"e": 365,
"s": 357,
"text": "Infosys"
},
{
"code": null,
"e": 371,
"s": 365,
"text": "Cisco"
},
{
"code": null,
"e": 377,
"s": 371,
"text": "Wipro"
},
{
"code": null,
"e": 386,
"s": 377,
"text": "Ola-Cabs"
},
{
"code": null,
"e": 401,
"s": 386,
"text": "Morgan-Stanley"
},
{
"code": null,
"e": 415,
"s": 401,
"text": "Goldman-Sachs"
},
{
"code": null,
"e": 580,
"s": 415,
"text": "\n\nPopular Topic Tags\n\nMaths\nArray\nDynamic-Programming\nGreedy-Algorithm\nHashing\nTree\nBit-Algorithm\nMatrix\nBacktracking\nOperating System\nLinked-List\nGraph\nshow more\n\n"
},
{
"code": null,
"e": 586,
"s": 580,
"text": "Maths"
},
{
"code": null,
"e": 592,
"s": 586,
"text": "Array"
},
{
"code": null,
"e": 612,
"s": 592,
"text": "Dynamic-Programming"
},
{
"code": null,
"e": 629,
"s": 612,
"text": "Greedy-Algorithm"
},
{
"code": null,
"e": 637,
"s": 629,
"text": "Hashing"
},
{
"code": null,
"e": 642,
"s": 637,
"text": "Tree"
},
{
"code": null,
"e": 656,
"s": 642,
"text": "Bit-Algorithm"
},
{
"code": null,
"e": 663,
"s": 656,
"text": "Matrix"
},
{
"code": null,
"e": 676,
"s": 663,
"text": "Backtracking"
},
{
"code": null,
"e": 693,
"s": 676,
"text": "Operating System"
},
{
"code": null,
"e": 705,
"s": 693,
"text": "Linked-List"
},
{
"code": null,
"e": 711,
"s": 705,
"text": "Graph"
},
{
"code": null,
"e": 752,
"s": 711,
"text": "\nHome\nAman Chauhan 1\nSubjective Answers\n"
},
{
"code": null,
"e": 757,
"s": 752,
"text": "Home"
},
{
"code": null,
"e": 772,
"s": 757,
"text": "Aman Chauhan 1"
},
{
"code": null,
"e": 791,
"s": 772,
"text": "Subjective Answers"
},
{
"code": null,
"e": 946,
"s": 791,
"text": "A formalized set of software calls and routines that can be referenced by an application program in order to access supporting system or network services."
},
{
"code": null,
"e": 1055,
"s": 948,
"text": "Verifying a product is accessible to the people having disabilities (deaf, blind, mentally disabled etc.)."
},
{
"code": null,
"e": 1132,
"s": 1055,
"text": "A set of activities conducted with the intent of finding errors in software."
},
{
"code": null,
"e": 1440,
"s": 1132,
"text": "There are two tasks with specially distinguished process IDs: swapper or sched has process ID 0 and is responsible for paging, and is actually part of the kernel rather than a normal user-mode process. Process ID 1 is usually the init process primarily responsible for starting and shutting down the system."
},
{
"code": null,
"e": 1738,
"s": 1440,
"text": "Job scheduling is the process of allocating system resources to many different tasks by an operating system (OS). The system handles prioritized job queues that are awaiting CPU time and it should determine which job to be taken from which queue and the amount of time to be allocated for the job."
},
{
"code": null,
"e": 2261,
"s": 1738,
"text": "A scheduler may aim at one of many goals, for example, maximizing throughput (the total amount of work completed per time unit), minimizing response time (time from work becoming enabled until the first point it begins execution on resources), or minimizing latency (the time between work becoming enabled and its subsequent completion),maximizing fairness (equal CPU time to each process, or more generally appropriate times according to the priority and workload of each process). In practice, these goals often conflict"
},
{
"code": null,
"e": 2546,
"s": 2261,
"text": "In computing, a web application or web app is a client–server software application in which the client (or user interface) runs in a web browser. Common web applications include webmail, online retail sales, online auctions, wikis, instant messaging services and many other functions."
},
{
"code": null,
"e": 2711,
"s": 2546,
"text": "Security testing is a process intended to reveal flaws in the security mechanisms of an information system that protect data and maintain functionality as intended."
},
{
"code": null,
"e": 3126,
"s": 2711,
"text": "Creating a REST API sesssion is similar to logging in to using a web browser. The only difference is that a web browser (in the typical sense) is never used. Instead, you need an application capable of sending and receiving HTTP requests—a REST client. REST clients are different than web browsers, although some REST clients are built on-top of web browsers like Chromium because they share interchangeable parts."
},
{
"code": null,
"e": 3348,
"s": 3126,
"text": "Event Viewer is a component of Microsoft's Windows NT line of operating systems that lets administrators and users view the event logs on a local or remote machine. In Windows Vista, Microsoft overhauled the event system."
},
{
"code": null,
"e": 3399,
"s": 3348,
"text": "Database tests are typically a three-step process:"
},
{
"code": null,
"e": 3650,
"s": 3399,
"text": "\nSetup the test. You need to put your database into a known state before running tests against it. ...\nRun the test. Using a database regression testing tool, run your database tests just like you would run your application tests.\nCheck the results.\n"
},
{
"code": null,
"e": 3752,
"s": 3650,
"text": "Setup the test. You need to put your database into a known state before running tests against it. ..."
},
{
"code": null,
"e": 3880,
"s": 3752,
"text": "Run the test. Using a database regression testing tool, run your database tests just like you would run your application tests."
},
{
"code": null,
"e": 3899,
"s": 3880,
"text": "Check the results."
},
{
"code": null,
"e": 4126,
"s": 3899,
"text": "Each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client."
},
{
"code": null,
"e": 4408,
"s": 4126,
"text": "The prefixes of right sentential forms that can appear on the stack of a shift-reduce parser are called viable prefixes. By definition, a viable prefix is a prefix of a right sentential form that does not continue past the right end of the rightmost handle of that sentential form."
},
{
"code": null,
"e": 4633,
"s": 4408,
"text": "In computer science, an operator precedence parser is a bottom-up parser that interprets an operator-precedence grammar. ... Edger Dijkstra's shunting yard algorithm is commonly used to implement operator precedence parsers."
},
{
"code": null,
"e": 4880,
"s": 4633,
"text": "A “handle” of a string is a substring that matches the RHS of a production and whose reduction to the non-terminal (on the LHS of the production) represents one step along the reverse of a rightmost derivation toward reducing to the start symbol."
},
{
"code": null,
"e": 5137,
"s": 4880,
"text": "Early Binding and Late binding. The compiler performs a process called binding when an object is assigned to an object variable. The early binding (static binding) refers to compile time binding and late binding (dynamic binding) refers to runtime binding."
},
{
"code": null,
"e": 5292,
"s": 5137,
"text": "RecyclerView was created as a ListView improvement, so yes, you can create an attached list with ListView control, but using RecyclerView is easier as it:"
},
{
"code": null,
"e": 5669,
"s": 5292,
"text": "\n\nReuses cells while scrolling up/down - this is possible with implementing View Holder in the listView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.\n\n\nDecouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.\n\n"
},
{
"code": null,
"e": 5878,
"s": 5669,
"text": "\nReuses cells while scrolling up/down - this is possible with implementing View Holder in the listView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.\n"
},
{
"code": null,
"e": 6085,
"s": 5878,
"text": "Reuses cells while scrolling up/down - this is possible with implementing View Holder in the listView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter."
},
{
"code": null,
"e": 6251,
"s": 6085,
"text": "\nDecouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.\n"
},
{
"code": null,
"e": 6415,
"s": 6251,
"text": "Decouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager."
},
{
"code": null,
"e": 6801,
"s": 6415,
"text": "singleTask :- A new task will always be created and a new instance will be pushed to the task as the root. However, if any activity instance exists in any tasks, the system routes the intent to that activity instance through the onNewIntent() method call. In this mode, activity instances can be pushed to the same task. This mode is useful for activities that act as the entry points."
},
{
"code": null,
"e": 7133,
"s": 6801,
"text": "single Top:- Same as singleTask, except that the no activities instance can be pushed into the same task of the single Top. Accordingly, the activity with launch mode is always in a single activity instance task. This is a very specialized mode and should only be used in applications that are implemented entirely as one activity."
},
{
"code": null,
"e": 7244,
"s": 7133,
"text": "Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages."
},
{
"code": null,
"e": 7361,
"s": 7246,
"text": "Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other."
},
{
"code": null,
"e": 7727,
"s": 7361,
"text": "Pragma is used inside the servlets in the header with a certain value. The value is of no-cache that tells that a servlets is acting as a proxy and it has to forward request. Pragma directives allow the compiler to use machine and operating system features while keeping the overall functionality with the Java language. These are different for different compilers."
},
{
"code": null,
"e": 7952,
"s": 7727,
"text": "The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. For example, closing a opened file, closing a opened database Connection."
},
{
"code": null,
"e": 8066,
"s": 7952,
"text": "Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions."
},
{
"code": null,
"e": 8485,
"s": 8068,
"text": "It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server."
},
{
"code": null,
"e": 8793,
"s": 8485,
"text": "A Translation lookaside buffer (TLB) is a memory cache that is used to reduce the time taken to access a user memory location. It is a part of the chip's memory-management unit (MMU). The TLB stores the recent translations of virtual memory to physical memory and can be called an address-translation cache."
},
{
"code": null,
"e": 9039,
"s": 8793,
"text": "NSLOOKUP is a program to query Internet domain name servers (DNS). NSLOOKUP or Reverse DNS (rDNS) is a method of resolving an IP address into a domain name, just as the domain name system (DNS) resolves domain names into associated IP addresses."
},
{
"code": null,
"e": 9268,
"s": 9039,
"text": "The Domain Name System (aka DNS) is used to resolve human-readable hostnames like www.Dyn.com into machine-readable IP addresses like 204.13.248.115. DNS also provides other information about domain names, such as mail services."
},
{
"code": null,
"e": 9554,
"s": 9268,
"text": "The hash function is used to index the original value or key and then used later each time the data associated with the value or key is to be retrieved. Thus, hashing is always a one-way operation. There's no need to \"reverse engineer\" the hash function by analyzing the hashed values."
},
{
"code": null,
"e": 9756,
"s": 9554,
"text": "Text files contain data that can easily be understood by humans. It includes letters, numbers and other characters. On the other hand, binary files contain 1s and 0s that only computers can interpret. "
},
{
"code": null,
"e": 10069,
"s": 9758,
"text": "Dynamic data structure provides a means for storing data more efficiently into memory. Using dynamic memory allocation, your program will access memory spaces as needed. This is in contrast to static data structure, wherein the programmer has to indicate a fix number of memory space to be used in the program."
},
{
"code": null,
"e": 10260,
"s": 10069,
"text": "It is used to convert any letter to its upper case mode. Toupper() function prototype is declared in . Note that this function will only convert a single character, and not an entire string."
},
{
"code": null,
"e": 10686,
"s": 10260,
"text": "It is the process of transferring data to an alternative output source other than the display screen. Output redirection allows a program to have its output saved to a file. For example, if you have a program named COMPUTE, typing this on the command line as COMPUTE >DATA can accept input from the user, perform certain computations, then have the output redirected to a file named DATA, instead of showing it on the screen."
},
{
"code": null,
"e": 10956,
"s": 10686,
"text": "Reserved words are words that are part of the standard C language library. This means that reserved words have special meaning and therefore cannot be used for purposes other than what it is originally intended for. Examples of reserved words are int, void, and return."
},
{
"code": null,
"e": 11066,
"s": 10958,
"text": "It is referred to as a terminating null character, and is used primarily to show the end of a string value."
},
{
"code": null,
"e": 11405,
"s": 11066,
"text": "Spaghetti programming refers to codes that tend to get tangled and overlapped throughout the program. This unstructured approach to coding is usually attributed to lack of experience on the part of the programmer. Spaghetti programming makes a program complex and analyzing the codes difficult, and so must be avoided as much as possible."
},
{
"code": null,
"e": 11743,
"s": 11405,
"text": "Merging is the sorting algorithm which combines two or more sorted sequences into a single sorted sequence. It is a divide and conquer algorithm, an O(n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, meaning that the implementation preserves the input order of equal elements in the sorted output."
},
{
"code": null,
"e": 11946,
"s": 11743,
"text": "It is an algorithm that considers systematically all possible outcomes for each decision. Examples of backtracking algorithms are the eight queens problem or generating permutations of a given sequence."
},
{
"code": null,
"e": 12048,
"s": 11946,
"text": "If software misses some feature or function from what is there in requirement it is called as defect."
},
{
"code": null,
"e": 12188,
"s": 12048,
"text": "The Socket is a Combination of Ip address and Port Number (in pairs)\nSession is a Logical Connectivity between the source and destination ."
},
{
"code": null,
"e": 12453,
"s": 12188,
"text": "The inverted page table scheme uses a page table that contains an entry for each physical frame, not for each logical page. This ensures that the table occupies a fixed fraction of memory. The size is proportional to physical memory, not the virtual address space."
},
{
"code": null,
"e": 12592,
"s": 12453,
"text": "The Heterogeneous Services data dictionary views, whose names all begin with the HS_ prefix, can be divided into the following categories:"
},
{
"code": null,
"e": 12608,
"s": 12592,
"text": "\nGeneral views\n"
},
{
"code": null,
"e": 12622,
"s": 12608,
"text": "General views"
},
{
"code": null,
"e": 12663,
"s": 12622,
"text": "\nViews used for the transaction service\n"
},
{
"code": null,
"e": 12702,
"s": 12663,
"text": "Views used for the transaction service"
},
{
"code": null,
"e": 12737,
"s": 12702,
"text": "\nViews used for the SQL service .\n"
},
{
"code": null,
"e": 12770,
"s": 12737,
"text": "Views used for the SQL service ."
},
{
"code": null,
"e": 13019,
"s": 12770,
"text": "A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved."
},
{
"code": null,
"e": 13298,
"s": 13019,
"text": "exec is a functionality of an operating system that runs an executable file in the context of an already existing process, replacing the previous executable. This act is also referred to as an overlay. It is especially important in Unix-like systems, although exists elsewhere. "
},
{
"code": null,
"e": 13370,
"s": 13298,
"text": "for detail :http://www.geeksforgeeks.org/exec-family-of-functions-in-c/"
},
{
"code": null,
"e": 13803,
"s": 13370,
"text": "System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork()."
},
{
"code": null,
"e": 14092,
"s": 13803,
"text": " Demand paging (as opposed to anticipatory paging) is a method of virtual memory management. It follows that a process begins execution with none of its pages in physical memory, and many page faults will occur until most of a process's working set of pages is located in physical memory."
},
{
"code": null,
"e": 14267,
"s": 14092,
"text": "Address registers - contain main memory addresses of data and instructions or they contain a portion of the address that is used in the calculation of the complete addresses."
},
{
"code": null,
"e": 14345,
"s": 14267,
"text": "Data registers - can be assigned to a variety of functions by the programmer."
},
{
"code": null,
"e": 14425,
"s": 14345,
"text": "They can be used with any machine instruction that performs operations on data."
},
{
"code": null,
"e": 14649,
"s": 14425,
"text": "Paging is solution to external fragmentation problem which is to permit the logical address space of a process to be non contiguous, thus allowing a process to be allocating physical memory wherever the latter is available."
},
{
"code": null,
"e": 14793,
"s": 14649,
"text": "1NF is the First Normal Form. It is the simplest type of normalization that you can implement in a database. The main objectives of 1NF are to:"
},
{
"code": null,
"e": 14838,
"s": 14793,
"text": "Remove duplicate columns from the same table"
},
{
"code": null,
"e": 14935,
"s": 14838,
"text": "Create separate tables for each group of related data and identify each row with a unique column"
},
{
"code": null,
"e": 15040,
"s": 14935,
"text": "Extension: Extension is the number of tuples present in a table at any instance. This is time dependent."
},
{
"code": null,
"e": 15153,
"s": 15040,
"text": "Intension: Intension is a constant value that gives the name, structure of table and the constraints laid on it."
},
{
"code": null,
"e": 15271,
"s": 15153,
"text": "Relational Calculus is a Non-procedural Query Language which uses mathematical predicate calculus instead of algebra."
},
{
"code": null,
"e": 15425,
"s": 15271,
"text": "Interface is a blueprint of a class that have static constants and abstract methods.It can be used to achieve fully abstraction and multiple inheritance."
},
{
"code": null,
"e": 15639,
"s": 15425,
"text": "The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc."
},
{
"code": null,
"e": 15709,
"s": 15639,
"text": "Synchronized block is used to lock an object for any shared resource."
},
{
"code": null,
"e": 15765,
"s": 15709,
"text": "Scope of synchronized block is smaller than the method."
},
{
"code": null,
"e": 15896,
"s": 15765,
"text": "The shutdown hook is basically a thread i.e. invoked implicitly before JVM shuts down. So we can use it perform clean up resource."
},
{
"code": null,
"e": 16204,
"s": 15896,
"text": "The thread executing this method, obtains one lock at a time. First, copies the state of the given person object into local variables using one lock. It then, uses these variables to transfer the state to the current object using another lock. This approach mitigated deadlocks by removing lock overlapping."
},
{
"code": null,
"e": 16498,
"s": 16204,
"text": "A thread pool is a software design pattern for achieving concurrency of execution in a computer program. Often also called a replicated workers or worker-crew model, a thread pool maintains multiple threads waiting for tasks to be allocated for concurrent execution by the supervising program."
},
{
"code": null,
"e": 16818,
"s": 16498,
"text": "Static methods cannot be overridden because method overriding only occurs in the context of dynamic (i.e. runtime) lookup of methods. Static methods (by their name) are looked up statically (i.e. at compile-time). Method overriding happens in the type of subtype polymorphism that exists in languages like Java and C++."
},
{
"code": null,
"e": 16918,
"s": 16818,
"text": "for detail refers:http://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/ "
},
{
"code": null,
"e": 17307,
"s": 16942,
"text": "Fail-Fast iterators, returned by most of the collection types, doesn’t tolerate any structural modifications to a collection while iterating over it. (Structural modifications means add, remove or updating an element in the collection) They throw ConcurrentModificationException if a collection is structurally modified while iteration is going on the collection. "
},
{
"code": null,
"e": 17819,
"s": 17307,
"text": "In systems design, a fail-fast system is one which immediately reports at its interface any condition that is likely to indicate a failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly flawed process. Such designs often check the system's state at several points in an operation, so any failures can be detected early. A fail-fast module passes the responsibility for handling errors, but not detecting them, to the next-highest level of the system."
},
{
"code": null,
"e": 18062,
"s": 17819,
"text": "A connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required. Connection pools are used to enhance the performance of executing commands on a database."
},
{
"code": null,
"e": 18199,
"s": 18062,
"text": "The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void."
},
{
"code": null,
"e": 18311,
"s": 18201,
"text": "Performance testing focused on ensuring the application under test gracefully handles increases in work load."
},
{
"code": null,
"e": 18527,
"s": 18311,
"text": "A standard of measurement. Software metrics are the statistics describing the structure or content of a program. A metric should be a real objective measurement of something such as number of bugs per lines of code."
},
{
"code": null,
"e": 18643,
"s": 18527,
"text": "A device, computer program, or system that accepts the same inputs and produces the same outputs as a given system."
},
{
"code": null,
"e": 18842,
"s": 18645,
"text": "DNS uses UDP for communication between servers. It is a better choice than TCP because of the improved speed a connectionless protocol offers. Of course, transmission reliability suffers with UDP."
},
{
"code": null,
"e": 19128,
"s": 18844,
"text": "In concurrent programming, a monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become true. Monitors also have a mechanism for signaling other threads that their condition has been met."
},
{
"code": null,
"e": 19179,
"s": 19128,
"text": "for detail :http://www.geeksforgeeks.org/monitors/"
},
{
"code": null,
"e": 19768,
"s": 19179,
"text": "Stock market prediction is the act of trying to determine the future value of a company stock or other financial instrument traded on an exchange. The successful prediction of a stock's future price could yield significant profit. The efficient-market hypothesis suggests that stock prices reflect all currently available information and any price changes that are not based on newly revealed information thus are inherently unpredictable. Others disagree and those with this viewpoint possess myriad methods and technologies which purportedly allow them to gain future price information."
},
{
"code": null,
"e": 20059,
"s": 19768,
"text": "SQL NOT NULL Constraint. By default, a column can hold NULL values. The NOTNULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field."
},
{
"code": null,
"e": 20378,
"s": 20059,
"text": "A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table. The unique key and primary key both provide a guarantee for uniqueness for a column or a set of columns. There is an automatically defined unique key constraint within a primary key constraint."
},
{
"code": null,
"e": 20496,
"s": 20378,
"text": "This is a primary file organization technique that provides very fast access to records on certain search conditions."
},
{
"code": null,
"e": 20744,
"s": 20496,
"text": "The description of a data base is called the database schema , which is specified during database design and is not expected to change frequently . A displayed schema is called schema diagram .We call each object in the schema as schema construct."
},
{
"code": null,
"e": 21052,
"s": 20746,
"text": "This is another recursion procedure which is the number of times the procedure is called recursively in the process of enlarging a given argument or arguments. Usually this quantity is not obvious except in the case of extremely simple recursive functions, such as FACTORIAL (N), for which the depth is N."
},
{
"code": null,
"e": 21234,
"s": 21052,
"text": "a semaphore is a variable or abstract data type used to control access to a common resource by multiple processes in a concurrent system such as a multiprogramming operating system."
},
{
"code": null,
"e": 21495,
"s": 21234,
"text": "Semaphores are widely used to control access to files and shared memory. The three basic functionalities associated with semaphores are set, check and wait until it clears to set it again. |\n\nSemaphores are used to address benchmark synchronization problems.\n "
},
{
"code": null,
"e": 21782,
"s": 21495,
"text": "In system programming, an interrupt is a signal to the processor emitted by hardware or software indicating an event that needs immediate attention. An interrupt alerts the processor to a high-priority condition requiring the interruption of the current code the processor is executing."
},
{
"code": null,
"e": 22036,
"s": 21782,
"text": "A memory management unit (MMU), sometimes called paged memory management unit (PMMU), is a computer hardware unit having all memory references passed through itself, primarily performing the translation of virtual memory addresses to physical addresses."
},
{
"code": null,
"e": 22304,
"s": 22036,
"text": "Thread safety is a computer programming concept applicable to multi-threaded code.Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfil their design specifications without unintended interaction."
},
{
"code": null,
"e": 22579,
"s": 22304,
"text": "A function is reentrant if it can be invoked while already in the process of executing. That is, a function is reentrant if it can be interrupted in the middle of execution (for example, by a signal or interrupt) and invoked again before the interrupted execution completes."
},
{
"code": null,
"e": 22761,
"s": 22579,
"text": "A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior."
},
{
"code": null,
"e": 22824,
"s": 22761,
"text": "for detail:http://www.geeksforgeeks.org/function-pointer-in-c/"
},
{
"code": null,
"e": 23102,
"s": 22824,
"text": "In computer science, a smart pointer is an abstract data type that simulates a pointer while providing added features, such as automatic memory management or bounds checking. Such features are intended to reduce bugs caused by the misuse ofpointers, while retaining efficiency."
},
{
"code": null,
"e": 23123,
"s": 23102,
"text": "Lambda Expressions. "
},
{
"code": null,
"e": 23163,
"s": 23123,
"text": "Automatic Type Deduction and decltype. "
},
{
"code": null,
"e": 23195,
"s": 23163,
"text": "Uniform Initialization Syntax. "
},
{
"code": null,
"e": 23229,
"s": 23195,
"text": "Deleted and Defaulted Functions. "
},
{
"code": null,
"e": 23239,
"s": 23229,
"text": "nullptr. "
},
{
"code": null,
"e": 23265,
"s": 23239,
"text": "Delegating Constructors. "
},
{
"code": null,
"e": 23285,
"s": 23265,
"text": "Rvalue References. "
},
{
"code": null,
"e": 23313,
"s": 23285,
"text": "C++11 Standard Library. etc"
},
{
"code": null,
"e": 23613,
"s": 23313,
"text": "A bitset stores bits (elements with only two possible values: 0 or 1, true or false).The class emulates an array of bool elements, but optimized for space allocation: generally, each element occupies only one bit (which, on most systems, is eight times less than the smallest elemental type: char )."
},
{
"code": null,
"e": 23998,
"s": 23613,
"text": "Mutual Exclusion: There is s resource that cannot be shared.\nHold and Wait: A process is holding at least one resource and waiting for another resource which is with some other process.\nNo Preemption: The operating system is not allowed to take a resource back from a process until process gives it back.\nCircular Wait: A set of processes are waiting for each other in circular form."
},
{
"code": null,
"e": 24176,
"s": 23998,
"text": "The set of dispatchable processes is in a safe state if there exists at least one temporal order in which all processes can be run to completion without resulting in a deadlock."
},
{
"code": null,
"e": 24276,
"s": 24176,
"text": "Dynamic Ram stores the data in the form of Capacitance, and Static RAM stores the data in Voltages."
},
{
"code": null,
"e": 24708,
"s": 24276,
"text": "\n Array is static in size while ArrayList is dynamic\nPrimitive Data Type: ArrayList cannot contain primitive data types while Array can contain both primitive objects as well as data types\nLength: Length of ArrayList is defined by size() method while that of Array has variable length .\nLength of the ArrayList is provided by the size() method while Each array object has the length variable which returns the length of the array.\n"
},
{
"code": null,
"e": 24760,
"s": 24708,
"text": " Array is static in size while ArrayList is dynamic"
},
{
"code": null,
"e": 24896,
"s": 24760,
"text": "Primitive Data Type: ArrayList cannot contain primitive data types while Array can contain both primitive objects as well as data types"
},
{
"code": null,
"e": 24994,
"s": 24896,
"text": "Length: Length of ArrayList is defined by size() method while that of Array has variable length ."
},
{
"code": null,
"e": 25138,
"s": 24994,
"text": "Length of the ArrayList is provided by the size() method while Each array object has the length variable which returns the length of the array."
},
{
"code": null,
"e": 25452,
"s": 25138,
"text": "The ArrayList class extends Abstract List and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold."
},
{
"code": null,
"e": 25701,
"s": 25452,
"text": "Hashmaps and hashtables are data structures (like arrays and lists), that use hashing to store data. In a hashtable, a hash is produced (either from a provided key, or from the object itself) that determines where in the table the object is stored."
},
{
"code": null,
"e": 25764,
"s": 25701,
"text": "for detail :http://www.geeksforgeeks.org/hashmap-treemap-java/"
},
{
"code": null,
"e": 26111,
"s": 25766,
"text": "\n\nType safe languages (like C++) have the advantage that many errors are found at compile time (as opposed to run-time). That means using Qt.grey (note the e) would fail to compile because the type is not defined.\n\n\nBetter performance and less memory. Behind the scenes Qt.gray is a number, and number operations are much faster than strings.\n\n"
},
{
"code": null,
"e": 26325,
"s": 26111,
"text": "\nType safe languages (like C++) have the advantage that many errors are found at compile time (as opposed to run-time). That means using Qt.grey (note the e) would fail to compile because the type is not defined.\n"
},
{
"code": null,
"e": 26537,
"s": 26325,
"text": "Type safe languages (like C++) have the advantage that many errors are found at compile time (as opposed to run-time). That means using Qt.grey (note the e) would fail to compile because the type is not defined."
},
{
"code": null,
"e": 26666,
"s": 26537,
"text": "\nBetter performance and less memory. Behind the scenes Qt.gray is a number, and number operations are much faster than strings.\n"
},
{
"code": null,
"e": 26793,
"s": 26666,
"text": "Better performance and less memory. Behind the scenes Qt.gray is a number, and number operations are much faster than strings."
},
{
"code": null,
"e": 27133,
"s": 26793,
"text": "A data type, in programming, is a classification that specifies which type of value a variable has and what type of mathematical, relational or logical operations can be applied to it without causing an error. A string, for example, is a data type that is used to classify text and an integer is a data type used to classify whole numbers."
},
{
"code": null,
"e": 27156,
"s": 27133,
"text": "Reduce the redundancy."
},
{
"code": null,
"e": 27203,
"s": 27156,
"text": "A large amount added bendable database design."
},
{
"code": null,
"e": 27240,
"s": 27203,
"text": "Better overall database association."
},
{
"code": null,
"e": 27277,
"s": 27240,
"text": "Data uniformity inside the database."
},
{
"code": null,
"e": 27585,
"s": 27277,
"text": "External sorting is a term for a class of sorting algorithms that can handle massive amounts of data.External sorting is required when the data being sorted do not fit into the main memory of a computing device (usually RAM) and instead they must reside in the slower external memory (usually a hard drive)."
},
{
"code": null,
"e": 27743,
"s": 27585,
"text": "Image map facilitates you link many different web pages using a single image. You can define shapes in images that you want to make part of an image mapping."
},
{
"code": null,
"e": 28039,
"s": 27743,
"text": "Semantic HTML is a coding style. It is the use of HTML markup to reinforce the semantics or meaning of the content. For example: In semantic HTML <b> </b> tag is not used for bold statement as well as <i> </i> tag is used for italic. Instead of these we use <strong></strong> and <em></em> tags."
},
{
"code": null,
"e": 28278,
"s": 28039,
"text": "For indexes to improve the performance of selections, the index expression must match the selection condition exactly. For example, if you have created an index whose expression is last_name, the following Select statement uses the index:"
},
{
"code": null,
"e": 28322,
"s": 28278,
"text": "SELECT * FROM emp WHERE last_name = 'Smith'"
},
{
"code": null,
"e": 28619,
"s": 28322,
"text": "As long as your query is \"covered\" by a leading edge of an index, it will be efficient. Database indexes are typically implemented as B-Trees and the structure of the B-Tree dictates that the search must be done in a certain order, which is why the order of fields in the composite index matters."
},
{
"code": null,
"e": 28870,
"s": 28619,
"text": "A secondary index is a data structure that contains a subset of attributes from a table, along with an alternate key to support Query operations. You can retrieve data from the index using a Query , in much the same way as you use Query with a table."
},
{
"code": null,
"e": 29044,
"s": 28870,
"text": "A primary index is an index on a set of fields that includes the unique primary key for the field and is guaranteed not to contain duplicates. Also Called a Clustered index."
},
{
"code": null,
"e": 29062,
"s": 29044,
"text": "eg. Employee ID ."
},
{
"code": null,
"e": 29270,
"s": 29062,
"text": "Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit characteristics and features from more than one parent object or parent class."
},
{
"code": null,
"e": 29512,
"s": 29270,
"text": "Proactive behavior aims at identification and exploitation of opportunities and in taking preemptory action against potential problems and threats, whereas reactive behavior focuses on fighting a fire or solving a problem after it occurs.\n\n "
},
{
"code": null,
"e": 29585,
"s": 29512,
"text": "Different phases are\n1.) Analysis phase,\n2.) Redo Phase,\n3.) Undo phase."
},
{
"code": null,
"e": 29773,
"s": 29585,
"text": "This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are described in a database by a set of attributes."
},
{
"code": null,
"e": 29810,
"s": 29773,
"text": "The are three levels of abstraction:"
},
{
"code": null,
"e": 30112,
"s": 29810,
"text": "\nPhysical level: The lowest level of abstraction describes how data are stored.\nLogical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data.\nView level: The highest level of abstraction describes only part of entire database.\n"
},
{
"code": null,
"e": 30191,
"s": 30112,
"text": "Physical level: The lowest level of abstraction describes how data are stored."
},
{
"code": null,
"e": 30327,
"s": 30191,
"text": "Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data."
},
{
"code": null,
"e": 30412,
"s": 30327,
"text": "View level: The highest level of abstraction describes only part of entire database."
},
{
"code": null,
"e": 30575,
"s": 30412,
"text": "\nRedundancy is controlled.\nUnauthorised access is restricted.\nProviding multiple user interfaces.\nEnforcing integrity constraints.\nProviding backup and recovery.\n"
},
{
"code": null,
"e": 30601,
"s": 30575,
"text": "Redundancy is controlled."
},
{
"code": null,
"e": 30636,
"s": 30601,
"text": "Unauthorised access is restricted."
},
{
"code": null,
"e": 30672,
"s": 30636,
"text": "Providing multiple user interfaces."
},
{
"code": null,
"e": 30705,
"s": 30672,
"text": "Enforcing integrity constraints."
},
{
"code": null,
"e": 30736,
"s": 30705,
"text": "Providing backup and recovery."
},
{
"code": null,
"e": 31067,
"s": 30736,
"text": "Assume that a relation R with set of functional dependencies F. If R is decomposed into relations R1 and R2, then this decomposition is said to be lossless decomposition (or lossless-join decomposition) if and only if at least one of the following functional dependencies holds in the closure of set of functional dependencies F+;"
},
{
"code": null,
"e": 31080,
"s": 31067,
"text": "R1 ∩ R2 → R1"
},
{
"code": null,
"e": 31093,
"s": 31080,
"text": "R1 ∩ R2 → R2"
},
{
"code": null,
"e": 31191,
"s": 31093,
"text": "R1 ∩ R2 should be a determinant that determines all the attributes of one of relations R1 and R2."
},
{
"code": null,
"e": 31287,
"s": 31191,
"text": "for detail :http://www.geeksforgeeks.org/lossless-join-and-dependency-preserving-decomposition/"
},
{
"code": null,
"e": 31585,
"s": 31287,
"text": "\"The decompositio of relation R into R1 and R2 is lossy when the join of R1 and R2 does not yield the same relation as in R.\"\n One of the disadvantages of decomposition into two or more relational schemes (or tables) is that some information is lost during retrieval of original relation or table."
},
{
"code": null,
"e": 31628,
"s": 31585,
"text": "First normal form enforces these criteria:"
},
{
"code": null,
"e": 31677,
"s": 31628,
"text": "Eliminate repeating groups in individual tables."
},
{
"code": null,
"e": 31731,
"s": 31677,
"text": "Create a separate table for each set of related data."
},
{
"code": null,
"e": 31786,
"s": 31731,
"text": "Identify each set of related data with a primary key ."
},
{
"code": null,
"e": 32107,
"s": 31786,
"text": "WhatsApp or most of the other messaging apps rarely work on a peer to peer basis. So it wouldn't open a connection (from your device) to each of your friends' devices. WhatsApp will use that connection to send them your messages. If their app is \"offline\" then they might choose to send them a push notification instead."
},
{
"code": null,
"e": 32379,
"s": 32107,
"text": "Loose coupling is an approach to interconnecting the components in a system or network so that those components, also called elements, depend on each other to the least extent practicable. Coupling refers to the degree of direct knowledge that one element has of another."
},
{
"code": null,
"e": 32631,
"s": 32379,
"text": "The Travelling Salesman Problem (often called TSP) is a classic algorithmic problem in the field of computer science. It is focused on optimization. In this context better solution often means a solution that is cheaper. TSP is a mathematical problem."
},
{
"code": null,
"e": 32872,
"s": 32631,
"text": " the travelling salesperson problem, asks the following question: \"Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city ."
},
{
"code": null,
"e": 32993,
"s": 32872,
"text": "Solution of a travelling salesman problem: the black line shows the shortest possible loop that connects every red dot ."
},
{
"code": null,
"e": 33009,
"s": 32993,
"text": "\nAbstraction .\n"
},
{
"code": null,
"e": 33023,
"s": 33009,
"text": "Abstraction ."
},
{
"code": null,
"e": 33041,
"s": 33023,
"text": "\nEncapsulation .\n"
},
{
"code": null,
"e": 33057,
"s": 33041,
"text": "Encapsulation ."
},
{
"code": null,
"e": 33074,
"s": 33057,
"text": "\nPolymorphism .\n"
},
{
"code": null,
"e": 33089,
"s": 33074,
"text": "Polymorphism ."
},
{
"code": null,
"e": 33105,
"s": 33089,
"text": "\nInheritance .\n"
},
{
"code": null,
"e": 33119,
"s": 33105,
"text": "Inheritance ."
},
{
"code": null,
"e": 33405,
"s": 33119,
"text": "Data hiding is a software development technique specifically used in object-oriented programming (OOP) to hide internal object details (data members). Data hiding ensures exclusive data access to class members and protects object integrity by preventing unintended or intended changes."
},
{
"code": null,
"e": 33597,
"s": 33405,
"text": " Search: ArrayList search operation is pretty fast compared to the LinkedList search operation. get(int index) in ArrayList gives the performance of O(1) while LinkedList performance is O(n)."
},
{
"code": null,
"e": 33647,
"s": 33597,
"text": "\nThe time complexity comparison is as follows: \n\n"
},
{
"code": null,
"e": 33694,
"s": 33647,
"text": "The time complexity comparison is as follows: "
},
{
"code": null,
"e": 33866,
"s": 33694,
"text": "\nArrayList class can act as a list only because it implements List only.LinkedList class can act as a list and queue both because it implements List and Deque interfaces.\n"
},
{
"code": null,
"e": 34036,
"s": 33866,
"text": "ArrayList class can act as a list only because it implements List only.LinkedList class can act as a list and queue both because it implements List and Deque interfaces."
},
{
"code": null,
"e": 34133,
"s": 34036,
"text": "\nArrayList is better for storing and accessing data.LinkedList is better for manipulating data.\n"
},
{
"code": null,
"e": 34228,
"s": 34133,
"text": "ArrayList is better for storing and accessing data.LinkedList is better for manipulating data."
},
{
"code": null,
"e": 34407,
"s": 34228,
"text": "Responsive web design (RWD) is an approach to web design aimed at allowing desktop webpages to be viewed in response to the size of the screen or web browser one is viewing with."
},
{
"code": null,
"e": 34687,
"s": 34407,
"text": "The web server locates and then sends the information to the web browser, which displays the results. When web browsers contact servers, they're asking to be sent pages built with Hypertext Markup Language (HTML). Browsers interpret those pages and display them on your computer."
},
{
"code": null,
"e": 34994,
"s": 34687,
"text": "A server is a computer program that provides services to other computer programs (and their users) in the same or other computers. Servers are used to manage network resources. For example, a user may setup a server to control access to a network, send/receive e-mail, manage print jobs, or host a website."
},
{
"code": null,
"e": 35201,
"s": 34994,
"text": "A client is a computer that retrieves information from or uses resources provided by the server or main computer. Many corporate networks are comprised of a client computer at each of the employees' desks. "
},
{
"code": null,
"e": 35324,
"s": 35201,
"text": "A web application is a computer program that utilizes web browsers and web technology to perform tasks over the Internet."
},
{
"code": null,
"e": 35607,
"s": 35324,
"text": "Interfaces are contracts between two disparate pieces of code. The exchange can be between software, computer hardware, peripheral devices, humans and combinations of these. Some computer hardware devices, such as a touchscreen, can both send and receive data through the interface."
},
{
"code": null,
"e": 35790,
"s": 35607,
"text": "Ternery search tree requires O(log(n)+k) comparisons where n is number of strings and k is the length of the string to be searched and binary search tree requires log(n) comparisons."
},
{
"code": null,
"e": 35871,
"s": 35790,
"text": "for detail :http://www.geeksforgeeks.org/binary-search-preferred-ternary-search/"
},
{
"code": null,
"e": 36019,
"s": 35871,
"text": "select top 1 * from\n(\n select top 3 * from\n (\n select distinct emp_sal from employee order by asc emp_sal\n ) d orderby desc emp_sal\n)"
},
{
"code": null,
"e": 36040,
"s": 36019,
"text": "Creation of Sockets:"
},
{
"code": null,
"e": 36243,
"s": 36040,
"text": "socket() \n| \nbind() \n| \nrecvfrom() \n| \n(wait for a sendto request from some client) \n| \n(process the sendto request) \n| \nsendto (in reply to the request from the client...for example, send an HTML file)"
},
{
"code": null,
"e": 36478,
"s": 36243,
"text": "Sockets are commonly used for client/server interaction. Typical system configuration places the server on one machine, with the clients on other machines. The clients connect to the server, exchange information, and then disconnect ."
},
{
"code": null,
"e": 36675,
"s": 36478,
"text": "A server may create several concurrently established TCP sockets with the same local port number and local IP address, each mapped to its own server-child process, serving its own client process. "
},
{
"code": null,
"e": 36892,
"s": 36675,
"text": "The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible."
},
{
"code": null,
"e": 37001,
"s": 36892,
"text": "An undirected graph is tree if it has following properties.\n1) There is no cycle.\n2) The graph is connected."
},
{
"code": null,
"e": 37086,
"s": 37001,
"text": "For an undirected graph we can either use BFS or DFS to detect above two properties."
},
{
"code": null,
"e": 37151,
"s": 37086,
"text": "for detail :http://www.geeksforgeeks.org/check-given-graph-tree/"
},
{
"code": null,
"e": 37167,
"s": 37151,
"text": "Process State :"
},
{
"code": null,
"e": 37243,
"s": 37167,
"text": "To measure the demand paging, the effective access time for a demand –paged"
},
{
"code": null,
"e": 37268,
"s": 37243,
"text": "memory is calculated by:"
},
{
"code": null,
"e": 37327,
"s": 37268,
"text": "Effective access time = (1 – p) x ma + p x page fault time"
},
{
"code": null,
"e": 37378,
"s": 37327,
"text": "Where p: The probability of page fault, 0 < p < 1;"
},
{
"code": null,
"e": 37466,
"s": 37383,
"text": "To improve both the utilization of the CPU and the speed of its response to users."
},
{
"code": null,
"e": 37832,
"s": 37466,
"text": "A jigsaw puzzle is a tiling puzzle that requires the assembly of often oddly shaped interlocking and tessellating pieces. Each piece usually has a small part of a picture on it; when complete, a jigsaw puzzle produces a complete picture. In some cases more advanced types have appeared on the market, such as spherical jigsaws and puzzles showing optical illusions."
},
{
"code": null,
"e": 38015,
"s": 37832,
"text": "During recent years, a range of jigsaw puzzle accessories including boards, cases, frames and roll-up mats has become available that are designed to assist jigsaw puzzle enthusiasts."
},
{
"code": null,
"e": 38042,
"s": 38015,
"text": "print 1, 2, 3, 4, 5, 6, 7."
},
{
"code": null,
"e": 38133,
"s": 38042,
"text": "for more detail refers :http://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/"
},
{
"code": null,
"e": 38222,
"s": 38133,
"text": " The worst case complexity looks like O(nLogn), upper bound of time complexity is O(n). "
},
{
"code": null,
"e": 38380,
"s": 38222,
"text": "Max heap is a specialized full binary tree in which every parent node contains greater or equal value than its child nodes. And last leaf node can be alone ."
},
{
"code": null,
"e": 38390,
"s": 38380,
"text": "Example :"
},
{
"code": null,
"e": 38642,
"s": 38390,
"text": "A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to Min Heap."
},
{
"code": null,
"e": 38664,
"s": 38642,
"text": "Examples of Min Heap:"
},
{
"code": null,
"e": 38887,
"s": 38664,
"text": " 10 10\n / \\ / \\ \n 20 100 15 30 \n / / \\ / \\\n 30 40 50 100 40"
},
{
"code": null,
"e": 38963,
"s": 38887,
"text": "C follows the procedural programming. Java is platform independent language"
},
{
"code": null,
"e": 39026,
"s": 38963,
"text": "Java is an Interpreted language while C is a compiled language"
},
{
"code": null,
"e": 39095,
"s": 39026,
"text": "C uses the top-down approach while JAVA uses the bottom-up approach."
},
{
"code": null,
"e": 39156,
"s": 39095,
"text": "Java is a high-level language and C is a low-level language."
},
{
"code": null,
"e": 39348,
"s": 39156,
"text": "Another minor difference regarding boolean is that in C, stands for false and all the other numbers are considered true. Whereas in Java, they are represented literally by ‘true’ and ‘false'."
},
{
"code": null,
"e": 39449,
"s": 39348,
"text": "C uses the top-down {sharp & smooth} approach while JAVA uses the bottom-up {on the rocks} approach."
},
{
"code": null,
"e": 39507,
"s": 39449,
"text": "Exception Handling in JAVA And the errors & crashes in C."
},
{
"code": null,
"e": 39586,
"s": 39507,
"text": " JAVA supports Method Overloading while C does not support overloading at all."
},
{
"code": null,
"e": 39790,
"s": 39586,
"text": "Database Normalization, or simply normalization, is the process of organizing the columns (attributes) and tables(relations) of a relational database to reduce data redundancy and improve data integrity."
},
{
"code": null,
"e": 39930,
"s": 39790,
"text": "data normalization rules tend to increase the duplication of data, it does not introduce data redundancy, which is unnecessary duplication."
},
{
"code": null,
"e": 40179,
"s": 39930,
"text": "Normalization can also be thought of as a trade-off between data redundancy and performance. Normalizing a relation reduces data redundancy but introduces the need for joins when all of the data is required by an application such as a report query."
},
{
"code": null,
"e": 40306,
"s": 40179,
"text": "To find out if your computer is running a 32-bit or 64-bit version of Windows in Windows 7 or Windows Vista, do the following:"
},
{
"code": null,
"e": 40407,
"s": 40306,
"text": "1. Open System by clicking the Start button , right-clicking Computer, and then clicking Properties."
},
{
"code": null,
"e": 40454,
"s": 40407,
"text": "2. Under System, you can view the system type."
},
{
"code": null,
"e": 40744,
"s": 40454,
"text": "A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number."
},
{
"code": null,
"e": 41037,
"s": 40744,
"text": "Process Synchronization means sharing system resources by processes in a such a way that, Concurrent access to shared data is handled thereby minimizing the chance of inconsistent data. Maintaining data consistency demands mechanisms to ensure synchronized execution of cooperating processes."
},
{
"code": null,
"e": 41116,
"s": 41037,
"text": "for detail refers :http://www.geeksforgeeks.org/process-synchronization-set-1/"
},
{
"code": null,
"e": 41394,
"s": 41116,
"text": "A directory is a file system cataloging structure which contains references to other computer files, and possibly other directories. On many computers, directories are known as folders, or drawers to provide some relevancy to a workbench or the traditional office file cabinet."
},
{
"code": null,
"e": 41661,
"s": 41394,
"text": "Files are organized by storing related files in the same directory. In a hierarchical file system (that is, one in which files and directories are organized in a manner that resembles a tree), a directory contained inside another directory is called a sub directory."
},
{
"code": null,
"e": 42142,
"s": 41661,
"text": " file system or file system is used to control how data is stored and retrieved. Without a file system, information placed in a storage medium would be one large body of data with no way to tell where one piece of information stops and the next begins. By separating the data into pieces and giving each piece a name, the information is easily isolated and identified. Taking its name from the way paper-based information systems are named, each group of data is called a \"file\". "
},
{
"code": null,
"e": 42405,
"s": 42142,
"text": "File systems can be used on numerous different types of storage devices that use different kinds of media. The most common storage device in use today is a hard disk drive. Other kinds of media that are used include flash memory,magnetic tapes, and optical discs"
},
{
"code": null,
"e": 42515,
"s": 42405,
"text": "Insertion sort is faster for small n because Quick Sort has extra overhead from the recursive function calls."
},
{
"code": null,
"e": 42592,
"s": 42515,
"text": "Insertion sort is also more stable than Quick sort and requires less memory."
},
{
"code": null,
"e": 42665,
"s": 42592,
"text": "Best case of insertion sort is O(n).Best case of quick sort is O(nlogn)."
},
{
"code": null,
"e": 42677,
"s": 42667,
"text": "Examples:"
},
{
"code": null,
"e": 42877,
"s": 42677,
"text": " 20\n / \\\n 8 22\n / \\ \\\n 5 3 25\n / \\ \n 10 14\n\n"
},
{
"code": null,
"e": 42935,
"s": 42877,
"text": "For the above tree the output should be 5, 10, 3, 14, 25."
},
{
"code": null,
"e": 43008,
"s": 42935,
"text": "for detail refers :http://www.geeksforgeeks.org/bottom-view-binary-tree/"
},
{
"code": null,
"e": 43290,
"s": 43008,
"text": "An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails .A service is a component that runs in the background to perform long-running operations or to perform work for remote processes."
},
{
"code": null,
"e": 43372,
"s": 43290,
"text": "Activity is a GUI and service is non-gui thread which can run in the background ."
},
{
"code": null,
"e": 43610,
"s": 43372,
"text": "\nAn activity represents a single screen with a user interface.\nA service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface.\n"
},
{
"code": null,
"e": 43672,
"s": 43610,
"text": "An activity represents a single screen with a user interface."
},
{
"code": null,
"e": 43846,
"s": 43672,
"text": "A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface."
},
{
"code": null,
"e": 44121,
"s": 43848,
"text": "By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error. Tip. Although the __autoload() function can also be used forautoloading classes and interfaces, it's preferred to use the spl_autoload_register() function."
},
{
"code": null,
"e": 44386,
"s": 44121,
"text": "PHP provides a number of 'magic' methods that allow you to do some pretty neat tricks in object oriented programming. These methods, identified by a two underscore prefix (__), function as interceptors that are automatically called when certain conditions are met."
},
{
"code": null,
"e": 44705,
"s": 44386,
"text": "Singleton class means you can create only one object for the given class. You can create a singleton class by making its constructor as private, so that you can restrict the creation of the object. Provide a static method to get instance of the object, wherein you can handle the object creation inside the class only."
},
{
"code": null,
"e": 45188,
"s": 44705,
"text": "We close a resource inside the try block. However this is not a good practice, because if an exception is thrown before our close statement is reached, then it will not be executed and resources might thus leak. We could add the close statement in the catch block, which leads to code duplication. If we have several catch blocks, this means we have to add the close statement there. Whenever we need to add a new catch block, we must also remember to put the close statement there."
},
{
"code": null,
"e": 45210,
"s": 45188,
"text": "Arithmetic Exception."
},
{
"code": null,
"e": 45242,
"s": 45210,
"text": "ArrayIndexOutOfBoundException ."
},
{
"code": null,
"e": 45267,
"s": 45242,
"text": "ClassNotFoundException ."
},
{
"code": null,
"e": 45291,
"s": 45267,
"text": "FileNotFoundException ."
},
{
"code": null,
"e": 45314,
"s": 45291,
"text": "InterruptedException ."
},
{
"code": null,
"e": 45333,
"s": 45314,
"text": "RuntimeException ."
},
{
"code": null,
"e": 45371,
"s": 45333,
"text": "StringIndexOutOfBoundsException . etc"
},
{
"code": null,
"e": 45454,
"s": 45371,
"text": "for detail :http://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/"
},
{
"code": null,
"e": 45628,
"s": 45454,
"text": "An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions."
},
{
"code": null,
"e": 45689,
"s": 45628,
"text": "for detail :http://www.geeksforgeeks.org/exceptions-in-java/"
},
{
"code": null,
"e": 46099,
"s": 45689,
"text": "Multithreading is a type of execution model that allows multiple threads to exist within the context of a process such that they execute independently but share their process resources.This approach differs from multiprocessing, as with multithreading the processes and threads share the resources of a single or multiple cores: the computing units, the CPU caches, and the translation lookaside buffer (TLB)."
},
{
"code": null,
"e": 46264,
"s": 46099,
"text": "For example, a multithreaded operating system may run several background tasks, such as logging file changes, indexing data, and managing windows at the same time. "
},
{
"code": null,
"e": 46544,
"s": 46264,
"text": "Dynamic-link library (or DLL) is Microsoft's implementation of the shared library concept in the Microsoft Windows and OS/2 operating systems. These libraries usually have the file extension DLL, OCX (for libraries containing ActiveX controls), or DRV(for legacy system drivers)."
},
{
"code": null,
"e": 46784,
"s": 46544,
"text": "For example, several different programs might all call upon the very useful.dll file (I made that up, of course) to find the free space on a hard drive, locate a file in a particular directory, and print a test page to the default printer."
},
{
"code": null,
"e": 47033,
"s": 46784,
"text": "When the CPU gets to that instruction, and executes the int3 , this causes the CPU to generate a debug exception. The OS receives this interrupt, realizes the process is being debugged, and notifies the debugger process that the breakpoint was hit."
},
{
"code": null,
"e": 47249,
"s": 47033,
"text": "Any class type (whether declared with class-key class or struct) may be declared as derived from one or more base classes which, in turn, may be derived from their own base classes, forming an inheritance hierarchy."
},
{
"code": null,
"e": 47257,
"s": 47249,
"text": "Syntax:"
},
{
"code": null,
"e": 47505,
"s": 47257,
"text": "struct Base {\n int a, b, c;\n};\n// every object of type Derived includes Base as a subobject\nstruct Derived : Base {\n int b;\n};\n// every object of type Derived2 includes Derived and Base as subobjects\nstruct Derived2 : Derived {\n int c;\n};"
},
{
"code": null,
"e": 47820,
"s": 47507,
"text": "The best way to think about space complexity of recursive functions is (# of stack frames)*(space per stack frame). In your case, you have n stack frames f(n), f(n-1), f(n-2), ..., f(1) and O(1) space per stack frame (to store the argument n).\nbut there are fibonnaci(n) recursive calls so Space Complexity O(n)."
},
{
"code": null,
"e": 48391,
"s": 47820,
"text": "/* a[] is the array, p is starting index, that is 0, \nand r is the last index of array. */\n\nvoid quicksort(int a[], int p, int r) \n{\n if(p < r)\n {\n int q;\n q = partition(a, p, r);\n quicksort(a, p, q);\n quicksort(a, q+1, r);\n }\n}\n\nint partition(int a[], int p, int r)\n{\n int i, j, pivot, temp;\n pivot = a[p];\n i = p;\n j = r;\n while(1)\n {\n while(a[i] < pivot && a[i] != pivot)\n i++;\n while(a[j] > pivot && a[j] != pivot)\n j--;\n if(i < j)\n {\n temp = a[i];\n a[i] = a[j];\n a[j] = temp;\n }\n else\n {\n return j;\n }\n }\n}"
},
{
"code": null,
"e": 48450,
"s": 48391,
"text": "for detail refer :http://www.geeksforgeeks.org/quick-sort/"
},
{
"code": null,
"e": 48721,
"s": 48450,
"text": "INSERTION-SORT (A)\n1 for j <- 2 to length[A]\n2 do key <- A[j]\n3 Insert A[j] into the sorted sequence A[1 . . j - 1].\n4 i <- j - 1\n5 while i > 0 and A[i] > key\n6 do A[i + 1] <- A[i]\n7 i <- i - 1\n8 A[i + 1] <- key"
},
{
"code": null,
"e": 48785,
"s": 48721,
"text": "for detail refers :http://www.geeksforgeeks.org/insertion-sort/"
},
{
"code": null,
"e": 49099,
"s": 48785,
"text": "a heap is a specialized tree-based data structure that satisfies the heap property: if P is a parent node of C, then the key (the value) of node P is ordered with respect to the key of node C with the same ordering applying across the heap. A heap can be classified further as either a \"max heap\" or a \"min heap\"."
},
{
"code": null,
"e": 49160,
"s": 49099,
"text": "for detail refers :http://www.geeksforgeeks.org/binary-heap/"
},
{
"code": null,
"e": 49419,
"s": 49160,
"text": " perform a simple inorder traversal and keep the previous value of the node. If the current node is smaller than the previous node then it is not a binary search tree. You use constant additional space (for the previous value) apart from the recursion stack."
},
{
"code": null,
"e": 49518,
"s": 49419,
"text": "for detail refers :http://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/"
},
{
"code": null,
"e": 49759,
"s": 49518,
"text": "In database management an aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurement such as a set, a bag or a list."
},
{
"code": null,
"e": 49796,
"s": 49759,
"text": "Common aggregate functions include :"
},
{
"code": null,
"e": 49830,
"s": 49796,
"text": "Average() (i.e., arithmetic mean)"
},
{
"code": null,
"e": 49838,
"s": 49830,
"text": "Count()"
},
{
"code": null,
"e": 49853,
"s": 49838,
"text": "Maximum() etc."
},
{
"code": null,
"e": 49949,
"s": 49853,
"text": "for detail refers :http://www.geeksforgeeks.org/database-management-system-aggregate-functions/"
},
{
"code": null,
"e": 50048,
"s": 49949,
"text": "The keyword struct is used to define a structure while keyword union is used to define a union. "
},
{
"code": null,
"e": 50340,
"s": 50048,
"text": "In Structure, the address of each member will be in ascending order This indicates that memory for each member will start at different offset values while in unions the address is same for all the members of a union. This indicates that every member begins at the same offset value. "
},
{
"code": null,
"e": 50597,
"s": 50340,
"text": "A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter."
},
{
"code": null,
"e": 50725,
"s": 50597,
"text": " In case of structure, each member have their own memory space but In union, one block is used by all the member of the union."
},
{
"code": null,
"e": 50802,
"s": 50725,
"text": "for detail refers:http://www.geeksforgeeks.org/difference-structure-union-c/"
},
{
"code": null,
"e": 50964,
"s": 50802,
"text": "A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type."
},
{
"code": null,
"e": 51064,
"s": 50964,
"text": "How to create a structure?\n‘struct’ keyword is used to create a structure. Following is an example."
},
{
"code": null,
"e": 51080,
"s": 51064,
"text": "struct addrress"
},
{
"code": null,
"e": 51082,
"s": 51080,
"text": "{"
},
{
"code": null,
"e": 51100,
"s": 51082,
"text": " char name[50];"
},
{
"code": null,
"e": 51121,
"s": 51100,
"text": " char street[100];"
},
{
"code": null,
"e": 51139,
"s": 51121,
"text": " char city[50];"
},
{
"code": null,
"e": 51157,
"s": 51139,
"text": " char state[20]"
},
{
"code": null,
"e": 51169,
"s": 51157,
"text": " int pin;"
},
{
"code": null,
"e": 51172,
"s": 51169,
"text": "};"
},
{
"code": null,
"e": 51227,
"s": 51172,
"text": "for detail :http://www.geeksforgeeks.org/structures-c/"
},
{
"code": null,
"e": 51466,
"s": 51227,
"text": "Demultiplex (DEMUX) is the reverse of the multiplex (MUX) process – combining multiple unrelated analog or digital signal streams into one signal over a single shared medium, such as a single conductor of copper wire or fiber optic cable."
},
{
"code": null,
"e": 51619,
"s": 51466,
"text": "Multiplexing (sometimes contracted to muxing) is a method by which multiple analog or digital signals are combined into one signal over a shared medium."
},
{
"code": null,
"e": 51822,
"s": 51619,
"text": "Multiplexing is done by using a device called multiplexer (MUX) that combines n input lines to generate one output line i.e. (many to one). Therefore multiplexer (MUX) has several inputs and one output."
},
{
"code": null,
"e": 51914,
"s": 51824,
"text": "Networking company almost all data structures are being used, some of them are followings"
},
{
"code": null,
"e": 52029,
"s": 51914,
"text": "\nStack\nQueue\nList\nTree ( AVL, BST, n-ary)\nGraph ( MST, dijkstra algorithm etc )\nTrie ( prefix tree: Route lookup)\n"
},
{
"code": null,
"e": 52035,
"s": 52029,
"text": "Stack"
},
{
"code": null,
"e": 52041,
"s": 52035,
"text": "Queue"
},
{
"code": null,
"e": 52046,
"s": 52041,
"text": "List"
},
{
"code": null,
"e": 52070,
"s": 52046,
"text": "Tree ( AVL, BST, n-ary)"
},
{
"code": null,
"e": 52108,
"s": 52070,
"text": "Graph ( MST, dijkstra algorithm etc )"
},
{
"code": null,
"e": 52142,
"s": 52108,
"text": "Trie ( prefix tree: Route lookup)"
},
{
"code": null,
"e": 52369,
"s": 52142,
"text": "Constants provide some level of guarantee that code can't change the underlying value. This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors."
},
{
"code": null,
"e": 52528,
"s": 52369,
"text": "Constants are also inherently static - you can declare the constant and its value in a header file, and not have to worry about defining it exactly one place."
},
{
"code": null,
"e": 52701,
"s": 52528,
"text": "The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal "
},
{
"code": null,
"e": 52756,
"s": 52701,
"text": "pointer, using the void keyword as the pointer's type:"
},
{
"code": null,
"e": 52794,
"s": 52756,
"text": " void *ptr; // ptr is a void pointer."
},
{
"code": null,
"e": 52857,
"s": 52794,
"text": "for detail refers:http://www.geeksforgeeks.org/void-pointer-c/"
},
{
"code": null,
"e": 53107,
"s": 52857,
"text": "an automatic variable is a local variable which is allocated and deal located automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or block in which available is defined."
},
{
"code": null,
"e": 53176,
"s": 53107,
"text": "for detail refers:http://www.geeksforgeeks.org/storage-classes-in-c/"
},
{
"code": null,
"e": 53441,
"s": 53176,
"text": " a \"default constructor\" refers to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class. The default constructor implicitly calls the superclass's nullary constructor, then executes an empty body."
},
{
"code": null,
"e": 53530,
"s": 53441,
"text": "for detail refers :http://www.geeksforgeeks.org/c-internals-default-constructors-set-1/"
},
{
"code": null,
"e": 53699,
"s": 53530,
"text": "DELETE :Command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. "
},
{
"code": null,
"e": 53888,
"s": 53699,
"text": "DROP :Drop command will delete the entire row also the structure.But truncate will delete the contents only not the structure, so no need to give specifications for another table creation."
},
{
"code": null,
"e": 54106,
"s": 53888,
"text": "TRUNCATE :TRUNCATE command is DDL command. It removes all the information of the table. Regarding performance if you have to delete all the rows of a table you should perform TRUNCATE command with DROP STORAGE option."
},
{
"code": null,
"e": 54210,
"s": 54108,
"text": "Suppose a pointer (say ptr) is pointing to a memory of 10 int on heap allocated usingmalloc as below."
},
{
"code": null,
"e": 54252,
"s": 54210,
"text": "int * ptr = (int*)malloc(10*sizeof(int));"
},
{
"code": null,
"e": 54456,
"s": 54252,
"text": "You want to increase the size of memory pointed to by ptr from 10 to 20, without loosing the contents of already allocated memory. In this case you can call the realloc function. Signature of realloc is:"
},
{
"code": null,
"e": 54495,
"s": 54456,
"text": "void *realloc(void *ptr, size_t size);"
},
{
"code": null,
"e": 54605,
"s": 54495,
"text": "malloc() allocates memory block of given size (in bytes) and returns a pointer to the beginning of the block."
},
{
"code": null,
"e": 54635,
"s": 54605,
"text": "void * malloc( size_t size );"
},
{
"code": null,
"e": 54687,
"s": 54637,
"text": "malloc() doesn’t initialize the allocated memory."
},
{
"code": null,
"e": 54768,
"s": 54687,
"text": "calloc() allocates the memory and also initializes the allocates memory to zero."
},
{
"code": null,
"e": 54810,
"s": 54768,
"text": "void * calloc( size_t num, size_t size );"
},
{
"code": null,
"e": 54899,
"s": 54810,
"text": "calloc() takes two arguments: 1) number of blocks to be allocated 2) size of each block."
},
{
"code": null,
"e": 54985,
"s": 54899,
"text": "We can achieve same functionality as calloc() by using malloc() followed by memset(),"
},
{
"code": null,
"e": 55005,
"s": 54985,
"text": "ptr = malloc(size);"
},
{
"code": null,
"e": 55027,
"s": 55005,
"text": "memset(ptr, 0, size);"
},
{
"code": null,
"e": 55252,
"s": 55027,
"text": "he Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower and sometimes pluralized) is a mathematical game or puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod."
},
{
"code": null,
"e": 55360,
"s": 55252,
"text": "The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:"
},
{
"code": null,
"e": 55624,
"s": 55360,
"text": "\nOnly one disk can be moved at a time.\nEach move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.\nNo disk may be placed on top of a smaller disk.\n"
},
{
"code": null,
"e": 55662,
"s": 55624,
"text": "Only one disk can be moved at a time."
},
{
"code": null,
"e": 55838,
"s": 55662,
"text": "Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack."
},
{
"code": null,
"e": 55886,
"s": 55838,
"text": "No disk may be placed on top of a smaller disk."
},
{
"code": null,
"e": 56051,
"s": 55886,
"text": "With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2^n − 1, where n is the number of disks."
},
{
"code": null,
"e": 56125,
"s": 56051,
"text": "for detail refers :http://www.geeksforgeeks.org/iterative-tower-of-hanoi/"
},
{
"code": null,
"e": 56553,
"s": 56125,
"text": "Function to insert node in the beginning of the List,\nstruct Node *addBegin(struct Node *last, int data)\n{\n if (last == NULL)\n return addToEmpty(last, data);\n \n // Creating a node dynamically.\n struct Node *temp\n = (struct Node *)malloc(sizeof(struct Node));\n \n // Assigning the data.\n temp -> data = data;\n \n // Adjusting the links.\n temp -> next = last -> next;\n last -> next = temp;\n \n return last;\n}"
},
{
"code": null,
"e": 56640,
"s": 56553,
"text": "for detail refers :http://www.geeksforgeeks.org/circular-singly-linked-list-insertion/"
},
{
"code": null,
"e": 56931,
"s": 56640,
"text": "Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates.Other way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield."
},
{
"code": null,
"e": 57002,
"s": 56931,
"text": "for detail refers :http://www.geeksforgeeks.org/encapsulation-in-java/"
},
{
"code": null,
"e": 57123,
"s": 57002,
"text": "Static binding is being used for overloaded methods and dynamic binding is being used for overridden/overriding methods."
},
{
"code": null,
"e": 57319,
"s": 57123,
"text": "Method overloading is used to increase the readability of the program.\n\tMethod overriding is used to provide the specific implementation of the method that is already provided by its super class."
},
{
"code": null,
"e": 57436,
"s": 57319,
"text": "Argument list should be different while doing method overloading. Argument list should be same in method Overriding."
},
{
"code": null,
"e": 57617,
"s": 57436,
"text": "In Method Overloading, methods have same name different signatures but in the same class.In Method Overriding, methods have same name and same signature but in the different class."
},
{
"code": null,
"e": 57727,
"s": 57617,
"text": "It may or may not need inheritance in Method Overloading.It always requires inheritance in Method Overriding."
},
{
"code": null,
"e": 58049,
"s": 57727,
"text": " A memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. In object-oriented programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code."
},
{
"code": null,
"e": 58135,
"s": 58049,
"text": "for detail refers :http://www.geeksforgeeks.org/what-is-memory-leak-how-can-we-avoid/"
},
{
"code": null,
"e": 58445,
"s": 58135,
"text": "Python provides a lot of inbuilt functionality and is a very powerful language. It is more closer to the English language as compared to most other languages. Therefore it becomes easier to focus more on the logic of the program rather than the syntax ( especially if it is the first language that you learn )"
},
{
"code": null,
"e": 58589,
"s": 58445,
"text": "Python works with the very little code the way most common “use cases” require, reserving lengthy explicit coding for outliers and exceptions ."
},
{
"code": null,
"e": 58733,
"s": 58589,
"text": "Python is highly approachable by complete beginners, and yet still powerful enough for pros to use as “shortcut-glue” in enterprise-class apps."
},
{
"code": null,
"e": 58956,
"s": 58733,
"text": "We can execute a stored procedure whenever we want with the help of the exec command, but a trigger can only be executed whenever an event (insert, delete, and update) is fired on the table on which the trigger is defined."
},
{
"code": null,
"e": 59029,
"s": 58956,
"text": "Stored procedures can return values but a trigger cannot return a value."
},
{
"code": null,
"e": 59170,
"s": 59029,
"text": "We can call a stored procedure from the front end (.asp files, .aspx files, .ascx files, etc.) but we can't call a trigger from these files."
},
{
"code": null,
"e": 59266,
"s": 59170,
"text": "Stored procedure can take input parameters, but we can't pass parameters as input to a trigger."
},
{
"code": null,
"e": 59941,
"s": 59266,
"text": "All the objects which are created dynamically (using new in C++ and Java) are allocated memory in the heap. If we go on creating objects we might get Out Of Memory error, since it is not possible to allocate heap memory to objects. So we need to clear heap memory by releasing memory for all those objects which are no longer referenced by the program (or the unreachable objects) so that the space is made available for subsequent new objects. This memory can be released by the programmer itself but it seems to be an overhead for the programmer, here garbage collection comes to our rescue, and it automatically releases the heap memory for all the unreferenced objects ."
},
{
"code": null,
"e": 60034,
"s": 59941,
"text": "for detail refers :http://www.geeksforgeeks.org/mark-and-sweep-garbage-collection-algorithm/"
},
{
"code": null,
"e": 60294,
"s": 60034,
"text": "“Garbage Collection” as the name suggests is used to remove the objects that are no longer needed by the Java application. The Java Garbage Collector will identify those objects and remove those from the memory thereby freeing the memory for the new objects ."
},
{
"code": null,
"e": 60367,
"s": 60294,
"text": "for detail refers :http://www.geeksforgeeks.org/garbage-collection-java/"
},
{
"code": null,
"e": 60776,
"s": 60367,
"text": "binary search trees (BST), sometimes called orderedor sorted binary trees, are a particular type of container: data structures that store \"items\" (such as numbers, names etc.) in memory. They allow fast lookup, addition and removal of items, and can be used to implement either dynamic sets of items, or lookup tables that allow finding an item by its key(e.g., finding the phone number of a person by name)."
},
{
"code": null,
"e": 60786,
"s": 60776,
"text": "Example :"
},
{
"code": null,
"e": 60881,
"s": 60786,
"text": "for detail refers :http://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/"
},
{
"code": null,
"e": 61146,
"s": 60881,
"text": "A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed \"abstract\" and they cannot be instantiated directly."
},
{
"code": null,
"e": 61239,
"s": 61146,
"text": "for detail refers :http://www.geeksforgeeks.org/pure-virtual-functions-and-abstract-classes/"
},
{
"code": null,
"e": 61509,
"s": 61239,
"text": "Abstract classes are classes that contain one or more abstract methods. Anabstract method is a method that is declared, but contains no implementation.Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods ."
},
{
"code": null,
"e": 61583,
"s": 61509,
"text": "for detail refers :http://www.geeksforgeeks.org/abstract-classes-in-java/"
},
{
"code": null,
"e": 61800,
"s": 61583,
"text": " Exit controlled loop - The loop which keeps on executing until a particular condition is satisfied and when the condition is satisfied according to the criteria the loop exits, this is known as exit controlled loop."
},
{
"code": null,
"e": 61804,
"s": 61800,
"text": "EX-"
},
{
"code": null,
"e": 61834,
"s": 61804,
"text": "\nWhile loop (during polling)\n"
},
{
"code": null,
"e": 61862,
"s": 61834,
"text": "While loop (during polling)"
},
{
"code": null,
"e": 62024,
"s": 61862,
"text": " The loop which has a condition check at the entrance of the loop, the loop executes only and only if the condition is satisfied is called as entry control loop."
},
{
"code": null,
"e": 62028,
"s": 62024,
"text": "EX-"
},
{
"code": null,
"e": 62050,
"s": 62028,
"text": "\nwhile loop\nFor loop\n"
},
{
"code": null,
"e": 62061,
"s": 62050,
"text": "while loop"
},
{
"code": null,
"e": 62070,
"s": 62061,
"text": "For loop"
},
{
"code": null,
"e": 62316,
"s": 62070,
"text": "Solution to the problem of external fragmentation is compaction. The process is to shuffle the memory contents so that all free memory is placed together in one large block. It is only possible if relocation is dynamic and done only at run time."
},
{
"code": null,
"e": 62347,
"s": 62316,
"text": "Example:Compaction Algorithm ."
},
{
"code": null,
"e": 62586,
"s": 62347,
"text": "External fragmentation arises when free memory is separated into small blocks and is interspersed by allocated memory. It is a weakness of certain storage allocation algorithms, when they fail to order memory used by programs efficiently."
},
{
"code": null,
"e": 62894,
"s": 62586,
"text": "For example, consider a situation wherein a program allocates 3 continuous blocks of memory and then frees the middle block. The memory allocator can use this free block of memory for future allocations. However, it cannot use this block if the memory to be allocated is larger in size than this free block."
},
{
"code": null,
"e": 63169,
"s": 62894,
"text": "External fragmentation also occurs in file systems as many files of different sizes are created, change size, and are deleted. The effect is even worse if a file which is divided into many small pieces is deleted, because this leaves similarly small regions of free spaces ."
},
{
"code": null,
"e": 63450,
"s": 63169,
"text": "Internal fragmentation is the space wasted inside of allocated memory blocks because of restriction on the allowed sizes of allocated blocks.Allocated memory may be slightly larger than requested memory; this size difference is memory internal to a partition, but not being used ."
},
{
"code": null,
"e": 63768,
"s": 63450,
"text": " For example, memory can only be provided to programs in chunks divisible by 4, 8 or 16, and as a result if a program requests perhaps 23 bytes, it will actually get a chunk of 32 bytes. When this happens, the excess memory goes to waste. In this scenario, the unusable memory is contained within an allocated region."
},
{
"code": null,
"e": 63900,
"s": 63768,
"text": "The degree of multiprogramming describes the maximum number of processes that a single-processor system can accommodate efficiently"
},
{
"code": null,
"e": 64035,
"s": 63900,
"text": " The primary factor affecting the degree of multiprogramming is the amount of memory available to be allocated to executing processes."
},
{
"code": null,
"e": 64281,
"s": 64037,
"text": "The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called."
},
{
"code": null,
"e": 64293,
"s": 64281,
"text": "Advantages "
},
{
"code": null,
"e": 64332,
"s": 64293,
"text": " Function call overhead doesn’t occur."
},
{
"code": null,
"e": 64420,
"s": 64332,
"text": " It also saves the overhead of push/pop variables on the stack when function is called."
},
{
"code": null,
"e": 64478,
"s": 64420,
"text": " It also saves overhead of a return call from a function."
},
{
"code": null,
"e": 64544,
"s": 64478,
"text": "detail refers :http://www.geeksforgeeks.org/inline-functions-cpp/"
},
{
"code": null,
"e": 64819,
"s": 64546,
"text": "A signal as referred to in communication systems, signal processing, and electrical engineering is a function that \"conveys information about the behavior or attributes of some phenomenon\".The simplest form of signal is a direct current (DC) that is switched on and off . "
},
{
"code": null,
"e": 65138,
"s": 64819,
"text": "The keyword ‘register’ instructs the compiler to persist the variable that is being declared , in a CPU register.\n\nEx: register int number;\n\nThe persistence of register variables in CPU register is to optimize the access. Even the optimization is turned off; the register variables are forced to store in CPU register."
},
{
"code": null,
"e": 65212,
"s": 65138,
"text": "Read more on http://www.geeksforgeeks.org/understanding-register-keyword/"
},
{
"code": null,
"e": 65843,
"s": 65212,
"text": "Huge pointer is the pointer that can point to the whole memory of the RAM and that can access all the segments that are present in a program. The normalization can be done depending on the microprocessor of the system. The physical memory of the system is represented in 20 bit and then there is a conversion of 4 byte or 32 bit address. The increment of the huge pointer will also affect the offset and segment address. Through the huge pointer the access and modification of device driver memory, video memory, etc. Huge pointer manages the overall system of the memory model and also normalizes the overall use of the pointers."
},
{
"code": null,
"e": 66071,
"s": 65843,
"text": "Invalid pointer arithmetic include:\n\n(i) Adding, dividing and multiplying two pointers \n(ii) Adding double or float to pointer \n(iii) Masking or shifting pointer \n(iv) Assigning a pointer of one type to another type of pointer."
},
{
"code": null,
"e": 66151,
"s": 66071,
"text": " ftell() function is used to get the current file referred by the file pointer."
},
{
"code": null,
"e": 66267,
"s": 66151,
"text": " ftell(fp); returns a long integer value referring the current location of the file pointed by the file pointer fp."
},
{
"code": null,
"e": 66308,
"s": 66267,
"text": " If there's an error, it will return -1."
},
{
"code": null,
"e": 66532,
"s": 66308,
"text": "\"Far\" and \"Near\" - non-standard qualifiers available in x86 systems only.\n\nNear pointer - Refers to an address in known segment only. \n\nFar pointer - Compound value containing a segment number and offset into that segment ."
},
{
"code": null,
"e": 66943,
"s": 66532,
"text": "There is nothing like total generic pointer type, only void* holds the object (i.e. data) pointers. Converting function pointer to type void* is not a portable and it is not appropriate to convert it also. You can use any function type like int*() or void*(), these pointers can be treated as a generic function pointer. The best way to have the portability, is to use void* and a generic pointer combination. "
},
{
"code": null,
"e": 67506,
"s": 66943,
"text": "- The terminate() is a library function which by default aborts the program.\n- It is called whenever the exception handling mechanism cannot find a handler for a thrown exception.\n- The unexpected() is called when a function with an exception specification throws an exception of a type that is not listed in the exception specification for the function\n- A function declaration without a specification like throw(char*) may throw any type of exception, and one with throw() is not allowed to throw exceptions at all.\n- By default unexpected() calls terminate()."
},
{
"code": null,
"e": 68195,
"s": 67506,
"text": "Model transformations involve multiple models that are used to define different views of a system. It provides different level of granularity that it doesn’t use either the top-down approach or the bottom-up approach to implement the basic functionality of the system. It is used to integrate the library components used that involves the iteration of the model that needs to be constructed. It also involves the analysis of the model so that the process can be made automated by using the construction tools. The compilation made the progress by improving the code that is written in high level language and the code generator produce the code that is required for the machine language ."
},
{
"code": null,
"e": 68274,
"s": 68195,
"text": " Prototype of the function used to create a child process is pid_t fork(void);"
},
{
"code": null,
"e": 68396,
"s": 68274,
"text": " Fork is the system call that is used to create a child process. It takes no arguments and returns a value of type pid_t."
},
{
"code": null,
"e": 68552,
"s": 68396,
"text": " If the function succeeds it returns the pid of the child process created to its parent and child receives a zero value indicating its successful creation."
},
{
"code": null,
"e": 68669,
"s": 68552,
"text": " On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set."
},
{
"code": null,
"e": 68911,
"s": 68669,
"text": "- The child process normally performs all its operations in its parents context but each process independently of one nother and also inherits some of the important attributes from it such as UID, current directory, root directory and so on."
},
{
"code": null,
"e": 69714,
"s": 68911,
"text": "Critical section allows the process to run in an area that is defined by that process only. It is a sequence of instructions that can be corrupted if any other process tries to interrupt it. This process allow the operating system to give the synchronization objects that are used to monitor the processes that are up and running so that no other process will get executed till the critical region consists of a process that is already running. The example includes removal of the data from a queue running in a critical section and if not protected then it can be interrupted and the data have chances of getting corrupted. The processes exit from the critical section as soon as they finish the execution so that the chances can be given to other processes that are waiting for their chance to come ."
},
{
"code": null,
"e": 70054,
"s": 69714,
"text": "- Damage of memory devices due to transient current and static discharges.\n- Malfunctioning of address lines due to a short in the circuit.\n- Malfunctioning of Data lines.\n- Some memory locations being inaccessible in storage due to garbage or errors.\n- Improper insertion of Memory devices into the memory slots.\n- Faulty control signals."
},
{
"code": null,
"e": 70161,
"s": 70054,
"text": " Direct memory access is mainly used to overcome the disadvantages of interrupt and progam controlled I/O."
},
{
"code": null,
"e": 70397,
"s": 70161,
"text": " DMA modules usually take the control over from the processor and perform the memory operations and this is mainly because to counteract the mismatch in the processing speeds of I/O units and the procesor. This is comparatively faster."
},
{
"code": null,
"e": 70561,
"s": 70397,
"text": " It is an important part of any embedded systems,and the reason for their use is that they can be used for bursty data transfers instead of single byte approaches."
},
{
"code": null,
"e": 70666,
"s": 70561,
"text": " It has to wait for the systems resources such as the system bus in case it is already in control of it."
},
{
"code": null,
"e": 71181,
"s": 70666,
"text": "Cloud computing consists of 3 layers in the hierarchy and these are as follows:\n1. Infrastructure as a Service (IaaS) provides cloud infrastructure in terms of hardware like memory, processor speed etc. \n2. Platform as a Service (PaaS) provides cloud application platform for the developers. \n3. Software as a Service (SaaS) provides cloud applications which are used by the user directly without installing anything on the system. The application remains on the cloud and it can be saved and edited in there only."
},
{
"code": null,
"e": 71505,
"s": 71181,
"text": "Cloud computing is a metaphor used for internet. It provides on-demand access to virtualized IT resources that can be shared by others or subscribed by you. It provides an easy way to provide configurable resources by taking it from a shared pool. The pool consists of networks, servers, storage, applications and services."
},
{
"code": null,
"e": 71959,
"s": 71505,
"text": "Utility computing allow the user to pay per use means whatever they are using only for that they have to pay. It is a plug in that needs to be managed by the organizations on deciding what type of services has to be deployed from the cloud. Utility computing allows the user to think and implement the services according to them. Most organizations go for hybrid strategy that combines internal delivered services that are hosted or outsourced services."
},
{
"code": null,
"e": 72241,
"s": 71959,
"text": "VPN stands for virtual private network; it is a private cloud which manages the security of the data during the transport in the cloud environment. VPN allows an organization to make a public network as private network and use it to transfer files and other resources on a network."
},
{
"code": null,
"e": 72764,
"s": 72241,
"text": "Cloud computing provides the services to the organizations so they can run their applications and install them on the cloud. Virtualization is used to deploy the cloud computing models as it provides a hidden layer between the user and the physical layer of the system. The cloud services are measured in terms of use. Pay as much as you use that can be on the basis of hours or months or years. Cloud services allow users to pay for only what they use and according to the demand the charges or the prices gets increased."
},
{
"code": null,
"e": 72859,
"s": 72764,
"text": "- Table Scan - Iterating over the table rows .\n- Index Scan - Iterating over the index items ."
},
{
"code": null,
"e": 73210,
"s": 72859,
"text": " During the process of distributed deadlock detection, sometime a delay occurs while propagating local information and this leads to deadlock detection algorithms pointing to deadlocks that do not actually occur. \n- These deadlocks are referred to as phantom deadlocks, as they do not really exist. \n- Phantom deadlock lead to unnecessary abortions. "
},
{
"code": null,
"e": 73383,
"s": 73210,
"text": "- Materialized views are disk based views. \n- Materialized views get updated periodically based on the interval specified in the query.\n- Materialized views can be indexed."
},
{
"code": null,
"e": 73795,
"s": 73383,
"text": "Clustered Index - \n\n- A clustered index reorders the way records in the table are physically stored. \n- There can be only one clustered index per table. \n- It makes data retrieval faster.\n\nNon-clustered Index\n\n- A non-clustered index does not make any changes to the way the records were stored but creates a completely separate object inside the table. \n- This makes the insert and update command work faster ."
},
{
"code": null,
"e": 74116,
"s": 73795,
"text": "Database partitioning refers to dividing the large database into small logical units. It helps in improving the management, availability & performance of the system. \n\nThe advantages of database partitioning are: \n\ni.) It improves and speeds up the performance of queries \nii.) You can easily bigger parts of a partition"
},
{
"code": null,
"e": 74765,
"s": 74116,
"text": "There are various translation phases that can be used in C language. These are as follows:\na) The first stage of the translation phase is to check the tri-graph and allow it to be used with the system.\nb) The second stage is to identify the type of program that has to be written for that, the identification of identifiers and others are figured out. \nc) The third stage is the important stage where the translation from comments to the space takes place. The space is not being seen in the case of strings or character constant. And multiple white spaces may be combined in one.\nd) The last stage involves the complete translation of the program."
},
{
"code": null,
"e": 74916,
"s": 74765,
"text": "Volatile variables are like other variables except that the values might be changed at any given point of time only by ‘some external resources’.\n\nEx:"
},
{
"code": null,
"e": 74937,
"s": 74916,
"text": "volatile int number;"
},
{
"code": null,
"e": 75117,
"s": 74937,
"text": "\nThe value may be altered by some external factor, though if it does not appear to the left of the assignment statement. The compiler will keep track of these volatile variables ."
},
{
"code": null,
"e": 75343,
"s": 75117,
"text": "- #include<...> means that the directories other than the current one will be searched for the header file. \n- #include \"...\" means that the current directory will be searched for the header file before any other directories."
},
{
"code": null,
"e": 75438,
"s": 75343,
"text": " Enumerated types allow the programmers to use more meaningful words as values to a variable. "
},
{
"code": null,
"e": 75636,
"s": 75438,
"text": " Each item in the enumerated type variable is actually associated with a numeric code. For an enumerated type variable named Months can be created. Its values can be January, February,....December."
},
{
"code": null,
"e": 75699,
"s": 75636,
"text": " Both functions accept a character input value from the user. "
},
{
"code": null,
"e": 75836,
"s": 75699,
"text": " When getch() is used, the key that was pressed will not appear on the screen. It is automatically captured and assigned to a variable. "
},
{
"code": null,
"e": 75956,
"s": 75836,
"text": " While when getche() is used, the key that was pressed by the user appears on the screen and is assigned to a variable."
},
{
"code": null,
"e": 76042,
"s": 75956,
"text": "for detail refers :http://www.geeksforgeeks.org/difference-getchar-getch-getc-getche/"
},
{
"code": null,
"e": 76104,
"s": 76042,
"text": " It is done for parsing process and compilation of the code. "
},
{
"code": null,
"e": 76276,
"s": 76104,
"text": " A semicolon acts as a delimiter. This tells the compiler where each statement ends, and can proceed to divide the statement into smaller elements for checking the syntax."
},
{
"code": null,
"e": 76340,
"s": 76276,
"text": " A newline escape sequence is represented by the \\n character. "
},
{
"code": null,
"e": 76408,
"s": 76340,
"text": " It is used to insert a new line while displaying the output data. "
},
{
"code": null,
"e": 76459,
"s": 76408,
"text": "To add more spaces you can use more \\n characters."
},
{
"code": null,
"e": 76562,
"s": 76459,
"text": "Spaghetti programming refers to codes that tend to get tangled and overlapped throughout the program. "
},
{
"code": null,
"e": 76707,
"s": 76562,
"text": " It makes a program complex and analyzing the code becomes difficult. It usually happens due to the lack of work experience on developer's part."
},
{
"code": null,
"e": 76759,
"s": 76707,
"text": "for detail :http://www.geeksforgeeks.org/g-fact-87/"
},
{
"code": null,
"e": 76907,
"s": 76759,
"text": "Declaring all header files in every program would lead to increase in the overall file size and load of the program. It is not a good programming. "
},
{
"code": null,
"e": 77149,
"s": 76907,
"text": "The choice of header files that you want to declare in the program depends on the commands/functions you want to use in the program. Each header file contains different commands and functions. So we use only the files relevant to our program"
},
{
"code": null,
"e": 77554,
"s": 77149,
"text": "- While writing programs that store and retrieve data in a file, it is possible to designate that file into different forms. \n- A sequential access file is such that data are saved in sequential order: one data is placed into the file after another. \n- If you want to access a particular data within the sequential access file, data has to be read - one data at a time, until you reach the data you want."
},
{
"code": null,
"e": 77993,
"s": 77554,
"text": "- JAXM messaging models has two types of messaging model, synchronous and asynchronous.\n\n1. Synchronous messaging model :\n\n- In this type of model, client directly interacts with the source. The client sends a request and waits for the response.\n\n2. Asynchronous messaging model :\n\n- In this model, client sends message to the messaging provider and returns back. Messaging provider then performs the routing of message to the end source."
},
{
"code": null,
"e": 78308,
"s": 77993,
"text": "- JAX-RPC uses SOAP to call remote procedures.\n- It enables JAX-RPC clients to invoke web services developed across heterogeneous platform.\n- It is an Application Program Interface(API).\n- It is easier for the web services to call other applications.\n- It provides a programming model for the development of SOAP ."
},
{
"code": null,
"e": 78639,
"s": 78308,
"text": "- It is the service called as distributed lock manager.\n- In cluster systems to avoid file sharing the distributed systems must provide the access control and file locking.\n- This ensures that no conflicting operations occur in the system.\n- Here the distributed file systems are not general purpose therefore it requires locking."
},
{
"code": null,
"e": 78970,
"s": 78641,
"text": "- These systems are also called as the distributed systems.\n- It consist of collection of processors that do not share memory or clock.\n- The processors communicate through high speed buses or telephone lines.\n- It can be a centralized system where the server responds to client requests.\n- It can also be a peer to peer system."
},
{
"code": null,
"e": 79326,
"s": 78970,
"text": "- It is the ability to continue providing service proportional to level of hardware.\n- Systems designed for graceful degradation are called fault tolerant.\n- If we have several processors connected together, then failure of one would not stop the system.\n- Then the entire system runs only 10% slower.\n- This leads to increased reliability of the system ."
},
{
"code": null,
"e": 80869,
"s": 79326,
"text": "The VFS layer also known as the virtual file system functions in many ways similar to object oriented programming techniques. It acts like an abstraction layer on top of a more specific file system. The VFS layer enables the OS to make system calls independent of the file system type used. Any file system that is used gives its function calls used and the data structures to the layer of VFS. The VFS layer translates a system call into the correct specific functions for the targeted file system. The program that is used for calling does not have a file system specific code also the system call structures used in upper levels are file system independent. The VFS layer translation translates the non-file system specific calls into a file system specific operation.The VFS layer also known as the virtual file system functions in many ways similar to object oriented programming techniques. It acts like an abstraction layer on top of a more specific file system. The VFS layer enables the OS to make system calls independent of the file system type used. Any file system that is used gives its function calls used and the data structures to the layer of VFS. The VFS layer translates a system call into the correct specific functions for the targeted file system. The program that is used for calling does not have a file system specific code also the system call structures used in upper levels are file system independent. The VFS layer translation translates the non-file system specific calls into a file system specific operation."
},
{
"code": null,
"e": 81659,
"s": 80869,
"text": "The Belady's anomaly is a situation in which the number of page faults increases when additional physical memory is added to a system. This anomaly arises in some algorithms that implement virtual memory. The virtual memory allows programs larger than the physical memory space to execute. An algorithm suffers from this problem when it cannot guarantee that a page will be kept when a small number of frames are available. An optimal algorithm would not suffer from this problem as it replaces the page not to be used for the longest time. The anomaly occurs when the page replacement algorithm will remove a page that will be needed in the immediate future. An optimal algorithm will not select such a page that will be required immediately. This anomaly is also stated to be unbounded ."
},
{
"code": null,
"e": 81938,
"s": 81659,
"text": "Read - write locks provide simultaneous read access to many threads while the write access stays with one thread at a time. They are especially useful in protecting the data that is not frequently written but read simultaneously by many threads. \n- They are slower than mutexes."
},
{
"code": null,
"e": 82055,
"s": 81938,
"text": "for detail :http://www.geeksforgeeks.org/readers-writers-problem-set-1-introduction-and-readers-preference-solution/"
},
{
"code": null,
"e": 82567,
"s": 82055,
"text": "- A traditional pipe is unnamed and can be used only for the communication of related process. If unrelated processes are required to communicate - named pipes are required. \n- It is a pipe whose access point is a file available on the file system. When this file is opened for reading, a process is granted access to the reading end of the pipe. Similarly, when the file is opened for writing, the process is granted access to writing end of the pipe. \n- A named pipe is also referred to as FIFO or named FIFO."
},
{
"code": null,
"e": 82931,
"s": 82567,
"text": "- Kernel is the part of OS which handles all details of sharing resources and device handling. \n- It can be considered as the core of OS which manages the core features of an OS. \n- Its purpose is to handle the communication between software and hardware \n- Its services are used through system calls. \n- A layer of software called shell wraps around the Kernel ."
},
{
"code": null,
"e": 83218,
"s": 82931,
"text": "LEFT JOIN: This join returns all the rows of the table on the left side of the join and matching rows for the table on the right side of join. The rows for which there is no matching row on right side, the result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.Syntax:"
},
{
"code": null,
"e": 83453,
"s": 83218,
"text": "SELECT table1.column1,table1.column2,table2.column1,....\nFROM table1 \nLEFT JOIN table2\nON table1.matching_column = table2.matching_column;\n\n\ntable1: First table.\ntable2: Second table\nmatching_column: Column common to both the tables ."
},
{
"code": null,
"e": 83549,
"s": 83453,
"text": "for detail refers :http://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/"
},
{
"code": null,
"e": 83874,
"s": 83549,
"text": "RIGHT JOIN: RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join and matching rows for the table on the left side of join. The rows for which there is no matching row on left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.Syntax:"
},
{
"code": null,
"e": 84110,
"s": 83874,
"text": "SELECT table1.column1,table1.column2,table2.column1,....\nFROM table1 \nRIGHT JOIN table2\nON table1.matching_column = table2.matching_column;\n\n\ntable1: First table.\ntable2: Second table\nmatching_column: Column common to both the tables ."
},
{
"code": null,
"e": 84206,
"s": 84110,
"text": "for detail refers :http://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/"
},
{
"code": null,
"e": 84456,
"s": 84206,
"text": "FULL JOIN: FULL JOIN creates the result-set by combining result of both LEFT JOIN and RIGHT JOIN. The result-set will contain all the rows from both the tables. The rows for which there is no matching, the result-set will contain NULL values.Syntax:"
},
{
"code": null,
"e": 84779,
"s": 84456,
"text": "SELECT table1.column1,table1.column2,table2.column1,....\nFROM table1 \nFULL JOIN table2\nON table1.matching_column = table2.matching_column;\nfor detail :http://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/\n\n\ntable1: First table.\ntable2: Second table\nmatching_column: Column common to both the tables."
},
{
"code": null,
"e": 85053,
"s": 84779,
"text": "INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as long as the condition satisfies. This keyword will create the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be same.\nSyntax:"
},
{
"code": null,
"e": 85290,
"s": 85055,
"text": "SELECT table1.column1,table1.column2,table2.column1,....\nFROM table1 \nINNER JOIN table2\nON table1.matching_column = table2.matching_column;\n\n\ntable1: First table.\ntable2: Second table\nmatching_column: Column common to both the tables."
},
{
"code": null,
"e": 85385,
"s": 85290,
"text": "for detail refer :http://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/"
},
{
"code": null,
"e": 85463,
"s": 85385,
"text": "You can configure whether and how sessions use cookies in the following ways:"
},
{
"code": null,
"e": 85536,
"s": 85465,
"text": "You can configure the session-properties for the entire web container:"
},
{
"code": null,
"e": 85774,
"s": 85538,
"text": "To use the Administration interface, select Containers and then Web Container under your server instance. Then click on the Properties button under Session Configuration Properties. After editing the properties, click on OK, then Save."
},
{
"code": null,
"e": 86023,
"s": 85776,
"text": "You can also edit the session-properties element in the server.xml file, which is the same as the corresponding element in the sun-web.xml file. For details, see the Sun Java System Application Server Administrator’s Configuration File Reference."
},
{
"code": null,
"e": 86154,
"s": 86023,
"text": "You can configure the session-properties and cookie-properties elements in the sun-web.xml file for an individual web application."
},
{
"code": null,
"e": 86430,
"s": 86154,
"text": "A cookie (called an Internet or Web cookie) is the term given to describe a type of message that is given to a Web browser by a Web server. The main purpose of a cookie is to identify users and possibly prepare customized Web pages or to save site login information for you."
},
{
"code": null,
"e": 86899,
"s": 86430,
"text": "When you enter a Web site using cookies, you may be asked to fill out a form providing personal information; like your name, e-mail address, and interests. This information is packaged into a cookie and sent to your Web browser, which then stores the information for later use. The next time you go to the same Web site, your browser will send the cookie to the Web server. The message is sent back to the server each time the browser requests a page from the server ."
},
{
"code": null,
"e": 87177,
"s": 86899,
"text": "Phrase level error recovery is implemented by filling in the blank entries in the predictive parsing table with pointers to error routines. These routines may change, insert, or delete symbols on the input and issue appropriate error messages. They may also pop from the stack."
},
{
"code": null,
"e": 87397,
"s": 87177,
"text": "A handle of a string is a substring that matches the right side of a production, and whose reduction to the nonterminal on the left side of the production represents one step along the reverse of a rightmost derivation."
},
{
"code": null,
"e": 87689,
"s": 87397,
"text": "A handle of a right – sentential form γ is a production A→β and a position of γ where the string β may be found and replaced by A to produce the previous right-sentential form in a rightmost derivation of γ. That is , if S =>αAw =>αβw,then A→β in the position following α is a handle of αβw."
},
{
"code": null,
"e": 87754,
"s": 87689,
"text": "· Tokens- Sequence of characters that have a collective meaning."
},
{
"code": null,
"e": 87939,
"s": 87754,
"text": "· Patterns- There is a set of strings in the input for which the same token is produced as output. This set of strings is described by a rule called a pattern associated with the token"
},
{
"code": null,
"e": 88040,
"s": 87939,
"text": "· Lexeme- A sequence of characters in the source program that is matched by the pattern for a token."
},
{
"code": null,
"e": 88097,
"s": 88040,
"text": "Analysis and Synthesis are the two parts of compilation."
},
{
"code": null,
"e": 88234,
"s": 88097,
"text": "The analysis part breaks up the source program into constituent pieces and creates an intermediate representation of the source program."
},
{
"code": null,
"e": 88329,
"s": 88234,
"text": "The synthesis part constructs the desired target program from the intermediate representation."
},
{
"code": null,
"e": 88584,
"s": 88329,
"text": "A compiler is a program that reads a program written in one language –the source language and translates it into an equivalent program in another language-the target language. The compiler reports to its user the presence of errors in the source program."
},
{
"code": null,
"e": 88926,
"s": 88584,
"text": "Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack, the only element that can be removed is the element that was at the top of the stack, just like a pile of objects."
},
{
"code": null,
"e": 88950,
"s": 88926,
"text": "Basic features of Stack"
},
{
"code": null,
"e": 89370,
"s": 88950,
"text": "\nStack is an ordered list of similar data type.\nStack is a LIFO structure. (Last in First out).\npush() function is used to insert new elements into the Stack and pop() is used to delete an element from the stack. Both insertion and deletion are allowed at only one end of Stack called Top.\nStack is said to be in Overflow state when it is completely full and is said to be in Underflow state if it is completely empty.\n"
},
{
"code": null,
"e": 89417,
"s": 89370,
"text": "Stack is an ordered list of similar data type."
},
{
"code": null,
"e": 89465,
"s": 89417,
"text": "Stack is a LIFO structure. (Last in First out)."
},
{
"code": null,
"e": 89659,
"s": 89465,
"text": "push() function is used to insert new elements into the Stack and pop() is used to delete an element from the stack. Both insertion and deletion are allowed at only one end of Stack called Top."
},
{
"code": null,
"e": 89788,
"s": 89659,
"text": "Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state if it is completely empty."
},
{
"code": null,
"e": 89857,
"s": 89788,
"text": "for detail refer :http://www.geeksforgeeks.org/stack-data-structure/"
},
{
"code": null,
"e": 89894,
"s": 89857,
"text": "Polish and Reverse Polish notations."
},
{
"code": null,
"e": 89920,
"s": 89894,
"text": "Operating System | Paging"
},
{
"code": null,
"e": 90112,
"s": 89920,
"text": "Paging is a memory management scheme that eliminates the need for contiguous allocation of physical memory. This scheme permits the physical address space of a process to be non – contiguous."
},
{
"code": null,
"e": 90202,
"s": 90112,
"text": "Logical Address or Virtual Address (represented in bits): An address generated by the CPU"
},
{
"code": null,
"e": 90338,
"s": 90202,
"text": "Logical Address Space or Virtual Address Space( represented in words or bytes): The set of all logical addresses generated by a program"
},
{
"code": null,
"e": 90423,
"s": 90338,
"text": "Physical Address (represented in bits): An address actually available on memory unit"
},
{
"code": null,
"e": 90554,
"s": 90423,
"text": "Physical Address Space (represented in words or bytes): The set of all physical addresses corresponding to the logical addresses ."
},
{
"code": null,
"e": 90620,
"s": 90554,
"text": "for detail :http://www.geeksforgeeks.org/operating-system-paging/"
},
{
"code": null,
"e": 90893,
"s": 90620,
"text": "Network security combines multiple layers of defenses at the edge and in the network. Each network security layer implements policies and controls. Authorized users gain access to network resources, but malicious actors are blocked from carrying out exploits and threats ."
},
{
"code": null,
"e": 91135,
"s": 90893,
"text": "HTTP is Hyper Text Transfer protocol that is used in networking. Whenever basically you type a website in the browser, its is this protocol which by default listens at port 80 on server side and helps you to see the webpage on your machine. "
},
{
"code": null,
"e": 91331,
"s": 91135,
"text": "HTTPS : This is Hyper text Transfer protocol with added security layer in place in form on TLS/SSL. Servers and clients communicate with each other exactly same as HTTP but over a secure channel."
},
{
"code": null,
"e": 91364,
"s": 91331,
"text": "HTTP URL begins with “http://” ."
},
{
"code": null,
"e": 91399,
"s": 91364,
"text": "HTTPS URL begins with “https://” ."
},
{
"code": null,
"e": 91446,
"s": 91399,
"text": "HTTP Operate in Operates at Application Layer."
},
{
"code": null,
"e": 91482,
"s": 91446,
"text": "HTTPS Operates at Transport Layer ."
},
{
"code": null,
"e": 91514,
"s": 91482,
"text": "HTTP No certificates required ."
},
{
"code": null,
"e": 91545,
"s": 91514,
"text": "HTTPs certificates required ."
},
{
"code": null,
"e": 91839,
"s": 91545,
"text": "he automotive differential is designed to drive a pair of wheels while allowing them to rotate at different speeds. In vehicles without a differential, such as karts, both driving wheels are forced to rotate at the same speed, usually on a common axle driven by a simple chain-drive mechanism."
},
{
"code": null,
"e": 91988,
"s": 91839,
"text": "Unix is more flexible and can be installed on many different types of machines, including main-frame computers, super computers and micro-computers."
},
{
"code": null,
"e": 92113,
"s": 91988,
"text": "- Unix is more stable and does not go down as often as Windows does, therefore requires less administration and maintenance."
},
{
"code": null,
"e": 92189,
"s": 92113,
"text": "- Unix has greater built-in security and permissions features than Windows."
},
{
"code": null,
"e": 92250,
"s": 92189,
"text": "- Unix possesses much greater processing power than Windows."
},
{
"code": null,
"e": 92407,
"s": 92250,
"text": "- Unix is the leader in serving the Web. About 90% of the Internet relies on Unix operating systems running Apache, the world's most widely used Web server."
},
{
"code": null,
"e": 92557,
"s": 92407,
"text": "- Software upgrades from Microsoft often require the user to purchase new or more hardware or prerequisite software. That is not the case with Unix ."
},
{
"code": null,
"e": 92877,
"s": 92557,
"text": "The “Core 2 Duo” is a name given to series of Processors of Intel. The name is specific to that range only and not any other. These processors had only two cores as the “Duo” the term says. Similary, there was a series of Intel Proecessors named “Core 2 Quad” whose processors had four Cores as the term “Quad” applies."
},
{
"code": null,
"e": 93287,
"s": 92877,
"text": "The term “Dual Core” obviously means that the referenced processor would have two cores. However, this term was mainly used in non-mainstream processor. These were meant for budget class, or more power-efficiency than performance. So, basically a Core 2 Duo Processor would perform better that a Dual Core stated Processor, but there are few more things to look at when comparing and there are few exceptions."
},
{
"code": null,
"e": 93516,
"s": 93287,
"text": "The smallest value that can be measured by the measuring instrument is called its least count. Measured values are good only up to this value. The least count error is the error associated with the resolution of the instrument ."
},
{
"code": null,
"e": 93643,
"s": 93516,
"text": "COBOL (Common Business Oriented Language) was the first widely-used high-level programming language for business applications."
},
{
"code": null,
"e": 94081,
"s": 93643,
"text": "While the language has been updated over the years, COBOL programs are generally viewed as being outdated. Today, however, a majority of payroll, accounting and other business application programs still use COBOL despite the growing popularity of more modern programming languages such as Java, C++ and .NET. In fact, there are more existing lines of programming code still in use written in COBOL than in any other programming language."
},
{
"code": null,
"e": 94259,
"s": 94081,
"text": "The Pentium 4 570 processor is a 3.8GHz chip with 1Mbytes of Level 2 cache that will feature the fastest clock speed of any Pentium 4 processor for an indefinite period of time."
},
{
"code": null,
"e": 94576,
"s": 94259,
"text": "Linear programming (LP) (also called linear optimization) is a method to achieve the best outcome (such as maximum profit or lowest cost) in a mathematical model whose requirements are represented by linear relationships. Linear programming is a special case of mathematical programming (mathematical optimization) ."
},
{
"code": null,
"e": 94800,
"s": 94576,
"text": "Grid computing is the collection of computer resources from multiple locations to reach a common goal. The grid can be thought of as a distributed system with non-interactive workloads that involve a large number of files ."
},
{
"code": null,
"e": 94885,
"s": 94800,
"text": "for detail refers :http://www.geeksforgeeks.org/mpi-distributed-computing-made-easy/"
},
{
"code": null,
"e": 95200,
"s": 94885,
"text": "1) Data stored in normalized schema in OLTP systems can have hundreds to thousands of tables for an enterprise. OLTP systems have a probability, that a portion of these tables can be often less descriptive due to lack of self relevant naming conventions. This makes designing queries harder for reporting purposes."
},
{
"code": null,
"e": 95604,
"s": 95202,
"text": "2) As normalised schema has a lot of tables, a single piece of related information is split and stored into various tables with referential integrity constraints. This means that reading this data requires creating joins with many tables. For reporting and analysis purposes over a very huge dataset spanning thousands to millions of records of historical data, such queries would perform very poorly."
},
{
"code": null,
"e": 95816,
"s": 95606,
"text": "3) OLTP systems tend to archive data time to time on a scheduled basis. It might be in the form of hard / soft delete. Lack of historical data can limit the level of analysis that can be performed on the data."
},
{
"code": null,
"e": 96150,
"s": 95818,
"text": "4) OLTP systems tend to store most updated version of data only. For ex employee address, product name, martial status etc. Generally history for such attributes would not be preserved, which results in loss of historical data. Lack of history for such attributes can limit the level of analysis that can be performed on the data ."
},
{
"code": null,
"e": 96481,
"s": 96150,
"text": " image processing is processing of images using mathematical operations by using any form of signal processing for which the input is an image, a series of images, or a video, such as a photograph or video frame; the output of image processing may be either an image or a set of characteristics or parameters related to the image."
},
{
"code": null,
"e": 96801,
"s": 96481,
"text": "The abacus (plural abaci or abacuses), also called a counting frame, is a calculating tool that was in use in Europe, China and Russia, centuries before the adoption of the written Hindu–Arabic numeral system and is still used by merchants, traders and clerks in some parts of Eastern Europe, Russia, China and Africa ."
},
{
"code": null,
"e": 97034,
"s": 96801,
"text": "PageRank (PR) is an algorithm used by Google Search to rank websites in their search engine results. PageRank was named after Larry Page, one of the founders of Google. PageRank is a way of measuring the importance of website pages."
},
{
"code": null,
"e": 97319,
"s": 97034,
"text": "A decision support system (DSS) is a computerized information system used to support decision-making in an organization or a business. A DSS lets users sift through and analyze massive reams of data and compile information that can be used to solve problems and make better decisions."
},
{
"code": null,
"e": 97592,
"s": 97319,
"text": "A 64-bit processor is a microprocessor with a word size of 64 bits, a requirement for memory and data intensive applications such as computer-aided design (CAD) applications, database management systems, technical and scientific applications, and high-performance servers."
},
{
"code": null,
"e": 97906,
"s": 97592,
"text": "genetic programming (GP) is a technique whereby computer programs are encoded as a set of genes that are then modified (evolved) using an evolutionary algorithm (often a genetic algorithm, \"GA\") – it is an application of (for example) genetic algorithms where the space of solutions consists of computer programs."
},
{
"code": null,
"e": 97975,
"s": 97906,
"text": "SAP stands for Systems Applications and Products in Data Processing."
},
{
"code": null,
"e": 98091,
"s": 97975,
"text": "SAP by definition is also named of the ERP (Enterprise Resource Planning) software as well the name of the company."
},
{
"code": null,
"e": 98178,
"s": 98091,
"text": "SAP Software was Founded in 1972 by Wellenreuther, Hopp, Hector, Plattner and Tschira."
},
{
"code": null,
"e": 98303,
"s": 98178,
"text": "SAP system consists of a number of fully integrated modules, which covers virtually every aspect of the business management."
},
{
"code": null,
"e": 98489,
"s": 98303,
"text": "SAP is #1 in the ERP market. As of 2010, SAP has more than 140,000 installations worldwide, over 25 industry-specific business solutions and more than 75,000 customers in 120 countries"
},
{
"code": null,
"e": 98582,
"s": 98489,
"text": "Other Competitive products of SAP Software in the market are Oracle, Microsoft Dynamics etc"
},
{
"code": null,
"e": 98845,
"s": 98582,
"text": "A collection of wires through which data is transmitted from one part of a computer to another. You can think of a bus as a highway on which data travels within a computer. When used in reference to personal computers, the term bus usually refers to internal bus"
},
{
"code": null,
"e": 99081,
"s": 98845,
"text": "Embedded software is computer software, written to control machines or devices that are not typically thought of as computers. It is typically specialized for the particular hardware that it runs on and has time and memory constraints."
},
{
"code": null,
"e": 99350,
"s": 99081,
"text": "Operations research (OR) is an analytical method of problem-solving and decision-making that is useful in the management of organizations. In operations research, problems are broken down into basic components and then solved in defined steps by mathematical analysis."
},
{
"code": null,
"e": 99692,
"s": 99350,
"text": "The JVM uses locks in conjunction with monitors. A monitor is basically a guardian that watches over a sequence of synchronized code and ensuring that only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. The thread is not allowed to execute the code until it obtains the lock."
},
{
"code": null,
"e": 99771,
"s": 99692,
"text": "for detail refers :http://www.geeksforgeeks.org/process-synchronization-set-1/"
},
{
"code": null,
"e": 99980,
"s": 99771,
"text": "Java API provides several convenient methods to split string based upon any delimiter e.g. comma, semi colon or colon. You can even use regular expression to split a big string into several smaller strings.\n "
},
{
"code": null,
"e": 100076,
"s": 99980,
"text": "SSL and SSH both are special encryption and protocol technologies used to connect two computers"
},
{
"code": null,
"e": 100572,
"s": 100076,
"text": "• SSH: SSH stands for “Secure Shell” which commonly uses port 22 to connect your system on another system via internet. It is often used by network administrators as a remote login or remote control to manage their business servers.\n• SSL: SSL stands for “Secure Sockets Layer” it commonly uses port 443 to connect your system to a secure system on the Internet. It is often used for transmitting information like tax, banking, credit card, personal information to a business server somewhere."
},
{
"code": null,
"e": 100692,
"s": 100572,
"text": "Software Metrics provide measures for various aspects of software process and software product. They are divided into –"
},
{
"code": null,
"e": 100748,
"s": 100692,
"text": "Requirement metrics : Length requirements, completeness"
},
{
"code": null,
"e": 100829,
"s": 100748,
"text": "Product metrics :Lines of Code, Object oriented metrics, design and test metrics"
},
{
"code": null,
"e": 100899,
"s": 100829,
"text": "Process metrics: Evaluate and track budget, schedule, human resource."
},
{
"code": null,
"e": 101098,
"s": 100899,
"text": "Baseline is a measurement that defines completeness of a phase. After all activities associated with a particular phase are accomplished, the phase is complete and acts as a baseline for next phase."
},
{
"code": null,
"e": 101349,
"s": 101098,
"text": "This is the most obvious question accurued in mind that if the cloud data is secure; To ensure that, check that there is no data leak with the encryption key implemented with the data you sending while the data moves from point A to point B in cloud."
},
{
"code": null,
"e": 101887,
"s": 101349,
"text": "Scalability is a characteristic of cloud computing which is used to handle the increasing workload by increasing in proportion amount of resource capacity. By the use of scalability, the architecture provides on demand resources if the requirement is being raised by the traffic. Whereas, Elasticity is a characteristic which provides the concept of commissioning and decommissioning of large amount of resource capacity dynamically. It is measured by the speed by which the resources are coming on demand and the usage of the resources."
},
{
"code": null,
"e": 102194,
"s": 101887,
"text": "Synchronicity is used to bind the client to the execution of the service. In synchronous invocations, the client blocks and waits for the service to complete its operation before continuing. On the other hand, synchronous operations facilitate a client to invoke a service and then execute other functions."
},
{
"code": null,
"e": 102322,
"s": 102194,
"text": "Interoperability: By the help of web services, an application can communicate with other application developed in any language."
},
{
"code": null,
"e": 102404,
"s": 102322,
"text": "Reusability: We can expose the web service so that other applications can use it."
},
{
"code": null,
"e": 102517,
"s": 102404,
"text": "Modularity: By the help of web service, we can create a service for a specific task such as tax calculation etc."
},
{
"code": null,
"e": 102658,
"s": 102517,
"text": "Benchmarking testing is the process of comparing application performance with respect to industry standard given by some other organization."
},
{
"code": null,
"e": 102752,
"s": 102658,
"text": "It is a standard testing which specifies where our application stands with respect to others."
},
{
"code": null,
"e": 103069,
"s": 102752,
"text": "In Baseline testing, a set of tests is run to capture performance information. Baseline testing improves performance and capabilities of the application by using the information collected and make the changes in the application. Baseline compares present performance of application with its own previous performance."
},
{
"code": null,
"e": 103196,
"s": 103069,
"text": "The \"netstat\" is a command line utility program. It gives useful information about the current TCP/IP setting of a connection."
},
{
"code": null,
"e": 103399,
"s": 103196,
"text": "NOS stands for Network Operating System. It is specialized software which is used to provide network connectivity to a computer to make communication possible with other computers and connected devices."
},
{
"code": null,
"e": 103442,
"s": 103399,
"text": "A list of predefined exceptions in PL/SQL:"
},
{
"code": null,
"e": 103459,
"s": 103442,
"text": "DUP_VAL_ON_INDEX"
},
{
"code": null,
"e": 103471,
"s": 103459,
"text": "ZERO_DIVIDE"
},
{
"code": null,
"e": 103485,
"s": 103471,
"text": "NO_DATA_FOUND"
},
{
"code": null,
"e": 103499,
"s": 103485,
"text": "TOO_MANY_ROWS"
},
{
"code": null,
"e": 103519,
"s": 103499,
"text": "CURSOR_ALREADY_OPEN"
},
{
"code": null,
"e": 103534,
"s": 103519,
"text": "INVALID_NUMBER"
},
{
"code": null,
"e": 103549,
"s": 103534,
"text": "INVALID_CURSOR"
},
{
"code": null,
"e": 103563,
"s": 103549,
"text": "PROGRAM_ERROR"
},
{
"code": null,
"e": 103584,
"s": 103563,
"text": "TIMEOUT _ON_RESOURCE"
},
{
"code": null,
"e": 103598,
"s": 103584,
"text": "STORAGE_ERROR"
},
{
"code": null,
"e": 103611,
"s": 103598,
"text": "LOGON_DENIED"
},
{
"code": null,
"e": 103623,
"s": 103611,
"text": "VALUE_ERROR"
},
{
"code": null,
"e": 103628,
"s": 103623,
"text": "etc."
},
{
"code": null,
"e": 103913,
"s": 103628,
"text": "Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes to one object \"sachin\".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java."
},
{
"code": null,
"e": 104147,
"s": 103913,
"text": "Boxing:Implicit conversion of a value type (integer, character etc.) to a reference type (object) is called boxing. In boxing process a value type(which generally stores on stack) is being allocated on the heap rather than the stack."
},
{
"code": null,
"e": 104374,
"s": 104147,
"text": "Unboxing:explicit conversion of that same reference type (which is created by boxing process) back to a value type is known as unboxing. In unboxing process boxed value type is unboxed from the heap and allocated on the stack."
},
{
"code": null,
"e": 104580,
"s": 104374,
"text": "SQL Server is DBMS system provided by Microsoft. Sometimes it is mistakenly referred as SQL but both are totally different, as SQL is a language whereas SQL Server is a Microsoft product that supports SQL."
},
{
"code": null,
"e": 104774,
"s": 104580,
"text": "ORM is an acronym for Object/Relational mapping. It is a programming strategy to map object with the data stored in the database. It simplifies data creation, data manipulation and data access."
},
{
"code": null,
"e": 104898,
"s": 104774,
"text": "Hibernate is an open-source and lightweight ORM tool that is used to store, manipulate and retrieve data from the database."
},
{
"code": null,
"e": 105183,
"s": 104898,
"text": "Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones."
},
{
"code": null,
"e": 105437,
"s": 105183,
"text": "strstr() returns part of a given string from the first occurrence of a given substring to the end of the string.\nFor example:strstr(\"user@example.com\",\"@\") will return \"@example.com\".\nstristr() is idential to strstr() except that it is case insensitive."
},
{
"code": null,
"e": 105454,
"s": 105439,
"text": "Answer: 5,20,1"
},
{
"code": null,
"e": 105468,
"s": 105454,
"text": "Answer : 5794"
},
{
"code": null,
"e": 105940,
"s": 105468,
"text": "The major difference between B-tree and binary tres is that B-tree is a external data structure and binary tree is a main memory data structure. The computational complexity of binary tree is counted by the number of comparison operations at each node, while the computational complexity of B-tree is determined by the disk I/O, that is, the number of node that will be loaded from disk to main memory. The comparision of the different values in one node is not counted ."
},
{
"code": null,
"e": 106774,
"s": 105940,
"text": "CTS is the component of CLR through which .NET Framework provides support for multiple languages because it contains a type system that is common across all the languages. Two CTS-compliant languages do not require type conversion when calling the code written in one language from within the code written in another language. CTS provide a base set of data types for all the languages supported by.NET Framework. This means that the size of integer and long variables is same across all .NET-compliant programming languages. However, each language uses aliases for the base data types provided by CTS. For example, CTS uses the data type system. int32 to represent a 4 byte integer value; however, Visual Basic uses the alias integer for the same; whereas, C# uses the alias int. This is done for the sake of clarity and simplicity."
},
{
"code": null,
"e": 107097,
"s": 106774,
"text": "Managed extensibility framework (MEF) is a new library that is introduced as a part of .NET 4.0 and Silverlight 4. It helps in extending your application by providing greater reuse of applications and components. MEF provides a way for host application to consume external extensions without any configuration requirement."
},
{
"code": null,
"e": 107460,
"s": 107097,
"text": "Code contracts help you to express the code assumptions and statements stating the behavior of your code in a language-neutral way. The contracts are included in the form of pre-conditions, post-conditions and object-invariants. The contracts help you to improve-testing by enabling run-time checking, static contract verification, and documentation generation ."
},
{
"code": null,
"e": 107570,
"s": 107460,
"text": "Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following things"
},
{
"code": null,
"e": 107591,
"s": 107570,
"text": "Version of assembly."
},
{
"code": null,
"e": 107610,
"s": 107591,
"text": "Security identity."
},
{
"code": null,
"e": 107633,
"s": 107610,
"text": "Scope of the assembly."
},
{
"code": null,
"e": 107678,
"s": 107633,
"text": "Resolve references to resources and classes."
},
{
"code": null,
"e": 107930,
"s": 107678,
"text": "\nThe assembly manifest can be stored in a PE file either (an .exe or) .dll with Microsoft \nintermediate language (MSIL code with Microsoft intermediate language (MSIL) code or in a \nstand-alone PE file, that contains only assembly manifest information"
},
{
"code": null,
"e": 108219,
"s": 107930,
"text": "Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code is compiled to IL. IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler."
},
{
"code": null,
"e": 108391,
"s": 108219,
"text": "struct ABC{\n int a;\n float b;\n char c;\n};\nint main(){\n struct ABC *ptr=(struct ABC *)0;\n ptr++;\n printf(\"Size of structure is: %d\",*ptr);\n return 0;\n"
},
{
"code": null,
"e": 108401,
"s": 108393,
"text": "Merits:"
},
{
"code": null,
"e": 108449,
"s": 108401,
"text": "(a) We can easily access each element of array."
},
{
"code": null,
"e": 108498,
"s": 108449,
"text": "(b) Not necessity to declare too many variables."
},
{
"code": null,
"e": 108559,
"s": 108498,
"text": "(c) Array elements are stored in continuous memory location."
},
{
"code": null,
"e": 108570,
"s": 108561,
"text": "Demerit:"
},
{
"code": null,
"e": 108648,
"s": 108570,
"text": "(a) Wastage of memory space. We cannot change size of array at the run time. "
},
{
"code": null,
"e": 108692,
"s": 108648,
"text": "(b) It can store only similar type of data."
},
{
"code": null,
"e": 108765,
"s": 108692,
"text": "You can modify constant variable with the help of pointers. For example:"
},
{
"code": null,
"e": 108904,
"s": 108765,
"text": "#include<stdio.h>\n\nint main(){\n\n int i=10;\n\n int *ptr=&i;\n\n *ptr=(int *)20;\n\n printf(\"%d\",i);\n\n return 0;\n\n}\n\n\n\nOutput: 20 "
},
{
"code": null,
"e": 108975,
"s": 108906,
"text": "In c we can pass the parameters in a function in two different ways."
},
{
"code": null,
"e": 109184,
"s": 108977,
"text": "(a)Pass by value: In this approach we pass copy of actual variables in function as a parameter. Hence any modification on parameters inside the function will not reflect in the actual variable. For example:"
},
{
"code": null,
"e": 109204,
"s": 109186,
"text": "#include<stdio.h>"
},
{
"code": null,
"e": 109216,
"s": 109204,
"text": "int main(){"
},
{
"code": null,
"e": 109234,
"s": 109216,
"text": " int a=5,b=10;"
},
{
"code": null,
"e": 109249,
"s": 109234,
"text": " swap(a,b);"
},
{
"code": null,
"e": 109279,
"s": 109249,
"text": " printf(\"%d %d\",a,b);"
},
{
"code": null,
"e": 109293,
"s": 109279,
"text": " return 0;"
},
{
"code": null,
"e": 109296,
"s": 109293,
"text": "} "
},
{
"code": null,
"e": 109320,
"s": 109296,
"text": "void swap(int a,int b){"
},
{
"code": null,
"e": 109334,
"s": 109320,
"text": " int temp;"
},
{
"code": null,
"e": 109347,
"s": 109334,
"text": " temp =a;"
},
{
"code": null,
"e": 109356,
"s": 109347,
"text": " a=b;"
},
{
"code": null,
"e": 109368,
"s": 109356,
"text": " b=temp;"
},
{
"code": null,
"e": 109370,
"s": 109368,
"text": "}"
},
{
"code": null,
"e": 109386,
"s": 109370,
"text": "Output: 5 10"
},
{
"code": null,
"e": 109602,
"s": 109388,
"text": "(b)Pass by reference: In this approach we pass memory address actual variables in function as a parameter. Hence any modification on parameters inside the function will reflect in the actual variable. For example:"
},
{
"code": null,
"e": 109621,
"s": 109604,
"text": "#incude<stdio.h>"
},
{
"code": null,
"e": 109633,
"s": 109621,
"text": "int main(){"
},
{
"code": null,
"e": 109651,
"s": 109633,
"text": " int a=5,b=10;"
},
{
"code": null,
"e": 109668,
"s": 109651,
"text": " swap(&a,&b);"
},
{
"code": null,
"e": 109693,
"s": 109668,
"text": " printf(\"%d %d\",a,b);"
},
{
"code": null,
"e": 109707,
"s": 109693,
"text": " return 0;"
},
{
"code": null,
"e": 109710,
"s": 109707,
"text": "} "
},
{
"code": null,
"e": 109736,
"s": 109710,
"text": "void swap(int *a,int *b){"
},
{
"code": null,
"e": 109752,
"s": 109736,
"text": " int *temp;"
},
{
"code": null,
"e": 109767,
"s": 109752,
"text": " *temp =*a;"
},
{
"code": null,
"e": 109778,
"s": 109767,
"text": " *a=*b;"
},
{
"code": null,
"e": 109792,
"s": 109778,
"text": " *b=*temp;"
},
{
"code": null,
"e": 109794,
"s": 109792,
"text": "}"
},
{
"code": null,
"e": 109809,
"s": 109796,
"text": "Output: 10 5"
},
{
"code": null,
"e": 109881,
"s": 109809,
"text": "A pointer in c which has not been initialized is known as wild pointer."
},
{
"code": null,
"e": 109892,
"s": 109883,
"text": "Example:"
},
{
"code": null,
"e": 109967,
"s": 109892,
"text": "int main(){\n\nint *ptr;\n\nprintf(\"%u\\n\",ptr);\n\nprintf(\"%d\",*ptr);\n\nreturn 0;"
},
{
"code": null,
"e": 109969,
"s": 109967,
"text": "}"
},
{
"code": null,
"e": 109991,
"s": 109971,
"text": "Output: Any address"
},
{
"code": null,
"e": 110005,
"s": 109991,
"text": "Garbage value"
},
{
"code": null,
"e": 110243,
"s": 110007,
"text": "Here ptr is wild pointer because it has not been initialized. There is difference between the NULL pointer and wild pointer. Null pointer points the base address of segment while wild pointer doesn’t point any specific memory location."
},
{
"code": null,
"e": 110326,
"s": 110243,
"text": "for details refers :http://www.geeksforgeeks.org/dangling-void-null-wild-pointers/"
},
{
"code": null,
"e": 110678,
"s": 110326,
"text": "If one or a few processes have a high access rate to data on one track of a storage disk, then they may monopolize the device by repeated requests to that track. This generally happens with most common device scheduling algorithms (LIFO, SSTF, C-SCAN, etc). High-density multisurface disks are more likely to be affected by this than low density ones."
},
{
"code": null,
"e": 110955,
"s": 110678,
"text": "VFS, or Virtual File System, separates file system generic operations from their implementation by defining a clean VFS interface. It is also based on a file-representation structure known as vnode, which contains a numerical designator needed to support network file systems."
},
{
"code": null,
"e": 111161,
"s": 110955,
"text": "Overlays are used to enable a process to be larger than the amount of memory allocated to it. The basic idea of this is that only instructions and data that are needed at any given time are kept in memory."
},
{
"code": null,
"e": 111537,
"s": 111161,
"text": "\nMutual Exclusion: Only one process may use a critical resource at a time.\nHold & Wait: A process may be allocated some resources while waiting for others.\nNo Pre-emption: No resource can be forcible removed from a process holding it.\nCircular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain.\n"
},
{
"code": null,
"e": 111611,
"s": 111537,
"text": "Mutual Exclusion: Only one process may use a critical resource at a time."
},
{
"code": null,
"e": 111692,
"s": 111611,
"text": "Hold & Wait: A process may be allocated some resources while waiting for others."
},
{
"code": null,
"e": 111771,
"s": 111692,
"text": "No Pre-emption: No resource can be forcible removed from a process holding it."
},
{
"code": null,
"e": 111911,
"s": 111771,
"text": "Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain."
},
{
"code": null,
"e": 112663,
"s": 111911,
"text": "It is a useful, memory-saving technique for multiprogrammed timesharing systems. A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program code cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Each execution instance is called activation. It executes the code in the permanent part, but has its own copy of local variables/parameters. The temporary part associated with each activation is the activation record. Generally, the activation record is kept on the stack."
},
{
"code": null,
"e": 113322,
"s": 112663,
"text": "Two important pieces of RDBMS architecture are the kernel, which is the software, and the data dictionary, which consists of the system-level data structures used by the kernel to manage the database You might think of an RDBMS as an operating system (or set of subsystems), designed specifically for controlling data access; its primary functions are storing, retrieving, and securing data. An RDBMS maintains its own list of authorized users and their associated privileges; manages memory caches and paging; controls locking for concurrent resource usage; dispatches and schedules user requests; and manages space usage within its table-space structures ."
},
{
"code": null,
"e": 113649,
"s": 113322,
"text": "\nProactive Update: The updates that are applied to database before it becomes effective in real world.\nRetroactive Update: The updates that are applied to database after it becomes effective in real world.\nSimulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world.\n"
},
{
"code": null,
"e": 113751,
"s": 113649,
"text": "Proactive Update: The updates that are applied to database before it becomes effective in real world."
},
{
"code": null,
"e": 113854,
"s": 113751,
"text": "Retroactive Update: The updates that are applied to database after it becomes effective in real world."
},
{
"code": null,
"e": 113974,
"s": 113854,
"text": "Simulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world."
},
{
"code": null,
"e": 114631,
"s": 113974,
"text": "\nCold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy. If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost.\nHot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option.\n"
},
{
"code": null,
"e": 115099,
"s": 114631,
"text": "Cold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy. If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost."
},
{
"code": null,
"e": 115286,
"s": 115099,
"text": "Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option."
},
{
"code": null,
"e": 115664,
"s": 115286,
"text": "Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These types of procedures are not available for reference from other Oracle tools. Another limitation of stand-alone procedures is that they are compiled at run time, which slows execution."
},
{
"code": null,
"e": 116160,
"s": 115664,
"text": "Advantages:\n1. Views don't store data in a physical location.\n2. The view can be used to hide some of the columns \nfrom the table.\n3. Views can provide Access Restriction,\n since data insertion, update and deletion \nis not possible with the view.\n\nDisadvantages:\n1. When a table is dropped, associated view become irrelevant.\n2. Since the view is created when a query\n requesting data from view is triggered,\n its a bit slow.\n3. When views are created for large tables, \nit occupies more memory."
},
{
"code": null,
"e": 116362,
"s": 116160,
"text": "Default gateways provide means for the local networks to connect to the external network. The default gateway for connecting to the external network is usually the address of the external router port ."
},
{
"code": null,
"e": 116648,
"s": 116362,
"text": "Traceroute is a widely used command line utility available in almost all operating systems. It shows you the complete route to a destination address. It also shows the time taken (or delays) between intermediate routers. Isn’t it great? Below is an example on Windows operating System."
},
{
"code": null,
"e": 116726,
"s": 116648,
"text": "for detail refers :http://www.geeksforgeeks.org/computer-networks-traceroute/"
},
{
"code": null,
"e": 117085,
"s": 116726,
"text": "DoS, or Denial-of-Service attack, is an attempt to prevent users from being able to access the internet or any other network services. Such attacks may come in different forms and are done by a group of perpetuators. One common method of doing this is to overload the system server so it cannot anymore process legitimate traffic and will be forced to reset."
},
{
"code": null,
"e": 117294,
"s": 117085,
"text": "NOS, or Network Operating System, is specialized software whose main task is to provide network connectivity to a computer in order for it to be able to communicate with other computers and connected devices."
},
{
"code": null,
"e": 117563,
"s": 117294,
"text": "RIP, short for Routing Information Protocol is used by routers to send data from one network to another. It efficiently manages routing data by broadcasting its routing table to all other routers within the network. It determines the network distance in units of hops."
},
{
"code": null,
"e": 117816,
"s": 117565,
"text": "Gray box testing, also called gray box analysis, is a strategy for software debugging in which the tester has limited knowledge of the internal details of the program. A gray box is a device, program or system whose workings are partially understood."
},
{
"code": null,
"e": 118063,
"s": 117816,
"text": "The Capability Maturity Model (CMM) is a methodology used to develop and refine an organization's software development process. The model describes a five-level evolutionary path of increasingly organized and systematically more mature processes."
},
{
"code": null,
"e": 118169,
"s": 118065,
"text": "In Windows NT a mutant provides kernel mode or user mode mutual exclusion with the notion of ownership."
},
{
"code": null,
"e": 119143,
"s": 118169,
"text": "\nLoad Sharing: Processes are not assigned to a particular processor. A global queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis.\nGang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads / processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy.\nDedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool.\nDynamic scheduling: The number of thread in a program can be altered during the course of execution .\n"
},
{
"code": null,
"e": 119422,
"s": 119143,
"text": "Load Sharing: Processes are not assigned to a particular processor. A global queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis."
},
{
"code": null,
"e": 119715,
"s": 119422,
"text": "Gang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads / processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy."
},
{
"code": null,
"e": 120013,
"s": 119715,
"text": "Dedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool."
},
{
"code": null,
"e": 120115,
"s": 120013,
"text": "Dynamic scheduling: The number of thread in a program can be altered during the course of execution ."
},
{
"code": null,
"e": 120277,
"s": 120115,
"text": "The activation record is a block of memory used for managing the information needed by a single execution of a procedure. Various fields f activation record are:"
},
{
"code": null,
"e": 120299,
"s": 120277,
"text": "· Temporary variables"
},
{
"code": null,
"e": 120317,
"s": 120299,
"text": "· Local variables"
},
{
"code": null,
"e": 120343,
"s": 120317,
"text": "· Saved machine registers"
},
{
"code": null,
"e": 120358,
"s": 120343,
"text": "· Control link"
},
{
"code": null,
"e": 120372,
"s": 120358,
"text": "· Access link"
},
{
"code": null,
"e": 120392,
"s": 120372,
"text": "· Actual parameters"
},
{
"code": null,
"e": 120408,
"s": 120392,
"text": "· Return values"
},
{
"code": null,
"e": 120513,
"s": 120408,
"text": "Directed acyclic graph(DAG) is a useful data structure for implementing transformations on basic blocks."
},
{
"code": null,
"e": 120528,
"s": 120513,
"text": "DAG is used in"
},
{
"code": null,
"e": 120570,
"s": 120528,
"text": "· Determining the common sub-expressions."
},
{
"code": null,
"e": 120654,
"s": 120570,
"text": "· Determining which names are used inside the block and computed outside the block."
},
{
"code": null,
"e": 120749,
"s": 120654,
"text": "· Determining which statements of the block could have their computed value outside the block."
},
{
"code": null,
"e": 120911,
"s": 120749,
"text": "· Simplifying the list of quadruples by eliminating the common su-expressions and not performing the assignment of the form x := y unless and until it is a must."
},
{
"code": null,
"e": 120976,
"s": 120911,
"text": "The following are the problems associated with top down parsing:"
},
{
"code": null,
"e": 120991,
"s": 120976,
"text": "· Backtracking"
},
{
"code": null,
"e": 121008,
"s": 120991,
"text": "· Left recursion"
},
{
"code": null,
"e": 121025,
"s": 121008,
"text": "· Left factoring"
},
{
"code": null,
"e": 121037,
"s": 121025,
"text": "· Ambiguity"
},
{
"code": null,
"e": 121521,
"s": 121037,
"text": "The most important point to remember is REDO is not the opposite of UNDO. Whenever a DML transaction happens in database, the data to be updated goes to the DATABASE BUFFER CACHE. From here the data is written to REDO BUFFER and then to REDO Logs. These logs are saved for future use. Future ROLLBACK and DATA RECOVERY operations require these logs. Without these logs it is impossible to do DATA RECOVERY. If ARCHIVING is enabled then these logs are bundled or archived and stored. "
},
{
"code": null,
"e": 121779,
"s": 121521,
"text": "Branch coverage is a testing method, which aims to ensure that each one of the possible branch from each decision point is executed at least once and thereby ensuring that all reachable code is executed. That is, every branch taken each way, true and false."
},
{
"code": null,
"e": 122009,
"s": 121779,
"text": "This results in the index that is automatically generated being placed in the users default tablespace. Since this will usually be the same tablespace as the table is being created in, this can cause serious performance problems."
},
{
"code": null,
"e": 122070,
"s": 122009,
"text": "Thrashing can be solved by one or combination of the below :"
},
{
"code": null,
"e": 122414,
"s": 122070,
"text": "1) Allocating the memory required by the program before executing.\n2) If sufficient memory is not available, effective replacement algorithms for memory allocating should be used\n3) One more way is to reduce the number of programs running currently.\n4) From developers point of view, Large programs in memory can be replaced by small programs."
},
{
"code": null,
"e": 122863,
"s": 122414,
"text": "After receiving a Software build with the minor issues fixes in code or functionality, Sanity testing is carry out to check whether the bugs reported in previous build are fixed & there is regression introduced due to these fixes i.e. not breaking any previously working functionality. The main aim of Sanity testing to check the planned functionality is working as expected. Instead of doing whole regression testing the Sanity testing is perform."
},
{
"code": null,
"e": 122979,
"s": 122863,
"text": "To increase lookup performance. For a unique key to guarantee the uniqueness of the values for a column on a table."
},
{
"code": null,
"e": 123040,
"s": 122979,
"text": "The Join statement combines data from more that two tables ."
},
{
"code": null,
"e": 123154,
"s": 123040,
"text": "Code-division multiple access (CDMA) is a channel access method used by various radio communication technologies."
},
{
"code": null,
"e": 123294,
"s": 123154,
"text": " CDMA is an example of multiple access, where several transmitters can send information simultaneously over a single communication channel."
},
{
"code": null,
"e": 123739,
"s": 123294,
"text": "Techniques generally used are direct sequence spread spectrum modulation (DS-CDMA), frequency hopping or mixed CDMA detection (JDCDMA). Here, a signal is generated which extends over a wide bandwidth. A code called spreading code is used to perform this action. Using a group of codes, which are orthogonal to each other, it is possible to select a signal with a given code in the presence of many other signals with different orthogonal codes."
},
{
"code": null,
"e": 123758,
"s": 123739,
"text": "Advantages of CDMA"
},
{
"code": null,
"e": 123881,
"s": 123758,
"text": "CDMA has a soft capacity. The greater the number of codes, the more the number of users. It has the following advantages −"
},
{
"code": null,
"e": 124127,
"s": 123881,
"text": "\nCDMA requires a tight power control, as it suffers from near-far effect. In other words, a user near the base station transmitting with the same power will drown the signal latter. All signals must have more or less equal power at the receiver\n"
},
{
"code": null,
"e": 124371,
"s": 124127,
"text": "CDMA requires a tight power control, as it suffers from near-far effect. In other words, a user near the base station transmitting with the same power will drown the signal latter. All signals must have more or less equal power at the receiver"
},
{
"code": null,
"e": 124568,
"s": 124371,
"text": "\nRake receivers can be used to improve signal reception. Delayed versions of time (a chip or later) of the signal (multipath signals) can be collected and used to make decisions at the bit level.\n"
},
{
"code": null,
"e": 124763,
"s": 124568,
"text": "Rake receivers can be used to improve signal reception. Delayed versions of time (a chip or later) of the signal (multipath signals) can be collected and used to make decisions at the bit level."
},
{
"code": null,
"e": 124869,
"s": 124763,
"text": "Primary Key constraint does not allow null values to be inserted while it is legal in case of Unique key."
},
{
"code": null,
"e": 124882,
"s": 124869,
"text": "n(n - 1) / 2"
},
{
"code": null,
"e": 125068,
"s": 124882,
"text": " A mesh network is a fully connected network with every node (or computer/device) connected to every other node. The number of links is n(n - 1) / 2 which can be proved mathematically. "
},
{
"code": null,
"e": 125083,
"s": 125068,
"text": "The issues are"
},
{
"code": null,
"e": 125167,
"s": 125083,
"text": "i) Length of time required by the programmer in coding a particular sorting program"
},
{
"code": null,
"e": 125239,
"s": 125167,
"text": "ii) Amount of machine time necessary for running the particular program"
},
{
"code": null,
"e": 125302,
"s": 125239,
"text": "iii)The amount of space necessary for the particular program ."
},
{
"code": null,
"e": 125342,
"s": 125302,
"text": "1.Prefix Notation: ^ – * +ABC – DE + FG"
},
{
"code": null,
"e": 125385,
"s": 125342,
"text": "2.Postfix Notation: AB + C * DE – – FG + ^"
},
{
"code": null,
"e": 125482,
"s": 125385,
"text": "The number of comparisons depends on where the record with the argument key appears in the table"
},
{
"code": null,
"e": 125534,
"s": 125482,
"text": "If it appears at first position then one comparison"
},
{
"code": null,
"e": 125584,
"s": 125534,
"text": "If it appears at last position then n comparisons"
},
{
"code": null,
"e": 125612,
"s": 125584,
"text": "Average=(n+1)/2 comparisons"
},
{
"code": null,
"e": 125690,
"s": 125612,
"text": "Unsuccessful search n comparisons Number of comparisons in any case is O (n)."
},
{
"code": null,
"e": 125948,
"s": 125690,
"text": "A cross compiler is a compiler capable of creating executable code for a platform other than the one on which the compiler is running. For example, a compiler that runs on a Windows 7 PC but generates code that runs on Android smartphone is a cross compiler"
},
{
"code": null,
"e": 126116,
"s": 125948,
"text": "A control flow graph (CFG) in computer science is a representation, using graph notation, of all paths that might be traversed through a program during its execution ."
},
{
"code": null,
"e": 126329,
"s": 126116,
"text": "The term daemon is a UNIX term, though many other operating systems provide support for daemons, though they're sometimes called other names. Windows, for example, refers to daemons as System Agents and services."
},
{
"code": null,
"e": 126547,
"s": 126329,
"text": "Typical daemon processes include print spoolers, e-mail handlers, and other programs that perform administrative tasks for the operating system. The term comes from Greek mythology, where daemons were guardian spirits"
},
{
"code": null,
"e": 126854,
"s": 126547,
"text": "The Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call, and to be called by, native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly ."
},
{
"code": null,
"e": 127176,
"s": 126854,
"text": "They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a 0-argument constructor, and allows access to properties using getter and setter methods ."
},
{
"code": null,
"e": 127451,
"s": 127176,
"text": "The java.util.SortedSet interface is a subtype of the java.util.Set interface. It behaves like a normal set with the exception that the elements are sorted internally. This means that when you iterate the elements of a SortedSet the elements are returned in thesorted order."
},
{
"code": null,
"e": 127638,
"s": 127451,
"text": "The elements can be sorted in two ways. One way is to use the Comparable interface. Objects can be compared using the compareTo() method. This approach is referred to as a natural order."
},
{
"code": null,
"e": 127921,
"s": 127638,
"text": "The other way is to specify a comparator for the elements in the set if the class doesn't implement the Comparable interface, or you don’t want to use the compareTo() method in the class that implements the Comparable interface. This approach is referred to as order by comparator ."
},
{
"code": null,
"e": 128618,
"s": 127921,
"text": "When you do a shallow copy, all the fields of the source object is copied to target object as it is. That means, if there is a dynamically created field in the source object, shallow copy will copy the same pointer to target object. So you will have two objects with fields that are pointing to same memory location which is not what you usually want.\nIn case of deep copy, instead of copying the pointer, the object itself is copied to target. In this case if you modify the target object, it will not affect the source. By default copy constructors and assignment operators do shallow copy. To make it as deep copy, you need to create a custom copy constructor and override assignment operator."
},
{
"code": null,
"e": 128782,
"s": 128618,
"text": "Tool Selection – List down the automation tools compatible, depending on whether the application is Desktop / Web based, language used for software development etc"
},
{
"code": null,
"e": 128883,
"s": 128782,
"text": "Scope of Automation – List down the scenarios and functionality which are repetitive and automatable"
},
{
"code": null,
"e": 128963,
"s": 128883,
"text": "Planning – Design a framework, Schedule the scripting and execution of the same"
},
{
"code": null,
"e": 129058,
"s": 128963,
"text": "iDevelopment – Scripting the scenarios to be tested with inputs(Test Data) and expected output"
},
{
"code": null,
"e": 129126,
"s": 129058,
"text": "Execution – Running/Executing the scripts and reporting the results"
},
{
"code": null,
"e": 129227,
"s": 129126,
"text": "vMaintenance – Update the scripts in accordance to the latest changes with the software under test ."
},
{
"code": null,
"e": 129620,
"s": 129227,
"text": "Group policy provides the stream line access to all the users in the network, it can be used to define the users security and networking policies. By group policy you can keep control over certain function like not allowing the users to shut down the system or using the control panel or running the command. Group policy is applicable on active directory container like OU, site and Domain."
},
{
"code": null,
"e": 129838,
"s": 129620,
"text": "VPN means Virtual Private Network. It is a private communications network often used by companies or organizations to communicate confidentially over a public network. This is used by the mobile users in the network."
},
{
"code": null,
"e": 130240,
"s": 129838,
"text": "RAS means Remote Access Server. It allows operating the tool or information that typically resides on a network or IT devices through combination of hardware and software, for example connecting to printer or file. It is usually used for mobile users who are in the network. It uses telephone line to provide connectivity to its users. It can also connect two or more than two offices in the network."
},
{
"code": null,
"e": 130413,
"s": 130240,
"text": "A Blue Screen of Death (or just a Blue Screen Error) is an indication of a Critical System Problem wherein the Computer freezes altogether and does not respond to anything."
},
{
"code": null,
"e": 130667,
"s": 130413,
"text": "In distributed deadlock detection, the delay in propagating local information might cause the deadlock detection algorithms to identify deadlocks that do not really exist. Such situations are called phantom deadlocks and they lead to unnecessary aborts."
},
{
"code": null,
"e": 131221,
"s": 130667,
"text": "Shadowing is either through scope or through inheritance. Shadowing through inheritance is hiding a method of a base class and providing a new implementation for the same. This is the default when a derived class writes an implementation of a method of base class which is not declared as overridden in the base class. This also serves the purpose of protecting an implementation of a new method against subsequent addition of a method with the same name in the base class.’shadows’ keyword is recommended although not necessary since it is the default."
},
{
"code": null,
"e": 131404,
"s": 131223,
"text": "The Portable Executable (PE) format is a file format for executables, object code, DLLs, FON Font files, and others used in 32-bit and 64-bit versions of Windows operating systems."
},
{
"code": null,
"e": 132580,
"s": 131404,
"text": "\n\nIEEE 802 : LAN/MAN\n\n\nIEEE 802.1 : Standards for LAN/MAN bridging and management and remote media access control bridging.\n\n\nIEEE 802.2 : Standards for Logical Link Control (LLC) standards for connectivity.\n\n\nIEEE 802.3 : Ethernet Standards for Carrier Sense Multiple Access with Collision Detection (CSMA/CD).\n\n\nIEEE 802.4 : Standards for token passing bus access.\n\n\nIEEE 802.5 : Standards for token ring access and for communications between LANs and MANs\n\n\nIEEE 802.6 : Standards for information exchange between systems.\n\n\nIEEE 802.7 : Standards for broadband LAN cabling.\n\n\nIEEE 802.8 : Fiber optic connection.\n\n\nIEEE 802.9 : Standards for integrated services, like voice and data.\n\n\nIEEE 802.10 : Standards for LAN/MAN security implementations.\n\n\nIEEE 802.11 : Wireless Networking \"WiFi\".\n\n\nIEEE 802.12 : Standards for demand priority access method.\n\n\nIEEE 802.14 : Standards for cable television broadband communications.\n\n\nIEEE 802.15.1 : Bluetooth\n\n\nIEEE 802.15.4 : Wireless Sensor/Control Networks \"ZigBee\"\n\n\nIEEE 802.16 : Wireless Networking \"WiMAX\"\n\n"
},
{
"code": null,
"e": 132608,
"s": 132580,
"text": "\nIEEE 802 : LAN/MAN\n"
},
{
"code": null,
"e": 132634,
"s": 132608,
"text": "IEEE 802 : LAN/MAN"
},
{
"code": null,
"e": 132764,
"s": 132634,
"text": "\nIEEE 802.1 : Standards for LAN/MAN bridging and management and remote media access control bridging.\n"
},
{
"code": null,
"e": 132892,
"s": 132764,
"text": "IEEE 802.1 : Standards for LAN/MAN bridging and management and remote media access control bridging."
},
{
"code": null,
"e": 132978,
"s": 132892,
"text": "\nIEEE 802.2 : Standards for Logical Link Control (LLC) standards for connectivity.\n"
},
{
"code": null,
"e": 133062,
"s": 132978,
"text": "IEEE 802.2 : Standards for Logical Link Control (LLC) standards for connectivity."
},
{
"code": null,
"e": 133193,
"s": 133062,
"text": "\nIEEE 802.3 : Ethernet Standards for Carrier Sense Multiple Access with Collision Detection (CSMA/CD).\n"
},
{
"code": null,
"e": 133322,
"s": 133193,
"text": "IEEE 802.3 : Ethernet Standards for Carrier Sense Multiple Access with Collision Detection (CSMA/CD)."
},
{
"code": null,
"e": 133379,
"s": 133322,
"text": "\nIEEE 802.4 : Standards for token passing bus access.\n"
},
{
"code": null,
"e": 133434,
"s": 133379,
"text": "IEEE 802.4 : Standards for token passing bus access."
},
{
"code": null,
"e": 133555,
"s": 133434,
"text": "\nIEEE 802.5 : Standards for token ring access and for communications between LANs and MANs\n"
},
{
"code": null,
"e": 133674,
"s": 133555,
"text": "IEEE 802.5 : Standards for token ring access and for communications between LANs and MANs"
},
{
"code": null,
"e": 133743,
"s": 133674,
"text": "\nIEEE 802.6 : Standards for information exchange between systems.\n"
},
{
"code": null,
"e": 133810,
"s": 133743,
"text": "IEEE 802.6 : Standards for information exchange between systems."
},
{
"code": null,
"e": 133864,
"s": 133810,
"text": "\nIEEE 802.7 : Standards for broadband LAN cabling.\n"
},
{
"code": null,
"e": 133916,
"s": 133864,
"text": "IEEE 802.7 : Standards for broadband LAN cabling."
},
{
"code": null,
"e": 133958,
"s": 133916,
"text": "\nIEEE 802.8 : Fiber optic connection.\n"
},
{
"code": null,
"e": 133998,
"s": 133958,
"text": "IEEE 802.8 : Fiber optic connection."
},
{
"code": null,
"e": 134071,
"s": 133998,
"text": "\nIEEE 802.9 : Standards for integrated services, like voice and data.\n"
},
{
"code": null,
"e": 134142,
"s": 134071,
"text": "IEEE 802.9 : Standards for integrated services, like voice and data."
},
{
"code": null,
"e": 134206,
"s": 134142,
"text": "\nIEEE 802.10 : Standards for LAN/MAN security implementations.\n"
},
{
"code": null,
"e": 134268,
"s": 134206,
"text": "IEEE 802.10 : Standards for LAN/MAN security implementations."
},
{
"code": null,
"e": 134314,
"s": 134268,
"text": "\nIEEE 802.11 : Wireless Networking \"WiFi\".\n"
},
{
"code": null,
"e": 134358,
"s": 134314,
"text": "IEEE 802.11 : Wireless Networking \"WiFi\"."
},
{
"code": null,
"e": 134419,
"s": 134358,
"text": "\nIEEE 802.12 : Standards for demand priority access method.\n"
},
{
"code": null,
"e": 134478,
"s": 134419,
"text": "IEEE 802.12 : Standards for demand priority access method."
},
{
"code": null,
"e": 134551,
"s": 134478,
"text": "\nIEEE 802.14 : Standards for cable television broadband communications.\n"
},
{
"code": null,
"e": 134622,
"s": 134551,
"text": "IEEE 802.14 : Standards for cable television broadband communications."
},
{
"code": null,
"e": 134650,
"s": 134622,
"text": "\nIEEE 802.15.1 : Bluetooth\n"
},
{
"code": null,
"e": 134676,
"s": 134650,
"text": "IEEE 802.15.1 : Bluetooth"
},
{
"code": null,
"e": 134738,
"s": 134676,
"text": "\nIEEE 802.15.4 : Wireless Sensor/Control Networks \"ZigBee\"\n"
},
{
"code": null,
"e": 134798,
"s": 134738,
"text": "IEEE 802.15.4 : Wireless Sensor/Control Networks \"ZigBee\""
},
{
"code": null,
"e": 134847,
"s": 134798,
"text": "\nIEEE 802.16 : Wireless Networking \"WiMAX\"\n"
},
{
"code": null,
"e": 134894,
"s": 134847,
"text": "IEEE 802.16 : Wireless Networking \"WiMAX\""
},
{
"code": null,
"e": 135293,
"s": 134894,
"text": "Three ranges of IP addresses have been reserved for private address and they are not valid for use on the Internet. If you want to access internet with these address you must have to use proxy server or NAT server (on normal cases the role of proxy server is played by your ISP.).If you do decide to implement a private IP address range, you can use IP addresses from any of the following classes: "
},
{
"code": null,
"e": 135403,
"s": 135293,
"text": "Class A : 10.0.0.0 10.255.255.255 \nClass B : 172.16.0.0 172.31.255.255 \nClass C : 192.168.0.0 192.168.255.255"
},
{
"code": null,
"e": 135600,
"s": 135405,
"text": "Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created. A very simple immutable object is an object without any field ."
},
{
"code": null,
"e": 135972,
"s": 135600,
"text": "An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. "
},
{
"code": null,
"e": 136300,
"s": 135972,
"text": "It is a feature in C++ to minimize name collisions in the global name space. This namespace keyword assigns a distinct name to a library that allows other libraries to use the same identifier names without creating any name collisions. Furthermore, the compiler uses the namespace signature for differentiating the definitions."
},
{
"code": null,
"e": 137134,
"s": 136300,
"text": "Union is a collection of data items of different data types.\nIt can hold data of only one member at a time though it has members of different data types.\n\nIf a union has two members of different data types, they are allocated the same memory. The memory allocated is equal to maximum size of the members. The data is interpreted in bytes depending on which member is being accessed.\n\nExample:\n\nunion pen {\nchar name;\nfloat point;\n};\n\nHere name and point are union members. Out of these two variables, point is larger variable which is of float data type and it would need 4 bytes of memory. Therefore 4 bytes space is allocated for both the variables. Both the variables have the same memory location. They are accessed according to their type.\nUnion is efficient when members of it are not required to be accessed at the same time"
},
{
"code": null,
"e": 137431,
"s": 137134,
"text": "The file positioning of a stream describes where in the file the stream is currently reading or writing. I/O on the stream advances the file position through the file. On GNU systems, the file position is represented as an integer, which counts the number of bytes from the beginning of the file."
},
{
"code": null,
"e": 137926,
"s": 137431,
"text": "A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.\n "
},
{
"code": null,
"e": 138426,
"s": 137926,
"text": "De-normalization is the process of attempting to optimize the performance of a database by adding redundant data. It is sometimes necessary because current DBMSs implement the relational model poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while providing physical storage of data that is tuned for high performance. De-normalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access."
},
{
"code": null,
"e": 138587,
"s": 138426,
"text": "The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused."
},
{
"code": null,
"e": 138698,
"s": 138587,
"text": "A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used."
},
{
"code": null,
"e": 138848,
"s": 138698,
"text": "Float is used when you want to make an element of your page (usually an image) be pushed to the right or left and make other elements wrap around it."
},
{
"code": null,
"e": 139087,
"s": 138848,
"text": "his can be tricky and the best way to keep in your head is to memorise because if you try to relate java script null to other languages, it will get more confusing. \nIn java script, null is an object with no value and undefined is a type."
},
{
"code": null,
"e": 139150,
"s": 139087,
"text": "typeof null; // \"object\" \ntypeof undefined; // \"undefined\" \n"
},
{
"code": null,
"e": 139278,
"s": 139150,
"text": "var a; \nvar b = null; \na == b; // \"true\" because their values are the same \na === b; // \"false\". they have different types "
},
{
"code": null,
"e": 139838,
"s": 139278,
"text": "There are several technical differences between these two types of requests, regarding length limitation, security, caching and a few others. But if someone asks you WHEN would you use it, I'd say one of the most important points that any front-end developer should take into account is that we should only use GET foridempotent requests, it means requests that don't make significant changes in the backend system or database but if you do need to make inserts, updates or deletes in a database, trigger emails or any other major action, POST is recommended."
},
{
"code": null,
"e": 140031,
"s": 139838,
"text": "That's pretty much it that I wanted to share according to my recent interviews and I believe you'll come across some of these questions or a variation of them in your next technical interview."
},
{
"code": null,
"e": 140341,
"s": 140031,
"text": "XHTML is an HTML that follows the XML rules, which means a XHTML document must have well-formed markups in order to be rendered properly in all web browsers. Differently from XHTML, the HTML document can be rendered in most of the browsers even with markup errors such as no closing tags or wrong nested tags."
},
{
"code": null,
"e": 140379,
"s": 140341,
"text": "And how do I create a XHTML document?"
},
{
"code": null,
"e": 140517,
"s": 140379,
"text": "XHTML is basically a HTML document with some rules that need to be applied. Have a look at these examples below and spot the differences."
},
{
"code": null,
"e": 140707,
"s": 140517,
"text": "<head> \n <title>This is head</title>\n</head> \n<BODY> \n This is the body of the document with body tag in capital letters\n Notice that there's no close body tag and no tag as well.\n"
},
{
"code": null,
"e": 140867,
"s": 140707,
"text": "This HTML document above can be opened with no problems in Chrome, even containing many markup errors because most browsers can fix them for you automatically."
},
{
"code": null,
"e": 141107,
"s": 140867,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\"> \n <head>\n <title></title>\n </head>\n <body>\n </body>\n</html> \n"
},
{
"code": null,
"e": 141400,
"s": 141107,
"text": "The code above is a well-formed XHTML document and that's the minimum you must have in order to render it. Notice the declaration of the doctype at the top of the document and the namespace (xmlns) attribute in html open tag. These elements are mandatory as well as all the tags in lowercase."
},
{
"code": null,
"e": 141631,
"s": 141400,
"text": "Stack. Because of its LIFO (Last In First Out) property it remembers its 'caller' so knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls."
},
{
"code": null,
"e": 141801,
"s": 141631,
"text": "Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used."
},
{
"code": null,
"e": 142070,
"s": 141801,
"text": "The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events raised by ASP.NET or by HttpModules. The Global.asax file resides in the root directory of an ASP.NET-based application."
},
{
"code": null,
"e": 142279,
"s": 142070,
"text": "A link is a second name (not a file) for a file. Links can be used to assign more than one name to a file, but cannot be used to assign a directory more than one name or link filenames on different computers."
},
{
"code": null,
"e": 142486,
"s": 142279,
"text": "Symbolic link 'is' a file that only contains the name of another file.Operation on the symbolic link is directed to the file pointed by the it.Both the limitations of links are eliminated in symbolic links."
},
{
"code": null,
"e": 142592,
"s": 142486,
"text": "Commands for linking files are: \nLink \"ln filename1 filename2\" \nSymbolic link \"ln -s filename1 filename2\""
},
{
"code": null,
"e": 142890,
"s": 142592,
"text": "Interpolation search is an algorithm for searching for a given key in an indexed array that has been ordered by numerical values assigned to the keys (key values). It parallels how humans search through a telephone book for a particular name, the key value by which the book's entries are ordered."
},
{
"code": null,
"e": 143122,
"s": 142890,
"text": "SCSI - Small computer systems interface is a type of interface used for computer components such as hard drives, optical drives, scanners and tape drives. It is a competing technology to standard IDE (Integrated Drive Electronics)."
},
{
"code": null,
"e": 143310,
"s": 143122,
"text": "To achieve maximum efficiency and reliability a mode of operation known as symmetric multiprocessing is used. In essence, with SMP any process or threads can be assigned to any processor."
},
{
"code": null,
"e": 143542,
"s": 143310,
"text": "The process that allows a network to self-repair networks problems. The stations on the network notify the other stations on the ring when they are not receiving the transmissions. Beaconing is used in Token ring and FDDI networks."
},
{
"code": null,
"e": 143807,
"s": 143542,
"text": "APIPA. (Automatic Private IP Addressing) The Windows function that provides DHCP autoconfiguration addressing. APIPA assigns a class B IP address from 169.254.0.0 to 169.254.255.255 to the client when a DHCP server is either permanently or temporarily unavailable."
},
{
"code": null,
"e": 144102,
"s": 143807,
"text": "The LMHOSTS file is a static method of resolving NetBIOS names to IP addresses in the same way that the HOSTS file is a static method of resolving domain names into IP addresses. An LMHOSTS file is a text file that maps NetBIOS names to IP addresses; it must be manually configured and updated."
},
{
"code": null,
"e": 144341,
"s": 144102,
"text": "POP3 stands for Post Office Protocol Version3 (Current Version). POP is a protocol which listens on port 110 and is responsible for accessing the mail service on a client machine. POP3 works in two modes such as Delete Mode and Keep Mode."
},
{
"code": null,
"e": 144501,
"s": 144341,
"text": "a) Delete Mode: A mail is deleted from the mailbox after successful retrieval.\nb) Keep Mode: The Mail remains Intact in the mailbox after successful retrieval."
},
{
"code": null,
"e": 144557,
"s": 144501,
"text": "A network Reliability is measured on following factors."
},
{
"code": null,
"e": 144600,
"s": 144557,
"text": "a) Downtime: The time it takes to recover."
},
{
"code": null,
"e": 144682,
"s": 144600,
"text": "b) Failure Frequency: The frequency when it fails to work the way it is intended."
},
{
"code": null,
"e": 145126,
"s": 144682,
"text": "An object-relational database (ORD), or object-relational database management system (ORDBMS), is a database management system (DBMS) similar to a relational database, but with an object-oriented database model: objects, classes and inheritance are directly supported in database schemas and in the query language. In addition, just as with proper relational systems, it supports extension of the data model with custom data-types and methods."
},
{
"code": null,
"e": 145502,
"s": 145126,
"text": "The terms EXE and DLL are very common in programming. When coding, you can either export your final project to either a DLL or an EXE. The term EXE is a shortened version of the word executable as it identifies the file as a program. On the other hand, DLL stands for Dynamic Link Library, which commonly contains functions and procedures that can be used by other programs ."
},
{
"code": null,
"e": 145783,
"s": 145502,
"text": "A DLL is a library and therefore can not be executed. If you try to run it you'll get an error about a missing entry point. An EXE is a program that can be executed. It has an entry point. A flag inside the PE header indicates which file type it is (irrelevant of file extension)."
},
{
"code": null,
"e": 145923,
"s": 145783,
"text": ".A DLL would share the same process and memory space of the calling application while an EXE creates its separate process and memory space."
},
{
"code": null,
"e": 146343,
"s": 145923,
"text": "A data source name (DSN) is a data structure that contains the information about a specific database that an Open Database Connectivity ( ODBC ) driver needs in order to connect to it. DSNs also exist for JDBC and for other data access mechanisms. The term often overlaps with \"connection string\". Most systems do not make a distinction between DSNs or connection strings and the term can often be used interchangeably."
},
{
"code": null,
"e": 146356,
"s": 146343,
"text": "Types of DSN"
},
{
"code": null,
"e": 146387,
"s": 146356,
"text": "There are three types of DSNs:"
},
{
"code": null,
"e": 146490,
"s": 146387,
"text": "System DSN -- can be used by anyone who has access to the machine. DSN info is stored in the registry."
},
{
"code": null,
"e": 146560,
"s": 146490,
"text": "User DSN -- created for a specific user. Also stored in the registry."
},
{
"code": null,
"e": 146626,
"s": 146560,
"text": "File DSN-- DSN info is stored in a text file with .DSN extension."
},
{
"code": null,
"e": 146807,
"s": 146626,
"text": "There is also what is known as a \"DSN-less connection.\" Instead of using a DSN to connect to a database, the developer specifies the necessary information right in the application."
},
{
"code": null,
"e": 147107,
"s": 146807,
"text": "The term \"schema\" refers to the organization of data as a blueprint of how the database is constructed (divided into database tables in the case of relational databases). The formal definition of a database schema is a set of formulas (sentences) called integrity constraints imposed on a database ."
},
{
"code": null,
"e": 147390,
"s": 147107,
"text": "Null pointer is a special reserved value of a pointer. Apointer of any type has such a reserved value. Formally, each specific pointer type ( int * , char * etc.) has its own dedicated null-pointer value. Conceptually, when a pointer has that null value it is not pointing anywhere."
},
{
"code": null,
"e": 147402,
"s": 147390,
"text": " Example :"
},
{
"code": null,
"e": 147421,
"s": 147402,
"text": "int * pInt = NULL;"
},
{
"code": null,
"e": 147691,
"s": 147421,
"text": "Waiting (Device) Queues: The set of processes waiting for allocation of certain I/Odevices is kept in the waiting (device) queue. The short-term scheduler (also known as CPU scheduling) selects a process from the ready queue and yields control of the CPU to the process"
},
{
"code": null,
"e": 147985,
"s": 147691,
"text": "marshalling is the process of gathering data from one or more application s or non-contiguous sources in computer storage, putting the data pieces into a message buffer , and organizing or converting the data into a format that is prescribed for a particular receiver or programming interface."
},
{
"code": null,
"e": 148190,
"s": 147985,
"text": "Trapdoor is a secret undocumented entry point into a program used to grant access without normal methods of access authentication. A trap is a software interrupt, usually the result of an error condition."
},
{
"code": null,
"e": 148372,
"s": 148190,
"text": "When a software testing performed without proper planning and documentation, it is said to be Adhoc Testing. Such kind of tests are executed only once unless we uncover the defects."
},
{
"code": null,
"e": 148752,
"s": 148372,
"text": "The tests are intended to be run only once, unless a defect is discovered. Adhoc testing is the least formal test method. As such, it has been criticized because it is not structured and hence defects found using this method may be harder to reproduce (since there are no written test cases). However, the strength of adhoc testing is that important defects can be found quickly."
},
{
"code": null,
"e": 149034,
"s": 148752,
"text": "Boundary testing or boundary value analysis, is where test cases are generated using the extremes of the input domain, e.g. maximum, minimum, just inside/outside boundaries, typical values, and error values. It is similar to Equivalence Partitioning but focuses on \"corner cases\" ."
},
{
"code": null,
"e": 149333,
"s": 149034,
"text": "Redundant array of inexpensive (or independent) disks. The main goal of raid technology is to even out the widely different rates of performance improvement of disks against those in memory and microprocessor. Raid technology employs the technique of data striping to achieve higher transfer rates."
},
{
"code": null,
"e": 149500,
"s": 149333,
"text": "DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks."
},
{
"code": null,
"e": 149763,
"s": 149500,
"text": "The general strategy in a Markov Algorithm is to take as input a string x and, through a number of steps in the algorithm, transform x to an output string y. this transformation process is generally performed in computers for text editing or program compilation."
},
{
"code": null,
"e": 149924,
"s": 149763,
"text": "These are the following arguments which are present in pattern matching Algorithms.\n1) Subject,\n2) Pattern\n3) Cursor\n4) MATCH_STR\n5) REPLACE_STR\n6) REPLACE_FLAG"
},
{
"code": null,
"e": 150024,
"s": 149924,
"text": "Packages are schema objects that groups logically related PL/SQL types, variables, and subprograms."
},
{
"code": null,
"e": 150066,
"s": 150024,
"text": "A package will have two mandatory parts −"
},
{
"code": null,
"e": 150088,
"s": 150066,
"text": "Package specification"
},
{
"code": null,
"e": 150117,
"s": 150088,
"text": "Package body or definition ."
},
{
"code": null,
"e": 150140,
"s": 150117,
"text": "Package Specification "
},
{
"code": null,
"e": 150233,
"s": 150140,
"text": "CREATE PACKAGE cust_sal AS \n PROCEDURE find_sal(c_id customers.id%type); \nEND cust_sal; \n/"
},
{
"code": null,
"e": 150246,
"s": 150233,
"text": "Package Body"
},
{
"code": null,
"e": 150550,
"s": 150246,
"text": "CREATE OR REPLACE PACKAGE BODY cust_sal AS \n \n PROCEDURE find_sal(c_id customers.id%TYPE) IS \n c_sal customers.salary%TYPE; \n BEGIN \n SELECT salary INTO c_sal \n FROM customers \n WHERE id = c_id; \n dbms_output.put_line('Salary: '|| c_sal); \n END find_sal; \nEND cust_sal; \n/"
},
{
"code": null,
"e": 150912,
"s": 150552,
"text": "Grep is an amazing utility on command line. Every one might have heard of grep. It's a great tool to search for a pattern with in a directory or in a file. On searching for a pattern using grep, the default result will print the pattern along with the line number at which the pattern is found. Grep is one of those handy commands on bash that are often used."
},
{
"code": null,
"e": 150936,
"s": 150912,
"text": "Pre requisites for grep"
},
{
"code": null,
"e": 151029,
"s": 150936,
"text": "Grep comes installed with an ubuntu machine, if it is not installed, it could be done using,"
},
{
"code": null,
"e": 151056,
"s": 151029,
"text": "sudo apt-get grep install;"
},
{
"code": null,
"e": 151071,
"s": 151056,
"text": "grep and egrep"
},
{
"code": null,
"e": 151253,
"s": 151071,
"text": "I have played around with grep for a while, at some point I have noticed egrep. grep and egrep does the same function, but the way they interpret the pattern is the only difference."
},
{
"code": null,
"e": 151521,
"s": 151253,
"text": "Grep stands for \"Global Regular Expressions Print\", were as Egrep for \"Extended Global Regular Expressions Print\". The pattern often treated as a regular expression, for which e in egrep stands for \"Extended Regular Expressions\" abbreviated 'ERE' is enabled in egrep."
},
{
"code": null,
"e": 151546,
"s": 151521,
"text": "grep -E is same as egrep"
},
{
"code": null,
"e": 151817,
"s": 151546,
"text": "In egrep, +, ?, |, (, and ), treated as meta characters. Where as in grep, they are rather treated as pattern instead of meta characters. By including 'backslash' followed by meta character can let the grep to treat it as meta characters like \\?, \\+, \\{, \\|, \\(, and \\)."
},
{
"code": null,
"e": 151838,
"s": 151817,
"text": "ls | grep '.txt|.php"
},
{
"code": null,
"e": 151976,
"s": 151838,
"text": "With the help of Apache Commons Net API, it is easy to write Java code for downloading a file from a remote FTP server to local computer."
},
{
"code": null,
"e": 151991,
"s": 151976,
"text": "Http Handlers:"
},
{
"code": null,
"e": 152354,
"s": 151991,
"text": "Http handlers are component developed by asp.net developers to work as end point to asp.net pipeline. It has to implement System.Web.IHttpHandler interface and this will act as target for asp.net requests. Handlers can be act as ISAPI dlls the only difference between ISAPI dlls and HTTP Handlers are Handlers can be called directly URL as compare to ISAPI Dlls."
},
{
"code": null,
"e": 152368,
"s": 152354,
"text": "Http Modules:"
},
{
"code": null,
"e": 152634,
"s": 152368,
"text": "Http modules are objects which also participate in the asp.net request pipeline but it does job after and before HTTP Handlers complete its work. For example it will associate a session and cache with asp.net request. It implements System.Web.IHttpModule interface."
},
{
"code": null,
"e": 152690,
"s": 152634,
"text": "HTTP Handler implement following Methods and Properties"
},
{
"code": null,
"e": 152965,
"s": 152690,
"text": "\nProcess Request: This method is called when processing asp.net requests. Here you can perform all the things related to processing request.\nIsReusable: This property is to determine whether same instance of HTTP Handler can be used to fulfill another request of same type.\n"
},
{
"code": null,
"e": 153105,
"s": 152965,
"text": "Process Request: This method is called when processing asp.net requests. Here you can perform all the things related to processing request."
},
{
"code": null,
"e": 153238,
"s": 153105,
"text": "IsReusable: This property is to determine whether same instance of HTTP Handler can be used to fulfill another request of same type."
},
{
"code": null,
"e": 153299,
"s": 153238,
"text": "Typical uses for custom HTTP handlers include the following:"
},
{
"code": null,
"e": 153591,
"s": 153299,
"text": "\nRSS feeds To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request.\n"
},
{
"code": null,
"e": 153881,
"s": 153591,
"text": "RSS feeds To create an RSS feed for a Web site, you can create a handler that emits RSS-formatted XML. You can then bind a file name extension such as .rss to the custom handler. When users send a request to your site that ends in .rss, ASP.NET calls your handler to process the request."
},
{
"code": null,
"e": 154073,
"s": 153881,
"text": "\nImage server If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler's response.\n"
},
{
"code": null,
"e": 154263,
"s": 154073,
"text": "Image server If you want a Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them to the user as the handler's response."
},
{
"code": null,
"e": 154316,
"s": 154263,
"text": "Typical uses for HTTP modules include the following:"
},
{
"code": null,
"e": 154659,
"s": 154316,
"text": "\nSecurity Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application.\n"
},
{
"code": null,
"e": 155000,
"s": 154659,
"text": "Security Because you can examine incoming requests, an HTTP module can perform custom authentication or other security checks before the requested page, XML Web service, or handler is called. In Internet Information Services (IIS) 7.0 running in Integrated mode, you can extend forms authentication to all content types in an application."
},
{
"code": null,
"e": 155188,
"s": 155000,
"text": "\nStatistics and logging Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages.\n"
},
{
"code": null,
"e": 155374,
"s": 155188,
"text": "Statistics and logging Because HTTP modules are called on every request, you can gather request statistics and log information in a centralized module, instead of in individual pages."
},
{
"code": null,
"e": 155552,
"s": 155374,
"text": "\nCustom headers or footers Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response.\n"
},
{
"code": null,
"e": 155728,
"s": 155552,
"text": "Custom headers or footers Because you can modify the outgoing response, you can insert content such as custom header information into every page or XML Web service response."
},
{
"code": null,
"e": 155737,
"s": 155728,
"text": "Features"
},
{
"code": null,
"e": 155793,
"s": 155737,
"text": "HTTP handler and module features include the following:"
},
{
"code": null,
"e": 155899,
"s": 155793,
"text": "\nThe IHttpHandler and IHttpModule interfaces are the starting point for developing handlers and modules.\n"
},
{
"code": null,
"e": 156003,
"s": 155899,
"text": "The IHttpHandler and IHttpModule interfaces are the starting point for developing handlers and modules."
},
{
"code": null,
"e": 156097,
"s": 156003,
"text": "\nThe IHttpAsyncHandler interface is the starting point for developing asynchronous handlers.\n"
},
{
"code": null,
"e": 156189,
"s": 156097,
"text": "The IHttpAsyncHandler interface is the starting point for developing asynchronous handlers."
},
{
"code": null,
"e": 156349,
"s": 156189,
"text": "\nCustom handler and module source code can be put in the App_Code folder of an application, or it can be compiled and put in the Bin folder of an application.\n"
},
{
"code": null,
"e": 156507,
"s": 156349,
"text": "Custom handler and module source code can be put in the App_Code folder of an application, or it can be compiled and put in the Bin folder of an application."
},
{
"code": null,
"e": 156608,
"s": 156507,
"text": "\nHandlers and modules developed for use in IIS 6.0 can be used in IIS 7.0 with little or no change.\n"
},
{
"code": null,
"e": 156707,
"s": 156608,
"text": "Handlers and modules developed for use in IIS 6.0 can be used in IIS 7.0 with little or no change."
},
{
"code": null,
"e": 156754,
"s": 156709,
"text": "LockObjects always starts with character 'E'"
},
{
"code": null,
"e": 157154,
"s": 156754,
"text": "The static identifier is used for initializing only once, and the value retains during the life time of the program / application. A separate memory is allocated for static variables. This value can be used between function calls. The default value of an un initialized static variable is zero. A function can also be defined as a static function, which has the same scope of the static variable ."
},
{
"code": null,
"e": 157345,
"s": 157154,
"text": "Most of the times when we are developing an application in java, we often feel a need to create and throw our own exceptions. These exceptions are known as User defined or Custom exceptions."
},
{
"code": null,
"e": 157398,
"s": 157345,
"text": "Let's see a simple example of java custom exception."
},
{
"code": null,
"e": 157502,
"s": 157398,
"text": "class InvalidAgeException extends Exception{ \n InvalidAgeException(String s){ \n super(s); \n } \n} "
},
{
"code": null,
"e": 157555,
"s": 157504,
"text": "There are 5 operators which cannot be overloaded :"
},
{
"code": null,
"e": 157694,
"s": 157555,
"text": "\n.* - class member access operator \n\n:: - scope resolution operator \n\n. - dot operator \n\n?:: - conditional operator \n\nSizeof() - operator "
},
{
"code": null,
"e": 158029,
"s": 157694,
"text": "Macro execution is faster than function execution because in function, much of time is used to take control from function call to called function and much of time is spent in this process. Whereas in macro expression are directly replaced in the source code.Much of time is spent in the binding of the function to the caller function."
},
{
"code": null,
"e": 158408,
"s": 158031,
"text": "The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.The DOM provides a representation of the document as a structured group of nodes and objects that have properties and methods. Essentially, it connects web pages to scripts or programming languages."
},
{
"code": null,
"e": 158640,
"s": 158410,
"text": "Microsoft SQL Server Profiler is a graphical user interface to SQL Trace for monitoring an instance of the Database Engine or Analysis Services. You can capture and save data about each event to a file or table to analyze later ."
},
{
"code": null,
"e": 158807,
"s": 158640,
"text": " SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as which SQL Scripts are running, failed jobs etc."
},
{
"code": null,
"e": 158923,
"s": 158807,
"text": "SQL> delete from table_name where rowid not in (select max(rowid) from table group by duplicate_values_field_name);"
},
{
"code": null,
"e": 158976,
"s": 158923,
"text": "structure :- In structure have a by default public. "
},
{
"code": null,
"e": 159012,
"s": 158976,
"text": "In class have a by default private."
},
{
"code": null,
"e": 159062,
"s": 159012,
"text": " Structure cannot be inherited. But class can be "
},
{
"code": null,
"e": 159071,
"s": 159062,
"text": "inherit."
},
{
"code": null,
"e": 159117,
"s": 159071,
"text": " There is no data hiding features comes with "
},
{
"code": null,
"e": 159172,
"s": 159117,
"text": "structures. Classes do, private, protected and public."
},
{
"code": null,
"e": 159677,
"s": 159172,
"text": "\nWhen deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.\n\tFor example program 3 fails in compilation and program 4 works fine.\n// Program 3\n#include <stdio.h>\n \nclass Base {\npublic:\n int x;\n};\n \nclass Derived : Base { }; // is equilalent to class Derived : private Base {}\n \nint main()\n{\n Derived d;\n d.x = 20; // compiler error becuase inheritance is private\n getchar();\n return 0;\n}\n"
},
{
"code": null,
"e": 159915,
"s": 159677,
"text": "When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.\n\tFor example program 3 fails in compilation and program 4 works fine."
},
{
"code": null,
"e": 159928,
"s": 159915,
"text": "// Program 3"
},
{
"code": null,
"e": 159947,
"s": 159928,
"text": "#include <stdio.h>"
},
{
"code": null,
"e": 159962,
"s": 159949,
"text": "class Base {"
},
{
"code": null,
"e": 159970,
"s": 159962,
"text": "public:"
},
{
"code": null,
"e": 159981,
"s": 159970,
"text": " int x;"
},
{
"code": null,
"e": 159984,
"s": 159981,
"text": "};"
},
{
"code": null,
"e": 160064,
"s": 159986,
"text": "class Derived : Base { }; // is equilalent to class Derived : private Base {}"
},
{
"code": null,
"e": 160077,
"s": 160066,
"text": "int main()"
},
{
"code": null,
"e": 160079,
"s": 160077,
"text": "{"
},
{
"code": null,
"e": 160092,
"s": 160079,
"text": " Derived d;"
},
{
"code": null,
"e": 160153,
"s": 160092,
"text": " d.x = 20; // compiler error becuase inheritance is private"
},
{
"code": null,
"e": 160166,
"s": 160153,
"text": " getchar();"
},
{
"code": null,
"e": 160178,
"s": 160166,
"text": " return 0;"
},
{
"code": null,
"e": 160180,
"s": 160178,
"text": "}"
},
{
"code": null,
"e": 160418,
"s": 160186,
"text": "Stack unwinding is a process of calling all destructors for all automatic objects constructed at run time when an exception is thrown. Destructors are called between the places where the exception was thrown and where it is caught."
},
{
"code": null,
"e": 160481,
"s": 160418,
"text": "for detail :http://www.geeksforgeeks.org/stack-unwinding-in-c/"
},
{
"code": null,
"e": 160709,
"s": 160481,
"text": "XML is case sensitive when uppercase and lowercase characters are treated differently.\nElement type names, Attribute names, Attribute values, All general and parameter entity names, and data content (text), are case-sensitive. "
},
{
"code": null,
"e": 160810,
"s": 160709,
"text": "Project plan, Requirements, Design, Coding, Testing, Re-coding and design, Development, Maintenance."
},
{
"code": null,
"e": 161122,
"s": 160810,
"text": "An Internet Protocol address (IP address) is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication.An IP address serves two principal functions: host or network interface identification and location addressing ."
},
{
"code": null,
"e": 161388,
"s": 161122,
"text": "Portability focuses on adaptation of software in various OS, by recompiling the source to make the binary compatible with the target OS and not necessarily modifying the source. If the source code strictly follows POSIX standard less likely one end up modifying it."
},
{
"code": null,
"e": 161613,
"s": 161388,
"text": "Platform independence focuses on ability of software to run on VIRTUAL hardware that inturn interfaces with the PHYSICAL hardware. Examples of cross-platform or platform independent languages are Python, JavaScript, Java etc"
},
{
"code": null,
"e": 161788,
"s": 161613,
"text": "An interrupt is a signal from a device attached to a computer or from a program within the computer that requires the operating system to stop and figure out what to do next."
},
{
"code": null,
"e": 162099,
"s": 161788,
"text": "The processor responds by suspending its current activities, saving its state, and executing a function called an interrupt handler (or an interrupt service routine, ISR) to deal with the event. This interruption is temporary, and, after the interrupt handler finishes, the processor resumes normal activities."
},
{
"code": null,
"e": 162342,
"s": 162099,
"text": "Static is an access qualifier. If a variable is declared as static inside a function, the scope is limited to the function,but it will exists for the life time of the program. Values will be persisted between successive \ncalls to a function ."
},
{
"code": null,
"e": 162356,
"s": 162342,
"text": "For example :"
},
{
"code": null,
"e": 162536,
"s": 162362,
"text": "#include<stdio.h>\n\nint fun()\n\n{\n\n static int count = 0;\n\n count++;\n\n return count;\n\n}\n\n \n\nint main()\n\n{\n\n printf(\"%d \", fun());\n\n printf(\"%d \", fun());\n\n return 0;\n\n}"
},
{
"code": null,
"e": 162546,
"s": 162538,
"text": "Output:"
},
{
"code": null,
"e": 162550,
"s": 162546,
"text": "1 2"
},
{
"code": null,
"e": 162678,
"s": 162550,
"text": "An enumeration is a user-defined data type that consists of integral constants. To define an enumeration, keyword enum is used."
},
{
"code": null,
"e": 162721,
"s": 162678,
"text": "enum flag { const1, const2, ..., constN };"
},
{
"code": null,
"e": 163461,
"s": 162723,
"text": "Garbage collection is the systematic recovery of pooled computer storage that is being used by a program when that program no longer needs the storage. This frees the storage for use by other programs \n(or processes within a program). It also ensures that a program using increasing amounts of pooled storage does not reach its quota (in which case it may no longer be able to function). \n\nGarbage collection is an automatic memory management feature in many modern programming languages, such as Java and languages in the .NET framework. Languages that use garbage collection are often interpreted or run within a virtual machine like the JVM. In each case, the environment that runs the code is also responsible for garbage collection."
},
{
"code": null,
"e": 163771,
"s": 163461,
"text": "A spanning tree is a subset of Graph G, which has all the vertices covered with minimum possible number of edges. Hence, a spanning tree does not have cycles and it cannot be disconnected.. By this definition, we can draw a conclusion that every connected and undirected Graph G has at least one spanning tree"
},
{
"code": null,
"e": 164234,
"s": 163771,
"text": "A friend function for a class is used in object-oriented programming to allow access to public, private, or protected data in the class from the outside.\nNormally, a function that is not a member of a class cannot access such information; neither can an external class. Occasionally, such access will be advantageous for the programmer. Under these circumstances, the function or external class can be declared as a friend of the class using the friend keyword ."
},
{
"code": null,
"e": 164334,
"s": 164234,
"text": "ifdef means \"if the following is defined\" while ifndef means \"if the following is not defined\". So:"
},
{
"code": null,
"e": 164346,
"s": 164334,
"text": "#define one"
},
{
"code": null,
"e": 164385,
"s": 164346,
"text": " #ifdef one printf(\"one is defined \");"
},
{
"code": null,
"e": 164435,
"s": 164385,
"text": "#endif #ifndef one printf(\"one is not defined \");"
},
{
"code": null,
"e": 164488,
"s": 164435,
"text": "#endif. is equivalent to: printf(\"one is defined \");"
},
{
"code": null,
"e": 164618,
"s": 164488,
"text": "The keyword delete is used to destroy the single variable memory created dynamically which is pointed by single pointer variable."
},
{
"code": null,
"e": 164849,
"s": 164618,
"text": "Eg: int *r=new(int)\nthe memory pointed by r can be deleted by delete r.\ndelete [] is used to destroy array of memory pointed by single pointer variable.\nEg:int *r=new(int a[10])\nThe memory pointed by r can be deleted by delete []."
},
{
"code": null,
"e": 165009,
"s": 164849,
"text": "Alignment refers to the arrangement of data in memory, and specifically deals with the issue of accessing data as proper units of information from main memory."
},
{
"code": null,
"e": 165187,
"s": 165009,
"text": "Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. "
},
{
"code": null,
"e": 165508,
"s": 165189,
"text": "A Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a Java program. There are three notions of the JVM: specification, implementation, and instance. ... An instance of a JVM is an implementation running in a process that executes a computer program compiled into Java bytecode."
},
{
"code": null,
"e": 165757,
"s": 165508,
"text": "A debugger is a computer program used by programmers to test and debug a target program. Debuggers may use instruction-set simulators, rather than running a program directly on the processor to achieve a higher level of control over its execution. "
},
{
"code": null,
"e": 165889,
"s": 165757,
"text": "Getting the arguments from command prompt in c is known as command line arguments. In c main function has three arguments.They are:"
},
{
"code": null,
"e": 165941,
"s": 165889,
"text": "Argument counter\nArgument vector\nEnvironment vector"
},
{
"code": null,
"e": 166312,
"s": 165941,
"text": "The two types of integrity rules are referential integrity rules and entity integrity rules. Referential integrity rules dictate that a database does not contain orphan foreign key values. This means that \nA primary key value cannot be modified if the value is used as a foreign key in a child table. Entity integrity dictates that the primary key value cannot be Null."
},
{
"code": null,
"e": 166611,
"s": 166312,
"text": "inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables."
},
{
"code": null,
"e": 166835,
"s": 166611,
"text": "A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look like when they are used."
},
{
"code": null,
"e": 166845,
"s": 166835,
"text": "Example :"
},
{
"code": null,
"e": 167103,
"s": 166845,
"text": "#include <stdio.h>\n#define PI 3.1415\n#define circleArea(r) (PI*r*r)\n \nint main()\n{\n int radius;\n float area;\n \n printf(\"Enter the radius: \");\n scanf(\"%d\", &radius);\n area = circleArea(radius);\n printf(\"Area = %.2f\", area);\n \n return 0;\n"
},
{
"code": null,
"e": 167140,
"s": 167105,
"text": "%p in printf to print the address."
},
{
"code": null,
"e": 167356,
"s": 167140,
"text": "Product based company : company/group which makes some product may it software, hardware or any other. Also it's not compulsive that, company sell their product. Only requirement is that company should make product."
},
{
"code": null,
"e": 167618,
"s": 167356,
"text": "Service based company : company which ability/offer services to their clients. They don't make anything. Just provide services. For example printer service they don't make printer not cartige nor ink but offer service to customers of refilling cartige, ink etc."
},
{
"code": null,
"e": 168022,
"s": 167618,
"text": "\nProject can be anything. On anything.\nDeadlines are mostly defined by clients.\nLess innovation and flexibility.\nMore strictness and mutil tasking.\nClient will be dissatisfied mostly.\nYou would get expert on the language u are working. But you cannot learn new. Because u dont have time.\nIn case of small scale, company might fire you on the basis of no new projects or clients saying of ur performance\n"
},
{
"code": null,
"e": 168060,
"s": 168022,
"text": "Project can be anything. On anything."
},
{
"code": null,
"e": 168101,
"s": 168060,
"text": "Deadlines are mostly defined by clients."
},
{
"code": null,
"e": 168134,
"s": 168101,
"text": "Less innovation and flexibility."
},
{
"code": null,
"e": 168169,
"s": 168134,
"text": "More strictness and mutil tasking."
},
{
"code": null,
"e": 168205,
"s": 168169,
"text": "Client will be dissatisfied mostly."
},
{
"code": null,
"e": 168309,
"s": 168205,
"text": "You would get expert on the language u are working. But you cannot learn new. Because u dont have time."
},
{
"code": null,
"e": 168424,
"s": 168309,
"text": "In case of small scale, company might fire you on the basis of no new projects or clients saying of ur performance"
},
{
"code": null,
"e": 168553,
"s": 168424,
"text": "The third normal form (3NF) is a normal form used in database normalization. ... Codd's definition states that a table is in 3NF"
},
{
"code": null,
"e": 168609,
"s": 168553,
"text": " if and only if both of the following conditions hold: "
},
{
"code": null,
"e": 168663,
"s": 168609,
"text": "The relation R (table) is in second normal form (2NF)"
},
{
"code": null,
"e": 168743,
"s": 168663,
"text": "Every non-prime attribute of R is non-transitively dependent on every key of R."
},
{
"code": null,
"e": 168858,
"s": 168743,
"text": "For example, in the following table – the street name, city and the state are unbreakably bound to their zip code."
},
{
"code": null,
"e": 169176,
"s": 168858,
"text": "CREATE TABLE CUSTOMERS(\n CUST_ID INT NOT NULL,\n CUST_NAME VARCHAR (20) NOT NULL,\n DOB DATE,\n STREET VARCHAR(200),\n CITY VARCHAR(100),\n STATE VARCHAR(100),\n ZIP VARCHAR(12),\n EMAIL_ID VARCHAR(256),\n PRIMARY KEY (CUST_ID)\n);"
},
{
"code": null,
"e": 169438,
"s": 169176,
"text": "The dependency between the zip code and the address is called as a transitive dependency. To comply with the third normal form, all you need to do is to move the Street, City and the State fields into their own table, which you can call as the Zip Code table. −"
},
{
"code": null,
"e": 169607,
"s": 169438,
"text": "CREATE TABLE ADDRESS(\n ZIP VARCHAR(12),\n STREET VARCHAR(200),\n CITY VARCHAR(100),\n STATE VARCHAR(100),\n PRIMARY KEY (ZIP)\n);"
},
{
"code": null,
"e": 169777,
"s": 169609,
"text": "JSP is a webpage scripting language that can generate dynamic content while Servlets are Java programs that are already compiled which also creates dynamic web content"
},
{
"code": null,
"e": 169815,
"s": 169777,
"text": "Servlets run faster compared to JSP ."
},
{
"code": null,
"e": 169942,
"s": 169815,
"text": "JSP is a technology that allows you to write dynamic HTTP response with static data mixed with dynamic data with special tags."
},
{
"code": null,
"e": 170032,
"s": 169942,
"text": "Servlet is a technology that allows you to write dynamic HTTP response with a Java class."
},
{
"code": null,
"e": 170116,
"s": 170032,
"text": "Servlet will accept all protocol request but JSP only accept http protocol request."
},
{
"code": null,
"e": 170388,
"s": 170118,
"text": "Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages through the use of servlets, small programs that are specified in the Web page and run on the Web server to modify the Web page before it is sent to the user who requested it."
},
{
"code": null,
"e": 170568,
"s": 170388,
"text": "A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs."
},
{
"code": null,
"e": 170813,
"s": 170568,
"text": "JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing Java Beans components, passing control between pages, and sharing information between requests, pages etc."
},
{
"code": null,
"e": 170903,
"s": 170813,
"text": "Following diagram shows the position of JSP container and JSP files in a Web application."
},
{
"code": null,
"e": 171013,
"s": 170903,
"text": "Servlet technology is used to create web application (resides at server side and generates dynamic web page)."
},
{
"code": null,
"e": 171266,
"s": 171013,
"text": "A servlet is a Web component that is managed by a container and generates dynamic content. Servlets are Java classes that are compiled to byte code that can be loaded dynamically into and run by a Java technology-enabled Web server or Servlet container"
},
{
"code": null,
"e": 171331,
"s": 171266,
"text": "Servlet can be described in many ways, depending on the context."
},
{
"code": null,
"e": 171392,
"s": 171331,
"text": "Servlet is a technology i.e. used to create web application."
},
{
"code": null,
"e": 171478,
"s": 171392,
"text": "Servlet is an API that provides many interfaces and classes including documentations."
},
{
"code": null,
"e": 171553,
"s": 171478,
"text": "Servlet is an interface that must be implemented for creating any servlet."
},
{
"code": null,
"e": 171907,
"s": 171553,
"text": "Encoding:\n\nEncoding is the process of converting data into various formats in which to be used on a different device or system. The encoding process uses publicly available methods in which to transform data. An encoding method could be used to convert Base 10 (binary) data into Base 16 (hex).\n\nExample: Changing data type from ASCII to UTF.\n "
},
{
"code": null,
"e": 172316,
"s": 171907,
"text": "Encryption:\n\nEncryption is the process of scrambling data to make it decipherable only by the intended recipients. Typically, the recipients who are authorized to view the data are provided a matching key string in which the data was encrypted with, they then apply the secret key to the scrambled data and convert it back into clear text.\n\nExample: Sending sensitive information over public medium."
},
{
"code": null,
"e": 172458,
"s": 172316,
"text": "Encoding is for maintaining data usability and can be reversed by employing the same algorithm that encoded the content, i.e. no key is used."
},
{
"code": null,
"e": 172587,
"s": 172458,
"text": "Encryption is for maintaining data confidentiality and requires the use of a key (kept secret) in order to return to plain text."
},
{
"code": null,
"e": 172842,
"s": 172587,
"text": "A software requirements specification (SRS) is a description of a software system to be developed. It lays out functional and non-functional requirements, and may include a set of use cases that describe user interactions that the software must provide ."
},
{
"code": null,
"e": 172978,
"s": 172842,
"text": " This document lays a foundation for software engineering activities and is created when entire requirements are elicited and analyzed."
},
{
"code": null,
"e": 172990,
"s": 172978,
"text": "Advantages "
},
{
"code": null,
"e": 173113,
"s": 172990,
"text": "Software SRS establishes the basic for agreement between the client and the supplier on what the software product will do."
},
{
"code": null,
"e": 173185,
"s": 173115,
"text": "1. A SRS provides a reference for validation of the final product."
},
{
"code": null,
"e": 173254,
"s": 173185,
"text": "2. A high-quality SRS is a prerequisite to high-quality software."
},
{
"code": null,
"e": 173310,
"s": 173254,
"text": "3. A high-quality SRS reduces the development cost. "
},
{
"code": null,
"e": 173336,
"s": 173310,
"text": "Characteristics of an SRS"
},
{
"code": null,
"e": 173355,
"s": 173338,
"text": "1. Correct"
},
{
"code": null,
"e": 173373,
"s": 173355,
"text": "2. Complete"
},
{
"code": null,
"e": 173394,
"s": 173373,
"text": "3. Unambiguous"
},
{
"code": null,
"e": 173414,
"s": 173394,
"text": "4. Verifiable"
},
{
"code": null,
"e": 173434,
"s": 173414,
"text": "5. Consistent"
},
{
"code": null,
"e": 173482,
"s": 173434,
"text": "6. Ranked for importance and/or stability"
},
{
"code": null,
"e": 173502,
"s": 173482,
"text": "7. Modifiable"
},
{
"code": null,
"e": 173521,
"s": 173502,
"text": "8. Traceable"
},
{
"code": null,
"e": 173760,
"s": 173521,
"text": "WHERE clause introduces a condition on individual rows; HAVING clause introduces a condition on aggregations, i.e. results of selection where a single result, such as count, average, min, max, or sum, has been produced from multiple rows."
},
{
"code": null,
"e": 174013,
"s": 173760,
"text": "Apart from SELECT queries, you can use WHERE clause with UPDATE and DELETE clause but HAVING clause can only be used with SELECT query. For example following query, which involve WHERE clause will work but other which uses HAVING clause will not work ."
},
{
"code": null,
"e": 174119,
"s": 174013,
"text": "A WHERE clause is used is filter records from a result. The filter occurs before any groupings are made."
},
{
"code": null,
"e": 174174,
"s": 174119,
"text": "A HAVING clause is used to filter values from a group."
},
{
"code": null,
"e": 174239,
"s": 174174,
"text": "WHERE is used to filter records before any groupings take place."
},
{
"code": null,
"e": 174394,
"s": 174239,
"text": "HAVING is used to filter values after they have been groups. Only columns or expression in the group can be included in the HAVING clause’s conditions.."
},
{
"code": null,
"e": 174690,
"s": 174396,
"text": "Computer data interchange format used mainly as a datastorage and network transfer format in the MongoDB database. It is a binary form for representing simple data structures, associative arrays (called objects or documents in MongoDB), and various data types of specific interest to MongoDB ."
},
{
"code": null,
"e": 174819,
"s": 174690,
"text": "Normalization is a database design technique which organizes tables in a manner that reduces redundancy and dependency of data ."
},
{
"code": null,
"e": 174961,
"s": 174819,
"text": "Normalization is a process of organizing the data in database to avoid data redundancy, insertion anomaly, update anomaly & deletion anomaly."
},
{
"code": null,
"e": 175162,
"s": 174961,
"text": "Normalization in DBMS: 1NF, 2NF, 3NF and BCNF in Database. Normalization is a process of organizing the data in database to avoid data redundancy, insertion anomaly, update anomaly & deletion anomaly."
},
{
"code": null,
"e": 175422,
"s": 175162,
"text": "In computing, the star schema is the simplest style of data mart schema and is the approach most widely used to develop data warehouses and dimensional data marts. The star schema consists of one or more fact tables referencing any number of dimension tables."
},
{
"code": null,
"e": 175885,
"s": 175422,
"text": "GET method sends the data in the form of key-value pairs in the URL. This is a serious security flaw as anyone can then send data to your server by just typing out the URL in the address bar and altering data in the server, unless you have extra security measures like CSRF tokens, cookies etc.\n\nPOST method does not send the data through the URLs. Therefore, web requests cannot be spoofed through the URLs.\n\nHence, it is a better practice to use GET over POST."
},
{
"code": null,
"e": 176178,
"s": 175885,
"text": "maintainability is defined as the degree to which an application is understood, repaired, or enhanced. ... Understanding software maintainability allows organizations to identify improvement areas as well as determine the value supplied by current applications or during development changes ."
},
{
"code": null,
"e": 176383,
"s": 176178,
"text": "compatibility (countable and uncountable, plural compatibilities) The state of being compatible; in which two or more things are able to exist or work together in combination without problems or conflict."
},
{
"code": null,
"e": 176636,
"s": 176383,
"text": "Modularity is the degree to which a system's components may be separated and recombined. The meaning of the word, however, can vary somewhat by context. In biology,modularity is the concept that organisms or metabolic pathways are composed of modules ."
},
{
"code": null,
"e": 176881,
"s": 176636,
"text": "A public key infrastructure (PKI) supports the distribution and identification of public encryption keys, enabling users and computers to both securely exchange data over networks such as the Internet and verify the identity of the other party."
},
{
"code": null,
"e": 177061,
"s": 176881,
"text": "The purpose of a PKI is to facilitate the secure electronic transfer of information for a range of network activities such as e-commerce, internet banking and confidential email. "
},
{
"code": null,
"e": 177112,
"s": 177061,
"text": "A typical PKI includes the following key elements:"
},
{
"code": null,
"e": 177290,
"s": 177112,
"text": "A trusted party, called a certificate authority (CA), acts as the root of trust and provides services that authenticate the identity of individuals, computers and other entities"
},
{
"code": null,
"e": 177432,
"s": 177290,
"text": "A registration authority, often called a subordinate CA, certified by a root CA to issue certificates for specific uses permitted by the root"
},
{
"code": null,
"e": 177528,
"s": 177432,
"text": "A certificate database, which stores certificate requests and issues and revokes certificates ."
},
{
"code": null,
"e": 177816,
"s": 177528,
"text": "Load balancing is dividing the amount of work that a computer has to do between two or more computers so that more work gets done in the same amount of time and, in general, all users get served faster. Load balancing can be implemented with hardware, software, or a combination of both."
},
{
"code": null,
"e": 178112,
"s": 177816,
"text": "A load balancer acts as the “traffic cop” sitting in front of your servers and routing client requests across all servers capable of fulfilling those requests in a manner that maximizes speed and capacity utilization and ensures that no one server is overworked, which could degrade performance."
},
{
"code": null,
"e": 178244,
"s": 178112,
"text": "Load balancing usually involves dedicated software or hardware, such as a multilayer switch or a Domain Name System server process."
},
{
"code": null,
"e": 178294,
"s": 178244,
"text": "a load balancer performs the following functions:"
},
{
"code": null,
"e": 178374,
"s": 178294,
"text": "Distributes client requests or network load efficiently across multiple servers"
},
{
"code": null,
"e": 178468,
"s": 178374,
"text": "Ensures high availability and reliability by sending requests only to servers that are online"
},
{
"code": null,
"e": 178750,
"s": 178468,
"text": "Black-box testing is a method of software testing that examines the functionality of an application without peering into its internal structures or workings. This method of test can be applied virtually to every level of software testing: unit, integration, system and acceptance ."
},
{
"code": null,
"e": 178968,
"s": 178750,
"text": "This method of test can be applied virtually to every level of software testing: unit, integration,system and acceptance. It typically comprises most if not all higher level testing, but can also embody unit testing ."
},
{
"code": null,
"e": 179163,
"s": 178968,
"text": "his method is named so because the software program, in the eyes of the tester, is like a black box; inside which one cannot see. This method attempts to find errors in the following categories:"
},
{
"code": null,
"e": 179194,
"s": 179163,
"text": "Incorrect or missing functions"
},
{
"code": null,
"e": 179211,
"s": 179194,
"text": "Interface errors"
},
{
"code": null,
"e": 179265,
"s": 179211,
"text": "Errors in data structures or external database access"
},
{
"code": null,
"e": 179298,
"s": 179265,
"text": "Behavior or performance errors ."
},
{
"code": null,
"e": 179330,
"s": 179298,
"text": "Behavioural Testing Techniques:"
},
{
"code": null,
"e": 179392,
"s": 179330,
"text": "There are different techniques involved in Black Box testing."
},
{
"code": null,
"e": 179412,
"s": 179392,
"text": "\nEquivalence Class\n"
},
{
"code": null,
"e": 179430,
"s": 179412,
"text": "Equivalence Class"
},
{
"code": null,
"e": 179456,
"s": 179430,
"text": "\nBoundary Value Analysis\n"
},
{
"code": null,
"e": 179480,
"s": 179456,
"text": "Boundary Value Analysis"
},
{
"code": null,
"e": 179495,
"s": 179480,
"text": "\nDomain Tests\n"
},
{
"code": null,
"e": 179508,
"s": 179495,
"text": "Domain Tests"
},
{
"code": null,
"e": 179528,
"s": 179508,
"text": "\nOrthogonal Arrays\n"
},
{
"code": null,
"e": 179546,
"s": 179528,
"text": "Orthogonal Arrays"
},
{
"code": null,
"e": 179564,
"s": 179546,
"text": "\nDecision Tables\n"
},
{
"code": null,
"e": 179580,
"s": 179564,
"text": "Decision Tables"
},
{
"code": null,
"e": 179595,
"s": 179580,
"text": "\nState Models\n"
},
{
"code": null,
"e": 179608,
"s": 179595,
"text": "State Models"
},
{
"code": null,
"e": 179880,
"s": 179608,
"text": "White-box testing (also known as clear box testing, glass box testing, transparent box testing, and structural testing) is a method of testing software that tests internal structures or workings of an application, as opposed to its functionality (i.e. black-box testing)."
},
{
"code": null,
"e": 180104,
"s": 179880,
"text": " In white-box testing an internal perspective of the system, as well as programming skills, are used to design test cases. The tester chooses inputs to exercise paths through the code and determine the appropriate outputs ."
},
{
"code": null,
"e": 180363,
"s": 180104,
"text": "Typically such method are used at Unit Testing of the code but this different as Unit testing done by the developer & White Box Testing done by the testers, this is learning the part of the code & finding out the weakness in the software program under test ."
},
{
"code": null,
"e": 180393,
"s": 180363,
"text": "White Box Testing Techniques:"
},
{
"code": null,
"e": 180501,
"s": 180393,
"text": "\nStatement Coverage - This technique is aimed at exercising all programming statements with minimal tests.\n"
},
{
"code": null,
"e": 180607,
"s": 180501,
"text": "Statement Coverage - This technique is aimed at exercising all programming statements with minimal tests."
},
{
"code": null,
"e": 180725,
"s": 180607,
"text": "\nBranch Coverage - This technique is running a series of tests to ensure that all branches are tested at least once.\n"
},
{
"code": null,
"e": 180841,
"s": 180725,
"text": "Branch Coverage - This technique is running a series of tests to ensure that all branches are tested at least once."
},
{
"code": null,
"e": 180971,
"s": 180841,
"text": "\nPath Coverage - This technique corresponds to testing all possible paths which means that each statement and branch is covered.\n"
},
{
"code": null,
"e": 181099,
"s": 180971,
"text": "Path Coverage - This technique corresponds to testing all possible paths which means that each statement and branch is covered."
},
{
"code": null,
"e": 181247,
"s": 181099,
"text": "IPv4 and IPv6 are two generations of Internet Protocols where IPv4 stands for Internet Protocol version 4 and IPv6 for Internet Protocol version 6."
},
{
"code": null,
"e": 181571,
"s": 181247,
"text": "IPv6 is more advanced and has better features compared to IPv4. It has the capability to provide an infinite number of addresses. It is replacing IPv4 to accommodate the growing number of networks worldwide and help solve the IP address exhaustion problem. IPv6 was developed by the Internet Engineering Task Force (IETF) ."
},
{
"code": null,
"e": 181746,
"s": 181571,
"text": "One of the main difference between IPv4 and IPv6 is their address space. As we already said the size of an address in IPv4 is 32-bits. Where IPv6 address fields are 128-bits."
},
{
"code": null,
"e": 181823,
"s": 181746,
"text": "Checksum field is available in IPv4 header.No checksum field in IPv6 header."
},
{
"code": null,
"e": 181987,
"s": 181823,
"text": "IPv4 Internet Group Management Protocol (IGMP) is used to manage multicast group membership.IPv6 IGMP is replaced with Multicast Listener Discovery (MLD) messages."
},
{
"code": null,
"e": 182016,
"s": 181987,
"text": "Advantages of IPv6 over IPv4"
},
{
"code": null,
"e": 182068,
"s": 182016,
"text": "IPv6 simplified the router’s task compared to IPv4."
},
{
"code": null,
"e": 182122,
"s": 182068,
"text": "IPv6 is more compatible to mobile networks than IPv4."
},
{
"code": null,
"e": 182184,
"s": 182122,
"text": "IPv6 allows for bigger payloads than what is allowed in IPv4."
},
{
"code": null,
"e": 182279,
"s": 182184,
"text": "IPv6 is used by less than 1% of the networks, while IPv4 is still in use by the remaining 99%."
},
{
"code": null,
"e": 182604,
"s": 182279,
"text": "Network Address Translation (NAT) is the process where a network device, usually a firewall, assigns a public address to a computer (or group of computers) inside a private network. The main use of NAT is to limit the number of public IP addresses an organization or company must use, for both economy and security purposes."
},
{
"code": null,
"e": 182802,
"s": 182604,
"text": "NAT conserves the number of globally valid IP addresses a company needs, and in combination with Classless Inter-Domain Routing (CIDR) has done a lot to extend the useful life of IPv4 as a result ."
},
{
"code": null,
"e": 182821,
"s": 182802,
"text": "The Purpose of NAT"
},
{
"code": null,
"e": 182853,
"s": 182821,
"text": "NAT serves three main purposes:"
},
{
"code": null,
"e": 182910,
"s": 182853,
"text": "Provides a type of firewall hiding internal IP addresses"
},
{
"code": null,
"e": 183095,
"s": 182910,
"text": "Enables a company to use more internal IP addresses. Since they're used internally only, there's no possibility of conflict with IP addresses used by other companies and organizations."
},
{
"code": null,
"e": 183185,
"s": 183095,
"text": "Allows a company to combine multiple ISDN connections into a single Internet connection ."
},
{
"code": null,
"e": 183452,
"s": 183185,
"text": "A race condition is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time, but because of the nature of the device or system, the operations must be done in the proper sequence to be done correctly ."
},
{
"code": null,
"e": 183598,
"s": 183452,
"text": "A Job scheduling system allows one process to use the CPU while another is waiting for I/O, thereby making full use of otherwise lost CPU cycles."
},
{
"code": null,
"e": 183838,
"s": 183598,
"text": "The challenge is to make the overall system as \"efficient\" and \"fair\" as possible, subject to varying and often dynamic conditions, and where \"efficient\" and \"fair\" are somewhat subjective terms, often subject to shifting priority policy ."
},
{
"code": null,
"e": 184149,
"s": 183838,
"text": "A Job scheduling is the method by which work specified by some means is assigned to resources that complete the work. The work may be virtual computation elements such as threads, processes or data flows, which are in turn scheduled onto hardware resources such as processors, network links or expansion cards."
},
{
"code": null,
"e": 184376,
"s": 184151,
"text": "Eavesdropping :the majority of network communications occur in an unsecured or \"clear text\" format, which allows an attacker who has gained access to data paths in your network to \"listen in\" or interpret (read) the traffic."
},
{
"code": null,
"e": 184591,
"s": 184376,
"text": "\nDenial-of-Service Attack :Randomize the attention of your internal Information Systems staff so that they do not see the intrusion immediately, which allows the attacker to make more attacks during the diversion.\n"
},
{
"code": null,
"e": 184804,
"s": 184591,
"text": "Denial-of-Service Attack :Randomize the attention of your internal Information Systems staff so that they do not see the intrusion immediately, which allows the attacker to make more attacks during the diversion."
},
{
"code": null,
"e": 184848,
"s": 184804,
"text": "\nModification Attacks Changing Information\n"
},
{
"code": null,
"e": 184890,
"s": 184848,
"text": "Modification Attacks Changing Information"
},
{
"code": null,
"e": 184942,
"s": 184890,
"text": " Example: We just modified your HomePage!"
},
{
"code": null,
"e": 185182,
"s": 184942,
"text": "\nTrojan Horses :A Trojan horse or Trojan is a file or e-mail attachment disguised as a friendly, legitimate file. When executed though, the file corrupts data and can even install a backdoor that hackers can utilize to access the network.\n"
},
{
"code": null,
"e": 185420,
"s": 185182,
"text": "Trojan Horses :A Trojan horse or Trojan is a file or e-mail attachment disguised as a friendly, legitimate file. When executed though, the file corrupts data and can even install a backdoor that hackers can utilize to access the network."
},
{
"code": null,
"e": 185662,
"s": 185420,
"text": "\nMan-in-the-Middle Attack :As the name indicates, a man-in-the-middle attack occurs when someone between you and the person with whom you are communicating is actively monitoring, capturing, and controlling your communication transparently.\n"
},
{
"code": null,
"e": 185902,
"s": 185662,
"text": "Man-in-the-Middle Attack :As the name indicates, a man-in-the-middle attack occurs when someone between you and the person with whom you are communicating is actively monitoring, capturing, and controlling your communication transparently."
},
{
"code": null,
"e": 186133,
"s": 185902,
"text": "DDoS is short for Distributed Denial of Service. DDoS is a type of DOS attack where multiple compromised systems, which are often infected with a Trojan, are used to target a single system causing a Denial of Service (DoS) attack."
},
{
"code": null,
"e": 186310,
"s": 186133,
"text": "DDoS threats come in many flavors, with some directly targeting the underlying server infrastructure. Others exploit vulnerabilities in application and communication protocols."
},
{
"code": null,
"e": 186471,
"s": 186310,
"text": "The DDoS attack uses multiple computers and Internet connections to flood the targeted resource. DDoS attacks are often global attacks, distributed via botnets."
},
{
"code": null,
"e": 186494,
"s": 186471,
"text": "Types of DDoS Attacks "
},
{
"code": null,
"e": 186690,
"s": 186494,
"text": "Traffic attacks: Traffic flooding attacks send a huge volume of TCP, UDP and ICPM packets to the target. Legitimate requests get lost and these attacks may be accompanied by malware exploitation."
},
{
"code": null,
"e": 186896,
"s": 186690,
"text": "Bandwidth attacks: This DDos attack overloads the target with massive amounts of junk data. This results in a loss of network bandwidth and equipment resources and can lead to a complete denial of service."
},
{
"code": null,
"e": 187206,
"s": 186896,
"text": "They can be either network- or host-based. A host-based intrusion detection system is installed on the client computer, while a network-based intrusion detection system resides on the network. intrusion detection systems work by either looking for signatures of known attacks or deviations of normal activity."
},
{
"code": null,
"e": 187534,
"s": 187206,
"text": "intrusion detection systems work by either looking for signatures of known attacks or deviations of normal activity. These deviations or anomalies are pushed up the stack and examined at the protocol and application layer. They can effectively detect things such as Xmas tree scans, DNS poisonings, and other malformed packets."
},
{
"code": null,
"e": 188025,
"s": 187534,
"text": "IPS or intrusion prevention system, is definitely the next level of security technology with its capability to provide security at all system levels from the operating system kernel to network data packets. It provides policies and rules for network traffic along with an IDS for alerting system or network administrators to suspicious traffic, but allows the administrator to provide the action upon being alerted. Where IDS informs of a potential attack, an IPS makes attempts to stop it."
},
{
"code": null,
"e": 188215,
"s": 188025,
"text": " These security measures are available as intrusion detection systems (IDS) and intrusion prevention systems (IPS), which become part of your network to detect and stop potential incidents."
},
{
"code": null,
"e": 188504,
"s": 188215,
"text": "Signature-Based Detection compares signatures against observed events to identify possible incidents. This is the simplest detection method because it compares only the current unit of activity (such as a packet or a log entry, to a list of signatures) using string comparison operations."
},
{
"code": null,
"e": 188806,
"s": 188504,
"text": "\nMicro kernel is a kernel which run services those are minimal for operating system performance. In this kernel all other operations are performed by processor. Macro Kernel is a combination of micro and monolithic kernel. In monolithic kernel all operating system code is in single executable image.\n"
},
{
"code": null,
"e": 189106,
"s": 188806,
"text": "Micro kernel is a kernel which run services those are minimal for operating system performance. In this kernel all other operations are performed by processor. Macro Kernel is a combination of micro and monolithic kernel. In monolithic kernel all operating system code is in single executable image."
},
{
"code": null,
"e": 189306,
"s": 189106,
"text": "\nMonolithic kernels are faster than microkernels. The first microkernel Mach was 50% slower than Monolithic kernel, while later version like L4 were only 2% or 4% slower than the Monolithic kernel .\n"
},
{
"code": null,
"e": 189504,
"s": 189306,
"text": "Monolithic kernels are faster than microkernels. The first microkernel Mach was 50% slower than Monolithic kernel, while later version like L4 were only 2% or 4% slower than the Monolithic kernel ."
},
{
"code": null,
"e": 189669,
"s": 189504,
"text": "\nAdding a new feature to a monolithic system means recompiling the whole kernel, whereas with microkernels you can add new features or patches without recompiling.\n"
},
{
"code": null,
"e": 189832,
"s": 189669,
"text": "Adding a new feature to a monolithic system means recompiling the whole kernel, whereas with microkernels you can add new features or patches without recompiling."
},
{
"code": null,
"e": 190012,
"s": 189832,
"text": "\nMonolithic kernels use signals and sockets to ensure IPC, microkernel approach uses message queues. 1st gen microkernels poorly implemented IPC so were slow on context switches.\n"
},
{
"code": null,
"e": 190190,
"s": 190012,
"text": "Monolithic kernels use signals and sockets to ensure IPC, microkernel approach uses message queues. 1st gen microkernels poorly implemented IPC so were slow on context switches."
},
{
"code": null,
"e": 190291,
"s": 190190,
"text": "\nTo write a microkernel, more code is required.To write a monolithic kernel, less code is required.\n"
},
{
"code": null,
"e": 190390,
"s": 190291,
"text": "To write a microkernel, more code is required.To write a monolithic kernel, less code is required."
},
{
"code": null,
"e": 190538,
"s": 190390,
"text": "Parameters are temporary variable names within functions. The argument can be thought of as the value that is assigned to that temporary variable ."
},
{
"code": null,
"e": 190841,
"s": 190538,
"text": "An argument in context with functions is the actual value that is passed to the function ( as input) ,when it is called. However parameter refers to the variables that are used in the function declaration/definition to represent those arguments that were send to the function during the function call ."
},
{
"code": null,
"e": 191096,
"s": 190841,
"text": "The major difference between actual and formal arguments is that actual arguments are the source of information; calling programs pass actual arguments to called functions. The called functions access the information using corresponding formal arguments."
},
{
"code": null,
"e": 191282,
"s": 191096,
"text": "The arguments passed to the functions while the function is called is known as the actual arguments, whereas the arguments declared in the function header is called as formal arguments."
},
{
"code": null,
"e": 191501,
"s": 191282,
"text": "Cross-site Scripting (XSS) refers to client-side code injection attack wherein an attacker can execute malicious scripts (also commonly referred to as a malicious payload) into a legitimate website or web application ."
},
{
"code": null,
"e": 191639,
"s": 191501,
"text": "Cross-site scripting carried out on websites accounted for roughly 84% of all security vulnerabilities documented by Symantec as of 2007."
},
{
"code": null,
"e": 191977,
"s": 191639,
"text": "Example :Let us imagine, a hacker has discovered XSS vulnerability in Gmail and inject malicious script. When a user visit the site, it will execute the malicious script. The malicious code can be used to redirect users to fake gmail page or capture cookies. Using this stolen cookies, he can login into your account and change password."
},
{
"code": null,
"e": 192174,
"s": 191977,
"text": "ageing is a scheduling technique used to avoid starvation. Fixed priority scheduling is a scheduling discipline, in which tasks queued for utilizing a system resource are assigned a priority each."
},
{
"code": null,
"e": 192306,
"s": 192174,
"text": "Basically Aging is a technique of gradually increasing the priority of processes that wait in the system for a long period of time."
},
{
"code": null,
"e": 192538,
"s": 192306,
"text": "\nPython is easy to learn for even a novice developer. Its code is easy to read and you can do a lot of things just by looking at it. Also, you can execute a lot of complex functionalities with ease, thanks to the standard library.\n"
},
{
"code": null,
"e": 192768,
"s": 192538,
"text": "Python is easy to learn for even a novice developer. Its code is easy to read and you can do a lot of things just by looking at it. Also, you can execute a lot of complex functionalities with ease, thanks to the standard library."
},
{
"code": null,
"e": 192812,
"s": 192768,
"text": "\n Supports multiple systems and platforms.\n"
},
{
"code": null,
"e": 192854,
"s": 192812,
"text": " Supports multiple systems and platforms."
},
{
"code": null,
"e": 192937,
"s": 192854,
"text": "\npython code is executed in n interpreter which makes slow execution of the code.\n"
},
{
"code": null,
"e": 193018,
"s": 192937,
"text": "python code is executed in n interpreter which makes slow execution of the code."
},
{
"code": null,
"e": 193214,
"s": 193018,
"text": "\nPython allows for a more productive coding environment than massive languages like C# and Java. Experienced coders tend to stay more organized and productive when working with Python, as well .\n"
},
{
"code": null,
"e": 193408,
"s": 193214,
"text": "Python allows for a more productive coding environment than massive languages like C# and Java. Experienced coders tend to stay more organized and productive when working with Python, as well ."
},
{
"code": null,
"e": 193541,
"s": 193408,
"text": "\n\"Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers,\"\n"
},
{
"code": null,
"e": 193672,
"s": 193541,
"text": "\"Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers,\""
},
{
"code": null,
"e": 193882,
"s": 193672,
"text": "\nRetail Industry : Data Mining has its great application in Retail Industry because it collects large amount of data from on sales, customer purchasing history, goods transportation, consumption and services.\n"
},
{
"code": null,
"e": 194090,
"s": 193882,
"text": "Retail Industry : Data Mining has its great application in Retail Industry because it collects large amount of data from on sales, customer purchasing history, goods transportation, consumption and services."
},
{
"code": null,
"e": 194170,
"s": 194090,
"text": "Credit card spending by customer groups can be identified by using data mining."
},
{
"code": null,
"e": 194274,
"s": 194170,
"text": "The hidden correlation’s between different financial indicators can be discovered by using data mining."
},
{
"code": null,
"e": 194524,
"s": 194274,
"text": "\nIntrusion Detection : Any action that will compromise the integrity and confidentiality of a resource is an intrusion. The defensive measures to avoid an intrusion includes user authentication, avoid programming errors, and information protection.\n"
},
{
"code": null,
"e": 194772,
"s": 194524,
"text": "Intrusion Detection : Any action that will compromise the integrity and confidentiality of a resource is an intrusion. The defensive measures to avoid an intrusion includes user authentication, avoid programming errors, and information protection."
},
{
"code": null,
"e": 195004,
"s": 194772,
"text": "\nTelecommunication Industry :Today the telecommunication industry is one of the most emerging industries providing various services such as fax, pager, cellular phone, internet messenger, images, e-mail, web data transmission, etc\n"
},
{
"code": null,
"e": 195234,
"s": 195004,
"text": "Telecommunication Industry :Today the telecommunication industry is one of the most emerging industries providing various services such as fax, pager, cellular phone, internet messenger, images, e-mail, web data transmission, etc"
},
{
"code": null,
"e": 195433,
"s": 195234,
"text": "Concurrent programming is a form of computing in which several computations are executed during overlapping time periods—concurrently—instead of sequentially (one completing before the next starts)."
},
{
"code": null,
"e": 195734,
"s": 195433,
"text": "Concurrent programming is characterized by programming with more than one process.Concurrent programming involves the notations for expressing potential parallelism so that operations may be executed in parallel and the techniques for solving the resulting synchronization and communication problems."
},
{
"code": null,
"e": 196066,
"s": 195734,
"text": "Quality assurance (QA) is a way of preventing mistakes or defects in manufactured products and avoiding problems when delivering solutions or services to customers.The methods by which this is accomplished are many and varied, and may include ensuring conformance to one or more standards, such as ISO 9000 or a model such as CMMI."
},
{
"code": null,
"e": 196242,
"s": 196066,
"text": "Quality assurance includes two principles: \"Fit for purpose\" (the product should be suitable for the intended purpose); and \"right first time\" (mistakes should be eliminated)."
},
{
"code": null,
"e": 196633,
"s": 196242,
"text": "Agile software development methodology is an process for developing software (like other software development methodologies –Waterfall model, V-Model, Iterative model etc.) however Agile development model is also a type of Incremental model. Software is developed in incremental, rapid cycles. This results in small incremental releases with each release building on previous functionality."
},
{
"code": null,
"e": 197158,
"s": 196633,
"text": "The addresses of an object's polymorphic methods is stored in a method table in the object. When invoking some polymorphic method at run time the method name is looked up in this table to get the address. A method table contains the names and addresses of the object's dynamically bound (polymorphic) methods. The method table is the same for all objects belonging to the same class, so is stored in the Class object (for the object's type, here Integer or Double). (In other languages method tables are called vtables.)"
},
{
"code": null,
"e": 197168,
"s": 197158,
"text": "Example :"
},
{
"code": null,
"e": 197474,
"s": 197168,
"text": "#include<iostream>\nusing namespace std;\n\nclass A\n{\npublic:\n int i;\n A(){i=100;}\n};\n\nclass B : public A\n{\npublic:\n int j;\n B(){i = -1; j = 99;}\n};\n\nvoid func(A& myA)\n{\n cout<<myA.i << endl;\n}\n\nint main()\n{\n B b;\n A* a = new B();\n func(*a);\n func(b);\n delete a;\n return 0;\n}"
},
{
"code": null,
"e": 197710,
"s": 197476,
"text": "Virtual Table is a lookup table of function pointers used to dynamically bind the virtual functions to objects at run time. It is not intended to be used directly by the program, and as such there is no standardized way to access it."
},
{
"code": null,
"e": 198642,
"s": 197710,
"text": "Virtual Table is created even for classes that have virtual base classes. In this case, the vtable has pointer to the shared instance of the base class along with the pointers to the classe's virtual functions if any.\n\n_vptr :\n\nThis vtable pointer or _vptr, is a hidden pointer added by the Compiler to the base class. And this pointer is pointing to the virtual table of that particular class.\nExpalnation :\n\nHere in function main b pointer gets assigned to D1's _vptr and now starts pointing to D1's vtable. Then calling to a function1(), makes it's _vptr startightway calls D1's vtable function1() and so in turn calls D1's method i.e. function1() as D1 has it's own function1()defined it's class.\n\nWhere as pointer b calling to a function2(), makes it's _vptr points to D1's vatble which in-turn pointing to Base class's vtablefunction2 () as shown in the diagram (as D1 class does not have it's own definition or function2())."
},
{
"code": null,
"e": 199043,
"s": 198642,
"text": "Register are used to quickly accept, store, and transfer data and instructions that are being used immediately by the CPU, there are various types of Registers those are used for various purpose. Among of the some Mostly used Registers named as AC or Accumulator, Data Register or DR, the AR or Address Register, program counter(PC), Memory Data Register (MDR) ,Index register,Memory Buffer Register."
},
{
"code": null,
"e": 199402,
"s": 199043,
"text": "\nWith a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index.\nWith a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indexes, although each new index will increase the time it takes to write new records.\n"
},
{
"code": null,
"e": 199550,
"s": 199402,
"text": "With a clustered index the rows are stored physically on the disk in the same order as the index. Therefore, there can be only one clustered index."
},
{
"code": null,
"e": 199759,
"s": 199550,
"text": "With a non clustered index there is a second list that has pointers to the physical rows. You can have many non clustered indexes, although each new index will increase the time it takes to write new records."
},
{
"code": null,
"e": 199924,
"s": 199759,
"text": "\nThe real difference [between clustered and unclustered indexes] is that a clustered index will reorder the records on disk, whereas an unclustered index will not.\n"
},
{
"code": null,
"e": 200087,
"s": 199924,
"text": "The real difference [between clustered and unclustered indexes] is that a clustered index will reorder the records on disk, whereas an unclustered index will not."
},
{
"code": null,
"e": 200787,
"s": 200087,
"text": "\nA clustered index alters the way that the rows are stored. When you create a clustered index on a column (or a number of columns), SQL server sorts the table’s rows by that column(s). It is like a dictionary, where all words are sorted in alphabetical order in the entire book.\nA non-clustered index, on the other hand, does not alter the way the rows are stored in the table. It creates a completely different object within the table that contains the column(s) selected for indexing and a pointer back to the table’s rows containing the data. It is like an index in the last pages of a book, where keywords are sorted and contain the page number to the material of the book for faster reference.\n"
},
{
"code": null,
"e": 201065,
"s": 200787,
"text": "A clustered index alters the way that the rows are stored. When you create a clustered index on a column (or a number of columns), SQL server sorts the table’s rows by that column(s). It is like a dictionary, where all words are sorted in alphabetical order in the entire book."
},
{
"code": null,
"e": 201485,
"s": 201065,
"text": "A non-clustered index, on the other hand, does not alter the way the rows are stored in the table. It creates a completely different object within the table that contains the column(s) selected for indexing and a pointer back to the table’s rows containing the data. It is like an index in the last pages of a book, where keywords are sorted and contain the page number to the material of the book for faster reference."
},
{
"code": null,
"e": 201692,
"s": 201485,
"text": "The inode is a data structure in a Unix-style file system that describes a file system object such as a file or a directory. Each inode stores the attributes and disk block location(s) of the object's data."
},
{
"code": null,
"e": 202007,
"s": 201692,
"text": "When a file is created inside a directory then the file-name and Inode number are assigned to file. These two entries are associated with every file in a directory. The user might think that the directory contains the complete file and all the extra information related to it but this might not be the case always."
},
{
"code": null,
"e": 202141,
"s": 202007,
"text": "File system object attributes may include metadata (times of last change,access, modification), as well as owner and permission data."
},
{
"code": null,
"e": 202486,
"s": 202141,
"text": "A red–black tree is a kind of self-balancing binary search tree. Each node of the binary tree has an extra bit, and that bit is often interpreted as the color (red or black) of the node. These color bits are used to ensure the tree remains approximately balanced during insertions and deletions .\n\n1) Every node has a color either red or black."
},
{
"code": null,
"e": 202519,
"s": 202486,
"text": "2) Root of tree is always black."
},
{
"code": null,
"e": 202610,
"s": 202519,
"text": "3) There are no two adjacent red nodes (A red node cannot have a red parent or red child)."
},
{
"code": null,
"e": 202681,
"s": 202610,
"text": "4) Every path from root to a NULL node has same number of black nodes."
},
{
"code": null,
"e": 202855,
"s": 202681,
"text": "struct t_red_black_node {\n enum { red, black } colour;\n void *item;\n struct t_red_black_node *left,\n *right,\n *parent;\n }"
},
{
"code": null,
"e": 202863,
"s": 202855,
"text": "Example"
},
{
"code": null,
"e": 202963,
"s": 202865,
"text": "Super Block: Each filesystem has one super block (+ duplicate super block) it contains info about"
},
{
"code": null,
"e": 203001,
"s": 202963,
"text": "1. type of filesystem (ext2, ext3...)"
},
{
"code": null,
"e": 203019,
"s": 203001,
"text": "2. the block size"
},
{
"code": null,
"e": 203056,
"s": 203019,
"text": "3. pointers to a list of free blocks"
},
{
"code": null,
"e": 203098,
"s": 203056,
"text": "4. the inode number of the root directory"
},
{
"code": null,
"e": 203390,
"s": 203098,
"text": "a boot block located in the first few sectors of a file system. The boot block contains the initial bootstrap program used to load the operating system. Typically, the first sector contains a bootstrap program that reads in a larger bootstrap program from the next few sectors, and so forth."
},
{
"code": null,
"e": 203761,
"s": 203394,
"text": "The two phase commit protocol is a distributed algorithm which lets all sites in a distributed system agree to commit or rollback a transaction based upon consensus of all participating sites.If any database server is unable to commit its portion of the transaction, all database servers participating in the transaction must be prevented from committing their work."
},
{
"code": null,
"e": 203967,
"s": 203761,
"text": "Hadoop File System was developed using distributed file system design. It is run on commodity hardware. Unlike other distributed systems, HDFS is highly fault tolerant and designed using low-cost hardware."
},
{
"code": null,
"e": 204304,
"s": 203967,
"text": "According to The Apache Software Foundation, the primary objective of HDFS is to store data reliably even in the presence of failures including Name Node failures, Data Node failures and network partitions. The Name Node is a single point of failure for the HDFS cluster and a Data Node stores data in the Hadoop file management system."
},
{
"code": null,
"e": 204424,
"s": 204304,
"text": "HDFS uses a master/slave architecture in which one device (the master) controls one or more other devices (the slaves)."
},
{
"code": null,
"e": 204441,
"s": 204424,
"text": "Features of HDFS"
},
{
"code": null,
"e": 204500,
"s": 204441,
"text": "It is suitable for the distributed storage and processing."
},
{
"code": null,
"e": 204559,
"s": 204500,
"text": "Hadoop provides a command interface to interact with HDFS."
},
{
"code": null,
"e": 204655,
"s": 204559,
"text": "The built-in servers of namenode and datanode help users to easily check the status of cluster."
},
{
"code": null,
"e": 204693,
"s": 204655,
"text": "Streaming access to file system data."
},
{
"code": null,
"e": 204873,
"s": 204693,
"text": "Lex is a program designed to generate scanners, also known as tokenizers, which recognize lexical patterns in text. Lex is an acronym that stands for \"lexical analyzer generator.\""
},
{
"code": null,
"e": 205101,
"s": 204873,
"text": "Lex is short for \"lexical analysis\". Lex takes an input file containing a set of lexical analysis rules or regular expressions. For output, Lex produces a C function which when invoked, finds the next match in the input stream."
},
{
"code": null,
"e": 205386,
"s": 205101,
"text": "Yacc (for \"yet another compiler compiler.\" ) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc"
},
{
"code": null,
"e": 205795,
"s": 205386,
"text": "The input subroutine produced by Yacc calls a user-supplied routine to return the next basic input item. Thus, the user can specify his input in terms of individual input characters, or in terms of higher level constructs such as names and numbers. The user-supplied routine may also handle idiomatic features such as comment and continuation conventions, which typically defy easy grammatical specification."
},
{
"code": null,
"e": 205986,
"s": 205795,
"text": "Yacc has also been used for less conventional languages, including a phototypesetter language, several desk calculator languages, a document retrieval system, and a Fortran debugging system."
},
{
"code": null,
"e": 206225,
"s": 205986,
"text": "Difference between LL parsing and LR parsing is that LL parser begin at the start symbol and try to apply productions to arrive at the target string, whereas LR parser begin at the target string and try to arrive back at the start symbol."
},
{
"code": null,
"e": 206318,
"s": 206225,
"text": "LL parsing, also known as top-down parsing and LR parsing, also known as bottom-up parsing ."
},
{
"code": null,
"e": 206429,
"s": 206318,
"text": "LL starts with only the root non terminal on the stack, LR ends with only the root non terminal on the stack ."
},
{
"code": null,
"e": 206555,
"s": 206429,
"text": "LL uses grammar rules in an order which corresponds to pre-order traversal of the parse tree, LR does a post-order traversal."
},
{
"code": null,
"e": 206757,
"s": 206555,
"text": "LL continuously pops a non terminal off the stack, and pushes a corresponding right hand side; LR tries to recognize a right hand side on the stack, pops it, and pushes the corresponding non terminal ."
},
{
"code": null,
"e": 206862,
"s": 206757,
"text": "LL reads terminal when it pops one off the stack, LR reads terminals while it pushes them on the stack ."
},
{
"code": null,
"e": 207041,
"s": 206864,
"text": "map uses a red-black tree as the data structure, so the elements you put in there are sorted, and insert/delete is O(log(n)). The elements need to implement at least operator<."
},
{
"code": null,
"e": 207189,
"s": 207041,
"text": "hash map uses a hash, so elements are unsorted, insert/delete is O(1). Elements need to implement at least operator== and you need a hash function."
},
{
"code": null,
"e": 207584,
"s": 207189,
"text": "The main difference otherwise is a difference in the speed at which you can access individual elements. Maps are usually stored as binary trees and hash maps are stored as hash tables. This means that if you have N elements in your container, then accessing an element in a map requires O(log(N)) time and the same operation in a hash map is O(1). So hash maps are faster, in general than maps."
},
{
"code": null,
"e": 207782,
"s": 207584,
"text": "\nuse a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key.\nmap is implemented as a balanced binary search tree (usually a red/black tree).\n"
},
{
"code": null,
"e": 207898,
"s": 207782,
"text": "use a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key."
},
{
"code": null,
"e": 207978,
"s": 207898,
"text": "map is implemented as a balanced binary search tree (usually a red/black tree)."
},
{
"code": null,
"e": 208155,
"s": 207978,
"text": "A polyphase merge sort is an algorithm which decreases the number of runs at every iteration of the main loop by merging runs into larger runs. It is used for external sorting."
},
{
"code": null,
"e": 208415,
"s": 208155,
"text": " In this type of sort, the tapes being merged, and the tape to which the merged sub files are written, vary continuously throughout the sort. In this technique, the concept of a pass through records is not as clear-cut as in the straight or the natural merge."
},
{
"code": null,
"e": 208425,
"s": 208415,
"text": "Example :"
},
{
"code": null,
"e": 208643,
"s": 208425,
"text": "Select Operation : This operation is used to select rows from a table (relation) that specifies a given logic, which is called as a predicate. The predicate is a user defined condition to select rows of user's choice."
},
{
"code": null,
"e": 208838,
"s": 208643,
"text": "Project Operation : If the user is interested in selecting the values of a few attributes, rather than selection all attributes of the Table (Relation), then one should go for PROJECT Operation."
},
{
"code": null,
"e": 208858,
"s": 208838,
"text": "Example : Selection"
},
{
"code": null,
"e": 208890,
"s": 208858,
"text": "Notation uses lower case sigma:"
},
{
"code": null,
"e": 208911,
"s": 208890,
"text": "σcondition(relation)"
},
{
"code": null,
"e": 208931,
"s": 208911,
"text": "Example :Projection"
},
{
"code": null,
"e": 209295,
"s": 208931,
"text": "A hub is the most basic networking device that connects multiple computers or other network devices together.In a hub, a frame is passed along or \"broadcast\" to every one of its ports. It doesn't matter that the frame is only destined for one port. they use protocols such as ICMP to communicate with each other and configure the best route between any two hosts."
},
{
"code": null,
"e": 209632,
"s": 209295,
"text": "Arcesium is a post-trade technology and professional services firm. We offer a new way for hedge fund managers to scale their business while maintaining control of critical non-investment activities. Arcesium in terms of software development would be either at par with Shaw or gonna be better since the higher management is from Shaw ."
},
{
"code": null,
"e": 209754,
"s": 209632,
"text": "Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. "
},
{
"code": null,
"e": 209972,
"s": 209754,
"text": "A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept."
},
{
"code": null,
"e": 210149,
"s": 209972,
"text": "\nTemplates are often used in larger code bbase for the purpose of code reusability and flexibility of the programs.\nThe concept of templates can be used in two different ways:\n"
},
{
"code": null,
"e": 210264,
"s": 210149,
"text": "Templates are often used in larger code bbase for the purpose of code reusability and flexibility of the programs."
},
{
"code": null,
"e": 210324,
"s": 210264,
"text": "The concept of templates can be used in two different ways:"
},
{
"code": null,
"e": 210343,
"s": 210324,
"text": "Function Templates"
},
{
"code": null,
"e": 210359,
"s": 210343,
"text": "Class Templates"
},
{
"code": null,
"e": 210377,
"s": 210359,
"text": "Function Template"
},
{
"code": null,
"e": 210443,
"s": 210377,
"text": "The general form of a template function definition is shown here:"
},
{
"code": null,
"e": 210528,
"s": 210443,
"text": "template <class type> ret-type func-name(parameter list) {\n // body of function\n} "
},
{
"code": null,
"e": 210653,
"s": 210528,
"text": "Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition."
},
{
"code": null,
"e": 210721,
"s": 210653,
"text": "for detail :http://www.geeksforgeeks.org/template-specialization-c/"
},
{
"code": null,
"e": 211000,
"s": 210721,
"text": "A heap overflow is a type of buffer overflow that occurs in the heap data area. Heap overflows are exploitable in a different manner to that of stack-based overflows. Memory on the heap is dynamically allocated by the application at run-time and typically contains program data."
},
{
"code": null,
"e": 211054,
"s": 211000,
"text": "The heap overflow is very small, and hard to detect. "
},
{
"code": null,
"e": 211245,
"s": 211054,
"text": "The canonical heap overflow technique overwrites dynamic memory allocation linkage (such as malloc meta data) and uses the resulting pointer exchange to overwrite a program function pointer."
},
{
"code": null,
"e": 211464,
"s": 211245,
"text": "Heap overflows actually include a class of exploits that are more complicated than those explained in this tutorial. Some of these exploits attack vulnerabilities in memory allocating functions such as malloc in lib-c."
},
{
"code": null,
"e": 211753,
"s": 211464,
"text": "A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system)."
},
{
"code": null,
"e": 211879,
"s": 211753,
"text": "Segmentation faults are a common class of error in programs written in languages like C that provide low-level memory access."
},
{
"code": null,
"e": 212045,
"s": 211879,
"text": "Segmentation fault is raised by hardware when any program attempts to access the memory location which is not allow to access, or attempts to access in wrong manner."
},
{
"code": null,
"e": 212263,
"s": 212045,
"text": "Newer programming languages may employ mechanisms designed to avoid segmentation faults and improve memory safety. For example, the Rust programming language employs an 'Ownership' based model to ensure memory safety."
},
{
"code": null,
"e": 212399,
"s": 212263,
"text": "Information about files(data) are sometimes called metadata. So you can even say it in another way, \"An inode is metadata of the data.\""
},
{
"code": null,
"e": 212625,
"s": 212399,
"text": " Inode : Its a complex data-structure that contains all the necessary information to specify a file. It includes the memory layout of the file on disk, file permissions, access time, number of different links to the file etc."
},
{
"code": null,
"e": 212830,
"s": 212625,
"text": " Global File table : It contains information that is global to the kernel e.g. the byte offset in the file where the user's next read/write will start and the access rights allowed to the opening process."
},
{
"code": null,
"e": 212991,
"s": 212830,
"text": "Process file descriptor table : maintained by the kernel, that in turn indexes into a system-wide table of filesopened by all processes, called the file table ."
},
{
"code": null,
"e": 213309,
"s": 212991,
"text": "stdio.h> searches in standard C library locations, whereas \"stdio.h\" searches in the current directory as well. ... You use #include \"double quoted\" when you want to say: \"look for a file with this name in my own application's include directory; however, if it can't be found, look in the system's include directory\"."
},
{
"code": null,
"e": 213586,
"s": 213309,
"text": "Thrashing is a state in which our CPU perform 'productive' work less and 'swapping' more. CPU is busy in swapping pages, so much that it can not respond to user program as much as required. Thrashing can potentially result in total collapse of the hard drive of the computer."
},
{
"code": null,
"e": 213850,
"s": 213586,
"text": "When thrashing occurs you will notice the computer hard drive always working and a decrease in system performance. Thrashing is bad on the hard drive because of the amount of work the hard drive has to do and if left unfixed can cause an early hard drive failure."
},
{
"code": null,
"e": 214142,
"s": 213850,
"text": "A dangling pointer is one that has a value (not NULL) which refers to some memory which is not valid for the type of object you expect. For example if you set a pointer to an object then overwrote that memory with something else unrelated or freed the memory if it was dynamically allocated."
},
{
"code": null,
"e": 214177,
"s": 214142,
"text": " Dangling pointer"
},
{
"code": null,
"e": 214301,
"s": 214177,
"text": "A TCP connection controls its transmission rate by limiting its number of transmitted-but-yet-to-be-acknowledged segments. "
},
{
"code": null,
"e": 215012,
"s": 214301,
"text": "TCP’s congestion control scheme is based on a congestion window. The current value of the congestion window (cwnd) is stored in the TCB of each TCP connection and the window that can be used by the sender is constrained by min(cwnd,rwin,swin)min(cwnd,rwin,swin) where swinswin is the current sending window and rwinrwin the last received receive window. The Additive Increase part of the TCP congestion control increments the congestion window by MSS bytes every round-trip-time. In the TCP literature, this phase is often called the congestion avoidance phase. The Multiplicative Decrease part of the TCP congestion control divides the current value of the congestion window once congestion has been detected."
},
{
"code": null,
"e": 215047,
"s": 215012,
"text": "A socket consists of three things:"
},
{
"code": null,
"e": 215098,
"s": 215047,
"text": "\nAn IP address\nA transport protocol\nA port number\n"
},
{
"code": null,
"e": 215112,
"s": 215098,
"text": "An IP address"
},
{
"code": null,
"e": 215133,
"s": 215112,
"text": "A transport protocol"
},
{
"code": null,
"e": 215147,
"s": 215133,
"text": "A port number"
},
{
"code": null,
"e": 215310,
"s": 215147,
"text": "A port is a number between 1 and 65535 inclusive that signifies a logical gate in a device. Every connection between a client and server requires a unique socket."
},
{
"code": null,
"e": 215323,
"s": 215310,
"text": "For example:"
},
{
"code": null,
"e": 215339,
"s": 215323,
"text": "1030 is a port."
},
{
"code": null,
"e": 215381,
"s": 215339,
"text": "(10.1.1.2 , TCP , port 1030) is a socket."
},
{
"code": null,
"e": 215687,
"s": 215381,
"text": "A port is one half of a protocol demuxing namespace. Typically we use TCP or UDP ports, where each port represents a single service. A server process listens on a port and accepts incoming connections (TCP) or incoming packets (UDP). The client allocates a local port number for initiating the connection."
},
{
"code": null,
"e": 215699,
"s": 215687,
"text": "For socket:"
},
{
"code": null,
"e": 215742,
"s": 215699,
"text": "An ip address with port is know as socket."
},
{
"code": null,
"e": 216090,
"s": 215742,
"text": "\nSocket is the API's abstraction for a IP-port pair. It handles the network and transfer layer of communication. It can be thought of as a application's interface to the network.\nA port on the other hand is the destination/origin of a packet. A IP address is further divided into ports so that applications can share the network without conflict.\n"
},
{
"code": null,
"e": 216268,
"s": 216090,
"text": "Socket is the API's abstraction for a IP-port pair. It handles the network and transfer layer of communication. It can be thought of as a application's interface to the network."
},
{
"code": null,
"e": 216436,
"s": 216268,
"text": "A port on the other hand is the destination/origin of a packet. A IP address is further divided into ports so that applications can share the network without conflict."
},
{
"code": null,
"e": 216746,
"s": 216436,
"text": "The basic function that any switch is supposed to perform is to receive information from any source connected to it and dispatch that information to the appropriate destination only. This thing differentiates switches from hubs. Hub gets the information and forwards that to every other device in the network."
},
{
"code": null,
"e": 216882,
"s": 216746,
"text": "const int *p\n 1. => int const * \n 2. => pointer to a const int \n so the pointer \"points\" to an int that can't be changed"
},
{
"code": null,
"e": 217027,
"s": 216882,
"text": " int * const \n 2. => const pointer to int \n so the pointer \"points\" to an int that can be changed, \n but the pointer can't change"
},
{
"code": null,
"e": 217491,
"s": 217027,
"text": "A cursor is the position indicator on a computer display screen where a user can enter text. In an operating system with a graphical user interface (GUI), the cursor is also a visible and moving pointer that the user controls with a mouse, touch pad, or similar input device. A cursor library is software, often implemented as a part of a database system or a data access API, that is used to manage attributes of data returned from a data source (a result set). "
},
{
"code": null,
"e": 217759,
"s": 217491,
"text": "\nSQL is a Structured Query Language used to issue a single query or execute a single insert/update/delete.\nPL-SQL is a programming language SQL, used to write full programs using variables, loops,operators etc. to carry out multiple selects/inserts/updates/deletes.\n"
},
{
"code": null,
"e": 217865,
"s": 217759,
"text": "SQL is a Structured Query Language used to issue a single query or execute a single insert/update/delete."
},
{
"code": null,
"e": 218025,
"s": 217865,
"text": "PL-SQL is a programming language SQL, used to write full programs using variables, loops,operators etc. to carry out multiple selects/inserts/updates/deletes."
},
{
"code": null,
"e": 218165,
"s": 218025,
"text": "\nSQL is a data oriented language used to select and manipulate sets of data.\n\tPL/SQL is a procedural language used to create applications.\n"
},
{
"code": null,
"e": 218303,
"s": 218165,
"text": "SQL is a data oriented language used to select and manipulate sets of data.\n\tPL/SQL is a procedural language used to create applications."
},
{
"code": null,
"e": 218468,
"s": 218303,
"text": "\nSQL you can execute only one query at a time, where in PL/SQL you can execute an number of queries in one block and get executed all there queues at one command .\n"
},
{
"code": null,
"e": 218631,
"s": 218468,
"text": "SQL you can execute only one query at a time, where in PL/SQL you can execute an number of queries in one block and get executed all there queues at one command ."
},
{
"code": null,
"e": 218771,
"s": 218631,
"text": "\nSQL is used to code queries, DML and DDL statements. PL/SQL is used to code program blocks, triggers, functions, procedures and packages.\n"
},
{
"code": null,
"e": 218909,
"s": 218771,
"text": "SQL is used to code queries, DML and DDL statements. PL/SQL is used to code program blocks, triggers, functions, procedures and packages."
},
{
"code": null,
"e": 219001,
"s": 218909,
"text": "\nWe can embed SQL in a PL/SQL program, but we cannot embed PL/SQL within a SQL statement .\n"
},
{
"code": null,
"e": 219091,
"s": 219001,
"text": "We can embed SQL in a PL/SQL program, but we cannot embed PL/SQL within a SQL statement ."
},
{
"code": null,
"e": 219412,
"s": 219091,
"text": "A trigger (from the Dutch trekken, meaning to pull) is a lever which, when pulled by the finger, releases the hammer on a firearm. In a database, a trigger is a set of Structured Query Language (SQL) statements that automatically \"fires off\" an action when a specific operation, such as changing data in a table, occurs."
},
{
"code": null,
"e": 219592,
"s": 219412,
"text": " For example, when a new record (representing a new worker) is added to the employees table, new records should also be created in the tables of the taxes, vacations and salaries."
},
{
"code": null,
"e": 219610,
"s": 219592,
"text": "Trigger is used :"
},
{
"code": null,
"e": 219657,
"s": 219610,
"text": "Automatically generate derived column values ."
},
{
"code": null,
"e": 219688,
"s": 219657,
"text": "Prevent invalid transactions ."
},
{
"code": null,
"e": 219730,
"s": 219688,
"text": "Enforce complex security authorizations ."
},
{
"code": null,
"e": 219801,
"s": 219730,
"text": "Enforce referential integrity across nodes in a distributed database ."
},
{
"code": null,
"e": 219833,
"s": 219801,
"text": "Enforce complex business rules."
},
{
"code": null,
"e": 220005,
"s": 219833,
"text": " Linux is based upon the UNIX philosophy and supports the standard POSIX system call interface. Windows on the other hand only provides for POSIX using an emulation layer."
},
{
"code": null,
"e": 220210,
"s": 220005,
"text": "Windows requires it's users to purchase a license to use the software (often the license cost is included in the price of a new computer). Linux is licensed such that it's freely distributable at no cost."
},
{
"code": null,
"e": 220459,
"s": 220210,
"text": "Flexibility: It is used for high performance applications, desktop applications and embedded applications. You can save disk space by installing components required for a particular use. You can restrict specific computers instead of all computers."
},
{
"code": null,
"e": 220689,
"s": 220459,
"text": "Windows exposes partitions and devices at drive letters. Whether you have multiple hard drives, multiple partitions on the same hard drive, or removable devices connected, each file system is available under its own drive letter."
},
{
"code": null,
"e": 220870,
"s": 220689,
"text": "\nLinux doesn’t have drive letters. Instead, it makes other file systems accessible at arbitrary directories. (Windows can do this too, but this isn’t how it works out of the box.)\n"
},
{
"code": null,
"e": 221049,
"s": 220870,
"text": "Linux doesn’t have drive letters. Instead, it makes other file systems accessible at arbitrary directories. (Windows can do this too, but this isn’t how it works out of the box.)"
},
{
"code": null,
"e": 221423,
"s": 221049,
"text": "The proc file-system (proc fs) is a special filesystem in Unix-like operating systems that presents information about processes and other system information in a hierarchical file-like structure, providing a more convenient and standardized method for dynamically accessing process data held in the kernel than traditional tracing methods or direct access to kernel memory."
},
{
"code": null,
"e": 221717,
"s": 221423,
"text": "Within the /proc/ directory, one can find a wealth of information detailing the system hardware and any processes currently running. In addition, some of the files within the /proc/ directory tree can be manipulated by users and applications to communicate configuration changes to the kernel."
},
{
"code": null,
"e": 221859,
"s": 221717,
"text": "The /proc file system is nicely documented in the proc man page. You can access this document by running the below command on a linux system."
},
{
"code": null,
"e": 222106,
"s": 221859,
"text": "The proc filesystem provides a method of communication between kernel space and user space. For example, the GNU version of the process reporting utility ps uses the proc file system to obtain its data, without using any specialized system calls."
},
{
"code": null,
"e": 222375,
"s": 222106,
"text": "A scripting language is a programming language that employs a high-level construct to interpret and execute one command at a time. In general, scripting languages are easier to learn and faster to code in than more structured and compiled languages such as C and C++ ."
},
{
"code": null,
"e": 222556,
"s": 222375,
"text": "A scripting language can be viewed as a domain-specific language for a particular environment; in the case of scripting an application, this is also known as an extension language."
},
{
"code": null,
"e": 222748,
"s": 222556,
"text": "Scripting languages came about largely because of the development of the Internet as a communications tool.JavaScript, ASP, JSP, PHP, Perl, Tcl and Python are examples of scripting languages."
},
{
"code": null,
"e": 222845,
"s": 222748,
"text": "Scripting languages like JavaScript are often used to facilitate enhanced features of websites. "
},
{
"code": null,
"e": 223134,
"s": 222847,
"text": "OS makes a DNS lookup and replies the IP address to the browser. browser opens a TCP connection to server (this step is much more complex with HTTPS) browser sends the HTTP request through TCP connection. ... browser renders response, or offers a download dialog for unrecognized types."
},
{
"code": null,
"e": 223308,
"s": 223134,
"text": "When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration."
},
{
"code": null,
"e": 223366,
"s": 223308,
"text": "for detail :http://www.geeksforgeeks.org/references-in-c/"
},
{
"code": null,
"e": 223665,
"s": 223366,
"text": "Generics are a facility of generic programming that were added to the Java programming language in 2004 within the official version J2SE 5.0. They were designed to extend Java's type system to allow “a type or method to operate on objects of various types while providing compile-time type safety.”"
},
{
"code": null,
"e": 223925,
"s": 223665,
"text": "CMOS (complementary metal-oxide-semiconductor) is the term usually used to describe the small amount of memory on a computer motherboard that stores the BIOS settings. Some of these BIOS settings include the system time and date as well as hardware settings ."
},
{
"code": null,
"e": 224027,
"s": 223925,
"text": "CMOS is also sometimes referred to as complementary-symmetry metal–oxide–semiconductor (or COS-MOS) ."
},
{
"code": null,
"e": 224363,
"s": 224027,
"text": "Like most RAM chips, the chip that stores your BIOS settings is manufactured using the CMOS process. It holds a small amount of data, usually 256 bytes. The information on the CMOS chip includes what types of disk drives are installed on your computer, the current date and time of your system clock, and your computer's boot sequence."
},
{
"code": null,
"e": 224535,
"s": 224363,
"text": "CMOS is used in static RAM, digital logic circuits, microprocessors, micro controllers, image sensors, and the conversion of computer data from one file format to another."
},
{
"code": null,
"e": 224657,
"s": 224535,
"text": "The Basic Input Output System, usually referred to as BIOS, is software stored on a small memory chip on the motherboard."
},
{
"code": null,
"e": 224811,
"s": 224657,
"text": " It also manages data flow between the computer's operating system and attached devices such as the hard disk,video adapter, keyboard, mouse and printer."
},
{
"code": null,
"e": 225150,
"s": 224811,
"text": "The BIOS includes instructions on how to load basic computer hardware and includes a test referred to as a POST (Power On Self Test) that helps verify the computer meets requirements to boot up properly. If the computer does not pass the POST, you will receive a combination of beeps indicating what is malfunctioning within the computer."
},
{
"code": null,
"e": 225368,
"s": 225150,
"text": "The BIOS additionally provides an abstraction layer for the hardware, i.e., a consistent way for application programs and operating systems to interact with the keyboard, display, and other input/output (I/O) devices."
},
{
"code": null,
"e": 225662,
"s": 225368,
"text": "There are possibly of many IP connection between two system (identified by their IP address) for different application on each end . UDP \"Source Port\" field identified the associated application in the source system and \"Destination Port\" the associated application in the destination system ."
},
{
"code": null,
"e": 225855,
"s": 225662,
"text": "\nThe key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it.\nSo if you're going to need to change the values use a List.\n"
},
{
"code": null,
"e": 225986,
"s": 225855,
"text": "The key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it."
},
{
"code": null,
"e": 226046,
"s": 225986,
"text": "So if you're going to need to change the values use a List."
},
{
"code": null,
"e": 226154,
"s": 226046,
"text": "Tuples can be used as keys for dicts and properly implement __hash__(), lists do not, and are not hashable."
},
{
"code": null,
"e": 226195,
"s": 226154,
"text": "Tuples have structure, lists have order."
},
{
"code": null,
"e": 226314,
"s": 226195,
"text": "The literal syntax of tuples is shown by parentheses whereas the literal syntax of lists is shown by square brackets ."
},
{
"code": null,
"e": 226417,
"s": 226314,
"text": "Tuples are heterogeneous while lists are homogeneous. One has to deal individually with the items.\n\n\t "
},
{
"code": null,
"e": 226736,
"s": 226417,
"text": "\nDynamic (run time) polymorphism is the polymorphism existed at run-time. Here, Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at run-time. Method overloading and method overriding using instance methods are the examples for dynamic polymorphism.\n"
},
{
"code": null,
"e": 227053,
"s": 226736,
"text": "Dynamic (run time) polymorphism is the polymorphism existed at run-time. Here, Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at run-time. Method overloading and method overriding using instance methods are the examples for dynamic polymorphism."
},
{
"code": null,
"e": 227175,
"s": 227053,
"text": "Whenever we call the method on to the object based on the object corresponding class method will be executed dynamically."
},
{
"code": null,
"e": 227186,
"s": 227175,
"text": "Example : "
},
{
"code": null,
"e": 227689,
"s": 227186,
"text": "public class DynamicTest {\n\n public static void main(String args[]) {\n Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car\n vehicle.start(); //Car's start called because start() is overridden method\n }\n}\n\nclass Vehicle {\n\n public void start() {\n System.out.println(\"Inside start method of Vehicle\");\n }\n}\n\nclass Car extends Vehicle {\n\n @Override\n public void start() {\n System.out.println(\"Inside start method of Car\");\n }\n}"
},
{
"code": null,
"e": 227960,
"s": 227691,
"text": "A UNIX shell script is a human-readable text file containing a group of commands that could also be manually executed one-by-one at the UNIX operating system command prompt and these command sequences in order to make ones life at the shell easier and more productive."
},
{
"code": null,
"e": 228015,
"s": 227960,
"text": "The following is an example of a basic shell script:\n "
},
{
"code": null,
"e": 228065,
"s": 228015,
"text": "echo \"Text Line 1\"\n\nprint \"Text Line 2\"\n\nexit 0\n "
},
{
"code": null,
"e": 228207,
"s": 228065,
"text": "AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related technologies like JavaScript, DOM, XML, HTML, CSS etc."
},
{
"code": null,
"e": 228420,
"s": 228207,
"text": "the Ajax model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions."
},
{
"code": null,
"e": 228638,
"s": 228420,
"text": "Although X in Ajax stands for XML, JSON is used more than XML nowadays because of its many advantages such as being lighter and a part of JavaScript. Both JSON and XML are used for packaging information in Ajax model."
},
{
"code": null,
"e": 228886,
"s": 228638,
"text": "MongoDB is an open-source document database and leading NoSQL database. MongoDB is written in C++. This tutorial will give you great understanding on MongoDB concepts needed to create and deploy a highly scalable and performance-oriented database."
},
{
"code": null,
"e": 229139,
"s": 228886,
"text": "MongoDB supports field, range queries, regular expression searches. Queries can return specific fields of documents and also include user-defined JavaScript functions. Queries can also be configured to return a random sample of results of a given size."
},
{
"code": null,
"e": 229280,
"s": 229139,
"text": "MongoDB scales horizontally using sharding The user chooses a shard key, which determines how the data in a collection will be distributed ."
},
{
"code": null,
"e": 229550,
"s": 229280,
"text": "JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. Squarespace uses JSON to store and organize site content created with the CMS."
},
{
"code": null,
"e": 229558,
"s": 229550,
"text": "Example"
},
{
"code": null,
"e": 229709,
"s": 229558,
"text": "var myJSON = '{ \"name\":\"John\", \"age\":31, \"city\":\"New York\" }';\nvar myObj = JSON.parse(myJSON);\ndocument.getElementById(\"demo\").innerHTML = myObj.name;"
},
{
"code": null,
"e": 229866,
"s": 229711,
"text": "The primary difference between a div and a span is their default behavior. By default, a <div> is a block level element and a <span> is an inline element."
},
{
"code": null,
"e": 230380,
"s": 229866,
"text": "\nWhile a span allows you to separate things from the other elements around them on a page or within a document, it does not cause a line break. This is why it is perfect for in-line styling, like coloring a single word in a sentence to draw more attention to it.\nBut a div, by default, creates a line break because it is used to make separate containers or boxes within a page or document, hence the name division. So the proper way to use a div is as a containing element, rather than an inline styling element.\n"
},
{
"code": null,
"e": 230642,
"s": 230380,
"text": "While a span allows you to separate things from the other elements around them on a page or within a document, it does not cause a line break. This is why it is perfect for in-line styling, like coloring a single word in a sentence to draw more attention to it."
},
{
"code": null,
"e": 230892,
"s": 230642,
"text": "But a div, by default, creates a line break because it is used to make separate containers or boxes within a page or document, hence the name division. So the proper way to use a div is as a containing element, rather than an inline styling element."
},
{
"code": null,
"e": 230921,
"s": 230892,
"text": "Example of a HTML <span> tag"
},
{
"code": null,
"e": 230981,
"s": 230921,
"text": "Example text that is red text and an example of a span tag."
},
{
"code": null,
"e": 231092,
"s": 230981,
"text": "HTML code:\n\n<p>Example text that is <span style=\"color:red;\">red text</span> and an example of a span tag.</p>"
},
{
"code": null,
"e": 231120,
"s": 231092,
"text": "Example of a HTML <div> tag"
},
{
"code": null,
"e": 231208,
"s": 231120,
"text": "An example of a div tag that has a maximum width of 200 pixels and a silver background."
},
{
"code": null,
"e": 231409,
"s": 231210,
"text": "HTML code:\n\n<div style=\"width: 200px; background-color:#E5E4E2;padding:10px;margin-bottom:2em;\">\n<p>An example of a div tag that has a maximum width of 200 pixels and a silver background.</p>\n</div>"
},
{
"code": null,
"e": 231617,
"s": 231409,
"text": "Android is an open source and Linux-based Operating System for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies."
},
{
"code": null,
"e": 231741,
"s": 231617,
"text": "The goal of android project is to create a successful real-world product that improves the mobile experience for end users."
},
{
"code": null,
"e": 232005,
"s": 231741,
"text": "Android Inc was founded in Palo Alto of California, U.S. by Andy Rubin, Rich miner, Nick sears and Chris White in 2003. Later Android Inc. was acquired by Google in 2005. After original release there have been number of updates in the original version of Android."
},
{
"code": null,
"e": 232144,
"s": 232005,
"text": "Versions usually come with a numerical code and a name that’s so far been themed after sweets and desserts, running in alphabetical order."
},
{
"code": null,
"e": 232164,
"s": 232144,
"text": "Android 1.5 Cupcake"
},
{
"code": null,
"e": 232182,
"s": 232164,
"text": "Android 1.6 Donut"
},
{
"code": null,
"e": 232201,
"s": 232182,
"text": "Android 2.1 Eclair"
},
{
"code": null,
"e": 232219,
"s": 232201,
"text": "Android 2.2 Froyo"
},
{
"code": null,
"e": 232243,
"s": 232219,
"text": "Android 2.3 Gingerbread"
},
{
"code": null,
"e": 232344,
"s": 232243,
"text": "Android 3.2 Honeycomb - The first OS design specifically for tablets, launching on the Motorola Xoom"
},
{
"code": null,
"e": 232458,
"s": 232344,
"text": "Android 4.0 Ice Cream Sandwich: The first OS to run on smartphones and tablets, ending the 2.X naming convention."
},
{
"code": null,
"e": 232528,
"s": 232458,
"text": "Android 4.1 Jelly Bean: Launched on the Google Nexus 7 tablet by Asus"
},
{
"code": null,
"e": 232578,
"s": 232528,
"text": "Android 4.2 Jelly Bean: Arrived on the LG Nexus 4"
},
{
"code": null,
"e": 232601,
"s": 232578,
"text": "Android 4.3 Jelly Bean"
},
{
"code": null,
"e": 232648,
"s": 232601,
"text": "Android 4.4 KitKat: Launched on the LG Nexus 5"
},
{
"code": null,
"e": 232719,
"s": 232648,
"text": "Android 5.0 Lollipop: Launched on the Motorola Nexus 6 and HTC Nexus 9"
},
{
"code": null,
"e": 232792,
"s": 232719,
"text": "Android 6.0 Marshmallow: Launched on the LG Nexus 5X and Huawei Nexus 6P"
},
{
"code": null,
"e": 232811,
"s": 232792,
"text": "Android 7.0 Nougat"
},
{
"code": null,
"e": 232882,
"s": 232811,
"text": "Android 7.1 Nougat: Launched on the HTC-made Google Pixel and Pixel XL"
},
{
"code": null,
"e": 232969,
"s": 232882,
"text": "Android 8.0 O: Currently in beta form, only available for developers (and the curious)"
},
{
"code": null,
"e": 233268,
"s": 232969,
"text": "Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites.XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user."
},
{
"code": null,
"e": 233387,
"s": 233268,
"text": "A cross-site scripting vulnerability may be used by attackers to bypass access control such as the same origin policy."
},
{
"code": null,
"e": 233537,
"s": 233387,
"text": "A successful cross site scripting attack can have devastating consequences for an online business's reputation and its relationship with its clients."
},
{
"code": null,
"e": 233967,
"s": 233537,
"text": "\nIn order for an XSS attack to take place the vulnerable website needs to directly include user input in its pages. An attacker can then insert a string that will be used within the web page and treated as code by the victim’s browser.\nThe following server-side pseudo-code is used to display the most recent comment on a web page.\nprint \"<html>\"\nprint \"<h1>Most recent comment</h1>\"\nprint database.latestComment\nprint \"</html>\"\n"
},
{
"code": null,
"e": 234202,
"s": 233967,
"text": "In order for an XSS attack to take place the vulnerable website needs to directly include user input in its pages. An attacker can then insert a string that will be used within the web page and treated as code by the victim’s browser."
},
{
"code": null,
"e": 234298,
"s": 234202,
"text": "The following server-side pseudo-code is used to display the most recent comment on a web page."
},
{
"code": null,
"e": 234395,
"s": 234298,
"text": "print \"<html>\"\nprint \"<h1>Most recent comment</h1>\"\nprint database.latestComment\nprint \"</html>\""
},
{
"code": null,
"e": 234609,
"s": 234395,
"text": "The transient keyword may be used as a property modifier in Java and is directly related with serialization. In short the properties declared as transient are not serialized by the default serialization mechanism."
},
{
"code": null,
"e": 234708,
"s": 234609,
"text": "transient keyword is used along with instance variable to exclude them from serialization process."
},
{
"code": null,
"e": 235112,
"s": 234708,
"text": "The transient access modifier is used at the time of object serialization in order not to serialize the instance variable value.\n\tIn the following code snippet, the content of the variable “nopersist” would not be saved. The content of the variable “number” would be saved.\n\tclass SampleSerialize \n{\n transient int nopersist; // will not persist\n int number; // will persist\n ......\n ......\n}\n \n"
},
{
"code": null,
"e": 235238,
"s": 235112,
"text": "class SampleSerialize \n{\n transient int nopersist; // will not persist\n int number; // will persist\n ......\n ......\n}"
},
{
"code": null,
"e": 235476,
"s": 235240,
"text": "Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object."
},
{
"code": null,
"e": 235544,
"s": 235476,
"text": "It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies."
},
{
"code": null,
"e": 235665,
"s": 235544,
"text": "A class must implement Serializable interface present in java.io package in order to serialize its object successfully. "
},
{
"code": null,
"e": 235675,
"s": 235665,
"text": "Example :"
},
{
"code": null,
"e": 235871,
"s": 235675,
"text": "import java.io.Serializable; \npublic class Student implements Serializable{ \n int id; \n String name; \n public Student(int id, String name) { \n this.id = id; \n this.name = name; \n } \n} "
},
{
"code": null,
"e": 236160,
"s": 235873,
"text": "As per the Second Normal Form there must not be any partial dependency of any column on primary key. It means that for a table that has concatenated primary key, each column in the table that is not part of the primary key must depend upon the entire concatenated key for its existence."
},
{
"code": null,
"e": 236238,
"s": 236160,
"text": "A database is in second normal form if it satisfies the following conditions:"
},
{
"code": null,
"e": 236265,
"s": 236238,
"text": "It is in first normal form"
},
{
"code": null,
"e": 236338,
"s": 236265,
"text": "All non-key attributes are fully functional dependent on the primary key"
},
{
"code": null,
"e": 236752,
"s": 236338,
"text": "A hypervisor is one of the most important components of comprehensive, server-based, distributed manufacturing automation systems. This abstraction allows the underlying host machine hardware to independently operate one or more virtual machine as guests, allowing multiple guest VMs to effectively share the system's physical compute resources, such as procesor cycles, memory space, network bandwidth and so on."
},
{
"code": null,
"e": 236871,
"s": 236752,
"text": "Secure Socket Shell, is a network protocol that provides administrators with a secure way to access a remote computer."
},
{
"code": null,
"e": 237016,
"s": 236871,
"text": "SSH provides a secure channel over an unsecured network in a client-server architecture, connecting an SSH client application with an SSH sever."
},
{
"code": null,
"e": 237142,
"s": 237016,
"text": "The SSH client drives the connection setup process and uses public key cryptography to verify the identity of the SSH server."
},
{
"code": null,
"e": 237357,
"s": 237142,
"text": "SSH is widely used by network administrators for managing systems and applications remotely, allowing them to log in to another computer over a network, execute commands and move files from one computer to another."
},
{
"code": null,
"e": 237569,
"s": 237357,
"text": "Telnet is a protocol that allows you to connect to remote computers (called hosts) over a TCP/IP network (such as the Internet). For example, typing telnet hostname would connect a user to a host named hostname."
},
{
"code": null,
"e": 237750,
"s": 237569,
"text": "The term telnet is also used to refer to the software that implements the client part of the protocol. Telnet client applications are available for virtually all computer platform."
},
{
"code": null,
"e": 237858,
"s": 237750,
"text": "Telnet is used most often for remote management but also sometimes for the initial setup for some devices ."
},
{
"code": null,
"e": 238057,
"s": 237858,
"text": "The tlntadmn commands allow you to remotely manage a computer running Telnet Server. These commands are run from the command prompt. Used without parameters, tlntadmn displays local server settings."
},
{
"code": null,
"e": 238279,
"s": 238057,
"text": "volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time-without any action being taken by the code the compiler finds nearby. "
},
{
"code": null,
"e": 238436,
"s": 238279,
"text": "This keyword prevents an optimizing compiler from optimizing away subsequent reads or writes and thus incorrectly reusing a stale value or omitting writes. "
},
{
"code": null,
"e": 238443,
"s": 238436,
"text": "Syntax"
},
{
"code": null,
"e": 238479,
"s": 238443,
"text": "volatile int foo;\nint volatile foo;"
},
{
"code": null,
"e": 238764,
"s": 238479,
"text": "This automatically precludes it being a member function! An object has to EXISTbefore it has a \"this\" pointer and thus a Vitale. ... Constructor can not be virtual, because when constructor of a class is executed there is no Vitale in the memory, means no virtual pointer defined yet."
},
{
"code": null,
"e": 239254,
"s": 238764,
"text": "TcpEndpoint objects allow you to easily establish and communicate over TCP/IP network connections between client and server processes, possibly residing on different hosts .\n\tThe TcpEndpoint class follows a telephone-like model of networking: clients \"call\" servers and servers \"answer\" clients. Once a network connection is established between a client and a server, the two can \"talk\" to each other by reading from and writing to the connection:\nClient <----------------------> Server\n \n"
},
{
"code": null,
"e": 239527,
"s": 239254,
"text": "The TcpEndpoint class follows a telephone-like model of networking: clients \"call\" servers and servers \"answer\" clients. Once a network connection is established between a client and a server, the two can \"talk\" to each other by reading from and writing to the connection:"
},
{
"code": null,
"e": 239566,
"s": 239527,
"text": "Client <----------------------> Server"
},
{
"code": null,
"e": 240028,
"s": 239568,
"text": "#include <stdio.h>\n#include <stdlib.h>\n \nint main()\n{\n int r = 3, c = 4;\n int *arr = (int *)malloc(r * c * sizeof(int));\n \n int i, j, count = 0;\n for (i = 0; i < r; i++)\n for (j = 0; j < c; j++)\n *(arr + i*c + j) = ++count;\n \n for (i = 0; i < r; i++)\n for (j = 0; j < c; j++)\n printf(\"%d \", *(arr + i*c + j));\n \n /* Code for further processing and free the \n dynamically allocated memory */\n \n return 0;\n}"
},
{
"code": null,
"e": 240039,
"s": 240028,
"text": " output :"
},
{
"code": null,
"e": 240082,
"s": 240041,
"text": " 1 2 3 4\n 5 6 7 8\n 9 10 11 12 "
},
{
"code": null,
"e": 240205,
"s": 240082,
"text": "ARP (Address Resolution Protocol) converts an Internet protocol(IP) address to its corresponding physical network address."
},
{
"code": null,
"e": 240322,
"s": 240205,
"text": "The protocol operates below the network layer as a part of the interface between the OSI network and OSI link layer."
},
{
"code": null,
"e": 240435,
"s": 240322,
"text": "ARP provides the protocol rules for making this correlation and providing address conversion in both directions."
},
{
"code": null,
"e": 240643,
"s": 240435,
"text": "The purpose of Address Resolution Protocol (ARP) is to find out the MAC address of a device in your Local Area Network, for the corresponding IPv4 address, which network application is trying to communicate."
},
{
"code": null,
"e": 240859,
"s": 240643,
"text": " It is used by network devices, including routers, to send error messages and operational information indicating, for example, that a requested service is not available or that a host or router could not be reached."
},
{
"code": null,
"e": 240982,
"s": 240859,
"text": "ICMP helps you gather information about a network. ICMP is an IP packet with an added header to define the ICMP protocol ."
},
{
"code": null,
"e": 241268,
"s": 240984,
"text": "When two or more objects are derived from a common base class, we can prevent multiple copies of the base class being present in an object derived from those objects by declaring the base class as virtual when it is being inherited. Such a base class is known as virtual base class. "
},
{
"code": null,
"e": 241451,
"s": 241268,
"text": "Virtual base classes, used in virtual inheritance, is a way of preventing multiple \"instances\" of a given class appearing in an inheritance hierarchy when using multiple inheritance."
},
{
"code": null,
"e": 241561,
"s": 241451,
"text": "Node.js is a very powerful JavaScript-based framework/platform built on Google Chrome's JavaScript V8 Engine."
},
{
"code": null,
"e": 241641,
"s": 241561,
"text": " Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36."
},
{
"code": null,
"e": 241759,
"s": 241641,
"text": "Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications."
},
{
"code": null,
"e": 241939,
"s": 241759,
"text": "Node.js enables JavaScript to be used for sever side scripting, and runs scripts server-side to produce dynamic web page content before the page is sent to the user's web browser."
},
{
"code": null,
"e": 242047,
"s": 241939,
"text": "Node.js connects the ease of a scripting language (JavaScript) with the power of Unix network programming ."
},
{
"code": null,
"e": 242197,
"s": 242047,
"text": "Like linear search and binary search, ternary search is a searching technique that is used to determine the position of a specific value in an array."
},
{
"code": null,
"e": 242399,
"s": 242197,
"text": "A ternary search determines either that the minimum or maximum cannot be in the first third of the domain or that it cannot be in the last third of the domain, then repeats on the remaining two-thirds."
},
{
"code": null,
"e": 242466,
"s": 242399,
"text": "A ternary search is an example of a divide and conquer algorithm ."
},
{
"code": null,
"e": 242697,
"s": 242466,
"text": "Stock market prediction is the act of trying to determine the future value of a company stock or other financial instrument traded on an exchange. The successful prediction of a stock's future price could yield significant profit."
},
{
"code": null,
"e": 242906,
"s": 242697,
"text": "The efficient market hypothesis suggests that stock prices reflect all currently available information and any price changes that are not based on newly revealed information thus are inherently unpredictable."
},
{
"code": null,
"e": 243067,
"s": 242908,
"text": "Primary Key is used to identify a row (record) in a table, whereas Unique-key is to prevent duplicate values in a column (with the exception of a null entry)."
},
{
"code": null,
"e": 243156,
"s": 243067,
"text": "PRIMARY KEY is always not null but columns with unique constraint can hold NULL values ."
},
{
"code": null,
"e": 243391,
"s": 243156,
"text": "When you create a UNIQUE constraint, the database automatically creates a UNIQUE index. For MS SQL Server databases, a PRIMARY KEY will generate a unique CLUSTERED INDEX. A UNIQUE constraint will generate a unique NON-CLUSTERED INDEX."
},
{
"code": null,
"e": 243503,
"s": 243391,
"text": "There will be only one primary key in a table whereas More than one unique key will be there in a table. "
},
{
"code": null,
"e": 243563,
"s": 243503,
"text": "Every primary is a unique but every unique is not primary ."
},
{
"code": null,
"e": 243575,
"s": 243563,
"text": "Pseudocode:"
},
{
"code": null,
"e": 243947,
"s": 243575,
"text": "curNodePtr := FirstNode\n\nif curNodePtr == NULL\n return 'Less Nodes in the List'\n\nforever:\n\n tmpPtr := curNodePtr\n count := 0\n\n forever:\n\n if tmpPtr == NULL || count == N\n break\n\n tmpPtr := tmpPtr.NEXT\n count++\n\n if tmpPtr == NULL\n if count == n\n return curNodePtr\n else\n return 'Less Nodes in the List'\n\n curNodePtr := curNodePtr.NEXT "
},
{
"code": null,
"e": 243959,
"s": 243947,
"text": "Complexity:"
},
{
"code": null,
"e": 244025,
"s": 243959,
"text": "Time Complexity: O(n^2) - For traversing each node after curNode."
},
{
"code": null,
"e": 244048,
"s": 244025,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 244386,
"s": 244048,
"text": "In graph theory and computer science, the lowest common ancestor (LCA) of two nodes v and w in a tree or directed acyclic graph (DAG) T is the lowest (i.e. deepest) node that has both v and w as descendants, where we define each node to be a descendant of itself (so if v has a direct connection from w, w is the lowest common ancestor)."
},
{
"code": null,
"e": 244396,
"s": 244386,
"text": "Example :"
},
{
"code": null,
"e": 244532,
"s": 244396,
"text": "In this tree, the lowest common ancestor of the nodes x and y is marked in dark green. Other common ancestors are shown in light green."
},
{
"code": null,
"e": 244623,
"s": 244532,
"text": "Message passing is a type of communication between process or objects in computer science."
},
{
"code": null,
"e": 244876,
"s": 244623,
"text": "Message passing is used ubiquitously in modern computer software. It is used as a way for the objects that make up a program to work with each other and as a means for objects and systems running on different computers (e.g., the Internet) to interact."
},
{
"code": null,
"e": 245047,
"s": 244876,
"text": "An Interface is basically a kind of class like class Interface contain method and variable but with a measure difference in it contain a abstract method and final fields."
},
{
"code": null,
"e": 245159,
"s": 245047,
"text": "This means that Interface do not specify or to Implement for these method and data field contain only constant."
},
{
"code": null,
"e": 245196,
"s": 245159,
"text": "Syntax for declaring the Interface :"
},
{
"code": null,
"e": 245547,
"s": 245196,
"text": "[access specifier] interface <interface name>\n\n{\n\n return type method name1(Parameter list);\n\n return type method name2(Parameter list);\n\n------------------------------------------------------\n\nreturn type method nameN(Parameter list);\n\nFinal constant value 1;\n\nFinal constant value 2;\n\n-----------------\n\n--------------\n\nFinal constant value N;\n\n}"
},
{
"code": null,
"e": 245557,
"s": 245547,
"text": "Example :"
},
{
"code": null,
"e": 245791,
"s": 245557,
"text": "interface printable{ \nvoid print(); \n} \nclass A6 implements printable{ \npublic void print(){System.out.println(\"Hello\");} \n \npublic static void main(String args[]){ \nA6 obj = new A6(); \nobj.print(); \n } \n} \n\noutput :\nHello"
},
{
"code": null,
"e": 245979,
"s": 245793,
"text": "An Abstract class is a class just opposite to final modifier .An abstract class is a class that does not have body of the method that means we declare the method only not implemented ."
},
{
"code": null,
"e": 246007,
"s": 245979,
"text": "Syntax For Abstract Class :"
},
{
"code": null,
"e": 246086,
"s": 246007,
"text": "We used Abstract Keyword for declare the class and declaration of the method ."
},
{
"code": null,
"e": 246305,
"s": 246089,
"text": "abstract class <class name>\n{\n abstract method Name1(Parameter list);\n abstract method Name2(Parameter list);\n\n -----------------\n \nreturn type method name3(Parameter list)\n{\n body of the method\n}\n}"
},
{
"code": null,
"e": 246344,
"s": 246305,
"text": "An abstract class cannot be instanced."
},
{
"code": null,
"e": 246552,
"s": 246344,
"text": "An abstract method of an abstract class must be define in is sub class .It can be used to create object reference because java approach to run time polymorphism is implemented to super .class references ."
},
{
"code": null,
"e": 246563,
"s": 246552,
"text": " Example :"
},
{
"code": null,
"e": 246789,
"s": 246563,
"text": "abstract class Bike{ \n abstract void run(); \n} \nclass Honda4 extends Bike{ \nvoid run(){System.out.println(\"running safely..\");} \npublic static void main(String args[]){ \n Bike obj = new Honda4(); \n obj.run(); \n} \n} "
},
{
"code": null,
"e": 247026,
"s": 246791,
"text": "Most differences between the features of the two languages arise due to the use of different programming paradigm. C breaks down to functions while JAVA breaks down to Objects. C is more procedure-oriented while JAVA is data-oriented."
},
{
"code": null,
"e": 247140,
"s": 247026,
"text": "Java uses a “Garbage Collector” which manages memory automatically so the programmer doesn’t have to handle that."
},
{
"code": null,
"e": 247375,
"s": 247140,
"text": "Java doesn't support the enum keyword used in C to define types that consist of fixed sets of named values. This is surprising for a strongly typed language like Java, but there are ways to simulate this feature with object constants."
},
{
"code": null,
"e": 247485,
"s": 247375,
"text": "Java doesn't support C struct and union types. A Java class can be thought of as an enhanced struct, however."
},
{
"code": null,
"e": 247576,
"s": 247485,
"text": "Operator overloading in C is an important feature which is not supported in Java language."
},
{
"code": null,
"e": 247832,
"s": 247576,
"text": "In computer science, a self-balancing (or height-balanced) binary search tree is any node-based binary search tree that automatically keeps its height (maximal number of levels below the root) small in the face of arbitrary item insertions and deletions ."
},
{
"code": null,
"e": 248075,
"s": 247832,
"text": "AVL trees are used for performing search operations on high dimension external data storage. For example, a phone call list may generate a huge database which may be recorded only on external hard drives, hard-disks or other storage devices ."
},
{
"code": null,
"e": 248146,
"s": 248075,
"text": "The structure of the nodes of a balanced tree can be represented like:"
},
{
"code": null,
"e": 248208,
"s": 248146,
"text": "\nstruct NodeAVL{\n int key;\n int ech;\n node *left, *right;\n}; "
},
{
"code": null,
"e": 248215,
"s": 248208,
"text": "Where:"
},
{
"code": null,
"e": 248269,
"s": 248215,
"text": "- key represents the tag of the node(integer number),"
},
{
"code": null,
"e": 248307,
"s": 248269,
"text": "- ech represents the balancing factor"
},
{
"code": null,
"e": 248375,
"s": 248307,
"text": "- left and right represent pointers to the left and right children."
},
{
"code": null,
"e": 248385,
"s": 248375,
"text": "Example :"
},
{
"code": null,
"e": 248417,
"s": 248385,
"text": " AVL tree with balance factors "
},
{
"code": null,
"e": 248633,
"s": 248417,
"text": "Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor."
},
{
"code": null,
"e": 248726,
"s": 248633,
"text": "for detail review :http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors"
},
{
"code": null,
"e": 248956,
"s": 248726,
"text": "Windows Azure, which was later renamed as Microsoft Azure in 2014, is a cloud computing platform, designed by Microsoft to successfully build, deploy, and manage applications and services through a global network of data centers."
},
{
"code": null,
"e": 249076,
"s": 248956,
"text": "Microsoft Azure is widely considered both a Platform as Service (PaaS) and Infrastructure as a Service (IaaS) offering."
},
{
"code": null,
"e": 249196,
"s": 249076,
"text": "C++ supports both procedural and object oriented programming paradigms; therefore C++ is also called a hybrid language."
},
{
"code": null,
"e": 249287,
"s": 249196,
"text": "C++ allows the declaration of variable anywhere in the scope i.e at time of its First use."
},
{
"code": null,
"e": 249338,
"s": 249287,
"text": " C++ supports Exception Handling while C does not."
},
{
"code": null,
"e": 249436,
"s": 249338,
"text": "C++ provides Boolean or String data types. It supports both user-defined and built-in data types."
},
{
"code": null,
"e": 249527,
"s": 249436,
"text": "Data is hidden in C++ and is not accessible to external functions. Hence, is more secure ."
},
{
"code": null,
"e": 249574,
"s": 249527,
"text": "C++ program file is saved with .CPP extension."
},
{
"code": null,
"e": 249724,
"s": 249574,
"text": "C++ does provide references too. It considers them as aliases to another variable or object. They are safer than pointers where they can be used.\n\n\t "
},
{
"code": null,
"e": 250005,
"s": 249724,
"text": "Bing is a web search engine owned and operated by Microsoft. The service has its origins in Microsoft's previous search engines: MSN Search, Windows Live Search and later Live Search. Bing provides a variety of search services, including web, video, image and map search products."
},
{
"code": null,
"e": 250024,
"s": 250005,
"text": "Benefits of Bing :"
},
{
"code": null,
"e": 250060,
"s": 250024,
"text": "Search for cash with Bing Rewards ."
},
{
"code": null,
"e": 250112,
"s": 250060,
"text": "\nSearch quality: as good or better than Google's .\n"
},
{
"code": null,
"e": 250162,
"s": 250112,
"text": "Search quality: as good or better than Google's ."
},
{
"code": null,
"e": 250188,
"s": 250162,
"text": "\nBing gets the picture .\n"
},
{
"code": null,
"e": 250212,
"s": 250188,
"text": "Bing gets the picture ."
},
{
"code": null,
"e": 250288,
"s": 250212,
"text": "\nBing gives more auto complete suggestions than Google does in most cases.\n"
},
{
"code": null,
"e": 250362,
"s": 250288,
"text": "Bing gives more auto complete suggestions than Google does in most cases."
},
{
"code": null,
"e": 250551,
"s": 250362,
"text": "Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. "
},
{
"code": null,
"e": 250877,
"s": 250551,
"text": "Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding."
},
{
"code": null,
"e": 250895,
"s": 250877,
"text": " Example :"
},
{
"code": null,
"e": 251864,
"s": 250895,
"text": "Public class EncapsulationDemo{\n private int ssn;\n private String empName;\n private int empAge;\n\n //Getter and Setter methods\n public int getEmpSSN(){\n return ssn;\n }\n\n public String getEmpName(){\n return empName;\n }\n\n public int getEmpAge(){\n return empAge;\n }\n\n public void setEmpAge(int newValue){\n empAge = newValue;\n }\n\n public void setEmpName(String newValue){\n empName = newValue;\n }\n\n public void setEmpSSN(int newValue){\n ssn = newValue;\n }\n}\npublic class EncapsTest{\n public static void main(String args[]){\n EncapsulationDemo obj = new EncapsulationDemo();\n obj.setEmpName(\"Mario\");\n obj.setEmpAge(32);\n obj.setEmpSSN(112233);\n System.out.println(\"Employee Name: \" + obj.getEmpName());\n System.out.println(\"Employee SSN: \" + obj.getEmpSSN());\n System.out.println(\"Employee Age: \" + obj.getEmpAge());\n } \n}"
},
{
"code": null,
"e": 251872,
"s": 251864,
"text": "Output:"
},
{
"code": null,
"e": 251931,
"s": 251872,
"text": "Employee Name: Mario\nEmployee SSN: 112233\nEmployee Age: 32"
},
{
"code": null,
"e": 252020,
"s": 251931,
"text": "Cloud computing is a general term for the delivery of hosted services over the internet."
},
{
"code": null,
"e": 252190,
"s": 252020,
"text": "Simply put, cloud computing is the delivery of computing services—servers, storage, databases, networking, software, analytics and more—over the Internet (“the cloud”) ."
},
{
"code": null,
"e": 252419,
"s": 252190,
"text": "Examples of cloud services include online data storage and backup solutions, Web-based e-mail services, hosted office suites and document collaboration services, database processing, managed technical support services and more. "
},
{
"code": null,
"e": 252434,
"s": 252419,
"text": "Pseudo Code : "
},
{
"code": null,
"e": 252697,
"s": 252434,
"text": "public class Singleton {\n private Singleton() {}\n\n private static class SingletonHolder {\n private static final Singleton INSTANCE = new Singleton();\n }\n\n public static Singleton getInstance() {\n return SingletonHolder.INSTANCE;\n }\n}"
},
{
"code": null,
"e": 252831,
"s": 252699,
"text": "A load balancer is a device that acts as a reverse proxy and distributes network or application traffic across a number of servers."
},
{
"code": null,
"e": 253000,
"s": 252831,
"text": "Load Balancers that optimize the performance of servers delivering important content to in house users as well as co-workers form other companies or the general public."
},
{
"code": null,
"e": 253134,
"s": 253000,
"text": "Load balancing usually involves dedicated software or hardware, such as a multilayer Switch or a Domain Name Service server process ."
},
{
"code": null,
"e": 253385,
"s": 253134,
"text": "Software as a service (or SaaS) is a way of delivering applications over the Internet—as a service. Instead of installing and maintaining software, you simply access it via the Internet, freeing yourself from complex software and hardware management."
},
{
"code": null,
"e": 253460,
"s": 253385,
"text": "SaaS is typically accessed by users using a thin client via a web browser."
},
{
"code": null,
"e": 253511,
"s": 253460,
"text": "Examples of where SaaS can be used by enterprises:"
},
{
"code": null,
"e": 253536,
"s": 253511,
"text": "Accounting and invoicing"
},
{
"code": null,
"e": 253551,
"s": 253536,
"text": "Tracking sales"
},
{
"code": null,
"e": 253560,
"s": 253551,
"text": "Planning"
},
{
"code": null,
"e": 253584,
"s": 253560,
"text": "Performance monitoring "
},
{
"code": null,
"e": 253634,
"s": 253584,
"text": "Communications (including web mail and messaging)"
},
{
"code": null,
"e": 253881,
"s": 253634,
"text": "The registry is a single place for keeping such information as what hardware is attached, what system options have been selected, how computer memory is set up, and what application programs are to be present when the operating system is started."
},
{
"code": null,
"e": 254003,
"s": 253881,
"text": "The Windows Registry is meant to solve that problem by providing a single place for all settings across all applications."
},
{
"code": null,
"e": 254144,
"s": 254003,
"text": "Java is platform independent because of the machine independent code also called \"Byte Code\". Which make java a purely platform independent."
},
{
"code": null,
"e": 254281,
"s": 254144,
"text": "Which can be once complied, can be run anywhere on any platform. Only necessity is the availability of Java Run-time Environment (JVM) ."
},
{
"code": null,
"e": 254484,
"s": 254283,
"text": "A memory leak is the gradual loss of available computer memory when a program (an application or part of the operating system) repeatedly fails to return memory that it has obtained for temporary use."
},
{
"code": null,
"e": 254569,
"s": 254484,
"text": "Memory leak occurs when programmers create a memory in heap and forget to delete it."
},
{
"code": null,
"e": 254614,
"s": 254569,
"text": "A memory leak is also known as a space leak."
},
{
"code": null,
"e": 254713,
"s": 254614,
"text": "A transient event is a short-lived burst of energy in a system caused by a sudden change of state."
},
{
"code": null,
"e": 254965,
"s": 254713,
"text": "The transient is the behavior of the circuit (for example) after a certain action, and this behavior didn't last for a long time. After this transient period the steady state behavior dominate, i.e. the steady state solution is at t tends to infinity."
},
{
"code": null,
"e": 255064,
"s": 254965,
"text": "An example of transient oscillation can be found in digital (pulse) signals in computer networks ."
},
{
"code": null,
"e": 255466,
"s": 255066,
"text": "Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement ."
},
{
"code": null,
"e": 255489,
"s": 255466,
"text": "Synchronized methods :"
},
{
"code": null,
"e": 255498,
"s": 255489,
"text": "Example:"
},
{
"code": null,
"e": 255544,
"s": 255498,
"text": "Public synchronized void increment()\n{\nX++;\n}"
},
{
"code": null,
"e": 255568,
"s": 255544,
"text": "Synchronize statement :"
},
{
"code": null,
"e": 255577,
"s": 255568,
"text": "Example:"
},
{
"code": null,
"e": 255698,
"s": 255577,
"text": "public void run()\n{\nsynchronized(p1)\n{ //synchronize statement. P1 here is an object of some class P\np1.display(s1);\n}\n}"
},
{
"code": null,
"e": 256105,
"s": 255700,
"text": "Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.\n\tclass HelloTest extends Thread{ \n public void run(){ \n System.out.println(\"running...\"); \n } \n public static void main(String args[]){ \n HelloTest t1=new HelloTest(); \n t1.run();//fine, but does not start a separate call stack \n } \n} \n\n\nOutput :\n"
},
{
"code": null,
"e": 256355,
"s": 256105,
"text": "class HelloTest extends Thread{ \n public void run(){ \n System.out.println(\"running...\"); \n } \n public static void main(String args[]){ \n HelloTest t1=new HelloTest(); \n t1.run();//fine, but does not start a separate call stack \n } \n} \n\n"
},
{
"code": null,
"e": 256364,
"s": 256355,
"text": "Output :"
},
{
"code": null,
"e": 256385,
"s": 256364,
"text": " running..."
},
{
"code": null,
"e": 256467,
"s": 256385,
"text": "A package is a name space that organizes a set of related classes and interfaces."
},
{
"code": null,
"e": 256630,
"s": 256467,
"text": "A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and namespace management."
},
{
"code": null,
"e": 256693,
"s": 256630,
"text": "Using package it becomes easier to locate the related classes."
},
{
"code": null,
"e": 256775,
"s": 256693,
"text": "In java there are already many predefined packages that we use while programming."
},
{
"code": null,
"e": 256825,
"s": 256775,
"text": "For example: java.lang, java.io, java.util etc."
},
{
"code": null,
"e": 256985,
"s": 256825,
"text": "Defining a Package:\nThis statement should be used in the beginning of the program to include that program in that particular package.\n package <package name> ."
},
{
"code": null,
"e": 256994,
"s": 256985,
"text": "Example:"
},
{
"code": null,
"e": 257098,
"s": 256994,
"text": "package hello;\npublic class Trap {\n public void id ()\n {\n System.out.println (\"Trap\");\n }\n}"
},
{
"code": null,
"e": 257275,
"s": 257098,
"text": "The C library function void *realloc(void *ptr, size_t size)attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc."
},
{
"code": null,
"e": 257287,
"s": 257275,
"text": "Declaration"
},
{
"code": null,
"e": 257340,
"s": 257287,
"text": "Following is the declaration for realloc() function."
},
{
"code": null,
"e": 257378,
"s": 257340,
"text": "void *realloc(void *ptr, size_t size)"
},
{
"code": null,
"e": 257438,
"s": 257378,
"text": "for detail review : http://www.geeksforgeeks.org/g-fact-66/"
},
{
"code": null,
"e": 257453,
"s": 257438,
"text": "Pseudo Code : "
},
{
"code": null,
"e": 257470,
"s": 257453,
"text": "Important Fact :"
},
{
"code": null,
"e": 257482,
"s": 257470,
"text": "S1: Stack 1"
},
{
"code": null,
"e": 257494,
"s": 257482,
"text": "S2: Stack 2"
},
{
"code": null,
"e": 257512,
"s": 257494,
"text": "x: Data (A,B,etc)"
},
{
"code": null,
"e": 257553,
"s": 257512,
"text": " Enqueue(S1,x){\n \n push(S1,x);\n\n}"
},
{
"code": null,
"e": 257747,
"s": 257553,
"text": "Dequeue(S1,S2)\n{\n\n if(S2 is not empty)\n \n return(pop(s2));\n\n}\n else {\n \n while(S1 is not empty)\n \n{\n x=pop(S1);\n push(S2,x); \n\n}\n return(pop(s2))\n}"
},
{
"code": null,
"e": 257766,
"s": 257747,
"text": "Time Complexity : "
},
{
"code": null,
"e": 257818,
"s": 257766,
"text": "Best case: O(1)\nAverage case: O(1)\nWorst case: O(n)"
},
{
"code": null,
"e": 257973,
"s": 257820,
"text": "Windows 8 doesn’t have a Start Menu. Instead, it has a ‘Charms Bar’ (see right) which is where you go to shut down and use other tools such as ‘Search’."
},
{
"code": null,
"e": 258237,
"s": 257973,
"text": "Traditionally, users type in passwords in order to gain access to their locked computers. Windows 8 adds the picture password. When logging in, users are presented with a picture and by touching features in the photo in the right order they can unlock the device."
},
{
"code": null,
"e": 258561,
"s": 258237,
"text": "\nWindows 8 includes hundreds of small features. For instance, faster boot times, Airplane mode, enhanced copy/move/paste operations, native antivirus program (Windows Defender now includes all features of Microsoft Security Essential), fully customizable lock screen, custom refresh image and better multi-monitor support.\n"
},
{
"code": null,
"e": 258883,
"s": 258561,
"text": "Windows 8 includes hundreds of small features. For instance, faster boot times, Airplane mode, enhanced copy/move/paste operations, native antivirus program (Windows Defender now includes all features of Microsoft Security Essential), fully customizable lock screen, custom refresh image and better multi-monitor support."
},
{
"code": null,
"e": 259173,
"s": 258883,
"text": "Compatibility is always an issue when talking about operating systems. Luckily, they are both compatible with almost all applications and programs. The only key difference is that Windows 8 was developed at a later time, giving it an edge for troubleshooting current compatibility issues ."
},
{
"code": null,
"e": 259507,
"s": 259173,
"text": "For Windows 8, a clean install also contains the extended Windows Defender technology, which, for the first time incorporates complete anti malware functionality – also optimized for memory and resource use. (This functionality does not exist on a clean install of Windows 7 where we would recommend that you add security software) ."
},
{
"code": null,
"e": 259625,
"s": 259507,
"text": "Addition/Deletion of an element from the list at any index which is an O(1) operation in Lists as compared to Arrays."
},
{
"code": null,
"e": 259809,
"s": 259625,
"text": "Arrays are good for random access and good for sequential access (both are in constant time). Linked lists on the other hand are constant for sequential, but linear for random access."
},
{
"code": null,
"e": 259947,
"s": 259809,
"text": "As the linked list doesn't have a size limit, we can go on adding new nodes (elements) and increasing the size of the list to any extent."
},
{
"code": null,
"e": 260033,
"s": 259947,
"text": "Data structures such as stack and queues can be easily implemented using linked list."
},
{
"code": null,
"e": 260225,
"s": 260033,
"text": "An important advantage of linked lists over arrays is that the linked list uses exactly as much memory as it needs, and can be made to expand to fill all available memory locations if needed."
},
{
"code": null,
"e": 260371,
"s": 260225,
"text": "It is not necessary to know in advance the number of elements to be stored in the list and therefore, need not allocate. d as and when necessary."
},
{
"code": null,
"e": 260470,
"s": 260371,
"text": "A makefile is used with the Unix make utility to determine which portions of a program to compile."
},
{
"code": null,
"e": 260545,
"s": 260470,
"text": "Make provides most help when the program consists of many component files."
},
{
"code": null,
"e": 260680,
"s": 260545,
"text": "Makefiles are special format files that together with the make utility will help you to automagically build and manage your projects ."
},
{
"code": null,
"e": 260697,
"s": 260680,
"text": "The make utility"
},
{
"code": null,
"e": 260702,
"s": 260697,
"text": "make"
},
{
"code": null,
"e": 260791,
"s": 260702,
"text": "this program will look for a file named makefile in your directory, and then execute it."
},
{
"code": null,
"e": 260866,
"s": 260791,
"text": "If you have several makefiles, then you can execute them with the command:"
},
{
"code": null,
"e": 260885,
"s": 260866,
"text": "make -f MyMakefile"
},
{
"code": null,
"e": 260895,
"s": 260885,
"text": "Extern : "
},
{
"code": null,
"e": 261010,
"s": 260895,
"text": "The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere else."
},
{
"code": null,
"e": 261183,
"s": 261010,
"text": "An external variable may also be declared inside a function. In this case the extern keyword must be used, otherwise the compiler will consider it a definition of a local ."
},
{
"code": null,
"e": 261491,
"s": 261183,
"text": "A variable that is explicitly declared to be external cannot be redefined since it is declared in another source file nor any additional storage tp be allocated to it.An external declaration merely serves to declare for the remainder of that source such that a variable exists and has been created earlier."
},
{
"code": null,
"e": 261507,
"s": 261491,
"text": " Example :"
},
{
"code": null,
"e": 261750,
"s": 261507,
"text": "\nint num = 75 ; \n\nvoid display();\n\nvoid main()\n{\n extern int num ;\n printf(\"nNum : %d\",num);\n display();\n}\n\nvoid display()\n{\n extern int num ;\n printf(\"nNum : %d\",num);\n}\nOutput :\nNum : 75\nNum : 75\nStatic Variable :\n"
},
{
"code": null,
"e": 261973,
"s": 261750,
"text": "int num = 75 ; \n\nvoid display();\n\nvoid main()\n{\n extern int num ;\n printf(\"nNum : %d\",num);\n display();\n}\n\nvoid display()\n{\n extern int num ;\n printf(\"nNum : %d\",num);\n}\nOutput :\nNum : 75\nNum : 75"
},
{
"code": null,
"e": 261991,
"s": 261973,
"text": "Static Variable :"
},
{
"code": null,
"e": 262219,
"s": 261991,
"text": "\nStatic variables have a property of preserving their value even after they are out of their scope . Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.\n"
},
{
"code": null,
"e": 262445,
"s": 262219,
"text": "Static variables have a property of preserving their value even after they are out of their scope . Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope."
},
{
"code": null,
"e": 262528,
"s": 262445,
"text": "\nDefault initial value of static integral type variables are zero otherwise null.\n"
},
{
"code": null,
"e": 262609,
"s": 262528,
"text": "Default initial value of static integral type variables are zero otherwise null."
},
{
"code": null,
"e": 262828,
"s": 262609,
"text": "\nStatic variables may be initialized in their declarations; however, the initializes must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable.\n"
},
{
"code": null,
"e": 263045,
"s": 262828,
"text": "Static variables may be initialized in their declarations; however, the initializes must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable."
},
{
"code": null,
"e": 263061,
"s": 263045,
"text": " Example :"
},
{
"code": null,
"e": 263380,
"s": 263061,
"text": "\n#include <stdio.h>\nstatic int i=10;\nint main(){\n i=5;\n for(i=0;i<5;i++){\n static int a=10; //This statement will execute\n //only time.\n printf(\"%d\",a++);//This statement will execute\n //five times.\n } \n return 0;\n}\n\nOutput: 10 11 12 13 14"
},
{
"code": null,
"e": 263576,
"s": 263382,
"text": "Virtual Memory is a space where large programs can store themselves in form of pages while their execution and only the required pages or portions of processes are loaded into the main memory ."
},
{
"code": null,
"e": 263681,
"s": 263576,
"text": "The operating system manages virtual address spaces and the assignment of real memory to virtual memory."
},
{
"code": null,
"e": 263870,
"s": 263681,
"text": "The purpose of virtual memory is to enlarge the address space, the set of addresses a program can utilize. For example, virtual memory might contain twice as many addresses as main memory."
},
{
"code": null,
"e": 263954,
"s": 263872,
"text": "Hashing is one simple option for this. We can put all words in a hash table .But "
},
{
"code": null,
"e": 264059,
"s": 263954,
"text": "the worst case running time would be O(n) where n would be the total number of elements in dictionary . "
},
{
"code": null,
"e": 264092,
"s": 264059,
"text": "so we have used Trie which have "
},
{
"code": null,
"e": 264174,
"s": 264092,
"text": " Worst case time taken in case of Trie is O(m) where m is the length of string .\n"
},
{
"code": null,
"e": 264264,
"s": 264174,
"text": " for detail review :http://www.geeksforgeeks.org/data-structure-dictionary-spell-checker/"
},
{
"code": null,
"e": 264401,
"s": 264264,
"text": "A stack frame is a memory management strategy used to create and destroy temporary (automatic) variables in some programming languages ."
},
{
"code": null,
"e": 264513,
"s": 264401,
"text": "The stack frame is a procedure contains all necessary information to save and restore the state of a procedure."
},
{
"code": null,
"e": 264610,
"s": 264513,
"text": "Each stack frame contains space for actual parameter, local variables, temporary locations etc ."
},
{
"code": null,
"e": 264687,
"s": 264610,
"text": "The stack frames are allocated in a region of memory called the call stack ."
},
{
"code": null,
"e": 264841,
"s": 264687,
"text": "Threads can directly communicate with other threads of its process; processes must use inter process communication to communicate with sibling processes."
},
{
"code": null,
"e": 264943,
"s": 264841,
"text": "Both process and threads are independent path of execution but one process can have multiple Threads."
},
{
"code": null,
"e": 265121,
"s": 264943,
"text": "Each process has its own code, data and kernel context (VM structures, descriptor table, etc). While the threads of a process, they share the same code, data and kernel context."
},
{
"code": null,
"e": 265234,
"s": 265121,
"text": "New threads are easily created. However the creation of new processes require duplication of the parent process."
},
{
"code": null,
"e": 265440,
"s": 265234,
"text": "Processes are heavily dependent on system resources available while threads require minimal amounts of resource, so a process is considered as heavyweight while a thread is termed as a lightweight process."
},
{
"code": null,
"e": 265688,
"s": 265440,
"text": "Defragmentation is the process of locating the non contiguous fragments of data into which a computer file may be divided as it is stored on a hard disk, and rearranging the fragments and restoring them into fewer fragments or into the whole file."
},
{
"code": null,
"e": 265801,
"s": 265688,
"text": "It also attempts to create larger regions of free space using compaction to impede the return of fragmentation ."
},
{
"code": null,
"e": 265984,
"s": 265801,
"text": "Defragmentation works by locating file fragments that are scattered and putting them back together. The purpose is to decrease file access times and increase space on the hard-drive."
},
{
"code": null,
"e": 266243,
"s": 265988,
"text": "An access code is a password you use to access course content online. The content you access depends on the course, but can include things such as practice exam questions, interactive videos to help you understand course concepts, and course assignments."
},
{
"code": null,
"e": 266269,
"s": 266243,
"text": "Access code may refer to:"
},
{
"code": null,
"e": 266288,
"s": 266269,
"text": "In authentication:"
},
{
"code": null,
"e": 266312,
"s": 266288,
"text": "Password, a secret word"
},
{
"code": null,
"e": 266374,
"s": 266312,
"text": "Personal Identification Number (PIN), a secret numeric code ."
},
{
"code": null,
"e": 266457,
"s": 266374,
"text": "Cookie is a piece of code that are transmitted by a server to the client browser ."
},
{
"code": null,
"e": 266554,
"s": 266457,
"text": "Cookies were designed to be a reliable mechanism for websites to remember stateful information ."
},
{
"code": null,
"e": 266642,
"s": 266554,
"text": "Cookies may also be called a web cookie, Internet cookie,browser cookie or HTTP cookie."
},
{
"code": null,
"e": 266654,
"s": 266642,
"text": "Advantage :"
},
{
"code": null,
"e": 266670,
"s": 266654,
"text": "Authorization ."
},
{
"code": null,
"e": 266688,
"s": 266670,
"text": "Faster response ."
},
{
"code": null,
"e": 266703,
"s": 266688,
"text": " Pseudo code :"
},
{
"code": null,
"e": 266839,
"s": 266703,
"text": "c=0 s1=Head;\nwhile(Head!=0)\n{\n c=c+1;\n s1=s1->next;\n\n}\nc=ceil(c/2);\nwhile(c!=1){\n\n c=c-1;\n Head=Head->next;\n}\nreturn(Head);"
},
{
"code": null,
"e": 266923,
"s": 266839,
"text": " In level order traversal, we visit the nodes level by level from left to right. \n\n"
},
{
"code": null,
"e": 267060,
"s": 266925,
"text": "AVL tree is a self-balancing Binary Search Tree (BST) where the height of the two child sub trees of any node differ by at most one ."
},
{
"code": null,
"e": 267185,
"s": 267060,
"text": "If at any time they differ by more than one, rebalancing is done to restore this property. Lookup, insertion, and deletion ."
},
{
"code": null,
"e": 267202,
"s": 267185,
"text": " Example :"
},
{
"code": null,
"e": 267330,
"s": 267202,
"text": "The above tree is AVL because differences between heights of left and right subtrees for every node is less than or equal to 1."
},
{
"code": null,
"e": 267404,
"s": 267330,
"text": "for detail refer : http://www.geeksforgeeks.org/avl-tree-set-1-insertion/"
},
{
"code": null,
"e": 267489,
"s": 267404,
"text": "XML file validated by compile the XML file with a XML compiler (DTD or XML schema) ."
},
{
"code": null,
"e": 267587,
"s": 267489,
"text": "DTD contain he pre-defined XML structure to cover the possible errors in the developed XML file ."
},
{
"code": null,
"e": 267660,
"s": 267587,
"text": "XML file is valid if and only if its satisfy the following constraints ."
},
{
"code": null,
"e": 267723,
"s": 267660,
"text": "Every opening tag must contain the corresponding closing tag ."
},
{
"code": null,
"e": 267758,
"s": 267723,
"text": "No-overlapping tag in a XML file ."
},
{
"code": null,
"e": 267849,
"s": 267758,
"text": "It is not possible to test for NULL values with comparison operators, such as =, <, or <>."
},
{
"code": null,
"e": 267909,
"s": 267849,
"text": "We will have to use the IS NULL and IS NOT NULL operators ."
},
{
"code": null,
"e": 267918,
"s": 267909,
"text": "Syntax :"
},
{
"code": null,
"e": 267981,
"s": 267918,
"text": "SELECT column_names\nFROM table_name\nWHERE column_name IS NULL;"
},
{
"code": null,
"e": 268215,
"s": 267981,
"text": "HashMap is similar to Hash table with two exceptions .Basically HashMap methods are unsynchronized and it can allow null key and also null value which cannot allow in Hash table .HashMap maintain the key and value pairs <Key,Value> ."
},
{
"code": null,
"e": 268434,
"s": 268215,
"text": "It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. It neither does any kind of sorting to the stored keys and Values."
},
{
"code": null,
"e": 268478,
"s": 268434,
"text": "Create and add objects in Hash-map in Java "
},
{
"code": null,
"e": 268543,
"s": 268478,
"text": "HashMap<String, Integer> cache = new HashMap<String, Integer>();"
},
{
"code": null,
"e": 268894,
"s": 268543,
"text": "Trie is an ordered tree data structure that uses strings as keys. Unlike Binary Trees, Tries store keys associated with the node. The key is actually determined based on the position of the node on the tree.All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string ."
},
{
"code": null,
"e": 269020,
"s": 268894,
"text": "Since this data structure is a prefix tree, trie is commonly used in Dictionaries, Phone Directories and matching algorithms."
},
{
"code": null,
"e": 269089,
"s": 269020,
"text": "A trie for keys \"A\",\"to\", \"tea\", \"ted\", \"ten\", \"i\", \"in\", and \"inn\"."
},
{
"code": null,
"e": 269130,
"s": 269089,
"text": "Optimization using dynamic programming :"
},
{
"code": null,
"e": 269149,
"s": 269130,
"text": "#include<iostream>"
},
{
"code": null,
"e": 269172,
"s": 269151,
"text": "using namespace std;"
},
{
"code": null,
"e": 269211,
"s": 269172,
"text": "#define tiff(i,n) for(int i=0;i<n;i++)"
},
{
"code": null,
"e": 269224,
"s": 269213,
"text": "struct ds{"
},
{
"code": null,
"e": 269238,
"s": 269227,
"text": " int zero;"
},
{
"code": null,
"e": 269249,
"s": 269238,
"text": " int ones;"
},
{
"code": null,
"e": 269255,
"s": 269252,
"text": "};"
},
{
"code": null,
"e": 269283,
"s": 269255,
"text": "typedef struct ds solution;"
},
{
"code": null,
"e": 269304,
"s": 269283,
"text": "solution arr[10000];"
},
{
"code": null,
"e": 269332,
"s": 269306,
"text": "solution easyopti(int n){"
},
{
"code": null,
"e": 269341,
"s": 269332,
"text": " if(n<0)"
},
{
"code": null,
"e": 269344,
"s": 269341,
"text": " {"
},
{
"code": null,
"e": 269361,
"s": 269344,
"text": " solution tmp ;"
},
{
"code": null,
"e": 269376,
"s": 269361,
"text": " tmp.zero =0;"
},
{
"code": null,
"e": 269391,
"s": 269376,
"text": " tmp.ones =0;"
},
{
"code": null,
"e": 269404,
"s": 269391,
"text": " return tmp;"
},
{
"code": null,
"e": 269407,
"s": 269404,
"text": " }"
},
{
"code": null,
"e": 269430,
"s": 269413,
"text": " arr[0].zero=1;"
},
{
"code": null,
"e": 269447,
"s": 269430,
"text": " arr[0].ones=0;"
},
{
"code": null,
"e": 269468,
"s": 269451,
"text": " arr[1].zero=1;"
},
{
"code": null,
"e": 269485,
"s": 269468,
"text": " arr[1].ones=1;"
},
{
"code": null,
"e": 269506,
"s": 269489,
"text": " arr[2].zero=2;"
},
{
"code": null,
"e": 269523,
"s": 269506,
"text": " arr[2].ones=1;"
},
{
"code": null,
"e": 269544,
"s": 269527,
"text": " arr[3].zero=4;"
},
{
"code": null,
"e": 269561,
"s": 269544,
"text": " arr[3].ones=2;"
},
{
"code": null,
"e": 269588,
"s": 269564,
"text": " if(n==0)return arr[0];"
},
{
"code": null,
"e": 269620,
"s": 269591,
"text": " else if(n==1)return arr[1];"
},
{
"code": null,
"e": 269653,
"s": 269623,
"text": " else if(n==2)return arr[2];"
},
{
"code": null,
"e": 269685,
"s": 269656,
"text": " else if(n==3)return arr[3];"
},
{
"code": null,
"e": 269695,
"s": 269688,
"text": " else{"
},
{
"code": null,
"e": 269725,
"s": 269699,
"text": " for(int i = 4;i<=n;i++){"
},
{
"code": null,
"e": 269784,
"s": 269725,
"text": " arr[i].zero = arr[i-1].zero+arr[i-2].zero+arr[i-3].zero;"
},
{
"code": null,
"e": 269844,
"s": 269784,
"text": " arr[i].ones = arr[i-1].ones+arr[i-2].ones+arr[i-3].ones; "
},
{
"code": null,
"e": 269847,
"s": 269844,
"text": " }"
},
{
"code": null,
"e": 269854,
"s": 269850,
"text": " }"
},
{
"code": null,
"e": 269870,
"s": 269854,
"text": " return arr[n];"
},
{
"code": null,
"e": 269872,
"s": 269870,
"text": "}"
},
{
"code": null,
"e": 269884,
"s": 269872,
"text": "int main(){"
},
{
"code": null,
"e": 269913,
"s": 269887,
"text": "solution a= easyopti(10);"
},
{
"code": null,
"e": 269948,
"s": 269913,
"text": " cout<<a.zero<<\" \"<<a.ones<<endl;"
},
{
"code": null,
"e": 269953,
"s": 269951,
"text": "}"
},
{
"code": null,
"e": 270119,
"s": 269953,
"text": "Post order are tree traversal are given below .\n\nTraverse the left sub tree of R in post order.\nTraverse the right sub tree of R in post order.\nProcess the root R.\n\n"
},
{
"code": null,
"e": 270166,
"s": 270119,
"text": "Traverse the left sub tree of R in post order."
},
{
"code": null,
"e": 270214,
"s": 270166,
"text": "Traverse the right sub tree of R in post order."
},
{
"code": null,
"e": 270234,
"s": 270214,
"text": "Process the root R."
},
{
"code": null,
"e": 270482,
"s": 270234,
"text": "/* Recursive function to print the elements of a binary tree \nwith postorder traversal*/\nvoid postorder(struct btreenode *node)\n{\n if (node != NULL)\n {\n postorder(node->left); \n postorder(node->right);\n printf(\"%d\", node->data);\n }\n}"
},
{
"code": null,
"e": 270492,
"s": 270482,
"text": "Example :"
},
{
"code": null,
"e": 270531,
"s": 270492,
"text": "Post-order: A, C, E, D, B, H, I, G, F."
},
{
"code": null,
"e": 270684,
"s": 270531,
"text": "Inorder are tree traversal are given below\n\nTraverse the left subtree of R in inorder.\nProcess the root R.\nTraverse the right subtree of R in inorder.\n\n"
},
{
"code": null,
"e": 270727,
"s": 270684,
"text": "Traverse the left subtree of R in inorder."
},
{
"code": null,
"e": 270747,
"s": 270727,
"text": "Process the root R."
},
{
"code": null,
"e": 270791,
"s": 270747,
"text": "Traverse the right subtree of R in inorder."
},
{
"code": null,
"e": 271031,
"s": 270791,
"text": "/* Recursive function to print the elements of a binary tree with \ninorder traversal*/\nvoid inorder(struct btreenode *node)\n{\n if (node != NULL)\n {\n inorder(node->left); \n printf(\"%d\", node->data);\n inorder(node->right);\n }\n}"
},
{
"code": null,
"e": 271041,
"s": 271031,
"text": "Example :"
},
{
"code": null,
"e": 271078,
"s": 271041,
"text": "In-order: A, B, C, D, E, F, G, H, I."
},
{
"code": null,
"e": 271236,
"s": 271078,
"text": "Preorder are tree traversal are given below \n\t\nProcess the root R.\nTraverse the left subtree of R in preorder.\nTraverse the right subtree of R in preorder.\n\n"
},
{
"code": null,
"e": 271256,
"s": 271236,
"text": "Process the root R."
},
{
"code": null,
"e": 271300,
"s": 271256,
"text": "Traverse the left subtree of R in preorder."
},
{
"code": null,
"e": 271345,
"s": 271300,
"text": "Traverse the right subtree of R in preorder."
},
{
"code": null,
"e": 271586,
"s": 271345,
"text": "/* Recursive function to print the elements \nof a binary tree with preorder traversal*/\nvoid preorder(struct btreenode *node)\n{\n if (node != NULL)\n {\n printf(\"%d\", node->data);\n preorder(node->left);\n preorder(node->right);\n }\n}"
},
{
"code": null,
"e": 271596,
"s": 271586,
"text": "Example :"
},
{
"code": null,
"e": 271634,
"s": 271596,
"text": "Pre-order: F, B, A, D, C, E, G, I, H."
},
{
"code": null,
"e": 271945,
"s": 271634,
"text": "Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum. \nFormally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j ."
},
{
"code": null,
"e": 272026,
"s": 271945,
"text": "Example:\nThe sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3)."
},
{
"code": null,
"e": 272033,
"s": 272026,
"text": "code :"
},
{
"code": null,
"e": 272177,
"s": 272033,
"text": "for(i=0 to n-2 ) \n{ \n for(j=i+1 to n-1) \n if(a[i] > a[j]) \n count++; \n} \n\nTime-complexity = O(n^2) \n\nBy merge-sort- it is O(n logn)"
},
{
"code": null,
"e": 272252,
"s": 272177,
"text": "for detail review refer: http://www.geeksforgeeks.org/counting-inversions/"
},
{
"code": null,
"e": 272337,
"s": 272252,
"text": "A stack is an abstract data type which operate basically two fundamental principals "
},
{
"code": null,
"e": 272391,
"s": 272337,
"text": "\npush() − Pushing (storing) an element on the stack.\n"
},
{
"code": null,
"e": 272443,
"s": 272391,
"text": "push() − Pushing (storing) an element on the stack."
},
{
"code": null,
"e": 272501,
"s": 272443,
"text": "\npop() − Removing (accessing) an element from the stack.\n"
},
{
"code": null,
"e": 272557,
"s": 272501,
"text": "pop() − Removing (accessing) an element from the stack."
},
{
"code": null,
"e": 272669,
"s": 272557,
"text": "The order in which elements come off a stack gives rise to its alternative name, LIFO (for last in, first out)."
},
{
"code": null,
"e": 272706,
"s": 272669,
"text": "Implementation of stack :Using Array"
},
{
"code": null,
"e": 272720,
"s": 272706,
"text": "Pseudo Code :"
},
{
"code": null,
"e": 272827,
"s": 272720,
"text": "Push(S,N,x,top)\n{\nif(top+1==N)\n {\n print(\"Stack is overflow\");\n}\nelse \n{\n top++;\n S[top]=x;\n}\n\n}"
},
{
"code": null,
"e": 272969,
"s": 272827,
"text": "POP(S,N,top)\n{\nif(top==-1)\n {\n print(\"Stack is underflow\");\n exit(1);\n}\nelse \n{\n \n y=S[top];\n top--;\n return(y);\n}\n\n}"
},
{
"code": null,
"e": 272985,
"s": 272969,
"text": "Uses of Stack :"
},
{
"code": null,
"e": 273028,
"s": 272985,
"text": "Expression evaluation and syntax parsing ."
},
{
"code": null,
"e": 273045,
"s": 273028,
"text": "\nBacktracking .\n"
},
{
"code": null,
"e": 273060,
"s": 273045,
"text": "Backtracking ."
},
{
"code": null,
"e": 273072,
"s": 273060,
"text": "\nParsing .\n"
},
{
"code": null,
"e": 273082,
"s": 273072,
"text": "Parsing ."
},
{
"code": null,
"e": 273103,
"s": 273082,
"text": "Recursive Function ."
},
{
"code": null,
"e": 273231,
"s": 273113,
"text": "New state : Initially process will be in New state . It means process is under creation or process is being created ."
},
{
"code": null,
"e": 273372,
"s": 273231,
"text": "Ready state : Once the process is created it will be moved on to ready state . In the ready state there will be multiple number of process ."
},
{
"code": null,
"e": 273673,
"s": 273372,
"text": "Running state : One of the process will be selected from the ready state and dispatched on to the running state .When the process in the running state it occupied the CPU and executing the instruction of the process and performing CPU time .In the running state one process at any point of the time ."
},
{
"code": null,
"e": 273916,
"s": 273673,
"text": "Wait or Block state : If the running process required any input output then it will come to wait state .In the wait state there will be multiple number of process .It means multiple process will perform input output operation simultaneously ."
},
{
"code": null,
"e": 274204,
"s": 273916,
"text": "Suspended Ready : If the resources are not sufficient to maintain the process in the ready state the some of the process will suspended and they will be moved on to suspended ready state . If the process in the suspended ready state it is reside in the backing store (Secondary memory) ."
},
{
"code": null,
"e": 274492,
"s": 274204,
"text": "Suspend wait or Block state : If the resources are not sufficient to maintain the process in the wait or block state then some of the process (Low priority) will be suspended and they will be moved to the suspended waiting or block state. In this process is reside in the backing store ."
},
{
"code": null,
"e": 274574,
"s": 274505,
"text": " Cycle Detection (Single Instance)"
},
{
"code": null,
"e": 274737,
"s": 274574,
"text": "If all the resources are of Single Instance Type then the Cycle in the Resource Allocation Graph is necessary and sufficient condition for occurring of deadlock ."
},
{
"code": null,
"e": 274920,
"s": 274737,
"text": "If all the resources of a not single instance type then cycle in the resource allocation graph is just a necessary condition but not sufficient condition for occurring of deadlock .."
},
{
"code": null,
"e": 275422,
"s": 274922,
"text": "\nMonitors is a programming language compiler support type of solution achieved synchronization .\nThe Monitors is collection of variables , conditional variable and procedure combine together in a special kind of module and package .\nThe processes running outside the monitor cannot directly access the internal variables of the monitor but how ever they can call procedure of the Monitor .\nMonitor has important property that only one process can be active inside the monitor at any point of time .\n"
},
{
"code": null,
"e": 275518,
"s": 275422,
"text": "Monitors is a programming language compiler support type of solution achieved synchronization ."
},
{
"code": null,
"e": 275654,
"s": 275518,
"text": "The Monitors is collection of variables , conditional variable and procedure combine together in a special kind of module and package ."
},
{
"code": null,
"e": 275811,
"s": 275654,
"text": "The processes running outside the monitor cannot directly access the internal variables of the monitor but how ever they can call procedure of the Monitor ."
},
{
"code": null,
"e": 275920,
"s": 275811,
"text": "Monitor has important property that only one process can be active inside the monitor at any point of time ."
},
{
"code": null,
"e": 275942,
"s": 275920,
"text": "Syntax of Monitor : "
},
{
"code": null,
"e": 275956,
"s": 275942,
"text": "Pseudo code "
},
{
"code": null,
"e": 276082,
"s": 275956,
"text": " Fibo(n)\n{\n if(n==0)\n return(0) ;\n \n if(n==1)\n return(1);\n\n else\n return(fibo(n-1)+fibo(n-2));\n \n }"
},
{
"code": null,
"e": 276102,
"s": 276082,
"text": "Recurrence relation"
},
{
"code": null,
"e": 276112,
"s": 276102,
"text": "Example :"
},
{
"code": null,
"e": 276131,
"s": 276112,
"text": " Time Complexity :"
},
{
"code": null,
"e": 276148,
"s": 276131,
"text": " fibo(n)"
},
{
"code": null,
"e": 276162,
"s": 276148,
"text": " ||"
},
{
"code": null,
"e": 276215,
"s": 276162,
"text": " n-level-Complete Binary tree [upper bound]"
},
{
"code": null,
"e": 276229,
"s": 276215,
"text": " ||"
},
{
"code": null,
"e": 276252,
"s": 276229,
"text": " 2^n -1 nodes"
},
{
"code": null,
"e": 276266,
"s": 276252,
"text": " ||"
},
{
"code": null,
"e": 276295,
"s": 276266,
"text": " 2^n function calls"
},
{
"code": null,
"e": 276310,
"s": 276295,
"text": " || "
},
{
"code": null,
"e": 276327,
"s": 276310,
"text": " O(2^n)"
},
{
"code": null,
"e": 276340,
"s": 276327,
"text": "Pseudo code "
},
{
"code": null,
"e": 276471,
"s": 276340,
"text": "Reverse(head)\n{\n r=head,p=q=null ;\n\n while(r)\n{\n p=q;\n q=r;\n r=r->next;\n q->next=p;\n\n\n}\n head=q;\n return(head);\n\n}"
},
{
"code": null,
"e": 278086,
"s": 276471,
"text": "\nImage Acquisition : This is the first step or process of the fundamental steps of digital image processing. Image acquisition could be as simple as being given an image that is already in digital form. Generally, the image acquisition stage involves pre processing, such as scaling etc.\nImage Enhancement : Image enhancement is among the simplest and most appealing areas of digital image processing. Basically, the idea behind enhancement techniques is to bring out detail that is obscured, or simply to highlight certain features of interest in an image. Such as, changing brightness & contrast etc.\nImage Restoration : Image restoration is an area that also deals with improving the appearance of an image. However, unlike enhancement, which is subjective, image restoration is objective, in the sense that restoration techniques tend to be based on mathematical or probabilistic models of image degradation.\nColor Image Processing : Color image processing is an area that has been gaining its importance because of the significant increase in the use of digital images over the Internet. This may include color modeling and processing in a digital domain etc.\nWavelets and Multiresolution Processing : Wavelets are the foundation for representing images in various degrees of resolution. Images subdivision successively into smaller regions for data compression and for pyramidal representation.\nCompression : Compression deals with techniques for reducing the storage required to save an image or the bandwidth to transmit it. Particularly in the uses of internet it is very much necessary to compress data.\n"
},
{
"code": null,
"e": 278373,
"s": 278086,
"text": "Image Acquisition : This is the first step or process of the fundamental steps of digital image processing. Image acquisition could be as simple as being given an image that is already in digital form. Generally, the image acquisition stage involves pre processing, such as scaling etc."
},
{
"code": null,
"e": 278688,
"s": 278373,
"text": "Image Enhancement : Image enhancement is among the simplest and most appealing areas of digital image processing. Basically, the idea behind enhancement techniques is to bring out detail that is obscured, or simply to highlight certain features of interest in an image. Such as, changing brightness & contrast etc."
},
{
"code": null,
"e": 278998,
"s": 278688,
"text": "Image Restoration : Image restoration is an area that also deals with improving the appearance of an image. However, unlike enhancement, which is subjective, image restoration is objective, in the sense that restoration techniques tend to be based on mathematical or probabilistic models of image degradation."
},
{
"code": null,
"e": 279250,
"s": 278998,
"text": "Color Image Processing : Color image processing is an area that has been gaining its importance because of the significant increase in the use of digital images over the Internet. This may include color modeling and processing in a digital domain etc."
},
{
"code": null,
"e": 279486,
"s": 279250,
"text": "Wavelets and Multiresolution Processing : Wavelets are the foundation for representing images in various degrees of resolution. Images subdivision successively into smaller regions for data compression and for pyramidal representation."
},
{
"code": null,
"e": 279699,
"s": 279486,
"text": "Compression : Compression deals with techniques for reducing the storage required to save an image or the bandwidth to transmit it. Particularly in the uses of internet it is very much necessary to compress data."
},
{
"code": null,
"e": 279958,
"s": 279699,
"text": "Face detection can be regarded as a specific case of object-class detection. In object-class detection, the task is to find the locations and sizes of all objects in an image that belong to a given class. Examples include upper torsos, pedestrians, and cars."
},
{
"code": null,
"e": 280250,
"s": 279958,
"text": "Face-detection algorithms focus on the detection of frontal human faces. It is analogous to image detection in which the image of a person is matched bit by bit. Image matches with the image stores in database. Any facial feature changes in the database will invalidate the matching process."
},
{
"code": null,
"e": 280303,
"s": 280250,
"text": "refers :https://en.wikipedia.org/wiki/Face_detection"
},
{
"code": null,
"e": 280980,
"s": 280305,
"text": "Edge detection includes a variety of mathematical methods that aim at identifying points in a digital image at which the image brightness changes sharply or, more formally, has discontinuities. The points at which image brightness changes sharply are typically organized into a set of curved line segments termed edges. The same problem of finding discontinuities in one-dimensional signals is known as step detection and the problem of finding signal discontinuities over time is known as change detection. Edge detection is a fundamental tool in image processing, machine vision and computer vision, particularly in the areas of feature detection and feature extraction . "
},
{
"code": null,
"e": 281034,
"s": 280980,
"text": "refers : https://en.wikipedia.org/wiki/Edge_detection"
},
{
"code": null,
"e": 281052,
"s": 281034,
"text": "Searching a key :"
},
{
"code": null,
"e": 281290,
"s": 281052,
"text": "To search a given key in Binary Search Tree, we first compare it with root, if the key is present at root, we return root. If key is greater than root’s key, we recur for right sub tree of root node. Otherwise we recur for left sub tree."
},
{
"code": null,
"e": 281697,
"s": 281290,
"text": "// C function to search a given key in a given BST\nstruct node* search(struct node* root, int key)\n{\n // Base Cases: root is null or key is present at root\n if (root == NULL || root->key == key)\n return root;\n \n // Key is greater than root's key\n if (root->key < key)\n return search(root->right, key);\n \n // Key is smaller than root's key\n return search(root->left, key);\n}"
},
{
"code": null,
"e": 281718,
"s": 281697,
"text": "Insertion of a key :"
},
{
"code": null,
"e": 281894,
"s": 281718,
"text": "A new key is always inserted at leaf. We start searching a key from root till we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf node."
},
{
"code": null,
"e": 282229,
"s": 281894,
"text": " 100 100\n / \\ Insert 40 / \\\n 20 500 ---------> 20 500 \n / \\ / \\ \n 10 30 10 30\n \\ \n 40"
},
{
"code": null,
"e": 283797,
"s": 282229,
"text": "// C program to demonstrate insert operation in binary search tree\n#include<stdio.h>\n#include<stdlib.h>\n \nstruct node\n{\n int key;\n struct node *left, *right;\n};\n \n// A utility function to create a new BST node\nstruct node *newNode(int item)\n{\n struct node *temp = (struct node *)malloc(sizeof(struct node));\n temp->key = item;\n temp->left = temp->right = NULL;\n return temp;\n}\n \n// A utility function to do inorder traversal of BST\nvoid inorder(struct node *root)\n{\n if (root != NULL)\n {\n inorder(root->left);\n printf(\"%d \\n\", root->key);\n inorder(root->right);\n }\n}\n \n/* A utility function to insert a new node with given key in BST */\nstruct node* insert(struct node* node, int key)\n{\n /* If the tree is empty, return a new node */\n if (node == NULL) return newNode(key);\n \n /* Otherwise, recur down the tree */\n if (key < node->key)\n node->left = insert(node->left, key);\n else if (key > node->key)\n node->right = insert(node->right, key); \n \n /* return the (unchanged) node pointer */\n return node;\n}\n \n// Driver Program to test above functions\nint main()\n{\n /* Let us create following BST\n 50\n / \\\n 30 70\n / \\ / \\\n 20 40 60 80 */\n struct node *root = NULL;\n root = insert(root, 50);\n insert(root, 30);\n insert(root, 20);\n insert(root, 40);\n insert(root, 70);\n insert(root, 60);\n insert(root, 80);\n \n // print inoder traversal of the BST\n inorder(root);\n \n return 0;\n}"
},
{
"code": null,
"e": 284112,
"s": 283797,
"text": "Time Complexity: The worst case time complexity of search and insert operations is O(h) where h is height of Binary Search Tree. In worst case, we may have to travel from root to the deepest leaf node. The height of a skewed tree may become n and the time complexity of search and insert operation may become O(n)."
},
{
"code": null,
"e": 284210,
"s": 284112,
"text": "for detail refer as :http://quiz.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/"
},
{
"code": null,
"e": 284830,
"s": 284210,
"text": "In order to find common node of two linked lists we need to consider one of the important factor - length of linked list. If length of both linked list is same then it is just a cake walk, iterate both linked list with same frequency(one node at a time) and check whether both linked list reference same node at any point, if intersection node exist we will find it, else reaches at end of list. However, problem is all about two linked list of different length.Refer following diagram, length of first linked list is 4 and 3 for second one. We will start with brute force approach followed by some time efficient ways."
},
{
"code": null,
"e": 285215,
"s": 284830,
"text": "Brute force approach- Iterate any given linked list for every node of another linked list and compare if both nodes are equals or not, if at any moment nodes passes equals() test that nodde is common node, otherwise no common node exist. Time and space complexity :- Suppose length of linked lists are p and q respectively then, time complexity is O(pq) and space complexity is O(1)."
},
{
"code": null,
"e": 285960,
"s": 285215,
"text": "/* Find common node, intersection of two Linked list- brute force approach */\nprivate static Node getCommonNodeBruteForce(Node head1, Node head2) {\n Node commonNode = null;\n Node current = head2;\n if (head1 != null && head2 != null)\n /*For each node of linked list 1, traverse linked list 2*/\n while (head1 != null) {\n while (current != null) {\n if (current.equals(head1)) {\n commonNode = current;\n break;\n }\n current = current.next;\n }\n /*If commonNode is not null, it means we have found common node*/\n if (commonNode != null) {\n break;\n }\n /* Move linked list 1 head and reset current \n * to head2 (for each node of linked list 1, traverse linked list 2)\n * */\n head1 = head1.next;\n current = head2;\n }\n return commonNode;\n}"
},
{
"code": null,
"e": 286464,
"s": 285960,
"text": "Method 2(Using difference of node counts)\n1) Get count of the nodes in first list, let count be c1.\n2) Get count of the nodes in second list, let count be c2.\n3) Get the difference of counts d = abs(c1 – c2)\n4) Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes.\n5) Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes)"
},
{
"code": null,
"e": 286589,
"s": 286464,
"text": "for Detail refer this link :http://www.geeksforgeeks.org/write-a-function-to-get-the-intersection-point-of-two-linked-lists/"
},
{
"code": null,
"e": 286822,
"s": 286589,
"text": "Virtual Function is a function in base class, which is override in the derived class, and which tells the compiler to perform Late Binding on this function.Virtual Keyword is used to make a member function of the base class Virtual."
},
{
"code": null,
"e": 286832,
"s": 286822,
"text": "Example :"
},
{
"code": null,
"e": 286846,
"s": 286832,
"text": "Definitions :"
},
{
"code": null,
"e": 286957,
"s": 286846,
"text": "\nOverloading occurs when two or more methods in one class have the same method name but different parameters.\n"
},
{
"code": null,
"e": 287066,
"s": 286957,
"text": "Overloading occurs when two or more methods in one class have the same method name but different parameters."
},
{
"code": null,
"e": 287375,
"s": 287066,
"text": "\nOverriding means having two methods with the same method name and parameters (i.e., method signature). One of the methods is in the parent class and the other is in the child class. Overriding allows a child class to provide a specific implementation of a method that is already provided its parent class .\n"
},
{
"code": null,
"e": 287682,
"s": 287375,
"text": "Overriding means having two methods with the same method name and parameters (i.e., method signature). One of the methods is in the parent class and the other is in the child class. Overriding allows a child class to provide a specific implementation of a method that is already provided its parent class ."
},
{
"code": null,
"e": 287709,
"s": 287682,
"text": "Overriding vs. Overloading"
},
{
"code": null,
"e": 287773,
"s": 287709,
"text": "Here are some important facts about Overriding and Overloading:"
},
{
"code": null,
"e": 288049,
"s": 287773,
"text": "When a method by an object is called, Java matches up the method name first and then the number and data type of parameters to decide which one of the overloaded methods to execute. i.e., compiler decides which method is to be called depending upon the number of parameters ."
},
{
"code": null,
"e": 288153,
"s": 288049,
"text": "A subclass will override the method by facilitating its own functionality to it ( by using @override) ."
},
{
"code": null,
"e": 288228,
"s": 288153,
"text": "Access modifier & Non access modifier can also be changed in overloading ."
},
{
"code": null,
"e": 288458,
"s": 288228,
"text": "but in overriding Non access modifier – final :if a method can contain final keyword in a parent class we cannot override. static:if a method can contain static keyword child cannot override parent class methods but hide (child)."
},
{
"code": null,
"e": 288514,
"s": 288458,
"text": "Polymorphism applies to overriding, not to overloading."
},
{
"code": null,
"e": 288593,
"s": 288514,
"text": "Overriding is a run-time concept while overloading is a compile-time concept ."
},
{
"code": null,
"e": 288618,
"s": 288593,
"text": "An Example of Overriding"
},
{
"code": null,
"e": 288997,
"s": 288618,
"text": "class Cat{\n public void hello(){\n System.out.println(\"woof \");\n }\n}\nclass Help extends Cat{\n public void sniff(){\n System.out.println(\"sniff \");\n }\n \n public void hello(){\n System.out.println(\"bowl\");\n }\n}\n \npublic class OverridingTen{\n public static void main(String [] args){\n Cat cat = new Help();\n Cat.hello();\n }\n}"
},
{
"code": null,
"e": 289398,
"s": 288997,
"text": "In the example above, the cat variable is declared to be a Cat. During compile time, the compiler checks if the Cat class has the bark() method. As long as the Cat class has the bark() method, the code compilers. At run-time, a Help is created and assigned to cat. The JVM knows that cat is referring to the object of Help, so it calls the bark() method of Help. This is called Dynamic Polymorphism ."
},
{
"code": null,
"e": 289407,
"s": 289398,
"text": "Output :"
},
{
"code": null,
"e": 289412,
"s": 289407,
"text": "bowl"
},
{
"code": null,
"e": 289440,
"s": 289412,
"text": "An Example of Overloading :"
},
{
"code": null,
"e": 289655,
"s": 289440,
"text": "class Cat{\n public void Test(){\n System.out.println(\"woofing \");\n }\n \n //overloading method\n public void Test(int num){\n \tfor(int i=0; i<num; i++)\n \t\tSystem.out.println(\"woofing \");\n }\n}"
},
{
"code": null,
"e": 289869,
"s": 289655,
"text": "In this overloading example, the two Test method can be invoked by using different parameters. Compiler know they are different because they have different method signature (method name and method parameter list)."
},
{
"code": null,
"e": 289878,
"s": 289869,
"text": "output :"
},
{
"code": null,
"e": 289886,
"s": 289878,
"text": "woofing"
},
{
"code": null,
"e": 290055,
"s": 289886,
"text": "If the pivot divides the array into two pieces of roughly the same size each time, then Quicksort behaves like Mergesort with log n splits of the array. More precisely,"
},
{
"code": null,
"e": 290085,
"s": 290055,
"text": "T(n) = f(n) + T(n/2) + T(n/2)"
},
{
"code": null,
"e": 290166,
"s": 290085,
"text": "where f(n) is the time taken by Partition. Since Partition compares every key in"
},
{
"code": null,
"e": 290182,
"s": 290166,
"text": "A[0 .. (n - 1)]"
},
{
"code": null,
"e": 290326,
"s": 290182,
"text": "to the pivot x, the running time for partition is linear, with time complexity f(n) = n. So Quicksort has a time complexity function T given by"
},
{
"code": null,
"e": 290354,
"s": 290326,
"text": "T(1) = 1 T(n) = 2T(n/2) + n"
},
{
"code": null,
"e": 290394,
"s": 290354,
"text": "which, like mergesort, has the solution"
},
{
"code": null,
"e": 290435,
"s": 290394,
"text": "T(n) = n log n + n and so is Θ(n log n)."
},
{
"code": null,
"e": 290497,
"s": 290435,
"text": "But this is if the pivot divides the array in a balanced way."
},
{
"code": null,
"e": 290865,
"s": 290497,
"text": "Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty."
},
{
"code": null,
"e": 290874,
"s": 290865,
"text": "Example:"
},
{
"code": null,
"e": 290994,
"s": 290874,
"text": "The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Logn)."
},
{
"code": null,
"e": 291047,
"s": 290994,
"text": "source :http://quiz.geeksforgeeks.org/binary-search/"
},
{
"code": null,
"e": 291328,
"s": 291047,
"text": "The solution uses a two pointers (traversing the list two items at a time) If there is a loop, then the one pointer will go around the loop twice as fast as the another pointer. At one point, these two pointers will point to the same item. Here’s some code to make this clearer. "
},
{
"code": null,
"e": 291597,
"s": 291328,
"text": "bool hasLoop( Node *p )\n{\n Node *p, *q;\n p = q = headNode;\n while( p && q && q->next )\n {\n if( p == q->next || p== q->next->next )\n {\n return true;\n }\n p = p->next;\n q = q->next->next;\n }\n return false;\n}"
},
{
"code": null,
"e": 291825,
"s": 291597,
"text": "\nTo implement DFS we are using Stack data structure .\nTime Complexity : O(V+E) .\nSpace Complexity : O(V+E) .\nIn DFT (Depth first traversal ) is printed and if adjacent is not present then using backtracking we print adjacent .\n"
},
{
"code": null,
"e": 291878,
"s": 291825,
"text": "To implement DFS we are using Stack data structure ."
},
{
"code": null,
"e": 291905,
"s": 291878,
"text": "Time Complexity : O(V+E) ."
},
{
"code": null,
"e": 291933,
"s": 291905,
"text": "Space Complexity : O(V+E) ."
},
{
"code": null,
"e": 292051,
"s": 291933,
"text": "In DFT (Depth first traversal ) is printed and if adjacent is not present then using backtracking we print adjacent ."
},
{
"code": null,
"e": 292080,
"s": 292051,
"text": " Application of DFS :"
},
{
"code": null,
"e": 292502,
"s": 292080,
"text": "\nUsing DFT we can check given graph is connected or not .\nUsing DFT we can find out number of connected component in a given graph .\nUsing DFT we can check given graph contain cycle or not .\nUsing DFT we can check given directed graph is strongly connected or not.\nFind out Biconnected Component and Euler path .\nCompute number of path between two vertex .\nUsing DFT we can check a vertex in Articulation point or not .\n"
},
{
"code": null,
"e": 292559,
"s": 292502,
"text": "Using DFT we can check given graph is connected or not ."
},
{
"code": null,
"e": 292634,
"s": 292559,
"text": "Using DFT we can find out number of connected component in a given graph ."
},
{
"code": null,
"e": 292692,
"s": 292634,
"text": "Using DFT we can check given graph contain cycle or not ."
},
{
"code": null,
"e": 292766,
"s": 292692,
"text": "Using DFT we can check given directed graph is strongly connected or not."
},
{
"code": null,
"e": 292814,
"s": 292766,
"text": "Find out Biconnected Component and Euler path ."
},
{
"code": null,
"e": 292859,
"s": 292814,
"text": "Compute number of path between two vertex ."
},
{
"code": null,
"e": 292922,
"s": 292859,
"text": "Using DFT we can check a vertex in Articulation point or not ."
},
{
"code": null,
"e": 293067,
"s": 292922,
"text": "A vertex in a given graph is said to be articulation point iff by deleting that vertex together its edges then resulting graph is disconnected ."
},
{
"code": null,
"e": 293090,
"s": 293067,
"text": " DFS Pseudo code :"
},
{
"code": null,
"e": 293305,
"s": 293090,
"text": "\nTo implement BFT (Breadth first traversal) we are using Queue data structure .\nBFT is also known as level order traversal .\nIn BFT all adjacent are printed .\nTime Complexity : O(V+E) .\nSpace Complexity : O(V+E) .\n"
},
{
"code": null,
"e": 293384,
"s": 293305,
"text": "To implement BFT (Breadth first traversal) we are using Queue data structure ."
},
{
"code": null,
"e": 293429,
"s": 293384,
"text": "BFT is also known as level order traversal ."
},
{
"code": null,
"e": 293463,
"s": 293429,
"text": "In BFT all adjacent are printed ."
},
{
"code": null,
"e": 293490,
"s": 293463,
"text": "Time Complexity : O(V+E) ."
},
{
"code": null,
"e": 293518,
"s": 293490,
"text": "Space Complexity : O(V+E) ."
},
{
"code": null,
"e": 293542,
"s": 293518,
"text": " Application :"
},
{
"code": null,
"e": 294025,
"s": 293542,
"text": "\nUsing BFT we can check given graph is connected or not.\nUsing BFT we can find out connected component in given graph .\nUsing BFT we can check given graph contain cycle or not .\nUsing BFT we can find out shortest path from given source to every vertex in a given unweighted graph (Dijkstra Algorithm) .\nUsing BFT we can check given graph is bipartite graph or not .\nQueue and Greedy Technique .\nUsing for Topology sort and Dijkstra algorithm .\nFind Transitive closure of a graph . \n"
},
{
"code": null,
"e": 294081,
"s": 294025,
"text": "Using BFT we can check given graph is connected or not."
},
{
"code": null,
"e": 294144,
"s": 294081,
"text": "Using BFT we can find out connected component in given graph ."
},
{
"code": null,
"e": 294202,
"s": 294144,
"text": "Using BFT we can check given graph contain cycle or not ."
},
{
"code": null,
"e": 294327,
"s": 294202,
"text": "Using BFT we can find out shortest path from given source to every vertex in a given unweighted graph (Dijkstra Algorithm) ."
},
{
"code": null,
"e": 294390,
"s": 294327,
"text": "Using BFT we can check given graph is bipartite graph or not ."
},
{
"code": null,
"e": 294419,
"s": 294390,
"text": "Queue and Greedy Technique ."
},
{
"code": null,
"e": 294468,
"s": 294419,
"text": "Using for Topology sort and Dijkstra algorithm ."
},
{
"code": null,
"e": 294506,
"s": 294468,
"text": "Find Transitive closure of a graph . "
},
{
"code": null,
"e": 294680,
"s": 294513,
"text": "\nBridge is LAN device and its operation is based on MAC protocol .\nBridge is used to connecting similar LAN.\nInitially the Bridge table of the Bridge will be empty .\n"
},
{
"code": null,
"e": 294746,
"s": 294680,
"text": "Bridge is LAN device and its operation is based on MAC protocol ."
},
{
"code": null,
"e": 294788,
"s": 294746,
"text": "Bridge is used to connecting similar LAN."
},
{
"code": null,
"e": 294845,
"s": 294788,
"text": "Initially the Bridge table of the Bridge will be empty ."
},
{
"code": null,
"e": 295012,
"s": 294845,
"text": "Whenever frame reaches to the Bridge it will store in a buffer and a Dummy frame is created with destination address of the frame and is broadcast on the other LAN ."
},
{
"code": null,
"e": 295117,
"s": 295012,
"text": "If their is reply then Bridge will update the table with destination address this is known as Learning ."
},
{
"code": null,
"e": 295245,
"s": 295117,
"text": " Now the data that is stored in a buffer of the Bridge is transmitted to the other side of the LAN this is known as Forwarding."
},
{
"code": null,
"e": 295328,
"s": 295245,
"text": "When the data is transmitted to the same side of the LAN it is known as Blocking ."
},
{
"code": null,
"e": 295415,
"s": 295328,
"text": "When Bridge known the complete information of the network its is Stable and Converse ."
},
{
"code": null,
"e": 295839,
"s": 295424,
"text": "\nRouter is WAN device an its operation is based on IP address .\nRouter is used for connecting different classes of networks .\nBy default Router is Broadcast Domain Separator .\nRouter is used for connecting different networks (Bus topology , Ring topology) .\nRouter is not a multi-protocol convertor because it cannot convert one model of the packet to another .\nBy default Router is a Collision Domain Separator .\n"
},
{
"code": null,
"e": 295902,
"s": 295839,
"text": "Router is WAN device an its operation is based on IP address ."
},
{
"code": null,
"e": 295964,
"s": 295902,
"text": "Router is used for connecting different classes of networks ."
},
{
"code": null,
"e": 296014,
"s": 295964,
"text": "By default Router is Broadcast Domain Separator ."
},
{
"code": null,
"e": 296096,
"s": 296014,
"text": "Router is used for connecting different networks (Bus topology , Ring topology) ."
},
{
"code": null,
"e": 296200,
"s": 296096,
"text": "Router is not a multi-protocol convertor because it cannot convert one model of the packet to another ."
},
{
"code": null,
"e": 296252,
"s": 296200,
"text": "By default Router is a Collision Domain Separator ."
},
{
"code": null,
"e": 297116,
"s": 296252,
"text": "\nText Based Protocol\n\n By default SMTP is text based protocol but we can send Graphical data with the help of MIME (Multi-media Internet Mail Extension) \n\n\n\nSMTP uses port 25.\n\n\nSMTP is a Post protocol it is used for sending the mail into mail server.\n\n\nPOP3 or (IMAP4) are known for the Pull protocol because they are used for retrieving the mail from mail server .\n\n\nSMTP combine with POP3 or IMAP4 is client to client protocol with mediation done by mail server .\n\n\nSMTP used TCP as a transport layer protocol.\n\n\nSMTP is an asynchronies because the clocks of both clients need not synchronize.\n\n\nSMTP follows store and forward technique with the respect of server .\n\n\nPriority to the mail is provided by IMAP4 where as POP3 is considered all mail are equal.\n\n\nIMAP4 providing security for the file mare are attached but this facility not available on POP3. \n\n"
},
{
"code": null,
"e": 297272,
"s": 297116,
"text": "Text Based Protocol\n\n By default SMTP is text based protocol but we can send Graphical data with the help of MIME (Multi-media Internet Mail Extension) \n\n"
},
{
"code": null,
"e": 297405,
"s": 297272,
"text": " By default SMTP is text based protocol but we can send Graphical data with the help of MIME (Multi-media Internet Mail Extension) "
},
{
"code": null,
"e": 297426,
"s": 297405,
"text": "\nSMTP uses port 25.\n"
},
{
"code": null,
"e": 297445,
"s": 297426,
"text": "SMTP uses port 25."
},
{
"code": null,
"e": 297521,
"s": 297445,
"text": "\nSMTP is a Post protocol it is used for sending the mail into mail server.\n"
},
{
"code": null,
"e": 297595,
"s": 297521,
"text": "SMTP is a Post protocol it is used for sending the mail into mail server."
},
{
"code": null,
"e": 297710,
"s": 297595,
"text": "\nPOP3 or (IMAP4) are known for the Pull protocol because they are used for retrieving the mail from mail server .\n"
},
{
"code": null,
"e": 297823,
"s": 297710,
"text": "POP3 or (IMAP4) are known for the Pull protocol because they are used for retrieving the mail from mail server ."
},
{
"code": null,
"e": 297923,
"s": 297823,
"text": "\nSMTP combine with POP3 or IMAP4 is client to client protocol with mediation done by mail server .\n"
},
{
"code": null,
"e": 298021,
"s": 297923,
"text": "SMTP combine with POP3 or IMAP4 is client to client protocol with mediation done by mail server ."
},
{
"code": null,
"e": 298068,
"s": 298021,
"text": "\nSMTP used TCP as a transport layer protocol.\n"
},
{
"code": null,
"e": 298113,
"s": 298068,
"text": "SMTP used TCP as a transport layer protocol."
},
{
"code": null,
"e": 298196,
"s": 298113,
"text": "\nSMTP is an asynchronies because the clocks of both clients need not synchronize.\n"
},
{
"code": null,
"e": 298277,
"s": 298196,
"text": "SMTP is an asynchronies because the clocks of both clients need not synchronize."
},
{
"code": null,
"e": 298349,
"s": 298277,
"text": "\nSMTP follows store and forward technique with the respect of server .\n"
},
{
"code": null,
"e": 298419,
"s": 298349,
"text": "SMTP follows store and forward technique with the respect of server ."
},
{
"code": null,
"e": 298511,
"s": 298419,
"text": "\nPriority to the mail is provided by IMAP4 where as POP3 is considered all mail are equal.\n"
},
{
"code": null,
"e": 298601,
"s": 298511,
"text": "Priority to the mail is provided by IMAP4 where as POP3 is considered all mail are equal."
},
{
"code": null,
"e": 298701,
"s": 298601,
"text": "\nIMAP4 providing security for the file mare are attached but this facility not available on POP3. \n"
},
{
"code": null,
"e": 298799,
"s": 298701,
"text": "IMAP4 providing security for the file mare are attached but this facility not available on POP3. "
},
{
"code": null,
"e": 298808,
"s": 298799,
"text": "\nWeekly\n"
},
{
"code": null,
"e": 298818,
"s": 298808,
"text": "\nMonthly\n"
},
{
"code": null,
"e": 298828,
"s": 298818,
"text": "\nOverall\n"
},
{
"code": null,
"e": 298834,
"s": 298828,
"text": "Error"
},
{
"code": null,
"e": 298856,
"s": 298834,
"text": "Content Related Issue"
}
] |
Lovecraft with NLP: Tokenisation and Word Counts | Towards Data Science
|
This is the second blog post in my series in which I analyse the works of H. P. Lovecraft through the lens of Natural Language Processing. In the first post, we kicked things off by analysing the overall sentiment of the stories. We can’t postpone this any longer, we have to talk about the basis of all NLP analysis: tokenisation. I thought it would be fun to pair this with a particular question, so in this post, we are going to find which words Lovecraft used the most in each story, and in his literary work combined.
One of the things you remember the most about reading Lovecraft is the odd language. He tends to use lots of negative words, horror, madness, depression, especially with adjectives: unnamable, indescribable, unspeakable horrors everywhere, right? There is something about this section from The Outsider (1921):
God knows it was not of this world — or no longer of this world — yet to my horror I saw in its eaten-away and bone-revealing outlines a leering, abhorrent travesty on the human shape; and in its mouldy, disintegrating apparel an unspeakable quality that chilled me even more.
that screams Lovecraft. On Arkham Archivist (the website from where I downloaded the text), there is a separate page dedicated to word counts, people submitted suggestions and the person who collected the stories counted them. I was curious to see if this notion can be observed “scientifically”. Are the stories as negative as we thought? What are the most used adjectives, are they “horrible” and “unknown” and “ancient”? Are verbs about knowledge and/or going crazy? Does he ever use the word “woman”? Well, let’s find out!
We are going to start with a quick theory background, apply some practical prep-work on the text, have a look at a couple of examples in spaCy, and then finally get on with word counting.
First, let’s have a look at a few concepts that we are going to use in this project.
tokenisation: a kind of document segmentation technique that breaks unstructured (text) data in small pieces of data that can be counted as discrete elements. In our analysis, individual tokens are going to be words, but that’s not necessarily the case, a token can be a paragraph, a sentence, a part of the word, or even characters.
bag-of-words: an unordered aggregated representation of a larger volume of text, which can be a document, chapter, paragraph, sentence, etc.... The grammar, punctuation, and word order from the original text are ignored, the only thing that’s kept is the unique words and a number attached to them. That number can be the frequency with which the word occurs in the text, or it can be a binary 0 or 1, simply measuring whether the word is in the text or not.
normalisation: in the NLP token context, normalisation is a group of techniques that take the original tokens as they appear in the text, and convert them to another form. This form can be the root of the word, for example, when we count the word “house” in a text, we probably want to also include “houses” and “House”, if it’s capitalised because it is at the beginning of a sentence. There are many different approaches, the one that we are going to use is lemmatisation, for example stemming and even taking the lower-case version of the text are also normalisations.
lemmatisation: the process of finding the lemma of the words. Lemmas are basically the dictionary forms of words. For example, the lemma of “houses” is “house”, “better” becomes “good”, “thought” becomes “think”, etc.
stop words: words that are so frequent in a language that their presence in a text does not contain much meaning regarding the topic of the document. For example, “a”, “why”, “do”, etc. For certain NLP tasks (like ours), it makes sense to ignore these words.
When I first did the text pre-work for this project, I suspected that I will have to circle back and do some additional tweaking, which turned out to b true — as soon as I started playing with the tokenisation, I ran into problems. For example, would you guess that these two sentences:
“Why wouldn’t we?”
“Why wouldn‘t we?”
will be lemmatised differently? The reason is the apostrophes. Generally, you want the “n’t” part of a word to be separated from the base. So “isn’t” becomes “is” and “not”. But it does not work with all apostrophes. Similar issues with hyphens, dashes, quotation marks — you wouldn’t imagine how many different characters exist for the same exact purpose!
(Note: Lovecraft almost never used contractions because he saw them as a sure sign of lack of proper education. However, he sprinkles them in sometimes in dialogues, to show — and also tell — how uneducated that person is. He did use a lot of dashes though.)
So before we do the investigation, we need to hunt down these weird characters. I think it’s important to talk a bit about these steps, even if it might seem like a bit boring, because (in my personal experience) a lot of NLP guides skip it entirely and just start with a clean text. There might be methods for this in large NLP libraries like NLTK, it might be a Unicode decoding issue, but to me, manually adjusting the text seemed like the most logical solution.
I started with analysing the characters in one story, The Dunwich Horror (1928), assumed to be saved in the text variable. Excluded whitespace and made it lower-case:
text = text.lower()text = text.replace('\n','')text = text.replace('\x0c','')text = text.replace(' ','')
Then you can create a string of unique characters like so:
unique_characters = set(text)
If you want to print them as a string, you can simply join the set
unique_characters_in_string = ''.join(set(text))
In the case of Dunwich, these were the unique characters:
'-2wdj0i”m8uüosczävèr‖l)q,4b76e’n—a1(:é.ftpk?x‘hg!;93―y5'
Then, I created a string called regular_characters, which included letters from the English alphabet, numbers, punctuation, brackets, regular quotation marks and apostrophes. We loop through them and remove the regular characters from the unique characters, so what we are left with are going to be the irregular characters.
for character in regular_characters: try: unique_characters.remove(character) except: pass
These are the characters that are left:
'ä', 'è', 'é', 'ü', '—', '―', '‖', '‘', '’', '”'
and yes,
'—' == '―'
is FALSE for some reason, and at that point, we already excluded what I thought to be the regular hyphen and dash! Similar issue with quotation marks, ‘‖’ being one of them. (That’s not a capital I, those are two vertical lines that were quotation marks in the text.) The non-English Latin letters are OK, their usage is legit in the text, in case you are wondering:
ä: “Iä! Shub-Niggurath!”
è: “Bibliothèque Nationale in Paris”
é: ”De Vigenère‘s Traité des Chiffres”
ü: “Klüber‘s Kryptographik”
I repeated this process for all the stories and collected all the weird characters that I wanted to tweak. I ended up with this replace dictionary:
replace_dict = {}replace_dict['*'] = ''replace_dict['—'] = '–'replace_dict['―'] = ''replace_dict['‖'] = '\"'replace_dict[' ̳'] = ''replace_dict['”'] = '"'replace_dict['‘'] = '\''replace_dict['’'] = '\''
And looped through all the text files, applied the replacements:
for replace_char in replace_dict: text = raw_text.replace(\ replace_char, replace_dict[replace_char])
and saved them as new TXT files. They should work properly. All right, on to the real thing now.
We start by installing the NLP library we are going to work with: spaCy.
pip install spacy
We also need to separately install a language model that we are going to use. There are models available for a number of languages, three different ones for English. Most of the guides I found recommend starting with en_core_web_sm, and I figured that would do for a simple project, but after some trial and error, I decided to useen_core_web_lg. (We will see an example of why later on.)
To install the model:
python -m spacy download en_core_web_lg
Please note that it might take some time to download and build the large model.
Now, we can set up an nlp object that is going to be our NLP model, and create a doc object that is the processed version of the string input:
nlp = spacy.load(“en_core_web_lg”)doc = nlp(“At midnight the doorbell rang, startling him fearfully.”)
doc is a Doc object, it’s basically a container of tokens. So at this point, we already have our text tokenised! Doc keeps all the information from the original text like whitespace, so you can re-build the text from it.
The tokens in a Doc object are Token objects, with a long list of attributes you can request, see the full list here. For now, we are going to use three attributes:
text: simply the text of the token as it appears in the text
lemma_: lemma of the token
pos_: the part-of-speech tag of the token (for example noun, adjective, verb, etc...)
To analyse our sentence, we can list the token attributes:
for token in doc: print(token.text, token.lemma_, token.pos_)
Which will print out this:
At at ADPmidnight midnight NOUNthe the DETdoorbell doorbell PROPNrang ring VERB, , PUNCTstartling startle VERBhim -PRON- PRONfearfully fearfully ADV. . PUNCT
It seems almost correct, falsely categorised “doorbell” as a proper noun, as opposed to a noun. This was the large model. The small model performed worse, categorised “rang” as a proper noun, and did not find the present tense of the verb. For some reason, this turned out to be a tricky sentence.
You can also visualise a sentence with the display method, although I think this is mainly useful in an educational environment. If you are working in a Jupyter Notebook, you already have a browser window open, and you can use the render method:
spacy.displacy.render(doc, style=”dep”)
You can also save these visualisations as SVG files, you can read more about how to do that in the documentation.
We saw how well spaCy works out of the box with a random sentence. What about really weird sentences with intentional misspellings like this one from Old Bugs (1919):
Some swell guy, too–’s father’s a big corp’ration lawyer up in his burg, ’n’ ‘s mother’s some lit’ry genius.
Well, the library struggles, as expected. It more or less gets the part of speech indexes of the tokens, but does not recognise that “ ’n’ ” is supposed to be “and”, “ ‘s “ is supposed to be “his”, etc...
One more thing I want to talk about in the spaCy library is how it recognises named entities in a text. To my surprise, it even works on fictional ones.
Take the opening sentence from Herbert West — Reanimator (1922).
Of Herbert West, who was my friend in college and in after life, I can speak only with extreme terror.
We can loop through the ents in the Doc object for the named entities:
doc = nlp(text)for ent in doc.ents: print(ent.text, ent.label_)
Will return:
Herbert West PERSON
Which I found to be a quite impressive feature. Let’s see another sentence from the same story:
We were in the third year of our course at the Miskatonic University Medical School in Arkham.
After we list the entities in the same way, we get:
the third year DATEUniversity Medical School ORGArkham GPE
Almost perfect, although it missed the “Miskatonic” part for some reason.
This can also be visualised, this time we should set the style to “ent”:
spacy.displacy.render(doc, style=”ent”)
returns:
That’s all we need from spaCy for now.
As a first step, we are concentrating on one story. There are many built-in methods in libraries that do bag-of-words for you automatically, I did not find one that did exactly what I needed, and fortunately, it’s really simple to code it ourselves! Let’s create a number of helper functions first for this project.
First, we build a create_word_counts_by_pos function that takes in a raw text file, a list of part-of-speech tags, and optionally a word count dictionary in case we want to aggregate multiple stories this way. It will return one dictionary, where the keys are part-of-speech tags, and the values are smaller dictionaries with the words of the corresponding tag as values and their counts in the text as values... So the result dictionary of word_count_dict will have a word_count_dict[‘NOUN’] dictionary inside, which will consist of key-value pairs like ‘man’: 4, ‘house’: 28, ..., similar structure for word_count_dict[‘ADJ’], word_count_dict[‘VERB’], etc.
An important part of this process is that we want to exclude the stop words, which is really simple to do with spaCy, the tokens have an is_stop method that returns a boolean, we only need to consider tokens where this attribute is False.
Assuming we have a word_count_dict in this format, we might want to filter down to words above a certain threshold. This is what filter_word_count_dict_to_frequent will do, keep the structure of the input dictionary, but delete all elements where the count was below the threshold.
And finally, we will need some way to order the words so we can know which ones were the most frequent. This is what collect_most_frequent_words will be responsible for, you enter a word count dictionary with a number, and you get that many of the highest frequency words from each part-of-speech category.
This is all the code we are going to need to accomplish what we just discussed:
Now that we have these functions, getting the word counts in different structures is very easy. For now, we are only curious about the nouns, proper nouns, adjectives, and verbs:
list_of_pos = ['NOUN', 'PROPN', 'ADJ', 'VERB']
Assuming we have all the text in the text variable, to get the word_count_dict:
word_count_dict = \ word_count_func.create_word_counts_by_pos(text, list_of_pos)
word_count_dict will be a long collection of words, any noun, adjective, or verb that appears in the text even once will be represented there. We can filter it down to only words that appear more than 10 times:
frequent_word_count_dict = \ word_count_func.filter_word_count_dict_to_frequent( word_count_dict, 10)
frequent_word_count_dict is concise enough that it does not seem excessive to simply copy it here:
{'NOUN': {'friend': 13, 'college': 21, 'life': 39, 'work': 18, 'year': 19, 'experiment': 24, 'fear': 13, 'death': 16, 'solution': 22, 'time': 20, 'case': 11, 'reanimation': 13, 'corpse': 14, 'specimen': 34, 'body': 49, 'eye': 17, 'field': 15, 'thing': 53, 'room': 12, 'laboratory': 18, 'house': 16, 'horror': 15, 'man': 28, 'result': 15, 'night': 17, 'sound': 14, 'police': 13}, 'PROPN': {'Herbert': 20, 'West': 132, 'Arkham': 18, 'Dr.': 15, 'Bolton': 12}, 'ADJ': {'great': 20, 'hideous': 17, 'dead': 23, 'human': 21, 'fresh': 28, 'small': 12, 'new': 14, 'large': 12}, 'VERB': {'see': 17, 'come': 24, 'hold': 11, 'know': 18, 'find': 14, 'restore': 11, 'inject': 15, 'think': 18, 'look': 14, 'tell': 11}}
If you read the story / saw the film, you will probably find a lot of these satisfying. For those of you who did not: the story is basically about a mad scientist who creates zombies, and is on a never-ending quest to find fresh corpses.
Let’s take the adjectives, the top three adjectives are: “fresh dead human” could be the working title of the story. “specimen” is used more often than “man”, apparently the narrator who is friends with Herbert West mostly refers to him as “West”, not as “Herbert”, and the verb “inject” is used suspiciously often.
Now let’s do this for all the stories!
I decided to omit the proper nouns from the analysis, and concentrate on the top 5 words per part-of-speech for each story. First, we need to set up some variables:
number_of_words_to_collect = 5list_of_pos = ['NOUN', 'ADJ', 'VERB']words = {}word_counts = {}for part_of_speech in list_of_pos: words[part_of_speech] = {} word_counts[part_of_speech] = {} for number in range(number_of_words_to_collect): words[part_of_speech][number] = [] word_counts[part_of_speech][number] = []
Then, we can do a similar process to what we did with the individual story in the previous chapter. We are not using the frequent dictionaries, instead, request a list of the most frequent words. Assuming filenames contains the names of files we want to import, and they are saved in the txt_folder:
for filename in filenames: my_file = open(txt_adjusted_folder + filename + '.txt') print("Currently processing: " + filename) raw_text = my_file.read() word_count_dict = \ word_count_func.create_word_counts_by_pos( raw_text, list_of_pos) most_frequent_list_dict = \ word_count_func.collect_most_frequent_words( word_count_dict, number_of_words_to_collect) for part_of_speech in list_of_pos: for number in range(number_of_words_to_collect): words[part_of_speech][number].append( most_frequent_list_dict[part_of_speech][number][0]) word_counts[part_of_speech][number].append( most_frequent_list_dict[part_of_speech][number][1])
After that’s done, we should have everything we need in the two dictionaries, words and word_counts. I combined them with pandas, for the ‘NOUN’ group, we can do it like so:
noun_counts = pd.DataFrame()noun_counts['filename'] = filenamesfor i in range(number_of_words_to_collect): noun_counts['word_' + str(i+1)] = \ words['NOUN'][i] noun_counts['word_' + str(i+1) + '_count'] = \ word_counts['NOUN'][i]
Repeat the same for adjectives and verbs, and now we have the top 5 words with their counts in the 3 part-of-speech groups for the 63 stories in the corpus. Copying them all here would be a bit much, you can find the data in CSV files here for nouns, adjectives, and verbs.
Let me just grab a couple of examples that I found to be really interesting.
Nouns:
One of my personal favourites, The Music of Erich Zann (1921) is represented by these nouns: street, music, night, window, room.
The Lurking Fear (1922): mansion, fear, night, thing, eye.
The Whisperer in Darkness (1930): thing, man, letter, time, voice
Adjectives:
Celephaïs (1920): strange, white, great, golden, old
The Call of Cthulhu (1925): great, old, strange, young, dead
The verbs are usually not that closely matching with the story, there are a lot of general verbs out there after all. Plus Lovecraft’s style is very descriptive and distant, and there is hardly any action.
All right, I’m pretty satisfied so far, I think it’s impressive how such a basic analysis managed to capture the essence of so many of the stories.
And finally, back to the big question, which words did he use the most often ever? Following a similar process as above, but in every turn, we keep the word_count_dict, so it calculates a combined score. (Combining all the text does not work, it’s roughly 2.5 times more than the memory limit in spaCy.)
So, drumroll, these are the 20 nouns, adjectives, and verbs that Lovecraft used the most often:
{'NOUN': [('thing', 1152), ('man', 1075), ('time', 830), ('night', 666), ('place', 569), ('house', 490), ('day', 476), ('city', 453), ('year', 432), ('stone', 407), ('dream', 392), ('room', 383), ('world', 379), ('door', 370), ('way', 367), ('horror', 352), ('light', 350), ('life', 340), ('wall', 335), ('eye', 333)], 'ADJ': [('old', 917), ('great', 797), ('strange', 488), ('certain', 446), ('black', 379), ('little', 336), ('ancient', 308), ('high', 297), ('small', 282), ('dark', 277), ('new', 268), ('human', 267), ('unknown', 259), ('terrible', 256), ('long', 244), ('curious', 227), ('low', 216), ('hideous', 213), ('young', 210), ('good', 204)], 'VERB': [('come', 1100), ('know', 1095), ('see', 1079), ('find', 784), ('tell', 649), ('think', 571), ('hear', 528), ('look', 474), ('go', 439), ('say', 425), ('leave', 401), ('begin', 400), ('feel', 397), ('take', 368), ('grow', 310), ('give', 306), ('shew', 275), ('bring', 267), ('speak', 266), ('try', 262)]}
Once again, I think the verbs are the least exciting, although you can see how most of the verbs are about knowledge gathering or sharing. In case you are wondering, “shew” is the old-fashioned spelling of show.
Nouns are better, “time”, “night”, “stone”, “dream”, “horror” — I would guess the writer is Lovecraft based on just these five words. I mean, horror is there in the top 20 nouns ever used, that is certainly reassuring!
And finally, the adjectives, at least 2/3rd of them would generally be weird to have so high on the list. The most often used adjective is “old”, I mean, how awesome is that? And the list goes on to “great”, “strange”, “ancient”, “unknown”, “terrible”, etc.
(You might notice that we have “hideous” 213 times, but on the Arkham Archivist page that I mentioned in the intro, there are 260 counts of the word. The difference is due to the fact that we separate word usage by part-of-speech. He used the word 213 times as an adjective, but that does not include “hideousness” which is a noun, or “hideously” which is an adverb.)
I think there are many more interesting analysis you could do with these simple NLP tools. We limited our scope to nouns, adjectives, and verbs, it would be interesting to see adverbs or proper nouns too. Analysing the relative portion of let’s say verbs in different years would also be interesting. That way, we could see if the stories became more action-packed as time went by, or was it the other way around? There is also a very important concept we did not consider: the n-grams. A very similar analysis could be done to find the most frequently used expressions in his writings.
We started with a very simple question: I wonder what is Lovecraft's most frequently used word? And for such a simple question this turned out to be more complicated than I imagined. It was really cool to see such a simple NLP representation to work surprisingly well.
In the next post, I am going to write about how one can take word counts a step further and calculate the differences between documents using TF-IDF vectors.
Hobson, L. & Cole, H. & Hannes, H. (2019). Natural Language Processing in Action: Understanding, Analyzing, and Generating Text with Python. Manning Publications, 2019.
spacy.io
The Complete Works of H. P. Lovecraft:
|
[
{
"code": null,
"e": 694,
"s": 171,
"text": "This is the second blog post in my series in which I analyse the works of H. P. Lovecraft through the lens of Natural Language Processing. In the first post, we kicked things off by analysing the overall sentiment of the stories. We can’t postpone this any longer, we have to talk about the basis of all NLP analysis: tokenisation. I thought it would be fun to pair this with a particular question, so in this post, we are going to find which words Lovecraft used the most in each story, and in his literary work combined."
},
{
"code": null,
"e": 1005,
"s": 694,
"text": "One of the things you remember the most about reading Lovecraft is the odd language. He tends to use lots of negative words, horror, madness, depression, especially with adjectives: unnamable, indescribable, unspeakable horrors everywhere, right? There is something about this section from The Outsider (1921):"
},
{
"code": null,
"e": 1282,
"s": 1005,
"text": "God knows it was not of this world — or no longer of this world — yet to my horror I saw in its eaten-away and bone-revealing outlines a leering, abhorrent travesty on the human shape; and in its mouldy, disintegrating apparel an unspeakable quality that chilled me even more."
},
{
"code": null,
"e": 1809,
"s": 1282,
"text": "that screams Lovecraft. On Arkham Archivist (the website from where I downloaded the text), there is a separate page dedicated to word counts, people submitted suggestions and the person who collected the stories counted them. I was curious to see if this notion can be observed “scientifically”. Are the stories as negative as we thought? What are the most used adjectives, are they “horrible” and “unknown” and “ancient”? Are verbs about knowledge and/or going crazy? Does he ever use the word “woman”? Well, let’s find out!"
},
{
"code": null,
"e": 1997,
"s": 1809,
"text": "We are going to start with a quick theory background, apply some practical prep-work on the text, have a look at a couple of examples in spaCy, and then finally get on with word counting."
},
{
"code": null,
"e": 2082,
"s": 1997,
"text": "First, let’s have a look at a few concepts that we are going to use in this project."
},
{
"code": null,
"e": 2416,
"s": 2082,
"text": "tokenisation: a kind of document segmentation technique that breaks unstructured (text) data in small pieces of data that can be counted as discrete elements. In our analysis, individual tokens are going to be words, but that’s not necessarily the case, a token can be a paragraph, a sentence, a part of the word, or even characters."
},
{
"code": null,
"e": 2875,
"s": 2416,
"text": "bag-of-words: an unordered aggregated representation of a larger volume of text, which can be a document, chapter, paragraph, sentence, etc.... The grammar, punctuation, and word order from the original text are ignored, the only thing that’s kept is the unique words and a number attached to them. That number can be the frequency with which the word occurs in the text, or it can be a binary 0 or 1, simply measuring whether the word is in the text or not."
},
{
"code": null,
"e": 3447,
"s": 2875,
"text": "normalisation: in the NLP token context, normalisation is a group of techniques that take the original tokens as they appear in the text, and convert them to another form. This form can be the root of the word, for example, when we count the word “house” in a text, we probably want to also include “houses” and “House”, if it’s capitalised because it is at the beginning of a sentence. There are many different approaches, the one that we are going to use is lemmatisation, for example stemming and even taking the lower-case version of the text are also normalisations."
},
{
"code": null,
"e": 3665,
"s": 3447,
"text": "lemmatisation: the process of finding the lemma of the words. Lemmas are basically the dictionary forms of words. For example, the lemma of “houses” is “house”, “better” becomes “good”, “thought” becomes “think”, etc."
},
{
"code": null,
"e": 3924,
"s": 3665,
"text": "stop words: words that are so frequent in a language that their presence in a text does not contain much meaning regarding the topic of the document. For example, “a”, “why”, “do”, etc. For certain NLP tasks (like ours), it makes sense to ignore these words."
},
{
"code": null,
"e": 4211,
"s": 3924,
"text": "When I first did the text pre-work for this project, I suspected that I will have to circle back and do some additional tweaking, which turned out to b true — as soon as I started playing with the tokenisation, I ran into problems. For example, would you guess that these two sentences:"
},
{
"code": null,
"e": 4230,
"s": 4211,
"text": "“Why wouldn’t we?”"
},
{
"code": null,
"e": 4249,
"s": 4230,
"text": "“Why wouldn‘t we?”"
},
{
"code": null,
"e": 4606,
"s": 4249,
"text": "will be lemmatised differently? The reason is the apostrophes. Generally, you want the “n’t” part of a word to be separated from the base. So “isn’t” becomes “is” and “not”. But it does not work with all apostrophes. Similar issues with hyphens, dashes, quotation marks — you wouldn’t imagine how many different characters exist for the same exact purpose!"
},
{
"code": null,
"e": 4865,
"s": 4606,
"text": "(Note: Lovecraft almost never used contractions because he saw them as a sure sign of lack of proper education. However, he sprinkles them in sometimes in dialogues, to show — and also tell — how uneducated that person is. He did use a lot of dashes though.)"
},
{
"code": null,
"e": 5331,
"s": 4865,
"text": "So before we do the investigation, we need to hunt down these weird characters. I think it’s important to talk a bit about these steps, even if it might seem like a bit boring, because (in my personal experience) a lot of NLP guides skip it entirely and just start with a clean text. There might be methods for this in large NLP libraries like NLTK, it might be a Unicode decoding issue, but to me, manually adjusting the text seemed like the most logical solution."
},
{
"code": null,
"e": 5498,
"s": 5331,
"text": "I started with analysing the characters in one story, The Dunwich Horror (1928), assumed to be saved in the text variable. Excluded whitespace and made it lower-case:"
},
{
"code": null,
"e": 5603,
"s": 5498,
"text": "text = text.lower()text = text.replace('\\n','')text = text.replace('\\x0c','')text = text.replace(' ','')"
},
{
"code": null,
"e": 5662,
"s": 5603,
"text": "Then you can create a string of unique characters like so:"
},
{
"code": null,
"e": 5692,
"s": 5662,
"text": "unique_characters = set(text)"
},
{
"code": null,
"e": 5759,
"s": 5692,
"text": "If you want to print them as a string, you can simply join the set"
},
{
"code": null,
"e": 5808,
"s": 5759,
"text": "unique_characters_in_string = ''.join(set(text))"
},
{
"code": null,
"e": 5866,
"s": 5808,
"text": "In the case of Dunwich, these were the unique characters:"
},
{
"code": null,
"e": 5928,
"s": 5866,
"text": "'-2wdj0i”m8uüosczävèr‖l)q,4b76e’n—a1(:é.ftpk?x‘hg!;93―y5'"
},
{
"code": null,
"e": 6253,
"s": 5928,
"text": "Then, I created a string called regular_characters, which included letters from the English alphabet, numbers, punctuation, brackets, regular quotation marks and apostrophes. We loop through them and remove the regular characters from the unique characters, so what we are left with are going to be the irregular characters."
},
{
"code": null,
"e": 6364,
"s": 6253,
"text": "for character in regular_characters: try: unique_characters.remove(character) except: pass"
},
{
"code": null,
"e": 6404,
"s": 6364,
"text": "These are the characters that are left:"
},
{
"code": null,
"e": 6457,
"s": 6404,
"text": "'ä', 'è', 'é', 'ü', '—', '―', '‖', '‘', '’', '”'"
},
{
"code": null,
"e": 6466,
"s": 6457,
"text": "and yes,"
},
{
"code": null,
"e": 6477,
"s": 6466,
"text": "'—' == '―'"
},
{
"code": null,
"e": 6844,
"s": 6477,
"text": "is FALSE for some reason, and at that point, we already excluded what I thought to be the regular hyphen and dash! Similar issue with quotation marks, ‘‖’ being one of them. (That’s not a capital I, those are two vertical lines that were quotation marks in the text.) The non-English Latin letters are OK, their usage is legit in the text, in case you are wondering:"
},
{
"code": null,
"e": 6871,
"s": 6844,
"text": "ä: “Iä! Shub-Niggurath!”"
},
{
"code": null,
"e": 6910,
"s": 6871,
"text": "è: “Bibliothèque Nationale in Paris”"
},
{
"code": null,
"e": 6952,
"s": 6910,
"text": "é: ”De Vigenère‘s Traité des Chiffres”"
},
{
"code": null,
"e": 6982,
"s": 6952,
"text": "ü: “Klüber‘s Kryptographik”"
},
{
"code": null,
"e": 7130,
"s": 6982,
"text": "I repeated this process for all the stories and collected all the weird characters that I wanted to tweak. I ended up with this replace dictionary:"
},
{
"code": null,
"e": 7333,
"s": 7130,
"text": "replace_dict = {}replace_dict['*'] = ''replace_dict['—'] = '–'replace_dict['―'] = ''replace_dict['‖'] = '\\\"'replace_dict[' ̳'] = ''replace_dict['”'] = '\"'replace_dict['‘'] = '\\''replace_dict['’'] = '\\''"
},
{
"code": null,
"e": 7398,
"s": 7333,
"text": "And looped through all the text files, applied the replacements:"
},
{
"code": null,
"e": 7512,
"s": 7398,
"text": "for replace_char in replace_dict: text = raw_text.replace(\\ replace_char, replace_dict[replace_char])"
},
{
"code": null,
"e": 7609,
"s": 7512,
"text": "and saved them as new TXT files. They should work properly. All right, on to the real thing now."
},
{
"code": null,
"e": 7682,
"s": 7609,
"text": "We start by installing the NLP library we are going to work with: spaCy."
},
{
"code": null,
"e": 7700,
"s": 7682,
"text": "pip install spacy"
},
{
"code": null,
"e": 8089,
"s": 7700,
"text": "We also need to separately install a language model that we are going to use. There are models available for a number of languages, three different ones for English. Most of the guides I found recommend starting with en_core_web_sm, and I figured that would do for a simple project, but after some trial and error, I decided to useen_core_web_lg. (We will see an example of why later on.)"
},
{
"code": null,
"e": 8111,
"s": 8089,
"text": "To install the model:"
},
{
"code": null,
"e": 8151,
"s": 8111,
"text": "python -m spacy download en_core_web_lg"
},
{
"code": null,
"e": 8231,
"s": 8151,
"text": "Please note that it might take some time to download and build the large model."
},
{
"code": null,
"e": 8374,
"s": 8231,
"text": "Now, we can set up an nlp object that is going to be our NLP model, and create a doc object that is the processed version of the string input:"
},
{
"code": null,
"e": 8477,
"s": 8374,
"text": "nlp = spacy.load(“en_core_web_lg”)doc = nlp(“At midnight the doorbell rang, startling him fearfully.”)"
},
{
"code": null,
"e": 8698,
"s": 8477,
"text": "doc is a Doc object, it’s basically a container of tokens. So at this point, we already have our text tokenised! Doc keeps all the information from the original text like whitespace, so you can re-build the text from it."
},
{
"code": null,
"e": 8863,
"s": 8698,
"text": "The tokens in a Doc object are Token objects, with a long list of attributes you can request, see the full list here. For now, we are going to use three attributes:"
},
{
"code": null,
"e": 8924,
"s": 8863,
"text": "text: simply the text of the token as it appears in the text"
},
{
"code": null,
"e": 8951,
"s": 8924,
"text": "lemma_: lemma of the token"
},
{
"code": null,
"e": 9037,
"s": 8951,
"text": "pos_: the part-of-speech tag of the token (for example noun, adjective, verb, etc...)"
},
{
"code": null,
"e": 9096,
"s": 9037,
"text": "To analyse our sentence, we can list the token attributes:"
},
{
"code": null,
"e": 9162,
"s": 9096,
"text": "for token in doc: print(token.text, token.lemma_, token.pos_)"
},
{
"code": null,
"e": 9189,
"s": 9162,
"text": "Which will print out this:"
},
{
"code": null,
"e": 9347,
"s": 9189,
"text": "At at ADPmidnight midnight NOUNthe the DETdoorbell doorbell PROPNrang ring VERB, , PUNCTstartling startle VERBhim -PRON- PRONfearfully fearfully ADV. . PUNCT"
},
{
"code": null,
"e": 9645,
"s": 9347,
"text": "It seems almost correct, falsely categorised “doorbell” as a proper noun, as opposed to a noun. This was the large model. The small model performed worse, categorised “rang” as a proper noun, and did not find the present tense of the verb. For some reason, this turned out to be a tricky sentence."
},
{
"code": null,
"e": 9891,
"s": 9645,
"text": "You can also visualise a sentence with the display method, although I think this is mainly useful in an educational environment. If you are working in a Jupyter Notebook, you already have a browser window open, and you can use the render method:"
},
{
"code": null,
"e": 9931,
"s": 9891,
"text": "spacy.displacy.render(doc, style=”dep”)"
},
{
"code": null,
"e": 10045,
"s": 9931,
"text": "You can also save these visualisations as SVG files, you can read more about how to do that in the documentation."
},
{
"code": null,
"e": 10212,
"s": 10045,
"text": "We saw how well spaCy works out of the box with a random sentence. What about really weird sentences with intentional misspellings like this one from Old Bugs (1919):"
},
{
"code": null,
"e": 10321,
"s": 10212,
"text": "Some swell guy, too–’s father’s a big corp’ration lawyer up in his burg, ’n’ ‘s mother’s some lit’ry genius."
},
{
"code": null,
"e": 10526,
"s": 10321,
"text": "Well, the library struggles, as expected. It more or less gets the part of speech indexes of the tokens, but does not recognise that “ ’n’ ” is supposed to be “and”, “ ‘s “ is supposed to be “his”, etc..."
},
{
"code": null,
"e": 10679,
"s": 10526,
"text": "One more thing I want to talk about in the spaCy library is how it recognises named entities in a text. To my surprise, it even works on fictional ones."
},
{
"code": null,
"e": 10744,
"s": 10679,
"text": "Take the opening sentence from Herbert West — Reanimator (1922)."
},
{
"code": null,
"e": 10847,
"s": 10744,
"text": "Of Herbert West, who was my friend in college and in after life, I can speak only with extreme terror."
},
{
"code": null,
"e": 10918,
"s": 10847,
"text": "We can loop through the ents in the Doc object for the named entities:"
},
{
"code": null,
"e": 10985,
"s": 10918,
"text": "doc = nlp(text)for ent in doc.ents: print(ent.text, ent.label_)"
},
{
"code": null,
"e": 10998,
"s": 10985,
"text": "Will return:"
},
{
"code": null,
"e": 11018,
"s": 10998,
"text": "Herbert West PERSON"
},
{
"code": null,
"e": 11114,
"s": 11018,
"text": "Which I found to be a quite impressive feature. Let’s see another sentence from the same story:"
},
{
"code": null,
"e": 11209,
"s": 11114,
"text": "We were in the third year of our course at the Miskatonic University Medical School in Arkham."
},
{
"code": null,
"e": 11261,
"s": 11209,
"text": "After we list the entities in the same way, we get:"
},
{
"code": null,
"e": 11320,
"s": 11261,
"text": "the third year DATEUniversity Medical School ORGArkham GPE"
},
{
"code": null,
"e": 11394,
"s": 11320,
"text": "Almost perfect, although it missed the “Miskatonic” part for some reason."
},
{
"code": null,
"e": 11467,
"s": 11394,
"text": "This can also be visualised, this time we should set the style to “ent”:"
},
{
"code": null,
"e": 11507,
"s": 11467,
"text": "spacy.displacy.render(doc, style=”ent”)"
},
{
"code": null,
"e": 11516,
"s": 11507,
"text": "returns:"
},
{
"code": null,
"e": 11555,
"s": 11516,
"text": "That’s all we need from spaCy for now."
},
{
"code": null,
"e": 11871,
"s": 11555,
"text": "As a first step, we are concentrating on one story. There are many built-in methods in libraries that do bag-of-words for you automatically, I did not find one that did exactly what I needed, and fortunately, it’s really simple to code it ourselves! Let’s create a number of helper functions first for this project."
},
{
"code": null,
"e": 12530,
"s": 11871,
"text": "First, we build a create_word_counts_by_pos function that takes in a raw text file, a list of part-of-speech tags, and optionally a word count dictionary in case we want to aggregate multiple stories this way. It will return one dictionary, where the keys are part-of-speech tags, and the values are smaller dictionaries with the words of the corresponding tag as values and their counts in the text as values... So the result dictionary of word_count_dict will have a word_count_dict[‘NOUN’] dictionary inside, which will consist of key-value pairs like ‘man’: 4, ‘house’: 28, ..., similar structure for word_count_dict[‘ADJ’], word_count_dict[‘VERB’], etc."
},
{
"code": null,
"e": 12769,
"s": 12530,
"text": "An important part of this process is that we want to exclude the stop words, which is really simple to do with spaCy, the tokens have an is_stop method that returns a boolean, we only need to consider tokens where this attribute is False."
},
{
"code": null,
"e": 13051,
"s": 12769,
"text": "Assuming we have a word_count_dict in this format, we might want to filter down to words above a certain threshold. This is what filter_word_count_dict_to_frequent will do, keep the structure of the input dictionary, but delete all elements where the count was below the threshold."
},
{
"code": null,
"e": 13358,
"s": 13051,
"text": "And finally, we will need some way to order the words so we can know which ones were the most frequent. This is what collect_most_frequent_words will be responsible for, you enter a word count dictionary with a number, and you get that many of the highest frequency words from each part-of-speech category."
},
{
"code": null,
"e": 13438,
"s": 13358,
"text": "This is all the code we are going to need to accomplish what we just discussed:"
},
{
"code": null,
"e": 13617,
"s": 13438,
"text": "Now that we have these functions, getting the word counts in different structures is very easy. For now, we are only curious about the nouns, proper nouns, adjectives, and verbs:"
},
{
"code": null,
"e": 13664,
"s": 13617,
"text": "list_of_pos = ['NOUN', 'PROPN', 'ADJ', 'VERB']"
},
{
"code": null,
"e": 13744,
"s": 13664,
"text": "Assuming we have all the text in the text variable, to get the word_count_dict:"
},
{
"code": null,
"e": 13828,
"s": 13744,
"text": "word_count_dict = \\ word_count_func.create_word_counts_by_pos(text, list_of_pos)"
},
{
"code": null,
"e": 14039,
"s": 13828,
"text": "word_count_dict will be a long collection of words, any noun, adjective, or verb that appears in the text even once will be represented there. We can filter it down to only words that appear more than 10 times:"
},
{
"code": null,
"e": 14151,
"s": 14039,
"text": "frequent_word_count_dict = \\ word_count_func.filter_word_count_dict_to_frequent( word_count_dict, 10)"
},
{
"code": null,
"e": 14250,
"s": 14151,
"text": "frequent_word_count_dict is concise enough that it does not seem excessive to simply copy it here:"
},
{
"code": null,
"e": 15000,
"s": 14250,
"text": "{'NOUN': {'friend': 13, 'college': 21, 'life': 39, 'work': 18, 'year': 19, 'experiment': 24, 'fear': 13, 'death': 16, 'solution': 22, 'time': 20, 'case': 11, 'reanimation': 13, 'corpse': 14, 'specimen': 34, 'body': 49, 'eye': 17, 'field': 15, 'thing': 53, 'room': 12, 'laboratory': 18, 'house': 16, 'horror': 15, 'man': 28, 'result': 15, 'night': 17, 'sound': 14, 'police': 13}, 'PROPN': {'Herbert': 20, 'West': 132, 'Arkham': 18, 'Dr.': 15, 'Bolton': 12}, 'ADJ': {'great': 20, 'hideous': 17, 'dead': 23, 'human': 21, 'fresh': 28, 'small': 12, 'new': 14, 'large': 12}, 'VERB': {'see': 17, 'come': 24, 'hold': 11, 'know': 18, 'find': 14, 'restore': 11, 'inject': 15, 'think': 18, 'look': 14, 'tell': 11}}"
},
{
"code": null,
"e": 15238,
"s": 15000,
"text": "If you read the story / saw the film, you will probably find a lot of these satisfying. For those of you who did not: the story is basically about a mad scientist who creates zombies, and is on a never-ending quest to find fresh corpses."
},
{
"code": null,
"e": 15554,
"s": 15238,
"text": "Let’s take the adjectives, the top three adjectives are: “fresh dead human” could be the working title of the story. “specimen” is used more often than “man”, apparently the narrator who is friends with Herbert West mostly refers to him as “West”, not as “Herbert”, and the verb “inject” is used suspiciously often."
},
{
"code": null,
"e": 15593,
"s": 15554,
"text": "Now let’s do this for all the stories!"
},
{
"code": null,
"e": 15758,
"s": 15593,
"text": "I decided to omit the proper nouns from the analysis, and concentrate on the top 5 words per part-of-speech for each story. First, we need to set up some variables:"
},
{
"code": null,
"e": 16094,
"s": 15758,
"text": "number_of_words_to_collect = 5list_of_pos = ['NOUN', 'ADJ', 'VERB']words = {}word_counts = {}for part_of_speech in list_of_pos: words[part_of_speech] = {} word_counts[part_of_speech] = {} for number in range(number_of_words_to_collect): words[part_of_speech][number] = [] word_counts[part_of_speech][number] = []"
},
{
"code": null,
"e": 16394,
"s": 16094,
"text": "Then, we can do a similar process to what we did with the individual story in the previous chapter. We are not using the frequent dictionaries, instead, request a list of the most frequent words. Assuming filenames contains the names of files we want to import, and they are saved in the txt_folder:"
},
{
"code": null,
"e": 17135,
"s": 16394,
"text": "for filename in filenames: my_file = open(txt_adjusted_folder + filename + '.txt') print(\"Currently processing: \" + filename) raw_text = my_file.read() word_count_dict = \\ word_count_func.create_word_counts_by_pos( raw_text, list_of_pos) most_frequent_list_dict = \\ word_count_func.collect_most_frequent_words( word_count_dict, number_of_words_to_collect) for part_of_speech in list_of_pos: for number in range(number_of_words_to_collect): words[part_of_speech][number].append( most_frequent_list_dict[part_of_speech][number][0]) word_counts[part_of_speech][number].append( most_frequent_list_dict[part_of_speech][number][1])"
},
{
"code": null,
"e": 17309,
"s": 17135,
"text": "After that’s done, we should have everything we need in the two dictionaries, words and word_counts. I combined them with pandas, for the ‘NOUN’ group, we can do it like so:"
},
{
"code": null,
"e": 17560,
"s": 17309,
"text": "noun_counts = pd.DataFrame()noun_counts['filename'] = filenamesfor i in range(number_of_words_to_collect): noun_counts['word_' + str(i+1)] = \\ words['NOUN'][i] noun_counts['word_' + str(i+1) + '_count'] = \\ word_counts['NOUN'][i]"
},
{
"code": null,
"e": 17834,
"s": 17560,
"text": "Repeat the same for adjectives and verbs, and now we have the top 5 words with their counts in the 3 part-of-speech groups for the 63 stories in the corpus. Copying them all here would be a bit much, you can find the data in CSV files here for nouns, adjectives, and verbs."
},
{
"code": null,
"e": 17911,
"s": 17834,
"text": "Let me just grab a couple of examples that I found to be really interesting."
},
{
"code": null,
"e": 17918,
"s": 17911,
"text": "Nouns:"
},
{
"code": null,
"e": 18047,
"s": 17918,
"text": "One of my personal favourites, The Music of Erich Zann (1921) is represented by these nouns: street, music, night, window, room."
},
{
"code": null,
"e": 18106,
"s": 18047,
"text": "The Lurking Fear (1922): mansion, fear, night, thing, eye."
},
{
"code": null,
"e": 18172,
"s": 18106,
"text": "The Whisperer in Darkness (1930): thing, man, letter, time, voice"
},
{
"code": null,
"e": 18184,
"s": 18172,
"text": "Adjectives:"
},
{
"code": null,
"e": 18238,
"s": 18184,
"text": "Celephaïs (1920): strange, white, great, golden, old"
},
{
"code": null,
"e": 18299,
"s": 18238,
"text": "The Call of Cthulhu (1925): great, old, strange, young, dead"
},
{
"code": null,
"e": 18505,
"s": 18299,
"text": "The verbs are usually not that closely matching with the story, there are a lot of general verbs out there after all. Plus Lovecraft’s style is very descriptive and distant, and there is hardly any action."
},
{
"code": null,
"e": 18653,
"s": 18505,
"text": "All right, I’m pretty satisfied so far, I think it’s impressive how such a basic analysis managed to capture the essence of so many of the stories."
},
{
"code": null,
"e": 18957,
"s": 18653,
"text": "And finally, back to the big question, which words did he use the most often ever? Following a similar process as above, but in every turn, we keep the word_count_dict, so it calculates a combined score. (Combining all the text does not work, it’s roughly 2.5 times more than the memory limit in spaCy.)"
},
{
"code": null,
"e": 19053,
"s": 18957,
"text": "So, drumroll, these are the 20 nouns, adjectives, and verbs that Lovecraft used the most often:"
},
{
"code": null,
"e": 20077,
"s": 19053,
"text": "{'NOUN': [('thing', 1152), ('man', 1075), ('time', 830), ('night', 666), ('place', 569), ('house', 490), ('day', 476), ('city', 453), ('year', 432), ('stone', 407), ('dream', 392), ('room', 383), ('world', 379), ('door', 370), ('way', 367), ('horror', 352), ('light', 350), ('life', 340), ('wall', 335), ('eye', 333)], 'ADJ': [('old', 917), ('great', 797), ('strange', 488), ('certain', 446), ('black', 379), ('little', 336), ('ancient', 308), ('high', 297), ('small', 282), ('dark', 277), ('new', 268), ('human', 267), ('unknown', 259), ('terrible', 256), ('long', 244), ('curious', 227), ('low', 216), ('hideous', 213), ('young', 210), ('good', 204)], 'VERB': [('come', 1100), ('know', 1095), ('see', 1079), ('find', 784), ('tell', 649), ('think', 571), ('hear', 528), ('look', 474), ('go', 439), ('say', 425), ('leave', 401), ('begin', 400), ('feel', 397), ('take', 368), ('grow', 310), ('give', 306), ('shew', 275), ('bring', 267), ('speak', 266), ('try', 262)]}"
},
{
"code": null,
"e": 20289,
"s": 20077,
"text": "Once again, I think the verbs are the least exciting, although you can see how most of the verbs are about knowledge gathering or sharing. In case you are wondering, “shew” is the old-fashioned spelling of show."
},
{
"code": null,
"e": 20508,
"s": 20289,
"text": "Nouns are better, “time”, “night”, “stone”, “dream”, “horror” — I would guess the writer is Lovecraft based on just these five words. I mean, horror is there in the top 20 nouns ever used, that is certainly reassuring!"
},
{
"code": null,
"e": 20766,
"s": 20508,
"text": "And finally, the adjectives, at least 2/3rd of them would generally be weird to have so high on the list. The most often used adjective is “old”, I mean, how awesome is that? And the list goes on to “great”, “strange”, “ancient”, “unknown”, “terrible”, etc."
},
{
"code": null,
"e": 21134,
"s": 20766,
"text": "(You might notice that we have “hideous” 213 times, but on the Arkham Archivist page that I mentioned in the intro, there are 260 counts of the word. The difference is due to the fact that we separate word usage by part-of-speech. He used the word 213 times as an adjective, but that does not include “hideousness” which is a noun, or “hideously” which is an adverb.)"
},
{
"code": null,
"e": 21721,
"s": 21134,
"text": "I think there are many more interesting analysis you could do with these simple NLP tools. We limited our scope to nouns, adjectives, and verbs, it would be interesting to see adverbs or proper nouns too. Analysing the relative portion of let’s say verbs in different years would also be interesting. That way, we could see if the stories became more action-packed as time went by, or was it the other way around? There is also a very important concept we did not consider: the n-grams. A very similar analysis could be done to find the most frequently used expressions in his writings."
},
{
"code": null,
"e": 21990,
"s": 21721,
"text": "We started with a very simple question: I wonder what is Lovecraft's most frequently used word? And for such a simple question this turned out to be more complicated than I imagined. It was really cool to see such a simple NLP representation to work surprisingly well."
},
{
"code": null,
"e": 22148,
"s": 21990,
"text": "In the next post, I am going to write about how one can take word counts a step further and calculate the differences between documents using TF-IDF vectors."
},
{
"code": null,
"e": 22317,
"s": 22148,
"text": "Hobson, L. & Cole, H. & Hannes, H. (2019). Natural Language Processing in Action: Understanding, Analyzing, and Generating Text with Python. Manning Publications, 2019."
},
{
"code": null,
"e": 22326,
"s": 22317,
"text": "spacy.io"
}
] |
Find the single digit sum of alphabetical values of a string - GeeksforGeeks
|
11 Nov, 2021
Given string S of size N, the task is to find the single-digit sum by the repetitive sum of digits of the value obtained by the sum of order of all alphabets in the given string.
The order of alphabets is given by the position at which they occur in English Alaphabets.
Examples:
Input: S = “geek”Output: 1Explanation:The value obtained by the sum order of alphabets is 7 + 5 + 5 + 11 = 28.The single digit sum obtained by sum of 28 = 2 + 8 = 10 = 1 + 0 = 1.
Input: S = “GeeksforGeeks”Output: 7
Approach: The given problem can be solved by first find the sum of orders of all the alphabets present in the given string S by adding the value (S[i] – ‘a’ + 1) or (S[i] – ‘A’ + 1) if S[i] is lowercase or uppercase character. After finding the value of sum, find the single digit of this value using the approach discussed in this article.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; int findTheSum(string str){ string alpha; // Traverse the given string for (int i = 0; i < str.length(); i++) { // If character is an alphabet if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha.push_back(str[i]); } // Stores the sum of order of values int score = 0, n = 0; for (int i = 0; i < alpha.length(); i++) { // Find the score if (alpha[i] >= 'A' && alpha[i] <= 'Z') score += alpha[i] - 'A' + 1; else score += alpha[i] - 'a' + 1; } // Find the single digit sum while (score > 0 || n > 9) { if (score == 0) { score = n; n = 0; } n += score % 10; score /= 10; } // Return the resultant sum return n;} // Driver Codeint main(){ string S = "GeeksforGeeks"; cout << findTheSum(S); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ static int findTheSum(char []str){ String alpha=""; // Traverse the given String for (int i = 0; i < str.length; i++) { // If character is an alphabet if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha+=(str[i]); } // Stores the sum of order of values int score = 0, n = 0; for (int i = 0; i < alpha.length(); i++) { // Find the score if (alpha.charAt(i) >= 'A' && alpha.charAt(i) <= 'Z') score += alpha.charAt(i) - 'A' + 1; else score += alpha.charAt(i) - 'a' + 1; } // Find the single digit sum while (score > 0 || n > 9) { if (score == 0) { score = n; n = 0; } n += score % 10; score /= 10; } // Return the resultant sum return n;} // Driver Codepublic static void main(String[] args){ String S = "GeeksforGeeks"; System.out.print(findTheSum(S.toCharArray()));}} // This code is contributed by 29AjayKumar
# Python program for the above approachdef findTheSum(str): alpha = "" # Traverse the given string for i in range(0, len(str)): # If character is an alphabet if ((str[i] >= 'A' and str[i] <= 'Z') or (str[i] >= 'a' and str[i] <= 'z')): alpha += str[i] # Stores the sum of order of values score = 0 n = 0 for i in range(0, len(alpha)): # Find the score if (alpha[i] >= 'A' and alpha[i] <= 'Z'): score += ord(alpha[i]) - ord('A') + 1 else: score += ord(alpha[i]) - ord('a') + 1 # Find the single digit sum while (score > 0 or n > 9): if (score == 0): score = n n = 0 n += score % 10 score = score // 10 # Return the resultant sum return n # Driver Codeif __name__ == "__main__": S = "GeeksforGeeks" print(findTheSum(S)) # This code is contributed by rakeshsahni
// C# program for the above approachusing System;class GFG { static int findTheSum(string str) { string alpha = ""; // Traverse the given string for (int i = 0; i < str.Length; i++) { // If character is an alphabet if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha += (str[i]); } // Stores the sum of order of values int score = 0, n = 0; for (int i = 0; i < alpha.Length; i++) { // Find the score if (alpha[i] >= 'A' && alpha[i] <= 'Z') score += alpha[i] - 'A' + 1; else score += alpha[i] - 'a' + 1; } // Find the single digit sum while (score > 0 || n > 9) { if (score == 0) { score = n; n = 0; } n += score % 10; score /= 10; } // Return the resultant sum return n; } // Driver Code public static void Main() { string S = "GeeksforGeeks"; Console.WriteLine(findTheSum(S)); }} // This code is contributed by ukasp.
<script>// Javascript program for the above approach function findTheSum(str) { let alpha = []; // Traverse the given string for (let i = 0; i < str.length; i++) { // If character is an alphabet if ( (str[i].charCodeAt(0) >= "A".charCodeAt(0) && str[i].charCodeAt(0) <= "Z".charCodeAt(0)) || (str[i].charCodeAt(0) >= "a".charCodeAt(0) && str[i].charCodeAt(0) <= "z".charCodeAt(0)) ) alpha.push(str[i]); } // Stores the sum of order of values let score = 0, n = 0; for (let i = 0; i < alpha.length; i++) { // Find the score if ( alpha[i].charCodeAt(0) >= "A".charCodeAt(0) && alpha[i].charCodeAt(0) <= "Z".charCodeAt(0) ) score += alpha[i].charCodeAt(0) - "A".charCodeAt(0) + 1; else score += alpha[i].charCodeAt(0) - "a".charCodeAt(0) + 1; } // Find the single digit sum while (score > 0 || n > 9) { if (score == 0) { score = n; n = 0; } n += score % 10; score = Math.floor(score / 10); } // Return the resultant sum return n;} // Driver Code let S = "GeeksforGeeks";document.write(findTheSum(S)); // This code is contributed by saurabh_jaiswal.</script>
7
Time Complexity: O(N)Auxiliary Space: O(1)
rakeshsahni
_saurabh_jaiswal
ukasp
29AjayKumar
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 24480,
"s": 24301,
"text": "Given string S of size N, the task is to find the single-digit sum by the repetitive sum of digits of the value obtained by the sum of order of all alphabets in the given string."
},
{
"code": null,
"e": 24571,
"s": 24480,
"text": "The order of alphabets is given by the position at which they occur in English Alaphabets."
},
{
"code": null,
"e": 24581,
"s": 24571,
"text": "Examples:"
},
{
"code": null,
"e": 24760,
"s": 24581,
"text": "Input: S = “geek”Output: 1Explanation:The value obtained by the sum order of alphabets is 7 + 5 + 5 + 11 = 28.The single digit sum obtained by sum of 28 = 2 + 8 = 10 = 1 + 0 = 1."
},
{
"code": null,
"e": 24796,
"s": 24760,
"text": "Input: S = “GeeksforGeeks”Output: 7"
},
{
"code": null,
"e": 25137,
"s": 24796,
"text": "Approach: The given problem can be solved by first find the sum of orders of all the alphabets present in the given string S by adding the value (S[i] – ‘a’ + 1) or (S[i] – ‘A’ + 1) if S[i] is lowercase or uppercase character. After finding the value of sum, find the single digit of this value using the approach discussed in this article."
},
{
"code": null,
"e": 25188,
"s": 25137,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25192,
"s": 25188,
"text": "C++"
},
{
"code": null,
"e": 25197,
"s": 25192,
"text": "Java"
},
{
"code": null,
"e": 25205,
"s": 25197,
"text": "Python3"
},
{
"code": null,
"e": 25208,
"s": 25205,
"text": "C#"
},
{
"code": null,
"e": 25219,
"s": 25208,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; int findTheSum(string str){ string alpha; // Traverse the given string for (int i = 0; i < str.length(); i++) { // If character is an alphabet if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha.push_back(str[i]); } // Stores the sum of order of values int score = 0, n = 0; for (int i = 0; i < alpha.length(); i++) { // Find the score if (alpha[i] >= 'A' && alpha[i] <= 'Z') score += alpha[i] - 'A' + 1; else score += alpha[i] - 'a' + 1; } // Find the single digit sum while (score > 0 || n > 9) { if (score == 0) { score = n; n = 0; } n += score % 10; score /= 10; } // Return the resultant sum return n;} // Driver Codeint main(){ string S = \"GeeksforGeeks\"; cout << findTheSum(S); return 0;}",
"e": 26211,
"s": 25219,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ static int findTheSum(char []str){ String alpha=\"\"; // Traverse the given String for (int i = 0; i < str.length; i++) { // If character is an alphabet if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha+=(str[i]); } // Stores the sum of order of values int score = 0, n = 0; for (int i = 0; i < alpha.length(); i++) { // Find the score if (alpha.charAt(i) >= 'A' && alpha.charAt(i) <= 'Z') score += alpha.charAt(i) - 'A' + 1; else score += alpha.charAt(i) - 'a' + 1; } // Find the single digit sum while (score > 0 || n > 9) { if (score == 0) { score = n; n = 0; } n += score % 10; score /= 10; } // Return the resultant sum return n;} // Driver Codepublic static void main(String[] args){ String S = \"GeeksforGeeks\"; System.out.print(findTheSum(S.toCharArray()));}} // This code is contributed by 29AjayKumar",
"e": 27298,
"s": 26211,
"text": null
},
{
"code": "# Python program for the above approachdef findTheSum(str): alpha = \"\" # Traverse the given string for i in range(0, len(str)): # If character is an alphabet if ((str[i] >= 'A' and str[i] <= 'Z') or (str[i] >= 'a' and str[i] <= 'z')): alpha += str[i] # Stores the sum of order of values score = 0 n = 0 for i in range(0, len(alpha)): # Find the score if (alpha[i] >= 'A' and alpha[i] <= 'Z'): score += ord(alpha[i]) - ord('A') + 1 else: score += ord(alpha[i]) - ord('a') + 1 # Find the single digit sum while (score > 0 or n > 9): if (score == 0): score = n n = 0 n += score % 10 score = score // 10 # Return the resultant sum return n # Driver Codeif __name__ == \"__main__\": S = \"GeeksforGeeks\" print(findTheSum(S)) # This code is contributed by rakeshsahni",
"e": 28250,
"s": 27298,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG { static int findTheSum(string str) { string alpha = \"\"; // Traverse the given string for (int i = 0; i < str.Length; i++) { // If character is an alphabet if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha += (str[i]); } // Stores the sum of order of values int score = 0, n = 0; for (int i = 0; i < alpha.Length; i++) { // Find the score if (alpha[i] >= 'A' && alpha[i] <= 'Z') score += alpha[i] - 'A' + 1; else score += alpha[i] - 'a' + 1; } // Find the single digit sum while (score > 0 || n > 9) { if (score == 0) { score = n; n = 0; } n += score % 10; score /= 10; } // Return the resultant sum return n; } // Driver Code public static void Main() { string S = \"GeeksforGeeks\"; Console.WriteLine(findTheSum(S)); }} // This code is contributed by ukasp.",
"e": 29420,
"s": 28250,
"text": null
},
{
"code": "<script>// Javascript program for the above approach function findTheSum(str) { let alpha = []; // Traverse the given string for (let i = 0; i < str.length; i++) { // If character is an alphabet if ( (str[i].charCodeAt(0) >= \"A\".charCodeAt(0) && str[i].charCodeAt(0) <= \"Z\".charCodeAt(0)) || (str[i].charCodeAt(0) >= \"a\".charCodeAt(0) && str[i].charCodeAt(0) <= \"z\".charCodeAt(0)) ) alpha.push(str[i]); } // Stores the sum of order of values let score = 0, n = 0; for (let i = 0; i < alpha.length; i++) { // Find the score if ( alpha[i].charCodeAt(0) >= \"A\".charCodeAt(0) && alpha[i].charCodeAt(0) <= \"Z\".charCodeAt(0) ) score += alpha[i].charCodeAt(0) - \"A\".charCodeAt(0) + 1; else score += alpha[i].charCodeAt(0) - \"a\".charCodeAt(0) + 1; } // Find the single digit sum while (score > 0 || n > 9) { if (score == 0) { score = n; n = 0; } n += score % 10; score = Math.floor(score / 10); } // Return the resultant sum return n;} // Driver Code let S = \"GeeksforGeeks\";document.write(findTheSum(S)); // This code is contributed by saurabh_jaiswal.</script>",
"e": 30583,
"s": 29420,
"text": null
},
{
"code": null,
"e": 30585,
"s": 30583,
"text": "7"
},
{
"code": null,
"e": 30630,
"s": 30587,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30642,
"s": 30630,
"text": "rakeshsahni"
},
{
"code": null,
"e": 30659,
"s": 30642,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 30665,
"s": 30659,
"text": "ukasp"
},
{
"code": null,
"e": 30677,
"s": 30665,
"text": "29AjayKumar"
},
{
"code": null,
"e": 30690,
"s": 30677,
"text": "Mathematical"
},
{
"code": null,
"e": 30698,
"s": 30690,
"text": "Strings"
},
{
"code": null,
"e": 30706,
"s": 30698,
"text": "Strings"
},
{
"code": null,
"e": 30719,
"s": 30706,
"text": "Mathematical"
},
{
"code": null,
"e": 30817,
"s": 30719,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30826,
"s": 30817,
"text": "Comments"
},
{
"code": null,
"e": 30839,
"s": 30826,
"text": "Old Comments"
},
{
"code": null,
"e": 30884,
"s": 30839,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 30916,
"s": 30884,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 30960,
"s": 30916,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 30985,
"s": 30960,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 31018,
"s": 30985,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 31043,
"s": 31018,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31089,
"s": 31043,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 31123,
"s": 31089,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 31180,
"s": 31123,
"text": "Python program to check if a string is palindrome or not"
}
] |
Using findOneAndUpdate () to update in MongoDB?
|
The findOneAndUpdate() is used to update a single document based on the filter and sort criteria i.e. −
db.collection.findOneAndUpdate(filter, update, options)
Let us create a collection with documents −
> db.demo328.insertOne({Name:"Chris",Marks:67});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e516b19f8647eb59e56207a")
}
> db.demo328.insertOne({Name:"David",Marks:78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e516b24f8647eb59e56207b")
}
> db.demo328.insertOne({Name:"Bob",Marks:97});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e516b2bf8647eb59e56207c")
}
Display all documents from a collection with the help of find() method −
> db.demo328.find();
This will produce the following output −
{ "_id" : ObjectId("5e516b19f8647eb59e56207a"), "Name" : "Chris", "Marks" : 67 }
{ "_id" : ObjectId("5e516b24f8647eb59e56207b"), "Name" : "David", "Marks" : 78 }
{ "_id" : ObjectId("5e516b2bf8647eb59e56207c"), "Name" : "Bob", "Marks" : 97 }
Following is the query to update with findOneAndUpdate(). Here, we are incrementing a specific document’s field Marks −
> db.demo328.findOneAndUpdate({Name:"David"},{ $inc: { "Marks" : 10} });
{
"_id" : ObjectId("5e516b24f8647eb59e56207b"),
"Name" : "David",
"Marks" : 78
}
Display all documents from a collection with the help of find() method −
> db.demo328.find();
This will produce the following output −
{ "_id" : ObjectId("5e516b19f8647eb59e56207a"), "Name" : "Chris", "Marks" : 67 }
{ "_id" : ObjectId("5e516b24f8647eb59e56207b"), "Name" : "David", "Marks" : 88 }
{ "_id" : ObjectId("5e516b2bf8647eb59e56207c"), "Name" : "Bob", "Marks" : 97 }
|
[
{
"code": null,
"e": 1166,
"s": 1062,
"text": "The findOneAndUpdate() is used to update a single document based on the filter and sort criteria i.e. −"
},
{
"code": null,
"e": 1222,
"s": 1166,
"text": "db.collection.findOneAndUpdate(filter, update, options)"
},
{
"code": null,
"e": 1266,
"s": 1222,
"text": "Let us create a collection with documents −"
},
{
"code": null,
"e": 1666,
"s": 1266,
"text": "> db.demo328.insertOne({Name:\"Chris\",Marks:67});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e516b19f8647eb59e56207a\")\n}\n> db.demo328.insertOne({Name:\"David\",Marks:78});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e516b24f8647eb59e56207b\")\n}\n> db.demo328.insertOne({Name:\"Bob\",Marks:97});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e516b2bf8647eb59e56207c\")\n}"
},
{
"code": null,
"e": 1739,
"s": 1666,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1760,
"s": 1739,
"text": "> db.demo328.find();"
},
{
"code": null,
"e": 1801,
"s": 1760,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2042,
"s": 1801,
"text": "{ \"_id\" : ObjectId(\"5e516b19f8647eb59e56207a\"), \"Name\" : \"Chris\", \"Marks\" : 67 }\n{ \"_id\" : ObjectId(\"5e516b24f8647eb59e56207b\"), \"Name\" : \"David\", \"Marks\" : 78 }\n{ \"_id\" : ObjectId(\"5e516b2bf8647eb59e56207c\"), \"Name\" : \"Bob\", \"Marks\" : 97 }"
},
{
"code": null,
"e": 2162,
"s": 2042,
"text": "Following is the query to update with findOneAndUpdate(). Here, we are incrementing a specific document’s field Marks −"
},
{
"code": null,
"e": 2325,
"s": 2162,
"text": "> db.demo328.findOneAndUpdate({Name:\"David\"},{ $inc: { \"Marks\" : 10} });\n{\n \"_id\" : ObjectId(\"5e516b24f8647eb59e56207b\"),\n \"Name\" : \"David\",\n \"Marks\" : 78\n}"
},
{
"code": null,
"e": 2398,
"s": 2325,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2419,
"s": 2398,
"text": "> db.demo328.find();"
},
{
"code": null,
"e": 2460,
"s": 2419,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2701,
"s": 2460,
"text": "{ \"_id\" : ObjectId(\"5e516b19f8647eb59e56207a\"), \"Name\" : \"Chris\", \"Marks\" : 67 }\n{ \"_id\" : ObjectId(\"5e516b24f8647eb59e56207b\"), \"Name\" : \"David\", \"Marks\" : 88 }\n{ \"_id\" : ObjectId(\"5e516b2bf8647eb59e56207c\"), \"Name\" : \"Bob\", \"Marks\" : 97 }"
}
] |
OpenShift - Docker and Kubernetes
|
OpenShift is built on top of Docker and Kubernetes. All the containers are built on top of Docker cluster, which is basically Kubernetes service on top of Linux machines, using Kubernetes orchestrations feature.
In this process, we build Kubernetes master which controls all the nodes and deploys the containers to all the nodes. The main function of Kubernetes is to control OpenShift cluster and deployment flow using a different kind of configuration file. As in Kubernetes, we use kubctl in the same way we use OC command line utility to build and deploy containers on cluster nodes.
Following are the different kinds of config files used for creation of different kind of objects in the cluster.
Images
POD
Service
Replication Controller
Replica set
Deployment
Kubernetes (Docker) images are the key building blocks of Containerized Infrastructure. As of now, Kubernetes only support Docker images. Each container in a pod has its Docker image running inside it.
apiVersion: v1
kind: pod
metadata:
name: Tesing_for_Image_pull -----------> 1
spec:
containers:
- name: neo4j-server ------------------------> 2
image: <Name of the Docker image>----------> 3
imagePullPolicy: Always ------------->4
command: [“echo”, “SUCCESS”] -------------------> 5
A pod is collection of containers and its storage inside a node of a Kubernetes cluster. It is possible to create a pod with multiple containers inside it. Following is an example of keeping a database container and web interface container in the same pod.
apiVersion: v1
kind: Pod
metadata:
name: Tomcat
spec:
containers:
- name: Tomcat
image: tomcat: 8.0
ports:
- containerPort: 7500
imagePullPolicy: Always
A service can be defined as a logical set of pods. It can be defined as an abstraction on top of the pod that provides a single IP address and DNS name by which pods can be accessed. With Service, it is very easy to manage load balancing configuration. It helps PODs to scale very easily.
apiVersion: v1
kind: Service
metadata:
name: Tutorial_point_service
spec:
ports:
- port: 8080
targetPort: 31999
Replication Controller is one of the key features of Kubernetes, which is responsible for managing the pod lifecycle. It is responsible for making sure that specified numbers of pod replicas are running at any point of time.
apiVersion: v1
kind: ReplicationController
metadata:
name: Tomcat-ReplicationController
spec:
replicas: 3
template:
metadata:
name: Tomcat-ReplicationController
labels:
app: App
component: neo4j
spec:
containers:
- name: Tomcat
image: tomcat: 8.0
ports:
- containerPort: 7474
The replica set ensures how many replica of pod should be running. It can be considered as a replacement of the replication controller.
apiVersion: extensions/v1beta1
kind: ReplicaSet
metadata:
name: Tomcat-ReplicaSet
spec:
replicas: 3
selector:
matchLables:
tier: Backend
matchExpression:
- { key: tier, operation: In, values: [Backend]}
app: App
component: neo4j
spec:
containers:
- name: Tomcat-
image: tomcat: 8.0
ports:
containerPort: 7474
Deployments are upgraded and higher versions of the replication controller. They manage the deployment of replica sets, which is also an upgraded version of the replication controller. They have the capability to update the replica set and they are also capable of rolling back to the previous version.
apiVersion: extensions/v1beta1 --------------------->1
kind: Deployment --------------------------> 2
metadata:
name: Tomcat-ReplicaSet
spec:
replicas: 3
template:
metadata:
lables:
app: Tomcat-ReplicaSet
tier: Backend
spec:
containers:
name: Tomcat-
image: tomcat: 8.0
ports:
- containerPort: 7474
All config files can be used to create their respective Kubernetes objects.
$ Kubectl create –f <file name>.yaml
Following commands can be used to know the details and description of the Kubernetes objects.
For POD
$ Kubectl get pod <pod name>
$ kubectl delete pod <pod name>
$ kubectl describe pod <pod name>
For Replication Controller
$ Kubectl get rc <rc name>
$ kubectl delete rc <rc name>
$ kubectl describe rc <rc name>
For Service
$ Kubectl get svc <svc name>
$ kubectl delete svc <svc name>
$ kubectl describe svc <svc name>
For more details on how to work with Docker and Kubernetes, please visit our Kubernetes tutorial using the following link kubernetes.
70 Lectures
4 hours
Cloud Passion
19 Lectures
1 hours
Pranjal Srivastava
26 Lectures
1.5 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2160,
"s": 1948,
"text": "OpenShift is built on top of Docker and Kubernetes. All the containers are built on top of Docker cluster, which is basically Kubernetes service on top of Linux machines, using Kubernetes orchestrations feature."
},
{
"code": null,
"e": 2536,
"s": 2160,
"text": "In this process, we build Kubernetes master which controls all the nodes and deploys the containers to all the nodes. The main function of Kubernetes is to control OpenShift cluster and deployment flow using a different kind of configuration file. As in Kubernetes, we use kubctl in the same way we use OC command line utility to build and deploy containers on cluster nodes."
},
{
"code": null,
"e": 2649,
"s": 2536,
"text": "Following are the different kinds of config files used for creation of different kind of objects in the cluster."
},
{
"code": null,
"e": 2656,
"s": 2649,
"text": "Images"
},
{
"code": null,
"e": 2660,
"s": 2656,
"text": "POD"
},
{
"code": null,
"e": 2668,
"s": 2660,
"text": "Service"
},
{
"code": null,
"e": 2691,
"s": 2668,
"text": "Replication Controller"
},
{
"code": null,
"e": 2703,
"s": 2691,
"text": "Replica set"
},
{
"code": null,
"e": 2714,
"s": 2703,
"text": "Deployment"
},
{
"code": null,
"e": 2916,
"s": 2714,
"text": "Kubernetes (Docker) images are the key building blocks of Containerized Infrastructure. As of now, Kubernetes only support Docker images. Each container in a pod has its Docker image running inside it."
},
{
"code": null,
"e": 3210,
"s": 2916,
"text": "apiVersion: v1\nkind: pod\nmetadata:\n name: Tesing_for_Image_pull -----------> 1\n spec:\n containers:\n- name: neo4j-server ------------------------> 2\nimage: <Name of the Docker image>----------> 3\nimagePullPolicy: Always ------------->4\ncommand: [“echo”, “SUCCESS”] -------------------> 5\n"
},
{
"code": null,
"e": 3467,
"s": 3210,
"text": "A pod is collection of containers and its storage inside a node of a Kubernetes cluster. It is possible to create a pod with multiple containers inside it. Following is an example of keeping a database container and web interface container in the same pod."
},
{
"code": null,
"e": 3642,
"s": 3467,
"text": "apiVersion: v1\nkind: Pod\nmetadata:\n name: Tomcat\nspec:\n containers:\n - name: Tomcat\n image: tomcat: 8.0\n ports:\n- containerPort: 7500\nimagePullPolicy: Always\n"
},
{
"code": null,
"e": 3931,
"s": 3642,
"text": "A service can be defined as a logical set of pods. It can be defined as an abstraction on top of the pod that provides a single IP address and DNS name by which pods can be accessed. With Service, it is very easy to manage load balancing configuration. It helps PODs to scale very easily."
},
{
"code": null,
"e": 4059,
"s": 3931,
"text": "apiVersion: v1\nkind: Service\nmetadata:\n name: Tutorial_point_service\nspec:\n ports:\n - port: 8080\n targetPort: 31999\n"
},
{
"code": null,
"e": 4284,
"s": 4059,
"text": "Replication Controller is one of the key features of Kubernetes, which is responsible for managing the pod lifecycle. It is responsible for making sure that specified numbers of pod replicas are running at any point of time."
},
{
"code": null,
"e": 4627,
"s": 4284,
"text": "apiVersion: v1\nkind: ReplicationController\nmetadata:\n name: Tomcat-ReplicationController\nspec:\n replicas: 3\n template:\n metadata:\n name: Tomcat-ReplicationController\n labels:\n app: App\n component: neo4j\n spec:\n containers:\n - name: Tomcat\n image: tomcat: 8.0\n ports:\n - containerPort: 7474\n"
},
{
"code": null,
"e": 4763,
"s": 4627,
"text": "The replica set ensures how many replica of pod should be running. It can be considered as a replacement of the replication controller."
},
{
"code": null,
"e": 5122,
"s": 4763,
"text": "apiVersion: extensions/v1beta1\nkind: ReplicaSet\nmetadata:\n name: Tomcat-ReplicaSet\nspec:\n replicas: 3\n selector:\n matchLables:\n tier: Backend\n matchExpression:\n - { key: tier, operation: In, values: [Backend]}\n \n app: App\n component: neo4j\nspec:\n containers:\n - name: Tomcat-\nimage: tomcat: 8.0\n ports:\ncontainerPort: 7474\n"
},
{
"code": null,
"e": 5425,
"s": 5122,
"text": "Deployments are upgraded and higher versions of the replication controller. They manage the deployment of replica sets, which is also an upgraded version of the replication controller. They have the capability to update the replica set and they are also capable of rolling back to the previous version."
},
{
"code": null,
"e": 5758,
"s": 5425,
"text": "apiVersion: extensions/v1beta1 --------------------->1\nkind: Deployment --------------------------> 2\nmetadata:\n name: Tomcat-ReplicaSet\nspec:\n replicas: 3\n template:\n metadata:\nlables:\n app: Tomcat-ReplicaSet\n tier: Backend\nspec:\n containers:\nname: Tomcat-\n image: tomcat: 8.0\n ports:\n - containerPort: 7474\n"
},
{
"code": null,
"e": 5834,
"s": 5758,
"text": "All config files can be used to create their respective Kubernetes objects."
},
{
"code": null,
"e": 5872,
"s": 5834,
"text": "$ Kubectl create –f <file name>.yaml\n"
},
{
"code": null,
"e": 5966,
"s": 5872,
"text": "Following commands can be used to know the details and description of the Kubernetes objects."
},
{
"code": null,
"e": 5974,
"s": 5966,
"text": "For POD"
},
{
"code": null,
"e": 6070,
"s": 5974,
"text": "$ Kubectl get pod <pod name>\n$ kubectl delete pod <pod name>\n$ kubectl describe pod <pod name>\n"
},
{
"code": null,
"e": 6097,
"s": 6070,
"text": "For Replication Controller"
},
{
"code": null,
"e": 6187,
"s": 6097,
"text": "$ Kubectl get rc <rc name>\n$ kubectl delete rc <rc name>\n$ kubectl describe rc <rc name>\n"
},
{
"code": null,
"e": 6199,
"s": 6187,
"text": "For Service"
},
{
"code": null,
"e": 6295,
"s": 6199,
"text": "$ Kubectl get svc <svc name>\n$ kubectl delete svc <svc name>\n$ kubectl describe svc <svc name>\n"
},
{
"code": null,
"e": 6429,
"s": 6295,
"text": "For more details on how to work with Docker and Kubernetes, please visit our Kubernetes tutorial using the following link kubernetes."
},
{
"code": null,
"e": 6462,
"s": 6429,
"text": "\n 70 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6477,
"s": 6462,
"text": " Cloud Passion"
},
{
"code": null,
"e": 6510,
"s": 6477,
"text": "\n 19 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6530,
"s": 6510,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6565,
"s": 6530,
"text": "\n 26 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6585,
"s": 6565,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 6592,
"s": 6585,
"text": " Print"
},
{
"code": null,
"e": 6603,
"s": 6592,
"text": " Add Notes"
}
] |
Flutter - Introduction to Layouts
|
Since the core concept of Flutter is Everything is widget, Flutter incorporates a user interface layout functionality into the widgets itself. Flutter provides quite a lot of specially designed widgets like Container, Center, Align, etc., only for the purpose of laying out the user interface. Widgets build by composing other widgets normally use layout widgets. Let use learn the Flutter layout concept in this chapter.
Layout widgets can be grouped into two distinct category based on its child −
Widget supporting a single child
Widget supporting multiple child
Let us learn both type of widgets and its functionality in the upcoming sections.
In this category, widgets will have only one widget as its child and every widget will have a special layout functionality.
For example, Center widget just centers it child widget with respect to its parent widget and Container widget provides complete flexibility to place it child at any given place inside it using different option like padding, decoration, etc.,
Single child widgets are great options to create high quality widget having single functionality such as button, label, etc.,
The code to create a simple button using Container widget is as follows −
class MyButton extends StatelessWidget {
MyButton({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
border: Border(
top: BorderSide(width: 1.0, color: Color(0xFFFFFFFFFF)),
left: BorderSide(width: 1.0, color: Color(0xFFFFFFFFFF)),
right: BorderSide(width: 1.0, color: Color(0xFFFF000000)),
bottom: BorderSide(width: 1.0, color: Color(0xFFFF000000)),
),
),
child: Container(
padding: const
EdgeInsets.symmetric(horizontal: 20.0, vertical: 2.0),
decoration: const BoxDecoration(
border: Border(
top: BorderSide(width: 1.0, color: Color(0xFFFFDFDFDF)),
left: BorderSide(width: 1.0, color: Color(0xFFFFDFDFDF)),
right: BorderSide(width: 1.0, color: Color(0xFFFF7F7F7F)),
bottom: BorderSide(width: 1.0, color: Color(0xFFFF7F7F7F)),
),
color: Colors.grey,
),
child: const Text(
'OK',textAlign: TextAlign.center, style: TextStyle(color: Colors.black)
),
),
);
}
}
Here, we have used two widgets – a Container widget and a Text widget. The result of the widget is as a custom button as shown below −
Let us check some of the most important single child layout widgets provided by Flutter −
Padding − Used to arrange its child widget by the given padding. Here, padding can be provided by EdgeInsets class.
Padding − Used to arrange its child widget by the given padding. Here, padding can be provided by EdgeInsets class.
Align − Align its child widget within itself using the value of alignment property. The value for alignment property can be provided by FractionalOffset class. The FractionalOffset class specifies the offsets in terms of a distance from the top left.
Align − Align its child widget within itself using the value of alignment property. The value for alignment property can be provided by FractionalOffset class. The FractionalOffset class specifies the offsets in terms of a distance from the top left.
Some of the possible values of offsets are as follows −
FractionalOffset(1.0, 0.0) represents the top right.
FractionalOffset(1.0, 0.0) represents the top right.
FractionalOffset(0.0, 1.0) represents the bottom left.
FractionalOffset(0.0, 1.0) represents the bottom left.
A sample code about offsets is shown below −
Center(
child: Container(
height: 100.0,
width: 100.0,
color: Colors.yellow, child: Align(
alignment: FractionalOffset(0.2, 0.6),
child: Container( height: 40.0, width:
40.0, color: Colors.red,
),
),
),
)
FittedBox − It scales the child widget and then positions it according to the specified fit.
FittedBox − It scales the child widget and then positions it according to the specified fit.
AspectRatio − It attempts to size the child widget to the specified aspect ratio
AspectRatio − It attempts to size the child widget to the specified aspect ratio
ConstrainedBox
ConstrainedBox
Baseline
Baseline
FractinallySizedBox
FractinallySizedBox
IntrinsicHeight
IntrinsicHeight
IntrinsicWidth
IntrinsicWidth
LiimitedBox
LiimitedBox
OffStage
OffStage
OverflowBox
OverflowBox
SizedBox
SizedBox
SizedOverflowBox
SizedOverflowBox
Transform
Transform
CustomSingleChildLayout
CustomSingleChildLayout
Our hello world application is using material based layout widgets to design the home page. Let us modify our hello world application to build the home page using basic layout widgets as specified below −
Container − Generic, single child, box based container widget with alignment, padding, border and margin along with rich styling features.
Container − Generic, single child, box based container widget with alignment, padding, border and margin along with rich styling features.
Center − Simple, Single child container widget, which centers its child widget.
Center − Simple, Single child container widget, which centers its child widget.
The modified code of the MyHomePage and MyApp widget is as below −
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MyHomePage(title: "Hello World demo app");
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(color: Colors.white,),
padding: EdgeInsets.all(25), child: Center(
child:Text(
'Hello World', style: TextStyle(
color: Colors.black, letterSpacing: 0.5, fontSize: 20,
),
textDirection: TextDirection.ltr,
),
)
);
}
}
Here,
Container widget is the top level or root widget. Container is configured using decoration and padding property to layout its content.
Container widget is the top level or root widget. Container is configured using decoration and padding property to layout its content.
BoxDecoration has many properties like color, border, etc., to decorate the Container widget and here, color is used to set the color of the container.
BoxDecoration has many properties like color, border, etc., to decorate the Container widget and here, color is used to set the color of the container.
padding of the Container widget is set by using dgeInsets class, which provides the option to specify the padding value.
padding of the Container widget is set by using dgeInsets class, which provides the option to specify the padding value.
Center is the child widget of the Container widget. Again, Text is the child of the Center widget. Text is used to show message and Center is used to center the text message with respect to the parent widget, Container.
Center is the child widget of the Container widget. Again, Text is the child of the Center widget. Text is used to show message and Center is used to center the text message with respect to the parent widget, Container.
The final result of the code given above is a layout sample as shown below −
In this category, a given widget will have more than one child widgets and the layout of each widget is unique.
For example, Row widget allows the laying out of its children in horizontal direction, whereas Column widget allows laying out of its children in vertical direction. By composing Row and Column, widget with any level of complexity can be built.
Let us learn some of the frequently used widgets in this section.
Row − Allows to arrange its children in a horizontal manner.
Row − Allows to arrange its children in a horizontal manner.
Column − Allows to arrange its children in a vertical manner.
Column − Allows to arrange its children in a vertical manner.
ListView − Allows to arrange its children as list.
ListView − Allows to arrange its children as list.
GridView − Allows to arrange its children as gallery.
GridView − Allows to arrange its children as gallery.
Expanded − Used to make the children of Row and Column widget to occupy the maximum possible area.
Expanded − Used to make the children of Row and Column widget to occupy the maximum possible area.
Table − Table based widget.
Table − Table based widget.
Flow − Flow based widget.
Flow − Flow based widget.
Stack − Stack based widget.
Stack − Stack based widget.
In this section, let us learn how to create a complex user interface of product listing with custom design using both single and multiple child layout widgets.
For this purpose, follow the sequence given below −
Create a new Flutter application in Android studio, product_layout_app.
Create a new Flutter application in Android studio, product_layout_app.
Replace the main.dart code with folowing code −
Replace the main.dart code with folowing code −
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo', theme: ThemeData(
primarySwatch: Colors.blue,),
home: MyHomePage(title: 'Product layout demo home page'),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(this.title),),
body: Center(child: Text( 'Hello World', )),
);
}
}
Here,
Here,
We have created MyHomePage widget by extending StatelessWidget instead of default StatefulWidget and then removed the relevant code.
We have created MyHomePage widget by extending StatelessWidget instead of default StatefulWidget and then removed the relevant code.
Now, create a new widget, ProductBox according to the specified design as shown below −
Now, create a new widget, ProductBox according to the specified design as shown below −
The code for the ProductBox is as follows.
The code for the ProductBox is as follows.
class ProductBox extends StatelessWidget {
ProductBox({Key key, this.name, this.description, this.price, this.image})
: super(key: key);
final String name;
final String description;
final int price;
final String image;
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(2), height: 120, child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[
Image.asset("assets/appimages/" +image), Expanded(
child: Container(
padding: EdgeInsets.all(5), child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.name, style: TextStyle(fontWeight:
FontWeight.bold)), Text(this.description),
Text("Price: " + this.price.toString()),
],
)
)
)
]
)
)
);
}
}
Please observe the following in the code −
Please observe the following in the code −
ProductBox has used four arguments as specified below −
ProductBox has used four arguments as specified below −
name - Product name
name - Product name
description - Product description
description - Product description
price - Price of the product
price - Price of the product
image - Image of the product
image - Image of the product
ProductBox uses seven build-in widgets as specified below −
ProductBox uses seven build-in widgets as specified below −
Container
Expanded
Row
Column
Card
Text
Image
ProductBox is designed using the above mentioned widget. The arrangement or hierarchy of the widget is specified in the diagram shown below −
ProductBox is designed using the above mentioned widget. The arrangement or hierarchy of the widget is specified in the diagram shown below −
Now, place some dummy image (see below) for product information in the assets folder of the application and configure the assets folder in the pubspec.yaml file as shown below −
Now, place some dummy image (see below) for product information in the assets folder of the application and configure the assets folder in the pubspec.yaml file as shown below −
assets:
- assets/appimages/floppy.png
- assets/appimages/iphone.png
- assets/appimages/laptop.png
- assets/appimages/pendrive.png
- assets/appimages/pixel.png
- assets/appimages/tablet.png
iPhone.png
Pixel.png
Laptop.png
Tablet.png
Pendrive.png
Floppy.png
Finally, Use the ProductBox widget in the MyHomePage widget as specified below −
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:Text("Product Listing")),
body: ListView(
shrinkWrap: true, padding: const EdgeInsets.fromLTRB(2.0, 10.0, 2.0, 10.0),
children: <Widget> [
ProductBox(
name: "iPhone",
description: "iPhone is the stylist phone ever",
price: 1000,
image: "iphone.png"
),
ProductBox(
name: "Pixel",
description: "Pixel is the most featureful phone ever",
price: 800,
image: "pixel.png"
),
ProductBox(
name: "Laptop",
description: "Laptop is most productive development tool",
price: 2000,
image: "laptop.png"
),
ProductBox(
name: "Tablet",
description: "Tablet is the most useful device ever for meeting",
price: 1500,
image: "tablet.png"
),
ProductBox(
name: "Pendrive",
description: "Pendrive is useful storage medium",
price: 100,
image: "pendrive.png"
),
ProductBox(
name: "Floppy Drive",
description: "Floppy drive is useful rescue storage medium",
price: 20,
image: "floppy.png"
),
],
)
);
}
}
Here,we have used ProductBox as children of ListView widget.
Here,we have used ProductBox as children of ListView widget.
The complete code (main.dart) of the product layout application (product_layout_app) is as follows −
The complete code (main.dart) of the product layout application (product_layout_app) is as follows −
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo', theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Product layout demo home page'),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product Listing")),
body: ListView(
shrinkWrap: true,
padding: const EdgeInsets.fromLTRB(2.0, 10.0, 2.0, 10.0),
children: <Widget>[
ProductBox(
name: "iPhone",
description: "iPhone is the stylist phone ever",
price: 1000,
image: "iphone.png"
),
ProductBox(
name: "Pixel",
description: "Pixel is the most featureful phone ever",
price: 800,
image: "pixel.png"
),
ProductBox(
name: "Laptop",
description: "Laptop is most productive development tool",
price: 2000,
image: "laptop.png"
),
ProductBox(
name: "Tablet",
description: "Tablet is the most useful device ever for meeting",
price: 1500,
image: "tablet.png"
),
ProductBox(
name: "Pendrive",
description: "Pendrive is useful storage medium",
price: 100,
image: "pendrive.png"
),
ProductBox(
name: "Floppy Drive",
description: "Floppy drive is useful rescue storage medium",
price: 20,
image: "floppy.png"
),
],
)
);
}
}
class ProductBox extends StatelessWidget {
ProductBox({Key key, this.name, this.description, this.price, this.image}) :
super(key: key);
final String name;
final String description;
final int price;
final String image;
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(2),
height: 120,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Image.asset("assets/appimages/" + image),
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(
this.name, style: TextStyle(
fontWeight: FontWeight.bold
)
),
Text(this.description), Text(
"Price: " + this.price.toString()
),
],
)
)
)
]
)
)
);
}
}
The final output of the application is as follows −
34 Lectures
4 hours
Sriyank Siddhartha
117 Lectures
10 hours
Frahaan Hussain
27 Lectures
1 hours
Skillbakerystudios
17 Lectures
51 mins
Harsh Kumar Khatri
17 Lectures
1.5 hours
Pramila Rawat
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2640,
"s": 2218,
"text": "Since the core concept of Flutter is Everything is widget, Flutter incorporates a user interface layout functionality into the widgets itself. Flutter provides quite a lot of specially designed widgets like Container, Center, Align, etc., only for the purpose of laying out the user interface. Widgets build by composing other widgets normally use layout widgets. Let use learn the Flutter layout concept in this chapter."
},
{
"code": null,
"e": 2718,
"s": 2640,
"text": "Layout widgets can be grouped into two distinct category based on its child −"
},
{
"code": null,
"e": 2751,
"s": 2718,
"text": "Widget supporting a single child"
},
{
"code": null,
"e": 2784,
"s": 2751,
"text": "Widget supporting multiple child"
},
{
"code": null,
"e": 2866,
"s": 2784,
"text": "Let us learn both type of widgets and its functionality in the upcoming sections."
},
{
"code": null,
"e": 2990,
"s": 2866,
"text": "In this category, widgets will have only one widget as its child and every widget will have a special layout functionality."
},
{
"code": null,
"e": 3233,
"s": 2990,
"text": "For example, Center widget just centers it child widget with respect to its parent widget and Container widget provides complete flexibility to place it child at any given place inside it using different option like padding, decoration, etc.,"
},
{
"code": null,
"e": 3359,
"s": 3233,
"text": "Single child widgets are great options to create high quality widget having single functionality such as button, label, etc.,"
},
{
"code": null,
"e": 3433,
"s": 3359,
"text": "The code to create a simple button using Container widget is as follows −"
},
{
"code": null,
"e": 4722,
"s": 3433,
"text": "class MyButton extends StatelessWidget {\n MyButton({Key key}) : super(key: key); \n\n @override \n Widget build(BuildContext context) {\n return Container(\n decoration: const BoxDecoration(\n border: Border(\n top: BorderSide(width: 1.0, color: Color(0xFFFFFFFFFF)),\n left: BorderSide(width: 1.0, color: Color(0xFFFFFFFFFF)),\n right: BorderSide(width: 1.0, color: Color(0xFFFF000000)),\n bottom: BorderSide(width: 1.0, color: Color(0xFFFF000000)),\n ),\n ),\n child: Container(\n padding: const\n EdgeInsets.symmetric(horizontal: 20.0, vertical: 2.0),\n decoration: const BoxDecoration(\n border: Border(\n top: BorderSide(width: 1.0, color: Color(0xFFFFDFDFDF)),\n left: BorderSide(width: 1.0, color: Color(0xFFFFDFDFDF)),\n right: BorderSide(width: 1.0, color: Color(0xFFFF7F7F7F)),\n bottom: BorderSide(width: 1.0, color: Color(0xFFFF7F7F7F)),\n ),\n color: Colors.grey,\n ),\n child: const Text(\n 'OK',textAlign: TextAlign.center, style: TextStyle(color: Colors.black)\n ), \n ), \n ); \n }\n}"
},
{
"code": null,
"e": 4857,
"s": 4722,
"text": "Here, we have used two widgets – a Container widget and a Text widget. The result of the widget is as a custom button as shown below −"
},
{
"code": null,
"e": 4947,
"s": 4857,
"text": "Let us check some of the most important single child layout widgets provided by Flutter −"
},
{
"code": null,
"e": 5063,
"s": 4947,
"text": "Padding − Used to arrange its child widget by the given padding. Here, padding can be provided by EdgeInsets class."
},
{
"code": null,
"e": 5179,
"s": 5063,
"text": "Padding − Used to arrange its child widget by the given padding. Here, padding can be provided by EdgeInsets class."
},
{
"code": null,
"e": 5430,
"s": 5179,
"text": "Align − Align its child widget within itself using the value of alignment property. The value for alignment property can be provided by FractionalOffset class. The FractionalOffset class specifies the offsets in terms of a distance from the top left."
},
{
"code": null,
"e": 5681,
"s": 5430,
"text": "Align − Align its child widget within itself using the value of alignment property. The value for alignment property can be provided by FractionalOffset class. The FractionalOffset class specifies the offsets in terms of a distance from the top left."
},
{
"code": null,
"e": 5737,
"s": 5681,
"text": "Some of the possible values of offsets are as follows −"
},
{
"code": null,
"e": 5790,
"s": 5737,
"text": "FractionalOffset(1.0, 0.0) represents the top right."
},
{
"code": null,
"e": 5843,
"s": 5790,
"text": "FractionalOffset(1.0, 0.0) represents the top right."
},
{
"code": null,
"e": 5898,
"s": 5843,
"text": "FractionalOffset(0.0, 1.0) represents the bottom left."
},
{
"code": null,
"e": 5953,
"s": 5898,
"text": "FractionalOffset(0.0, 1.0) represents the bottom left."
},
{
"code": null,
"e": 5998,
"s": 5953,
"text": "A sample code about offsets is shown below −"
},
{
"code": null,
"e": 6277,
"s": 5998,
"text": "Center(\n child: Container(\n height: 100.0, \n width: 100.0, \n color: Colors.yellow, child: Align(\n alignment: FractionalOffset(0.2, 0.6),\n child: Container( height: 40.0, width:\n 40.0, color: Colors.red,\n ), \n ), \n ), \n)"
},
{
"code": null,
"e": 6370,
"s": 6277,
"text": "FittedBox − It scales the child widget and then positions it according to the specified fit."
},
{
"code": null,
"e": 6463,
"s": 6370,
"text": "FittedBox − It scales the child widget and then positions it according to the specified fit."
},
{
"code": null,
"e": 6544,
"s": 6463,
"text": "AspectRatio − It attempts to size the child widget to the specified aspect ratio"
},
{
"code": null,
"e": 6625,
"s": 6544,
"text": "AspectRatio − It attempts to size the child widget to the specified aspect ratio"
},
{
"code": null,
"e": 6640,
"s": 6625,
"text": "ConstrainedBox"
},
{
"code": null,
"e": 6655,
"s": 6640,
"text": "ConstrainedBox"
},
{
"code": null,
"e": 6664,
"s": 6655,
"text": "Baseline"
},
{
"code": null,
"e": 6673,
"s": 6664,
"text": "Baseline"
},
{
"code": null,
"e": 6693,
"s": 6673,
"text": "FractinallySizedBox"
},
{
"code": null,
"e": 6713,
"s": 6693,
"text": "FractinallySizedBox"
},
{
"code": null,
"e": 6729,
"s": 6713,
"text": "IntrinsicHeight"
},
{
"code": null,
"e": 6745,
"s": 6729,
"text": "IntrinsicHeight"
},
{
"code": null,
"e": 6760,
"s": 6745,
"text": "IntrinsicWidth"
},
{
"code": null,
"e": 6775,
"s": 6760,
"text": "IntrinsicWidth"
},
{
"code": null,
"e": 6787,
"s": 6775,
"text": "LiimitedBox"
},
{
"code": null,
"e": 6799,
"s": 6787,
"text": "LiimitedBox"
},
{
"code": null,
"e": 6808,
"s": 6799,
"text": "OffStage"
},
{
"code": null,
"e": 6817,
"s": 6808,
"text": "OffStage"
},
{
"code": null,
"e": 6829,
"s": 6817,
"text": "OverflowBox"
},
{
"code": null,
"e": 6841,
"s": 6829,
"text": "OverflowBox"
},
{
"code": null,
"e": 6850,
"s": 6841,
"text": "SizedBox"
},
{
"code": null,
"e": 6859,
"s": 6850,
"text": "SizedBox"
},
{
"code": null,
"e": 6876,
"s": 6859,
"text": "SizedOverflowBox"
},
{
"code": null,
"e": 6893,
"s": 6876,
"text": "SizedOverflowBox"
},
{
"code": null,
"e": 6903,
"s": 6893,
"text": "Transform"
},
{
"code": null,
"e": 6913,
"s": 6903,
"text": "Transform"
},
{
"code": null,
"e": 6937,
"s": 6913,
"text": "CustomSingleChildLayout"
},
{
"code": null,
"e": 6961,
"s": 6937,
"text": "CustomSingleChildLayout"
},
{
"code": null,
"e": 7166,
"s": 6961,
"text": "Our hello world application is using material based layout widgets to design the home page. Let us modify our hello world application to build the home page using basic layout widgets as specified below −"
},
{
"code": null,
"e": 7305,
"s": 7166,
"text": "Container − Generic, single child, box based container widget with alignment, padding, border and margin along with rich styling features."
},
{
"code": null,
"e": 7444,
"s": 7305,
"text": "Container − Generic, single child, box based container widget with alignment, padding, border and margin along with rich styling features."
},
{
"code": null,
"e": 7524,
"s": 7444,
"text": "Center − Simple, Single child container widget, which centers its child widget."
},
{
"code": null,
"e": 7604,
"s": 7524,
"text": "Center − Simple, Single child container widget, which centers its child widget."
},
{
"code": null,
"e": 7671,
"s": 7604,
"text": "The modified code of the MyHomePage and MyApp widget is as below −"
},
{
"code": null,
"e": 8389,
"s": 7671,
"text": "class MyApp extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return MyHomePage(title: \"Hello World demo app\");\n }\n}\nclass MyHomePage extends StatelessWidget {\n MyHomePage({Key key, this.title}) : super(key: key);\n final String title;\n @override\n Widget build(BuildContext context) {\n return Container(\n decoration: BoxDecoration(color: Colors.white,),\n padding: EdgeInsets.all(25), child: Center(\n child:Text(\n 'Hello World', style: TextStyle(\n color: Colors.black, letterSpacing: 0.5, fontSize: 20,\n ),\n textDirection: TextDirection.ltr,\n ),\n )\n );\n }\n}"
},
{
"code": null,
"e": 8395,
"s": 8389,
"text": "Here,"
},
{
"code": null,
"e": 8530,
"s": 8395,
"text": "Container widget is the top level or root widget. Container is configured using decoration and padding property to layout its content."
},
{
"code": null,
"e": 8665,
"s": 8530,
"text": "Container widget is the top level or root widget. Container is configured using decoration and padding property to layout its content."
},
{
"code": null,
"e": 8817,
"s": 8665,
"text": "BoxDecoration has many properties like color, border, etc., to decorate the Container widget and here, color is used to set the color of the container."
},
{
"code": null,
"e": 8969,
"s": 8817,
"text": "BoxDecoration has many properties like color, border, etc., to decorate the Container widget and here, color is used to set the color of the container."
},
{
"code": null,
"e": 9090,
"s": 8969,
"text": "padding of the Container widget is set by using dgeInsets class, which provides the option to specify the padding value."
},
{
"code": null,
"e": 9211,
"s": 9090,
"text": "padding of the Container widget is set by using dgeInsets class, which provides the option to specify the padding value."
},
{
"code": null,
"e": 9431,
"s": 9211,
"text": "Center is the child widget of the Container widget. Again, Text is the child of the Center widget. Text is used to show message and Center is used to center the text message with respect to the parent widget, Container."
},
{
"code": null,
"e": 9651,
"s": 9431,
"text": "Center is the child widget of the Container widget. Again, Text is the child of the Center widget. Text is used to show message and Center is used to center the text message with respect to the parent widget, Container."
},
{
"code": null,
"e": 9728,
"s": 9651,
"text": "The final result of the code given above is a layout sample as shown below −"
},
{
"code": null,
"e": 9840,
"s": 9728,
"text": "In this category, a given widget will have more than one child widgets and the layout of each widget is unique."
},
{
"code": null,
"e": 10085,
"s": 9840,
"text": "For example, Row widget allows the laying out of its children in horizontal direction, whereas Column widget allows laying out of its children in vertical direction. By composing Row and Column, widget with any level of complexity can be built."
},
{
"code": null,
"e": 10151,
"s": 10085,
"text": "Let us learn some of the frequently used widgets in this section."
},
{
"code": null,
"e": 10212,
"s": 10151,
"text": "Row − Allows to arrange its children in a horizontal manner."
},
{
"code": null,
"e": 10273,
"s": 10212,
"text": "Row − Allows to arrange its children in a horizontal manner."
},
{
"code": null,
"e": 10335,
"s": 10273,
"text": "Column − Allows to arrange its children in a vertical manner."
},
{
"code": null,
"e": 10397,
"s": 10335,
"text": "Column − Allows to arrange its children in a vertical manner."
},
{
"code": null,
"e": 10448,
"s": 10397,
"text": "ListView − Allows to arrange its children as list."
},
{
"code": null,
"e": 10499,
"s": 10448,
"text": "ListView − Allows to arrange its children as list."
},
{
"code": null,
"e": 10553,
"s": 10499,
"text": "GridView − Allows to arrange its children as gallery."
},
{
"code": null,
"e": 10607,
"s": 10553,
"text": "GridView − Allows to arrange its children as gallery."
},
{
"code": null,
"e": 10706,
"s": 10607,
"text": "Expanded − Used to make the children of Row and Column widget to occupy the maximum possible area."
},
{
"code": null,
"e": 10805,
"s": 10706,
"text": "Expanded − Used to make the children of Row and Column widget to occupy the maximum possible area."
},
{
"code": null,
"e": 10833,
"s": 10805,
"text": "Table − Table based widget."
},
{
"code": null,
"e": 10861,
"s": 10833,
"text": "Table − Table based widget."
},
{
"code": null,
"e": 10887,
"s": 10861,
"text": "Flow − Flow based widget."
},
{
"code": null,
"e": 10913,
"s": 10887,
"text": "Flow − Flow based widget."
},
{
"code": null,
"e": 10941,
"s": 10913,
"text": "Stack − Stack based widget."
},
{
"code": null,
"e": 10969,
"s": 10941,
"text": "Stack − Stack based widget."
},
{
"code": null,
"e": 11129,
"s": 10969,
"text": "In this section, let us learn how to create a complex user interface of product listing with custom design using both single and multiple child layout widgets."
},
{
"code": null,
"e": 11181,
"s": 11129,
"text": "For this purpose, follow the sequence given below −"
},
{
"code": null,
"e": 11253,
"s": 11181,
"text": "Create a new Flutter application in Android studio, product_layout_app."
},
{
"code": null,
"e": 11325,
"s": 11253,
"text": "Create a new Flutter application in Android studio, product_layout_app."
},
{
"code": null,
"e": 11373,
"s": 11325,
"text": "Replace the main.dart code with folowing code −"
},
{
"code": null,
"e": 11421,
"s": 11373,
"text": "Replace the main.dart code with folowing code −"
},
{
"code": null,
"e": 12175,
"s": 11421,
"text": "import 'package:flutter/material.dart'; \nvoid main() => runApp(MyApp()); \n\nclass MyApp extends StatelessWidget {\n // This widget is the root of your application.\n @override \n Widget build(BuildContext context) {\n return MaterialApp( \n title: 'Flutter Demo', theme: ThemeData( \n primarySwatch: Colors.blue,), \n home: MyHomePage(title: 'Product layout demo home page'),\n ); \n } \n} \nclass MyHomePage extends StatelessWidget {\n MyHomePage({Key key, this.title}) : super(key: key); \n final String title; \n \n @override \n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(title: Text(this.title),), \n body: Center(child: Text( 'Hello World', )), \n ); \n }\n}"
},
{
"code": null,
"e": 12181,
"s": 12175,
"text": "Here,"
},
{
"code": null,
"e": 12187,
"s": 12181,
"text": "Here,"
},
{
"code": null,
"e": 12320,
"s": 12187,
"text": "We have created MyHomePage widget by extending StatelessWidget instead of default StatefulWidget and then removed the relevant code."
},
{
"code": null,
"e": 12453,
"s": 12320,
"text": "We have created MyHomePage widget by extending StatelessWidget instead of default StatefulWidget and then removed the relevant code."
},
{
"code": null,
"e": 12541,
"s": 12453,
"text": "Now, create a new widget, ProductBox according to the specified design as shown below −"
},
{
"code": null,
"e": 12629,
"s": 12541,
"text": "Now, create a new widget, ProductBox according to the specified design as shown below −"
},
{
"code": null,
"e": 12672,
"s": 12629,
"text": "The code for the ProductBox is as follows."
},
{
"code": null,
"e": 12715,
"s": 12672,
"text": "The code for the ProductBox is as follows."
},
{
"code": null,
"e": 13918,
"s": 12715,
"text": "class ProductBox extends StatelessWidget {\n ProductBox({Key key, this.name, this.description, this.price, this.image}) \n : super(key: key); \n final String name; \n final String description; \n final int price; \n final String image; \n\n Widget build(BuildContext context) {\n return Container(\n padding: EdgeInsets.all(2), height: 120, child: Card( \n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[\n Image.asset(\"assets/appimages/\" +image), Expanded(\n child: Container(\n padding: EdgeInsets.all(5), child: Column(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly, \n children: <Widget>[ \n \n Text(this.name, style: TextStyle(fontWeight: \n FontWeight.bold)), Text(this.description), \n Text(\"Price: \" + this.price.toString()), \n ], \n )\n )\n )\n ]\n )\n )\n );\n }\n}"
},
{
"code": null,
"e": 13961,
"s": 13918,
"text": "Please observe the following in the code −"
},
{
"code": null,
"e": 14004,
"s": 13961,
"text": "Please observe the following in the code −"
},
{
"code": null,
"e": 14060,
"s": 14004,
"text": "ProductBox has used four arguments as specified below −"
},
{
"code": null,
"e": 14116,
"s": 14060,
"text": "ProductBox has used four arguments as specified below −"
},
{
"code": null,
"e": 14136,
"s": 14116,
"text": "name - Product name"
},
{
"code": null,
"e": 14156,
"s": 14136,
"text": "name - Product name"
},
{
"code": null,
"e": 14190,
"s": 14156,
"text": "description - Product description"
},
{
"code": null,
"e": 14224,
"s": 14190,
"text": "description - Product description"
},
{
"code": null,
"e": 14253,
"s": 14224,
"text": "price - Price of the product"
},
{
"code": null,
"e": 14282,
"s": 14253,
"text": "price - Price of the product"
},
{
"code": null,
"e": 14311,
"s": 14282,
"text": "image - Image of the product"
},
{
"code": null,
"e": 14340,
"s": 14311,
"text": "image - Image of the product"
},
{
"code": null,
"e": 14400,
"s": 14340,
"text": "ProductBox uses seven build-in widgets as specified below −"
},
{
"code": null,
"e": 14460,
"s": 14400,
"text": "ProductBox uses seven build-in widgets as specified below −"
},
{
"code": null,
"e": 14470,
"s": 14460,
"text": "Container"
},
{
"code": null,
"e": 14479,
"s": 14470,
"text": "Expanded"
},
{
"code": null,
"e": 14483,
"s": 14479,
"text": "Row"
},
{
"code": null,
"e": 14490,
"s": 14483,
"text": "Column"
},
{
"code": null,
"e": 14495,
"s": 14490,
"text": "Card"
},
{
"code": null,
"e": 14500,
"s": 14495,
"text": "Text"
},
{
"code": null,
"e": 14506,
"s": 14500,
"text": "Image"
},
{
"code": null,
"e": 14648,
"s": 14506,
"text": "ProductBox is designed using the above mentioned widget. The arrangement or hierarchy of the widget is specified in the diagram shown below −"
},
{
"code": null,
"e": 14790,
"s": 14648,
"text": "ProductBox is designed using the above mentioned widget. The arrangement or hierarchy of the widget is specified in the diagram shown below −"
},
{
"code": null,
"e": 14968,
"s": 14790,
"text": "Now, place some dummy image (see below) for product information in the assets folder of the application and configure the assets folder in the pubspec.yaml file as shown below −"
},
{
"code": null,
"e": 15146,
"s": 14968,
"text": "Now, place some dummy image (see below) for product information in the assets folder of the application and configure the assets folder in the pubspec.yaml file as shown below −"
},
{
"code": null,
"e": 15360,
"s": 15146,
"text": "assets: \n - assets/appimages/floppy.png \n - assets/appimages/iphone.png \n - assets/appimages/laptop.png \n - assets/appimages/pendrive.png \n - assets/appimages/pixel.png \n - assets/appimages/tablet.png\n"
},
{
"code": null,
"e": 15371,
"s": 15360,
"text": "iPhone.png"
},
{
"code": null,
"e": 15381,
"s": 15371,
"text": "Pixel.png"
},
{
"code": null,
"e": 15392,
"s": 15381,
"text": "Laptop.png"
},
{
"code": null,
"e": 15403,
"s": 15392,
"text": "Tablet.png"
},
{
"code": null,
"e": 15416,
"s": 15403,
"text": "Pendrive.png"
},
{
"code": null,
"e": 15427,
"s": 15416,
"text": "Floppy.png"
},
{
"code": null,
"e": 15508,
"s": 15427,
"text": "Finally, Use the ProductBox widget in the MyHomePage widget as specified below −"
},
{
"code": null,
"e": 17324,
"s": 15508,
"text": "class MyHomePage extends StatelessWidget { \n MyHomePage({Key key, this.title}) : super(key: key); \n final String title; \n\n @override \n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(title:Text(\"Product Listing\")), \n body: ListView(\n shrinkWrap: true, padding: const EdgeInsets.fromLTRB(2.0, 10.0, 2.0, 10.0), \n children: <Widget> [\n ProductBox(\n name: \"iPhone\", \n description: \"iPhone is the stylist phone ever\", \n price: 1000, \n image: \"iphone.png\"\n ), \n ProductBox(\n name: \"Pixel\", \n description: \"Pixel is the most featureful phone ever\", \n price: 800, \n image: \"pixel.png\"\n ), \n ProductBox( \n name: \"Laptop\", \n description: \"Laptop is most productive development tool\", \n price: 2000, \n image: \"laptop.png\"\n ), \n ProductBox( \n name: \"Tablet\", \n description: \"Tablet is the most useful device ever for meeting\", \n price: 1500, \n image: \"tablet.png\"\n ), \n ProductBox(\n name: \"Pendrive\", \n description: \"Pendrive is useful storage medium\", \n price: 100, \n image: \"pendrive.png\"\n ), \n ProductBox(\n name: \"Floppy Drive\", \n description: \"Floppy drive is useful rescue storage medium\", \n price: 20, \n image: \"floppy.png\"\n ), \n ],\n )\n );\n }\n}"
},
{
"code": null,
"e": 17385,
"s": 17324,
"text": "Here,we have used ProductBox as children of ListView widget."
},
{
"code": null,
"e": 17446,
"s": 17385,
"text": "Here,we have used ProductBox as children of ListView widget."
},
{
"code": null,
"e": 17547,
"s": 17446,
"text": "The complete code (main.dart) of the product layout application (product_layout_app) is as follows −"
},
{
"code": null,
"e": 17648,
"s": 17547,
"text": "The complete code (main.dart) of the product layout application (product_layout_app) is as follows −"
},
{
"code": null,
"e": 21344,
"s": 17648,
"text": "import 'package:flutter/material.dart'; \nvoid main() => runApp(MyApp()); \n\nclass MyApp extends StatelessWidget { \n // This widget is the root of your application. \n @override \n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Flutter Demo', theme: ThemeData(\n primarySwatch: Colors.blue,\n ), \n home: MyHomePage(title: 'Product layout demo home page'), \n );\n }\n}\nclass MyHomePage extends StatelessWidget { \n MyHomePage({Key key, this.title}) : super(key: key); \n final String title; \n \n @override \n Widget build(BuildContext context) { \n return Scaffold( \n appBar: AppBar(title: Text(\"Product Listing\")), \n body: ListView(\n shrinkWrap: true, \n padding: const EdgeInsets.fromLTRB(2.0, 10.0, 2.0, 10.0), \n children: <Widget>[ \n ProductBox(\n name: \"iPhone\", \n description: \"iPhone is the stylist phone ever\", \n price: 1000, \n image: \"iphone.png\"\n ), \n ProductBox( \n name: \"Pixel\", \n description: \"Pixel is the most featureful phone ever\", \n price: 800, \n image: \"pixel.png\"\n ), \n ProductBox( \n name: \"Laptop\", \n description: \"Laptop is most productive development tool\", \n price: 2000, \n image: \"laptop.png\"\n ), \n ProductBox( \n name: \"Tablet\", \n description: \"Tablet is the most useful device ever for meeting\", \n price: 1500, \n image: \"tablet.png\"\n ), \n ProductBox( \n name: \"Pendrive\", \n description: \"Pendrive is useful storage medium\", \n price: 100, \n image: \"pendrive.png\"\n ), \n ProductBox(\n name: \"Floppy Drive\", \n description: \"Floppy drive is useful rescue storage medium\", \n price: 20, \n image: \"floppy.png\"\n ), \n ],\n )\n );\n }\n}\nclass ProductBox extends StatelessWidget {\n ProductBox({Key key, this.name, this.description, this.price, this.image}) :\n super(key: key); \n final String name; \n final String description; \n final int price; \n final String image; \n \n Widget build(BuildContext context) {\n return Container(\n padding: EdgeInsets.all(2), \n height: 120, \n child: Card(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly, \n children: <Widget>[ \n Image.asset(\"assets/appimages/\" + image), \n Expanded( \n child: Container( \n padding: EdgeInsets.all(5), \n child: Column( \n mainAxisAlignment: MainAxisAlignment.spaceEvenly, \n children: <Widget>[ \n Text(\n this.name, style: TextStyle(\n fontWeight: FontWeight.bold\n )\n ),\n Text(this.description), Text(\n \"Price: \" + this.price.toString()\n ), \n ], \n )\n )\n )\n ]\n )\n )\n );\n }\n}"
},
{
"code": null,
"e": 21396,
"s": 21344,
"text": "The final output of the application is as follows −"
},
{
"code": null,
"e": 21429,
"s": 21396,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 21449,
"s": 21429,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 21484,
"s": 21449,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 21501,
"s": 21484,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 21534,
"s": 21501,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 21554,
"s": 21534,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 21586,
"s": 21554,
"text": "\n 17 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 21606,
"s": 21586,
"text": " Harsh Kumar Khatri"
},
{
"code": null,
"e": 21641,
"s": 21606,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 21656,
"s": 21641,
"text": " Pramila Rawat"
},
{
"code": null,
"e": 21692,
"s": 21656,
"text": "\n 85 Lectures \n 16.5 hours \n"
},
{
"code": null,
"e": 21707,
"s": 21692,
"text": " Rahul Agarwal"
},
{
"code": null,
"e": 21714,
"s": 21707,
"text": " Print"
},
{
"code": null,
"e": 21725,
"s": 21714,
"text": " Add Notes"
}
] |
Python 3 - List index() Method
|
The index() method returns the lowest index in list that obj appears.
Following is the syntax for index() method −
list.index(obj)
obj − This is the object to be find out.
This method returns index of the found object otherwise raise an exception indicating that value does not find.
The following example shows the usage of index() method.
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 'maths']
print ('Index of chemistry', list1.index('chemistry'))
print ('Index of C#', list1.index('C#'))
When we run above program, it produces the following result −
Index of chemistry 1
Traceback (most recent call last):
File "test.py", line 3, in <module>
print ('Index of C#', list1.index('C#'))
ValueError: 'C#' is not in list
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": 2410,
"s": 2340,
"text": "The index() method returns the lowest index in list that obj appears."
},
{
"code": null,
"e": 2455,
"s": 2410,
"text": "Following is the syntax for index() method −"
},
{
"code": null,
"e": 2472,
"s": 2455,
"text": "list.index(obj)\n"
},
{
"code": null,
"e": 2513,
"s": 2472,
"text": "obj − This is the object to be find out."
},
{
"code": null,
"e": 2625,
"s": 2513,
"text": "This method returns index of the found object otherwise raise an exception indicating that value does not find."
},
{
"code": null,
"e": 2682,
"s": 2625,
"text": "The following example shows the usage of index() method."
},
{
"code": null,
"e": 2840,
"s": 2682,
"text": "#!/usr/bin/python3\n\nlist1 = ['physics', 'chemistry', 'maths']\nprint ('Index of chemistry', list1.index('chemistry'))\nprint ('Index of C#', list1.index('C#'))"
},
{
"code": null,
"e": 2902,
"s": 2840,
"text": "When we run above program, it produces the following result −"
},
{
"code": null,
"e": 3077,
"s": 2902,
"text": "Index of chemistry 1\nTraceback (most recent call last):\n File \"test.py\", line 3, in <module>\n print ('Index of C#', list1.index('C#'))\nValueError: 'C#' is not in list\n"
},
{
"code": null,
"e": 3114,
"s": 3077,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3130,
"s": 3114,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3163,
"s": 3130,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3182,
"s": 3163,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3217,
"s": 3182,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3239,
"s": 3217,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3273,
"s": 3239,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3301,
"s": 3273,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3336,
"s": 3301,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3350,
"s": 3336,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3383,
"s": 3350,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3400,
"s": 3383,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3407,
"s": 3400,
"text": " Print"
},
{
"code": null,
"e": 3418,
"s": 3407,
"text": " Add Notes"
}
] |
Using RStudio Project Templates to help the project standardization in data science teams | by Luis Henrique Zanandréa Paese | Towards Data Science
|
Many works in the data science realm rely solely upon the data scientist/analyst to guarantee the project standardization and code reproducibility; unfortunately, this becomes a source of confusion/disorganization since everybody (even on the same team) have different work strategies. To help ensure that teams share the same project standards, RStudio offers a sort of cookiecutter, where you can develop (in form of packages) many templates to be shared amongst users on the same team.
Recent studies aim to provide the society with methodologies that help users to better understand and organize their projects, data, and insights generated from this data. From CRISP-DM going all the way to Team Data Science Process, passing through KDD, we have experienced many ways to enhance our ability to work in teams, joining efforts to reach the desired insights faster, and with more reproducibility.
Nonetheless, this process repeats itself for an infinite number of times, and the process of going back and re-developing an insight, or re-training a model, becomes a challenge because the code that was written long ago, is not easily reachable, and may be hard to understand the whole process that took to develop this project a few weeks/months/years ago.
A few of the projects may look like this:
Even though it may be faster to just open a repository, and just put the scripts, files, functions, .gitignores and any sort of the files needed to deliver a shiny webpage or a machine learning model, or an analysis of some kind, this process lacks the ability to create code and processes that can be understood by any other person that may be assigned to this project in the future.
So, this RStudio Project Templates aims to help users create some sort of pattern when starting a project, helping the team to standardize the project organization and in a way that everybody can easily be assigned to a project, and understand what is happening there.
And maybe, turn projects into something like this:
-- project_directory/ | -- data/ | -- raw/ | -- reference/ | -- processed/ | -- scripts/ | -- modelling/ | -- analysis/ | -- production/ | -- markdown/ -- .gitignore -- project_directory.Rproj
Project templates can be used to create new projects with a pre-specified structure, and one way to create these project templates is by creating an R package, which will allow the user to share its template with as many users as one desires.
The process of R package creation (a fairly simple one) is pretty straightforward. Hadley’s R Package Guide covers many of the caveats involved in the process of creating a package. But since our package will contain only one function, it shouldn’t require the complexity involved in the development of a more robust package.
Creating an R package from the project’s menu is easy, and should leave the user in front of a sample package, which will contain the R package structure, a hello.R function, and a few other files. The first step is to remove the hello.R file located at R/ and the hello.Rd file located at man/. After that, we start with a clean package, and the first step is to create our function.
To “create the template” we have to instruct how R will deal with it, and how it will behave when we source this function in the New Project menu. So this function takes one mandatory argument, and the other is additional arguments that can help the logic of your Project Creation tool. The first argument will always be the path of this New Project since it’ll create a .RProj file as well, it’ll be hosted in a new folder. The other arguments of this function are passed as ... and they can be called within the code with their names, or by assigning them to dots <- list(...).
Our function will do a few tasks, to display a few of the features that can be embedded in the project creation templates. It will:
Create a README.md file with writeLines();
If a checkbox is selected, it will create a .gitignore file;
Create a folder with a specific name given a selected input from the user;
To create a function, and ensure that roxygen2 can interpret it, and export the function that should be exported by the final package, we'll write the function according to the syntax below.
#' This package will create a function called create_project()#'#' It's callback is at: inst/rstudio/templates/project/create_project.dcf#'#' @exportcreate_project <-function(path, ...) {# Create the project path given the name chosen by the user:dir.create(path, recursive = TRUE, showWarnings = FALSE)# Change the working directory to the recently created folder:setwd(file.path(getwd(), path))# Collect the list of inputs in a list to be called later:dots <- list(...)# In the project template we've added 2 choices for the user:# * One allows them to select if the project will have a .gitignore file# * The other will create a folder, given a select input from the user# Check .gitignore argumentif(dots[["createGitignore"]]) {git_ignores <-c('.Rhistory','.Rapp.history','.RData','.Ruserdata','.Rproj.user/','.Renviron')writeLines(paste(git_ignores, sep = '\n'), '.gitignore')}# Check selected folderif(dots[["folder"]] == "Production"){dir.create("production", recursive = TRUE, showWarnings = FALSE)} else {dir.create("development", recursive = TRUE, showWarnings = FALSE)}}
With the function file created, the next step is to create the .dcf file. This file is responsible to create the boxes which the user will interact with. Along with the path that the user will type, you can create as many checkboxes/text inputs/select inputs as you wish to grant customization to the end-user. For our project, we'll create a checkbox, so the user can decide whether to create the .gitignore file and a select input, so the user can define the scope of the project (development or production);
This solution (development or production) was just created for illustration purposes, it does not reflect any actual state of a project.
The .dcf file must be created within the package in the folder inst/rstudio/templates/project with the name of your choice, and it should follow the syntax below:
Binding: create_projectTitle: My First Project TemplateOpenFiles: README.md# In the project you can also add icons (the icon should be a PNG, smaller than 64kb# and in the inst/rstudio/templates folder# Icon: name_of_pic.pngParameter: folderWidget: SelectInputLabel: Choose the scope of the projectFields: Production, DevelopmentDefault: ProductionPosition: leftParameter: createGitignoreWidget: CheckboxInputLabel: Create .gitignoreDefault: OnPosition: right
Now that our package structure is created, we can use the devtools::document() function to create its documentation pages. Even though this package is mainly developed to be an add-in for RStudio, it's a good practice to document the package, before installing it in R, since it will search for any dependencies and packages that are needed for your project to work.
By running the devtools::install() function, within our package, we are going to install it and make it available in any other R Session from now on. This should be enough to make the add-in accessible by RStudio as a New Project Template.
After that, your project template should be available in RStudio’s list of projects. If you want to know more about different features to tweak your project template and add more customizability, please check the RStudio Project Template page.
Given the recent developments in data science and its integration with software engineering techniques, the need to standardize projects within teams comes handy to ensure that everybody can understand, and be understood by their pairs. This allows faster debugging of projects and mitigates the drawbacks of legacy code that is incomprehensible by people in the same teams. Of course, this feature alone will not help to document code, or standardize the way to write R scripts (please refer to The tidyverse style guide), but it is a tool that will help users to create patterns regarding project management.
Check out the GitHub page where the code used in this article is hosted, and if you wanna try out this example, clone the repository, or install it in R by running: devtools::install_github('paeselhz/rstudioProjectTemplate').
|
[
{
"code": null,
"e": 661,
"s": 172,
"text": "Many works in the data science realm rely solely upon the data scientist/analyst to guarantee the project standardization and code reproducibility; unfortunately, this becomes a source of confusion/disorganization since everybody (even on the same team) have different work strategies. To help ensure that teams share the same project standards, RStudio offers a sort of cookiecutter, where you can develop (in form of packages) many templates to be shared amongst users on the same team."
},
{
"code": null,
"e": 1072,
"s": 661,
"text": "Recent studies aim to provide the society with methodologies that help users to better understand and organize their projects, data, and insights generated from this data. From CRISP-DM going all the way to Team Data Science Process, passing through KDD, we have experienced many ways to enhance our ability to work in teams, joining efforts to reach the desired insights faster, and with more reproducibility."
},
{
"code": null,
"e": 1431,
"s": 1072,
"text": "Nonetheless, this process repeats itself for an infinite number of times, and the process of going back and re-developing an insight, or re-training a model, becomes a challenge because the code that was written long ago, is not easily reachable, and may be hard to understand the whole process that took to develop this project a few weeks/months/years ago."
},
{
"code": null,
"e": 1473,
"s": 1431,
"text": "A few of the projects may look like this:"
},
{
"code": null,
"e": 1858,
"s": 1473,
"text": "Even though it may be faster to just open a repository, and just put the scripts, files, functions, .gitignores and any sort of the files needed to deliver a shiny webpage or a machine learning model, or an analysis of some kind, this process lacks the ability to create code and processes that can be understood by any other person that may be assigned to this project in the future."
},
{
"code": null,
"e": 2127,
"s": 1858,
"text": "So, this RStudio Project Templates aims to help users create some sort of pattern when starting a project, helping the team to standardize the project organization and in a way that everybody can easily be assigned to a project, and understand what is happening there."
},
{
"code": null,
"e": 2178,
"s": 2127,
"text": "And maybe, turn projects into something like this:"
},
{
"code": null,
"e": 2389,
"s": 2178,
"text": "-- project_directory/ | -- data/ | -- raw/ | -- reference/ | -- processed/ | -- scripts/ | -- modelling/ | -- analysis/ | -- production/ | -- markdown/ -- .gitignore -- project_directory.Rproj"
},
{
"code": null,
"e": 2632,
"s": 2389,
"text": "Project templates can be used to create new projects with a pre-specified structure, and one way to create these project templates is by creating an R package, which will allow the user to share its template with as many users as one desires."
},
{
"code": null,
"e": 2958,
"s": 2632,
"text": "The process of R package creation (a fairly simple one) is pretty straightforward. Hadley’s R Package Guide covers many of the caveats involved in the process of creating a package. But since our package will contain only one function, it shouldn’t require the complexity involved in the development of a more robust package."
},
{
"code": null,
"e": 3343,
"s": 2958,
"text": "Creating an R package from the project’s menu is easy, and should leave the user in front of a sample package, which will contain the R package structure, a hello.R function, and a few other files. The first step is to remove the hello.R file located at R/ and the hello.Rd file located at man/. After that, we start with a clean package, and the first step is to create our function."
},
{
"code": null,
"e": 3923,
"s": 3343,
"text": "To “create the template” we have to instruct how R will deal with it, and how it will behave when we source this function in the New Project menu. So this function takes one mandatory argument, and the other is additional arguments that can help the logic of your Project Creation tool. The first argument will always be the path of this New Project since it’ll create a .RProj file as well, it’ll be hosted in a new folder. The other arguments of this function are passed as ... and they can be called within the code with their names, or by assigning them to dots <- list(...)."
},
{
"code": null,
"e": 4055,
"s": 3923,
"text": "Our function will do a few tasks, to display a few of the features that can be embedded in the project creation templates. It will:"
},
{
"code": null,
"e": 4098,
"s": 4055,
"text": "Create a README.md file with writeLines();"
},
{
"code": null,
"e": 4159,
"s": 4098,
"text": "If a checkbox is selected, it will create a .gitignore file;"
},
{
"code": null,
"e": 4234,
"s": 4159,
"text": "Create a folder with a specific name given a selected input from the user;"
},
{
"code": null,
"e": 4425,
"s": 4234,
"text": "To create a function, and ensure that roxygen2 can interpret it, and export the function that should be exported by the final package, we'll write the function according to the syntax below."
},
{
"code": null,
"e": 5507,
"s": 4425,
"text": "#' This package will create a function called create_project()#'#' It's callback is at: inst/rstudio/templates/project/create_project.dcf#'#' @exportcreate_project <-function(path, ...) {# Create the project path given the name chosen by the user:dir.create(path, recursive = TRUE, showWarnings = FALSE)# Change the working directory to the recently created folder:setwd(file.path(getwd(), path))# Collect the list of inputs in a list to be called later:dots <- list(...)# In the project template we've added 2 choices for the user:# * One allows them to select if the project will have a .gitignore file# * The other will create a folder, given a select input from the user# Check .gitignore argumentif(dots[[\"createGitignore\"]]) {git_ignores <-c('.Rhistory','.Rapp.history','.RData','.Ruserdata','.Rproj.user/','.Renviron')writeLines(paste(git_ignores, sep = '\\n'), '.gitignore')}# Check selected folderif(dots[[\"folder\"]] == \"Production\"){dir.create(\"production\", recursive = TRUE, showWarnings = FALSE)} else {dir.create(\"development\", recursive = TRUE, showWarnings = FALSE)}}"
},
{
"code": null,
"e": 6018,
"s": 5507,
"text": "With the function file created, the next step is to create the .dcf file. This file is responsible to create the boxes which the user will interact with. Along with the path that the user will type, you can create as many checkboxes/text inputs/select inputs as you wish to grant customization to the end-user. For our project, we'll create a checkbox, so the user can decide whether to create the .gitignore file and a select input, so the user can define the scope of the project (development or production);"
},
{
"code": null,
"e": 6155,
"s": 6018,
"text": "This solution (development or production) was just created for illustration purposes, it does not reflect any actual state of a project."
},
{
"code": null,
"e": 6318,
"s": 6155,
"text": "The .dcf file must be created within the package in the folder inst/rstudio/templates/project with the name of your choice, and it should follow the syntax below:"
},
{
"code": null,
"e": 6778,
"s": 6318,
"text": "Binding: create_projectTitle: My First Project TemplateOpenFiles: README.md# In the project you can also add icons (the icon should be a PNG, smaller than 64kb# and in the inst/rstudio/templates folder# Icon: name_of_pic.pngParameter: folderWidget: SelectInputLabel: Choose the scope of the projectFields: Production, DevelopmentDefault: ProductionPosition: leftParameter: createGitignoreWidget: CheckboxInputLabel: Create .gitignoreDefault: OnPosition: right"
},
{
"code": null,
"e": 7145,
"s": 6778,
"text": "Now that our package structure is created, we can use the devtools::document() function to create its documentation pages. Even though this package is mainly developed to be an add-in for RStudio, it's a good practice to document the package, before installing it in R, since it will search for any dependencies and packages that are needed for your project to work."
},
{
"code": null,
"e": 7385,
"s": 7145,
"text": "By running the devtools::install() function, within our package, we are going to install it and make it available in any other R Session from now on. This should be enough to make the add-in accessible by RStudio as a New Project Template."
},
{
"code": null,
"e": 7629,
"s": 7385,
"text": "After that, your project template should be available in RStudio’s list of projects. If you want to know more about different features to tweak your project template and add more customizability, please check the RStudio Project Template page."
},
{
"code": null,
"e": 8240,
"s": 7629,
"text": "Given the recent developments in data science and its integration with software engineering techniques, the need to standardize projects within teams comes handy to ensure that everybody can understand, and be understood by their pairs. This allows faster debugging of projects and mitigates the drawbacks of legacy code that is incomprehensible by people in the same teams. Of course, this feature alone will not help to document code, or standardize the way to write R scripts (please refer to The tidyverse style guide), but it is a tool that will help users to create patterns regarding project management."
}
] |
Engineering Intuitive Computer Vision | by Raveena Jayadev | Towards Data Science
|
Image classification is one of the hottest fields of machine learning, data science, and AI, and often used to benchmark certain types of AI algorithms — from logistic regression to deep neural networks.
But for now, I want to take your mind away from those hot techniques, and ask ourselves a question: if us humans saw an image of a handwritten character, or a dog or cat, how would our brains intuitively classify different types of images? Below is an example of digits in an image; “2”, “0”, “1” and “9”.
In the example above of digits (or numbers/numerals), how would our brains differentiate between, say, the 1 and 9 at the bottom? Well, intuitively our brains have a sort of “mental model” of what 1s look like, and a mental model of what 9s look like. For a new image of a digit, our brains can compare the digit based on each mental model and decide if it’s a 1, a 9, or an entirely different handwritten character. In fact, our mental model can do more than just classify: it can generate new instances of similar data. Show young children digits for the first time so their brains can form a mental model, and I’m pretty sure they can learn to draw new instances of, say a 1 or a 9, or the other digits in the photo above.
Now this type of decision-making, classification, is quite different from what you see in popular AI vision systems deployed around the world in cameras, hospitals, etc. — those rely on something called convolutional deep learning — check this visual demo out. While the convolutional-only layers of a convolutional neural network (CNN) might resemble specific parts of the vision system in our eyes according to this author, the actual decision making of a deep CNN network mainly comes from the thousands of tuned weights in the feedforward “final fully connected layer” of the network.
BTW, if you haven’t heard of neural networks or not familiar with how neural networks are used to classify images, I definitely recommend this video by Grant Sanderson on the 3Blue1Brown (3b1b) Youtube channel; his exposition and explanations are fantastic.
But the ML system we’ll be engineering to decide and classify digits will not be incorporating thousands of weights and parameters as is the case in artificial neural networks.
Before we go on, we need to clarify what a “mental model” of digits in the computer would look like.
What is a “Mental Model” in the Brain vs. Computer?
The short answer is that the actual mental models in the brain — well, we’re still figuring it out. There’s a lot we don’t know yet about the brain, and neuroscientists, cognitive scientists, and others have a lot to chime in.
However, there are theories growing about what mental models in the brain could resemble computationally. This article by computational neuroscientist Karl Friston talks more about the computational theory of how brains “call on an internal, mental generative model of the world” to infer and predict the causes behind the sensations signals it receives from the rest of the body, including the visual system. In this theory, the brain basically has to infer the causes of sensations based on a mental model it has about which probable causes lead to probable bodily perceptions. Friston also mentions that a wide range of real biological physiological and behavioral phenomena has been predicted by computational models like this. I’m leaving out a bunch of of details, so if you’re interested, read the article :)
In our machine learning case, we’re thankfully not having to deal with the whole host of body sensations — just 28x28 black and white images on a screen. But it’s still a challenging problem! — otherwise computer vision would have been “solved” already. So now the issue remains: how do we create, in a sense, a “mental generative model” the computer can hold as an object in its memory?
Generative Models as “Distributions”
Earlier I said how a “mental model”, or a generative model, allows you to basically create new instances of similar data. If I trained a generative model on, say, the digit 2, then the computer would be able to draw new instances of a 2. Having a model to create these instances is like a rough blueprint: it allows you to fill in the details and create different instances of houses, buildings, etc. This “rough blueprint” is called a distribution, because, intuitively, you basically are generating a collection of new data — and distribution is just another word for collection. The technical term for this is called a “probability distribution” (don’t worry, I won’t be revisiting the horrors of stats class!) because in your generated collection, some samples are more likely than others. For example if the computer were generating new instances of a “2”, then a sample of 2 with the “curly hook” missing at the top would be calculated as “less likely to resemble” a 2, than if it had a 2. Being less likely just means the model will generate that type of 2 less than the usual way a 2 looks.
Another way of looking at generative models in the language of machine learning is that they create models of “clusters” — they help cluster the data into specific regions. This would be called “unsupervised learning” — inferring structure within the data without any training labels to teach the machine.
Now that we know generative models are distributions, what we need to do first is see how to train a mental model over each of the 28x28 images of digit types (0,1,2,..9). In Python’s sci-kit learn library, there’s a function called density estimation model that will help us.
The Final Step in Classification: Inference
Now our computer calls on its own internal, generative “mental model” for each type of digit, and generate new types of images — and that’s all cool for sure! — but we still need to finish our first goal: classify and predict new images of digits it hasn’t seen before.
The key to classifying and predicting in our intuitive classifier is called inference. Our brains do it all the time, actually! Imagine the following question:
“You’re only gonna be eating greens for dinner today!” What does greens refer to?
Well, green is a color, and greens used in that plural way, it’s inferred that it refers to green objects — but what objects? our brains infer that the “objects” mean green vegetables like broccoli, spinach, kale, etc. because what other green things can be cooked and eaten? Our brains easily do inferences like this all the time, but getting a natural language processing (NLP) computer system to do inferences like this is very hard without billions of data points, parameters , and high energy usage— something human brains don’t really need. Luckily we’re not dealing with NLP inference for now, but don’t get me wrong — visual human-like inference is also a longstanding challenge in AI to overcome.
Anyway, back to vision. We want our computer to infer what the new digit will be, based on its “mental models” (distributions) for what digits look like. How would such an inference look like? Well, let’s say we were only dealing with two types of digits; a 2 and a 7. Suppose the computer has created distributions for what it thinks 28x28 images of 2 and 7 look like. When a new un-seen image comes in, how does it infer? The computer asks itself: under which mental model is the image more likely: my model of a 2, or a 7? If it’s more likely under a 2, then I’ll decide the image is a 2; otherwise I decide 7. In this way, the actual classification has turned into an if-else condition statement, a statement very pervasive in computer science languages from Python, to Java, to C. In an interesting spin, the decision is quite programmatic!
If you want to learn more about probability distributions or get familiarity, I recommend this video by Grant Sanderson from the “3Blue1Brown” Youtube channel, along with KhanAcademy videos on probability and statistics!
So...let’s begin the implementation! Feel free to take a pause before we dive right in!
Data Importing
The first order of business is to import the handwritten digit data from somewhere. For that, TensorFlow and Keras (the high-level language running on top of Tensorflow) have a beautifully organized collection of datasets, and Keras happens to have handwritten digits. The MNIST dataset can be found here (and its license is: CC BY-SA 3.0). To import the digit dataset, we just use the code:
from keras.datasets import mnist(x_train, y_train), (x_test, y_test) = mnist.load_data()
The MNIST dataset from Keras has 6,000 training samples per digit-class and we have 10 classes (so 60,000 training digits total), but we won’t be using that much data. Why? Well, for one, to show in principle we can create these generative models without as much data. But also, in the real world, 60,000 training data points might not exist — there might only be tens or a few hundred training data per class. So what we’re going to do is just select some random group of, say 6,000 digits from the training group. That gives us about 600 training digit samples per digit-class. That’s already a decrease of 90% of the original data! So if we can train generative “mental” models of each digit-class based on this smaller training set, we would be more data efficient.
We can randomly sample and create a new smaller training set with the following code:
np.random.seed(10)random_indices = np.random.choice(60000, size=6000, replace=False)random_x_train = x_train[random_indices, :]random_y_train = y_train[random_indices]
Feature Extraction
In order to create the models, we first have to do what’s called “feature engineering” (or “feature selection” if you’re working with data where the features are columns of a table). Why do we have to do this? Well, we have to realize something: these images live in a very, very high-dimensional space. Each image has 784 pixels, so as a vector, each image lives in the same 784-dimension space. We can’t even plot a graph in 4D space for that matter, so just give up on graphing in 784D space!
Working with data in high dimensions can be pretty difficult, and high-dimensional space does some weird, weird things — for example, spheres start to become “spiky” in 4D and higher: check out this video by Youtube channel Numberphile if you want to get a taste. You might have also heard of this phenomenon as the “curse of dimensionality” in machine learning.
If you have tabular data with features as columns, there are statistical ways to pre-select a smaller set of features based on statistical stuff like correlation and spread. If you don’t have tabular data, in general there are a few ways to do feature extraction. Luckily for us, there’s an amazing way to extract features — also called “dimension reduction” in the ML lingo — where we can save almost all the information about the data and go do all the way to 2D! It’s called UMAP — you can read the Python user manual here — and it was created in 2018 by mathematician Leland McInnes. UMAP stands for “Uniform Manifold Approximation and Projection” — if that’s a mouthful, don’t worry. (If you want an explanation, check this video out by Dr. Letitia) In the simplest way I can explain: the UMAP algorithm tries to connect the 784D image data by dots and lines depending on how clustered the data is (kinda like a social network!); then the whole graph is projected using topology, down into a lower-dimensional space. If you want to visualize the data points, you’ll have to project all the way down into 2D or 3D space, as I’ve done here below:
mapper = umap.UMAP(n_components=2, random_state=40).fit(random_x_train)umap_components = mapper.transform(random_x_train)
The distance you see up here between clusters reflects the fact that in some concrete way, certain digits like 0 and 7 are “far away” or “pretty separate” from 7 and 9. Of course you might say “Raveena! every digit is separate” and that’s true, but when handwriting digits, sometimes pen strokes can be confusing. And that’s the underlying structure UMAP is trying to compress into 2D so we can see it for ourselves!
(Disclaimer: Although the UMAP components show clear clustering in the scatterplot, the components axes themselves are not really human interpretable. However, the decision-making prediction process still is.)
Learning the “Mental” Generative Models
Now it’s time to learn the “mental models” — the generative probability models for each class of handwritten digit the computer will learn from data in order to make educated inferences at classification time. To create the actual model, we will use a technique in the sci-kit learn module called kernel density estimation (KDE). Imagine a data set of points, some of them close to each other, some more lonely and isolated. The estimation process is visualized below:
Once we learn the generative “mental” models for each digit, we can plot the models together and use 10 different colors to denote the digits 0–9 and their model shapes. Each “shapely blob” of color below represents the internal model the computer has learned from data for each digit, similar to how human brains have internal models for how digits should look like.
Now that our computer has generative models for each digit, it’s time to do...inference! What I want to emphasize in this project is two things: 1) we can program image classifier that infers and decides with internal “mental” models like a human brain can, and 2) this makes the AI system easy to troubleshoot. In an era where black-box deep AI systems are being deployed all over the world and often discriminate against marginalized people (article by Zachary Hay of Towards Data Science), it’s extremely hard to troubleshoot the discriminatory predictions those systems can make––and if you can’t troubleshoot, the system might as well be dangerous in my opinion.
Let me show you how we can check the system we’re creating in this article, though. Here’s the summarized code for how our system would infer and predict the content of an unseen test image:
def decision(sample, mental_models):... (summary) if likelihood_ratio <= 3.0: print("There's very little evidence that my first choice, is better than my second choice." return "I refuse to decide!" elif (likelihood_ratio > 4.0) and (likelihood_ratio <= 10.0): print("There is a bit of evidence that my first choice is better than my second choice") return "maybe digit {} over {}" else: print('There is strong evidence that my first choice, is better than my second choice.' return [confident machine choice]
(The machine prediction code looks just like an if-else statement (as said above), and the machine can predict with different levels of confidence, which is pretty intuitive!)
Now suppose we gave this AI system an image of a 3, and instead it predicted a 5. How could we troubleshoot the model to see how it made a mistake? Well, follow me here:
The machine decided from the if-else statement, that under its generative “mental” models, a 5 was more likely from the image data than a 3.
If-else decisions are pure logic, so that means the issue is not with the decision, but either the statistical mental models or the feature extraction. We can ask the machine to display the mental models and feature extraction, both as I did above. From there we can analyze the shortcomings of the models, and see how to adjust them.
In these 2 steps, we already identified where the problems might lie in this AI system if it made a mistake, By contrast, many of the deep learning systems connected to surveillance technologies around the world cannot even be troubleshooted in this way, and that makes for potentially dangerous AI.
I hope you, the reader, have come away from this article with a hope that 1) we can create AI systems that can potentially make decisions intuitively like humans can, and 2) we can potentially troubleshoot the AI model if it makes mistakes, and backtrack the error all the way into the internal parts of the system and understand what to fix and what to scrap.
Now admittedly, you might be telling me: “Raveena, the “UMAP” feature extraction doesn’t seem intuitive!” Yes, I know. The features are unfortunately not human-interpretable. However, there is a way to modify this system so that it can be interpretable, albeit in a different way. If you’re interested to know, this article in 2015 by MIT Prof. Joshua Tenenbaum talks about making a AI handwritten character classifier system using internal “mental models” that are quite similar to our probabilistic generative models. In fact, it’s so intuitive and data efficient, it only learns from 30 data points and imitates human handwritten symbols eerily well. In my opinion, it’s one of the most revolutionary creations for the future of AI.
By the way, here’s a link to my code if you want to see the full implementation details: my Github is public and free to access :)
References
Thomas Parr, Karl Friston, The Anatomy of Inference: Generative Models and Brain Structure (2018), Frontiers in Computational Neuroscience, 2018.S.R. Kheradpisheh et al., Deep Networks Can Resemble Human Feed-forward Vision in Invariant-Object Recognition (2016), Nature.Joshua Tenenbaum, Brendan Lake, Human-Level Concept Learning through Probabilistic Program Induction (2015), Science.
Thomas Parr, Karl Friston, The Anatomy of Inference: Generative Models and Brain Structure (2018), Frontiers in Computational Neuroscience, 2018.
S.R. Kheradpisheh et al., Deep Networks Can Resemble Human Feed-forward Vision in Invariant-Object Recognition (2016), Nature.
Joshua Tenenbaum, Brendan Lake, Human-Level Concept Learning through Probabilistic Program Induction (2015), Science.
|
[
{
"code": null,
"e": 376,
"s": 172,
"text": "Image classification is one of the hottest fields of machine learning, data science, and AI, and often used to benchmark certain types of AI algorithms — from logistic regression to deep neural networks."
},
{
"code": null,
"e": 682,
"s": 376,
"text": "But for now, I want to take your mind away from those hot techniques, and ask ourselves a question: if us humans saw an image of a handwritten character, or a dog or cat, how would our brains intuitively classify different types of images? Below is an example of digits in an image; “2”, “0”, “1” and “9”."
},
{
"code": null,
"e": 1408,
"s": 682,
"text": "In the example above of digits (or numbers/numerals), how would our brains differentiate between, say, the 1 and 9 at the bottom? Well, intuitively our brains have a sort of “mental model” of what 1s look like, and a mental model of what 9s look like. For a new image of a digit, our brains can compare the digit based on each mental model and decide if it’s a 1, a 9, or an entirely different handwritten character. In fact, our mental model can do more than just classify: it can generate new instances of similar data. Show young children digits for the first time so their brains can form a mental model, and I’m pretty sure they can learn to draw new instances of, say a 1 or a 9, or the other digits in the photo above."
},
{
"code": null,
"e": 1997,
"s": 1408,
"text": "Now this type of decision-making, classification, is quite different from what you see in popular AI vision systems deployed around the world in cameras, hospitals, etc. — those rely on something called convolutional deep learning — check this visual demo out. While the convolutional-only layers of a convolutional neural network (CNN) might resemble specific parts of the vision system in our eyes according to this author, the actual decision making of a deep CNN network mainly comes from the thousands of tuned weights in the feedforward “final fully connected layer” of the network."
},
{
"code": null,
"e": 2255,
"s": 1997,
"text": "BTW, if you haven’t heard of neural networks or not familiar with how neural networks are used to classify images, I definitely recommend this video by Grant Sanderson on the 3Blue1Brown (3b1b) Youtube channel; his exposition and explanations are fantastic."
},
{
"code": null,
"e": 2432,
"s": 2255,
"text": "But the ML system we’ll be engineering to decide and classify digits will not be incorporating thousands of weights and parameters as is the case in artificial neural networks."
},
{
"code": null,
"e": 2533,
"s": 2432,
"text": "Before we go on, we need to clarify what a “mental model” of digits in the computer would look like."
},
{
"code": null,
"e": 2585,
"s": 2533,
"text": "What is a “Mental Model” in the Brain vs. Computer?"
},
{
"code": null,
"e": 2812,
"s": 2585,
"text": "The short answer is that the actual mental models in the brain — well, we’re still figuring it out. There’s a lot we don’t know yet about the brain, and neuroscientists, cognitive scientists, and others have a lot to chime in."
},
{
"code": null,
"e": 3628,
"s": 2812,
"text": "However, there are theories growing about what mental models in the brain could resemble computationally. This article by computational neuroscientist Karl Friston talks more about the computational theory of how brains “call on an internal, mental generative model of the world” to infer and predict the causes behind the sensations signals it receives from the rest of the body, including the visual system. In this theory, the brain basically has to infer the causes of sensations based on a mental model it has about which probable causes lead to probable bodily perceptions. Friston also mentions that a wide range of real biological physiological and behavioral phenomena has been predicted by computational models like this. I’m leaving out a bunch of of details, so if you’re interested, read the article :)"
},
{
"code": null,
"e": 4016,
"s": 3628,
"text": "In our machine learning case, we’re thankfully not having to deal with the whole host of body sensations — just 28x28 black and white images on a screen. But it’s still a challenging problem! — otherwise computer vision would have been “solved” already. So now the issue remains: how do we create, in a sense, a “mental generative model” the computer can hold as an object in its memory?"
},
{
"code": null,
"e": 4053,
"s": 4016,
"text": "Generative Models as “Distributions”"
},
{
"code": null,
"e": 5152,
"s": 4053,
"text": "Earlier I said how a “mental model”, or a generative model, allows you to basically create new instances of similar data. If I trained a generative model on, say, the digit 2, then the computer would be able to draw new instances of a 2. Having a model to create these instances is like a rough blueprint: it allows you to fill in the details and create different instances of houses, buildings, etc. This “rough blueprint” is called a distribution, because, intuitively, you basically are generating a collection of new data — and distribution is just another word for collection. The technical term for this is called a “probability distribution” (don’t worry, I won’t be revisiting the horrors of stats class!) because in your generated collection, some samples are more likely than others. For example if the computer were generating new instances of a “2”, then a sample of 2 with the “curly hook” missing at the top would be calculated as “less likely to resemble” a 2, than if it had a 2. Being less likely just means the model will generate that type of 2 less than the usual way a 2 looks."
},
{
"code": null,
"e": 5458,
"s": 5152,
"text": "Another way of looking at generative models in the language of machine learning is that they create models of “clusters” — they help cluster the data into specific regions. This would be called “unsupervised learning” — inferring structure within the data without any training labels to teach the machine."
},
{
"code": null,
"e": 5735,
"s": 5458,
"text": "Now that we know generative models are distributions, what we need to do first is see how to train a mental model over each of the 28x28 images of digit types (0,1,2,..9). In Python’s sci-kit learn library, there’s a function called density estimation model that will help us."
},
{
"code": null,
"e": 5779,
"s": 5735,
"text": "The Final Step in Classification: Inference"
},
{
"code": null,
"e": 6049,
"s": 5779,
"text": "Now our computer calls on its own internal, generative “mental model” for each type of digit, and generate new types of images — and that’s all cool for sure! — but we still need to finish our first goal: classify and predict new images of digits it hasn’t seen before."
},
{
"code": null,
"e": 6209,
"s": 6049,
"text": "The key to classifying and predicting in our intuitive classifier is called inference. Our brains do it all the time, actually! Imagine the following question:"
},
{
"code": null,
"e": 6291,
"s": 6209,
"text": "“You’re only gonna be eating greens for dinner today!” What does greens refer to?"
},
{
"code": null,
"e": 6997,
"s": 6291,
"text": "Well, green is a color, and greens used in that plural way, it’s inferred that it refers to green objects — but what objects? our brains infer that the “objects” mean green vegetables like broccoli, spinach, kale, etc. because what other green things can be cooked and eaten? Our brains easily do inferences like this all the time, but getting a natural language processing (NLP) computer system to do inferences like this is very hard without billions of data points, parameters , and high energy usage— something human brains don’t really need. Luckily we’re not dealing with NLP inference for now, but don’t get me wrong — visual human-like inference is also a longstanding challenge in AI to overcome."
},
{
"code": null,
"e": 7843,
"s": 6997,
"text": "Anyway, back to vision. We want our computer to infer what the new digit will be, based on its “mental models” (distributions) for what digits look like. How would such an inference look like? Well, let’s say we were only dealing with two types of digits; a 2 and a 7. Suppose the computer has created distributions for what it thinks 28x28 images of 2 and 7 look like. When a new un-seen image comes in, how does it infer? The computer asks itself: under which mental model is the image more likely: my model of a 2, or a 7? If it’s more likely under a 2, then I’ll decide the image is a 2; otherwise I decide 7. In this way, the actual classification has turned into an if-else condition statement, a statement very pervasive in computer science languages from Python, to Java, to C. In an interesting spin, the decision is quite programmatic!"
},
{
"code": null,
"e": 8064,
"s": 7843,
"text": "If you want to learn more about probability distributions or get familiarity, I recommend this video by Grant Sanderson from the “3Blue1Brown” Youtube channel, along with KhanAcademy videos on probability and statistics!"
},
{
"code": null,
"e": 8152,
"s": 8064,
"text": "So...let’s begin the implementation! Feel free to take a pause before we dive right in!"
},
{
"code": null,
"e": 8167,
"s": 8152,
"text": "Data Importing"
},
{
"code": null,
"e": 8559,
"s": 8167,
"text": "The first order of business is to import the handwritten digit data from somewhere. For that, TensorFlow and Keras (the high-level language running on top of Tensorflow) have a beautifully organized collection of datasets, and Keras happens to have handwritten digits. The MNIST dataset can be found here (and its license is: CC BY-SA 3.0). To import the digit dataset, we just use the code:"
},
{
"code": null,
"e": 8648,
"s": 8559,
"text": "from keras.datasets import mnist(x_train, y_train), (x_test, y_test) = mnist.load_data()"
},
{
"code": null,
"e": 9418,
"s": 8648,
"text": "The MNIST dataset from Keras has 6,000 training samples per digit-class and we have 10 classes (so 60,000 training digits total), but we won’t be using that much data. Why? Well, for one, to show in principle we can create these generative models without as much data. But also, in the real world, 60,000 training data points might not exist — there might only be tens or a few hundred training data per class. So what we’re going to do is just select some random group of, say 6,000 digits from the training group. That gives us about 600 training digit samples per digit-class. That’s already a decrease of 90% of the original data! So if we can train generative “mental” models of each digit-class based on this smaller training set, we would be more data efficient."
},
{
"code": null,
"e": 9504,
"s": 9418,
"text": "We can randomly sample and create a new smaller training set with the following code:"
},
{
"code": null,
"e": 9672,
"s": 9504,
"text": "np.random.seed(10)random_indices = np.random.choice(60000, size=6000, replace=False)random_x_train = x_train[random_indices, :]random_y_train = y_train[random_indices]"
},
{
"code": null,
"e": 9691,
"s": 9672,
"text": "Feature Extraction"
},
{
"code": null,
"e": 10187,
"s": 9691,
"text": "In order to create the models, we first have to do what’s called “feature engineering” (or “feature selection” if you’re working with data where the features are columns of a table). Why do we have to do this? Well, we have to realize something: these images live in a very, very high-dimensional space. Each image has 784 pixels, so as a vector, each image lives in the same 784-dimension space. We can’t even plot a graph in 4D space for that matter, so just give up on graphing in 784D space!"
},
{
"code": null,
"e": 10550,
"s": 10187,
"text": "Working with data in high dimensions can be pretty difficult, and high-dimensional space does some weird, weird things — for example, spheres start to become “spiky” in 4D and higher: check out this video by Youtube channel Numberphile if you want to get a taste. You might have also heard of this phenomenon as the “curse of dimensionality” in machine learning."
},
{
"code": null,
"e": 11700,
"s": 10550,
"text": "If you have tabular data with features as columns, there are statistical ways to pre-select a smaller set of features based on statistical stuff like correlation and spread. If you don’t have tabular data, in general there are a few ways to do feature extraction. Luckily for us, there’s an amazing way to extract features — also called “dimension reduction” in the ML lingo — where we can save almost all the information about the data and go do all the way to 2D! It’s called UMAP — you can read the Python user manual here — and it was created in 2018 by mathematician Leland McInnes. UMAP stands for “Uniform Manifold Approximation and Projection” — if that’s a mouthful, don’t worry. (If you want an explanation, check this video out by Dr. Letitia) In the simplest way I can explain: the UMAP algorithm tries to connect the 784D image data by dots and lines depending on how clustered the data is (kinda like a social network!); then the whole graph is projected using topology, down into a lower-dimensional space. If you want to visualize the data points, you’ll have to project all the way down into 2D or 3D space, as I’ve done here below:"
},
{
"code": null,
"e": 11822,
"s": 11700,
"text": "mapper = umap.UMAP(n_components=2, random_state=40).fit(random_x_train)umap_components = mapper.transform(random_x_train)"
},
{
"code": null,
"e": 12239,
"s": 11822,
"text": "The distance you see up here between clusters reflects the fact that in some concrete way, certain digits like 0 and 7 are “far away” or “pretty separate” from 7 and 9. Of course you might say “Raveena! every digit is separate” and that’s true, but when handwriting digits, sometimes pen strokes can be confusing. And that’s the underlying structure UMAP is trying to compress into 2D so we can see it for ourselves!"
},
{
"code": null,
"e": 12449,
"s": 12239,
"text": "(Disclaimer: Although the UMAP components show clear clustering in the scatterplot, the components axes themselves are not really human interpretable. However, the decision-making prediction process still is.)"
},
{
"code": null,
"e": 12489,
"s": 12449,
"text": "Learning the “Mental” Generative Models"
},
{
"code": null,
"e": 12958,
"s": 12489,
"text": "Now it’s time to learn the “mental models” — the generative probability models for each class of handwritten digit the computer will learn from data in order to make educated inferences at classification time. To create the actual model, we will use a technique in the sci-kit learn module called kernel density estimation (KDE). Imagine a data set of points, some of them close to each other, some more lonely and isolated. The estimation process is visualized below:"
},
{
"code": null,
"e": 13326,
"s": 12958,
"text": "Once we learn the generative “mental” models for each digit, we can plot the models together and use 10 different colors to denote the digits 0–9 and their model shapes. Each “shapely blob” of color below represents the internal model the computer has learned from data for each digit, similar to how human brains have internal models for how digits should look like."
},
{
"code": null,
"e": 13994,
"s": 13326,
"text": "Now that our computer has generative models for each digit, it’s time to do...inference! What I want to emphasize in this project is two things: 1) we can program image classifier that infers and decides with internal “mental” models like a human brain can, and 2) this makes the AI system easy to troubleshoot. In an era where black-box deep AI systems are being deployed all over the world and often discriminate against marginalized people (article by Zachary Hay of Towards Data Science), it’s extremely hard to troubleshoot the discriminatory predictions those systems can make––and if you can’t troubleshoot, the system might as well be dangerous in my opinion."
},
{
"code": null,
"e": 14185,
"s": 13994,
"text": "Let me show you how we can check the system we’re creating in this article, though. Here’s the summarized code for how our system would infer and predict the content of an unseen test image:"
},
{
"code": null,
"e": 14734,
"s": 14185,
"text": "def decision(sample, mental_models):... (summary) if likelihood_ratio <= 3.0: print(\"There's very little evidence that my first choice, is better than my second choice.\" return \"I refuse to decide!\" elif (likelihood_ratio > 4.0) and (likelihood_ratio <= 10.0): print(\"There is a bit of evidence that my first choice is better than my second choice\") return \"maybe digit {} over {}\" else: print('There is strong evidence that my first choice, is better than my second choice.' return [confident machine choice]"
},
{
"code": null,
"e": 14910,
"s": 14734,
"text": "(The machine prediction code looks just like an if-else statement (as said above), and the machine can predict with different levels of confidence, which is pretty intuitive!)"
},
{
"code": null,
"e": 15080,
"s": 14910,
"text": "Now suppose we gave this AI system an image of a 3, and instead it predicted a 5. How could we troubleshoot the model to see how it made a mistake? Well, follow me here:"
},
{
"code": null,
"e": 15221,
"s": 15080,
"text": "The machine decided from the if-else statement, that under its generative “mental” models, a 5 was more likely from the image data than a 3."
},
{
"code": null,
"e": 15556,
"s": 15221,
"text": "If-else decisions are pure logic, so that means the issue is not with the decision, but either the statistical mental models or the feature extraction. We can ask the machine to display the mental models and feature extraction, both as I did above. From there we can analyze the shortcomings of the models, and see how to adjust them."
},
{
"code": null,
"e": 15856,
"s": 15556,
"text": "In these 2 steps, we already identified where the problems might lie in this AI system if it made a mistake, By contrast, many of the deep learning systems connected to surveillance technologies around the world cannot even be troubleshooted in this way, and that makes for potentially dangerous AI."
},
{
"code": null,
"e": 16217,
"s": 15856,
"text": "I hope you, the reader, have come away from this article with a hope that 1) we can create AI systems that can potentially make decisions intuitively like humans can, and 2) we can potentially troubleshoot the AI model if it makes mistakes, and backtrack the error all the way into the internal parts of the system and understand what to fix and what to scrap."
},
{
"code": null,
"e": 16953,
"s": 16217,
"text": "Now admittedly, you might be telling me: “Raveena, the “UMAP” feature extraction doesn’t seem intuitive!” Yes, I know. The features are unfortunately not human-interpretable. However, there is a way to modify this system so that it can be interpretable, albeit in a different way. If you’re interested to know, this article in 2015 by MIT Prof. Joshua Tenenbaum talks about making a AI handwritten character classifier system using internal “mental models” that are quite similar to our probabilistic generative models. In fact, it’s so intuitive and data efficient, it only learns from 30 data points and imitates human handwritten symbols eerily well. In my opinion, it’s one of the most revolutionary creations for the future of AI."
},
{
"code": null,
"e": 17084,
"s": 16953,
"text": "By the way, here’s a link to my code if you want to see the full implementation details: my Github is public and free to access :)"
},
{
"code": null,
"e": 17095,
"s": 17084,
"text": "References"
},
{
"code": null,
"e": 17484,
"s": 17095,
"text": "Thomas Parr, Karl Friston, The Anatomy of Inference: Generative Models and Brain Structure (2018), Frontiers in Computational Neuroscience, 2018.S.R. Kheradpisheh et al., Deep Networks Can Resemble Human Feed-forward Vision in Invariant-Object Recognition (2016), Nature.Joshua Tenenbaum, Brendan Lake, Human-Level Concept Learning through Probabilistic Program Induction (2015), Science."
},
{
"code": null,
"e": 17630,
"s": 17484,
"text": "Thomas Parr, Karl Friston, The Anatomy of Inference: Generative Models and Brain Structure (2018), Frontiers in Computational Neuroscience, 2018."
},
{
"code": null,
"e": 17757,
"s": 17630,
"text": "S.R. Kheradpisheh et al., Deep Networks Can Resemble Human Feed-forward Vision in Invariant-Object Recognition (2016), Nature."
}
] |
How to get the magnitude of a vector in NumPy? - GeeksforGeeks
|
29 Aug, 2020
The fundamental feature of linear algebra are vectors, these are the objects having both direction and magnitude. In Python, NumPy arrays can be used to depict a vector.
There are mainly two ways of getting the magnitude of vector:
By defining an explicit function which computes the magnitude of a given vector based on the below mathematical formula:if V is vector such that, V = (a, b, c)
then ||V|| = ?(a*a + b*b + c*c)
Here are some programs which computes the magnitude of a vector following the above approach:# program to compute magnitude of a vector # importing required librariesimport numpyimport math # function defination to compute magnitude o f the vectordef magnitude(vector): return math.sqrt(sum(pow(element, 2) for element in vector)) # displaying the original vectorv = numpy.array([0, 1, 2, 3, 4])print('Vector:', v) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', magnitude(v))Output:Vector: [0 1 2 3 4]
Magnitude of the Vector: 5.477225575051661
Below is another example with the same approach:# program to compute magnitude of a vector # importing required librariesimport numpyimport math # function defination to compute magnitude o f the vectordef magnitude(vector): return math.sqrt(sum(pow(element, 2) for element in vector)) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', magnitude(numpy.array([1, 2, 3])))Output:Magnitude of the Vector: 3.7416573867739413
if V is vector such that, V = (a, b, c)
then ||V|| = ?(a*a + b*b + c*c)
Here are some programs which computes the magnitude of a vector following the above approach:
# program to compute magnitude of a vector # importing required librariesimport numpyimport math # function defination to compute magnitude o f the vectordef magnitude(vector): return math.sqrt(sum(pow(element, 2) for element in vector)) # displaying the original vectorv = numpy.array([0, 1, 2, 3, 4])print('Vector:', v) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', magnitude(v))
Output:
Vector: [0 1 2 3 4]
Magnitude of the Vector: 5.477225575051661
Below is another example with the same approach:
# program to compute magnitude of a vector # importing required librariesimport numpyimport math # function defination to compute magnitude o f the vectordef magnitude(vector): return math.sqrt(sum(pow(element, 2) for element in vector)) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', magnitude(numpy.array([1, 2, 3])))
Output:
Magnitude of the Vector: 3.7416573867739413
By using the norm() method in linalg module of NumPy library. The Linear Algebra module of NumPy offers various methods to apply linear algebra on any NumPy array. Below are some programs which use numpy.linalg.norm() to compute the magnitude of a vector:# program to compute magnitude of a vector # importing required librariesimport numpy # displaying the original vectorv = numpy.array([1, 2, 3])print('Vector:', v) # computing and displaying the magnitude of# the vector using norm() methodprint('Magnitude of the Vector:', numpy.linalg.norm(v))Output:Vector: [1 2 3]
Magnitude of the Vector: 3.7416573867739413
An additional argument ord can be used to compute the nth order of the norm() of a vector.# program to compute the nth order of the # magnitude of a vector # importing required librariesimport numpy # displaying the original vectorv = numpy.array([0, 1, 2, 3, 4])print('Vector:', v) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', numpy.linalg.norm(v)) # Computing the nth order of the magnitude of vectorprint('ord is 0: ', numpy.linalg.norm(v, ord = 0))print('ord is 1: ', numpy.linalg.norm(v, ord = 1))print('ord is 2: ', numpy.linalg.norm(v, ord = 2))print('ord is 3: ', numpy.linalg.norm(v, ord = 3))print('ord is 4: ', numpy.linalg.norm(v, ord = 4))Output:Vector: [0 1 2 3 4]
Magnitude of the Vector: 5.477225575051661
ord is 0: 4.0
ord is 1: 10.0
ord is 2: 5.477225575051661
ord is 3: 4.641588833612778
ord is 4: 4.337613136533361
# program to compute magnitude of a vector # importing required librariesimport numpy # displaying the original vectorv = numpy.array([1, 2, 3])print('Vector:', v) # computing and displaying the magnitude of# the vector using norm() methodprint('Magnitude of the Vector:', numpy.linalg.norm(v))
Output:
Vector: [1 2 3]
Magnitude of the Vector: 3.7416573867739413
An additional argument ord can be used to compute the nth order of the norm() of a vector.
# program to compute the nth order of the # magnitude of a vector # importing required librariesimport numpy # displaying the original vectorv = numpy.array([0, 1, 2, 3, 4])print('Vector:', v) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', numpy.linalg.norm(v)) # Computing the nth order of the magnitude of vectorprint('ord is 0: ', numpy.linalg.norm(v, ord = 0))print('ord is 1: ', numpy.linalg.norm(v, ord = 1))print('ord is 2: ', numpy.linalg.norm(v, ord = 2))print('ord is 3: ', numpy.linalg.norm(v, ord = 3))print('ord is 4: ', numpy.linalg.norm(v, ord = 4))
Output:
Vector: [0 1 2 3 4]
Magnitude of the Vector: 5.477225575051661
ord is 0: 4.0
ord is 1: 10.0
ord is 2: 5.477225575051661
ord is 3: 4.641588833612778
ord is 4: 4.337613136533361
Python numpy-Linear Algebra
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 23779,
"s": 23751,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 23949,
"s": 23779,
"text": "The fundamental feature of linear algebra are vectors, these are the objects having both direction and magnitude. In Python, NumPy arrays can be used to depict a vector."
},
{
"code": null,
"e": 24011,
"s": 23949,
"text": "There are mainly two ways of getting the magnitude of vector:"
},
{
"code": null,
"e": 25264,
"s": 24011,
"text": "By defining an explicit function which computes the magnitude of a given vector based on the below mathematical formula:if V is vector such that, V = (a, b, c)\nthen ||V|| = ?(a*a + b*b + c*c)\nHere are some programs which computes the magnitude of a vector following the above approach:# program to compute magnitude of a vector # importing required librariesimport numpyimport math # function defination to compute magnitude o f the vectordef magnitude(vector): return math.sqrt(sum(pow(element, 2) for element in vector)) # displaying the original vectorv = numpy.array([0, 1, 2, 3, 4])print('Vector:', v) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', magnitude(v))Output:Vector: [0 1 2 3 4]\nMagnitude of the Vector: 5.477225575051661\nBelow is another example with the same approach:# program to compute magnitude of a vector # importing required librariesimport numpyimport math # function defination to compute magnitude o f the vectordef magnitude(vector): return math.sqrt(sum(pow(element, 2) for element in vector)) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', magnitude(numpy.array([1, 2, 3])))Output:Magnitude of the Vector: 3.7416573867739413\n"
},
{
"code": null,
"e": 25337,
"s": 25264,
"text": "if V is vector such that, V = (a, b, c)\nthen ||V|| = ?(a*a + b*b + c*c)\n"
},
{
"code": null,
"e": 25431,
"s": 25337,
"text": "Here are some programs which computes the magnitude of a vector following the above approach:"
},
{
"code": "# program to compute magnitude of a vector # importing required librariesimport numpyimport math # function defination to compute magnitude o f the vectordef magnitude(vector): return math.sqrt(sum(pow(element, 2) for element in vector)) # displaying the original vectorv = numpy.array([0, 1, 2, 3, 4])print('Vector:', v) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', magnitude(v))",
"e": 25863,
"s": 25431,
"text": null
},
{
"code": null,
"e": 25871,
"s": 25863,
"text": "Output:"
},
{
"code": null,
"e": 25935,
"s": 25871,
"text": "Vector: [0 1 2 3 4]\nMagnitude of the Vector: 5.477225575051661\n"
},
{
"code": null,
"e": 25984,
"s": 25935,
"text": "Below is another example with the same approach:"
},
{
"code": "# program to compute magnitude of a vector # importing required librariesimport numpyimport math # function defination to compute magnitude o f the vectordef magnitude(vector): return math.sqrt(sum(pow(element, 2) for element in vector)) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', magnitude(numpy.array([1, 2, 3])))",
"e": 26352,
"s": 25984,
"text": null
},
{
"code": null,
"e": 26360,
"s": 26352,
"text": "Output:"
},
{
"code": null,
"e": 26405,
"s": 26360,
"text": "Magnitude of the Vector: 3.7416573867739413\n"
},
{
"code": null,
"e": 27912,
"s": 26405,
"text": "By using the norm() method in linalg module of NumPy library. The Linear Algebra module of NumPy offers various methods to apply linear algebra on any NumPy array. Below are some programs which use numpy.linalg.norm() to compute the magnitude of a vector:# program to compute magnitude of a vector # importing required librariesimport numpy # displaying the original vectorv = numpy.array([1, 2, 3])print('Vector:', v) # computing and displaying the magnitude of# the vector using norm() methodprint('Magnitude of the Vector:', numpy.linalg.norm(v))Output:Vector: [1 2 3]\nMagnitude of the Vector: 3.7416573867739413\nAn additional argument ord can be used to compute the nth order of the norm() of a vector.# program to compute the nth order of the # magnitude of a vector # importing required librariesimport numpy # displaying the original vectorv = numpy.array([0, 1, 2, 3, 4])print('Vector:', v) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', numpy.linalg.norm(v)) # Computing the nth order of the magnitude of vectorprint('ord is 0: ', numpy.linalg.norm(v, ord = 0))print('ord is 1: ', numpy.linalg.norm(v, ord = 1))print('ord is 2: ', numpy.linalg.norm(v, ord = 2))print('ord is 3: ', numpy.linalg.norm(v, ord = 3))print('ord is 4: ', numpy.linalg.norm(v, ord = 4))Output:Vector: [0 1 2 3 4]\nMagnitude of the Vector: 5.477225575051661\nord is 0: 4.0\nord is 1: 10.0\nord is 2: 5.477225575051661\nord is 3: 4.641588833612778\nord is 4: 4.337613136533361\n"
},
{
"code": "# program to compute magnitude of a vector # importing required librariesimport numpy # displaying the original vectorv = numpy.array([1, 2, 3])print('Vector:', v) # computing and displaying the magnitude of# the vector using norm() methodprint('Magnitude of the Vector:', numpy.linalg.norm(v))",
"e": 28210,
"s": 27912,
"text": null
},
{
"code": null,
"e": 28218,
"s": 28210,
"text": "Output:"
},
{
"code": null,
"e": 28279,
"s": 28218,
"text": "Vector: [1 2 3]\nMagnitude of the Vector: 3.7416573867739413\n"
},
{
"code": null,
"e": 28370,
"s": 28279,
"text": "An additional argument ord can be used to compute the nth order of the norm() of a vector."
},
{
"code": "# program to compute the nth order of the # magnitude of a vector # importing required librariesimport numpy # displaying the original vectorv = numpy.array([0, 1, 2, 3, 4])print('Vector:', v) # computing and displaying the magnitude of the vectorprint('Magnitude of the Vector:', numpy.linalg.norm(v)) # Computing the nth order of the magnitude of vectorprint('ord is 0: ', numpy.linalg.norm(v, ord = 0))print('ord is 1: ', numpy.linalg.norm(v, ord = 1))print('ord is 2: ', numpy.linalg.norm(v, ord = 2))print('ord is 3: ', numpy.linalg.norm(v, ord = 3))print('ord is 4: ', numpy.linalg.norm(v, ord = 4))",
"e": 28980,
"s": 28370,
"text": null
},
{
"code": null,
"e": 28988,
"s": 28980,
"text": "Output:"
},
{
"code": null,
"e": 29170,
"s": 28988,
"text": "Vector: [0 1 2 3 4]\nMagnitude of the Vector: 5.477225575051661\nord is 0: 4.0\nord is 1: 10.0\nord is 2: 5.477225575051661\nord is 3: 4.641588833612778\nord is 4: 4.337613136533361\n"
},
{
"code": null,
"e": 29198,
"s": 29170,
"text": "Python numpy-Linear Algebra"
},
{
"code": null,
"e": 29211,
"s": 29198,
"text": "Python-numpy"
},
{
"code": null,
"e": 29218,
"s": 29211,
"text": "Python"
},
{
"code": null,
"e": 29316,
"s": 29218,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29325,
"s": 29316,
"text": "Comments"
},
{
"code": null,
"e": 29338,
"s": 29325,
"text": "Old Comments"
},
{
"code": null,
"e": 29356,
"s": 29338,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29391,
"s": 29356,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29413,
"s": 29391,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29445,
"s": 29413,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29475,
"s": 29445,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29517,
"s": 29475,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29543,
"s": 29517,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29586,
"s": 29543,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29630,
"s": 29586,
"text": "Reading and Writing to text files in Python"
}
] |
Perl pos Function
|
This function is used to find the offset or position of the last matched substring. If SCALAR is specified, it will return the offset of the last match on that scalar variable.
You can also assign a value to this function (for example, pos($foo) = 20;) in order to change the starting point of the next match operation.
Offset is counter starting from zeroth position.
Following is the simple syntax for this function −
pos EXPR
pos
This function returns Integer in Scalar context and then positions of all the matches within the regular expression in List context.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w
$name = "This is alpha beta gamma";
$name =~ m/alpha/g;
print("pos() ", pos($name), "\n");
When above code is executed, it produces the following result −
pos() 13
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2397,
"s": 2220,
"text": "This function is used to find the offset or position of the last matched substring. If SCALAR is specified, it will return the offset of the last match on that scalar variable."
},
{
"code": null,
"e": 2540,
"s": 2397,
"text": "You can also assign a value to this function (for example, pos($foo) = 20;) in order to change the starting point of the next match operation."
},
{
"code": null,
"e": 2589,
"s": 2540,
"text": "Offset is counter starting from zeroth position."
},
{
"code": null,
"e": 2640,
"s": 2589,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2655,
"s": 2640,
"text": "pos EXPR\n\npos\n"
},
{
"code": null,
"e": 2788,
"s": 2655,
"text": "This function returns Integer in Scalar context and then positions of all the matches within the regular expression in List context."
},
{
"code": null,
"e": 2844,
"s": 2788,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 2956,
"s": 2844,
"text": "#!/usr/bin/perl -w\n\n$name = \"This is alpha beta gamma\";\n$name =~ m/alpha/g;\n\nprint(\"pos() \", pos($name), \"\\n\");"
},
{
"code": null,
"e": 3020,
"s": 2956,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3030,
"s": 3020,
"text": "pos() 13\n"
},
{
"code": null,
"e": 3065,
"s": 3030,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3079,
"s": 3065,
"text": " Devi Killada"
},
{
"code": null,
"e": 3114,
"s": 3079,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3134,
"s": 3114,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3167,
"s": 3134,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3183,
"s": 3167,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3216,
"s": 3183,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3233,
"s": 3216,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3266,
"s": 3233,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3289,
"s": 3266,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3324,
"s": 3289,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3347,
"s": 3324,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3354,
"s": 3347,
"text": " Print"
},
{
"code": null,
"e": 3365,
"s": 3354,
"text": " Add Notes"
}
] |
Find records from one MySQL table which don't exist in another?
|
To find the records from one MySQL table which don’t exist in another table we can use the
subquery for the table which does not have the records. This can be better understood using the
given steps −
First a table is created using the create command. The table name is ‘PresentHistory’ and it has
two columns. This is given as follows −
mysql> CREATE table PresentHistory
-> (
-> HisID int,
-> HisName varchar(100)
-> );
Query OK, 0 rows affected (0.54 sec)
After creating the table, some records are inserted that will be present in the second table as
well. This is done with the help of the insert command as follows −
mysql> INSERT into PresentHistory values(1,'John');
Query OK, 1 row affected (0.13 sec)
mysql> INSERT into PresentHistory values(2,'Bob');
Query OK, 1 row affected (0.15 sec)
After inserting the records successfully, they are displayed with the select statement as follows −
mysql> SELECT * from PresentHistory;
After executing the above query, the output obtained is.
+-------+---------+
| HisID | HisName |
+-------+---------+
| 1 | John |
| 2 | Bob |
+-------+---------+
2 rows in set (0.00 sec)
Now, a second table is created using the create command. This table is named ‘PastHistory’
and contains two columns as given below.
mysql> CREATE table PastHistory
-> (
-> PastId int,
-> PastName varchar(100)
-> );
Query OK, 0 rows affected (0.74 sec)
After creating the table, some records which are present in first table and some records which
are not present in first table are inserted in PastHistory table.
mysql> INSERT into PastHistory values(1,'John');
Query OK, 1 row affected (0.13 sec)
mysql> INSERT into PastHistory values(2,'Bob');
Query OK, 1 row affected (0.13 sec)
mysql> INSERT into PastHistory values(3,'Carol');
Query OK, 1 row affected (0.17 sec)
mysql> INSERT into PastHistory values(4,'Jason');
Query OK, 1 row affected (0.16 sec)
Now, there are 4 records in the second table. Out of these, 2 records are from the first table and
2 records are different in second table.
The records in the second table are seen with the help of the select statement as follows −
mysql> SELECT * from PastHistory;
The output of the above query is
+--------+----------+
| PastId | PastName |
+--------+----------+
| 1 | John |
| 2 | Bob |
| 3 | Carol |
| 4 | Jason |
+--------+----------+
4 rows in set (0.00 sec)
The syntax to check the records from one table that don’t exist in the second table is given as
follows −
SELECT * from yourSecondTableName where columnNamefromSecondtable NOT IN
(SELECT columnNamefromfirsttable from yourFirstTableName);
The given query is used to get the records that are distinct in the second table −
mysql> SELECT * from PastHistory where PastName not in (select HisName from
PresentHistory);
The output of the above query is as follows −
+--------+----------+
| PastId | PastName |
+--------+----------+
| 3 | Carol |
| 4 | Jason |
+--------+----------+
2 rows in set (0.00 sec)
From the above output it is clear that we have found two records which are not present in the
first table.
|
[
{
"code": null,
"e": 1263,
"s": 1062,
"text": "To find the records from one MySQL table which don’t exist in another table we can use the\nsubquery for the table which does not have the records. This can be better understood using the\ngiven steps −"
},
{
"code": null,
"e": 1400,
"s": 1263,
"text": "First a table is created using the create command. The table name is ‘PresentHistory’ and it has\ntwo columns. This is given as follows −"
},
{
"code": null,
"e": 1521,
"s": 1400,
"text": "mysql> CREATE table PresentHistory\n-> (\n-> HisID int,\n-> HisName varchar(100)\n-> );\nQuery OK, 0 rows affected (0.54 sec)"
},
{
"code": null,
"e": 1685,
"s": 1521,
"text": "After creating the table, some records are inserted that will be present in the second table as\nwell. This is done with the help of the insert command as follows −"
},
{
"code": null,
"e": 1861,
"s": 1685,
"text": "mysql> INSERT into PresentHistory values(1,'John');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> INSERT into PresentHistory values(2,'Bob');\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 1961,
"s": 1861,
"text": "After inserting the records successfully, they are displayed with the select statement as follows −"
},
{
"code": null,
"e": 1999,
"s": 1961,
"text": "mysql> SELECT * from PresentHistory;\n"
},
{
"code": null,
"e": 2056,
"s": 1999,
"text": "After executing the above query, the output obtained is."
},
{
"code": null,
"e": 2201,
"s": 2056,
"text": "+-------+---------+\n| HisID | HisName |\n+-------+---------+\n| 1 | John |\n| 2 | Bob |\n+-------+---------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2333,
"s": 2201,
"text": "Now, a second table is created using the create command. This table is named ‘PastHistory’\nand contains two columns as given below."
},
{
"code": null,
"e": 2453,
"s": 2333,
"text": "mysql> CREATE table PastHistory\n-> (\n-> PastId int,\n-> PastName varchar(100)\n-> );\nQuery OK, 0 rows affected (0.74 sec)"
},
{
"code": null,
"e": 2614,
"s": 2453,
"text": "After creating the table, some records which are present in first table and some records which\nare not present in first table are inserted in PastHistory table."
},
{
"code": null,
"e": 2958,
"s": 2614,
"text": "mysql> INSERT into PastHistory values(1,'John');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> INSERT into PastHistory values(2,'Bob');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> INSERT into PastHistory values(3,'Carol');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> INSERT into PastHistory values(4,'Jason');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 3098,
"s": 2958,
"text": "Now, there are 4 records in the second table. Out of these, 2 records are from the first table and\n2 records are different in second table."
},
{
"code": null,
"e": 3190,
"s": 3098,
"text": "The records in the second table are seen with the help of the select statement as follows −"
},
{
"code": null,
"e": 3225,
"s": 3190,
"text": "mysql> SELECT * from PastHistory;\n"
},
{
"code": null,
"e": 3258,
"s": 3225,
"text": "The output of the above query is"
},
{
"code": null,
"e": 3459,
"s": 3258,
"text": "+--------+----------+\n| PastId | PastName |\n+--------+----------+\n| 1 | John |\n| 2 | Bob |\n| 3 | Carol |\n| 4 | Jason |\n+--------+----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3565,
"s": 3459,
"text": "The syntax to check the records from one table that don’t exist in the second table is given as\nfollows −"
},
{
"code": null,
"e": 3697,
"s": 3565,
"text": "SELECT * from yourSecondTableName where columnNamefromSecondtable NOT IN\n(SELECT columnNamefromfirsttable from yourFirstTableName);"
},
{
"code": null,
"e": 3780,
"s": 3697,
"text": "The given query is used to get the records that are distinct in the second table −"
},
{
"code": null,
"e": 3873,
"s": 3780,
"text": "mysql> SELECT * from PastHistory where PastName not in (select HisName from\nPresentHistory);"
},
{
"code": null,
"e": 3919,
"s": 3873,
"text": "The output of the above query is as follows −"
},
{
"code": null,
"e": 4076,
"s": 3919,
"text": "+--------+----------+\n| PastId | PastName |\n+--------+----------+\n| 3 | Carol |\n| 4 | Jason |\n+--------+----------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 4183,
"s": 4076,
"text": "From the above output it is clear that we have found two records which are not present in the\nfirst table."
}
] |
Autoencoders for the compression of stock market time series | by Gerard Martínez | Towards Data Science
|
Stock market data space is highly dimensional and, as such, algorithms that try to exploit potential patterns or structure in the price formation can suffer from the so-called “curse of dimensionality”. In this short article, we will explore the potential of 4 different types of autoencoders to capture the dynamic information of stock market prices in a lower and traceable dimension space. To do so, we will use the Python programming language and, as an example, we will apply these algorithms to the compression of Bitcoin price time series. The code to build the neural network models (using the Keras library) and the full Jupyter notebook used is available at the end of the article.
An autoencoder is a type of neural network in which the input and the output data are the same. As such, it is part of the so-called unsupervised learning or self-supervised learning because, unlike supervised learning, it requires no human intervention such as data labeling. The architecture of an autoencoder may vary, as we will see, but generally speaking it includes an encoder, that transforms the input into a lower dimensional representation, and a decoder, which tries to reconstruct the original input from the lower dimensional representation. Therefore, these models present some some sort of “bottle neck” in the middle that forces the network to learn how to compress the data in a lower dimensional space. When training these algorithms, the objective is to be able to reconstruct the original input with the minimum amount of information loss. Once the model is trained, we can compress data at will by only using the encoder component of the autoencoder.
The data we are going to use is the Bitcoin time series consisting of 1-hour candlestick close prices of the Coindesk Bitcoin Price Index starting from 01/01/2015 until today. Specifically, we will use the first 93% of the data as a training dataset and the final 7% as test dataset. The bitcoin prices will be transformed to log returns (i.e. the log of the difference between the price x+1 and price x) and windows of 10 consecutive returns will be produced. Each of these windows of consecutive returns will be normalized with a MinMaxScaler to the range [0,1].
The objective for the different autoencoder models is to be able to compress the input which is 10-dimensional to a 3-dimensional latent space. This constitutes a reduction factor of 3.3, which should be attainable with reasonably good accuracy.
For each model tried we will show a summary of the model, the loss for the training and test datasets at each stage of the training epochs and, finally, the input and output of the autoencoder for 10 randomly selected price return windows extracted from the test dataset (i.e. the model has not seen these data points). The selected test windows will intentionally remain the same across all models to be able to compare which kind of features each model may be learning.
Layer (type) Output Shape Param # =================================================================input_2 (InputLayer) (None, 10) 0 _________________________________________________________________dense_3 (Dense) (None, 3) 33 _________________________________________________________________dense_4 (Dense) (None, 10) 40 =================================================================Total params: 73Trainable params: 73Non-trainable params: 0
The model used is super simple but the comparison between the input and the output reveal the ability of the network to abstract few important features such as peaks and lows. Interestingly, we can see that the some of the outputs are almost identical between each other even though the inputs are reasonably different.
_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_3 (InputLayer) (None, 10) 0 _________________________________________________________________dense_5 (Dense) (None, 6) 66 _________________________________________________________________batch_normalization_1 (Batch (None, 6) 24 _________________________________________________________________dense_6 (Dense) (None, 3) 21 _________________________________________________________________dense_7 (Dense) (None, 6) 24 _________________________________________________________________batch_normalization_2 (Batch (None, 6) 24 _________________________________________________________________dense_8 (Dense) (None, 10) 70 =================================================================Total params: 229Trainable params: 205Non-trainable params: 24
Despite the few more parameters we seem to reach a similar accuracy when looking at the train/test loss. However, the input/output examples show a different type of plots, the majority of them containing one single low or high peak unlike the previous results, which were much more variant in the middle range.
_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_4 (InputLayer) (None, 10, 1) 0 _________________________________________________________________conv1d_1 (Conv1D) (None, 10, 16) 64 _________________________________________________________________max_pooling1d_1 (MaxPooling1 (None, 5, 16) 0 _________________________________________________________________conv1d_2 (Conv1D) (None, 5, 1) 49 _________________________________________________________________max_pooling1d_2 (MaxPooling1 (None, 3, 1) 0 _________________________________________________________________conv1d_3 (Conv1D) (None, 3, 1) 4 _________________________________________________________________up_sampling1d_1 (UpSampling1 (None, 6, 1) 0 _________________________________________________________________conv1d_4 (Conv1D) (None, 5, 16) 48 _________________________________________________________________up_sampling1d_2 (UpSampling1 (None, 10, 16) 0 _________________________________________________________________conv1d_5 (Conv1D) (None, 10, 1) 49 =================================================================Total params: 214Trainable params: 214Non-trainable params: 0
This third model gets kind of interesting. In this model we are using convolutions with kernel size of 3 and the idea is that these convolutions should look at patterns occurring in groups of 3 returns. The results were surprising to me. In most of them, we can see the main “event” very well represented while the overall reconstruction is very smooth as we had applied a moving average to the returns.
_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_5 (InputLayer) (None, 10, 1) 0 _________________________________________________________________lstm_1 (LSTM) (None, 3) 60 _________________________________________________________________repeat_vector_1 (RepeatVecto (None, 10, 3) 0 _________________________________________________________________lstm_2 (LSTM) (None, 10, 1) 20 =================================================================Total params: 80Trainable params: 80Non-trainable params: 0
While recurrent neural networks such as Long-Short Term Memory (LSTM) models are particularly suitable to tackle time series, we can see that their performance as autoencoders is very poor. Goodfellow et al. explain it succinctly well in their book “Deep Learning”:
When the recurrent network is trained to perform a task that requires predicting the future from the past, the network typically learns to use h(t) [the compressed representation] as a kind of lossy summary of the task-relevant aspects of the past sequence of inputs up to t. This summary is in general necessarily lossy, since it maps an arbitrary length sequence to a fixed length vector h(t).
[...]
The most demanding situation is when we ask h(t) to be rich enough to allow one to approximately recover the sequence, as in autoencoder frameworks.
The idea behind an autoencoder is to reduce an original high dimensionality to a lower dimensionality. In our case, the values of this high dimensional space are continuous between 0 and 1 thanks to the normalization scheme that we are applying. However, one can think that if we discretize this 0 to 1 range to, say, 10 bins, all the sudden we are kind of categorizing down the whole 0–1 spectrum to 10 simple categories. Now, if our windows are 10 returns-long, using this “discretized” continuous space one could easily generate the 10 to the power of 10 different existing combinations or “discretized time series”. This “synthethic” dataset could be used as training dataset to almost de facto enrich our model and teach it to understand parts of the price space that were undersampled in the Bitcoin time series. What a nice idea, isn’t it?
Or... is it? The results are bittersweet. Some of the progressions improve a lot (compare for instance the first column to previous models) but others are really bad (for instance the 6th column). This brings me to think that perhaps sampling the whole space of possibilities equiprobably is not an optimal idea. By sampling the whole space equally we are forcing the network to learn to compress the whole space equally, indifferently from whether the space is actually relevant to represent Bitcoin or stock prices. We must keep in mind that an autoencoder, like all the neural networks, is a function approximator and as such it tries to globally approximate all the data points we use in the training. This global optimization inherently means that in order to approximate some values better it will have to necessarily loose performance in approximating others. This suggests that in order for this idea to work, we should find smarter ways to sample only the relevant space so that the network gets at its best only on relevant compressions.
We have seen that autoencoders can be useful to compress the time series of stocks returns. If the objective was solely to compress the data, it would be interesting to try other classic dimensionality reduction algorithms such as PCA, which may well prove better at this specific task.
However, the advantage of using autoencoders is that some of its components, such as the encoder, can be separately trained on several independent stock market returns and then re-used in other end-to-end neural-networks while still keeping the potential to be globally optimized by back-propagation.
Some of the next ideas I’d like to try next are:
Train the same autoencoders described in this article with data from very different stock market instruments (e.g. non-cryptocurrency or other cryptocurrencies) and different year time spans to see if the performance increase at exactly the same task evaluated here (Bitcoin data compression).Plug in a trained encoder directly into other neural networks specialized in future price return prediction or x+1 UP/DOWN price predictors, and compare its performance to a network that takes in directly the raw price returns instead of the compressed representation.
Train the same autoencoders described in this article with data from very different stock market instruments (e.g. non-cryptocurrency or other cryptocurrencies) and different year time spans to see if the performance increase at exactly the same task evaluated here (Bitcoin data compression).
Plug in a trained encoder directly into other neural networks specialized in future price return prediction or x+1 UP/DOWN price predictors, and compare its performance to a network that takes in directly the raw price returns instead of the compressed representation.
As usual, here’s the Jupyter notebook to reproduce my work:
This project is part of our research at CryptoDatum.io, a cryptocurrency data API that aims to provide plug-and-play datasets to train machine learning algorithms. If you liked the data we showed in this article, get your free API key and play with it yourself at https://cryptodatum.io
|
[
{
"code": null,
"e": 864,
"s": 172,
"text": "Stock market data space is highly dimensional and, as such, algorithms that try to exploit potential patterns or structure in the price formation can suffer from the so-called “curse of dimensionality”. In this short article, we will explore the potential of 4 different types of autoencoders to capture the dynamic information of stock market prices in a lower and traceable dimension space. To do so, we will use the Python programming language and, as an example, we will apply these algorithms to the compression of Bitcoin price time series. The code to build the neural network models (using the Keras library) and the full Jupyter notebook used is available at the end of the article."
},
{
"code": null,
"e": 1837,
"s": 864,
"text": "An autoencoder is a type of neural network in which the input and the output data are the same. As such, it is part of the so-called unsupervised learning or self-supervised learning because, unlike supervised learning, it requires no human intervention such as data labeling. The architecture of an autoencoder may vary, as we will see, but generally speaking it includes an encoder, that transforms the input into a lower dimensional representation, and a decoder, which tries to reconstruct the original input from the lower dimensional representation. Therefore, these models present some some sort of “bottle neck” in the middle that forces the network to learn how to compress the data in a lower dimensional space. When training these algorithms, the objective is to be able to reconstruct the original input with the minimum amount of information loss. Once the model is trained, we can compress data at will by only using the encoder component of the autoencoder."
},
{
"code": null,
"e": 2402,
"s": 1837,
"text": "The data we are going to use is the Bitcoin time series consisting of 1-hour candlestick close prices of the Coindesk Bitcoin Price Index starting from 01/01/2015 until today. Specifically, we will use the first 93% of the data as a training dataset and the final 7% as test dataset. The bitcoin prices will be transformed to log returns (i.e. the log of the difference between the price x+1 and price x) and windows of 10 consecutive returns will be produced. Each of these windows of consecutive returns will be normalized with a MinMaxScaler to the range [0,1]."
},
{
"code": null,
"e": 2648,
"s": 2402,
"text": "The objective for the different autoencoder models is to be able to compress the input which is 10-dimensional to a 3-dimensional latent space. This constitutes a reduction factor of 3.3, which should be attainable with reasonably good accuracy."
},
{
"code": null,
"e": 3120,
"s": 2648,
"text": "For each model tried we will show a summary of the model, the loss for the training and test datasets at each stage of the training epochs and, finally, the input and output of the autoencoder for 10 randomly selected price return windows extracted from the test dataset (i.e. the model has not seen these data points). The selected test windows will intentionally remain the same across all models to be able to compare which kind of features each model may be learning."
},
{
"code": null,
"e": 3700,
"s": 3120,
"text": "Layer (type) Output Shape Param # =================================================================input_2 (InputLayer) (None, 10) 0 _________________________________________________________________dense_3 (Dense) (None, 3) 33 _________________________________________________________________dense_4 (Dense) (None, 10) 40 =================================================================Total params: 73Trainable params: 73Non-trainable params: 0"
},
{
"code": null,
"e": 4020,
"s": 3700,
"text": "The model used is super simple but the comparison between the input and the output reveal the ability of the network to abstract few important features such as peaks and lows. Interestingly, we can see that the some of the outputs are almost identical between each other even though the inputs are reasonably different."
},
{
"code": null,
"e": 5188,
"s": 4020,
"text": "_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_3 (InputLayer) (None, 10) 0 _________________________________________________________________dense_5 (Dense) (None, 6) 66 _________________________________________________________________batch_normalization_1 (Batch (None, 6) 24 _________________________________________________________________dense_6 (Dense) (None, 3) 21 _________________________________________________________________dense_7 (Dense) (None, 6) 24 _________________________________________________________________batch_normalization_2 (Batch (None, 6) 24 _________________________________________________________________dense_8 (Dense) (None, 10) 70 =================================================================Total params: 229Trainable params: 205Non-trainable params: 24"
},
{
"code": null,
"e": 5499,
"s": 5188,
"text": "Despite the few more parameters we seem to reach a similar accuracy when looking at the train/test loss. However, the input/output examples show a different type of plots, the majority of them containing one single low or high peak unlike the previous results, which were much more variant in the middle range."
},
{
"code": null,
"e": 7056,
"s": 5499,
"text": "_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_4 (InputLayer) (None, 10, 1) 0 _________________________________________________________________conv1d_1 (Conv1D) (None, 10, 16) 64 _________________________________________________________________max_pooling1d_1 (MaxPooling1 (None, 5, 16) 0 _________________________________________________________________conv1d_2 (Conv1D) (None, 5, 1) 49 _________________________________________________________________max_pooling1d_2 (MaxPooling1 (None, 3, 1) 0 _________________________________________________________________conv1d_3 (Conv1D) (None, 3, 1) 4 _________________________________________________________________up_sampling1d_1 (UpSampling1 (None, 6, 1) 0 _________________________________________________________________conv1d_4 (Conv1D) (None, 5, 16) 48 _________________________________________________________________up_sampling1d_2 (UpSampling1 (None, 10, 16) 0 _________________________________________________________________conv1d_5 (Conv1D) (None, 10, 1) 49 =================================================================Total params: 214Trainable params: 214Non-trainable params: 0"
},
{
"code": null,
"e": 7460,
"s": 7056,
"text": "This third model gets kind of interesting. In this model we are using convolutions with kernel size of 3 and the idea is that these convolutions should look at patterns occurring in groups of 3 returns. The results were surprising to me. In most of them, we can see the main “event” very well represented while the overall reconstruction is very smooth as we had applied a moving average to the returns."
},
{
"code": null,
"e": 8235,
"s": 7460,
"text": "_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_5 (InputLayer) (None, 10, 1) 0 _________________________________________________________________lstm_1 (LSTM) (None, 3) 60 _________________________________________________________________repeat_vector_1 (RepeatVecto (None, 10, 3) 0 _________________________________________________________________lstm_2 (LSTM) (None, 10, 1) 20 =================================================================Total params: 80Trainable params: 80Non-trainable params: 0"
},
{
"code": null,
"e": 8501,
"s": 8235,
"text": "While recurrent neural networks such as Long-Short Term Memory (LSTM) models are particularly suitable to tackle time series, we can see that their performance as autoencoders is very poor. Goodfellow et al. explain it succinctly well in their book “Deep Learning”:"
},
{
"code": null,
"e": 8897,
"s": 8501,
"text": "When the recurrent network is trained to perform a task that requires predicting the future from the past, the network typically learns to use h(t) [the compressed representation] as a kind of lossy summary of the task-relevant aspects of the past sequence of inputs up to t. This summary is in general necessarily lossy, since it maps an arbitrary length sequence to a fixed length vector h(t)."
},
{
"code": null,
"e": 8903,
"s": 8897,
"text": "[...]"
},
{
"code": null,
"e": 9052,
"s": 8903,
"text": "The most demanding situation is when we ask h(t) to be rich enough to allow one to approximately recover the sequence, as in autoencoder frameworks."
},
{
"code": null,
"e": 9899,
"s": 9052,
"text": "The idea behind an autoencoder is to reduce an original high dimensionality to a lower dimensionality. In our case, the values of this high dimensional space are continuous between 0 and 1 thanks to the normalization scheme that we are applying. However, one can think that if we discretize this 0 to 1 range to, say, 10 bins, all the sudden we are kind of categorizing down the whole 0–1 spectrum to 10 simple categories. Now, if our windows are 10 returns-long, using this “discretized” continuous space one could easily generate the 10 to the power of 10 different existing combinations or “discretized time series”. This “synthethic” dataset could be used as training dataset to almost de facto enrich our model and teach it to understand parts of the price space that were undersampled in the Bitcoin time series. What a nice idea, isn’t it?"
},
{
"code": null,
"e": 10947,
"s": 9899,
"text": "Or... is it? The results are bittersweet. Some of the progressions improve a lot (compare for instance the first column to previous models) but others are really bad (for instance the 6th column). This brings me to think that perhaps sampling the whole space of possibilities equiprobably is not an optimal idea. By sampling the whole space equally we are forcing the network to learn to compress the whole space equally, indifferently from whether the space is actually relevant to represent Bitcoin or stock prices. We must keep in mind that an autoencoder, like all the neural networks, is a function approximator and as such it tries to globally approximate all the data points we use in the training. This global optimization inherently means that in order to approximate some values better it will have to necessarily loose performance in approximating others. This suggests that in order for this idea to work, we should find smarter ways to sample only the relevant space so that the network gets at its best only on relevant compressions."
},
{
"code": null,
"e": 11234,
"s": 10947,
"text": "We have seen that autoencoders can be useful to compress the time series of stocks returns. If the objective was solely to compress the data, it would be interesting to try other classic dimensionality reduction algorithms such as PCA, which may well prove better at this specific task."
},
{
"code": null,
"e": 11535,
"s": 11234,
"text": "However, the advantage of using autoencoders is that some of its components, such as the encoder, can be separately trained on several independent stock market returns and then re-used in other end-to-end neural-networks while still keeping the potential to be globally optimized by back-propagation."
},
{
"code": null,
"e": 11584,
"s": 11535,
"text": "Some of the next ideas I’d like to try next are:"
},
{
"code": null,
"e": 12146,
"s": 11584,
"text": "Train the same autoencoders described in this article with data from very different stock market instruments (e.g. non-cryptocurrency or other cryptocurrencies) and different year time spans to see if the performance increase at exactly the same task evaluated here (Bitcoin data compression).Plug in a trained encoder directly into other neural networks specialized in future price return prediction or x+1 UP/DOWN price predictors, and compare its performance to a network that takes in directly the raw price returns instead of the compressed representation."
},
{
"code": null,
"e": 12440,
"s": 12146,
"text": "Train the same autoencoders described in this article with data from very different stock market instruments (e.g. non-cryptocurrency or other cryptocurrencies) and different year time spans to see if the performance increase at exactly the same task evaluated here (Bitcoin data compression)."
},
{
"code": null,
"e": 12709,
"s": 12440,
"text": "Plug in a trained encoder directly into other neural networks specialized in future price return prediction or x+1 UP/DOWN price predictors, and compare its performance to a network that takes in directly the raw price returns instead of the compressed representation."
},
{
"code": null,
"e": 12769,
"s": 12709,
"text": "As usual, here’s the Jupyter notebook to reproduce my work:"
}
] |
Python - How to remove duplicate elements from List - 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
In this tutorials, we will see how to remove duplicate elements from a python list.
We can accomplish this using different ways, let’s see all the ways.
The list of elements is reading from user input.
Removing duplicates using membership operators in python.
elem = eval(input("Enter List of values : "))
list1=[]
for x in elem:
if x not in list1:
list1.append(x)
print("After Removing duplicate elements ",list1)
Output:
Enter List of values : [10,20,30,40,10,20,50,60]
After Removing duplicate elements [10, 20, 30, 40, 50, 60]
Removing duplicate elements using Python’s list comprehension.
list1=[10,20,30,10,50,20,10,60,80,50,40,10]
newlist=[ele for n,ele in enumerate(list1) if ele not in list1[:n]]
print("New List : ",newlist)
Output:
New List : [10, 20, 30, 50, 60, 80, 40]
Removing duplicates usind sorted() function.
list1 = ['a','c','a','d','e','a','f','b']
list2 = sorted(set(list1),key=list1.index)
print(list2)
Output:
['a', 'c', 'd', 'e', 'f', 'b']
If you are concerning about insertion order, you can also remove duplicate elements using python set data structure.
elem = eval(input("Enter List of values : "))
set1 = set(elem)
print("After Removing duplicate elements ",set1)
Output:
Enter List of values : [1,2,3,4,5,1,2,6,4]
After Removing duplicate elements {1, 2, 3, 4, 5, 6}
Let’s consider, our list containing string elements. We can remove the duplicates from below set functions.
list1 = ["abc", "xyz", "pqr"]
list2 = ["aei", "oup", "xyz","abc"]
newSet= set(list1).symmetric_difference(list2).union(set(list1).intersection(list2))
print(newSet)
Output:
You can find more explanation about the output, from our earlier example of the set data structure.
{'pqr', 'aei', 'abc', 'xyz', 'oup'}
Reference:
Python List Data Structure
Python Set Data Structure
Python operators
Happy Learning 🙂
Python Set Data Structure in Depth
Java 8 How to get common elements from two lists
Python Tuple Data Structure in Depth
Python How to read input from keyboard
How to Create or Delete Directories in Python ?
Python – How to remove key from dictionary ?
How to Remove Spaces from String in Python
JQuery Remove Elements Example
Java 8 how to remove duplicates from list
How to Rotate Elements in List
What are the List of Python Keywords
Python List Data Structure In Depth
How to Convert Python List Of Objects to CSV File
How to Find Duplicate Words Count in a File
How to merge two lists in Python
Python Set Data Structure in Depth
Java 8 How to get common elements from two lists
Python Tuple Data Structure in Depth
Python How to read input from keyboard
How to Create or Delete Directories in Python ?
Python – How to remove key from dictionary ?
How to Remove Spaces from String in Python
JQuery Remove Elements Example
Java 8 how to remove duplicates from list
How to Rotate Elements in List
What are the List of Python Keywords
Python List Data Structure In Depth
How to Convert Python List Of Objects to CSV File
How to Find Duplicate Words Count in a File
How to merge two lists in Python
Δ
Python – Introduction
Python – Features
Python – Install on Windows
Python – Modes of Program
Python – Number System
Python – Identifiers
Python – Operators
Python – Ternary Operator
Python – Command Line Arguments
Python – Keywords
Python – Data Types
Python – Upgrade Python PIP
Python – Virtual Environment
Pyhton – Type Casting
Python – String to Int
Python – Conditional Statements
Python – if statement
Python – *args and **kwargs
Python – Date Formatting
Python – Read input from keyboard
Python – raw_input
Python – List In Depth
Python – List Comprehension
Python – Set in Depth
Python – Dictionary in Depth
Python – Tuple in Depth
Python – Stack Datastructure
Python – Classes and Objects
Python – Constructors
Python – Object Introspection
Python – Inheritance
Python – Decorators
Python – Serialization with Pickle
Python – Exceptions Handling
Python – User defined Exceptions
Python – Multiprocessing
Python – Default function parameters
Python – Lambdas Functions
Python – NumPy Library
Python – MySQL Connector
Python – MySQL Create Database
Python – MySQL Read Data
Python – MySQL Insert Data
Python – MySQL Update Records
Python – MySQL Delete Records
Python – String Case Conversion
Howto – Find biggest of 2 numbers
Howto – Remove duplicates from List
Howto – Convert any Number to Binary
Howto – Merge two Lists
Howto – Merge two dicts
Howto – Get Characters Count in a File
Howto – Get Words Count in a File
Howto – Remove Spaces from String
Howto – Read Env variables
Howto – Read a text File
Howto – Read a JSON File
Howto – Read Config.ini files
Howto – Iterate Dictionary
Howto – Convert List Of Objects to CSV
Howto – Merge two dict in Python
Howto – create Zip File
Howto – Get OS info
Howto – Get size of Directory
Howto – Check whether a file exists
Howto – Remove key from dictionary
Howto – Sort Objects
Howto – Create or Delete Directories
Howto – Read CSV File
Howto – Create Python Iterable class
Howto – Access for loop index
Howto – Clear all elements from List
Howto – Remove empty lists from a List
Howto – Remove special characters from String
Howto – Sort dictionary by key
Howto – Filter a list
|
[
{
"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": 482,
"s": 398,
"text": "In this tutorials, we will see how to remove duplicate elements from a python list."
},
{
"code": null,
"e": 551,
"s": 482,
"text": "We can accomplish this using different ways, let’s see all the ways."
},
{
"code": null,
"e": 600,
"s": 551,
"text": "The list of elements is reading from user input."
},
{
"code": null,
"e": 658,
"s": 600,
"text": "Removing duplicates using membership operators in python."
},
{
"code": null,
"e": 825,
"s": 658,
"text": "elem = eval(input(\"Enter List of values : \"))\nlist1=[]\nfor x in elem:\n if x not in list1:\n list1.append(x)\nprint(\"After Removing duplicate elements \",list1)"
},
{
"code": null,
"e": 833,
"s": 825,
"text": "Output:"
},
{
"code": null,
"e": 942,
"s": 833,
"text": "Enter List of values : [10,20,30,40,10,20,50,60]\nAfter Removing duplicate elements [10, 20, 30, 40, 50, 60]"
},
{
"code": null,
"e": 1005,
"s": 942,
"text": "Removing duplicate elements using Python’s list comprehension."
},
{
"code": null,
"e": 1148,
"s": 1005,
"text": "list1=[10,20,30,10,50,20,10,60,80,50,40,10]\n\nnewlist=[ele for n,ele in enumerate(list1) if ele not in list1[:n]]\n\nprint(\"New List : \",newlist)"
},
{
"code": null,
"e": 1156,
"s": 1148,
"text": "Output:"
},
{
"code": null,
"e": 1197,
"s": 1156,
"text": "New List : [10, 20, 30, 50, 60, 80, 40]"
},
{
"code": null,
"e": 1242,
"s": 1197,
"text": "Removing duplicates usind sorted() function."
},
{
"code": null,
"e": 1344,
"s": 1242,
"text": "list1 = ['a','c','a','d','e','a','f','b'] \nlist2 = sorted(set(list1),key=list1.index) \nprint(list2)"
},
{
"code": null,
"e": 1352,
"s": 1344,
"text": "Output:"
},
{
"code": null,
"e": 1383,
"s": 1352,
"text": "['a', 'c', 'd', 'e', 'f', 'b']"
},
{
"code": null,
"e": 1500,
"s": 1383,
"text": "If you are concerning about insertion order, you can also remove duplicate elements using python set data structure."
},
{
"code": null,
"e": 1612,
"s": 1500,
"text": "elem = eval(input(\"Enter List of values : \"))\nset1 = set(elem)\nprint(\"After Removing duplicate elements \",set1)"
},
{
"code": null,
"e": 1620,
"s": 1612,
"text": "Output:"
},
{
"code": null,
"e": 1717,
"s": 1620,
"text": "Enter List of values : [1,2,3,4,5,1,2,6,4]\nAfter Removing duplicate elements {1, 2, 3, 4, 5, 6}"
},
{
"code": null,
"e": 1825,
"s": 1717,
"text": "Let’s consider, our list containing string elements. We can remove the duplicates from below set functions."
},
{
"code": null,
"e": 1992,
"s": 1825,
"text": "list1 = [\"abc\", \"xyz\", \"pqr\"]\nlist2 = [\"aei\", \"oup\", \"xyz\",\"abc\"]\n\nnewSet= set(list1).symmetric_difference(list2).union(set(list1).intersection(list2))\n\nprint(newSet)"
},
{
"code": null,
"e": 2000,
"s": 1992,
"text": "Output:"
},
{
"code": null,
"e": 2100,
"s": 2000,
"text": "You can find more explanation about the output, from our earlier example of the set data structure."
},
{
"code": null,
"e": 2136,
"s": 2100,
"text": "{'pqr', 'aei', 'abc', 'xyz', 'oup'}"
},
{
"code": null,
"e": 2149,
"s": 2138,
"text": "Reference:"
},
{
"code": null,
"e": 2176,
"s": 2149,
"text": "Python List Data Structure"
},
{
"code": null,
"e": 2202,
"s": 2176,
"text": "Python Set Data Structure"
},
{
"code": null,
"e": 2219,
"s": 2202,
"text": "Python operators"
},
{
"code": null,
"e": 2236,
"s": 2219,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 2838,
"s": 2236,
"text": "\nPython Set Data Structure in Depth\nJava 8 How to get common elements from two lists\nPython Tuple Data Structure in Depth\nPython How to read input from keyboard\nHow to Create or Delete Directories in Python ?\nPython – How to remove key from dictionary ?\nHow to Remove Spaces from String in Python\nJQuery Remove Elements Example\nJava 8 how to remove duplicates from list\nHow to Rotate Elements in List\nWhat are the List of Python Keywords\nPython List Data Structure In Depth\nHow to Convert Python List Of Objects to CSV File\nHow to Find Duplicate Words Count in a File\nHow to merge two lists in Python\n"
},
{
"code": null,
"e": 2873,
"s": 2838,
"text": "Python Set Data Structure in Depth"
},
{
"code": null,
"e": 2922,
"s": 2873,
"text": "Java 8 How to get common elements from two lists"
},
{
"code": null,
"e": 2959,
"s": 2922,
"text": "Python Tuple Data Structure in Depth"
},
{
"code": null,
"e": 2998,
"s": 2959,
"text": "Python How to read input from keyboard"
},
{
"code": null,
"e": 3046,
"s": 2998,
"text": "How to Create or Delete Directories in Python ?"
},
{
"code": null,
"e": 3091,
"s": 3046,
"text": "Python – How to remove key from dictionary ?"
},
{
"code": null,
"e": 3134,
"s": 3091,
"text": "How to Remove Spaces from String in Python"
},
{
"code": null,
"e": 3165,
"s": 3134,
"text": "JQuery Remove Elements Example"
},
{
"code": null,
"e": 3207,
"s": 3165,
"text": "Java 8 how to remove duplicates from list"
},
{
"code": null,
"e": 3238,
"s": 3207,
"text": "How to Rotate Elements in List"
},
{
"code": null,
"e": 3275,
"s": 3238,
"text": "What are the List of Python Keywords"
},
{
"code": null,
"e": 3311,
"s": 3275,
"text": "Python List Data Structure In Depth"
},
{
"code": null,
"e": 3361,
"s": 3311,
"text": "How to Convert Python List Of Objects to CSV File"
},
{
"code": null,
"e": 3405,
"s": 3361,
"text": "How to Find Duplicate Words Count in a File"
},
{
"code": null,
"e": 3438,
"s": 3405,
"text": "How to merge two lists in Python"
},
{
"code": null,
"e": 3444,
"s": 3442,
"text": "Δ"
},
{
"code": null,
"e": 3467,
"s": 3444,
"text": " Python – Introduction"
},
{
"code": null,
"e": 3486,
"s": 3467,
"text": " Python – Features"
},
{
"code": null,
"e": 3515,
"s": 3486,
"text": " Python – Install on Windows"
},
{
"code": null,
"e": 3542,
"s": 3515,
"text": " Python – Modes of Program"
},
{
"code": null,
"e": 3566,
"s": 3542,
"text": " Python – Number System"
},
{
"code": null,
"e": 3588,
"s": 3566,
"text": " Python – Identifiers"
},
{
"code": null,
"e": 3608,
"s": 3588,
"text": " Python – Operators"
},
{
"code": null,
"e": 3635,
"s": 3608,
"text": " Python – Ternary Operator"
},
{
"code": null,
"e": 3668,
"s": 3635,
"text": " Python – Command Line Arguments"
},
{
"code": null,
"e": 3687,
"s": 3668,
"text": " Python – Keywords"
},
{
"code": null,
"e": 3708,
"s": 3687,
"text": " Python – Data Types"
},
{
"code": null,
"e": 3737,
"s": 3708,
"text": " Python – Upgrade Python PIP"
},
{
"code": null,
"e": 3767,
"s": 3737,
"text": " Python – Virtual Environment"
},
{
"code": null,
"e": 3790,
"s": 3767,
"text": " Pyhton – Type Casting"
},
{
"code": null,
"e": 3814,
"s": 3790,
"text": " Python – String to Int"
},
{
"code": null,
"e": 3847,
"s": 3814,
"text": " Python – Conditional Statements"
},
{
"code": null,
"e": 3870,
"s": 3847,
"text": " Python – if statement"
},
{
"code": null,
"e": 3899,
"s": 3870,
"text": " Python – *args and **kwargs"
},
{
"code": null,
"e": 3925,
"s": 3899,
"text": " Python – Date Formatting"
},
{
"code": null,
"e": 3960,
"s": 3925,
"text": " Python – Read input from keyboard"
},
{
"code": null,
"e": 3980,
"s": 3960,
"text": " Python – raw_input"
},
{
"code": null,
"e": 4004,
"s": 3980,
"text": " Python – List In Depth"
},
{
"code": null,
"e": 4033,
"s": 4004,
"text": " Python – List Comprehension"
},
{
"code": null,
"e": 4056,
"s": 4033,
"text": " Python – Set in Depth"
},
{
"code": null,
"e": 4086,
"s": 4056,
"text": " Python – Dictionary in Depth"
},
{
"code": null,
"e": 4111,
"s": 4086,
"text": " Python – Tuple in Depth"
},
{
"code": null,
"e": 4141,
"s": 4111,
"text": " Python – Stack Datastructure"
},
{
"code": null,
"e": 4171,
"s": 4141,
"text": " Python – Classes and Objects"
},
{
"code": null,
"e": 4194,
"s": 4171,
"text": " Python – Constructors"
},
{
"code": null,
"e": 4225,
"s": 4194,
"text": " Python – Object Introspection"
},
{
"code": null,
"e": 4247,
"s": 4225,
"text": " Python – Inheritance"
},
{
"code": null,
"e": 4268,
"s": 4247,
"text": " Python – Decorators"
},
{
"code": null,
"e": 4304,
"s": 4268,
"text": " Python – Serialization with Pickle"
},
{
"code": null,
"e": 4334,
"s": 4304,
"text": " Python – Exceptions Handling"
},
{
"code": null,
"e": 4368,
"s": 4334,
"text": " Python – User defined Exceptions"
},
{
"code": null,
"e": 4394,
"s": 4368,
"text": " Python – Multiprocessing"
},
{
"code": null,
"e": 4432,
"s": 4394,
"text": " Python – Default function parameters"
},
{
"code": null,
"e": 4460,
"s": 4432,
"text": " Python – Lambdas Functions"
},
{
"code": null,
"e": 4484,
"s": 4460,
"text": " Python – NumPy Library"
},
{
"code": null,
"e": 4510,
"s": 4484,
"text": " Python – MySQL Connector"
},
{
"code": null,
"e": 4542,
"s": 4510,
"text": " Python – MySQL Create Database"
},
{
"code": null,
"e": 4568,
"s": 4542,
"text": " Python – MySQL Read Data"
},
{
"code": null,
"e": 4596,
"s": 4568,
"text": " Python – MySQL Insert Data"
},
{
"code": null,
"e": 4627,
"s": 4596,
"text": " Python – MySQL Update Records"
},
{
"code": null,
"e": 4658,
"s": 4627,
"text": " Python – MySQL Delete Records"
},
{
"code": null,
"e": 4691,
"s": 4658,
"text": " Python – String Case Conversion"
},
{
"code": null,
"e": 4726,
"s": 4691,
"text": " Howto – Find biggest of 2 numbers"
},
{
"code": null,
"e": 4763,
"s": 4726,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 4801,
"s": 4763,
"text": " Howto – Convert any Number to Binary"
},
{
"code": null,
"e": 4827,
"s": 4801,
"text": " Howto – Merge two Lists"
},
{
"code": null,
"e": 4852,
"s": 4827,
"text": " Howto – Merge two dicts"
},
{
"code": null,
"e": 4892,
"s": 4852,
"text": " Howto – Get Characters Count in a File"
},
{
"code": null,
"e": 4927,
"s": 4892,
"text": " Howto – Get Words Count in a File"
},
{
"code": null,
"e": 4962,
"s": 4927,
"text": " Howto – Remove Spaces from String"
},
{
"code": null,
"e": 4991,
"s": 4962,
"text": " Howto – Read Env variables"
},
{
"code": null,
"e": 5017,
"s": 4991,
"text": " Howto – Read a text File"
},
{
"code": null,
"e": 5043,
"s": 5017,
"text": " Howto – Read a JSON File"
},
{
"code": null,
"e": 5075,
"s": 5043,
"text": " Howto – Read Config.ini files"
},
{
"code": null,
"e": 5103,
"s": 5075,
"text": " Howto – Iterate Dictionary"
},
{
"code": null,
"e": 5143,
"s": 5103,
"text": " Howto – Convert List Of Objects to CSV"
},
{
"code": null,
"e": 5177,
"s": 5143,
"text": " Howto – Merge two dict in Python"
},
{
"code": null,
"e": 5202,
"s": 5177,
"text": " Howto – create Zip File"
},
{
"code": null,
"e": 5223,
"s": 5202,
"text": " Howto – Get OS info"
},
{
"code": null,
"e": 5254,
"s": 5223,
"text": " Howto – Get size of Directory"
},
{
"code": null,
"e": 5291,
"s": 5254,
"text": " Howto – Check whether a file exists"
},
{
"code": null,
"e": 5328,
"s": 5291,
"text": " Howto – Remove key from dictionary"
},
{
"code": null,
"e": 5350,
"s": 5328,
"text": " Howto – Sort Objects"
},
{
"code": null,
"e": 5388,
"s": 5350,
"text": " Howto – Create or Delete Directories"
},
{
"code": null,
"e": 5411,
"s": 5388,
"text": " Howto – Read CSV File"
},
{
"code": null,
"e": 5449,
"s": 5411,
"text": " Howto – Create Python Iterable class"
},
{
"code": null,
"e": 5480,
"s": 5449,
"text": " Howto – Access for loop index"
},
{
"code": null,
"e": 5518,
"s": 5480,
"text": " Howto – Clear all elements from List"
},
{
"code": null,
"e": 5558,
"s": 5518,
"text": " Howto – Remove empty lists from a List"
},
{
"code": null,
"e": 5605,
"s": 5558,
"text": " Howto – Remove special characters from String"
},
{
"code": null,
"e": 5637,
"s": 5605,
"text": " Howto – Sort dictionary by key"
}
] |
Timetk: The R Library for Time Series Analysis | Towards Data Science
|
Have you ever seen data like weather temperature, stock price, or sales numbers that change over time? I’m pretty sure that you’ve already seen that data in real life at least once. Those are time-series data. Time Series is data where it changes over time, whether it’s caused by other factors or the time itself.
Analyzing time-series data can be a challenging task. For example, detecting anomalies or even want to see seasonality trends by months or weeks. If you want to do that, you need to do scripting and also use so many libraries.
Now thankfully, there’s a library for R programming language that can help us. It’s called timetk. Timetk is a library created by Matt Dancho and Davis Vaughan for analyzing and visualizing the time series data. Timetk is easy to use, and it’s way easier if you ever play with tidyverse.
In this article, I will show you how to use timetk in R.
Without further, let’s get started!
The first thing that we need to do is to install the libraries. In this case, we will install timetk and also tidyverse. After that, we can import the library. Here is the command look like,
install.packages("timetk")install.packages("tidyverse")library(tidyverse)library(lubridate)library(timetk)
After you import the libraries, now let’s import the data. In this case, we will use data from UCI Machine Learning Repository called Bike Sharing Dataset. This data contains information about the number of bike users on a single day from 2011 until 2012.
Thankfully, the timetk does include the data, so you don’t need to download it. If you still want to use the original data, You can access the dataset here.
To see the data, you can use the command here,
View(bike_sharing_daily)
Here is the preview of the data,
As you can see above, there are several columns inside the data. There is information regarding time, temperature, humidity, and the number of bike users. In this case, we only use dteday and cnt columns, where each represents the date and the number of bike users. Here is the code to retrieve the data,
# Get the databike_sharing <- bike_sharing_daily %>% # Get the columns select(dteday, cnt) %>% # Change the columns name set_names(c("date", "value"))bike_sharing
Here is the preview of the data,
After we get the data, now let’s get into the visualization. To visualize the time series, we can use the plot_time_series function from the timetk library. Here is the command look like,
bike_sharing %>% plot_time_series(date, value)
Here is the command’s result,
As you can see above, the function returns an interactive visualization. That visualization is based on a library called Plotly. Because of that, you can hover to get the data point and zoom to see details of the visualization.
You can also add a slider to filter the data observation by adding the .plotly_slider parameter to true. Here is the command look like,
bike_sharing %>% plot_time_series(date, value, .interactive=TRUE, .plotly_slider=TRUE)
Here is the result,
If you only want the static visualization, you can set the .interactive parameter to false. The function will return a static visualization which is based on the ggplot library. The command looks like this,
bike_sharing %>% plot_time_series(date, value, .interactive=FALSE)
Here is the result,
Just like with other visualizations, you can do grouping visualization with the timetk library. As you can see, the data ranges from 2011 and 2012. In this case, we will group the visualization based on the year it occurs. Here is the command looks like,
bike_sharing %>% group_by(year(date)) %>% plot_time_series(date, value, .facet_scales="free")
The result looks like this,
To make the visualization more eye-catching, we can add the .color_var parameter to color the data based on the month it occurs. Also, we will remove the smooth blue line by setting the .smooth parameter to false. Here is the command looks like,
bike_sharing %>% group_by(year(date)) %>% plot_time_series(date, value, .facet_scales="free", .smooth=FALSE .color_var=month(date), .interactive=FALSE)
Here is the result,
Besides that, we can also visualize the time series by its seasonality, whether in hours, days, weeks, or even months. You can get it all by using the plot_seasonal_diagnostics function. Here is the command looks like,
bike_sharing %>% group_by(year(date)) %>% plot_seasonal_diagnostics(date, value, .x_lab='Date', .y_lab='# of users', .title='Bike Sharing Users')
Here is the result,
Finally, I want to show you one of the main features of this library. You can detect anomalies by using only one function.
Anomaly detection is a task for finding data that has unusual value to it. In other words, the data is different from the other.
In timetk, we can do two things for anomaly detection. The first thing that you can do is to visualize the anomalies in the data. In this case, We will visualize the time series and the anomalies. Also, we divide them by year.
We can use the plot_anomaly_diagnostics function to visualize the time series and the anomalies and split them by year. The command looks like this,
# Get the databike_sharing %>% # Group the data by year group_by(year(date)) %>% # Visualize the result plot_anomaly_diagnostics(date, value)
Here is the visualization look like,
The second thing that you can do is to gather data that has anomaly to it. We group the data by year. Also, we filter the data to contain only the data that has anomaly to it. We can use the tk_anomaly_diagnostics function to gather the anomalies. Here is the command look like,
anomaly_data <- bike_sharing %>% group_by(year(date)) %>% tk_anomaly_diagnostics(date, value) %>% filter(anomaly == 'Yes')View(anomaly_data)
Here is the preview of the data,
Congratulations! Now you have learned how to use timetk in R for time series analysis. With timetk, we can analyze the time series data easier than before.
I hope the article useful to you. If you want to see more articles like this, you can follow my Medium. If you have any questions or want to have conversations, you can connect with me on LinkedIn.
Thank you for reading my article!
|
[
{
"code": null,
"e": 487,
"s": 172,
"text": "Have you ever seen data like weather temperature, stock price, or sales numbers that change over time? I’m pretty sure that you’ve already seen that data in real life at least once. Those are time-series data. Time Series is data where it changes over time, whether it’s caused by other factors or the time itself."
},
{
"code": null,
"e": 714,
"s": 487,
"text": "Analyzing time-series data can be a challenging task. For example, detecting anomalies or even want to see seasonality trends by months or weeks. If you want to do that, you need to do scripting and also use so many libraries."
},
{
"code": null,
"e": 1002,
"s": 714,
"text": "Now thankfully, there’s a library for R programming language that can help us. It’s called timetk. Timetk is a library created by Matt Dancho and Davis Vaughan for analyzing and visualizing the time series data. Timetk is easy to use, and it’s way easier if you ever play with tidyverse."
},
{
"code": null,
"e": 1059,
"s": 1002,
"text": "In this article, I will show you how to use timetk in R."
},
{
"code": null,
"e": 1095,
"s": 1059,
"text": "Without further, let’s get started!"
},
{
"code": null,
"e": 1286,
"s": 1095,
"text": "The first thing that we need to do is to install the libraries. In this case, we will install timetk and also tidyverse. After that, we can import the library. Here is the command look like,"
},
{
"code": null,
"e": 1393,
"s": 1286,
"text": "install.packages(\"timetk\")install.packages(\"tidyverse\")library(tidyverse)library(lubridate)library(timetk)"
},
{
"code": null,
"e": 1649,
"s": 1393,
"text": "After you import the libraries, now let’s import the data. In this case, we will use data from UCI Machine Learning Repository called Bike Sharing Dataset. This data contains information about the number of bike users on a single day from 2011 until 2012."
},
{
"code": null,
"e": 1806,
"s": 1649,
"text": "Thankfully, the timetk does include the data, so you don’t need to download it. If you still want to use the original data, You can access the dataset here."
},
{
"code": null,
"e": 1853,
"s": 1806,
"text": "To see the data, you can use the command here,"
},
{
"code": null,
"e": 1878,
"s": 1853,
"text": "View(bike_sharing_daily)"
},
{
"code": null,
"e": 1911,
"s": 1878,
"text": "Here is the preview of the data,"
},
{
"code": null,
"e": 2216,
"s": 1911,
"text": "As you can see above, there are several columns inside the data. There is information regarding time, temperature, humidity, and the number of bike users. In this case, we only use dteday and cnt columns, where each represents the date and the number of bike users. Here is the code to retrieve the data,"
},
{
"code": null,
"e": 2379,
"s": 2216,
"text": "# Get the databike_sharing <- bike_sharing_daily %>% # Get the columns select(dteday, cnt) %>% # Change the columns name set_names(c(\"date\", \"value\"))bike_sharing"
},
{
"code": null,
"e": 2412,
"s": 2379,
"text": "Here is the preview of the data,"
},
{
"code": null,
"e": 2600,
"s": 2412,
"text": "After we get the data, now let’s get into the visualization. To visualize the time series, we can use the plot_time_series function from the timetk library. Here is the command look like,"
},
{
"code": null,
"e": 2648,
"s": 2600,
"text": "bike_sharing %>% plot_time_series(date, value)"
},
{
"code": null,
"e": 2678,
"s": 2648,
"text": "Here is the command’s result,"
},
{
"code": null,
"e": 2906,
"s": 2678,
"text": "As you can see above, the function returns an interactive visualization. That visualization is based on a library called Plotly. Because of that, you can hover to get the data point and zoom to see details of the visualization."
},
{
"code": null,
"e": 3042,
"s": 2906,
"text": "You can also add a slider to filter the data observation by adding the .plotly_slider parameter to true. Here is the command look like,"
},
{
"code": null,
"e": 3130,
"s": 3042,
"text": "bike_sharing %>% plot_time_series(date, value, .interactive=TRUE, .plotly_slider=TRUE)"
},
{
"code": null,
"e": 3150,
"s": 3130,
"text": "Here is the result,"
},
{
"code": null,
"e": 3357,
"s": 3150,
"text": "If you only want the static visualization, you can set the .interactive parameter to false. The function will return a static visualization which is based on the ggplot library. The command looks like this,"
},
{
"code": null,
"e": 3424,
"s": 3357,
"text": "bike_sharing %>% plot_time_series(date, value, .interactive=FALSE)"
},
{
"code": null,
"e": 3444,
"s": 3424,
"text": "Here is the result,"
},
{
"code": null,
"e": 3699,
"s": 3444,
"text": "Just like with other visualizations, you can do grouping visualization with the timetk library. As you can see, the data ranges from 2011 and 2012. In this case, we will group the visualization based on the year it occurs. Here is the command looks like,"
},
{
"code": null,
"e": 3795,
"s": 3699,
"text": "bike_sharing %>% group_by(year(date)) %>% plot_time_series(date, value, .facet_scales=\"free\")"
},
{
"code": null,
"e": 3823,
"s": 3795,
"text": "The result looks like this,"
},
{
"code": null,
"e": 4069,
"s": 3823,
"text": "To make the visualization more eye-catching, we can add the .color_var parameter to color the data based on the month it occurs. Also, we will remove the smooth blue line by setting the .smooth parameter to false. Here is the command looks like,"
},
{
"code": null,
"e": 4223,
"s": 4069,
"text": "bike_sharing %>% group_by(year(date)) %>% plot_time_series(date, value, .facet_scales=\"free\", .smooth=FALSE .color_var=month(date), .interactive=FALSE)"
},
{
"code": null,
"e": 4243,
"s": 4223,
"text": "Here is the result,"
},
{
"code": null,
"e": 4462,
"s": 4243,
"text": "Besides that, we can also visualize the time series by its seasonality, whether in hours, days, weeks, or even months. You can get it all by using the plot_seasonal_diagnostics function. Here is the command looks like,"
},
{
"code": null,
"e": 4610,
"s": 4462,
"text": "bike_sharing %>% group_by(year(date)) %>% plot_seasonal_diagnostics(date, value, .x_lab='Date', .y_lab='# of users', .title='Bike Sharing Users')"
},
{
"code": null,
"e": 4630,
"s": 4610,
"text": "Here is the result,"
},
{
"code": null,
"e": 4753,
"s": 4630,
"text": "Finally, I want to show you one of the main features of this library. You can detect anomalies by using only one function."
},
{
"code": null,
"e": 4882,
"s": 4753,
"text": "Anomaly detection is a task for finding data that has unusual value to it. In other words, the data is different from the other."
},
{
"code": null,
"e": 5109,
"s": 4882,
"text": "In timetk, we can do two things for anomaly detection. The first thing that you can do is to visualize the anomalies in the data. In this case, We will visualize the time series and the anomalies. Also, we divide them by year."
},
{
"code": null,
"e": 5258,
"s": 5109,
"text": "We can use the plot_anomaly_diagnostics function to visualize the time series and the anomalies and split them by year. The command looks like this,"
},
{
"code": null,
"e": 5404,
"s": 5258,
"text": "# Get the databike_sharing %>% # Group the data by year group_by(year(date)) %>% # Visualize the result plot_anomaly_diagnostics(date, value)"
},
{
"code": null,
"e": 5441,
"s": 5404,
"text": "Here is the visualization look like,"
},
{
"code": null,
"e": 5720,
"s": 5441,
"text": "The second thing that you can do is to gather data that has anomaly to it. We group the data by year. Also, we filter the data to contain only the data that has anomaly to it. We can use the tk_anomaly_diagnostics function to gather the anomalies. Here is the command look like,"
},
{
"code": null,
"e": 5864,
"s": 5720,
"text": "anomaly_data <- bike_sharing %>% group_by(year(date)) %>% tk_anomaly_diagnostics(date, value) %>% filter(anomaly == 'Yes')View(anomaly_data)"
},
{
"code": null,
"e": 5897,
"s": 5864,
"text": "Here is the preview of the data,"
},
{
"code": null,
"e": 6053,
"s": 5897,
"text": "Congratulations! Now you have learned how to use timetk in R for time series analysis. With timetk, we can analyze the time series data easier than before."
},
{
"code": null,
"e": 6251,
"s": 6053,
"text": "I hope the article useful to you. If you want to see more articles like this, you can follow my Medium. If you have any questions or want to have conversations, you can connect with me on LinkedIn."
}
] |
LTrim() and RTrim() Function in MS Access - GeeksforGeeks
|
02 Sep, 2020
1. LTrim() Function :In MS Access LTrim() function remove all the leading spaces from the given string. In LTrim() function a string will be pass as a parameter and it will return the string with no leading spaces.
Syntax :
LTrim(string)
Example-1 :
SELECT LTrim(" GEEKSFORGEEKS") AS LeftTrimmedString;
Output –
Example-2 :
SELECT LTrim(" GFG") AS LeftTrimmedString;
Output –
2. RTrim() Function :It works same like LTrim() function but it will remove all trailing spaces from a string.
Syntax :
RTrim(string)
Example-1 :
SELECT RTrim("GEEKSFORGEEKS ") AS RightTrimmedString;
Output –
Example-2 :
SELECT RTrim("GFG ") AS RightTrimmedString;
Output –
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Window functions in SQL
|
[
{
"code": null,
"e": 23877,
"s": 23849,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 24092,
"s": 23877,
"text": "1. LTrim() Function :In MS Access LTrim() function remove all the leading spaces from the given string. In LTrim() function a string will be pass as a parameter and it will return the string with no leading spaces."
},
{
"code": null,
"e": 24101,
"s": 24092,
"text": "Syntax :"
},
{
"code": null,
"e": 24115,
"s": 24101,
"text": "LTrim(string)"
},
{
"code": null,
"e": 24127,
"s": 24115,
"text": "Example-1 :"
},
{
"code": null,
"e": 24183,
"s": 24127,
"text": "SELECT LTrim(\" GEEKSFORGEEKS\") AS LeftTrimmedString;"
},
{
"code": null,
"e": 24192,
"s": 24183,
"text": "Output –"
},
{
"code": null,
"e": 24204,
"s": 24192,
"text": "Example-2 :"
},
{
"code": null,
"e": 24250,
"s": 24204,
"text": "SELECT LTrim(\" GFG\") AS LeftTrimmedString;"
},
{
"code": null,
"e": 24259,
"s": 24250,
"text": "Output –"
},
{
"code": null,
"e": 24370,
"s": 24259,
"text": "2. RTrim() Function :It works same like LTrim() function but it will remove all trailing spaces from a string."
},
{
"code": null,
"e": 24379,
"s": 24370,
"text": "Syntax :"
},
{
"code": null,
"e": 24393,
"s": 24379,
"text": "RTrim(string)"
},
{
"code": null,
"e": 24405,
"s": 24393,
"text": "Example-1 :"
},
{
"code": null,
"e": 24462,
"s": 24405,
"text": "SELECT RTrim(\"GEEKSFORGEEKS \") AS RightTrimmedString;"
},
{
"code": null,
"e": 24471,
"s": 24462,
"text": "Output –"
},
{
"code": null,
"e": 24483,
"s": 24471,
"text": "Example-2 :"
},
{
"code": null,
"e": 24530,
"s": 24483,
"text": "SELECT RTrim(\"GFG \") AS RightTrimmedString;"
},
{
"code": null,
"e": 24539,
"s": 24530,
"text": "Output –"
},
{
"code": null,
"e": 24548,
"s": 24539,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 24552,
"s": 24548,
"text": "SQL"
},
{
"code": null,
"e": 24556,
"s": 24552,
"text": "SQL"
},
{
"code": null,
"e": 24654,
"s": 24556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24663,
"s": 24654,
"text": "Comments"
},
{
"code": null,
"e": 24676,
"s": 24663,
"text": "Old Comments"
},
{
"code": null,
"e": 24742,
"s": 24676,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 24774,
"s": 24742,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 24852,
"s": 24774,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 24869,
"s": 24852,
"text": "SQL using Python"
},
{
"code": null,
"e": 24884,
"s": 24869,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 24950,
"s": 24884,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 24986,
"s": 24950,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 25021,
"s": 24986,
"text": "SQL Query to Delete Duplicate Rows"
},
{
"code": null,
"e": 25052,
"s": 25021,
"text": "SQL Query to Compare Two Dates"
}
] |
Print triplets with sum less than k - GeeksforGeeks
|
24 May, 2021
Given an array of distinct integers and a sum value. Print all triplets with sum smaller than given sum value. Expected Time Complexity is O(n2).
Examples:
Input : arr[] = {-2, 0, 1, 3}
sum = 2.
Output : (-2, 0, 1)
(-2, 0, 3)
Explanation : The two triplets have sum less than 2.
Input : arr[] = {5, 1, 3, 4, 7}
sum = 12.
Output : (1, 3, 4)
(1, 3, 5)
(1, 3, 7)
(1, 4, 5)
A Simple Solution is to run three loops to consider all triplets one by one. For every triplet, compare the sums and print current triplet if its sum is smaller than given sum.
C++
Java
Python3
C#
PHP
Javascript
// A Simple C++ program to count triplets with sum// smaller than a given value#include<bits/stdc++.h>using namespace std; int printTriplets(int arr[], int n, int sum){ // Fix the first element as A[i] for (int i = 0; i < n-2; i++) { // Fix the second element as A[j] for (int j = i+1; j < n-1; j++) { // Now look for the third number for (int k = j+1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) cout << arr[i] << ", " << arr[j] << ", " << arr[k] << endl; } }} // Driver programint main(){ int arr[] = {5, 1, 3, 4, 7}; int n = sizeof arr / sizeof arr[0]; int sum = 12; printTriplets(arr, n, sum); return 0;}
// A Simple Java program to// count triplets with sum// smaller than a given valueimport java.io.*; class GFG{static int printTriplets(int arr[], int n, int sum){ // Fix the first // element as A[i] for (int i = 0; i < n - 2; i++) { // Fix the second // element as A[j] for (int j = i + 1; j < n - 1; j++) { // Now look for // the third number for (int k = j + 1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) System.out.println(arr[i] + ", " + arr[j] + ", " + arr[k]); } } return 0;} // Driver Codepublic static void main (String[] args){ int arr[] = {5, 1, 3, 4, 7}; int n = arr.length; int sum = 12; printTriplets(arr, n, sum);}} // This code is contributed// by anuj_67.
# A Simple python 3 program to count# triplets with sum smaller than a# given value def printTriplets(arr, n, sum): # Fix the first element as A[i] for i in range(0, n - 2, 1): # Fix the second element as A[j] for j in range(i + 1, n - 1, 1): # Now look for the third number for k in range(j + 1, n, 1): if (arr[i] + arr[j] + arr[k] < sum): print(arr[i], ",", arr[j], ",", arr[k])# Driver Codeif __name__ == '__main__': arr =[5, 1, 3, 4, 7] n = len(arr) sum = 12 printTriplets(arr, n, sum) # This code is contributed by# Sahil_Shelangia
// A Simple C# program to// count triplets with sum// smaller than a given valueusing System;class GFG{static int printTriplets(int[] arr, int n, int sum){ // Fix the first // element as A[i] for (int i = 0; i < n - 2; i++) { // Fix the second // element as A[j] for (int j = i + 1; j < n - 1; j++) { // Now look for // the third number for (int k = j + 1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) Console.WriteLine(arr[i] + ", " + arr[j] + ", " + arr[k]); } } return 0;} // Driver Codepublic static void Main (){ int[] arr = {5, 1, 3, 4, 7}; int n = arr.Length; int sum = 12; printTriplets(arr, n, sum);}} // This code is contributed// by Mukul Singh.
<?php// A Simple PHP program to count triplets// with sum smaller than a given value function printTriplets(&$arr, $n, $sum){ // Fix the first element as A[i] for ($i = 0; $i < $n - 2; $i++) { // Fix the second element as A[j] for ($j = $i + 1; $j < $n - 1; $j++) { // Now look for the third number for ($k = $j + 1; $k < $n; $k++) if ($arr[$i] + $arr[$j] + $arr[$k] < $sum) { echo($arr[$i]); echo(", " ); echo($arr[$j]); echo(", "); echo($arr[$k]); echo("\n"); } } }} // Driver Code$arr = array(5, 1, 3, 4, 7);$n = sizeof($arr);$sum = 12;printTriplets($arr, $n, $sum); // This code is contributed// by Shivi_Aggarwal?>
<script> // A Simple JavaScript program to// count triplets with sum// smaller than a given value function printTriplets(arr, n, sum){ // Fix the first element as A[i] for (let i = 0; i < n-2; i++) { // Fix the second element as A[j] for (let j = i+1; j < n-1; j++) { // Now look for the third number for (let k = j+1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) document.write(arr[i] + ", " + arr[j] + ", " + arr[k] + "<br>"); } }} // Driver program let arr = [5, 1, 3, 4, 7]; let n = arr.length; let sum = 12; printTriplets(arr, n, sum); // This code is contributed by Surbhi Tyagi. </script>
5, 1, 3
5, 1, 4
1, 3, 4
1, 3, 7
Time complexity of above solution is O(n3).
An Efficient Solution can print triplets in O(n2) by sorting the array first, and then using method 1 of this post in a loop.
1) Sort the input array in increasing order.
2) Initialize result as 0.
3) Run a loop from i = 0 to n-2. An iteration of this loop
finds all triplets with arr[i] as first element.
a) Initialize other two elements as corner elements
of subarray
arr[i+1..n-1], i.e., j = i+1 and k = n-1
b) Move j and k toward each other until they meet,
i.e., while (j = sum), then do k--
// Else for current i and j, there are (k-j) possible
// third elements that satisfy the constraint.
(ii) Else print elements from j to k
Below is the implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print triplets with sum smaller// than a given value#include <bits/stdc++.h>using namespace std; int printTriplets(int arr[], int n, int sum){ // Sort input array sort(arr, arr + n); // Every iteration of loop counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two elements as corner // elements of subarray arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the Middle concept while (j < k) { // If sum of current triplet is more or equal, // move right corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For current i and j, // there are total k-j third elements. for (int x = j + 1; x <= k; x++) cout << arr[i] << ", " << arr[j] << ", " << arr[x] << endl; j++; } } }} // Driver programint main(){ int arr[] = { 5, 1, 3, 4, 7 }; int n = sizeof arr / sizeof arr[0]; int sum = 12; printTriplets(arr, n, sum); return 0;}
// Java program to print// triplets with sum smaller// than a given valueimport java.util.*;import java.lang.*;import java.io.*; class GFG{static void printTriplets(int arr[], int n, int sum){ // Sort input array Arrays.sort(arr); // Every iteration of loop // counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the // Middle concept while (j < k) { // If sum of current triplet // is more or equal, move right // corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For // current i and j, there // are total k-j third elements. for (int x = j + 1; x <= k; x++) System.out.println(arr[i] + ", " + arr[j] + ", " + arr[x]); j++; } } }} // Driver Codepublic static void main(String args[]){ int arr[] = { 5, 1, 3, 4, 7 }; int n = arr.length; int sum = 12; printTriplets(arr, n, sum);}} // This code is contributed// by Subhadeep
# Python3 program to print# triplets with sum smaller# than a given valuedef printTriplets(arr, n, sum): # Sort input array arr.sort() # Every iteration of loop # counts triplet with # first element as arr[i]. for i in range(n - 2): # Initialize other two elements # as corner elements of subarray # arr[j+1..k] (j, k) = (i + 1, n - 1) # Use Meet in the # Middle concept while (j < k): # If sum of current triplet # is more or equal, move right # corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum): k -= 1 # Else move left corner else: # This is important. For # current i and j, there # are total k-j third elements. for x in range(j + 1, k + 1): print(str(arr[i]) + ", " + str(arr[j]) + ", " + str(arr[x])) j += 1 # Driver codeif __name__=="__main__": arr = [ 5, 1, 3, 4, 7 ] n = len(arr) sum = 12 printTriplets(arr, n, sum); # This code is contributed by rutvik_56
// C# program to print// triplets with sum smaller// than a given valueusing System; class GFG{static void printTriplets(int[] arr, int n, int sum){ // Sort input array Array.Sort(arr); // Every iteration of loop // counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the // Middle concept while (j < k) { // If sum of current triplet // is more or equal, move right // corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For // current i and j, there // are total k-j third elements. for (int x = j + 1; x <= k; x++) Console.WriteLine(arr[i] + ", " + arr[j] + ", " + arr[x]); j++; } } }} // Driver Codepublic static void Main(){ int[] arr = { 5, 1, 3, 4, 7 }; int n = arr.Length; int sum = 12; printTriplets(arr, n, sum);}} // This code is contributed// by Akanksha Rai
<?php// PHP program to print triplets with// sum smaller than a given value function printTriplets($arr, $n, $sum){ // Sort input array sort($arr, 0); // Every iteration of loop counts // triplet with first element as arr[i]. for ($i = 0; $i < $n - 2; $i++) { // Initialize other two elements as corner // elements of subarray arr[j+1..k] $j = $i + 1; $k = $n - 1; // Use Meet in the Middle concept while ($j < $k) { // If sum of current triplet is more // or equal, move right corner to // look for smaller values if ($arr[$i] + $arr[$j] + $arr[$k] >= $sum) $k--; // Else move left corner else { // This is important. For current i and j, // there are total k-j third elements. for ($x = $j + 1; $x <= $k; $x++) echo $arr[$i] . ", " . $arr[$j] . ", " . $arr[$x] . "\n"; $j++; } } }} // Driver Code$arr = array(5, 1, 3, 4, 7);$n = sizeof($arr);$sum = 12;printTriplets($arr, $n, $sum); // This code is contributed// by Akanksha Rai?>
<script> // JavaScript program to print // triplets with sum smaller // than a given value function printTriplets(arr, n, sum) { // Sort input array arr.sort(function(a, b){return a - b}); // Every iteration of loop // counts triplet with // first element as arr[i]. for (let i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] let j = i + 1, k = n - 1; // Use Meet in the // Middle concept while (j < k) { // If sum of current triplet // is more or equal, move right // corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For // current i and j, there // are total k-j third elements. for (let x = j + 1; x <= k; x++) document.write(arr[i] + ", " + arr[j] + ", " + arr[x] + "</br>"); j++; } } } } let arr = [ 5, 1, 3, 4, 7 ]; let n = arr.length; let sum = 12; printTriplets(arr, n, sum); </script>
1, 3, 4
1, 3, 5
1, 3, 7
1, 4, 5
vt_m
tufan_gupta2000
sahilshelangia
Code_Mech
Shivi_Aggarwal
Akanksha_Rai
sundarlucifer
rutvik_56
surbhityagi15
divyeshrabadiya07
two-pointer-algorithm
Arrays
Sorting
two-pointer-algorithm
Arrays
Sorting
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
|
[
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 24966,
"s": 24820,
"text": "Given an array of distinct integers and a sum value. Print all triplets with sum smaller than given sum value. Expected Time Complexity is O(n2)."
},
{
"code": null,
"e": 24977,
"s": 24966,
"text": "Examples: "
},
{
"code": null,
"e": 25263,
"s": 24977,
"text": "Input : arr[] = {-2, 0, 1, 3}\n sum = 2.\nOutput : (-2, 0, 1)\n (-2, 0, 3) \nExplanation : The two triplets have sum less than 2.\n\nInput : arr[] = {5, 1, 3, 4, 7}\n sum = 12.\nOutput : (1, 3, 4)\n (1, 3, 5)\n (1, 3, 7) \n (1, 4, 5)\n "
},
{
"code": null,
"e": 25441,
"s": 25263,
"text": "A Simple Solution is to run three loops to consider all triplets one by one. For every triplet, compare the sums and print current triplet if its sum is smaller than given sum. "
},
{
"code": null,
"e": 25445,
"s": 25441,
"text": "C++"
},
{
"code": null,
"e": 25450,
"s": 25445,
"text": "Java"
},
{
"code": null,
"e": 25458,
"s": 25450,
"text": "Python3"
},
{
"code": null,
"e": 25461,
"s": 25458,
"text": "C#"
},
{
"code": null,
"e": 25465,
"s": 25461,
"text": "PHP"
},
{
"code": null,
"e": 25476,
"s": 25465,
"text": "Javascript"
},
{
"code": "// A Simple C++ program to count triplets with sum// smaller than a given value#include<bits/stdc++.h>using namespace std; int printTriplets(int arr[], int n, int sum){ // Fix the first element as A[i] for (int i = 0; i < n-2; i++) { // Fix the second element as A[j] for (int j = i+1; j < n-1; j++) { // Now look for the third number for (int k = j+1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) cout << arr[i] << \", \" << arr[j] << \", \" << arr[k] << endl; } }} // Driver programint main(){ int arr[] = {5, 1, 3, 4, 7}; int n = sizeof arr / sizeof arr[0]; int sum = 12; printTriplets(arr, n, sum); return 0;}",
"e": 26213,
"s": 25476,
"text": null
},
{
"code": "// A Simple Java program to// count triplets with sum// smaller than a given valueimport java.io.*; class GFG{static int printTriplets(int arr[], int n, int sum){ // Fix the first // element as A[i] for (int i = 0; i < n - 2; i++) { // Fix the second // element as A[j] for (int j = i + 1; j < n - 1; j++) { // Now look for // the third number for (int k = j + 1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) System.out.println(arr[i] + \", \" + arr[j] + \", \" + arr[k]); } } return 0;} // Driver Codepublic static void main (String[] args){ int arr[] = {5, 1, 3, 4, 7}; int n = arr.length; int sum = 12; printTriplets(arr, n, sum);}} // This code is contributed// by anuj_67.",
"e": 27095,
"s": 26213,
"text": null
},
{
"code": "# A Simple python 3 program to count# triplets with sum smaller than a# given value def printTriplets(arr, n, sum): # Fix the first element as A[i] for i in range(0, n - 2, 1): # Fix the second element as A[j] for j in range(i + 1, n - 1, 1): # Now look for the third number for k in range(j + 1, n, 1): if (arr[i] + arr[j] + arr[k] < sum): print(arr[i], \",\", arr[j], \",\", arr[k])# Driver Codeif __name__ == '__main__': arr =[5, 1, 3, 4, 7] n = len(arr) sum = 12 printTriplets(arr, n, sum) # This code is contributed by# Sahil_Shelangia",
"e": 27751,
"s": 27095,
"text": null
},
{
"code": "// A Simple C# program to// count triplets with sum// smaller than a given valueusing System;class GFG{static int printTriplets(int[] arr, int n, int sum){ // Fix the first // element as A[i] for (int i = 0; i < n - 2; i++) { // Fix the second // element as A[j] for (int j = i + 1; j < n - 1; j++) { // Now look for // the third number for (int k = j + 1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) Console.WriteLine(arr[i] + \", \" + arr[j] + \", \" + arr[k]); } } return 0;} // Driver Codepublic static void Main (){ int[] arr = {5, 1, 3, 4, 7}; int n = arr.Length; int sum = 12; printTriplets(arr, n, sum);}} // This code is contributed// by Mukul Singh.",
"e": 28608,
"s": 27751,
"text": null
},
{
"code": "<?php// A Simple PHP program to count triplets// with sum smaller than a given value function printTriplets(&$arr, $n, $sum){ // Fix the first element as A[i] for ($i = 0; $i < $n - 2; $i++) { // Fix the second element as A[j] for ($j = $i + 1; $j < $n - 1; $j++) { // Now look for the third number for ($k = $j + 1; $k < $n; $k++) if ($arr[$i] + $arr[$j] + $arr[$k] < $sum) { echo($arr[$i]); echo(\", \" ); echo($arr[$j]); echo(\", \"); echo($arr[$k]); echo(\"\\n\"); } } }} // Driver Code$arr = array(5, 1, 3, 4, 7);$n = sizeof($arr);$sum = 12;printTriplets($arr, $n, $sum); // This code is contributed// by Shivi_Aggarwal?>",
"e": 29415,
"s": 28608,
"text": null
},
{
"code": "<script> // A Simple JavaScript program to// count triplets with sum// smaller than a given value function printTriplets(arr, n, sum){ // Fix the first element as A[i] for (let i = 0; i < n-2; i++) { // Fix the second element as A[j] for (let j = i+1; j < n-1; j++) { // Now look for the third number for (let k = j+1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) document.write(arr[i] + \", \" + arr[j] + \", \" + arr[k] + \"<br>\"); } }} // Driver program let arr = [5, 1, 3, 4, 7]; let n = arr.length; let sum = 12; printTriplets(arr, n, sum); // This code is contributed by Surbhi Tyagi. </script>",
"e": 30110,
"s": 29415,
"text": null
},
{
"code": null,
"e": 30142,
"s": 30110,
"text": "5, 1, 3\n5, 1, 4\n1, 3, 4\n1, 3, 7"
},
{
"code": null,
"e": 30188,
"s": 30144,
"text": "Time complexity of above solution is O(n3)."
},
{
"code": null,
"e": 30314,
"s": 30188,
"text": "An Efficient Solution can print triplets in O(n2) by sorting the array first, and then using method 1 of this post in a loop."
},
{
"code": null,
"e": 30889,
"s": 30314,
"text": "1) Sort the input array in increasing order.\n2) Initialize result as 0.\n3) Run a loop from i = 0 to n-2. An iteration of this loop \n finds all triplets with arr[i] as first element.\n a) Initialize other two elements as corner elements\n of subarray\n arr[i+1..n-1], i.e., j = i+1 and k = n-1\n b) Move j and k toward each other until they meet,\n i.e., while (j = sum), then do k--\n\n // Else for current i and j, there are (k-j) possible \n // third elements that satisfy the constraint.\n (ii) Else print elements from j to k"
},
{
"code": null,
"e": 30933,
"s": 30889,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 30937,
"s": 30933,
"text": "C++"
},
{
"code": null,
"e": 30942,
"s": 30937,
"text": "Java"
},
{
"code": null,
"e": 30950,
"s": 30942,
"text": "Python3"
},
{
"code": null,
"e": 30953,
"s": 30950,
"text": "C#"
},
{
"code": null,
"e": 30957,
"s": 30953,
"text": "PHP"
},
{
"code": null,
"e": 30968,
"s": 30957,
"text": "Javascript"
},
{
"code": "// C++ program to print triplets with sum smaller// than a given value#include <bits/stdc++.h>using namespace std; int printTriplets(int arr[], int n, int sum){ // Sort input array sort(arr, arr + n); // Every iteration of loop counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two elements as corner // elements of subarray arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the Middle concept while (j < k) { // If sum of current triplet is more or equal, // move right corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For current i and j, // there are total k-j third elements. for (int x = j + 1; x <= k; x++) cout << arr[i] << \", \" << arr[j] << \", \" << arr[x] << endl; j++; } } }} // Driver programint main(){ int arr[] = { 5, 1, 3, 4, 7 }; int n = sizeof arr / sizeof arr[0]; int sum = 12; printTriplets(arr, n, sum); return 0;}",
"e": 32203,
"s": 30968,
"text": null
},
{
"code": "// Java program to print// triplets with sum smaller// than a given valueimport java.util.*;import java.lang.*;import java.io.*; class GFG{static void printTriplets(int arr[], int n, int sum){ // Sort input array Arrays.sort(arr); // Every iteration of loop // counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the // Middle concept while (j < k) { // If sum of current triplet // is more or equal, move right // corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For // current i and j, there // are total k-j third elements. for (int x = j + 1; x <= k; x++) System.out.println(arr[i] + \", \" + arr[j] + \", \" + arr[x]); j++; } } }} // Driver Codepublic static void main(String args[]){ int arr[] = { 5, 1, 3, 4, 7 }; int n = arr.length; int sum = 12; printTriplets(arr, n, sum);}} // This code is contributed// by Subhadeep",
"e": 33665,
"s": 32203,
"text": null
},
{
"code": "# Python3 program to print# triplets with sum smaller# than a given valuedef printTriplets(arr, n, sum): # Sort input array arr.sort() # Every iteration of loop # counts triplet with # first element as arr[i]. for i in range(n - 2): # Initialize other two elements # as corner elements of subarray # arr[j+1..k] (j, k) = (i + 1, n - 1) # Use Meet in the # Middle concept while (j < k): # If sum of current triplet # is more or equal, move right # corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum): k -= 1 # Else move left corner else: # This is important. For # current i and j, there # are total k-j third elements. for x in range(j + 1, k + 1): print(str(arr[i]) + \", \" + str(arr[j]) + \", \" + str(arr[x])) j += 1 # Driver codeif __name__==\"__main__\": arr = [ 5, 1, 3, 4, 7 ] n = len(arr) sum = 12 printTriplets(arr, n, sum); # This code is contributed by rutvik_56",
"e": 34898,
"s": 33665,
"text": null
},
{
"code": "// C# program to print// triplets with sum smaller// than a given valueusing System; class GFG{static void printTriplets(int[] arr, int n, int sum){ // Sort input array Array.Sort(arr); // Every iteration of loop // counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the // Middle concept while (j < k) { // If sum of current triplet // is more or equal, move right // corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For // current i and j, there // are total k-j third elements. for (int x = j + 1; x <= k; x++) Console.WriteLine(arr[i] + \", \" + arr[j] + \", \" + arr[x]); j++; } } }} // Driver Codepublic static void Main(){ int[] arr = { 5, 1, 3, 4, 7 }; int n = arr.Length; int sum = 12; printTriplets(arr, n, sum);}} // This code is contributed// by Akanksha Rai",
"e": 36295,
"s": 34898,
"text": null
},
{
"code": "<?php// PHP program to print triplets with// sum smaller than a given value function printTriplets($arr, $n, $sum){ // Sort input array sort($arr, 0); // Every iteration of loop counts // triplet with first element as arr[i]. for ($i = 0; $i < $n - 2; $i++) { // Initialize other two elements as corner // elements of subarray arr[j+1..k] $j = $i + 1; $k = $n - 1; // Use Meet in the Middle concept while ($j < $k) { // If sum of current triplet is more // or equal, move right corner to // look for smaller values if ($arr[$i] + $arr[$j] + $arr[$k] >= $sum) $k--; // Else move left corner else { // This is important. For current i and j, // there are total k-j third elements. for ($x = $j + 1; $x <= $k; $x++) echo $arr[$i] . \", \" . $arr[$j] . \", \" . $arr[$x] . \"\\n\"; $j++; } } }} // Driver Code$arr = array(5, 1, 3, 4, 7);$n = sizeof($arr);$sum = 12;printTriplets($arr, $n, $sum); // This code is contributed// by Akanksha Rai?>",
"e": 37530,
"s": 36295,
"text": null
},
{
"code": "<script> // JavaScript program to print // triplets with sum smaller // than a given value function printTriplets(arr, n, sum) { // Sort input array arr.sort(function(a, b){return a - b}); // Every iteration of loop // counts triplet with // first element as arr[i]. for (let i = 0; i < n - 2; i++) { // Initialize other two elements // as corner elements of subarray // arr[j+1..k] let j = i + 1, k = n - 1; // Use Meet in the // Middle concept while (j < k) { // If sum of current triplet // is more or equal, move right // corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For // current i and j, there // are total k-j third elements. for (let x = j + 1; x <= k; x++) document.write(arr[i] + \", \" + arr[j] + \", \" + arr[x] + \"</br>\"); j++; } } } } let arr = [ 5, 1, 3, 4, 7 ]; let n = arr.length; let sum = 12; printTriplets(arr, n, sum); </script>",
"e": 39003,
"s": 37530,
"text": null
},
{
"code": null,
"e": 39035,
"s": 39003,
"text": "1, 3, 4\n1, 3, 5\n1, 3, 7\n1, 4, 5"
},
{
"code": null,
"e": 39042,
"s": 39037,
"text": "vt_m"
},
{
"code": null,
"e": 39058,
"s": 39042,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 39073,
"s": 39058,
"text": "sahilshelangia"
},
{
"code": null,
"e": 39083,
"s": 39073,
"text": "Code_Mech"
},
{
"code": null,
"e": 39098,
"s": 39083,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 39111,
"s": 39098,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 39125,
"s": 39111,
"text": "sundarlucifer"
},
{
"code": null,
"e": 39135,
"s": 39125,
"text": "rutvik_56"
},
{
"code": null,
"e": 39149,
"s": 39135,
"text": "surbhityagi15"
},
{
"code": null,
"e": 39167,
"s": 39149,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 39189,
"s": 39167,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 39196,
"s": 39189,
"text": "Arrays"
},
{
"code": null,
"e": 39204,
"s": 39196,
"text": "Sorting"
},
{
"code": null,
"e": 39226,
"s": 39204,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 39233,
"s": 39226,
"text": "Arrays"
},
{
"code": null,
"e": 39241,
"s": 39233,
"text": "Sorting"
},
{
"code": null,
"e": 39339,
"s": 39241,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39364,
"s": 39339,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 39384,
"s": 39364,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 39422,
"s": 39384,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 39471,
"s": 39422,
"text": "Program to find sum of elements in a given array"
}
] |
Python 3 - File truncate() Method
|
The method truncate() truncates the file's size. If the optional size argument is present, the file is truncated to (at most) that size.
The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file's current size, the result is platform-dependent.
Note − This method would not work in case file is opened in read-only mode.
Following is the syntax for truncate() method −
fileObject.truncate( [ size ])
size − If this optional argument is present, the file is truncated to (at most) that size.
This method does not return any value.
The following example shows the usage of truncate() method.
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
#!/usr/bin/python3
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
fo.truncate()
line = fo.readlines()
print ("Read Line: %s" % (line))
# Close opened file
fo.close()
When we run the above program, it produces the following result −
Name of the file: foo.txt
Read Line: This is 1s
Read Line: []
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": 2477,
"s": 2340,
"text": "The method truncate() truncates the file's size. If the optional size argument is present, the file is truncated to (at most) that size."
},
{
"code": null,
"e": 2659,
"s": 2477,
"text": "The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file's current size, the result is platform-dependent."
},
{
"code": null,
"e": 2735,
"s": 2659,
"text": "Note − This method would not work in case file is opened in read-only mode."
},
{
"code": null,
"e": 2783,
"s": 2735,
"text": "Following is the syntax for truncate() method −"
},
{
"code": null,
"e": 2815,
"s": 2783,
"text": "fileObject.truncate( [ size ])\n"
},
{
"code": null,
"e": 2906,
"s": 2815,
"text": "size − If this optional argument is present, the file is truncated to (at most) that size."
},
{
"code": null,
"e": 2945,
"s": 2906,
"text": "This method does not return any value."
},
{
"code": null,
"e": 3005,
"s": 2945,
"text": "The following example shows the usage of truncate() method."
},
{
"code": null,
"e": 3145,
"s": 3005,
"text": "Assuming that 'foo.txt' file contains following text:\nThis is 1st line\nThis is 2nd line\nThis is 3rd line\nThis is 4th line\nThis is 5th line\n"
},
{
"code": null,
"e": 3387,
"s": 3145,
"text": "#!/usr/bin/python3\n\nfo = open(\"foo.txt\", \"r+\")\nprint (\"Name of the file: \", fo.name)\n\nline = fo.readline()\nprint (\"Read Line: %s\" % (line))\n\nfo.truncate()\nline = fo.readlines()\nprint (\"Read Line: %s\" % (line))\n\n# Close opened file\nfo.close()"
},
{
"code": null,
"e": 3453,
"s": 3387,
"text": "When we run the above program, it produces the following result −"
},
{
"code": null,
"e": 3517,
"s": 3453,
"text": "Name of the file: foo.txt\nRead Line: This is 1s\nRead Line: []\n"
},
{
"code": null,
"e": 3554,
"s": 3517,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3570,
"s": 3554,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3603,
"s": 3570,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3622,
"s": 3603,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3657,
"s": 3622,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3679,
"s": 3657,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3713,
"s": 3679,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3741,
"s": 3713,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3776,
"s": 3741,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3790,
"s": 3776,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3823,
"s": 3790,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3840,
"s": 3823,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3847,
"s": 3840,
"text": " Print"
},
{
"code": null,
"e": 3858,
"s": 3847,
"text": " Add Notes"
}
] |
C library function - fread()
|
The C library function size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) reads data from the given stream into the array pointed to, by ptr.
Following is the declaration for fread() function.
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
ptr − This is the pointer to a block of memory with a minimum size of size*nmemb bytes.
ptr − This is the pointer to a block of memory with a minimum size of size*nmemb bytes.
size − This is the size in bytes of each element to be read.
size − This is the size in bytes of each element to be read.
nmemb − This is the number of elements, each one with a size of size bytes.
nmemb − This is the number of elements, each one with a size of size bytes.
stream − This is the pointer to a FILE object that specifies an input stream.
stream − This is the pointer to a FILE object that specifies an input stream.
The total number of elements successfully read are returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, then either an error had occurred or the End Of File was reached.
The following example shows the usage of fread() function.
#include <stdio.h>
#include <string.h>
int main () {
FILE *fp;
char c[] = "this is tutorialspoint";
char buffer[100];
/* Open file for both reading and writing */
fp = fopen("file.txt", "w+");
/* Write data to the file */
fwrite(c, strlen(c) + 1, 1, fp);
/* Seek to the beginning of the file */
fseek(fp, 0, SEEK_SET);
/* Read and display data */
fread(buffer, strlen(c)+1, 1, fp);
printf("%s\n", buffer);
fclose(fp);
return(0);
}
Let us compile and run the above program that will create a file file.txt and write a content this is tutorialspoint. After that, we use fseek() function to reset writing pointer to the beginning of the file and prepare the file content which is as follows −
this is tutorialspoint
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2163,
"s": 2007,
"text": "The C library function size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) reads data from the given stream into the array pointed to, by ptr."
},
{
"code": null,
"e": 2214,
"s": 2163,
"text": "Following is the declaration for fread() function."
},
{
"code": null,
"e": 2279,
"s": 2214,
"text": "size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)"
},
{
"code": null,
"e": 2367,
"s": 2279,
"text": "ptr − This is the pointer to a block of memory with a minimum size of size*nmemb bytes."
},
{
"code": null,
"e": 2455,
"s": 2367,
"text": "ptr − This is the pointer to a block of memory with a minimum size of size*nmemb bytes."
},
{
"code": null,
"e": 2516,
"s": 2455,
"text": "size − This is the size in bytes of each element to be read."
},
{
"code": null,
"e": 2577,
"s": 2516,
"text": "size − This is the size in bytes of each element to be read."
},
{
"code": null,
"e": 2653,
"s": 2577,
"text": "nmemb − This is the number of elements, each one with a size of size bytes."
},
{
"code": null,
"e": 2729,
"s": 2653,
"text": "nmemb − This is the number of elements, each one with a size of size bytes."
},
{
"code": null,
"e": 2807,
"s": 2729,
"text": "stream − This is the pointer to a FILE object that specifies an input stream."
},
{
"code": null,
"e": 2885,
"s": 2807,
"text": "stream − This is the pointer to a FILE object that specifies an input stream."
},
{
"code": null,
"e": 3112,
"s": 2885,
"text": "The total number of elements successfully read are returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, then either an error had occurred or the End Of File was reached."
},
{
"code": null,
"e": 3171,
"s": 3112,
"text": "The following example shows the usage of fread() function."
},
{
"code": null,
"e": 3653,
"s": 3171,
"text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n FILE *fp;\n char c[] = \"this is tutorialspoint\";\n char buffer[100];\n\n /* Open file for both reading and writing */\n fp = fopen(\"file.txt\", \"w+\");\n\n /* Write data to the file */\n fwrite(c, strlen(c) + 1, 1, fp);\n\n /* Seek to the beginning of the file */\n fseek(fp, 0, SEEK_SET);\n\n /* Read and display data */\n fread(buffer, strlen(c)+1, 1, fp);\n printf(\"%s\\n\", buffer);\n fclose(fp);\n \n return(0);\n}"
},
{
"code": null,
"e": 3912,
"s": 3653,
"text": "Let us compile and run the above program that will create a file file.txt and write a content this is tutorialspoint. After that, we use fseek() function to reset writing pointer to the beginning of the file and prepare the file content which is as follows −"
},
{
"code": null,
"e": 3936,
"s": 3912,
"text": "this is tutorialspoint\n"
},
{
"code": null,
"e": 3969,
"s": 3936,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3984,
"s": 3969,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4019,
"s": 3984,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4034,
"s": 4019,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4069,
"s": 4034,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4083,
"s": 4069,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4116,
"s": 4083,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4134,
"s": 4116,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 4169,
"s": 4134,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4188,
"s": 4169,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 4221,
"s": 4188,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4233,
"s": 4221,
"text": " Amit Diwan"
},
{
"code": null,
"e": 4240,
"s": 4233,
"text": " Print"
},
{
"code": null,
"e": 4251,
"s": 4240,
"text": " Add Notes"
}
] |
Read a character from standard input without waiting for a newline in C++
|
A portable solution doesn't exist for doing this. On windows, you can use the getch() function from the conio(Console I/O) library to get characters pressed.
#include<iostream>
#include<conio.h>
using namespace std;
int main() {
char c;
while(1){ // infinite loop
c = getch();
cout << c;
}
}
This will output whatever character you input to the terminal. Note that this will only work on windows as the conio library exists only on windows. On UNIX, you can achieve this by entering in system raw mode.
#include<iostream>
#include<stdio.h>
int main() {
char c;
// Set the terminal to raw mode
system("stty raw");
while(1) {
c = getchar();
// terminate when "." is pressed
if(c == '.') {
system("stty cooked");
exit(0);
}
std::cout << c << " was pressed."<< std::endl;
}
}
|
[
{
"code": null,
"e": 1220,
"s": 1062,
"text": "A portable solution doesn't exist for doing this. On windows, you can use the getch() function from the conio(Console I/O) library to get characters pressed."
},
{
"code": null,
"e": 1382,
"s": 1220,
"text": "#include<iostream>\n#include<conio.h>\nusing namespace std;\nint main() {\n char c;\n while(1){ // infinite loop\n c = getch();\n cout << c;\n }\n}"
},
{
"code": null,
"e": 1594,
"s": 1382,
"text": "This will output whatever character you input to the terminal. Note that this will only work on windows as the conio library exists only on windows. On UNIX, you can achieve this by entering in system raw mode. "
},
{
"code": null,
"e": 1948,
"s": 1594,
"text": "#include<iostream>\n#include<stdio.h>\nint main() {\n char c;\n // Set the terminal to raw mode\n system(\"stty raw\");\n while(1) {\n c = getchar();\n // terminate when \".\" is pressed\n if(c == '.') {\n system(\"stty cooked\");\n exit(0);\n } \n std::cout << c << \" was pressed.\"<< std::endl;\n }\n}"
}
] |
How to print object by id in an array of objects in JavaScript? - GeeksforGeeks
|
22 Feb, 2021
We have an array of objects and in every object, there is a key named id and whose value is a number.
Example:
const arr = [
{
'id' : 12,
'name' : 'Ram'
},
{
'id' : 32,
'name' : 'Shyam'
}
]
We want to find the value of the name property whose id number is n.
Example :
Input : 12
Output : Ram
Input : 32
Output : Shyam
There are many approaches to solve this problem which are following
Using Array.filter( )
Using Array.find( )
UsingLoops in JavaScript
Using Array.filter( ) Array.filter( ) method is used for creating a new array from an existing array after applying some conditions.
HTML
<!DOCTYPE html><html> <body> <h1>Geeksforgeeks</h1> <p>Name of the id is : <span id="geeks"></span> </p> <script> // This is our array of Objects var data = [ { id: 1, name: "a" }, { id: 2, name: "b" }, { id: 3, name: "c" }, { id: 4, name: "d" }, { id: 5, name: "e" }, { id: 6, name: "f" }, ]; let idYouWant = 1; let propertyYouWant = "name"; // Using Array.filter( ) method // we are iterating through each // items in the array and // checking which item's // id value is equal to the id we want let res = data.filter((item) => { return item.id == idYouWant; }); // After using filter method we got an array // of object. Now take its first element and // use its 'propertyYouWant' key let exactRes = res[0][propertyYouWant]; // Printing the property we want document.getElementById("geeks").innerText = exactRes; </script> </body></html>
Output:
Using Array.find( ): Using Array.find( ) first we are searching in which object the given id exists, then we extract the name property from that object.
HTML
<!DOCTYPE html><html> <body> <h1>Geeksforgeeks</h1> <p>Name of the id is : <span id="geeks"></span> </p> <script> // This is our array of Objects var data = [ { id: 1, name: "a" }, { id: 2, name: "b" }, { id: 3, name: "c" }, { id: 4, name: "d" }, { id: 5, name: "e" }, { id: 6, name: "f" }, ]; let idYouWant = 2; let propertyYouWant = "name"; // Using Array.find( ) we are searching // in which object our searching id present let res = data.find((item) => { return item.id == idYouWant; }); // Now print the property which you want from // the object res console.log(res[propertyYouWant]) document.getElementById("geeks").innerText = res[propertyYouWant]; </script> </body></html>
Output:
Using for loop Using for loop first we are iterating the array and searching in which object the given id present and after that, we are printing the property we wanted.
HTML
<!DOCTYPE html><html> <body> <h1>Geeksforgeeks</h1> <p>Name of the id is : <span id="geeks"></span> </p> <script> // This is our array of objects var data = [ { id: 1, name: "a" }, { id: 2, name: "b" }, { id: 3, name: "c" }, { id: 4, name: "d" }, { id: 5, name: "e" }, { id: 6, name: "f" }, ]; let idYouWant = 4; let propertyYouWant = "name"; // Iterating over the array using for loop and // searching in which object the id present // After getting the object we print the // property we wanted from the object for (var i = 0; i < data.length; i++) { if (data[i].id == idYouWant) { // console.log(data[i][propertyYouWant]) document.getElementById("geeks").innerText = data[i][propertyYouWant]; } } </script> </body></html>
Output :
javascript-array
javascript-object
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 37970,
"s": 37942,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 38072,
"s": 37970,
"text": "We have an array of objects and in every object, there is a key named id and whose value is a number."
},
{
"code": null,
"e": 38081,
"s": 38072,
"text": "Example:"
},
{
"code": null,
"e": 38258,
"s": 38081,
"text": "const arr = [\n {\n 'id' : 12, \n 'name' : 'Ram'\n }, \n {\n 'id' : 32, \n 'name' : 'Shyam'\n }\n ]"
},
{
"code": null,
"e": 38327,
"s": 38258,
"text": "We want to find the value of the name property whose id number is n."
},
{
"code": null,
"e": 38337,
"s": 38327,
"text": "Example :"
},
{
"code": null,
"e": 38388,
"s": 38337,
"text": "Input : 12\nOutput : Ram\n\nInput : 32\nOutput : Shyam"
},
{
"code": null,
"e": 38457,
"s": 38388,
"text": "There are many approaches to solve this problem which are following "
},
{
"code": null,
"e": 38479,
"s": 38457,
"text": "Using Array.filter( )"
},
{
"code": null,
"e": 38500,
"s": 38479,
"text": "Using Array.find( ) "
},
{
"code": null,
"e": 38525,
"s": 38500,
"text": "UsingLoops in JavaScript"
},
{
"code": null,
"e": 38658,
"s": 38525,
"text": "Using Array.filter( ) Array.filter( ) method is used for creating a new array from an existing array after applying some conditions."
},
{
"code": null,
"e": 38663,
"s": 38658,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>Geeksforgeeks</h1> <p>Name of the id is : <span id=\"geeks\"></span> </p> <script> // This is our array of Objects var data = [ { id: 1, name: \"a\" }, { id: 2, name: \"b\" }, { id: 3, name: \"c\" }, { id: 4, name: \"d\" }, { id: 5, name: \"e\" }, { id: 6, name: \"f\" }, ]; let idYouWant = 1; let propertyYouWant = \"name\"; // Using Array.filter( ) method // we are iterating through each // items in the array and // checking which item's // id value is equal to the id we want let res = data.filter((item) => { return item.id == idYouWant; }); // After using filter method we got an array // of object. Now take its first element and // use its 'propertyYouWant' key let exactRes = res[0][propertyYouWant]; // Printing the property we want document.getElementById(\"geeks\").innerText = exactRes; </script> </body></html>",
"e": 39884,
"s": 38663,
"text": null
},
{
"code": null,
"e": 39892,
"s": 39884,
"text": "Output:"
},
{
"code": null,
"e": 40045,
"s": 39892,
"text": "Using Array.find( ): Using Array.find( ) first we are searching in which object the given id exists, then we extract the name property from that object."
},
{
"code": null,
"e": 40050,
"s": 40045,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>Geeksforgeeks</h1> <p>Name of the id is : <span id=\"geeks\"></span> </p> <script> // This is our array of Objects var data = [ { id: 1, name: \"a\" }, { id: 2, name: \"b\" }, { id: 3, name: \"c\" }, { id: 4, name: \"d\" }, { id: 5, name: \"e\" }, { id: 6, name: \"f\" }, ]; let idYouWant = 2; let propertyYouWant = \"name\"; // Using Array.find( ) we are searching // in which object our searching id present let res = data.find((item) => { return item.id == idYouWant; }); // Now print the property which you want from // the object res console.log(res[propertyYouWant]) document.getElementById(\"geeks\").innerText = res[propertyYouWant]; </script> </body></html>",
"e": 41064,
"s": 40050,
"text": null
},
{
"code": null,
"e": 41072,
"s": 41064,
"text": "Output:"
},
{
"code": null,
"e": 41242,
"s": 41072,
"text": "Using for loop Using for loop first we are iterating the array and searching in which object the given id present and after that, we are printing the property we wanted."
},
{
"code": null,
"e": 41247,
"s": 41242,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>Geeksforgeeks</h1> <p>Name of the id is : <span id=\"geeks\"></span> </p> <script> // This is our array of objects var data = [ { id: 1, name: \"a\" }, { id: 2, name: \"b\" }, { id: 3, name: \"c\" }, { id: 4, name: \"d\" }, { id: 5, name: \"e\" }, { id: 6, name: \"f\" }, ]; let idYouWant = 4; let propertyYouWant = \"name\"; // Iterating over the array using for loop and // searching in which object the id present // After getting the object we print the // property we wanted from the object for (var i = 0; i < data.length; i++) { if (data[i].id == idYouWant) { // console.log(data[i][propertyYouWant]) document.getElementById(\"geeks\").innerText = data[i][propertyYouWant]; } } </script> </body></html>",
"e": 42339,
"s": 41247,
"text": null
},
{
"code": null,
"e": 42348,
"s": 42339,
"text": "Output :"
},
{
"code": null,
"e": 42365,
"s": 42348,
"text": "javascript-array"
},
{
"code": null,
"e": 42383,
"s": 42365,
"text": "javascript-object"
},
{
"code": null,
"e": 42404,
"s": 42383,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 42415,
"s": 42404,
"text": "JavaScript"
},
{
"code": null,
"e": 42432,
"s": 42415,
"text": "Web Technologies"
},
{
"code": null,
"e": 42530,
"s": 42432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42575,
"s": 42530,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42636,
"s": 42575,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 42705,
"s": 42636,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 42777,
"s": 42705,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 42829,
"s": 42777,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 42871,
"s": 42829,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 42904,
"s": 42871,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 42947,
"s": 42904,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 42997,
"s": 42947,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
GATE | GATE CS 2013 | Question 28 - GeeksforGeeks
|
19 Nov, 2018
Consider the following sequence of micro-operations.
MBR ← PC
MAR ← X
PC ← Y
Memory ← MBR
Which one of the following is a possible operation performed by this sequence?(A) Instruction fetch(B) Operand fetch(C) Conditional branch(D) Initiation of interrupt serviceAnswer: (D)Explanation: MBR – Memory Buffer Register ( that stores the data being transferred to and from the immediate access store)
MAR – Memory Address Register ( that holds the memory location of data that needs to be accessed.)
PC – Program Counter ( It contains the address of the instruction being executed at the current time )
The 1st instruction places the value of PC into MBR
The 2nd instruction places an address X into MAR.
The 3rd instruction places an address Y into PC.
The 4th instruction places the value of MBR ( which was the old PC value) into Memory.
Now it can be seen from the 1st and the 4th instructions, that the control flow was not sequential and the value of PC was stored in the memory, so that the control can again come back to the address where it left the execution.
This behavior is seen in the case of interrupt handling. And here X can be the address of the location in the memory which contains the beginning address of Interrupt service routine.And Y can be the beginning address of Interrupt service routine.
In case of conditional branch (as for option C ) only PC is updated with the target address and there is no need to store the old PC value into the memory.
And in the case of Instruction fetch and operand fetch ( as for option A and B), PC value is not stored anywhere else.
Hence option D.Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
|
[
{
"code": null,
"e": 24326,
"s": 24298,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 24379,
"s": 24326,
"text": "Consider the following sequence of micro-operations."
},
{
"code": null,
"e": 24441,
"s": 24379,
"text": " MBR ← PC \n MAR ← X \n PC ← Y \n Memory ← MBR"
},
{
"code": null,
"e": 24748,
"s": 24441,
"text": "Which one of the following is a possible operation performed by this sequence?(A) Instruction fetch(B) Operand fetch(C) Conditional branch(D) Initiation of interrupt serviceAnswer: (D)Explanation: MBR – Memory Buffer Register ( that stores the data being transferred to and from the immediate access store)"
},
{
"code": null,
"e": 24847,
"s": 24748,
"text": "MAR – Memory Address Register ( that holds the memory location of data that needs to be accessed.)"
},
{
"code": null,
"e": 24950,
"s": 24847,
"text": "PC – Program Counter ( It contains the address of the instruction being executed at the current time )"
},
{
"code": null,
"e": 25002,
"s": 24950,
"text": "The 1st instruction places the value of PC into MBR"
},
{
"code": null,
"e": 25052,
"s": 25002,
"text": "The 2nd instruction places an address X into MAR."
},
{
"code": null,
"e": 25101,
"s": 25052,
"text": "The 3rd instruction places an address Y into PC."
},
{
"code": null,
"e": 25188,
"s": 25101,
"text": "The 4th instruction places the value of MBR ( which was the old PC value) into Memory."
},
{
"code": null,
"e": 25417,
"s": 25188,
"text": "Now it can be seen from the 1st and the 4th instructions, that the control flow was not sequential and the value of PC was stored in the memory, so that the control can again come back to the address where it left the execution."
},
{
"code": null,
"e": 25665,
"s": 25417,
"text": "This behavior is seen in the case of interrupt handling. And here X can be the address of the location in the memory which contains the beginning address of Interrupt service routine.And Y can be the beginning address of Interrupt service routine."
},
{
"code": null,
"e": 25821,
"s": 25665,
"text": "In case of conditional branch (as for option C ) only PC is updated with the target address and there is no need to store the old PC value into the memory."
},
{
"code": null,
"e": 25940,
"s": 25821,
"text": "And in the case of Instruction fetch and operand fetch ( as for option A and B), PC value is not stored anywhere else."
},
{
"code": null,
"e": 25977,
"s": 25940,
"text": "Hence option D.Quiz of this Question"
},
{
"code": null,
"e": 25990,
"s": 25977,
"text": "GATE-CS-2013"
},
{
"code": null,
"e": 26008,
"s": 25990,
"text": "GATE-GATE CS 2013"
},
{
"code": null,
"e": 26013,
"s": 26008,
"text": "GATE"
},
{
"code": null,
"e": 26111,
"s": 26013,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26145,
"s": 26111,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 26187,
"s": 26145,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 26229,
"s": 26187,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26263,
"s": 26229,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 26296,
"s": 26263,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 26330,
"s": 26296,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 26364,
"s": 26330,
"text": "GATE | GATE CS 2011 | Question 65"
},
{
"code": null,
"e": 26398,
"s": 26364,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 26440,
"s": 26398,
"text": "GATE | GATE CS 2021 | Set 1 | Question 47"
}
] |
Groovy - Lists get()
|
Returns the element at the specified position in this List.
Object get(int index)
Index – The index at which the value needs to be returned.
The value at the index position in the list.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
def lst = [11, 12, 13, 14];
println(lst.get(0));
println(lst.get(2));
}
}
When we run the above program, we will get the following result −
11
13
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2298,
"s": 2238,
"text": "Returns the element at the specified position in this List."
},
{
"code": null,
"e": 2321,
"s": 2298,
"text": "Object get(int index)\n"
},
{
"code": null,
"e": 2380,
"s": 2321,
"text": "Index – The index at which the value needs to be returned."
},
{
"code": null,
"e": 2425,
"s": 2380,
"text": "The value at the index position in the list."
},
{
"code": null,
"e": 2479,
"s": 2425,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 2628,
"s": 2479,
"text": "class Example {\n static void main(String[] args) {\n def lst = [11, 12, 13, 14];\n println(lst.get(0));\n println(lst.get(2));\n } \n}"
},
{
"code": null,
"e": 2694,
"s": 2628,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 2702,
"s": 2694,
"text": "11 \n13\n"
},
{
"code": null,
"e": 2735,
"s": 2702,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2753,
"s": 2735,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 2788,
"s": 2753,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2806,
"s": 2788,
"text": " Packt Publishing"
},
{
"code": null,
"e": 2813,
"s": 2806,
"text": " Print"
},
{
"code": null,
"e": 2824,
"s": 2813,
"text": " Add Notes"
}
] |
Performing regex Queries with PyMongo?
|
PyMongo is a Python distribution containing tools for working with MongoDB. To perform regex queries with PyMongo, the syntax is as follows −
db.yourCollectionName.find({'yourCollectionName':{'$regex':'^yourWords'}}).pretty();
The above syntax will give all those documents that start from a specific word.
To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.performRegex.insertOne({"ClientName":"Larry","ClientFolderInformation":[
"Folder 1","Folder 2","Folder 3","Folder 4","Folder 5"], "MainFolderLocation":"/MainFolder/Details/ClientFolder" });
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a8b186cea1f28b7aa07f2")
}
> db.performRegex.insertOne({"ClientName":"Larry","ClientFolderInformation":[
"ClientFolder 1","ClientFolder 2","ClientFolder 3","ClientFolder 4","ClientFolder 5"],
"MainFolderLocation":"/MainFolder/Details/ClientFolder" });
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a8b1d6cea1f28b7aa07f3")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.performRegex.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c8a8b186cea1f28b7aa07f2"),
"ClientName" : "Larry",
"ClientFolderInformation" : [
"Folder 1",
"Folder 2",
"Folder 3",
"Folder 4",
"Folder 5"
],
"MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}
{
"_id" : ObjectId("5c8a8b1d6cea1f28b7aa07f3"),
"ClientName" : "Larry",
"ClientFolderInformation" : [
"ClientFolder 1",
"ClientFolder 2",
"ClientFolder 3",
"ClientFolder 4",
"ClientFolder 5"
],
"MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}
Here is the query to perform regex.
Case 1 − The below query gives all documents which starts from the word ‘ClientFolder’ −
> db.performRegex.find({'ClientFolderInformation':{'$regex':'^ClientFolder'}}).pretty();
The following is the output −
{
"_id" : ObjectId("5c8a8b1d6cea1f28b7aa07f3"),
"ClientName" : "Larry",
"ClientFolderInformation" : [
"ClientFolder 1",
"ClientFolder 2",
"ClientFolder 3",
"ClientFolder 4",
"ClientFolder 5"
],
"MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}
Case 2 − The below query gives all documents which starts from word ‘Folder’ −
> db.performRegex.find({'ClientFolderInformation':{'$regex':'^Folder'}}).pretty();
The following is the output −
{
"_id" : ObjectId("5c8a8b186cea1f28b7aa07f2"),
"ClientName" : "Larry",
"ClientFolderInformation" : [
"Folder 1",
"Folder 2",
"Folder 3",
"Folder 4",
"Folder 5"
],
"MainFolderLocation" : "/MainFolder/Details/ClientFolder"
}
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "PyMongo is a Python distribution containing tools for working with MongoDB. To perform regex queries with PyMongo, the syntax is as follows −"
},
{
"code": null,
"e": 1289,
"s": 1204,
"text": "db.yourCollectionName.find({'yourCollectionName':{'$regex':'^yourWords'}}).pretty();"
},
{
"code": null,
"e": 1369,
"s": 1289,
"text": "The above syntax will give all those documents that start from a specific word."
},
{
"code": null,
"e": 1506,
"s": 1369,
"text": "To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows −"
},
{
"code": null,
"e": 2105,
"s": 1506,
"text": "> db.performRegex.insertOne({\"ClientName\":\"Larry\",\"ClientFolderInformation\":[\n \"Folder 1\",\"Folder 2\",\"Folder 3\",\"Folder 4\",\"Folder 5\"], \"MainFolderLocation\":\"/MainFolder/Details/ClientFolder\" });\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8a8b186cea1f28b7aa07f2\")\n}\n> db.performRegex.insertOne({\"ClientName\":\"Larry\",\"ClientFolderInformation\":[\n \"ClientFolder 1\",\"ClientFolder 2\",\"ClientFolder 3\",\"ClientFolder 4\",\"ClientFolder 5\"],\n \"MainFolderLocation\":\"/MainFolder/Details/ClientFolder\" });\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8a8b1d6cea1f28b7aa07f3\")\n}"
},
{
"code": null,
"e": 2203,
"s": 2105,
"text": "Display all documents from a collection with the help of find() method. The query is as follows −"
},
{
"code": null,
"e": 2238,
"s": 2203,
"text": "> db.performRegex.find().pretty();"
},
{
"code": null,
"e": 2268,
"s": 2238,
"text": "The following is the output −"
},
{
"code": null,
"e": 2836,
"s": 2268,
"text": "{\n \"_id\" : ObjectId(\"5c8a8b186cea1f28b7aa07f2\"),\n \"ClientName\" : \"Larry\",\n \"ClientFolderInformation\" : [\n \"Folder 1\",\n \"Folder 2\",\n \"Folder 3\",\n \"Folder 4\",\n \"Folder 5\"\n ],\n \"MainFolderLocation\" : \"/MainFolder/Details/ClientFolder\"\n}\n{\n \"_id\" : ObjectId(\"5c8a8b1d6cea1f28b7aa07f3\"),\n \"ClientName\" : \"Larry\",\n \"ClientFolderInformation\" : [\n \"ClientFolder 1\",\n \"ClientFolder 2\",\n \"ClientFolder 3\",\n \"ClientFolder 4\",\n \"ClientFolder 5\"\n ],\n \"MainFolderLocation\" : \"/MainFolder/Details/ClientFolder\"\n}"
},
{
"code": null,
"e": 2872,
"s": 2836,
"text": "Here is the query to perform regex."
},
{
"code": null,
"e": 2961,
"s": 2872,
"text": "Case 1 − The below query gives all documents which starts from the word ‘ClientFolder’ −"
},
{
"code": null,
"e": 3050,
"s": 2961,
"text": "> db.performRegex.find({'ClientFolderInformation':{'$regex':'^ClientFolder'}}).pretty();"
},
{
"code": null,
"e": 3080,
"s": 3050,
"text": "The following is the output −"
},
{
"code": null,
"e": 3379,
"s": 3080,
"text": "{\n \"_id\" : ObjectId(\"5c8a8b1d6cea1f28b7aa07f3\"),\n \"ClientName\" : \"Larry\",\n \"ClientFolderInformation\" : [\n \"ClientFolder 1\",\n \"ClientFolder 2\",\n \"ClientFolder 3\",\n \"ClientFolder 4\",\n \"ClientFolder 5\"\n ],\n \"MainFolderLocation\" : \"/MainFolder/Details/ClientFolder\"\n}"
},
{
"code": null,
"e": 3458,
"s": 3379,
"text": "Case 2 − The below query gives all documents which starts from word ‘Folder’ −"
},
{
"code": null,
"e": 3541,
"s": 3458,
"text": "> db.performRegex.find({'ClientFolderInformation':{'$regex':'^Folder'}}).pretty();"
},
{
"code": null,
"e": 3571,
"s": 3541,
"text": "The following is the output −"
},
{
"code": null,
"e": 3840,
"s": 3571,
"text": "{\n \"_id\" : ObjectId(\"5c8a8b186cea1f28b7aa07f2\"),\n \"ClientName\" : \"Larry\",\n \"ClientFolderInformation\" : [\n \"Folder 1\",\n \"Folder 2\",\n \"Folder 3\",\n \"Folder 4\",\n \"Folder 5\"\n ],\n \"MainFolderLocation\" : \"/MainFolder/Details/ClientFolder\"\n}"
}
] |
Explain the logical operators in DBMS
|
Logical operators are used to specify conditions in the structured query language (SQL) statement. They are also used to serve as conjunctions for multiple conditions in a statement.
The different logical operators are shown below −
ALL − It is used to compare a value with every value in a list or returned by a query. Must be preceded by =, !=, >, < ,<=, or >= evaluates.
For example,
select * from emp where salary>= ALL(1500,4000);
AND − Returns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE; otherwise returns UNKNOWN.
For example,
select * from emp where job=’manager’ AND deptno=20;
OR − Return TRUE if either component condition is TRUE. Return FALSE if both are FALSE. Otherwise, return UNKNOWN.
For example,
select * from emp where job=’manager’ OR deptno=20;
IN − It is equivalent to any test. Equivalent to = ANY, The In operator is used to compare a value to a list of literal values that have been specified.
For example,
select * from emp where ename IN (‘bhanu’,’ward’);
NOT − Returns TRUE if the condition is FALSE. Returns FALSE, if it is TRUE. If it is UNKNOWN, it remains UNKNOWN.
For example,
select * from emp where NOT (job is NULL)
select * from emp where NOT(salary between 2000 AND 5000);
BETWEEN − It is used to define range limits.
For example,
If we want to find all employees whose age is in between 40 and 50 the query is as follows −
Select * from employee E where E.age between 40 AND 50;
LIKE − It is used to compare values to a list of literal values that are specified. “%” character is used to match any substring and “_” character is used to match any character. It expresses a pattern by using the ‘like’ comparison operator.
For example,
To display all names whose second letter is ‘b’, use the below mentioned command −
select * from emp where ename LIKE ‘_b%’;
To display a person details whose first letter is ‘A’ and third letter is ‘d’, use the command given below −
Select * from emp where ename LIKE ‘A_d_’;
|
[
{
"code": null,
"e": 1245,
"s": 1062,
"text": "Logical operators are used to specify conditions in the structured query language (SQL) statement. They are also used to serve as conjunctions for multiple conditions in a statement."
},
{
"code": null,
"e": 1295,
"s": 1245,
"text": "The different logical operators are shown below −"
},
{
"code": null,
"e": 1436,
"s": 1295,
"text": "ALL − It is used to compare a value with every value in a list or returned by a query. Must be preceded by =, !=, >, < ,<=, or >= evaluates."
},
{
"code": null,
"e": 1449,
"s": 1436,
"text": "For example,"
},
{
"code": null,
"e": 1498,
"s": 1449,
"text": "select * from emp where salary>= ALL(1500,4000);"
},
{
"code": null,
"e": 1617,
"s": 1498,
"text": "AND − Returns TRUE if both component conditions are TRUE. Returns FALSE if either is FALSE; otherwise returns UNKNOWN."
},
{
"code": null,
"e": 1630,
"s": 1617,
"text": "For example,"
},
{
"code": null,
"e": 1683,
"s": 1630,
"text": "select * from emp where job=’manager’ AND deptno=20;"
},
{
"code": null,
"e": 1798,
"s": 1683,
"text": "OR − Return TRUE if either component condition is TRUE. Return FALSE if both are FALSE. Otherwise, return UNKNOWN."
},
{
"code": null,
"e": 1811,
"s": 1798,
"text": "For example,"
},
{
"code": null,
"e": 1863,
"s": 1811,
"text": "select * from emp where job=’manager’ OR deptno=20;"
},
{
"code": null,
"e": 2016,
"s": 1863,
"text": "IN − It is equivalent to any test. Equivalent to = ANY, The In operator is used to compare a value to a list of literal values that have been specified."
},
{
"code": null,
"e": 2029,
"s": 2016,
"text": "For example,"
},
{
"code": null,
"e": 2081,
"s": 2029,
"text": "select * from emp where ename IN (‘bhanu’,’ward’);\n"
},
{
"code": null,
"e": 2195,
"s": 2081,
"text": "NOT − Returns TRUE if the condition is FALSE. Returns FALSE, if it is TRUE. If it is UNKNOWN, it remains UNKNOWN."
},
{
"code": null,
"e": 2208,
"s": 2195,
"text": "For example,"
},
{
"code": null,
"e": 2309,
"s": 2208,
"text": "select * from emp where NOT (job is NULL)\nselect * from emp where NOT(salary between 2000 AND 5000);"
},
{
"code": null,
"e": 2354,
"s": 2309,
"text": "BETWEEN − It is used to define range limits."
},
{
"code": null,
"e": 2367,
"s": 2354,
"text": "For example,"
},
{
"code": null,
"e": 2460,
"s": 2367,
"text": "If we want to find all employees whose age is in between 40 and 50 the query is as follows −"
},
{
"code": null,
"e": 2516,
"s": 2460,
"text": "Select * from employee E where E.age between 40 AND 50;"
},
{
"code": null,
"e": 2759,
"s": 2516,
"text": "LIKE − It is used to compare values to a list of literal values that are specified. “%” character is used to match any substring and “_” character is used to match any character. It expresses a pattern by using the ‘like’ comparison operator."
},
{
"code": null,
"e": 2772,
"s": 2759,
"text": "For example,"
},
{
"code": null,
"e": 2855,
"s": 2772,
"text": "To display all names whose second letter is ‘b’, use the below mentioned command −"
},
{
"code": null,
"e": 2897,
"s": 2855,
"text": "select * from emp where ename LIKE ‘_b%’;"
},
{
"code": null,
"e": 3006,
"s": 2897,
"text": "To display a person details whose first letter is ‘A’ and third letter is ‘d’, use the command given below −"
},
{
"code": null,
"e": 3050,
"s": 3006,
"text": "Select * from emp where ename LIKE ‘A_d_’;\n"
}
] |
Building and Evaluating Classification ML Models | by Nishit Jain | Towards Data Science
|
There are different types of problems in machine learning. Some might fall under regression (having continuous targets) while others might fall under classification (having discrete targets). Some might not have a target at all where you are just trying to learn the characteristics of data by distinguishing the data points based on their inherent features by creating clusters.
However, this article is not about different areas of machine learning but about a very little yet important thing, which if not tended to carefully can wreak “who knows what” on your operationalized classification models and eventually, the business. Therefore, the next time when someone at work tells you that her/his model is giving ~93.23% accuracy, do not fall for it before asking the right questions.
So, how do we know what are the right questions?
That’s a good question. Let us try to answer that by studying how to build and evaluate a classification model the right way. Everyone who has been studying machine learning is aware of all frequently used classification metrics but only a few of them know the right one to use to evaluate the performance of their classification model.
So, to enable you to ask the right questions, we will go through the following concepts in detail (for a classification model):
Data Distribution (Training, Validation, Test)Handling Class Imbalance.The Right Choice of Metric For Model Evaluation
Data Distribution (Training, Validation, Test)
Handling Class Imbalance.
The Right Choice of Metric For Model Evaluation
While splitting data for training, validation, and test set, one should always keep in mind that all three of them must be representative of the same population. For example, in the MNIST digit classification dataset where all the digit images are grey (black and white), you train it and achieve a validation accuracy of almost 90%, but your test data has digit images of various colors (not just black and white). Now, you have a problem there. No matter what you do, there will always be a data bias. You cannot get rid of it totally but what you can do is maintain a uniformity in your validation and test data set. This is an example of a difference in the distribution of validation and test sets.
Your test data set MUST always represent real-world data distribution. For example, in a binary classification problem, where you are supposed to detect positive patients for a rare disease (class 1) where 6% of the entire data set contains positive cases, then your test data should also have almost the same proportion. Make sure you follow the same distribution. This is not just the case with classification models. It holds for every type of ML modeling problem.
The test dataset should be extracted first without any data leakage into the leftover data and then, validation data must follow the distribution in the test data. And, what remains after these two splits goes into training. Hence, the right sequence to divide the entire dataset into training, validation, and test sets is to get the test, validation, and training set specifically in that order from the entire dataset.
There is a convenience of 70–20–10 split in the machine learning community but that is only when you have an average amount of data. If you are working on, for instance, an image classification problem and you have ~10 million of images, then doing a 70–20–10 split would be a bad idea because the amount of data is so huge that to validate your model, even 1 to 2% of it is enough. Hence, I would rather go with 96–2–2 split because you do not want to increase the unnecessary overhead on validation and test by increasing the size as the same representation of distribution can be achieved using 2% of the total data in the validation and test. Also, make sure you do not sample with a replacement while making splits.
In case of any classification problem, which affects the performance of a model most is the amount of loss contributed by every class to the total cost. The higher the number of examples of a certain class, the total loss contribution of that class is higher. The loss contribution to the total cost by a class is directly proportional to the number of examples belonging to that class. In this way, the classifier concentrates more on classifying those instances correctly which are contributing more to the total cost of the loss function (i.e. the instances from the majority class).
Following are the ways using which we can tackle class imbalance:
Weighted LossResampling
Weighted Loss
Resampling
In binary cross-entropy loss, we have the following loss function:
The model outputs the probability that the given example belongs to a positive (y=1) class. And, based on the above binary cross-entropy loss function, loss value is computed per example, and finally, the total cost is computed as the average loss across all examples. Let us conduct a simple simulation to understand it better by writing a simple python script. Let’s generate 100 ground truth labels, 25 out of which belong to the positive (y=1) class, and the rest are negative (y=0) to account for the class imbalance in our tiny experiment. Also, we will generate a random probability value of it belonging to the positive class for every example.
import numpy as npimport random# Generating Ground truth labels and Predicted probabilitiestruth, probs = [], []for i in range(100): # To maintain class imbalance if i < 25: truth.append(1) else: truth.append(0) probs.append(round(random.random(),2))print("Total Positive Example Count: ",sum(truth))print("Total Negative Example Count: ",len(truth) - sum(truth))print("Predicted Probability Values: ",probs)Output:Total Positive Example Count: 25Total Negative Example Count: 75Predicted Probability Values: [0.84, 0.65, 0.11, 0.21, 0.31, 0.05, 0.44, 0.83, 0.19, 0.61, 0.28, 0.36, 0.46, 0.79, 0.74, 0.58, 0.65, 0.8, 0.05, 0.39, 0.08, 0.45, 0.4, 0.03, 0.41, 0.75, 0.46, 0.49, 0.94, 0.57, 0.38, 0.7, 0.07, 0.91, 0.85, 0.91, 0.72, 0.28, 0.0, 0.55, 0.61, 0.55, 0.81, 0.98, 0.9, 0.36, 0.65, 0.91, 0.26, 0.1, 0.99, 0.48, 0.34, 0.96, 0.68, 0.21, 0.28, 0.37, 0.8, 0.27, 0.87, 0.93, 0.03, 0.95, 0.25, 0.63, 0.2, 0.45, 0.05, 0.7, 0.91, 0.85, 0.56, 0.61, 0.4, 0.35, 0.6, 0.27, 0.08, 0.85, 0.14, 0.82, 0.22, 0.41, 0.85, 0.72, 0.91, 0.5, 0.55, 0.89, 0.39, 0.92, 0.24, 0.07, 0.52, 0.88, 0.01, 0.01, 0.01, 0.31]
Now, that we have ground truth labels and predicted probabilities, using the above loss function, we can compute the total loss contribution by both the classes. A really small number was added to the predicted probabilities before calculating the log value to avoid error due to undefined value. [log(0) = undefined]
# Calculating Plain Binary Cross-Entropy Losspos_loss, neg_loss = 0, 0for i in range(len(truth)): # Applying the binary cross-entropy loss function if truth[i] == 1: pos_loss += -1 * np.log(probs[i] + 1e-7) else: neg_loss += -1 * np.log(1 - probs[i] + 1e-7)print("Positive Class Loss: ",round(pos_loss,2))print("Negative Class Loss: ",round(neg_loss,2))Output:Positive Class Loss: 29.08Negative Class Loss: 83.96
As we can see that the total loss over both the classes has a huge difference and the negative class is leading the race of loss contribution, the algorithm is technically going to focus more on the negative class to decrease loss radically while minimizing it. That is when we fool the model into believing what is not real by assigning a weight to total loss calculation by using the following weighted loss function:
Here, ‘Wp’ & ‘Wn’ are weights assigned to positive and negative class loss respectively and can be calculated as follows:
Wp = total number of negative (y=0) examples / total examples
Wn = total number of positive (y=1) examples / total examples
Now, let us calculate weighted loss by adding the weights to the calculation:
# Calculating Weighted Binary Cross-Entropy Losspos_loss, neg_loss = 0, 0# Wp (Weight for positive class)wp = (len(truth) - sum(truth))/len(truth)# Wn (Weight for negative class)wn = sum(truth) / len(truth)for i in range(len(truth)): # Applying the same function with class weights. if truth[i] == 1: pos_loss += -wp * np.log(probs[i] + 1e-7) else: neg_loss += -wn * np.log(1 - probs[i] + 1e-7)print("Positive Class Loss: ",round(pos_loss,2))print("Negative Class Loss: ",round(neg_loss,2))Output:Positive Class Loss: 21.81Negative Class Loss: 20.99
Amazing! Isn’t it? We managed to reduce the difference of loss contribution between both classes significantly by assigning the right weights.
This is yet another technique using which you can counter class imbalance but this should not be the first technique you use. Resampling can be done in three ways:
Either by oversampling the minority classOr by undersampling the majority classOr both by the right amount
Either by oversampling the minority class
Or by undersampling the majority class
Or both by the right amount
Oversampling can be achieved either by random sampling the minority class with the replacement or by synthetically generating more examples by using techniques such as SMOTE. Oversampling can help up to a limit because, after a certain amount, you are duplicating the information contained in the data. It might give you ideal loss contributions from both the classes but will fail at validation and test time. But, if you have a massive amount of data along with imbalance, you should go for undersampling without replacement of majority class.
Sometimes, people do use both the techniques at once when there is an average amount of data, and class imbalance is not huge. So, they oversample the minority class and undersample the majority class by a certain calculated amount to achieve balance.
Now, you understand when somebody comes to you and says I have got ~93.23% accuracy, you should think and ask about the class proportions in the data and the type of loss function used. Then, you should wonder whether measuring just accuracy is the right way to go. Or there is something more!
There is always something more at least when you are working on a machine learning model but to know when you want more is only possible when you have something to compare to. A Benchmark! Once you have a benchmark, you know how much improvement you want.
But to improve the performance, you need to know which metric is the right indicator of performance in the business problem you are trying to solve. For example, if you are trying to solve a tumor detection problem where the objective is to detect whether the tumor is malignant (y=1) or benign (y=0). In this case, you need to understand that in real word benign cases are more than the malignant cases. Hence, when you get the data, you will have a good amount of class imbalance (unless of course, you are really lucky). So, accuracy as a metric is out of the question. Now, the question is, what is more important? To detect whether a patient has a malignant tumor or a benign one. This is a business decision and you should always consult a domain expert(s) (in this case, expert doctors) to understand the business problem by asking such questions. If we are more concerned with detecting malignant tumors effectively even if we have a few false positives (Ground Truth: Benign, Model Prediction: Malignant) but we need as minimum false negatives (Ground Truth: Malignant, Model Prediction: Benign) as possible, then Recall should be our metric of choice but if it is vice-versa (which can never be in this particular case), Precision should be our choice.
Sometimes, in a business setting, there are problems where you need effective classifications on both the classes and hence you would want to optimize the F1 score. To tackle this trade-off, we should work on maximizing the area under the precision-recall curve as much as possible.
Also, the results must be conveyed in terms of confidence intervals with upper and lower bounds of the metric to get a fair idea of the behavior of the model on the population using all the experiments conducted over various samples.
To summarize it all, the following are the major takeaways from this article:
Data distribution is crucial when building a classification model and one should always start by getting their test distribution right first and then validation and train in that order.
Class imbalance should be handled properly to avoid really bad results on live data.
Only when you select the right metric for evaluation of your model, you can assess its performance correctly. There are a lot of factors ranging from business expertise to technicalities of the model itself that help us decide the right metric.
Thank you for reading the article.
|
[
{
"code": null,
"e": 552,
"s": 172,
"text": "There are different types of problems in machine learning. Some might fall under regression (having continuous targets) while others might fall under classification (having discrete targets). Some might not have a target at all where you are just trying to learn the characteristics of data by distinguishing the data points based on their inherent features by creating clusters."
},
{
"code": null,
"e": 961,
"s": 552,
"text": "However, this article is not about different areas of machine learning but about a very little yet important thing, which if not tended to carefully can wreak “who knows what” on your operationalized classification models and eventually, the business. Therefore, the next time when someone at work tells you that her/his model is giving ~93.23% accuracy, do not fall for it before asking the right questions."
},
{
"code": null,
"e": 1010,
"s": 961,
"text": "So, how do we know what are the right questions?"
},
{
"code": null,
"e": 1347,
"s": 1010,
"text": "That’s a good question. Let us try to answer that by studying how to build and evaluate a classification model the right way. Everyone who has been studying machine learning is aware of all frequently used classification metrics but only a few of them know the right one to use to evaluate the performance of their classification model."
},
{
"code": null,
"e": 1475,
"s": 1347,
"text": "So, to enable you to ask the right questions, we will go through the following concepts in detail (for a classification model):"
},
{
"code": null,
"e": 1594,
"s": 1475,
"text": "Data Distribution (Training, Validation, Test)Handling Class Imbalance.The Right Choice of Metric For Model Evaluation"
},
{
"code": null,
"e": 1641,
"s": 1594,
"text": "Data Distribution (Training, Validation, Test)"
},
{
"code": null,
"e": 1667,
"s": 1641,
"text": "Handling Class Imbalance."
},
{
"code": null,
"e": 1715,
"s": 1667,
"text": "The Right Choice of Metric For Model Evaluation"
},
{
"code": null,
"e": 2419,
"s": 1715,
"text": "While splitting data for training, validation, and test set, one should always keep in mind that all three of them must be representative of the same population. For example, in the MNIST digit classification dataset where all the digit images are grey (black and white), you train it and achieve a validation accuracy of almost 90%, but your test data has digit images of various colors (not just black and white). Now, you have a problem there. No matter what you do, there will always be a data bias. You cannot get rid of it totally but what you can do is maintain a uniformity in your validation and test data set. This is an example of a difference in the distribution of validation and test sets."
},
{
"code": null,
"e": 2887,
"s": 2419,
"text": "Your test data set MUST always represent real-world data distribution. For example, in a binary classification problem, where you are supposed to detect positive patients for a rare disease (class 1) where 6% of the entire data set contains positive cases, then your test data should also have almost the same proportion. Make sure you follow the same distribution. This is not just the case with classification models. It holds for every type of ML modeling problem."
},
{
"code": null,
"e": 3309,
"s": 2887,
"text": "The test dataset should be extracted first without any data leakage into the leftover data and then, validation data must follow the distribution in the test data. And, what remains after these two splits goes into training. Hence, the right sequence to divide the entire dataset into training, validation, and test sets is to get the test, validation, and training set specifically in that order from the entire dataset."
},
{
"code": null,
"e": 4030,
"s": 3309,
"text": "There is a convenience of 70–20–10 split in the machine learning community but that is only when you have an average amount of data. If you are working on, for instance, an image classification problem and you have ~10 million of images, then doing a 70–20–10 split would be a bad idea because the amount of data is so huge that to validate your model, even 1 to 2% of it is enough. Hence, I would rather go with 96–2–2 split because you do not want to increase the unnecessary overhead on validation and test by increasing the size as the same representation of distribution can be achieved using 2% of the total data in the validation and test. Also, make sure you do not sample with a replacement while making splits."
},
{
"code": null,
"e": 4617,
"s": 4030,
"text": "In case of any classification problem, which affects the performance of a model most is the amount of loss contributed by every class to the total cost. The higher the number of examples of a certain class, the total loss contribution of that class is higher. The loss contribution to the total cost by a class is directly proportional to the number of examples belonging to that class. In this way, the classifier concentrates more on classifying those instances correctly which are contributing more to the total cost of the loss function (i.e. the instances from the majority class)."
},
{
"code": null,
"e": 4683,
"s": 4617,
"text": "Following are the ways using which we can tackle class imbalance:"
},
{
"code": null,
"e": 4707,
"s": 4683,
"text": "Weighted LossResampling"
},
{
"code": null,
"e": 4721,
"s": 4707,
"text": "Weighted Loss"
},
{
"code": null,
"e": 4732,
"s": 4721,
"text": "Resampling"
},
{
"code": null,
"e": 4799,
"s": 4732,
"text": "In binary cross-entropy loss, we have the following loss function:"
},
{
"code": null,
"e": 5452,
"s": 4799,
"text": "The model outputs the probability that the given example belongs to a positive (y=1) class. And, based on the above binary cross-entropy loss function, loss value is computed per example, and finally, the total cost is computed as the average loss across all examples. Let us conduct a simple simulation to understand it better by writing a simple python script. Let’s generate 100 ground truth labels, 25 out of which belong to the positive (y=1) class, and the rest are negative (y=0) to account for the class imbalance in our tiny experiment. Also, we will generate a random probability value of it belonging to the positive class for every example."
},
{
"code": null,
"e": 6579,
"s": 5452,
"text": "import numpy as npimport random# Generating Ground truth labels and Predicted probabilitiestruth, probs = [], []for i in range(100): # To maintain class imbalance if i < 25: truth.append(1) else: truth.append(0) probs.append(round(random.random(),2))print(\"Total Positive Example Count: \",sum(truth))print(\"Total Negative Example Count: \",len(truth) - sum(truth))print(\"Predicted Probability Values: \",probs)Output:Total Positive Example Count: 25Total Negative Example Count: 75Predicted Probability Values: [0.84, 0.65, 0.11, 0.21, 0.31, 0.05, 0.44, 0.83, 0.19, 0.61, 0.28, 0.36, 0.46, 0.79, 0.74, 0.58, 0.65, 0.8, 0.05, 0.39, 0.08, 0.45, 0.4, 0.03, 0.41, 0.75, 0.46, 0.49, 0.94, 0.57, 0.38, 0.7, 0.07, 0.91, 0.85, 0.91, 0.72, 0.28, 0.0, 0.55, 0.61, 0.55, 0.81, 0.98, 0.9, 0.36, 0.65, 0.91, 0.26, 0.1, 0.99, 0.48, 0.34, 0.96, 0.68, 0.21, 0.28, 0.37, 0.8, 0.27, 0.87, 0.93, 0.03, 0.95, 0.25, 0.63, 0.2, 0.45, 0.05, 0.7, 0.91, 0.85, 0.56, 0.61, 0.4, 0.35, 0.6, 0.27, 0.08, 0.85, 0.14, 0.82, 0.22, 0.41, 0.85, 0.72, 0.91, 0.5, 0.55, 0.89, 0.39, 0.92, 0.24, 0.07, 0.52, 0.88, 0.01, 0.01, 0.01, 0.31]"
},
{
"code": null,
"e": 6897,
"s": 6579,
"text": "Now, that we have ground truth labels and predicted probabilities, using the above loss function, we can compute the total loss contribution by both the classes. A really small number was added to the predicted probabilities before calculating the log value to avoid error due to undefined value. [log(0) = undefined]"
},
{
"code": null,
"e": 7335,
"s": 6897,
"text": "# Calculating Plain Binary Cross-Entropy Losspos_loss, neg_loss = 0, 0for i in range(len(truth)): # Applying the binary cross-entropy loss function if truth[i] == 1: pos_loss += -1 * np.log(probs[i] + 1e-7) else: neg_loss += -1 * np.log(1 - probs[i] + 1e-7)print(\"Positive Class Loss: \",round(pos_loss,2))print(\"Negative Class Loss: \",round(neg_loss,2))Output:Positive Class Loss: 29.08Negative Class Loss: 83.96"
},
{
"code": null,
"e": 7755,
"s": 7335,
"text": "As we can see that the total loss over both the classes has a huge difference and the negative class is leading the race of loss contribution, the algorithm is technically going to focus more on the negative class to decrease loss radically while minimizing it. That is when we fool the model into believing what is not real by assigning a weight to total loss calculation by using the following weighted loss function:"
},
{
"code": null,
"e": 7877,
"s": 7755,
"text": "Here, ‘Wp’ & ‘Wn’ are weights assigned to positive and negative class loss respectively and can be calculated as follows:"
},
{
"code": null,
"e": 7939,
"s": 7877,
"text": "Wp = total number of negative (y=0) examples / total examples"
},
{
"code": null,
"e": 8001,
"s": 7939,
"text": "Wn = total number of positive (y=1) examples / total examples"
},
{
"code": null,
"e": 8079,
"s": 8001,
"text": "Now, let us calculate weighted loss by adding the weights to the calculation:"
},
{
"code": null,
"e": 8654,
"s": 8079,
"text": "# Calculating Weighted Binary Cross-Entropy Losspos_loss, neg_loss = 0, 0# Wp (Weight for positive class)wp = (len(truth) - sum(truth))/len(truth)# Wn (Weight for negative class)wn = sum(truth) / len(truth)for i in range(len(truth)): # Applying the same function with class weights. if truth[i] == 1: pos_loss += -wp * np.log(probs[i] + 1e-7) else: neg_loss += -wn * np.log(1 - probs[i] + 1e-7)print(\"Positive Class Loss: \",round(pos_loss,2))print(\"Negative Class Loss: \",round(neg_loss,2))Output:Positive Class Loss: 21.81Negative Class Loss: 20.99"
},
{
"code": null,
"e": 8797,
"s": 8654,
"text": "Amazing! Isn’t it? We managed to reduce the difference of loss contribution between both classes significantly by assigning the right weights."
},
{
"code": null,
"e": 8961,
"s": 8797,
"text": "This is yet another technique using which you can counter class imbalance but this should not be the first technique you use. Resampling can be done in three ways:"
},
{
"code": null,
"e": 9068,
"s": 8961,
"text": "Either by oversampling the minority classOr by undersampling the majority classOr both by the right amount"
},
{
"code": null,
"e": 9110,
"s": 9068,
"text": "Either by oversampling the minority class"
},
{
"code": null,
"e": 9149,
"s": 9110,
"text": "Or by undersampling the majority class"
},
{
"code": null,
"e": 9177,
"s": 9149,
"text": "Or both by the right amount"
},
{
"code": null,
"e": 9723,
"s": 9177,
"text": "Oversampling can be achieved either by random sampling the minority class with the replacement or by synthetically generating more examples by using techniques such as SMOTE. Oversampling can help up to a limit because, after a certain amount, you are duplicating the information contained in the data. It might give you ideal loss contributions from both the classes but will fail at validation and test time. But, if you have a massive amount of data along with imbalance, you should go for undersampling without replacement of majority class."
},
{
"code": null,
"e": 9975,
"s": 9723,
"text": "Sometimes, people do use both the techniques at once when there is an average amount of data, and class imbalance is not huge. So, they oversample the minority class and undersample the majority class by a certain calculated amount to achieve balance."
},
{
"code": null,
"e": 10269,
"s": 9975,
"text": "Now, you understand when somebody comes to you and says I have got ~93.23% accuracy, you should think and ask about the class proportions in the data and the type of loss function used. Then, you should wonder whether measuring just accuracy is the right way to go. Or there is something more!"
},
{
"code": null,
"e": 10525,
"s": 10269,
"text": "There is always something more at least when you are working on a machine learning model but to know when you want more is only possible when you have something to compare to. A Benchmark! Once you have a benchmark, you know how much improvement you want."
},
{
"code": null,
"e": 11788,
"s": 10525,
"text": "But to improve the performance, you need to know which metric is the right indicator of performance in the business problem you are trying to solve. For example, if you are trying to solve a tumor detection problem where the objective is to detect whether the tumor is malignant (y=1) or benign (y=0). In this case, you need to understand that in real word benign cases are more than the malignant cases. Hence, when you get the data, you will have a good amount of class imbalance (unless of course, you are really lucky). So, accuracy as a metric is out of the question. Now, the question is, what is more important? To detect whether a patient has a malignant tumor or a benign one. This is a business decision and you should always consult a domain expert(s) (in this case, expert doctors) to understand the business problem by asking such questions. If we are more concerned with detecting malignant tumors effectively even if we have a few false positives (Ground Truth: Benign, Model Prediction: Malignant) but we need as minimum false negatives (Ground Truth: Malignant, Model Prediction: Benign) as possible, then Recall should be our metric of choice but if it is vice-versa (which can never be in this particular case), Precision should be our choice."
},
{
"code": null,
"e": 12071,
"s": 11788,
"text": "Sometimes, in a business setting, there are problems where you need effective classifications on both the classes and hence you would want to optimize the F1 score. To tackle this trade-off, we should work on maximizing the area under the precision-recall curve as much as possible."
},
{
"code": null,
"e": 12305,
"s": 12071,
"text": "Also, the results must be conveyed in terms of confidence intervals with upper and lower bounds of the metric to get a fair idea of the behavior of the model on the population using all the experiments conducted over various samples."
},
{
"code": null,
"e": 12383,
"s": 12305,
"text": "To summarize it all, the following are the major takeaways from this article:"
},
{
"code": null,
"e": 12569,
"s": 12383,
"text": "Data distribution is crucial when building a classification model and one should always start by getting their test distribution right first and then validation and train in that order."
},
{
"code": null,
"e": 12654,
"s": 12569,
"text": "Class imbalance should be handled properly to avoid really bad results on live data."
},
{
"code": null,
"e": 12899,
"s": 12654,
"text": "Only when you select the right metric for evaluation of your model, you can assess its performance correctly. There are a lot of factors ranging from business expertise to technicalities of the model itself that help us decide the right metric."
}
] |
Assoc cmd command - GeeksforGeeks
|
15 Sep, 2020
Assoc is command (internal) found inside Windows Command Processor Command Prompt, that allows for file extension to file type association. A file extension is generally last few characters in File Name after period (“.”). Though it is not mandatory for file to have an extension at all (in case of extension-less files).
Extension to file type association is enforced predominantly by Windows OS. Other Operating Systems such as Linux and macOS does support such association but don’t enforce them to levels of Windows. Linux Kernel rather utilizes Magic Numbers for recognition of file types. In this article, we will take look at assoc command found in cmd, and would look at uses of it.
Description of Command :
ASSOC [.ext[=[fileType]]]
.ext Specifies file extension to associate file type with
fileType Specifies file type to associate with file extension
Type ASSOC without parameters to display current file associations. If ASSOC is invoked with just file extension, it displays current file association for that file extension. Specify nothing for file type and command will delete association for file extension.
Note –The above text could be obtained by executing assoc /? Command in command line
Using the Command :Displaying the list of every extension to file type association. To display list, execute following command in cmd.
Assoc :After the execution, an output appears as such.
.001=WinRAR
.386=vxdfile
.3ds=Photoshop.3DSFileType.130
.3g2=WMP11.AssocFile.3G2
.3ga=VLC.3ga
.3gp=WMP11.AssocFile.3GP
.3gp2=WMP11.AssocFile.3G2
.3gpp=WMP11.AssocFile.3GP
.669=VLC.669
.7z=WinRAR
.8ba=Photoshop.PlugIn
.8bc=Photoshop.PlugIn
Displaying file type association of single file extension :
To display association, run following command.
assoc ext
where ext is file extension we are wanting to get information about.
Example :To get association information about the .jpg file extension
assoc .jpg
Output :
.jpg=jpegfile
Note –There should always be period preceding the extension.
Creating file type association :Requires cmd to run with elevated privileges (administrator mode). For creating file type associated with an extension, following command is to be used.
assoc extension=filetype
Here, an extension is file extension that we want to associate, and file type is type with which we want to associate that extension with. The extension should always be preceded with period/Full stop, and there should always be an equal ( = ) sign between extension and file type.
Example :The command for associating the .jkl extension with pngfile filetype.
assoc .jkl=pngfile
It should be noted that the association of any extension should be done with known file type (ones known to operating systems). Otherwise, OS may become clueless with which application to assign for that particular file type.
That is due to the fact that Just like extensions are associated with file types, file types are further associated with an application. Therefore, if the user chooses new filetype, then it would not have an application associated with it (this could be dealt with by associating an application to the file type using ftype).
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Memory Management in Operating System
Difference between Internal and External fragmentation
Mutex lock for Linux Thread Synchronization
Logical and Physical Address in Operating System
Program for Least Recently Used (LRU) Page Replacement algorithm
Process Table and Process Control Block (PCB)
Dining Philosopher Problem Using Semaphores
States of a Process in Operating Systems
File Allocation Methods
Introduction of Process Management
|
[
{
"code": null,
"e": 24492,
"s": 24464,
"text": "\n15 Sep, 2020"
},
{
"code": null,
"e": 24814,
"s": 24492,
"text": "Assoc is command (internal) found inside Windows Command Processor Command Prompt, that allows for file extension to file type association. A file extension is generally last few characters in File Name after period (“.”). Though it is not mandatory for file to have an extension at all (in case of extension-less files)."
},
{
"code": null,
"e": 25183,
"s": 24814,
"text": "Extension to file type association is enforced predominantly by Windows OS. Other Operating Systems such as Linux and macOS does support such association but don’t enforce them to levels of Windows. Linux Kernel rather utilizes Magic Numbers for recognition of file types. In this article, we will take look at assoc command found in cmd, and would look at uses of it."
},
{
"code": null,
"e": 25208,
"s": 25183,
"text": "Description of Command :"
},
{
"code": null,
"e": 25364,
"s": 25208,
"text": "ASSOC [.ext[=[fileType]]]\n\n .ext Specifies file extension to associate file type with\n fileType Specifies file type to associate with file extension\n"
},
{
"code": null,
"e": 25626,
"s": 25364,
"text": "Type ASSOC without parameters to display current file associations. If ASSOC is invoked with just file extension, it displays current file association for that file extension. Specify nothing for file type and command will delete association for file extension."
},
{
"code": null,
"e": 25711,
"s": 25626,
"text": "Note –The above text could be obtained by executing assoc /? Command in command line"
},
{
"code": null,
"e": 25846,
"s": 25711,
"text": "Using the Command :Displaying the list of every extension to file type association. To display list, execute following command in cmd."
},
{
"code": null,
"e": 25901,
"s": 25846,
"text": "Assoc :After the execution, an output appears as such."
},
{
"code": null,
"e": 26142,
"s": 25901,
"text": ".001=WinRAR\n.386=vxdfile\n.3ds=Photoshop.3DSFileType.130\n.3g2=WMP11.AssocFile.3G2\n.3ga=VLC.3ga\n.3gp=WMP11.AssocFile.3GP\n.3gp2=WMP11.AssocFile.3G2\n.3gpp=WMP11.AssocFile.3GP\n.669=VLC.669\n.7z=WinRAR\n.8ba=Photoshop.PlugIn\n.8bc=Photoshop.PlugIn \n"
},
{
"code": null,
"e": 26202,
"s": 26142,
"text": "Displaying file type association of single file extension :"
},
{
"code": null,
"e": 26249,
"s": 26202,
"text": "To display association, run following command."
},
{
"code": null,
"e": 26260,
"s": 26249,
"text": "assoc ext "
},
{
"code": null,
"e": 26329,
"s": 26260,
"text": "where ext is file extension we are wanting to get information about."
},
{
"code": null,
"e": 26399,
"s": 26329,
"text": "Example :To get association information about the .jpg file extension"
},
{
"code": null,
"e": 26411,
"s": 26399,
"text": "assoc .jpg "
},
{
"code": null,
"e": 26420,
"s": 26411,
"text": "Output :"
},
{
"code": null,
"e": 26435,
"s": 26420,
"text": ".jpg=jpegfile "
},
{
"code": null,
"e": 26496,
"s": 26435,
"text": "Note –There should always be period preceding the extension."
},
{
"code": null,
"e": 26681,
"s": 26496,
"text": "Creating file type association :Requires cmd to run with elevated privileges (administrator mode). For creating file type associated with an extension, following command is to be used."
},
{
"code": null,
"e": 26707,
"s": 26681,
"text": "assoc extension=filetype "
},
{
"code": null,
"e": 26989,
"s": 26707,
"text": "Here, an extension is file extension that we want to associate, and file type is type with which we want to associate that extension with. The extension should always be preceded with period/Full stop, and there should always be an equal ( = ) sign between extension and file type."
},
{
"code": null,
"e": 27068,
"s": 26989,
"text": "Example :The command for associating the .jkl extension with pngfile filetype."
},
{
"code": null,
"e": 27088,
"s": 27068,
"text": "assoc .jkl=pngfile "
},
{
"code": null,
"e": 27314,
"s": 27088,
"text": "It should be noted that the association of any extension should be done with known file type (ones known to operating systems). Otherwise, OS may become clueless with which application to assign for that particular file type."
},
{
"code": null,
"e": 27640,
"s": 27314,
"text": "That is due to the fact that Just like extensions are associated with file types, file types are further associated with an application. Therefore, if the user chooses new filetype, then it would not have an application associated with it (this could be dealt with by associating an application to the file type using ftype)."
},
{
"code": null,
"e": 27658,
"s": 27640,
"text": "Operating Systems"
},
{
"code": null,
"e": 27676,
"s": 27658,
"text": "Operating Systems"
},
{
"code": null,
"e": 27774,
"s": 27676,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27783,
"s": 27774,
"text": "Comments"
},
{
"code": null,
"e": 27796,
"s": 27783,
"text": "Old Comments"
},
{
"code": null,
"e": 27834,
"s": 27796,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 27889,
"s": 27834,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 27933,
"s": 27889,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 27982,
"s": 27933,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 28047,
"s": 27982,
"text": "Program for Least Recently Used (LRU) Page Replacement algorithm"
},
{
"code": null,
"e": 28093,
"s": 28047,
"text": "Process Table and Process Control Block (PCB)"
},
{
"code": null,
"e": 28137,
"s": 28093,
"text": "Dining Philosopher Problem Using Semaphores"
},
{
"code": null,
"e": 28178,
"s": 28137,
"text": "States of a Process in Operating Systems"
},
{
"code": null,
"e": 28202,
"s": 28178,
"text": "File Allocation Methods"
}
] |
Spring Boot & H2 - Unit Test Service
|
To test a Service, we need the following annotation and classes −
@ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class.
@ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class.
@SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application.
@SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application.
@MockBean private EmployeeService employeeService − EmployeeService mock object to be tested.
@MockBean private EmployeeService employeeService − EmployeeService mock object to be tested.
Following is the complete code of EmployeeServiceTest.
package com.tutorialspoint.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doNothing;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.sprintbooth2.SprintBootH2Application;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = SprintBootH2Application.class)
public class EmployeeServiceTest {
@MockBean
private EmployeeService employeeService;
@Test
public void testGetAllEmployees() throws Exception {
Employee employee = getEmployee();
List<Employee> employees = new ArrayList<>();
employees.add(employee);
given(employeeService.getAllEmployees()).willReturn(employees);
List<Employee> result = employeeService.getAllEmployees();
assertEquals(result.size(), 1);
}
@Test
public void testGetEmployee() throws Exception {
Employee employee = getEmployee();
given(employeeService.getEmployeeById(1)).willReturn(employee);
Employee result = employeeService.getEmployeeById(1);
assertEquals(result.getId(), 1);
}
@Test
public void testDeleteEmployee() throws Exception {
doNothing().when(employeeService).deleteEmployeeById(1);
employeeService.deleteEmployeeById(1);
assertTrue(true);
}
@Test
public void testSaveOrUpdateEmployee() throws Exception {
Employee employee = getEmployee();
doNothing().when(employeeService).saveOrUpdate(employee);
employeeService.saveOrUpdate(employee);
assertTrue(true);
}
private Employee getEmployee() {
Employee employee = new Employee();
employee.setId(1);
employee.setName("Mahesh");
employee.setAge(30);
employee.setEmail("mahesh@test.com");
return employee;
}
}
Right Click on the file in eclipse and select Run a JUnit Test and verify the result.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2162,
"s": 2096,
"text": "To test a Service, we need the following annotation and classes −"
},
{
"code": null,
"e": 2263,
"s": 2162,
"text": "@ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class."
},
{
"code": null,
"e": 2364,
"s": 2263,
"text": "@ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class."
},
{
"code": null,
"e": 2462,
"s": 2364,
"text": "@SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application."
},
{
"code": null,
"e": 2560,
"s": 2462,
"text": "@SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application."
},
{
"code": null,
"e": 2654,
"s": 2560,
"text": "@MockBean private EmployeeService employeeService − EmployeeService mock object to be tested."
},
{
"code": null,
"e": 2748,
"s": 2654,
"text": "@MockBean private EmployeeService employeeService − EmployeeService mock object to be tested."
},
{
"code": null,
"e": 2803,
"s": 2748,
"text": "Following is the complete code of EmployeeServiceTest."
},
{
"code": null,
"e": 5002,
"s": 2803,
"text": "package com.tutorialspoint.service;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\nimport static org.mockito.BDDMockito.given;\nimport static org.mockito.Mockito.doNothing;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.boot.test.mock.mockito.MockBean;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\nimport com.tutorialspoint.entity.Employee;\nimport com.tutorialspoint.sprintbooth2.SprintBootH2Application;\n@ExtendWith(SpringExtension.class)\n@SpringBootTest(classes = SprintBootH2Application.class)\npublic class EmployeeServiceTest {\n @MockBean\n private EmployeeService employeeService;\n @Test\n public void testGetAllEmployees() throws Exception {\n Employee employee = getEmployee();\n List<Employee> employees = new ArrayList<>();\n employees.add(employee);\n given(employeeService.getAllEmployees()).willReturn(employees);\n List<Employee> result = employeeService.getAllEmployees();\n assertEquals(result.size(), 1);\n }\n @Test\n public void testGetEmployee() throws Exception {\n Employee employee = getEmployee();\n given(employeeService.getEmployeeById(1)).willReturn(employee);\n Employee result = employeeService.getEmployeeById(1);\n assertEquals(result.getId(), 1);\t\n }\n @Test\n public void testDeleteEmployee() throws Exception {\n doNothing().when(employeeService).deleteEmployeeById(1);\n employeeService.deleteEmployeeById(1);\n assertTrue(true);\n }\n @Test\n public void testSaveOrUpdateEmployee() throws Exception {\n Employee employee = getEmployee();\n doNothing().when(employeeService).saveOrUpdate(employee);\t\n employeeService.saveOrUpdate(employee);\n assertTrue(true);\n }\n private Employee getEmployee() {\n Employee employee = new Employee();\n employee.setId(1);\n employee.setName(\"Mahesh\");\n employee.setAge(30);\n employee.setEmail(\"mahesh@test.com\");\n return employee;\n }\n}"
},
{
"code": null,
"e": 5088,
"s": 5002,
"text": "Right Click on the file in eclipse and select Run a JUnit Test and verify the result."
},
{
"code": null,
"e": 5122,
"s": 5088,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5136,
"s": 5122,
"text": " Karthikeya T"
},
{
"code": null,
"e": 5169,
"s": 5136,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5184,
"s": 5169,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 5219,
"s": 5184,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5231,
"s": 5219,
"text": " Senol Atac"
},
{
"code": null,
"e": 5266,
"s": 5231,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5278,
"s": 5266,
"text": " Senol Atac"
},
{
"code": null,
"e": 5313,
"s": 5278,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5325,
"s": 5313,
"text": " Senol Atac"
},
{
"code": null,
"e": 5358,
"s": 5325,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5370,
"s": 5358,
"text": " Senol Atac"
},
{
"code": null,
"e": 5377,
"s": 5370,
"text": " Print"
},
{
"code": null,
"e": 5388,
"s": 5377,
"text": " Add Notes"
}
] |
HTML5 Canvas - Drawing Lines
|
We require the following methods to draw lines on the canvas −
beginPath()
This method resets the current path.
moveTo(x, y)
This method creates a new subpath with the given point.
closePath()
This method marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath.
fill()
This method fills the subpaths with the current fill style.
stroke()
This method strokes the subpaths with the current stroke style.
lineTo(x, y)
This method adds the given point to the current subpath, connected to the previous one by a straight line.
Following is a simple example which makes use of the above-mentioned methods to draw a triangle.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Filled triangle
ctx.beginPath();
ctx.moveTo(25,25);
ctx.lineTo(105,25);
ctx.lineTo(25,105);
ctx.fill();
// Stroked triangle
ctx.beginPath();
ctx.moveTo(125,125);
ctx.lineTo(125,45);
ctx.lineTo(45,125);
ctx.closePath();
ctx.stroke();
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
The above example would draw following shape −
There are several properties which allow us to style lines.
lineWidth [ = value ]
This property returns the current line width and can be set, to change the line width.
lineCap [ = value ]
This property returns the current line cap style and can be set, to change the line cap style. The possible line cap styles are butt, round, and square
lineJoin [ = value ]
This property returns the current line join style and can be set, to change the line join style. The possible line join styles are bevel, round, andmiter.
miterLimit [ = value ]
This property returns the current miter limit ratio and can be set, to change the miter limit ratio.
Following is a simple example which makes use of lineWidth property to draw lines of different width.
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
for (i=0;i<10;i++){
ctx.lineWidth = 1+i;
ctx.beginPath();
ctx.moveTo(5+i*14,5);
ctx.lineTo(5+i*14,140);
ctx.stroke();
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
The above example would draw following shape −
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": 2671,
"s": 2608,
"text": "We require the following methods to draw lines on the canvas −"
},
{
"code": null,
"e": 2683,
"s": 2671,
"text": "beginPath()"
},
{
"code": null,
"e": 2720,
"s": 2683,
"text": "This method resets the current path."
},
{
"code": null,
"e": 2733,
"s": 2720,
"text": "moveTo(x, y)"
},
{
"code": null,
"e": 2789,
"s": 2733,
"text": "This method creates a new subpath with the given point."
},
{
"code": null,
"e": 2801,
"s": 2789,
"text": "closePath()"
},
{
"code": null,
"e": 2947,
"s": 2801,
"text": "This method marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath."
},
{
"code": null,
"e": 2954,
"s": 2947,
"text": "fill()"
},
{
"code": null,
"e": 3014,
"s": 2954,
"text": "This method fills the subpaths with the current fill style."
},
{
"code": null,
"e": 3023,
"s": 3014,
"text": "stroke()"
},
{
"code": null,
"e": 3087,
"s": 3023,
"text": "This method strokes the subpaths with the current stroke style."
},
{
"code": null,
"e": 3100,
"s": 3087,
"text": "lineTo(x, y)"
},
{
"code": null,
"e": 3207,
"s": 3100,
"text": "This method adds the given point to the current subpath, connected to the previous one by a straight line."
},
{
"code": null,
"e": 3304,
"s": 3207,
"text": "Following is a simple example which makes use of the above-mentioned methods to draw a triangle."
},
{
"code": null,
"e": 4654,
"s": 3304,
"text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <style>\n #test {\n width: 100px;\n height:100px;\n margin: 0px auto;\n }\n </style>\n \n <script type = \"text/javascript\">\n function drawShape() {\n \n // get the canvas element using the DOM\n var canvas = document.getElementById('mycanvas');\n \n // Make sure we don't execute when canvas isn't supported\n if (canvas.getContext) {\n \n // use getContext to use the canvas for drawing\n var ctx = canvas.getContext('2d');\n \n // Filled triangle\n ctx.beginPath();\n ctx.moveTo(25,25);\n ctx.lineTo(105,25);\n ctx.lineTo(25,105);\n ctx.fill();\n \n // Stroked triangle\n ctx.beginPath();\n ctx.moveTo(125,125);\n ctx.lineTo(125,45);\n ctx.lineTo(45,125);\n ctx.closePath();\n ctx.stroke();\n } else {\n alert('You need Safari or Firefox 1.5+ to see this demo.');\n }\n }\n </script>\n </head>\n \n <body id = \"test\" onload = \"drawShape();\">\n <canvas id = \"mycanvas\"></canvas>\n </body>\n \n</html>"
},
{
"code": null,
"e": 4701,
"s": 4654,
"text": "The above example would draw following shape −"
},
{
"code": null,
"e": 4761,
"s": 4701,
"text": "There are several properties which allow us to style lines."
},
{
"code": null,
"e": 4783,
"s": 4761,
"text": "lineWidth [ = value ]"
},
{
"code": null,
"e": 4870,
"s": 4783,
"text": "This property returns the current line width and can be set, to change the line width."
},
{
"code": null,
"e": 4890,
"s": 4870,
"text": "lineCap [ = value ]"
},
{
"code": null,
"e": 5042,
"s": 4890,
"text": "This property returns the current line cap style and can be set, to change the line cap style. The possible line cap styles are butt, round, and square"
},
{
"code": null,
"e": 5063,
"s": 5042,
"text": "lineJoin [ = value ]"
},
{
"code": null,
"e": 5218,
"s": 5063,
"text": "This property returns the current line join style and can be set, to change the line join style. The possible line join styles are bevel, round, andmiter."
},
{
"code": null,
"e": 5241,
"s": 5218,
"text": "miterLimit [ = value ]"
},
{
"code": null,
"e": 5342,
"s": 5241,
"text": "This property returns the current miter limit ratio and can be set, to change the miter limit ratio."
},
{
"code": null,
"e": 5444,
"s": 5342,
"text": "Following is a simple example which makes use of lineWidth property to draw lines of different width."
},
{
"code": null,
"e": 6592,
"s": 5444,
"text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <style>\n #test {\n width: 100px;\n height:100px;\n margin: 0px auto;\n }\n </style>\n \n <script type = \"text/javascript\">\n function drawShape() {\n \n // get the canvas element using the DOM\n var canvas = document.getElementById('mycanvas');\n \n // Make sure we don't execute when canvas isn't supported\n if (canvas.getContext) {\n \n // use getContext to use the canvas for drawing\n var ctx = canvas.getContext('2d');\n \n for (i=0;i<10;i++){\n ctx.lineWidth = 1+i;\n ctx.beginPath();\n ctx.moveTo(5+i*14,5);\n ctx.lineTo(5+i*14,140);\n ctx.stroke();\n }\n } else {\n alert('You need Safari or Firefox 1.5+ to see this demo.');\n }\n }\n </script>\n </head>\n \n <body id = \"test\" onload = \"drawShape();\">\n <canvas id = \"mycanvas\"></canvas>\n </body>\n</html>"
},
{
"code": null,
"e": 6639,
"s": 6592,
"text": "The above example would draw following shape −"
},
{
"code": null,
"e": 6672,
"s": 6639,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6686,
"s": 6672,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6721,
"s": 6686,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6735,
"s": 6721,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6770,
"s": 6735,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6787,
"s": 6770,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6822,
"s": 6787,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6853,
"s": 6822,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6886,
"s": 6853,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6917,
"s": 6886,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6952,
"s": 6917,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6983,
"s": 6952,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6990,
"s": 6983,
"text": " Print"
},
{
"code": null,
"e": 7001,
"s": 6990,
"text": " Add Notes"
}
] |
Python – Check Similar elements in Matrix rows
|
08 Dec, 2020
Given a Matrix and list, the task is to write a Python program to check if all the matrix elements of the row are similar to the ith index of List.
Input : test_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Output : True Explanation : All rows have same elements.
Input : test_list = [[1, 1, 4], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Output : False Explanation : All rows don’t have same elements.
Method #1 : Using loop
In this, we iterate through each row and check for its similar number in the list, if all the elements in a row are the same as an ith element in the List, true is returned, else false.
Python3
# Python3 code to demonstrate working of# Similar all elements as List in Matrix rows# Using loop # initializing Matrixtest_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] # printing original listprint("The original list is : " + str(test_list)) # initializing tar_list tar_list = [1, 4, 3, 5] res = Trueflag = 0for idx in range(len(test_list)): for ele in test_list[idx]: # checking for row index # equal to list index elements if ele != tar_list[idx]: res = False flag = 1 break if flag: break # printing resultprint("Are row index element similar\ to list index element ? : " + str(res))
Output:
The original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]Are row index element similar to list index element ? : True
Method #2 : Using all() + generator expression
In this, we check for all elements to be equal using all(), and check for all elements follow this pattern using all() again. The iteration of elements and rows is done using generator expression.
Python3
# Python3 code to demonstrate working of# Similar all elements as List in Matrix rows# Using all() + generator expression # initializing Matrixtest_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] # printing original listprint("The original list is : " + str(test_list)) # initializing tar_list tar_list = [1, 4, 3, 5] # nested all() used to check each element and rowsres = all(all(ele == tar_list[idx] for ele in test_list[idx]) for idx in range(len(test_list)) ) # printing resultprint("Are row index element\ similar to list index element ? : " + str(res))
Output:
The original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]Are row index element similar to list index element ? : True
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": "\n08 Dec, 2020"
},
{
"code": null,
"e": 176,
"s": 28,
"text": "Given a Matrix and list, the task is to write a Python program to check if all the matrix elements of the row are similar to the ith index of List."
},
{
"code": null,
"e": 298,
"s": 176,
"text": "Input : test_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Output : True Explanation : All rows have same elements."
},
{
"code": null,
"e": 429,
"s": 298,
"text": "Input : test_list = [[1, 1, 4], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Output : False Explanation : All rows don’t have same elements. "
},
{
"code": null,
"e": 453,
"s": 429,
"text": "Method #1 : Using loop "
},
{
"code": null,
"e": 639,
"s": 453,
"text": "In this, we iterate through each row and check for its similar number in the list, if all the elements in a row are the same as an ith element in the List, true is returned, else false."
},
{
"code": null,
"e": 647,
"s": 639,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Similar all elements as List in Matrix rows# Using loop # initializing Matrixtest_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing tar_list tar_list = [1, 4, 3, 5] res = Trueflag = 0for idx in range(len(test_list)): for ele in test_list[idx]: # checking for row index # equal to list index elements if ele != tar_list[idx]: res = False flag = 1 break if flag: break # printing resultprint(\"Are row index element similar\\ to list index element ? : \" + str(res))",
"e": 1376,
"s": 647,
"text": null
},
{
"code": null,
"e": 1385,
"s": 1376,
"text": " Output:"
},
{
"code": null,
"e": 1513,
"s": 1385,
"text": "The original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]Are row index element similar to list index element ? : True"
},
{
"code": null,
"e": 1560,
"s": 1513,
"text": "Method #2 : Using all() + generator expression"
},
{
"code": null,
"e": 1757,
"s": 1560,
"text": "In this, we check for all elements to be equal using all(), and check for all elements follow this pattern using all() again. The iteration of elements and rows is done using generator expression."
},
{
"code": null,
"e": 1767,
"s": 1759,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Similar all elements as List in Matrix rows# Using all() + generator expression # initializing Matrixtest_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing tar_list tar_list = [1, 4, 3, 5] # nested all() used to check each element and rowsres = all(all(ele == tar_list[idx] for ele in test_list[idx]) for idx in range(len(test_list)) ) # printing resultprint(\"Are row index element\\ similar to list index element ? : \" + str(res))",
"e": 2377,
"s": 1767,
"text": null
},
{
"code": null,
"e": 2385,
"s": 2377,
"text": "Output:"
},
{
"code": null,
"e": 2513,
"s": 2385,
"text": "The original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]Are row index element similar to list index element ? : True"
},
{
"code": null,
"e": 2534,
"s": 2513,
"text": "Python list-programs"
},
{
"code": null,
"e": 2541,
"s": 2534,
"text": "Python"
},
{
"code": null,
"e": 2557,
"s": 2541,
"text": "Python Programs"
}
] |
Obtain List of Directories in R
|
06 Jun, 2021
A directory or folder in the R programming language may contain other directories. It is possible to access the list of all the directories using base methods in R and return them as a list of folders.
The list.dirs() method in R language is used to retrieve a list of directories present within the path specified. The output returned is in the form of a character vector containing the names of the files contained in the specified directory path, or returns null if no directories were returned. If the specified path does not exist or is not a directory or is unreadable it is skipped from evaluation.
Syntax:
list.dirs(path = “.”, full.names = TRUE, recursive = TRUE)
Parameter:
path – The path of the main directory
full.names (Default : TRUE) – If set to FALSE, only the names of the subdirectories are displayed. Else, the entire paths are displayed.
Returns: List of files in lexicographic order
Directory in use:
Input main directory
The full path returned when the attribute full.names = TRUE. If we set, recursive = TRUE, the directories are returned in hierarchical order, beginning with the main directory path and then followed by the sub-directories. However, if we specify recursive = FALSE, only the child directories are returned.
Example:
R
# specifying the pathmain_dir <- "/Users/mallikagupta/Desktop/gfg" print ("list of directories including the main directory") dir_list <- list.dirs(main_dir,recursive = TRUE) print (dir_list) print ("list of directories excluding the main directory") dir_list <- list.dirs(main_dir,recursive = FALSE) print (dir_list)
Output
“list of directories including the main directory”
[1] “/Users/mallikagupta/Desktop/gfg” “/Users/mallikagupta/Desktop/gfg/Interviews”
[3] “/Users/mallikagupta/Desktop/gfg/Placements” “/Users/mallikagupta/Desktop/gfg/WFH”
“list of directories excluding the main directory”
[1] “/Users/mallikagupta/Desktop/gfg/Interviews” “/Users/mallikagupta/Desktop/gfg/Placements”
[3] “/Users/mallikagupta/Desktop/gfg/WFH”
Another way, to exclude the main directory is to specify the [-1] index appended to the list.dirs() method which returns only subdirectories.
Example:
R
main_dir <- "/Users/mallikagupta/Desktop/gfg" print ("list of directories") dir_list <- list.dirs(main_dir)[- 1] print (dir_list)
Output
“list of directories”
[1] “/Users/mallikagupta/Desktop/gfg/Interviews” “/Users/mallikagupta/Desktop/gfg/Placements”
[3] “/Users/mallikagupta/Desktop/gfg/WFH”
It is possible to retrieve only the folder or directory names within the main directory. In this case, we set the parameter full.names = FALSE in the method call. The names are alphabetically sorted.
Example:
R
main_dir <- "/Users/mallikagupta/Desktop/gfg" print ("list of directory names") dir_list <- list.dirs(main_dir,full.names = FALSE, recursive = FALSE) print (dir_list)
Output
“list of directory names”
[1] “Interviews” “Placements” “WFH”
gsub() function is used to replace all the matches of a pattern from a string. The pattern we specify is equivalent to a regex (“\\./”) which is used to remove all the previous segments from the complete pathname and return only the last part of the path, that is the folder name.
Syntax:
gsub(pattern, replacement, string)
Parameter:
pattern – The pattern to locate in the string
replacement – The string to replace the matches with.
Example:
R
main_dir <- "/Users/mallikagupta/Desktop/gfg" # set working directorsetwd(main_dir) print ("list of directories")dir_list <- list.dirs()[- 1] # getting folder namesfolder_list <- gsub("\\./", "", dir_list) print (folder_list)
Output
“list of directories”
[1] “Interviews” “Placements” “WFH”
Picked
R directory-programs
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 231,
"s": 28,
"text": "A directory or folder in the R programming language may contain other directories. It is possible to access the list of all the directories using base methods in R and return them as a list of folders. "
},
{
"code": null,
"e": 636,
"s": 231,
"text": "The list.dirs() method in R language is used to retrieve a list of directories present within the path specified. The output returned is in the form of a character vector containing the names of the files contained in the specified directory path, or returns null if no directories were returned. If the specified path does not exist or is not a directory or is unreadable it is skipped from evaluation. "
},
{
"code": null,
"e": 644,
"s": 636,
"text": "Syntax:"
},
{
"code": null,
"e": 703,
"s": 644,
"text": "list.dirs(path = “.”, full.names = TRUE, recursive = TRUE)"
},
{
"code": null,
"e": 715,
"s": 703,
"text": "Parameter: "
},
{
"code": null,
"e": 754,
"s": 715,
"text": "path – The path of the main directory "
},
{
"code": null,
"e": 891,
"s": 754,
"text": "full.names (Default : TRUE) – If set to FALSE, only the names of the subdirectories are displayed. Else, the entire paths are displayed."
},
{
"code": null,
"e": 937,
"s": 891,
"text": "Returns: List of files in lexicographic order"
},
{
"code": null,
"e": 955,
"s": 937,
"text": "Directory in use:"
},
{
"code": null,
"e": 976,
"s": 955,
"text": "Input main directory"
},
{
"code": null,
"e": 1283,
"s": 976,
"text": "The full path returned when the attribute full.names = TRUE. If we set, recursive = TRUE, the directories are returned in hierarchical order, beginning with the main directory path and then followed by the sub-directories. However, if we specify recursive = FALSE, only the child directories are returned. "
},
{
"code": null,
"e": 1292,
"s": 1283,
"text": "Example:"
},
{
"code": null,
"e": 1294,
"s": 1292,
"text": "R"
},
{
"code": "# specifying the pathmain_dir <- \"/Users/mallikagupta/Desktop/gfg\" print (\"list of directories including the main directory\") dir_list <- list.dirs(main_dir,recursive = TRUE) print (dir_list) print (\"list of directories excluding the main directory\") dir_list <- list.dirs(main_dir,recursive = FALSE) print (dir_list)",
"e": 1616,
"s": 1294,
"text": null
},
{
"code": null,
"e": 1623,
"s": 1616,
"text": "Output"
},
{
"code": null,
"e": 1675,
"s": 1623,
"text": "“list of directories including the main directory” "
},
{
"code": null,
"e": 1770,
"s": 1675,
"text": "[1] “/Users/mallikagupta/Desktop/gfg” “/Users/mallikagupta/Desktop/gfg/Interviews” "
},
{
"code": null,
"e": 1865,
"s": 1770,
"text": "[3] “/Users/mallikagupta/Desktop/gfg/Placements” “/Users/mallikagupta/Desktop/gfg/WFH” "
},
{
"code": null,
"e": 1916,
"s": 1865,
"text": "“list of directories excluding the main directory”"
},
{
"code": null,
"e": 2011,
"s": 1916,
"text": "[1] “/Users/mallikagupta/Desktop/gfg/Interviews” “/Users/mallikagupta/Desktop/gfg/Placements” "
},
{
"code": null,
"e": 2055,
"s": 2011,
"text": "[3] “/Users/mallikagupta/Desktop/gfg/WFH” "
},
{
"code": null,
"e": 2198,
"s": 2055,
"text": "Another way, to exclude the main directory is to specify the [-1] index appended to the list.dirs() method which returns only subdirectories. "
},
{
"code": null,
"e": 2207,
"s": 2198,
"text": "Example:"
},
{
"code": null,
"e": 2209,
"s": 2207,
"text": "R"
},
{
"code": "main_dir <- \"/Users/mallikagupta/Desktop/gfg\" print (\"list of directories\") dir_list <- list.dirs(main_dir)[- 1] print (dir_list)",
"e": 2343,
"s": 2209,
"text": null
},
{
"code": null,
"e": 2350,
"s": 2343,
"text": "Output"
},
{
"code": null,
"e": 2372,
"s": 2350,
"text": "“list of directories”"
},
{
"code": null,
"e": 2467,
"s": 2372,
"text": "[1] “/Users/mallikagupta/Desktop/gfg/Interviews” “/Users/mallikagupta/Desktop/gfg/Placements” "
},
{
"code": null,
"e": 2513,
"s": 2467,
"text": "[3] “/Users/mallikagupta/Desktop/gfg/WFH” "
},
{
"code": null,
"e": 2714,
"s": 2513,
"text": "It is possible to retrieve only the folder or directory names within the main directory. In this case, we set the parameter full.names = FALSE in the method call. The names are alphabetically sorted. "
},
{
"code": null,
"e": 2723,
"s": 2714,
"text": "Example:"
},
{
"code": null,
"e": 2725,
"s": 2723,
"text": "R"
},
{
"code": "main_dir <- \"/Users/mallikagupta/Desktop/gfg\" print (\"list of directory names\") dir_list <- list.dirs(main_dir,full.names = FALSE, recursive = FALSE) print (dir_list)",
"e": 2918,
"s": 2725,
"text": null
},
{
"code": null,
"e": 2925,
"s": 2918,
"text": "Output"
},
{
"code": null,
"e": 2952,
"s": 2925,
"text": "“list of directory names” "
},
{
"code": null,
"e": 2989,
"s": 2952,
"text": "[1] “Interviews” “Placements” “WFH” "
},
{
"code": null,
"e": 3271,
"s": 2989,
"text": "gsub() function is used to replace all the matches of a pattern from a string. The pattern we specify is equivalent to a regex (“\\\\./”) which is used to remove all the previous segments from the complete pathname and return only the last part of the path, that is the folder name. "
},
{
"code": null,
"e": 3279,
"s": 3271,
"text": "Syntax:"
},
{
"code": null,
"e": 3314,
"s": 3279,
"text": "gsub(pattern, replacement, string)"
},
{
"code": null,
"e": 3326,
"s": 3314,
"text": "Parameter: "
},
{
"code": null,
"e": 3372,
"s": 3326,
"text": "pattern – The pattern to locate in the string"
},
{
"code": null,
"e": 3426,
"s": 3372,
"text": "replacement – The string to replace the matches with."
},
{
"code": null,
"e": 3435,
"s": 3426,
"text": "Example:"
},
{
"code": null,
"e": 3437,
"s": 3435,
"text": "R"
},
{
"code": "main_dir <- \"/Users/mallikagupta/Desktop/gfg\" # set working directorsetwd(main_dir) print (\"list of directories\")dir_list <- list.dirs()[- 1] # getting folder namesfolder_list <- gsub(\"\\\\./\", \"\", dir_list) print (folder_list)",
"e": 3668,
"s": 3437,
"text": null
},
{
"code": null,
"e": 3675,
"s": 3668,
"text": "Output"
},
{
"code": null,
"e": 3697,
"s": 3675,
"text": "“list of directories”"
},
{
"code": null,
"e": 3737,
"s": 3697,
"text": "[1] “Interviews” “Placements” “WFH” "
},
{
"code": null,
"e": 3744,
"s": 3737,
"text": "Picked"
},
{
"code": null,
"e": 3765,
"s": 3744,
"text": "R directory-programs"
},
{
"code": null,
"e": 3776,
"s": 3765,
"text": "R Language"
}
] |
Plot multiple separate graphs for same data from one Python script
|
13 Sep, 2021
It is very easy to plot different kinds of maps and plots of different data using Python. One such useful library in Python is Matplotlib which is very useful for creating different types of plots using the same data.
The easiest way to install Matplotlib is by using the pip command in the command-line as shown below:
pip install matplotlib
Also, we use numpy and pandas libraries for creating and using the data sets. Therefore, installing numpy and pandas library can also be done using pip command in command-line.
pip install numpy
pip install pandas
To make plots creative and easy to find the located data inside the graph we use the plotly and cufflinks libraries. To use these libraries the method of installation is also the same as above mentioned libraries.
pip install chart_studio.plotly
pip install cufflinks
In this article, we will create a Plotter that enables us to create different types of plots using the same data.
In this program, we first give the option for choosing the data set required to plot the graph. There are 3 options available for that using if-elif statements.
Creating random data using 100 rows and 5 columns
User input data set with 4 rows and 5 columns
Upload the CSV/JSON file
The second step is to decide the plot to be plotted with the entire data set or for specific columns. And lastly, we present different kinds of plotters users want to plot their data and plot the graph accordingly.
Below is the implementation:
Python3
# importing required librariesimport numpy as npimport pandas as pdimport chart_studio.plotly as plimport plotly.offline as poimport cufflinks as cfpo.init_notebook_mode(connected = True)cf.go_offline() # define a function for creating# data set for plotting graphdef createdata(data): # creating random data set if(data == 1): x = np.random.rand(100,5) df1 = pd.DataFrame(x, columns = ['A', 'B', 'C', 'D', 'E']) # creating user data set with input elif(data == 2): x = [0, 0, 0, 0, 0] r1 = [0, 0, 0, 0, 0] r2 = [0, 0, 0, 0, 0] r3 = [0, 0, 0, 0, 0] r4 = [0, 0, 0, 0, 0] print('Enter the values for columns') i = 0 for i in [0, 1, 2, 3, 4]: x[i] = input() i = i + 1 print('Enter the values for first row') i = 0 for i in [0, 1, 2, 3, 4]: r1[i] = int(input()) i = i + 1 print('Enter the values for second row') i = 0 for i in [0, 1, 2, 3, 4]: r2[i] = int(input()) i = i + 1 print('Enter the values for third row') i = 0 for i in [0, 1, 2, 3, 4]: r3[i] = int(input()) i = i + 1 print('Enter the values for fourth row') i = 0 for i in [0, 1, 2, 3, 4]: r4[i] = int(input()) i = i + 1 df1 = pd.DataFrame([r1,r2,r3,r4] , columns = x) # creating data set by csv file elif(data == 3): file = input('Enter the file name') x = pd.read_csv(file) df1 = pd.DataFrame(x) else: print('DataFrame creation failed please' + 'enter in between 1 to 3 and try again') return df1 # define a function for# types of plottersdef plotter(plot): if(plot == 1): finalplot = df1.iplot(kind = 'scatter') elif(plot == 2): finalplot = df1.iplot(kind = 'scatter', mode = 'markers', symbol = 'x', colorscale = 'paired') elif(plot == 3): finalplot = df1.iplot(kind = 'bar') elif(plot == 4): finalplot = df1.iplot(kind = 'hist') elif(plot == 5): finalplot = df1.iplot(kind = 'box') elif(plot == 6): finalplot = df1.iplot(kind = 'surface') else: finalplot = print('Select only between 1 to 7') return finalplot # define a function for allowing# to plot for specific rows and columnsdef plotter2(plot): col = input('Enter the number of columns you' + 'want to plot by selecting only 1 , 2 or 3') col = int(col) if(col==1): colm = input('Enter the column you want to plot' + 'by selecting any column from dataframe head') if(plot == 1): finalplot = df1[colm].iplot(kind = 'scatter') elif(plot == 2): finalplot = df1[colm].iplot(kind = 'scatter', mode = 'markers', symbol = 'x', colorscale = 'paired') elif(plot == 3): finalplot = df1[colm].iplot(kind = 'bar') elif(plot == 4): finalplot = df1[colm].iplot(kind = 'hist') elif(plot == 5): finalplot = df1[colm].iplot(kind = 'box') elif(plot == 6 or plot == 7): finalplot = print('Bubble plot and surface plot require' + 'more than one column arguments') else: finalplot = print('Select only between 1 to 7') elif(col == 2): print('Enter the columns you want to plot' + 'by selecting from dataframe head') x = input('First column') y = input('Second column') if(plot == 1): finalplot = df1[[x,y]].iplot(kind = 'scatter') elif(plot == 2): finalplot = df1[[x,y]].iplot(kind = 'scatter', mode = 'markers', symbol = 'x', colorscale = 'paired') elif(plot == 3): finalplot = df1[[x,y]].iplot(kind = 'bar') elif(plot == 4): finalplot = df1[[x,y]].iplot(kind = 'hist') elif(plot == 5): finalplot = df1[[x,y]].iplot(kind = 'box') elif(plot == 6): finalplot = df1[[x,y]].iplot(kind = 'surface') elif(plot == 7): size = input('Please enter the size column for bubble plot') finalplot = df1.iplot(kind = 'bubble', x = x, y = y, size = size) else: finalplot = print('Select only between 1 to 7') elif(col == 3): print('Enter the columns you want to plot') x = input('First column') y = input('Second column') z = input('Third column') if(plot == 1): finalplot = df1[[x,y,z]].iplot(kind = 'scatter') elif(plot == 2): finalplot = df1[[x,y,z]].iplot(kind = 'scatter', mode = 'markers', symbol = 'x' ,colorscale = 'paired') elif(plot == 3): finalplot = df1[[x,y,z]].iplot(kind = 'bar') elif(plot == 4): finalplot = df1[[x,y,z]].iplot(kind = 'hist') elif(plot == 5): finalplot = df1[[x,y,z]].iplot(kind = 'box') elif(plot == 6): finalplot = df1[[x,y,z]].iplot(kind = 'surface') elif(plot == 7): size = input('Please enter the size column for bubble plot') finalplot = df1.iplot(kind = 'bubble', x = x, y = y, z = z, size = size ) else: finalplot = print('Select only between 1 to 7') else: finalplot = print('Please enter only 1 , 2 or 3') return finalplot # define a main function# for asking type of plot# and calling respective functiondef main(cat): if(cat == 1): print('Select the type of plot you need to plot by writing 1 to 6') print('1.Line plot') print('2.Scatter plot') print('3.Bar plot') print('4.Histogram') print('5.Box plot') print('6.Surface plot') plot = int(input()) output = plotter(plot) elif(cat == 2): print('Select the type of plot you need to plot by writing 1 to 7') print('1.Line plot') print('2.Scatter plot') print('3.Bar plot') print('4.Histogram') print('5.Box plot') print('6.Surface plot') print('7.Bubble plot') plot = int(input()) output = plotter2(plot) else: print('Please enter 1 or 2 and try again') print('Select the type of data you need to plot(By writing 1,2 or 3)')print('1.Random data with 100 rows and 5 columns')print('2.Customize dataframe with 5 columns and. 4 rows')print('3.Upload csv/json/txt file') data = int(input())df1 = createdata(data)print('Your DataFrame head is given below check the columns to plot using cufflinks') df1.head()print('What kind of plot you need , the complete data plot or columns plot')cat = input('Press 1 for plotting all columns or press 2 for specifying columns to plot')cat = int(cat) main(cat)
Output:
Scatter plot:
Scatter graph plot
Histogram plot:
Histogram plot
Boxplot:
Boxplot
simmytarika5
anikakapoor
Data Visualization
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 246,
"s": 28,
"text": "It is very easy to plot different kinds of maps and plots of different data using Python. One such useful library in Python is Matplotlib which is very useful for creating different types of plots using the same data."
},
{
"code": null,
"e": 348,
"s": 246,
"text": "The easiest way to install Matplotlib is by using the pip command in the command-line as shown below:"
},
{
"code": null,
"e": 371,
"s": 348,
"text": "pip install matplotlib"
},
{
"code": null,
"e": 548,
"s": 371,
"text": "Also, we use numpy and pandas libraries for creating and using the data sets. Therefore, installing numpy and pandas library can also be done using pip command in command-line."
},
{
"code": null,
"e": 586,
"s": 548,
"text": "pip install numpy \npip install pandas"
},
{
"code": null,
"e": 801,
"s": 586,
"text": "To make plots creative and easy to find the located data inside the graph we use the plotly and cufflinks libraries. To use these libraries the method of installation is also the same as above mentioned libraries. "
},
{
"code": null,
"e": 855,
"s": 801,
"text": "pip install chart_studio.plotly\npip install cufflinks"
},
{
"code": null,
"e": 969,
"s": 855,
"text": "In this article, we will create a Plotter that enables us to create different types of plots using the same data."
},
{
"code": null,
"e": 1131,
"s": 969,
"text": "In this program, we first give the option for choosing the data set required to plot the graph. There are 3 options available for that using if-elif statements. "
},
{
"code": null,
"e": 1181,
"s": 1131,
"text": "Creating random data using 100 rows and 5 columns"
},
{
"code": null,
"e": 1227,
"s": 1181,
"text": "User input data set with 4 rows and 5 columns"
},
{
"code": null,
"e": 1252,
"s": 1227,
"text": "Upload the CSV/JSON file"
},
{
"code": null,
"e": 1468,
"s": 1252,
"text": "The second step is to decide the plot to be plotted with the entire data set or for specific columns. And lastly, we present different kinds of plotters users want to plot their data and plot the graph accordingly. "
},
{
"code": null,
"e": 1497,
"s": 1468,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1505,
"s": 1497,
"text": "Python3"
},
{
"code": "# importing required librariesimport numpy as npimport pandas as pdimport chart_studio.plotly as plimport plotly.offline as poimport cufflinks as cfpo.init_notebook_mode(connected = True)cf.go_offline() # define a function for creating# data set for plotting graphdef createdata(data): # creating random data set if(data == 1): x = np.random.rand(100,5) df1 = pd.DataFrame(x, columns = ['A', 'B', 'C', 'D', 'E']) # creating user data set with input elif(data == 2): x = [0, 0, 0, 0, 0] r1 = [0, 0, 0, 0, 0] r2 = [0, 0, 0, 0, 0] r3 = [0, 0, 0, 0, 0] r4 = [0, 0, 0, 0, 0] print('Enter the values for columns') i = 0 for i in [0, 1, 2, 3, 4]: x[i] = input() i = i + 1 print('Enter the values for first row') i = 0 for i in [0, 1, 2, 3, 4]: r1[i] = int(input()) i = i + 1 print('Enter the values for second row') i = 0 for i in [0, 1, 2, 3, 4]: r2[i] = int(input()) i = i + 1 print('Enter the values for third row') i = 0 for i in [0, 1, 2, 3, 4]: r3[i] = int(input()) i = i + 1 print('Enter the values for fourth row') i = 0 for i in [0, 1, 2, 3, 4]: r4[i] = int(input()) i = i + 1 df1 = pd.DataFrame([r1,r2,r3,r4] , columns = x) # creating data set by csv file elif(data == 3): file = input('Enter the file name') x = pd.read_csv(file) df1 = pd.DataFrame(x) else: print('DataFrame creation failed please' + 'enter in between 1 to 3 and try again') return df1 # define a function for# types of plottersdef plotter(plot): if(plot == 1): finalplot = df1.iplot(kind = 'scatter') elif(plot == 2): finalplot = df1.iplot(kind = 'scatter', mode = 'markers', symbol = 'x', colorscale = 'paired') elif(plot == 3): finalplot = df1.iplot(kind = 'bar') elif(plot == 4): finalplot = df1.iplot(kind = 'hist') elif(plot == 5): finalplot = df1.iplot(kind = 'box') elif(plot == 6): finalplot = df1.iplot(kind = 'surface') else: finalplot = print('Select only between 1 to 7') return finalplot # define a function for allowing# to plot for specific rows and columnsdef plotter2(plot): col = input('Enter the number of columns you' + 'want to plot by selecting only 1 , 2 or 3') col = int(col) if(col==1): colm = input('Enter the column you want to plot' + 'by selecting any column from dataframe head') if(plot == 1): finalplot = df1[colm].iplot(kind = 'scatter') elif(plot == 2): finalplot = df1[colm].iplot(kind = 'scatter', mode = 'markers', symbol = 'x', colorscale = 'paired') elif(plot == 3): finalplot = df1[colm].iplot(kind = 'bar') elif(plot == 4): finalplot = df1[colm].iplot(kind = 'hist') elif(plot == 5): finalplot = df1[colm].iplot(kind = 'box') elif(plot == 6 or plot == 7): finalplot = print('Bubble plot and surface plot require' + 'more than one column arguments') else: finalplot = print('Select only between 1 to 7') elif(col == 2): print('Enter the columns you want to plot' + 'by selecting from dataframe head') x = input('First column') y = input('Second column') if(plot == 1): finalplot = df1[[x,y]].iplot(kind = 'scatter') elif(plot == 2): finalplot = df1[[x,y]].iplot(kind = 'scatter', mode = 'markers', symbol = 'x', colorscale = 'paired') elif(plot == 3): finalplot = df1[[x,y]].iplot(kind = 'bar') elif(plot == 4): finalplot = df1[[x,y]].iplot(kind = 'hist') elif(plot == 5): finalplot = df1[[x,y]].iplot(kind = 'box') elif(plot == 6): finalplot = df1[[x,y]].iplot(kind = 'surface') elif(plot == 7): size = input('Please enter the size column for bubble plot') finalplot = df1.iplot(kind = 'bubble', x = x, y = y, size = size) else: finalplot = print('Select only between 1 to 7') elif(col == 3): print('Enter the columns you want to plot') x = input('First column') y = input('Second column') z = input('Third column') if(plot == 1): finalplot = df1[[x,y,z]].iplot(kind = 'scatter') elif(plot == 2): finalplot = df1[[x,y,z]].iplot(kind = 'scatter', mode = 'markers', symbol = 'x' ,colorscale = 'paired') elif(plot == 3): finalplot = df1[[x,y,z]].iplot(kind = 'bar') elif(plot == 4): finalplot = df1[[x,y,z]].iplot(kind = 'hist') elif(plot == 5): finalplot = df1[[x,y,z]].iplot(kind = 'box') elif(plot == 6): finalplot = df1[[x,y,z]].iplot(kind = 'surface') elif(plot == 7): size = input('Please enter the size column for bubble plot') finalplot = df1.iplot(kind = 'bubble', x = x, y = y, z = z, size = size ) else: finalplot = print('Select only between 1 to 7') else: finalplot = print('Please enter only 1 , 2 or 3') return finalplot # define a main function# for asking type of plot# and calling respective functiondef main(cat): if(cat == 1): print('Select the type of plot you need to plot by writing 1 to 6') print('1.Line plot') print('2.Scatter plot') print('3.Bar plot') print('4.Histogram') print('5.Box plot') print('6.Surface plot') plot = int(input()) output = plotter(plot) elif(cat == 2): print('Select the type of plot you need to plot by writing 1 to 7') print('1.Line plot') print('2.Scatter plot') print('3.Bar plot') print('4.Histogram') print('5.Box plot') print('6.Surface plot') print('7.Bubble plot') plot = int(input()) output = plotter2(plot) else: print('Please enter 1 or 2 and try again') print('Select the type of data you need to plot(By writing 1,2 or 3)')print('1.Random data with 100 rows and 5 columns')print('2.Customize dataframe with 5 columns and. 4 rows')print('3.Upload csv/json/txt file') data = int(input())df1 = createdata(data)print('Your DataFrame head is given below check the columns to plot using cufflinks') df1.head()print('What kind of plot you need , the complete data plot or columns plot')cat = input('Press 1 for plotting all columns or press 2 for specifying columns to plot')cat = int(cat) main(cat)",
"e": 9106,
"s": 1505,
"text": null
},
{
"code": null,
"e": 9117,
"s": 9109,
"text": "Output:"
},
{
"code": null,
"e": 9133,
"s": 9119,
"text": "Scatter plot:"
},
{
"code": null,
"e": 9155,
"s": 9135,
"text": " Scatter graph plot"
},
{
"code": null,
"e": 9171,
"s": 9155,
"text": "Histogram plot:"
},
{
"code": null,
"e": 9189,
"s": 9173,
"text": "Histogram plot "
},
{
"code": null,
"e": 9198,
"s": 9189,
"text": "Boxplot:"
},
{
"code": null,
"e": 9209,
"s": 9200,
"text": "Boxplot "
},
{
"code": null,
"e": 9224,
"s": 9211,
"text": "simmytarika5"
},
{
"code": null,
"e": 9236,
"s": 9224,
"text": "anikakapoor"
},
{
"code": null,
"e": 9255,
"s": 9236,
"text": "Data Visualization"
},
{
"code": null,
"e": 9270,
"s": 9255,
"text": "python-utility"
},
{
"code": null,
"e": 9277,
"s": 9270,
"text": "Python"
}
] |
Implementing ANDNOT Gate using Adaline Network
|
18 Jun, 2019
ADALINE (Adaptive Linear Neuron or later Adaptive Linear Element) is an early single-layer artificial neural network and the name of the physical device that implemented this network. The problem here is to implement AND-NOT using Adaline network. Here we perform 5 epochs of training and calculate total mean error in each case, the total mean error decreases after each epochs and later becomes nearly constant.
The Truth Table for AND-NOT Gate is as follows:
x1 x2 t
1 1 -1
1 -1 1
-1 1 -1
-1 -1 -1
#include <iostream>using namespace std;int main(){ // input array int arr[4][2] = { { 1, 1 }, { 1, -1 }, { -1, 1 }, { -1, -1 } }; // target array int t[4] = { -1, 1, -1, -1 }, i, j; float yi, dif, dw1, dw2, db, w1 = 0.2, w2 = 0.2, b = 0.2, err[4]; // taking bias in each case as 1 // Calculation upto 5 epochs // consider learning rate = 0.2 for (i = 0; i < 5; i++) { float avg = 0; cout << "EPOCH " << i + 1 << " Errors" << endl << endl; for (j = 0; j < 4; j++) { // calculating net input yi = arr[j][0] * w1 + arr[j][1] * w2 + 1 * b; dif = t[j] - yi; // updated weights w1 += 0.2 * dif * arr[j][0]; w2 += 0.2 * dif * arr[j][1]; b += 0.2 * dif * 1; err[j] = dif * dif; cout << err[j] << " "; avg += err[j]; } cout << endl << "Total Mean Error :" << avg << endl << endl << endl; } return 0;}
EPOCH 1 Errors
2.56 1.2544 0.430336 1.47088
Total Mean Error :5.71562
EPOCH 2 Errors
0.951327 0.569168 0.106353 0.803357
Total Mean Error :2.43021
EPOCH 3 Errors
0.617033 0.494715 0.369035 0.604961
Total Mean Error :2.08574
EPOCH 4 Errors
0.535726 0.496723 0.470452 0.541166
Total Mean Error :2.04407
EPOCH 5 Errors
0.515577 0.503857 0.499932 0.520188
Total Mean Error :2.03955
Neural Network
C++ Programs
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to check if a given String is Palindrome or not
How to find the minimum and maximum element of a Vector using STL in C++?
Shallow Copy and Deep Copy in C++
C Program to Swap two Numbers
Enumerated Types or Enums in C++
Naive Bayes Classifiers
Reinforcement learning
Agents in Artificial Intelligence
Search Algorithms in AI
Markov Decision Process
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2019"
},
{
"code": null,
"e": 442,
"s": 28,
"text": "ADALINE (Adaptive Linear Neuron or later Adaptive Linear Element) is an early single-layer artificial neural network and the name of the physical device that implemented this network. The problem here is to implement AND-NOT using Adaline network. Here we perform 5 epochs of training and calculate total mean error in each case, the total mean error decreases after each epochs and later becomes nearly constant."
},
{
"code": null,
"e": 546,
"s": 442,
"text": "The Truth Table for AND-NOT Gate is as follows:\n x1 x2 t\n 1 1 -1\n 1 -1 1\n-1 1 -1\n-1 -1 -1\n"
},
{
"code": "#include <iostream>using namespace std;int main(){ // input array int arr[4][2] = { { 1, 1 }, { 1, -1 }, { -1, 1 }, { -1, -1 } }; // target array int t[4] = { -1, 1, -1, -1 }, i, j; float yi, dif, dw1, dw2, db, w1 = 0.2, w2 = 0.2, b = 0.2, err[4]; // taking bias in each case as 1 // Calculation upto 5 epochs // consider learning rate = 0.2 for (i = 0; i < 5; i++) { float avg = 0; cout << \"EPOCH \" << i + 1 << \" Errors\" << endl << endl; for (j = 0; j < 4; j++) { // calculating net input yi = arr[j][0] * w1 + arr[j][1] * w2 + 1 * b; dif = t[j] - yi; // updated weights w1 += 0.2 * dif * arr[j][0]; w2 += 0.2 * dif * arr[j][1]; b += 0.2 * dif * 1; err[j] = dif * dif; cout << err[j] << \" \"; avg += err[j]; } cout << endl << \"Total Mean Error :\" << avg << endl << endl << endl; } return 0;}",
"e": 1632,
"s": 546,
"text": null
},
{
"code": null,
"e": 2029,
"s": 1632,
"text": "EPOCH 1 Errors\n\n2.56 1.2544 0.430336 1.47088 \nTotal Mean Error :5.71562\n\n\nEPOCH 2 Errors\n\n0.951327 0.569168 0.106353 0.803357 \nTotal Mean Error :2.43021\n\n\nEPOCH 3 Errors\n\n0.617033 0.494715 0.369035 0.604961 \nTotal Mean Error :2.08574\n\n\nEPOCH 4 Errors\n\n0.535726 0.496723 0.470452 0.541166 \nTotal Mean Error :2.04407\n\n\nEPOCH 5 Errors\n\n0.515577 0.503857 0.499932 0.520188 \nTotal Mean Error :2.03955\n"
},
{
"code": null,
"e": 2044,
"s": 2029,
"text": "Neural Network"
},
{
"code": null,
"e": 2057,
"s": 2044,
"text": "C++ Programs"
},
{
"code": null,
"e": 2074,
"s": 2057,
"text": "Machine Learning"
},
{
"code": null,
"e": 2091,
"s": 2074,
"text": "Machine Learning"
},
{
"code": null,
"e": 2189,
"s": 2091,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2249,
"s": 2189,
"text": "C++ Program to check if a given String is Palindrome or not"
},
{
"code": null,
"e": 2323,
"s": 2249,
"text": "How to find the minimum and maximum element of a Vector using STL in C++?"
},
{
"code": null,
"e": 2357,
"s": 2323,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 2387,
"s": 2357,
"text": "C Program to Swap two Numbers"
},
{
"code": null,
"e": 2420,
"s": 2387,
"text": "Enumerated Types or Enums in C++"
},
{
"code": null,
"e": 2444,
"s": 2420,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 2467,
"s": 2444,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 2501,
"s": 2467,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 2525,
"s": 2501,
"text": "Search Algorithms in AI"
}
] |
Pandas.cut() method in Python
|
13 Jul, 2021
Pandas cut() function is used to separate the array elements into different bins . The cut function is mainly used to perform statistical analysis on scalar data.
Syntax: cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False, duplicates=”raise”,)
Parameters:
x: The input array to be binned. Must be 1-dimensional.
bins: defines the bin edges for the segmentation.
right : (bool, default True ) Indicates whether bins includes the rightmost edge or not. If right == True (the default), then the bins [1, 2, 3, 4] indicate (1,2], (2,3], (3,4].
labels : (array or bool, optional) Specifies the labels for the returned bins. Must be the same length as the resulting bins. If False, returns only integer indicators of the bins.
retbins : (bool, default False) Whether to return the bins or not. Useful when bins is provided as a scalar.
Example 1: Let’s say we have an array of 10 random numbers from 1 to 100 and we wish to separate data into 5 bins of (1,20] , (20,40] , (40,60] , (60,80] , (80,100] .
Python3
import pandas as pdimport numpy as np df= pd.DataFrame({'number': np.random.randint(1, 100, 10)})df['bins'] = pd.cut(x=df['number'], bins=[1, 20, 40, 60, 80, 100])print(df) # We can check the frequency of each binprint(df['bins'].unique())
Output:
Example 2: We can also add labels to our bins, for example let’s look at the previous example and add some labels to it
Python3
import pandas as pdimport numpy as np df = pd.DataFrame({'number': np.random.randint(1, 100, 10)})df['bins'] = pd.cut(x=df['number'], bins=[1, 20, 40, 60, 80, 100], labels=['1 to 20', '21 to 40', '41 to 60', '61 to 80', '81 to 100']) print(df) # We can check the frequency of each binprint(df['bins'].unique())
Output:
rajeev0719singh
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 218,
"s": 53,
"text": "Pandas cut() function is used to separate the array elements into different bins . The cut function is mainly used to perform statistical analysis on scalar data. "
},
{
"code": null,
"e": 335,
"s": 218,
"text": "Syntax: cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False, duplicates=”raise”,)"
},
{
"code": null,
"e": 347,
"s": 335,
"text": "Parameters:"
},
{
"code": null,
"e": 403,
"s": 347,
"text": "x: The input array to be binned. Must be 1-dimensional."
},
{
"code": null,
"e": 453,
"s": 403,
"text": "bins: defines the bin edges for the segmentation."
},
{
"code": null,
"e": 633,
"s": 453,
"text": "right : (bool, default True ) Indicates whether bins includes the rightmost edge or not. If right == True (the default), then the bins [1, 2, 3, 4] indicate (1,2], (2,3], (3,4]. "
},
{
"code": null,
"e": 816,
"s": 633,
"text": "labels : (array or bool, optional) Specifies the labels for the returned bins. Must be the same length as the resulting bins. If False, returns only integer indicators of the bins. "
},
{
"code": null,
"e": 925,
"s": 816,
"text": "retbins : (bool, default False) Whether to return the bins or not. Useful when bins is provided as a scalar."
},
{
"code": null,
"e": 1093,
"s": 925,
"text": "Example 1: Let’s say we have an array of 10 random numbers from 1 to 100 and we wish to separate data into 5 bins of (1,20] , (20,40] , (40,60] , (60,80] , (80,100] ."
},
{
"code": null,
"e": 1101,
"s": 1093,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as np df= pd.DataFrame({'number': np.random.randint(1, 100, 10)})df['bins'] = pd.cut(x=df['number'], bins=[1, 20, 40, 60, 80, 100])print(df) # We can check the frequency of each binprint(df['bins'].unique())",
"e": 1383,
"s": 1101,
"text": null
},
{
"code": null,
"e": 1395,
"s": 1387,
"text": "Output:"
},
{
"code": null,
"e": 1520,
"s": 1399,
"text": "Example 2: We can also add labels to our bins, for example let’s look at the previous example and add some labels to it"
},
{
"code": null,
"e": 1530,
"s": 1522,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as np df = pd.DataFrame({'number': np.random.randint(1, 100, 10)})df['bins'] = pd.cut(x=df['number'], bins=[1, 20, 40, 60, 80, 100], labels=['1 to 20', '21 to 40', '41 to 60', '61 to 80', '81 to 100']) print(df) # We can check the frequency of each binprint(df['bins'].unique())",
"e": 1887,
"s": 1530,
"text": null
},
{
"code": null,
"e": 1895,
"s": 1887,
"text": "Output:"
},
{
"code": null,
"e": 1911,
"s": 1895,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 1925,
"s": 1911,
"text": "Python-pandas"
},
{
"code": null,
"e": 1932,
"s": 1925,
"text": "Python"
}
] |
QuickSort using Random Pivoting
|
20 Jun, 2022
In this article, we will discuss how to implement QuickSort using random pivoting. In QuickSort we first partition the array in place such that all elements to the left of the pivot element are smaller, while all elements to the right of the pivot are greater than the pivot. Then we recursively call the same procedure for left and right subarrays. Unlike merge sort, we don’t need to merge the two sorted arrays. Thus Quicksort requires lesser auxiliary space than Merge Sort, which is why it is often preferred to Merge Sort. Using a randomly generated pivot we can further improve the time complexity of QuickSort.
We have discussed at two popular methods for partitioning the arrays-Hoare’s vs Lomuto partition scheme It is advised that the reader has read that article or knows how to implement the QuickSort using either of the two partition schemes.
Algorithm for random pivoting using Lomuto Partitioning
partition(arr[], lo, hi)
pivot = arr[hi]
i = lo // place for swapping
for j := lo to hi – 1 do
if arr[j] <= pivot then
swap arr[i] with arr[j]
i = i + 1
swap arr[i] with arr[hi]
return i
partition_r(arr[], lo, hi)
r = Random Number from lo to hi
Swap arr[r] and arr[hi]
return partition(arr, lo, hi)
quicksort(arr[], lo, hi)
if lo < hi
p = partition_r(arr, lo, hi)
quicksort(arr, lo , p-1)
quicksort(arr, p+1, hi)
Implementation using Lomuto Partitioning:
C++
Java
Python3
C#
C
// C++ implementation QuickSort // using Lomuto's partition Scheme.#include <cstdlib>#include <time.h>#include <iostream>using namespace std; // This function takes last element// as pivot, places// the pivot element at its correct// position in sorted array, and // places all smaller (smaller than pivot)// to left of pivot and all greater // elements to right of pivotint partition(int arr[], int low, int high){ // pivot int pivot = arr[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { // increment index of // smaller element i++; swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); return (i + 1);} // Generates Random Pivot, swaps pivot with// end element and calls the partition functionint partition_r(int arr[], int low, int high){ // Generate a random number in between // low .. high srand(time(NULL)); int random = low + rand() % (high - low); // Swap A[random] with A[high] swap(arr[random], arr[high]); return partition(arr, low, high);} /* The main function that implementsQuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index */void quickSort(int arr[], int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition_r(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) cout<<arr[i]<<" "; } // Driver Codeint main(){ int arr[] = { 10, 7, 8, 9, 1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); printf("Sorted array: \n"); printArray(arr, n); return 0;}
// Java program to illustrate// Randomised Quick Sort import java.util.*; class RandomizedQsort { // This Function helps in calculating // random numbers between low(inclusive) // and high(inclusive) static void random(int arr[],int low,int high) { Random rand= new Random(); int pivot = rand.nextInt(high-low)+low; int temp1=arr[pivot]; arr[pivot]=arr[high]; arr[high]=temp1; } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int arr[], int low, int high) { // pivot is chosen randomly random(arr,low,high); int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] < pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi-1); sort(arr, pi+1, high); } } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i]+" "); System.out.println(); } // Driver Code public static void main(String args[]) { int arr[] = {10, 7, 8, 9, 1, 5}; int n = arr.length; sort(arr, 0, n-1); System.out.println("Sorted array"); printArray(arr); } } // This code is contributed by Ritika Gupta.
# Python implementation QuickSort using # Lomuto's partition Scheme.import random '''The function which implements QuickSort.arr :- array to be sorted.start :- starting index of the array.stop :- ending index of the array.'''def quicksort(arr, start , stop): if(start < stop): # pivotindex is the index where # the pivot lies in the array pivotindex = partitionrand(arr,\ start, stop) # At this stage the array is # partially sorted around the pivot. # Separately sorting the # left half of the array and the # right half of the array. quicksort(arr , start , pivotindex-1) quicksort(arr, pivotindex + 1, stop) # This function generates random pivot,# swaps the first element with the pivot # and calls the partition function.def partitionrand(arr , start, stop): # Generating a random number between the # starting index of the array and the # ending index of the array. randpivot = random.randrange(start, stop) # Swapping the starting element of # the array and the pivot arr[start], arr[randpivot] = \ arr[randpivot], arr[start] return partition(arr, start, stop) '''This function takes the first element as pivot, places the pivot element at the correct position in the sorted array. All the elements are re-arranged according to the pivot, the elements smaller than thepivot is places on the left and the elementsgreater than the pivot is placed to the right of pivot.'''def partition(arr,start,stop): pivot = start # pivot # a variable to memorize where the i = start + 1 # partition in the array starts from. for j in range(start + 1, stop + 1): # if the current element is smaller # or equal to pivot, shift it to the # left side of the partition. if arr[j] <= arr[pivot]: arr[i] , arr[j] = arr[j] , arr[i] i = i + 1 arr[pivot] , arr[i - 1] =\ arr[i - 1] , arr[pivot] pivot = i - 1 return (pivot) # Driver Codeif __name__ == "__main__": array = [10, 7, 8, 9, 1, 5] quicksort(array, 0, len(array) - 1) print(array) # This code is contributed by soumyasaurav
// C# program to illustrate// Randomised Quick sort using System;class RandomizedQsort { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int[] arr, int low, int high) { // pivot is chosen randomly random(arr, low, high); int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] < pivot) { i++; // swap arr[i] and arr[j] int tempp = arr[i]; arr[i] = arr[j]; arr[j] = tempp; } } // swap arr[i+1] and arr[high] (or pivot) int tempp2 = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = tempp2; return i + 1; } // This Function helps in calculating // random numbers between low(inclusive) // and high(inclusive) static int random(int[] arr, int low, int high) { Random rand = new Random(); int pivot = rand.Next() % (high - low) + low; int tempp1 = arr[pivot]; arr[pivot] = arr[high]; arr[high] = tempp1; return partition(arr, low, high); } /* The main function that implements Quicksort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(int[] arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi - 1); sort(arr, pi + 1, high); } } /* A utility function to print array of size n */ static void printArray(int[] arr) { int n = arr.Length; for (int i = 0; i < n; ++i) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver Code static public void Main () { int[] arr = {10, 7, 8, 9, 1, 5}; int n = arr.Length; sort(arr, 0, n-1); Console.WriteLine("sorted array"); printArray(arr); } } // This code is contributed by shubhamsingh10
#include <stdio.h>#include <stdlib.h>#include <time.h> int partition(int arr[], int low, int high){ int pivot = arr[low]; int i = low - 1, j = high + 1; while (1) { do { i++; } while (arr[i] < pivot); do { j--; } while (arr[j] > pivot); if (i >= j) return j; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }} int partition_r(int arr[], int low, int high){ srand(time(0)); int random = low + rand() % (high - low); int temp = arr[random]; arr[random] = arr[low]; arr[low] = temp; return partition(arr, low, high);} void quickSort(int arr[], int low, int high){ if (low < high) { int pi = partition_r(arr, low, high); quickSort(arr, low, pi); quickSort(arr, pi + 1, high); }} void printArray(int arr[], int n){ for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} int main(){ int arr[] = { 10, 7, 8, 9, 1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); printf("Sorted array: \n"); printArray(arr, n); return 0;}
Sorted array:
1 5 7 8 9 10
Algorithm for random pivoting using Hoare Partitioning
partition(arr[], lo, hi)
pivot = arr[lo]
i = lo - 1 // Initialize left index
j = hi + 1 // Initialize right index
while(True)
// Find a value in left side greater than pivot
do
i = i + 1
while arr[i] < pivot
// Find a value in right side smaller than pivot
do
j = j - 1
while arr[j] > pivot
if i >= j then
return j
else
swap arr[i] with arr[j]
end while
partition_r(arr[], lo, hi)
r = Random number from lo to hi
Swap arr[r] and arr[lo]
return partition(arr, lo, hi)
quicksort(arr[], lo, hi)
if lo < hi
p = partition_r(arr, lo, hi)
quicksort(arr, lo, p)
quicksort(arr, p+1, hi)
Implementation using Hoare’s Partitioning:
C++
Java
Python3
// C++ implementation of QuickSort// using Hoare's partition scheme #include <cstdlib>#include <iostream>using namespace std; // This function takes last element as // pivot, places the pivot element at// its correct position in sorted// array, and places all smaller // (smaller than pivot) to left of pivot// and all greater elements to rightint partition(int arr[], int low, int high){ int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // Find leftmost element greater than // or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller than // or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met if (i >= j) return j; swap(arr[i], arr[j]); }} // Generates Random Pivot, swaps pivot with// end element and calls the partition function// In Hoare partition the low element is selected// as first pivotint partition_r(int arr[], int low, int high){ // Generate a random number in between // low .. high srand(time(NULL)); int random = low + rand() % (high - low); // Swap A[random] with A[high] swap(arr[random], arr[low]); return partition(arr, low, high);} // The main function that implements QuickSort// arr[] --> Array to be sorted,// low --> Starting index,// high --> Ending indexvoid quickSort(int arr[], int low, int high){ if (low < high) { // pi is partitioning index, // arr[p] is now at right place int pi = partition_r(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); }} // Function to print an arrayvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // Driver Codeint main(){ int arr[] = { 10, 7, 8, 9, 1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); printf("Sorted array: \n"); printArray(arr, n); return 0;}
/*JAVA implementation of Randomize QuickSortusing Hoare's Partition*/import java.util.*; class GFG{ // swap function static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } /* // partition function This function takes array, low and high index, swaps low with random index between low and high then places all elements less than pivot in the left of pivot and all elements greater than pivot to the right of pivot */ static int partition(int[] arr, int low, int high) { // rIndex gives the random index between low and // high (both inclusive) int rIndex = (low) + (int)(Math.random() * (high - low + 1)); swap(arr, low, rIndex); // swap low with random index int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // increase i while elements are less than pivot do { i++; } while (arr[i] < pivot); // decrease j while elements are greater than pivot do { j--; } while (arr[j] > pivot); if (i >= j) // when both pointers meet // that means elements are at their // correct place for now return j; swap(arr, i, j); // swap i and j, since both are not at their // correct index } } // recursive quick sort function static void quickSort(int[] arr, int low, int high) { if (low < high) { // find partition index int p = partition(arr, low, high); // sort before and after the pivot quickSort(arr, low, p); quickSort(arr, p + 1, high); } } // Driver code public static void main(String[] args) { int[] arr = { 10, 7, 8, 9, 1, 5 }; quickSort(arr, 0, arr.length - 1); System.out.println("Sorted array : "); System.out.print(Arrays.toString(arr)); }} // This code is contributed by Anubhav Singh (singhanubhav)
# Python implementation QuickSort using # Hoare's partition Scheme. import random '''The function which implements randomisedQuickSort, using Haore's partition scheme.arr :- array to be sorted.start :- starting index of the array.stop :- ending index of the array.'''def quicksort(arr, start, stop): if(start < stop): # pivotindex is the index where # the pivot lies in the array pivotindex = partitionrand(arr,\ start, stop) # At this stage the array is # partially sorted around the pivot. # separately sorting the left half of # the array and the right # half of the array. quicksort(arr , start , pivotindex) quicksort(arr, pivotindex + 1, stop) # This function generates random pivot,# swaps the first element with the pivot# and calls the partition function.def partitionrand(arr , start, stop): # Generating a random number between # the starting index of the array and # the ending index of the array. randpivot = random.randrange(start, stop) # Swapping the starting element of # the array and the pivot arr[start], arr[randpivot] =\ arr[randpivot], arr[start] return partition(arr, start, stop) '''This function takes the first elementas pivot, places the pivot element atthe correct position in the sorted array.All the elements are re-arranged accordingto the pivot, the elements smaller than the pivot is places on the left and the elements greater than the pivot isplaced to the right of pivot.'''def partition(arr,start,stop): pivot = start # pivot i = start - 1 j = stop + 1 while True: while True: i = i + 1 if arr[i] >= arr[pivot]: break while True: j = j - 1 if arr[j] <= arr[pivot]: break if i >= j: return j arr[i] , arr[j] = arr[j] , arr[i] # Driver Codeif __name__ == "__main__": array = [10, 7, 8, 9, 1, 5] quicksort(array, 0, len(array) - 1) print(array) # This code is contributed by soumyasaurav
Sorted array:
1 5 7 8 9 10
Analysis of Randomized Quick Sort
Notes
Using random pivoting we improve the expected or average time complexity to O (N log N). The Worst-Case complexity is still O ( N^2 ).
ritz7
soumyasaurav
shubham_singh
Akanksha_Rai
sudhanshublaze
siddhantmodi18
SHUBHAMSINGH10
subhajit07
sooda367
simmytarika5
hdmehta406
meetgor
singhanubhav
Randomized
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 671,
"s": 52,
"text": "In this article, we will discuss how to implement QuickSort using random pivoting. In QuickSort we first partition the array in place such that all elements to the left of the pivot element are smaller, while all elements to the right of the pivot are greater than the pivot. Then we recursively call the same procedure for left and right subarrays. Unlike merge sort, we don’t need to merge the two sorted arrays. Thus Quicksort requires lesser auxiliary space than Merge Sort, which is why it is often preferred to Merge Sort. Using a randomly generated pivot we can further improve the time complexity of QuickSort."
},
{
"code": null,
"e": 910,
"s": 671,
"text": "We have discussed at two popular methods for partitioning the arrays-Hoare’s vs Lomuto partition scheme It is advised that the reader has read that article or knows how to implement the QuickSort using either of the two partition schemes."
},
{
"code": null,
"e": 966,
"s": 910,
"text": "Algorithm for random pivoting using Lomuto Partitioning"
},
{
"code": null,
"e": 1479,
"s": 966,
"text": "partition(arr[], lo, hi) \n pivot = arr[hi]\n i = lo // place for swapping\n for j := lo to hi – 1 do\n if arr[j] <= pivot then\n swap arr[i] with arr[j]\n i = i + 1\n swap arr[i] with arr[hi]\n return i\n\npartition_r(arr[], lo, hi)\n r = Random Number from lo to hi\n Swap arr[r] and arr[hi]\n return partition(arr, lo, hi)\n\nquicksort(arr[], lo, hi)\n if lo < hi\n p = partition_r(arr, lo, hi)\n quicksort(arr, lo , p-1)\n quicksort(arr, p+1, hi)"
},
{
"code": null,
"e": 1521,
"s": 1479,
"text": "Implementation using Lomuto Partitioning:"
},
{
"code": null,
"e": 1525,
"s": 1521,
"text": "C++"
},
{
"code": null,
"e": 1530,
"s": 1525,
"text": "Java"
},
{
"code": null,
"e": 1538,
"s": 1530,
"text": "Python3"
},
{
"code": null,
"e": 1541,
"s": 1538,
"text": "C#"
},
{
"code": null,
"e": 1543,
"s": 1541,
"text": "C"
},
{
"code": "// C++ implementation QuickSort // using Lomuto's partition Scheme.#include <cstdlib>#include <time.h>#include <iostream>using namespace std; // This function takes last element// as pivot, places// the pivot element at its correct// position in sorted array, and // places all smaller (smaller than pivot)// to left of pivot and all greater // elements to right of pivotint partition(int arr[], int low, int high){ // pivot int pivot = arr[high]; // Index of smaller element int i = (low - 1); for (int j = low; j <= high - 1; j++) { // If current element is smaller // than or equal to pivot if (arr[j] <= pivot) { // increment index of // smaller element i++; swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); return (i + 1);} // Generates Random Pivot, swaps pivot with// end element and calls the partition functionint partition_r(int arr[], int low, int high){ // Generate a random number in between // low .. high srand(time(NULL)); int random = low + rand() % (high - low); // Swap A[random] with A[high] swap(arr[random], arr[high]); return partition(arr, low, high);} /* The main function that implementsQuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index */void quickSort(int arr[], int low, int high){ if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition_r(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); }} /* Function to print an array */void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) cout<<arr[i]<<\" \"; } // Driver Codeint main(){ int arr[] = { 10, 7, 8, 9, 1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); printf(\"Sorted array: \\n\"); printArray(arr, n); return 0;}",
"e": 3600,
"s": 1543,
"text": null
},
{
"code": "// Java program to illustrate// Randomised Quick Sort import java.util.*; class RandomizedQsort { // This Function helps in calculating // random numbers between low(inclusive) // and high(inclusive) static void random(int arr[],int low,int high) { Random rand= new Random(); int pivot = rand.nextInt(high-low)+low; int temp1=arr[pivot]; arr[pivot]=arr[high]; arr[high]=temp1; } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int arr[], int low, int high) { // pivot is chosen randomly random(arr,low,high); int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] < pivot) { i++; // swap arr[i] and arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // swap arr[i+1] and arr[high] (or pivot) int temp = arr[i+1]; arr[i+1] = arr[high]; arr[high] = temp; return i+1; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi-1); sort(arr, pi+1, high); } } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i]+\" \"); System.out.println(); } // Driver Code public static void main(String args[]) { int arr[] = {10, 7, 8, 9, 1, 5}; int n = arr.length; sort(arr, 0, n-1); System.out.println(\"Sorted array\"); printArray(arr); } } // This code is contributed by Ritika Gupta.",
"e": 6149,
"s": 3600,
"text": null
},
{
"code": "# Python implementation QuickSort using # Lomuto's partition Scheme.import random '''The function which implements QuickSort.arr :- array to be sorted.start :- starting index of the array.stop :- ending index of the array.'''def quicksort(arr, start , stop): if(start < stop): # pivotindex is the index where # the pivot lies in the array pivotindex = partitionrand(arr,\\ start, stop) # At this stage the array is # partially sorted around the pivot. # Separately sorting the # left half of the array and the # right half of the array. quicksort(arr , start , pivotindex-1) quicksort(arr, pivotindex + 1, stop) # This function generates random pivot,# swaps the first element with the pivot # and calls the partition function.def partitionrand(arr , start, stop): # Generating a random number between the # starting index of the array and the # ending index of the array. randpivot = random.randrange(start, stop) # Swapping the starting element of # the array and the pivot arr[start], arr[randpivot] = \\ arr[randpivot], arr[start] return partition(arr, start, stop) '''This function takes the first element as pivot, places the pivot element at the correct position in the sorted array. All the elements are re-arranged according to the pivot, the elements smaller than thepivot is places on the left and the elementsgreater than the pivot is placed to the right of pivot.'''def partition(arr,start,stop): pivot = start # pivot # a variable to memorize where the i = start + 1 # partition in the array starts from. for j in range(start + 1, stop + 1): # if the current element is smaller # or equal to pivot, shift it to the # left side of the partition. if arr[j] <= arr[pivot]: arr[i] , arr[j] = arr[j] , arr[i] i = i + 1 arr[pivot] , arr[i - 1] =\\ arr[i - 1] , arr[pivot] pivot = i - 1 return (pivot) # Driver Codeif __name__ == \"__main__\": array = [10, 7, 8, 9, 1, 5] quicksort(array, 0, len(array) - 1) print(array) # This code is contributed by soumyasaurav",
"e": 8399,
"s": 6149,
"text": null
},
{
"code": "// C# program to illustrate// Randomised Quick sort using System;class RandomizedQsort { /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ static int partition(int[] arr, int low, int high) { // pivot is chosen randomly random(arr, low, high); int pivot = arr[high]; int i = (low-1); // index of smaller element for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot if (arr[j] < pivot) { i++; // swap arr[i] and arr[j] int tempp = arr[i]; arr[i] = arr[j]; arr[j] = tempp; } } // swap arr[i+1] and arr[high] (or pivot) int tempp2 = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = tempp2; return i + 1; } // This Function helps in calculating // random numbers between low(inclusive) // and high(inclusive) static int random(int[] arr, int low, int high) { Random rand = new Random(); int pivot = rand.Next() % (high - low) + low; int tempp1 = arr[pivot]; arr[pivot] = arr[high]; arr[high] = tempp1; return partition(arr, low, high); } /* The main function that implements Quicksort() arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ static void sort(int[] arr, int low, int high) { if (low < high) { /* pi is partitioning index, arr[pi] is now at right place */ int pi = partition(arr, low, high); // Recursively sort elements before // partition and after partition sort(arr, low, pi - 1); sort(arr, pi + 1, high); } } /* A utility function to print array of size n */ static void printArray(int[] arr) { int n = arr.Length; for (int i = 0; i < n; ++i) Console.Write(arr[i] + \" \"); Console.WriteLine(); } // Driver Code static public void Main () { int[] arr = {10, 7, 8, 9, 1, 5}; int n = arr.Length; sort(arr, 0, n-1); Console.WriteLine(\"sorted array\"); printArray(arr); } } // This code is contributed by shubhamsingh10",
"e": 10707,
"s": 8399,
"text": null
},
{
"code": "#include <stdio.h>#include <stdlib.h>#include <time.h> int partition(int arr[], int low, int high){ int pivot = arr[low]; int i = low - 1, j = high + 1; while (1) { do { i++; } while (arr[i] < pivot); do { j--; } while (arr[j] > pivot); if (i >= j) return j; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }} int partition_r(int arr[], int low, int high){ srand(time(0)); int random = low + rand() % (high - low); int temp = arr[random]; arr[random] = arr[low]; arr[low] = temp; return partition(arr, low, high);} void quickSort(int arr[], int low, int high){ if (low < high) { int pi = partition_r(arr, low, high); quickSort(arr, low, pi); quickSort(arr, pi + 1, high); }} void printArray(int arr[], int n){ for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} int main(){ int arr[] = { 10, 7, 8, 9, 1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); printf(\"Sorted array: \\n\"); printArray(arr, n); return 0;}",
"e": 11854,
"s": 10707,
"text": null
},
{
"code": null,
"e": 11883,
"s": 11854,
"text": "Sorted array: \n1 5 7 8 9 10 "
},
{
"code": null,
"e": 11938,
"s": 11883,
"text": "Algorithm for random pivoting using Hoare Partitioning"
},
{
"code": null,
"e": 12744,
"s": 11938,
"text": "partition(arr[], lo, hi)\n pivot = arr[lo]\n i = lo - 1 // Initialize left index\n j = hi + 1 // Initialize right index\n \n while(True)\n // Find a value in left side greater than pivot\n do\n i = i + 1\n while arr[i] < pivot\n // Find a value in right side smaller than pivot\n do\n j = j - 1\n while arr[j] > pivot\n \n if i >= j then \n return j\n else\n swap arr[i] with arr[j]\n end while\n \npartition_r(arr[], lo, hi)\n r = Random number from lo to hi\n Swap arr[r] and arr[lo]\n return partition(arr, lo, hi)\n\nquicksort(arr[], lo, hi)\n if lo < hi\n p = partition_r(arr, lo, hi)\n quicksort(arr, lo, p)\n quicksort(arr, p+1, hi)"
},
{
"code": null,
"e": 12787,
"s": 12744,
"text": "Implementation using Hoare’s Partitioning:"
},
{
"code": null,
"e": 12791,
"s": 12787,
"text": "C++"
},
{
"code": null,
"e": 12796,
"s": 12791,
"text": "Java"
},
{
"code": null,
"e": 12804,
"s": 12796,
"text": "Python3"
},
{
"code": "// C++ implementation of QuickSort// using Hoare's partition scheme #include <cstdlib>#include <iostream>using namespace std; // This function takes last element as // pivot, places the pivot element at// its correct position in sorted// array, and places all smaller // (smaller than pivot) to left of pivot// and all greater elements to rightint partition(int arr[], int low, int high){ int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // Find leftmost element greater than // or equal to pivot do { i++; } while (arr[i] < pivot); // Find rightmost element smaller than // or equal to pivot do { j--; } while (arr[j] > pivot); // If two pointers met if (i >= j) return j; swap(arr[i], arr[j]); }} // Generates Random Pivot, swaps pivot with// end element and calls the partition function// In Hoare partition the low element is selected// as first pivotint partition_r(int arr[], int low, int high){ // Generate a random number in between // low .. high srand(time(NULL)); int random = low + rand() % (high - low); // Swap A[random] with A[high] swap(arr[random], arr[low]); return partition(arr, low, high);} // The main function that implements QuickSort// arr[] --> Array to be sorted,// low --> Starting index,// high --> Ending indexvoid quickSort(int arr[], int low, int high){ if (low < high) { // pi is partitioning index, // arr[p] is now at right place int pi = partition_r(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi); quickSort(arr, pi + 1, high); }} // Function to print an arrayvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver Codeint main(){ int arr[] = { 10, 7, 8, 9, 1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); quickSort(arr, 0, n - 1); printf(\"Sorted array: \\n\"); printArray(arr, n); return 0;}",
"e": 14920,
"s": 12804,
"text": null
},
{
"code": "/*JAVA implementation of Randomize QuickSortusing Hoare's Partition*/import java.util.*; class GFG{ // swap function static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } /* // partition function This function takes array, low and high index, swaps low with random index between low and high then places all elements less than pivot in the left of pivot and all elements greater than pivot to the right of pivot */ static int partition(int[] arr, int low, int high) { // rIndex gives the random index between low and // high (both inclusive) int rIndex = (low) + (int)(Math.random() * (high - low + 1)); swap(arr, low, rIndex); // swap low with random index int pivot = arr[low]; int i = low - 1, j = high + 1; while (true) { // increase i while elements are less than pivot do { i++; } while (arr[i] < pivot); // decrease j while elements are greater than pivot do { j--; } while (arr[j] > pivot); if (i >= j) // when both pointers meet // that means elements are at their // correct place for now return j; swap(arr, i, j); // swap i and j, since both are not at their // correct index } } // recursive quick sort function static void quickSort(int[] arr, int low, int high) { if (low < high) { // find partition index int p = partition(arr, low, high); // sort before and after the pivot quickSort(arr, low, p); quickSort(arr, p + 1, high); } } // Driver code public static void main(String[] args) { int[] arr = { 10, 7, 8, 9, 1, 5 }; quickSort(arr, 0, arr.length - 1); System.out.println(\"Sorted array : \"); System.out.print(Arrays.toString(arr)); }} // This code is contributed by Anubhav Singh (singhanubhav)",
"e": 17047,
"s": 14920,
"text": null
},
{
"code": "# Python implementation QuickSort using # Hoare's partition Scheme. import random '''The function which implements randomisedQuickSort, using Haore's partition scheme.arr :- array to be sorted.start :- starting index of the array.stop :- ending index of the array.'''def quicksort(arr, start, stop): if(start < stop): # pivotindex is the index where # the pivot lies in the array pivotindex = partitionrand(arr,\\ start, stop) # At this stage the array is # partially sorted around the pivot. # separately sorting the left half of # the array and the right # half of the array. quicksort(arr , start , pivotindex) quicksort(arr, pivotindex + 1, stop) # This function generates random pivot,# swaps the first element with the pivot# and calls the partition function.def partitionrand(arr , start, stop): # Generating a random number between # the starting index of the array and # the ending index of the array. randpivot = random.randrange(start, stop) # Swapping the starting element of # the array and the pivot arr[start], arr[randpivot] =\\ arr[randpivot], arr[start] return partition(arr, start, stop) '''This function takes the first elementas pivot, places the pivot element atthe correct position in the sorted array.All the elements are re-arranged accordingto the pivot, the elements smaller than the pivot is places on the left and the elements greater than the pivot isplaced to the right of pivot.'''def partition(arr,start,stop): pivot = start # pivot i = start - 1 j = stop + 1 while True: while True: i = i + 1 if arr[i] >= arr[pivot]: break while True: j = j - 1 if arr[j] <= arr[pivot]: break if i >= j: return j arr[i] , arr[j] = arr[j] , arr[i] # Driver Codeif __name__ == \"__main__\": array = [10, 7, 8, 9, 1, 5] quicksort(array, 0, len(array) - 1) print(array) # This code is contributed by soumyasaurav",
"e": 19173,
"s": 17047,
"text": null
},
{
"code": null,
"e": 19202,
"s": 19173,
"text": "Sorted array: \n1 5 7 8 9 10 "
},
{
"code": null,
"e": 19236,
"s": 19202,
"text": "Analysis of Randomized Quick Sort"
},
{
"code": null,
"e": 19243,
"s": 19236,
"text": "Notes "
},
{
"code": null,
"e": 19378,
"s": 19243,
"text": "Using random pivoting we improve the expected or average time complexity to O (N log N). The Worst-Case complexity is still O ( N^2 )."
},
{
"code": null,
"e": 19384,
"s": 19378,
"text": "ritz7"
},
{
"code": null,
"e": 19397,
"s": 19384,
"text": "soumyasaurav"
},
{
"code": null,
"e": 19411,
"s": 19397,
"text": "shubham_singh"
},
{
"code": null,
"e": 19424,
"s": 19411,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 19439,
"s": 19424,
"text": "sudhanshublaze"
},
{
"code": null,
"e": 19454,
"s": 19439,
"text": "siddhantmodi18"
},
{
"code": null,
"e": 19469,
"s": 19454,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 19480,
"s": 19469,
"text": "subhajit07"
},
{
"code": null,
"e": 19489,
"s": 19480,
"text": "sooda367"
},
{
"code": null,
"e": 19502,
"s": 19489,
"text": "simmytarika5"
},
{
"code": null,
"e": 19513,
"s": 19502,
"text": "hdmehta406"
},
{
"code": null,
"e": 19521,
"s": 19513,
"text": "meetgor"
},
{
"code": null,
"e": 19534,
"s": 19521,
"text": "singhanubhav"
},
{
"code": null,
"e": 19545,
"s": 19534,
"text": "Randomized"
},
{
"code": null,
"e": 19553,
"s": 19545,
"text": "Sorting"
},
{
"code": null,
"e": 19561,
"s": 19553,
"text": "Sorting"
}
] |
JavaScript(ES6) | Object Literal Enhancement
|
10 May, 2020
Object literal enhancement is used to group variables from the global scope and form them into javascript objects. It is the process of restructuring or putting back together.
Example 1:
<script>// variable declarationvar name = "Duke";var color = "Brown";var age = 5; // Using Object Literal Enhancement// Combines all variables into a dog objectvar dog = {name, color, age};console.log(dog);</script>
Output : The name, color and age are now keys of dog object.
{
name:"Duke",
color:"Brown",
age:5
}
Example 2: We can also create object methods with object literal enhancement.
<script>// variable declarationvar name = "Tike";var color = "Black";var age = 7; // function declarationvar bark = function(){ console.log("Woof Woof!!");} // Using Object Literal Enhancement// combines all variables into an anotherDog objectvar anotherDog = {name, color, age, bark};anotherDog.bark();</script>
Output:
Woof Woof!!
Example 3: We can also use “this” keyword to access the object keys.
<script> // Variable declaration var name = "Lilly"; var color = "White"; var age = 3; // function declaration // using "this" keyword to access the object keys. var barkWithName = function(){ console.log('Woof Woof!!, I am ' +this.name+' and I am a ' +this.age+' years old, ' +this.color+ ' coloured dog.Woof Woof!!'); } // Using Object Literal Enhancement // combines all variables into a yetAnotherDog object var yetAnotherDog = {name, color, age, barkWithName}; yetAnotherDog.barkWithName();</script>
Output :
Woof Woof!!, I am lilly and I am a 3 years old,
white coloured dog.Woof Woof!!
Example 4: When defining object methods, it is no longer necessary to use the function keyword. Object literal enhancement allows us to pull global variables into objects and reduces typing by making the function keyword unnecessary.
<script>// Old syntaxvar driver1 = { name: "John", speed: 50, car:"Ferrari", speedUp: function(speedup){ this.speed = this.speed + speedup; console.log("new speed = "+ this.speed) }} // New syntax without function keywordconst driver2 = { name: "Jane", speed: 60, car:"McLaren", speedUp(speedup){ this.speed = this.speed + speedup; console.log("new speed = "+ this.speed) }}</script>
ES6
JavaScript
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": "\n10 May, 2020"
},
{
"code": null,
"e": 228,
"s": 52,
"text": "Object literal enhancement is used to group variables from the global scope and form them into javascript objects. It is the process of restructuring or putting back together."
},
{
"code": null,
"e": 239,
"s": 228,
"text": "Example 1:"
},
{
"code": "<script>// variable declarationvar name = \"Duke\";var color = \"Brown\";var age = 5; // Using Object Literal Enhancement// Combines all variables into a dog objectvar dog = {name, color, age};console.log(dog);</script>",
"e": 456,
"s": 239,
"text": null
},
{
"code": null,
"e": 517,
"s": 456,
"text": "Output : The name, color and age are now keys of dog object."
},
{
"code": null,
"e": 568,
"s": 517,
"text": "{\n name:\"Duke\",\n color:\"Brown\",\n age:5\n}\n"
},
{
"code": null,
"e": 646,
"s": 568,
"text": "Example 2: We can also create object methods with object literal enhancement."
},
{
"code": "<script>// variable declarationvar name = \"Tike\";var color = \"Black\";var age = 7; // function declarationvar bark = function(){ console.log(\"Woof Woof!!\");} // Using Object Literal Enhancement// combines all variables into an anotherDog objectvar anotherDog = {name, color, age, bark};anotherDog.bark();</script>",
"e": 964,
"s": 646,
"text": null
},
{
"code": null,
"e": 972,
"s": 964,
"text": "Output:"
},
{
"code": null,
"e": 984,
"s": 972,
"text": "Woof Woof!!"
},
{
"code": null,
"e": 1053,
"s": 984,
"text": "Example 3: We can also use “this” keyword to access the object keys."
},
{
"code": "<script> // Variable declaration var name = \"Lilly\"; var color = \"White\"; var age = 3; // function declaration // using \"this\" keyword to access the object keys. var barkWithName = function(){ console.log('Woof Woof!!, I am ' +this.name+' and I am a ' +this.age+' years old, ' +this.color+ ' coloured dog.Woof Woof!!'); } // Using Object Literal Enhancement // combines all variables into a yetAnotherDog object var yetAnotherDog = {name, color, age, barkWithName}; yetAnotherDog.barkWithName();</script> ",
"e": 1647,
"s": 1053,
"text": null
},
{
"code": null,
"e": 1656,
"s": 1647,
"text": "Output :"
},
{
"code": null,
"e": 1735,
"s": 1656,
"text": "Woof Woof!!, I am lilly and I am a 3 years old,\nwhite coloured dog.Woof Woof!!"
},
{
"code": null,
"e": 1969,
"s": 1735,
"text": "Example 4: When defining object methods, it is no longer necessary to use the function keyword. Object literal enhancement allows us to pull global variables into objects and reduces typing by making the function keyword unnecessary."
},
{
"code": "<script>// Old syntaxvar driver1 = { name: \"John\", speed: 50, car:\"Ferrari\", speedUp: function(speedup){ this.speed = this.speed + speedup; console.log(\"new speed = \"+ this.speed) }} // New syntax without function keywordconst driver2 = { name: \"Jane\", speed: 60, car:\"McLaren\", speedUp(speedup){ this.speed = this.speed + speedup; console.log(\"new speed = \"+ this.speed) }}</script>",
"e": 2416,
"s": 1969,
"text": null
},
{
"code": null,
"e": 2420,
"s": 2416,
"text": "ES6"
},
{
"code": null,
"e": 2431,
"s": 2420,
"text": "JavaScript"
},
{
"code": null,
"e": 2448,
"s": 2431,
"text": "Web Technologies"
}
] |
vector::operator= and vector::operator[ ] in C++ STL
|
30 Jun, 2022
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container.
This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new contents.
Syntax :
vectorname1 = (vectorname2)
Parameters :
Another container of the same type.
Result :
Assign the contents of the container passed as
parameter to the container written on left side of the operator.
Examples:
Input : myvector1 = 1, 2, 3
myvector2 = 3, 2, 1, 4
myvector1 = myvector2;
Output : myvector1 = 3, 2, 1, 4
Input : myvector1 = 2, 6, 1, 5
myvector2 = 3, 2
myvectoe1 = myvector2;
Output : myvector1 = 3, 2
Errors and Exceptions1. If the containers are of different types, an error is thrown. 2. It has a basic no exception throw guarantee otherwise.
Time Complexity – Linear O(N)
C++
// CPP program to illustrate// Implementation of = operator#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector1{ 1, 2, 3 }; vector<int> myvector2{ 3, 2, 1, 4 }; myvector1 = myvector2; cout << "myvector1 = "; for (auto it = myvector1.begin(); it != myvector1.end(); ++it) cout << ' ' << *it; return 0;}
Output:
myvector1= 3 2 1 4
This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of vector, while this operator causes undefined behavior.
Syntax :
vectorname[position]
Parameters :
Position of the element to be fetched.
Returns :
Direct reference to the element at the given position.
Examples:
Input : myvector = 1, 2, 3
myvector[2];
Output : 3
Input : myvector = 3, 4, 1, 7, 3
myvector[3];
Output : 7
Errors and Exceptions1. If the position is not present in the vector, it shows undefined behavior. 2. It has a no exception throw guarantee otherwise.
Time Complexity – Constant O(1)
C++
// CPP program to illustrate// Implementation of [] operator#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(3); myvector.push_back(4); myvector.push_back(1); myvector.push_back(7); myvector.push_back(3); cout << myvector[3]; return 0;}
Output:
7
Application Given a vector of integers, print all the integers present at odd positions.
Input :1, 2, 3, 4, 5, 6, 7, 8, 9
Output :2 4 6 8
Explanation - 2, 4, 6, and 8 are at position 1, 3, 5 and 7 which are odd
Algorithm 1. Run a loop till the size of the vector. 2. Check if the position is not divisible by 2, then print the element at that position.
C++
// CPP program to illustrate// Application of [] operator#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(1); myvector.push_back(2); myvector.push_back(3); myvector.push_back(4); myvector.push_back(5); myvector.push_back(6); myvector.push_back(7); myvector.push_back(8); myvector.push_back(9); // Vector becomes 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < myvector.size(); ++i) { if (i % 2 != 0) { cout << myvector[i]; cout << " "; } } return 0;}
Output:
2 4 6 8
Let us see the differences in a tabular form -:
Its syntax is -:
vector& operator= (const vector& x);
Its syntax is -:
vector& operator= (const vector& x);
It takes two parameters -:
1. A vector object of the same type
2. An initializer_list object.
It takes two parameters that are -:
1. A vector object of the same type
2. An initializer_list object.
chhabradhanvi
utkarshgupta110092
mayank007rawa
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 242,
"s": 53,
"text": "Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. "
},
{
"code": null,
"e": 397,
"s": 242,
"text": "This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new contents."
},
{
"code": null,
"e": 407,
"s": 397,
"text": "Syntax : "
},
{
"code": null,
"e": 606,
"s": 407,
"text": "vectorname1 = (vectorname2)\nParameters :\nAnother container of the same type.\nResult :\nAssign the contents of the container passed as \nparameter to the container written on left side of the operator."
},
{
"code": null,
"e": 618,
"s": 606,
"text": "Examples: "
},
{
"code": null,
"e": 868,
"s": 618,
"text": "Input : myvector1 = 1, 2, 3\n myvector2 = 3, 2, 1, 4\n myvector1 = myvector2;\nOutput : myvector1 = 3, 2, 1, 4\n\nInput : myvector1 = 2, 6, 1, 5\n myvector2 = 3, 2\n myvectoe1 = myvector2;\nOutput : myvector1 = 3, 2"
},
{
"code": null,
"e": 1012,
"s": 868,
"text": "Errors and Exceptions1. If the containers are of different types, an error is thrown. 2. It has a basic no exception throw guarantee otherwise."
},
{
"code": null,
"e": 1042,
"s": 1012,
"text": "Time Complexity – Linear O(N)"
},
{
"code": null,
"e": 1046,
"s": 1042,
"text": "C++"
},
{
"code": "// CPP program to illustrate// Implementation of = operator#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector1{ 1, 2, 3 }; vector<int> myvector2{ 3, 2, 1, 4 }; myvector1 = myvector2; cout << \"myvector1 = \"; for (auto it = myvector1.begin(); it != myvector1.end(); ++it) cout << ' ' << *it; return 0;}",
"e": 1411,
"s": 1046,
"text": null
},
{
"code": null,
"e": 1420,
"s": 1411,
"text": "Output: "
},
{
"code": null,
"e": 1439,
"s": 1420,
"text": "myvector1= 3 2 1 4"
},
{
"code": null,
"e": 1757,
"s": 1439,
"text": "This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of vector, while this operator causes undefined behavior."
},
{
"code": null,
"e": 1768,
"s": 1757,
"text": "Syntax : "
},
{
"code": null,
"e": 1906,
"s": 1768,
"text": "vectorname[position]\nParameters :\nPosition of the element to be fetched.\nReturns :\nDirect reference to the element at the given position."
},
{
"code": null,
"e": 1917,
"s": 1906,
"text": "Examples: "
},
{
"code": null,
"e": 2052,
"s": 1917,
"text": "Input : myvector = 1, 2, 3\n myvector[2];\nOutput : 3\n\nInput : myvector = 3, 4, 1, 7, 3\n myvector[3];\nOutput : 7"
},
{
"code": null,
"e": 2204,
"s": 2052,
"text": "Errors and Exceptions1. If the position is not present in the vector, it shows undefined behavior. 2. It has a no exception throw guarantee otherwise. "
},
{
"code": null,
"e": 2236,
"s": 2204,
"text": "Time Complexity – Constant O(1)"
},
{
"code": null,
"e": 2240,
"s": 2236,
"text": "C++"
},
{
"code": "// CPP program to illustrate// Implementation of [] operator#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(3); myvector.push_back(4); myvector.push_back(1); myvector.push_back(7); myvector.push_back(3); cout << myvector[3]; return 0;}",
"e": 2562,
"s": 2240,
"text": null
},
{
"code": null,
"e": 2571,
"s": 2562,
"text": "Output: "
},
{
"code": null,
"e": 2573,
"s": 2571,
"text": "7"
},
{
"code": null,
"e": 2663,
"s": 2573,
"text": "Application Given a vector of integers, print all the integers present at odd positions. "
},
{
"code": null,
"e": 2786,
"s": 2663,
"text": "Input :1, 2, 3, 4, 5, 6, 7, 8, 9\nOutput :2 4 6 8\nExplanation - 2, 4, 6, and 8 are at position 1, 3, 5 and 7 which are odd"
},
{
"code": null,
"e": 2928,
"s": 2786,
"text": "Algorithm 1. Run a loop till the size of the vector. 2. Check if the position is not divisible by 2, then print the element at that position."
},
{
"code": null,
"e": 2932,
"s": 2928,
"text": "C++"
},
{
"code": "// CPP program to illustrate// Application of [] operator#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(1); myvector.push_back(2); myvector.push_back(3); myvector.push_back(4); myvector.push_back(5); myvector.push_back(6); myvector.push_back(7); myvector.push_back(8); myvector.push_back(9); // Vector becomes 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < myvector.size(); ++i) { if (i % 2 != 0) { cout << myvector[i]; cout << \" \"; } } return 0;}",
"e": 3521,
"s": 2932,
"text": null
},
{
"code": null,
"e": 3530,
"s": 3521,
"text": "Output: "
},
{
"code": null,
"e": 3538,
"s": 3530,
"text": "2 4 6 8"
},
{
"code": null,
"e": 3587,
"s": 3538,
"text": " Let us see the differences in a tabular form -:"
},
{
"code": null,
"e": 3604,
"s": 3587,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3641,
"s": 3604,
"text": "vector& operator= (const vector& x);"
},
{
"code": null,
"e": 3658,
"s": 3641,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3695,
"s": 3658,
"text": "vector& operator= (const vector& x);"
},
{
"code": null,
"e": 3722,
"s": 3695,
"text": "It takes two parameters -:"
},
{
"code": null,
"e": 3758,
"s": 3722,
"text": "1. A vector object of the same type"
},
{
"code": null,
"e": 3789,
"s": 3758,
"text": "2. An initializer_list object."
},
{
"code": null,
"e": 3825,
"s": 3789,
"text": "It takes two parameters that are -:"
},
{
"code": null,
"e": 3861,
"s": 3825,
"text": "1. A vector object of the same type"
},
{
"code": null,
"e": 3892,
"s": 3861,
"text": "2. An initializer_list object."
},
{
"code": null,
"e": 3906,
"s": 3892,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 3925,
"s": 3906,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 3939,
"s": 3925,
"text": "mayank007rawa"
},
{
"code": null,
"e": 3950,
"s": 3939,
"text": "cpp-vector"
},
{
"code": null,
"e": 3954,
"s": 3950,
"text": "STL"
},
{
"code": null,
"e": 3958,
"s": 3954,
"text": "C++"
},
{
"code": null,
"e": 3962,
"s": 3958,
"text": "STL"
},
{
"code": null,
"e": 3966,
"s": 3962,
"text": "CPP"
}
] |
How to Find the Minimum and Maximum Value from Java HashSet?
|
28 Dec, 2020
HashSet is used to store distinct values in Java. The HashSet does not guarantee the constant order of elements over time, which means when we iterate a HashSet, there is no guarantee that we get the same order of elements as we added in order. HashSet does not provide any built-in method to get the maximum and minimum values.
There are a couple of ways to find the maximum and minimum from the HashSet in Java:
Using Collection classUsing simple iteration
Using Collection class
Using simple iteration
Method 1: Using Collections class
Using Collections class in Java we can find maximum and minimum value with the help of max() and min() method of Collections class.
Code:
Java
// Java code to find the maximum and minimum in HashSet import java.util.*; public class GFG { public static void main(String[] args) { // New HashSet HashSet<Integer> set = new HashSet<>(); // Add data to Hashset set.add(10); set.add(20); set.add(20); set.add(10); set.add(50); set.add(40); // Print Maximum value using max method of // Collections class System.out.println("Maximum value of HashSet : " + Collections.max(set)); // Print Maximum value using max method of // Collections class System.out.println("Minimum value of HashSet : " + Collections.min(set)); }}
Maximum value of HashSet : 50
Minimum value of HashSet : 10
Method 2: Using Simple Iteration
We can find Maximum and Minimum using simply iterate the HashSet and maintain the min and max variable and update it accordingly while traversing through each element and comparing it with the min and max values.
Code:
Java
// Java code to find the maximum and minimum in HashSet import java.util.*; public class GFG { public static void main(String[] args) { // New HashSet HashSet<Integer> set = new HashSet<>(); // Add data to Hashset set.add(10); set.add(20); set.add(20); set.add(10); set.add(50); set.add(40); int max = -1, min = -1; // Iterate HashSet to get Maximum value for (int val : set) { if (max == -1) { max = val; } else if (val > max) { max = val; } } // Iterate HashSet to get Minimum value for (int val : set) { if (min == -1) { min = val; } else if (val < min) { min = val; } } // Print Maximum value using max method of // Collections class System.out.println("Maximum value of HashSet : " + max); // Print Maximum value using max method of // Collections class System.out.println("Minimum value of HashSet : " + min); }}
Maximum value of HashSet : 50
Minimum value of HashSet : 10
java-hashset
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 383,
"s": 54,
"text": "HashSet is used to store distinct values in Java. The HashSet does not guarantee the constant order of elements over time, which means when we iterate a HashSet, there is no guarantee that we get the same order of elements as we added in order. HashSet does not provide any built-in method to get the maximum and minimum values."
},
{
"code": null,
"e": 468,
"s": 383,
"text": "There are a couple of ways to find the maximum and minimum from the HashSet in Java:"
},
{
"code": null,
"e": 513,
"s": 468,
"text": "Using Collection classUsing simple iteration"
},
{
"code": null,
"e": 536,
"s": 513,
"text": "Using Collection class"
},
{
"code": null,
"e": 559,
"s": 536,
"text": "Using simple iteration"
},
{
"code": null,
"e": 594,
"s": 559,
"text": "Method 1: Using Collections class "
},
{
"code": null,
"e": 727,
"s": 594,
"text": "Using Collections class in Java we can find maximum and minimum value with the help of max() and min() method of Collections class. "
},
{
"code": null,
"e": 733,
"s": 727,
"text": "Code:"
},
{
"code": null,
"e": 738,
"s": 733,
"text": "Java"
},
{
"code": "// Java code to find the maximum and minimum in HashSet import java.util.*; public class GFG { public static void main(String[] args) { // New HashSet HashSet<Integer> set = new HashSet<>(); // Add data to Hashset set.add(10); set.add(20); set.add(20); set.add(10); set.add(50); set.add(40); // Print Maximum value using max method of // Collections class System.out.println(\"Maximum value of HashSet : \" + Collections.max(set)); // Print Maximum value using max method of // Collections class System.out.println(\"Minimum value of HashSet : \" + Collections.min(set)); }}",
"e": 1485,
"s": 738,
"text": null
},
{
"code": null,
"e": 1545,
"s": 1485,
"text": "Maximum value of HashSet : 50\nMinimum value of HashSet : 10"
},
{
"code": null,
"e": 1578,
"s": 1545,
"text": "Method 2: Using Simple Iteration"
},
{
"code": null,
"e": 1792,
"s": 1578,
"text": "We can find Maximum and Minimum using simply iterate the HashSet and maintain the min and max variable and update it accordingly while traversing through each element and comparing it with the min and max values. "
},
{
"code": null,
"e": 1798,
"s": 1792,
"text": "Code:"
},
{
"code": null,
"e": 1803,
"s": 1798,
"text": "Java"
},
{
"code": "// Java code to find the maximum and minimum in HashSet import java.util.*; public class GFG { public static void main(String[] args) { // New HashSet HashSet<Integer> set = new HashSet<>(); // Add data to Hashset set.add(10); set.add(20); set.add(20); set.add(10); set.add(50); set.add(40); int max = -1, min = -1; // Iterate HashSet to get Maximum value for (int val : set) { if (max == -1) { max = val; } else if (val > max) { max = val; } } // Iterate HashSet to get Minimum value for (int val : set) { if (min == -1) { min = val; } else if (val < min) { min = val; } } // Print Maximum value using max method of // Collections class System.out.println(\"Maximum value of HashSet : \" + max); // Print Maximum value using max method of // Collections class System.out.println(\"Minimum value of HashSet : \" + min); }}",
"e": 3001,
"s": 1803,
"text": null
},
{
"code": null,
"e": 3061,
"s": 3001,
"text": "Maximum value of HashSet : 50\nMinimum value of HashSet : 10"
},
{
"code": null,
"e": 3074,
"s": 3061,
"text": "java-hashset"
},
{
"code": null,
"e": 3081,
"s": 3074,
"text": "Picked"
},
{
"code": null,
"e": 3086,
"s": 3081,
"text": "Java"
},
{
"code": null,
"e": 3100,
"s": 3086,
"text": "Java Programs"
},
{
"code": null,
"e": 3105,
"s": 3100,
"text": "Java"
}
] |
How to build a DAG Factory on Airflow | by Axel Furlan | Towards Data Science
|
Let’s look at a pretty simple DAG with 2 tasks...
Isn’t it weird the amount of boilerplate code necessary in order to execute 2 simple python scripts on Airflow? No matter how many DAGs you write, most certainly you will find yourself writing almost all the same variables with the slightest of changes in a lot of different DAGs.
Remember that, in coding, it’s generally better to write a piece of code that you can later call, instead of writing the same piece of code every time you need that procedure. This is called being DRY.
If many of your DAGs share similar values, e.g the email address, the start date, the schedule interval, the number of retries, and so-on, it’s probably better to have a piece of code that fulfills those values for you. This is what we try to achieve with a Factory class.
Using a DAG Factory on Airflow, we can reduce the number of lines necessary to create a DAG by half.
Here, we want a simple DAG that prints today’s date and then prints “hi”.
This is how it looks on Airflow:
Notice how much we reduced clutter. We haven’t specified what operator we use, what are the tasks’ ids, the schedule interval, who created the DAG nor when was it created.
We can also see that we specified tasks and dependencies using a dictionary and that ultimately translates into the correct tasks dependencies 😄
Let’s look at a slightly more complex example:
In this DAG, I specified 2 arguments that I wanted to override from the defaults. Those are the DAG’s owner and its number of retries. I also specified in the get_airflow_dag() method that I wanted for the schedule to be daily.
This DAG has 3 tasks. Both say_bye() and print_date() depend on say_hi(). Let’s see how this looks like on Airflow.
Now, let’s look at how we can build the DAG Factory 😃
To be honest, it is pretty simple. We first create a class that will have all methods that we need to run in order to create a DAG with its tasks.
Below is the full code for the DAG Factory.
The main method that we’re going to call in order to get a fully usable DAG is get_airflow_dag().
This method will receive 2 mandatory parameters: the DAG’s name and the tasks that it should run. The rest of the parameters are optional since we can set a default in the function’s implementation. When implementing, feel free to make any of those optional parameters mandatory, depending on your use case, it may be useful to make the cron (schedule_interval) a mandatory parameter or even the DAG’s owner, for instance.
The default_args parameter is going to be a dictionary that will hold any keys and values that you may want to override. If not specified, the default default_args are going to be used.
In our case, the defaults are:
DEFAULT_ARGS = {'owner': 'Data Engineer','depends_on_past': False,'start_date': datetime(2021, 1, 1),'email': ['data_engineers@company.com'],'email_on_failure': True,'email_on_retry': False,'retries': 1,'retry_delay': timedelta(minutes=5),}
The other 3 parameters are the main ones used to describe a DAG. There are more options so feel free to specify more.
get_airflow_dag() will run create_dag() in order to create the DAG object and return it. add_tasks_to_dag() is a little bit more complicated since we want to make it easy for the user to specify a way to create dependencies on tasks without having to write the Operators.
In our case, we always use the PythonOperator for our tasks, so it made sense for us to assume that as the norm.
The implementation aims to facilitate the data engineer’s job, so we avoid setting extra things like the task’s name, we just assume it’s the same as the function’s name — so we use a little bit of reflection to figure it out.
for func in tasks: task_id = func.__name__ task = PythonOperator( task_id=task_id, python_callable=func, dag=dag ) aux_dict[task_id] = taskfor func, dependencies in tasks.items(): task_id = func.__name__ for dep in dependencies: aux_dict[dep.__name__] >> aux_dict[task_id]
The function first creates an auxiliary dictionary to hold a key value pair of task name: task object. This is done to only have one set of tasks objects and to use that later to set dependencies. Then for each key in the tasks dictionary provided originally, the dependencies get set making use of the auxiliary dictionary.
After this is done, the DAG object is ready to be returned and used by the team 🎉.
There’s a little trick in the file in order for Airflow to recognize it’s a proper DAG that we’re returning.
When Airflow starts, the so-called DagBag process will parse all the files looking for DAGs. The way the current implementation works is something like this:
The DagBag spawns different processes that look through the files of the dag folder.
The function called process_file here runs for each file to figure out if there’s a DAG there.
The code runs might_contain_dag which returns a True depending if the file contains both “dag” and “airflow” in their code. Implementation here.
That’s why the function get_airflow_dag is called like that, in order to have both keywords in the file that will result in the file being correctly parsed.
This was a hard thing to find, I spent many hours trying to figure out why my DAG factory was not working. There’s not much documentation about what to take into account in order to create DAGs in a non-traditional way, so this is one of the big gotchas that you will have to take into account when doing something like this.
This simple article aimed to explain how to make a Data Engineer’s life easier by utilizing the Factory pattern on Airflow.
Hope you liked it! Feel free to click on my profile to see other useful Airflow and Data Engineering articles! 😄
|
[
{
"code": null,
"e": 222,
"s": 172,
"text": "Let’s look at a pretty simple DAG with 2 tasks..."
},
{
"code": null,
"e": 503,
"s": 222,
"text": "Isn’t it weird the amount of boilerplate code necessary in order to execute 2 simple python scripts on Airflow? No matter how many DAGs you write, most certainly you will find yourself writing almost all the same variables with the slightest of changes in a lot of different DAGs."
},
{
"code": null,
"e": 705,
"s": 503,
"text": "Remember that, in coding, it’s generally better to write a piece of code that you can later call, instead of writing the same piece of code every time you need that procedure. This is called being DRY."
},
{
"code": null,
"e": 978,
"s": 705,
"text": "If many of your DAGs share similar values, e.g the email address, the start date, the schedule interval, the number of retries, and so-on, it’s probably better to have a piece of code that fulfills those values for you. This is what we try to achieve with a Factory class."
},
{
"code": null,
"e": 1079,
"s": 978,
"text": "Using a DAG Factory on Airflow, we can reduce the number of lines necessary to create a DAG by half."
},
{
"code": null,
"e": 1153,
"s": 1079,
"text": "Here, we want a simple DAG that prints today’s date and then prints “hi”."
},
{
"code": null,
"e": 1186,
"s": 1153,
"text": "This is how it looks on Airflow:"
},
{
"code": null,
"e": 1358,
"s": 1186,
"text": "Notice how much we reduced clutter. We haven’t specified what operator we use, what are the tasks’ ids, the schedule interval, who created the DAG nor when was it created."
},
{
"code": null,
"e": 1503,
"s": 1358,
"text": "We can also see that we specified tasks and dependencies using a dictionary and that ultimately translates into the correct tasks dependencies 😄"
},
{
"code": null,
"e": 1550,
"s": 1503,
"text": "Let’s look at a slightly more complex example:"
},
{
"code": null,
"e": 1778,
"s": 1550,
"text": "In this DAG, I specified 2 arguments that I wanted to override from the defaults. Those are the DAG’s owner and its number of retries. I also specified in the get_airflow_dag() method that I wanted for the schedule to be daily."
},
{
"code": null,
"e": 1894,
"s": 1778,
"text": "This DAG has 3 tasks. Both say_bye() and print_date() depend on say_hi(). Let’s see how this looks like on Airflow."
},
{
"code": null,
"e": 1948,
"s": 1894,
"text": "Now, let’s look at how we can build the DAG Factory 😃"
},
{
"code": null,
"e": 2095,
"s": 1948,
"text": "To be honest, it is pretty simple. We first create a class that will have all methods that we need to run in order to create a DAG with its tasks."
},
{
"code": null,
"e": 2139,
"s": 2095,
"text": "Below is the full code for the DAG Factory."
},
{
"code": null,
"e": 2237,
"s": 2139,
"text": "The main method that we’re going to call in order to get a fully usable DAG is get_airflow_dag()."
},
{
"code": null,
"e": 2660,
"s": 2237,
"text": "This method will receive 2 mandatory parameters: the DAG’s name and the tasks that it should run. The rest of the parameters are optional since we can set a default in the function’s implementation. When implementing, feel free to make any of those optional parameters mandatory, depending on your use case, it may be useful to make the cron (schedule_interval) a mandatory parameter or even the DAG’s owner, for instance."
},
{
"code": null,
"e": 2846,
"s": 2660,
"text": "The default_args parameter is going to be a dictionary that will hold any keys and values that you may want to override. If not specified, the default default_args are going to be used."
},
{
"code": null,
"e": 2877,
"s": 2846,
"text": "In our case, the defaults are:"
},
{
"code": null,
"e": 3118,
"s": 2877,
"text": "DEFAULT_ARGS = {'owner': 'Data Engineer','depends_on_past': False,'start_date': datetime(2021, 1, 1),'email': ['data_engineers@company.com'],'email_on_failure': True,'email_on_retry': False,'retries': 1,'retry_delay': timedelta(minutes=5),}"
},
{
"code": null,
"e": 3236,
"s": 3118,
"text": "The other 3 parameters are the main ones used to describe a DAG. There are more options so feel free to specify more."
},
{
"code": null,
"e": 3508,
"s": 3236,
"text": "get_airflow_dag() will run create_dag() in order to create the DAG object and return it. add_tasks_to_dag() is a little bit more complicated since we want to make it easy for the user to specify a way to create dependencies on tasks without having to write the Operators."
},
{
"code": null,
"e": 3621,
"s": 3508,
"text": "In our case, we always use the PythonOperator for our tasks, so it made sense for us to assume that as the norm."
},
{
"code": null,
"e": 3848,
"s": 3621,
"text": "The implementation aims to facilitate the data engineer’s job, so we avoid setting extra things like the task’s name, we just assume it’s the same as the function’s name — so we use a little bit of reflection to figure it out."
},
{
"code": null,
"e": 4167,
"s": 3848,
"text": "for func in tasks: task_id = func.__name__ task = PythonOperator( task_id=task_id, python_callable=func, dag=dag ) aux_dict[task_id] = taskfor func, dependencies in tasks.items(): task_id = func.__name__ for dep in dependencies: aux_dict[dep.__name__] >> aux_dict[task_id]"
},
{
"code": null,
"e": 4492,
"s": 4167,
"text": "The function first creates an auxiliary dictionary to hold a key value pair of task name: task object. This is done to only have one set of tasks objects and to use that later to set dependencies. Then for each key in the tasks dictionary provided originally, the dependencies get set making use of the auxiliary dictionary."
},
{
"code": null,
"e": 4575,
"s": 4492,
"text": "After this is done, the DAG object is ready to be returned and used by the team 🎉."
},
{
"code": null,
"e": 4684,
"s": 4575,
"text": "There’s a little trick in the file in order for Airflow to recognize it’s a proper DAG that we’re returning."
},
{
"code": null,
"e": 4842,
"s": 4684,
"text": "When Airflow starts, the so-called DagBag process will parse all the files looking for DAGs. The way the current implementation works is something like this:"
},
{
"code": null,
"e": 4927,
"s": 4842,
"text": "The DagBag spawns different processes that look through the files of the dag folder."
},
{
"code": null,
"e": 5022,
"s": 4927,
"text": "The function called process_file here runs for each file to figure out if there’s a DAG there."
},
{
"code": null,
"e": 5167,
"s": 5022,
"text": "The code runs might_contain_dag which returns a True depending if the file contains both “dag” and “airflow” in their code. Implementation here."
},
{
"code": null,
"e": 5324,
"s": 5167,
"text": "That’s why the function get_airflow_dag is called like that, in order to have both keywords in the file that will result in the file being correctly parsed."
},
{
"code": null,
"e": 5650,
"s": 5324,
"text": "This was a hard thing to find, I spent many hours trying to figure out why my DAG factory was not working. There’s not much documentation about what to take into account in order to create DAGs in a non-traditional way, so this is one of the big gotchas that you will have to take into account when doing something like this."
},
{
"code": null,
"e": 5774,
"s": 5650,
"text": "This simple article aimed to explain how to make a Data Engineer’s life easier by utilizing the Factory pattern on Airflow."
}
] |
GridSearchCV or RandomSearchCV?. Comparing two sklearn hyperparameter... | by Brunna Torino | Towards Data Science
|
Hyperparameter tuning is a powerful tool to enhance your supervised learning models— improving accuracy, precision, and other important metrics by searching the optimal model parameters based on different scoring methods. There are two main options available from sklearn: GridSearchCV and RandomSearchCV. I will go through each one of them quickly and then do a full comparison of the two methods!
Since this is Python-based tutorial, enjoy this amazing close-up of a real Python:
GridSearchCV implements the most obvious way of finding an optimal value for anything — it simply tries all the possible values (that you pass) one at a time and returns which one yielded the best model results, based on the scoring that you want, such as accuracy on the test set.
Using GridSearchCV is also very simple, with a few customizable parameters. Here’s a breakdown of them:
1.estimator: the model you are using. 2.params_grid: the dictionary object that holds the hyperparameters you want to test.3.scoring: evaluation metric 4.cv: number of cross-validation for each set of hyperparameters5.verbose: The higher, the more messages are going to be printed.6.n_jobs: Number of jobs to run in parallel7.pre_dispatch: controls the number of jobs that can be done in parallel (to avoid memory issues)8. iid : assumes data is identically independently distributed. Default is False.9.refit : once best params are found, refit the estimator10. error_score : value to assign to the score if an error happens when fitting the estimator11.return_train_score: include train scores in cv_results_
To implement GridSearchCV when fitting you model is just as simple:
First, you define the possible values of all the parameters, using np.linspace for example or just a list of valuesThen you build a “grid” with all the parameter names (as in documentation) and their possible values that you would like to test.Then, you instantiate the GridSearchCV method and fit it to your data (X_train and y_train). Here, I am using the rf_grid as the parameters to be tested, using an accuracy score, and 5-fold cross-validation
First, you define the possible values of all the parameters, using np.linspace for example or just a list of values
Then you build a “grid” with all the parameter names (as in documentation) and their possible values that you would like to test.
Then, you instantiate the GridSearchCV method and fit it to your data (X_train and y_train). Here, I am using the rf_grid as the parameters to be tested, using an accuracy score, and 5-fold cross-validation
n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]max_depth = [int(x) for x in np.linspace(10, 110, num = 11)]max_features = ['auto', 'sqrt']min_samples_split = [2, 5, 10]min_samples_leaf = [1, 2, 4]rf_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf}model = GridSearchCV(RandomForest(), rf_grid, scoring = 'accuracy', cv = 5)# fit the modelmodel.fit(X_train, y_train)
There is a long list of different scoring methods that you can specify for you GridSearchCV, accuracy being the most popular for classification problems.
RandomSearchCV has the same purpose of GridSearchCV: they both were designed to find the best parameters to improve your model. However, here not all parameters are tested. Rather, the search is randomized and all the other parameters are held constant while the parameters we are testing is variable.
Pratically, the implementation of RandomSearchCV is very similar to that of the GridSearchCV:
n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]max_depth = [int(x) for x in np.linspace(10, 110, num = 11)]max_features = ['auto', 'sqrt']min_samples_split = [2, 5, 10]min_samples_leaf = [1, 2, 4]rf_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf}model = RandomizedSearchCV(estimator = RandomForest(), param_distributions = rf_grid, cv = 5, n_iter = 100)# fit the modelmodel.fit(X_train, y_train)
The main difference between the pratical implementation of the two methods is that we can use n_iter to specify how many parameter values we want to sample and test.
There is an obvious trade-off between n_iter and the running time, but (depending on how many possible values you are passing) it is recommended to set n_iter to at least 100 so we can have a higher confidence in the results of the algorithm.
With GridSearchCV, by calling the method best_params_ you are guaranteed to get the best model results (according to your scoring) within your test values, since it will test every single one of the values you passed.
However, with RandomSearchCV, the more samples you test from the value set, the more confident the search will be — but it will never be 100% certain (unless you test every value out of the set of possible values). Statistically speaking, we can be fairly confident that the best parameters found are indeed the best combination of optimal parameters since the search is completely randomized.
The running times of RandomSearchCV vs. GridSearchCV on the other hand, are widely different. Depending on the n_iter chosen, RandomSearchCV can be two, three, four times faster than GridSearchCV. However, the higher the n_iter chosen, the lower will be the speed of RandomSearchCV and the closer the algorithm will be to GridSearchCV.
If you have a small combination of parameters, but with large sets of possible values — along with a model that uses a lot processing time — then RandomSearchCV will save you a lot of time, while still giving you a good estimation of the optimal parameters.
Furthermore, you can use the results of the model to run RandomSearchCV again but now with a smaller set of possible values: or better yet, run GridSearchCV on the small set of possible values after having a rough idea of where the optimal parameter is with RandomSearchCV!
If your model does not take a lot of time to train, or if you already have a rough idea of where the optimal values are (due to inference, or theoretical knowledge), you should definitely use GridSearchCV as it will give you 100% certainty about which parameters you passed that produce the optimal model results.
If you are still not happy with your hyperparameter tuning, make sure to check out the GPOPY algorithm: https://github.com/domus123/gpopy
GPOPY implements the Generic Algorithm, which will generate a few combinations of parameters and at each step choose the best combinations, also called “parents”, and cross-over between them, generating more combinations with the characteristics from both of the parent combinations. Faster than GridSearchCV, but a little bit smarter than RandomSearchCV!
|
[
{
"code": null,
"e": 571,
"s": 172,
"text": "Hyperparameter tuning is a powerful tool to enhance your supervised learning models— improving accuracy, precision, and other important metrics by searching the optimal model parameters based on different scoring methods. There are two main options available from sklearn: GridSearchCV and RandomSearchCV. I will go through each one of them quickly and then do a full comparison of the two methods!"
},
{
"code": null,
"e": 654,
"s": 571,
"text": "Since this is Python-based tutorial, enjoy this amazing close-up of a real Python:"
},
{
"code": null,
"e": 936,
"s": 654,
"text": "GridSearchCV implements the most obvious way of finding an optimal value for anything — it simply tries all the possible values (that you pass) one at a time and returns which one yielded the best model results, based on the scoring that you want, such as accuracy on the test set."
},
{
"code": null,
"e": 1040,
"s": 936,
"text": "Using GridSearchCV is also very simple, with a few customizable parameters. Here’s a breakdown of them:"
},
{
"code": null,
"e": 1751,
"s": 1040,
"text": "1.estimator: the model you are using. 2.params_grid: the dictionary object that holds the hyperparameters you want to test.3.scoring: evaluation metric 4.cv: number of cross-validation for each set of hyperparameters5.verbose: The higher, the more messages are going to be printed.6.n_jobs: Number of jobs to run in parallel7.pre_dispatch: controls the number of jobs that can be done in parallel (to avoid memory issues)8. iid : assumes data is identically independently distributed. Default is False.9.refit : once best params are found, refit the estimator10. error_score : value to assign to the score if an error happens when fitting the estimator11.return_train_score: include train scores in cv_results_"
},
{
"code": null,
"e": 1819,
"s": 1751,
"text": "To implement GridSearchCV when fitting you model is just as simple:"
},
{
"code": null,
"e": 2270,
"s": 1819,
"text": "First, you define the possible values of all the parameters, using np.linspace for example or just a list of valuesThen you build a “grid” with all the parameter names (as in documentation) and their possible values that you would like to test.Then, you instantiate the GridSearchCV method and fit it to your data (X_train and y_train). Here, I am using the rf_grid as the parameters to be tested, using an accuracy score, and 5-fold cross-validation"
},
{
"code": null,
"e": 2386,
"s": 2270,
"text": "First, you define the possible values of all the parameters, using np.linspace for example or just a list of values"
},
{
"code": null,
"e": 2516,
"s": 2386,
"text": "Then you build a “grid” with all the parameter names (as in documentation) and their possible values that you would like to test."
},
{
"code": null,
"e": 2723,
"s": 2516,
"text": "Then, you instantiate the GridSearchCV method and fit it to your data (X_train and y_train). Here, I am using the rf_grid as the parameters to be tested, using an accuracy score, and 5-fold cross-validation"
},
{
"code": null,
"e": 3282,
"s": 2723,
"text": "n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]max_depth = [int(x) for x in np.linspace(10, 110, num = 11)]max_features = ['auto', 'sqrt']min_samples_split = [2, 5, 10]min_samples_leaf = [1, 2, 4]rf_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf}model = GridSearchCV(RandomForest(), rf_grid, scoring = 'accuracy', cv = 5)# fit the modelmodel.fit(X_train, y_train)"
},
{
"code": null,
"e": 3436,
"s": 3282,
"text": "There is a long list of different scoring methods that you can specify for you GridSearchCV, accuracy being the most popular for classification problems."
},
{
"code": null,
"e": 3738,
"s": 3436,
"text": "RandomSearchCV has the same purpose of GridSearchCV: they both were designed to find the best parameters to improve your model. However, here not all parameters are tested. Rather, the search is randomized and all the other parameters are held constant while the parameters we are testing is variable."
},
{
"code": null,
"e": 3832,
"s": 3738,
"text": "Pratically, the implementation of RandomSearchCV is very similar to that of the GridSearchCV:"
},
{
"code": null,
"e": 4461,
"s": 3832,
"text": "n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]max_depth = [int(x) for x in np.linspace(10, 110, num = 11)]max_features = ['auto', 'sqrt']min_samples_split = [2, 5, 10]min_samples_leaf = [1, 2, 4]rf_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf}model = RandomizedSearchCV(estimator = RandomForest(), param_distributions = rf_grid, cv = 5, n_iter = 100)# fit the modelmodel.fit(X_train, y_train)"
},
{
"code": null,
"e": 4627,
"s": 4461,
"text": "The main difference between the pratical implementation of the two methods is that we can use n_iter to specify how many parameter values we want to sample and test."
},
{
"code": null,
"e": 4870,
"s": 4627,
"text": "There is an obvious trade-off between n_iter and the running time, but (depending on how many possible values you are passing) it is recommended to set n_iter to at least 100 so we can have a higher confidence in the results of the algorithm."
},
{
"code": null,
"e": 5088,
"s": 4870,
"text": "With GridSearchCV, by calling the method best_params_ you are guaranteed to get the best model results (according to your scoring) within your test values, since it will test every single one of the values you passed."
},
{
"code": null,
"e": 5482,
"s": 5088,
"text": "However, with RandomSearchCV, the more samples you test from the value set, the more confident the search will be — but it will never be 100% certain (unless you test every value out of the set of possible values). Statistically speaking, we can be fairly confident that the best parameters found are indeed the best combination of optimal parameters since the search is completely randomized."
},
{
"code": null,
"e": 5818,
"s": 5482,
"text": "The running times of RandomSearchCV vs. GridSearchCV on the other hand, are widely different. Depending on the n_iter chosen, RandomSearchCV can be two, three, four times faster than GridSearchCV. However, the higher the n_iter chosen, the lower will be the speed of RandomSearchCV and the closer the algorithm will be to GridSearchCV."
},
{
"code": null,
"e": 6076,
"s": 5818,
"text": "If you have a small combination of parameters, but with large sets of possible values — along with a model that uses a lot processing time — then RandomSearchCV will save you a lot of time, while still giving you a good estimation of the optimal parameters."
},
{
"code": null,
"e": 6350,
"s": 6076,
"text": "Furthermore, you can use the results of the model to run RandomSearchCV again but now with a smaller set of possible values: or better yet, run GridSearchCV on the small set of possible values after having a rough idea of where the optimal parameter is with RandomSearchCV!"
},
{
"code": null,
"e": 6664,
"s": 6350,
"text": "If your model does not take a lot of time to train, or if you already have a rough idea of where the optimal values are (due to inference, or theoretical knowledge), you should definitely use GridSearchCV as it will give you 100% certainty about which parameters you passed that produce the optimal model results."
},
{
"code": null,
"e": 6802,
"s": 6664,
"text": "If you are still not happy with your hyperparameter tuning, make sure to check out the GPOPY algorithm: https://github.com/domus123/gpopy"
}
] |
3 Awesome Python Libraries That You Should Know About | by Ismael Araujo | Towards Data Science
|
A few days ago, I published a blog on 5 Python Libraries That You Don’t Know About, But Should. That blog had dozens of thousands of views in less than a week. Thus, I decided to write a part two with other cool libraries that you should try out.
Python is one of the most popular languages in computation. One of the main reasons is that it contains hundreds of open source libraries that can make our life easier. People focus on more popular (and more reliable) libraries. However, other less-known libraries can save hours of your precious time. That being said, let’s check some cool libraries that, if you don’t know about, you are missing out. Oh, in the end, I will have a bonus recommendation.
LazyPredict is my favorite on today’s list. I have written blogs about it in the past, and I can’t get enough of it. LazyPredict is a low-code machine learning library that allows you to run up to 40 baseline models with two lines of code. It’s because it works surprisingly well.
The coolest part is that it uses Sklearn, which allows you to get the models, see what works best for you, and hypertune it as you would usually do. To install, you can type pip install lazypredict in your Terminal, and you are good to go. The following image will show how to run 30 models at once. For this demonstration, I used the Titanic dataset.
# Importing the packages that we will useimport lazypredictfrom lazypredict.Supervised import LazyClassifier# Running all the modelsclf = LazyClassifier(verbose=0,ignore_warnings=True)models, predictions = clf.fit(X_train, X_test, y_train, y_test)models
At this point, you might be thinking: What just happened? Well, I did a train test split, as I usually would, then I imported LazyPredict, set up the iteration, and checked the models. Running all these models took less than 3 seconds! Finally, LazyPredict returned a DataFrame with some metrics, such as accuracy, ROC AUC, and F1-Score. Here's how the last part looks like.
Too good to be true, right? How can we know that these results are correct? Well, since LazyPredict is using scikit-learn, we can test it out running our models. Let's see what we get.
Bingo! If you compare the results above to what we got with LazyPredict, you will see that the results are very similar. LazyPredict can be very handy if you don’t know which models are the most recommended for your project. However, I don’t recommend using LazyPredict for your final models.
LazyPredict helps, but doesn’t substitute the job of a Data Scientist. If you want to learn more about LazyPredict, you can find my blogs about it here and here. If you are a Spanish speaker, you can find the Spanish version here.
Lux is another library that can save you a lot of time. In short, Lux is a low-code library that allows us to do a fast and easy data exploration by creating data visualizations with one click. The coolest part is that Lux decides what visualizations are recommended for your dataset without you having to decide. You can install it by typing pip install lux-api in your Terminal. Let's check a quick demonstration.
It's that easy. You click and voilá, you have your results. For this dataset, Lux returned visualizations for correlation, distribution, occurrence, and time series. If you want to check specific features, you can do that easily as well. To do so, you can type dataframe.intent(column_1, column_2). I highly recommend you try it out. If you want to read more about Lux, you can find my blog here. It was one of my most popular blogs, and the feedback of those who tried it out was very positive.
Black is a code formatter that makes your code looks way better. This is not a library but a handy extension. For most cases, Python doesn’t care about spaces in the code. HOWEVER, it can be tough to understand what is going on when you type 140 characters together in a line of code. It’s not a best practice, and some people don’t care about it.
The other case scenario is when you get code from other people, and it’s hard to understand what is going on. Black is here to help. To be honest, I don’t use Black because I try to write clean, easy-to-read code. Nevertheless, when I need to review someone’s code, I need to use Black in 90% of the cases.
To install, you can type pip install nb_black, and you should be good to go. To use it, you only have to type once %load_ext nb_black, and every time you run a cell, Black will automatically format your code. Let's explore it with an example that I got from the LazyPredict section. The code doesn't have spaces. However, as soon as I run the cell, Black automatically adds spaces and makes the code look way better.
Were you able to see the difference? Let's take a closer look.
Before running the cell:
After running the cell:
If you can see the difference, you understand the importance of this best practice and will be happy to use this extension with other people’s code. If you don’t see the difference... Well, then you should start using Black right away!
My opinion is that the code looks so much better! It’’ easy to read and understand what is going on. This is a small demonstration. However, for more extended codes, it makes a lot of difference.
While writing this blog, I wanted to check if the libraries were still receiving updates. I usually look individually for each library what was the last version released and if it matches the version I have. Sound like a lot of work. To my surprise, I found a website that solves this problem, and I had to share it.
Snyk Open Source Advisor helps us search about libraries, check their versions, their popularity, remain updated, their README page, and discover similar libraries. It works with PyPI. Thus, you can check PyPI at the same time. All in a nice-looking website.
It seems so good that I had to include it here. Some of my favorite features are the Package Health Score and Maintaince. Why haven’t I found this before?
Analyzing the page for Lux, we can see that it is being updated quickly regularly, and its most popular version is 0.3.0. How cool is that?
Our time is precious, and we should make the best of it. These Python libraries can be convenient for your next projects, and I highly recommend you trying them out. Doing so, you can invest your precious time in other tasks, such as hypertunning your models. None of these libraries should substitute a professional.
They should be seen as a way to improve our work. I don’t recommend you relying only on these libraries, but use them as an add-on. Thanks for reading, and let me know what library is not on this list. I might write about it next time. Happy coding!
You might also like...
5 Python Libraries That You Don’t Know About, But Should4 Cool Python Libraries That You Should Know About3 Low-Code Python Libraries That You Should Know About
|
[
{
"code": null,
"e": 419,
"s": 172,
"text": "A few days ago, I published a blog on 5 Python Libraries That You Don’t Know About, But Should. That blog had dozens of thousands of views in less than a week. Thus, I decided to write a part two with other cool libraries that you should try out."
},
{
"code": null,
"e": 875,
"s": 419,
"text": "Python is one of the most popular languages in computation. One of the main reasons is that it contains hundreds of open source libraries that can make our life easier. People focus on more popular (and more reliable) libraries. However, other less-known libraries can save hours of your precious time. That being said, let’s check some cool libraries that, if you don’t know about, you are missing out. Oh, in the end, I will have a bonus recommendation."
},
{
"code": null,
"e": 1156,
"s": 875,
"text": "LazyPredict is my favorite on today’s list. I have written blogs about it in the past, and I can’t get enough of it. LazyPredict is a low-code machine learning library that allows you to run up to 40 baseline models with two lines of code. It’s because it works surprisingly well."
},
{
"code": null,
"e": 1508,
"s": 1156,
"text": "The coolest part is that it uses Sklearn, which allows you to get the models, see what works best for you, and hypertune it as you would usually do. To install, you can type pip install lazypredict in your Terminal, and you are good to go. The following image will show how to run 30 models at once. For this demonstration, I used the Titanic dataset."
},
{
"code": null,
"e": 1762,
"s": 1508,
"text": "# Importing the packages that we will useimport lazypredictfrom lazypredict.Supervised import LazyClassifier# Running all the modelsclf = LazyClassifier(verbose=0,ignore_warnings=True)models, predictions = clf.fit(X_train, X_test, y_train, y_test)models"
},
{
"code": null,
"e": 2137,
"s": 1762,
"text": "At this point, you might be thinking: What just happened? Well, I did a train test split, as I usually would, then I imported LazyPredict, set up the iteration, and checked the models. Running all these models took less than 3 seconds! Finally, LazyPredict returned a DataFrame with some metrics, such as accuracy, ROC AUC, and F1-Score. Here's how the last part looks like."
},
{
"code": null,
"e": 2322,
"s": 2137,
"text": "Too good to be true, right? How can we know that these results are correct? Well, since LazyPredict is using scikit-learn, we can test it out running our models. Let's see what we get."
},
{
"code": null,
"e": 2615,
"s": 2322,
"text": "Bingo! If you compare the results above to what we got with LazyPredict, you will see that the results are very similar. LazyPredict can be very handy if you don’t know which models are the most recommended for your project. However, I don’t recommend using LazyPredict for your final models."
},
{
"code": null,
"e": 2846,
"s": 2615,
"text": "LazyPredict helps, but doesn’t substitute the job of a Data Scientist. If you want to learn more about LazyPredict, you can find my blogs about it here and here. If you are a Spanish speaker, you can find the Spanish version here."
},
{
"code": null,
"e": 3262,
"s": 2846,
"text": "Lux is another library that can save you a lot of time. In short, Lux is a low-code library that allows us to do a fast and easy data exploration by creating data visualizations with one click. The coolest part is that Lux decides what visualizations are recommended for your dataset without you having to decide. You can install it by typing pip install lux-api in your Terminal. Let's check a quick demonstration."
},
{
"code": null,
"e": 3759,
"s": 3262,
"text": "It's that easy. You click and voilá, you have your results. For this dataset, Lux returned visualizations for correlation, distribution, occurrence, and time series. If you want to check specific features, you can do that easily as well. To do so, you can type dataframe.intent(column_1, column_2). I highly recommend you try it out. If you want to read more about Lux, you can find my blog here. It was one of my most popular blogs, and the feedback of those who tried it out was very positive."
},
{
"code": null,
"e": 4107,
"s": 3759,
"text": "Black is a code formatter that makes your code looks way better. This is not a library but a handy extension. For most cases, Python doesn’t care about spaces in the code. HOWEVER, it can be tough to understand what is going on when you type 140 characters together in a line of code. It’s not a best practice, and some people don’t care about it."
},
{
"code": null,
"e": 4414,
"s": 4107,
"text": "The other case scenario is when you get code from other people, and it’s hard to understand what is going on. Black is here to help. To be honest, I don’t use Black because I try to write clean, easy-to-read code. Nevertheless, when I need to review someone’s code, I need to use Black in 90% of the cases."
},
{
"code": null,
"e": 4831,
"s": 4414,
"text": "To install, you can type pip install nb_black, and you should be good to go. To use it, you only have to type once %load_ext nb_black, and every time you run a cell, Black will automatically format your code. Let's explore it with an example that I got from the LazyPredict section. The code doesn't have spaces. However, as soon as I run the cell, Black automatically adds spaces and makes the code look way better."
},
{
"code": null,
"e": 4894,
"s": 4831,
"text": "Were you able to see the difference? Let's take a closer look."
},
{
"code": null,
"e": 4919,
"s": 4894,
"text": "Before running the cell:"
},
{
"code": null,
"e": 4943,
"s": 4919,
"text": "After running the cell:"
},
{
"code": null,
"e": 5179,
"s": 4943,
"text": "If you can see the difference, you understand the importance of this best practice and will be happy to use this extension with other people’s code. If you don’t see the difference... Well, then you should start using Black right away!"
},
{
"code": null,
"e": 5375,
"s": 5179,
"text": "My opinion is that the code looks so much better! It’’ easy to read and understand what is going on. This is a small demonstration. However, for more extended codes, it makes a lot of difference."
},
{
"code": null,
"e": 5692,
"s": 5375,
"text": "While writing this blog, I wanted to check if the libraries were still receiving updates. I usually look individually for each library what was the last version released and if it matches the version I have. Sound like a lot of work. To my surprise, I found a website that solves this problem, and I had to share it."
},
{
"code": null,
"e": 5951,
"s": 5692,
"text": "Snyk Open Source Advisor helps us search about libraries, check their versions, their popularity, remain updated, their README page, and discover similar libraries. It works with PyPI. Thus, you can check PyPI at the same time. All in a nice-looking website."
},
{
"code": null,
"e": 6106,
"s": 5951,
"text": "It seems so good that I had to include it here. Some of my favorite features are the Package Health Score and Maintaince. Why haven’t I found this before?"
},
{
"code": null,
"e": 6246,
"s": 6106,
"text": "Analyzing the page for Lux, we can see that it is being updated quickly regularly, and its most popular version is 0.3.0. How cool is that?"
},
{
"code": null,
"e": 6564,
"s": 6246,
"text": "Our time is precious, and we should make the best of it. These Python libraries can be convenient for your next projects, and I highly recommend you trying them out. Doing so, you can invest your precious time in other tasks, such as hypertunning your models. None of these libraries should substitute a professional."
},
{
"code": null,
"e": 6814,
"s": 6564,
"text": "They should be seen as a way to improve our work. I don’t recommend you relying only on these libraries, but use them as an add-on. Thanks for reading, and let me know what library is not on this list. I might write about it next time. Happy coding!"
},
{
"code": null,
"e": 6837,
"s": 6814,
"text": "You might also like..."
}
] |
C++ Program for Optimal Page Replacement Algorithm
|
Given page number and page size; the task is to find number of hits and misses as when we allocate the memory block to a page using Optimal Page Replacement Algorithm.
What is Optimal Page Replacement Algorithm?
Optimal page replacement algorithm is a page replacement algorithm. A page replacement algorithm is an algorithm which decides which memory page is to be replaced. In Optimal page replacement we replace the page which is not referred to the near future, although it can’t be practically implemented, but this is most optimal and have minimal miss, and is most optimal.
Let’s understand by using an example and explaining it diagrammatically.
Here after allocating 1, 2 and 3 now the memory is full, so for inserting 4 we will look for the page which is not again referred in near future from 1, 2 and 3 so page 3 is not in near future so we replace that page with new page 4, and so on we will repeat the steps till we reach the end.
Input: page[] = { 1, 7, 8, 3, 0, 2, 0, 3, 5, 4, 0, 6, 1 }
fn=3
Output: Hits = 3
Misses = 10
Input: page[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 }
fn = 4
Output: Hits = 7
Misses= 6
Approach we are using to solve the above problem −
Take the input of pages as an array.
Look for the page allocated is present in near future, if no then replace that page in the memory with new page,
If page already present increment hit, else increment miss.
Repeat till we reach the last element of the array.
Print the number of hits and misses.
Start
Step 1-> In function int predict(int page[], vector<int>& fr, int pn, int index)
Declare and initialize res = -1, farthest = index
Loop For i = 0 and i < fr.size() and i++
Loop For j = index and j < pn and j++
If fr[i] == page[j] then,
If j > farthest
Set farthest = j
End If
Set res = i
break
If j == pn then,
Return i
Return (res == -1) ? 0 : res
Step 2-> In function bool search(int key, vector<int>& fr)
Loop For i = 0 and i < fr.size() and i++
If fr[i] == key then,
Return true
Return false
Step 3-> In function void opr(int page[], int pn, int fn)
Declare vector<int> fr
Set hit = 0
Loop For i = 0 and i < pn and i++
If search(page[i], fr) then,
Increment hit by 1
continue
If fr.size() < fn then,
fr.push_back(page[i])
Else
Set j = predict(page, fr, pn, i + 1)
Set fr[j] = page[i]
Print the number of hits
Print the number of misses
Step 4-> In function int main()
Declare and assign page[] = { 1, 7, 8, 3, 0, 2, 0, 3, 5, 4, 0, 6, 1 }
Set pn = sizeof(page) / sizeof(page[0])
Set fn = 3
opr(page, pn, fn)
Stop
Live Demo
#include <bits/stdc++.h>
using namespace std;
int predict(int page[], vector<int>& fr, int pn, int index) {
// Store the index of pages which are going
// to be used recently in future
int res = -1, farthest = index;
for (int i = 0; i < fr.size(); i++) {
int j;
for (j = index; j < pn; j++) {
if (fr[i] == page[j]) {
if (j > farthest) {
farthest = j;
res = i;
}
break;
}
}
// Return the page which are
// are never referenced in future,
if (j == pn)
return i;
}
// If all of the frames were not in future,
// return any of them, we return 0. Otherwise
// we return res.
return (res == -1) ? 0 : res;
}
bool search(int key, vector<int>& fr) {
for (int i = 0; i < fr.size(); i++)
if (fr[i] == key)
return true;
return false;
}
void opr(int page[], int pn, int fn) {
vector<int> fr;
int hit = 0;
for (int i = 0; i < pn; i++) {
// Page found in a frame : HIT
if (search(page[i], fr)) {
hit++;
continue;
}
//If a page not found in a frame : MISS
// check if there is space available in frames.
if (fr.size() < fn)
fr.push_back(page[i]);
// Find the page to be replaced.
else {
int j = predict(page, fr, pn, i + 1);
fr[j] = page[i];
}
}
cout << "Hits = " << hit << endl;
cout << "Misses = " << pn - hit << endl;
}
// main Function
int main() {
int page[] = { 1, 7, 8, 3, 0, 2, 0, 3, 5, 4, 0, 6, 1 };
int pn = sizeof(page) / sizeof(page[0]);
int fn = 3;
opr(page, pn, fn);
return 0;
}
Hits = 3
Misses = 10
|
[
{
"code": null,
"e": 1230,
"s": 1062,
"text": "Given page number and page size; the task is to find number of hits and misses as when we allocate the memory block to a page using Optimal Page Replacement Algorithm."
},
{
"code": null,
"e": 1274,
"s": 1230,
"text": "What is Optimal Page Replacement Algorithm?"
},
{
"code": null,
"e": 1643,
"s": 1274,
"text": "Optimal page replacement algorithm is a page replacement algorithm. A page replacement algorithm is an algorithm which decides which memory page is to be replaced. In Optimal page replacement we replace the page which is not referred to the near future, although it can’t be practically implemented, but this is most optimal and have minimal miss, and is most optimal."
},
{
"code": null,
"e": 1716,
"s": 1643,
"text": "Let’s understand by using an example and explaining it diagrammatically."
},
{
"code": null,
"e": 2008,
"s": 1716,
"text": "Here after allocating 1, 2 and 3 now the memory is full, so for inserting 4 we will look for the page which is not again referred in near future from 1, 2 and 3 so page 3 is not in near future so we replace that page with new page 4, and so on we will repeat the steps till we reach the end."
},
{
"code": null,
"e": 2205,
"s": 2008,
"text": "Input: page[] = { 1, 7, 8, 3, 0, 2, 0, 3, 5, 4, 0, 6, 1 }\n fn=3\nOutput: Hits = 3\n Misses = 10\n\nInput: page[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 }\n fn = 4\nOutput: Hits = 7\n Misses= 6"
},
{
"code": null,
"e": 2256,
"s": 2205,
"text": "Approach we are using to solve the above problem −"
},
{
"code": null,
"e": 2293,
"s": 2256,
"text": "Take the input of pages as an array."
},
{
"code": null,
"e": 2406,
"s": 2293,
"text": "Look for the page allocated is present in near future, if no then replace that page in the memory with new page,"
},
{
"code": null,
"e": 2466,
"s": 2406,
"text": "If page already present increment hit, else increment miss."
},
{
"code": null,
"e": 2518,
"s": 2466,
"text": "Repeat till we reach the last element of the array."
},
{
"code": null,
"e": 2555,
"s": 2518,
"text": "Print the number of hits and misses."
},
{
"code": null,
"e": 3773,
"s": 2555,
"text": "Start\nStep 1-> In function int predict(int page[], vector<int>& fr, int pn, int index)\n Declare and initialize res = -1, farthest = index\n Loop For i = 0 and i < fr.size() and i++\n Loop For j = index and j < pn and j++\n If fr[i] == page[j] then,\n If j > farthest\n Set farthest = j\n End If\n Set res = i\n break\n If j == pn then,\n Return i\n Return (res == -1) ? 0 : res\nStep 2-> In function bool search(int key, vector<int>& fr)\n Loop For i = 0 and i < fr.size() and i++\n If fr[i] == key then,\n Return true\n Return false\nStep 3-> In function void opr(int page[], int pn, int fn)\n Declare vector<int> fr\n Set hit = 0\n Loop For i = 0 and i < pn and i++\n If search(page[i], fr) then,\n Increment hit by 1\n continue\n If fr.size() < fn then,\n fr.push_back(page[i])\n Else\n Set j = predict(page, fr, pn, i + 1)\n Set fr[j] = page[i]\n Print the number of hits\n Print the number of misses\nStep 4-> In function int main()\n Declare and assign page[] = { 1, 7, 8, 3, 0, 2, 0, 3, 5, 4, 0, 6, 1 }\n Set pn = sizeof(page) / sizeof(page[0])\n Set fn = 3\n opr(page, pn, fn)\nStop"
},
{
"code": null,
"e": 3784,
"s": 3773,
"text": " Live Demo"
},
{
"code": null,
"e": 5461,
"s": 3784,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint predict(int page[], vector<int>& fr, int pn, int index) {\n // Store the index of pages which are going\n // to be used recently in future\n int res = -1, farthest = index;\n for (int i = 0; i < fr.size(); i++) {\n int j;\n for (j = index; j < pn; j++) {\n if (fr[i] == page[j]) {\n if (j > farthest) {\n farthest = j;\n res = i;\n }\n break;\n }\n }\n // Return the page which are\n // are never referenced in future,\n if (j == pn)\n return i;\n }\n // If all of the frames were not in future,\n // return any of them, we return 0. Otherwise\n // we return res.\n return (res == -1) ? 0 : res;\n}\nbool search(int key, vector<int>& fr) {\n for (int i = 0; i < fr.size(); i++)\n if (fr[i] == key)\n return true;\n return false;\n}\nvoid opr(int page[], int pn, int fn) {\n vector<int> fr;\n int hit = 0;\n for (int i = 0; i < pn; i++) {\n // Page found in a frame : HIT\n if (search(page[i], fr)) {\n hit++;\n continue;\n }\n //If a page not found in a frame : MISS \n // check if there is space available in frames.\n if (fr.size() < fn)\n fr.push_back(page[i]);\n // Find the page to be replaced.\n else {\n int j = predict(page, fr, pn, i + 1);\n fr[j] = page[i];\n }\n }\n cout << \"Hits = \" << hit << endl;\n cout << \"Misses = \" << pn - hit << endl;\n}\n// main Function\nint main() {\n int page[] = { 1, 7, 8, 3, 0, 2, 0, 3, 5, 4, 0, 6, 1 };\n int pn = sizeof(page) / sizeof(page[0]);\n int fn = 3;\n opr(page, pn, fn);\n return 0;\n}"
},
{
"code": null,
"e": 5482,
"s": 5461,
"text": "Hits = 3\nMisses = 10"
}
] |
Exploratory Data Analysis in Python - GeeksforGeeks
|
26 Apr, 2022
EDA is a phenomenon under data analysis used for gaining a better understanding of data aspects like: – main features of data – variables and relationships that hold between them – identifying which variables are important for our problem We shall look at various exploratory data analysis methods like:
Descriptive Statistics, which is a way of giving a brief overview of the dataset we are dealing with, including some measures and features of the sample
Grouping data [Basic grouping with group by]
ANOVA, Analysis Of Variance, which is a computational method to divide variations in an observations set into different components.
Correlation and correlation methods
The dataset we’ll be using is child voting dataset, which you can import in python as:
Python3
import pandas as pdDf = pd.read_csv("https://vincentarelbundock.github.io / Rdatasets / csv / car / Child.csv")
Descriptive statistics is a helpful way to understand characteristics of your data and to get a quick summary of it. Pandas in python provide an interesting method describe(). The describe function applies basic statistical computations on the dataset like extreme values, count of data points standard deviation etc. Any missing value or NaN value is automatically skipped. describe() function gives a good picture of distribution of data.
Python3
DF.describe()
Here’s the output you’ll get on running above code:
Another useful method if value_counts() which can get count of each category in a categorical attributed series of values. For an instance suppose you are dealing with a dataset of customers who are divided as youth, medium and old categories under column name age and your dataframe is “DF”. You can run this statement to know how many people fall in respective categories. In our data set example education column can be used
Python3
DF["education"].value_counts()
The output of the above code will be:
One more useful tool is boxplot which you can use through matplotlib module. Boxplot is a pictorial representation of distribution of data which shows extreme values, median and quartiles. We can easily figure out outliers by using boxplots. Now consider the dataset we’ve been dealing with again and lets draw a boxplot on attribute population
Python3
import pandas as pdimport matplotlib.pyplot as pltDF = pd.read_csv("https://raw.githubusercontent.com / fivethirtyeight / data / master / airline-safety / airline-safety.csv")y = list(DF.population)plt.boxplot(y)plt.show()
The output plot would look like this with spotting out outliers:
Group by is an interesting measure available in pandas which can help us figure out effect of different categorical attributes on other data variables. Let’s see an example on the same dataset where we want to figure out affect of people’s age and education on the voting dataset.
Python3
DF.groupby(['education', 'vote']).mean()
The output would be somewhat like this:
If this group by output table is less understandable further analysts use pivot tables and heat maps for visualization on them.
ANOVA stands for Analysis of Variance. It is performed to figure out the relation between the different group of categorical data. Under ANOVA we have two measures as result: – F-testscore : which shows the variation of groups mean over variation – p-value: it shows the importance of the result This can be performed using python module scipy method name f_oneway() Syntax:
These samples are sample measurements for each group. As a conclusion, we can say that there is a strong correlation between other variables and a categorical variable if the ANOVA test gives us a large F-test value and a small p-value.
Correlation is a simple relationship between two variables in a context such that one variable affects the other. Correlation is different from act of causing. One way to calculate correlation among variables is to find Pearson correlation. Here we find two parameters namely, Pearson coefficient and p-value. We can say there is a strong correlation between two variables when Pearson correlation coefficient is close to either 1 or -1 and the p-value is less than 0.0001. Scipy module also provides a method to perform pearson correlation analysis, syntax:
Here samples are the attributes you want to compare. This is a brief overview of EDA in python, we can do lots more! Happy digging!
surindertarika1234
simranarora5sos
data-science
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24974,
"s": 24946,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 25280,
"s": 24974,
"text": "EDA is a phenomenon under data analysis used for gaining a better understanding of data aspects like: – main features of data – variables and relationships that hold between them – identifying which variables are important for our problem We shall look at various exploratory data analysis methods like: "
},
{
"code": null,
"e": 25433,
"s": 25280,
"text": "Descriptive Statistics, which is a way of giving a brief overview of the dataset we are dealing with, including some measures and features of the sample"
},
{
"code": null,
"e": 25478,
"s": 25433,
"text": "Grouping data [Basic grouping with group by]"
},
{
"code": null,
"e": 25610,
"s": 25478,
"text": "ANOVA, Analysis Of Variance, which is a computational method to divide variations in an observations set into different components."
},
{
"code": null,
"e": 25646,
"s": 25610,
"text": "Correlation and correlation methods"
},
{
"code": null,
"e": 25735,
"s": 25646,
"text": "The dataset we’ll be using is child voting dataset, which you can import in python as: "
},
{
"code": null,
"e": 25743,
"s": 25735,
"text": "Python3"
},
{
"code": "import pandas as pdDf = pd.read_csv(\"https://vincentarelbundock.github.io / Rdatasets / csv / car / Child.csv\")",
"e": 25855,
"s": 25743,
"text": null
},
{
"code": null,
"e": 26298,
"s": 25855,
"text": "Descriptive statistics is a helpful way to understand characteristics of your data and to get a quick summary of it. Pandas in python provide an interesting method describe(). The describe function applies basic statistical computations on the dataset like extreme values, count of data points standard deviation etc. Any missing value or NaN value is automatically skipped. describe() function gives a good picture of distribution of data. "
},
{
"code": null,
"e": 26306,
"s": 26298,
"text": "Python3"
},
{
"code": "DF.describe()",
"e": 26320,
"s": 26306,
"text": null
},
{
"code": null,
"e": 26374,
"s": 26320,
"text": "Here’s the output you’ll get on running above code: "
},
{
"code": null,
"e": 26804,
"s": 26374,
"text": "Another useful method if value_counts() which can get count of each category in a categorical attributed series of values. For an instance suppose you are dealing with a dataset of customers who are divided as youth, medium and old categories under column name age and your dataframe is “DF”. You can run this statement to know how many people fall in respective categories. In our data set example education column can be used "
},
{
"code": null,
"e": 26812,
"s": 26804,
"text": "Python3"
},
{
"code": "DF[\"education\"].value_counts()",
"e": 26843,
"s": 26812,
"text": null
},
{
"code": null,
"e": 26883,
"s": 26843,
"text": "The output of the above code will be: "
},
{
"code": null,
"e": 27230,
"s": 26883,
"text": "One more useful tool is boxplot which you can use through matplotlib module. Boxplot is a pictorial representation of distribution of data which shows extreme values, median and quartiles. We can easily figure out outliers by using boxplots. Now consider the dataset we’ve been dealing with again and lets draw a boxplot on attribute population "
},
{
"code": null,
"e": 27238,
"s": 27230,
"text": "Python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltDF = pd.read_csv(\"https://raw.githubusercontent.com / fivethirtyeight / data / master / airline-safety / airline-safety.csv\")y = list(DF.population)plt.boxplot(y)plt.show()",
"e": 27461,
"s": 27238,
"text": null
},
{
"code": null,
"e": 27528,
"s": 27461,
"text": "The output plot would look like this with spotting out outliers: "
},
{
"code": null,
"e": 27813,
"s": 27530,
"text": "Group by is an interesting measure available in pandas which can help us figure out effect of different categorical attributes on other data variables. Let’s see an example on the same dataset where we want to figure out affect of people’s age and education on the voting dataset. "
},
{
"code": null,
"e": 27821,
"s": 27813,
"text": "Python3"
},
{
"code": "DF.groupby(['education', 'vote']).mean()",
"e": 27862,
"s": 27821,
"text": null
},
{
"code": null,
"e": 27904,
"s": 27862,
"text": "The output would be somewhat like this: "
},
{
"code": null,
"e": 28034,
"s": 27904,
"text": "If this group by output table is less understandable further analysts use pivot tables and heat maps for visualization on them. "
},
{
"code": null,
"e": 28409,
"s": 28034,
"text": "ANOVA stands for Analysis of Variance. It is performed to figure out the relation between the different group of categorical data. Under ANOVA we have two measures as result: – F-testscore : which shows the variation of groups mean over variation – p-value: it shows the importance of the result This can be performed using python module scipy method name f_oneway() Syntax:"
},
{
"code": null,
"e": 28649,
"s": 28411,
"text": "These samples are sample measurements for each group. As a conclusion, we can say that there is a strong correlation between other variables and a categorical variable if the ANOVA test gives us a large F-test value and a small p-value. "
},
{
"code": null,
"e": 29209,
"s": 28649,
"text": "Correlation is a simple relationship between two variables in a context such that one variable affects the other. Correlation is different from act of causing. One way to calculate correlation among variables is to find Pearson correlation. Here we find two parameters namely, Pearson coefficient and p-value. We can say there is a strong correlation between two variables when Pearson correlation coefficient is close to either 1 or -1 and the p-value is less than 0.0001. Scipy module also provides a method to perform pearson correlation analysis, syntax: "
},
{
"code": null,
"e": 29344,
"s": 29211,
"text": "Here samples are the attributes you want to compare. This is a brief overview of EDA in python, we can do lots more! Happy digging! "
},
{
"code": null,
"e": 29363,
"s": 29344,
"text": "surindertarika1234"
},
{
"code": null,
"e": 29379,
"s": 29363,
"text": "simranarora5sos"
},
{
"code": null,
"e": 29392,
"s": 29379,
"text": "data-science"
},
{
"code": null,
"e": 29399,
"s": 29392,
"text": "Python"
},
{
"code": null,
"e": 29497,
"s": 29399,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29515,
"s": 29497,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29550,
"s": 29515,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29572,
"s": 29550,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29604,
"s": 29572,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29634,
"s": 29604,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29676,
"s": 29634,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29702,
"s": 29676,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29739,
"s": 29702,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29782,
"s": 29739,
"text": "Python program to convert a list to string"
}
] |
Find and plot your optimal path using OSM, Plotly and NetworkX in Python | by Apurv Priyam | Towards Data Science
|
Many libraries can be used to plot a path using Google Maps API, but this leads to reduced flexibility. Also, if you use a set of lines to draw a path then, in a lack of better words, it doesn’t look good. Let me give you an example:
Also, on many occasions, you may want some flexibility to not only change the desired path between two points (for example, instead of the shortest or fastest path given by google maps you want the path which satisfies your criteria) but also how you want to plot.
In this blog, I took an attempt to solve such a problem where not only we will find the optimal path but also plot them using Plotly. Let’s first start with importing some libraries.
import osmnx as oximport networkx as nximport plotly.graph_objects as goimport numpy as np
The OSMnx library helps to retrieve, analyze, and visualize street networks from OpenStreetMap. You can read more about OSMnx here. To demonstrate I will download the state boundary of Georgia, US and plot it using the OSMnx library.
state = ox.gdf_from_place('Georgia, US') ox.plot_shape(ox.project_gdf(state))
Now let’s download a map. This time we will download a more detailed map of the area surrounding Georgia Tech by providing an argument network_type = 'drive'. OSMnx downloads the map as a graph object which can easily be used by the NetworkX library.
# Defining the map boundaries north, east, south, west = 33.798, -84.378, 33.763, -84.422 # Downloading the map as a graph object G = ox.graph_from_bbox(north, south, east, west, network_type = 'drive') # Plotting the map graph ox.plot_graph(G)
In the above graph, we can see all the nodes (blue) and edges (gray) representing the roads with exact shapes. Let’s take a deep-dive into the graph object we downloaded and see what the edges and nodes look like:
# Displaying the 3rd node list(G.nodes(data=True))[2]
(69128194, {‘y’: 33.7692046, ‘x’: -84.390567, ‘osmid’: 69128194, ‘ref’: ‘249C’, ‘highway’: ‘motorway_junction’})
Above output shows the information of node id 69128194 with its x and y coordinates, OSM id, and type of node (a junction). Similarly, we can see the details of the edges:
# Displaying the 1st edgelist(G.edges(data=True))[1]
(69259268, 69508853, {‘osmid’: 9270483, ‘name’: ‘Lindsay Street Northwest’, ‘highway’: ‘residential’, ‘oneway’: False, ‘length’: 145.352, ‘geometry’: })
This shows the details of the edge connecting node 69259264 to 69290452 along with its OSM id, name, type, oneway/twoway, length and one interesting element of type geometry.linestring. We can see how this geometry looks like.
# Displaying the shape of edge using the geometry list(G.edges(data=True))[1][2]['geometry']
This shows that the edge is not a straight line but a curved path. We will use this information later while plotting this type of curved edges.
Now we will find the optimal path. For now, lets set our objective as to find the path with the smallest length. This can be changed to satisfy any criteria and will be covered in a separate blog. After deciding an origin and destination, first, we will need to get the closest nodes from these locations. This can be done using the function get_nearest_node from OSMnx.
# define origin and desination locations origin_point = (33.787201, -84.405076) destination_point = (33.764135, -84.394980)# get the nearest nodes to the locations origin_node = ox.get_nearest_node(G, origin_point) destination_node = ox.get_nearest_node(G, destination_point)# printing the closest node id to origin and destination points origin_node, destination_node
(69425048, 2919090915)
Now, we can use the shortest_path function from the NetworkX library to get the optimal path which minimizes the total length using Dijkstra's algorithm. Notice that we have provided weight='length'. This function returns a list of ordered nodes in the path.
# Finding the optimal path route = nx.shortest_path(G, origin_node, destination_node, weight = 'length') route
[69425048, 69425021, 69466983, 69466977, . .
Let’s plot these nodes on a map. We will use the Plotly library for this. We will plot all these nodes and connect them with lines to represent a path. Let’s see how it looks. But first, let’s get the co-ordinates of these nodes
# getting coordinates of the nodes# we will store the longitudes and latitudes in following list long = [] lat = [] for i in route: point = G.nodes[i] long.append(point['x']) lat.append(point['y'])
We will plot the path on a map multiple times so let’s define a function for this:
def plot_path(lat, long, origin_point, destination_point): """ Given a list of latitudes and longitudes, origin and destination point, plots a path on a map Parameters ---------- lat, long: list of latitudes and longitudes origin_point, destination_point: co-ordinates of origin and destination Returns ------- Nothing. Only shows the map. """ # adding the lines joining the nodes fig = go.Figure(go.Scattermapbox( name = "Path", mode = "lines", lon = long, lat = lat, marker = {'size': 10}, line = dict(width = 4.5, color = 'blue'))) # adding source marker fig.add_trace(go.Scattermapbox( name = "Source", mode = "markers", lon = [origin_point[1]], lat = [origin_point[0]], marker = {'size': 12, 'color':"red"})) # adding destination marker fig.add_trace(go.Scattermapbox( name = "Destination", mode = "markers", lon = [destination_point[1]], lat = [destination_point[0]], marker = {'size': 12, 'color':'green'})) # getting center for plots: lat_center = np.mean(lat) long_center = np.mean(long) # defining the layout using mapbox_style fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lat = 30, mapbox_center_lon=-80) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}, mapbox = { 'center': {'lat': lat_center, 'lon': long_center}, 'zoom': 13}) fig.show()
Let’s call the function and plot the path on the map:
plot_path(lat, long, origin_point, destination_point)
This looks good. We have plotted a path from the source node to the destination node, and these nodes are very close to the actual co-ordinates we provided as the source and destination (shown using red and green markers respectively). But something is missing. Yes, the curves on road are replaced by straight lines joining the two nodes in the path. This can be observed in the orange boxes. If you remember the geometry element of the edges from above, we will use that to solve this issue.
To illustrate we will see the edge shape of this portion of the path. This path is between the 6th and 7th nodes from the end in out route variable. Let’s get the edge connecting these two nodes and we will see its shape.
# Getting the start and end node of this part start_node=route[-7] end_node=route[-6]# Getting the edge connecting these nodes and storing it as a list in z to maintain the data structure of G.edges z = [] for i in list(G.edges(data=True)): if (i[0]==start_node) & (i[1]==end_node): z.append(i) z[0][2]['geometry']
This looks exactly like the street inside the second orange box. So now we have a way to get these curved shapes to plot. We just have to get these shapes and replace them with our original route data. For this, we will define a function that does exactly this. It loops over all the edges and if a curved shape is present for that edge, it stores that curve.
def node_list_to_path(G, node_list): """ Given a list of nodes, return a list of lines that together follow the path defined by the list of nodes. Parameters ---------- G : networkx multidigraph route : list the route as a list of nodes Returns ------- lines : list of lines given as pairs ( (x_start, y_start), (x_stop, y_stop) ) """ edge_nodes = list(zip(node_list[:-1], node_list[1:])) lines = [] for u, v in edge_nodes: # if there are parallel edges, select the shortest in length data = min(G.get_edge_data(u, v).values(), key=lambda x: x['length']) # if it has a geometry attribute if 'geometry' in data: # add them to the list of lines to plot xs, ys = data['geometry'].xy lines.append(list(zip(xs, ys))) else: # if it doesn't have a geometry attribute, # then the edge is a straight line from node to node x1 = G.nodes[u]['x'] y1 = G.nodes[u]['y'] x2 = G.nodes[v]['x'] y2 = G.nodes[v]['y'] line = [(x1, y1), (x2, y2)] lines.append(line)return lines# getting the list of coordinates from the path # (which is a list of nodes)lines = node_list_to_path(G, route)long2 = []lat2 = []for i in range(len(lines)): z = list(lines[i]) l1 = list(list(zip(*z))[0]) l2 = list(list(zip(*z))[1]) for j in range(len(l1)): long2.append(l1[j]) lat2.append(l2[j])
If we compare the length of lat and lat2 we will notice that lat2 has more than 6 times the co-ordinates as compared to the lat.
print("Length of lat: ", len(lat))print("Length of lat2: ", len(lat2))
Length of lat: 23 Length of lat2: 141
The last thing to do now is to plot the path and see how it looks.
plot_path(lat2, long2, origin_point, destination_point)
This looks much better. In this blog, we used libraries like OSMnx and Plotly to create our direction map. We used NetworkX to get the most optimal path based on our objective. Here we have used the most common objective – length, but this can be easily replaced.
Find the original post on my website apurv.page/plotthepath.html
|
[
{
"code": null,
"e": 405,
"s": 171,
"text": "Many libraries can be used to plot a path using Google Maps API, but this leads to reduced flexibility. Also, if you use a set of lines to draw a path then, in a lack of better words, it doesn’t look good. Let me give you an example:"
},
{
"code": null,
"e": 670,
"s": 405,
"text": "Also, on many occasions, you may want some flexibility to not only change the desired path between two points (for example, instead of the shortest or fastest path given by google maps you want the path which satisfies your criteria) but also how you want to plot."
},
{
"code": null,
"e": 853,
"s": 670,
"text": "In this blog, I took an attempt to solve such a problem where not only we will find the optimal path but also plot them using Plotly. Let’s first start with importing some libraries."
},
{
"code": null,
"e": 944,
"s": 853,
"text": "import osmnx as oximport networkx as nximport plotly.graph_objects as goimport numpy as np"
},
{
"code": null,
"e": 1178,
"s": 944,
"text": "The OSMnx library helps to retrieve, analyze, and visualize street networks from OpenStreetMap. You can read more about OSMnx here. To demonstrate I will download the state boundary of Georgia, US and plot it using the OSMnx library."
},
{
"code": null,
"e": 1256,
"s": 1178,
"text": "state = ox.gdf_from_place('Georgia, US') ox.plot_shape(ox.project_gdf(state))"
},
{
"code": null,
"e": 1507,
"s": 1256,
"text": "Now let’s download a map. This time we will download a more detailed map of the area surrounding Georgia Tech by providing an argument network_type = 'drive'. OSMnx downloads the map as a graph object which can easily be used by the NetworkX library."
},
{
"code": null,
"e": 1754,
"s": 1507,
"text": "# Defining the map boundaries north, east, south, west = 33.798, -84.378, 33.763, -84.422 # Downloading the map as a graph object G = ox.graph_from_bbox(north, south, east, west, network_type = 'drive') # Plotting the map graph ox.plot_graph(G)"
},
{
"code": null,
"e": 1968,
"s": 1754,
"text": "In the above graph, we can see all the nodes (blue) and edges (gray) representing the roads with exact shapes. Let’s take a deep-dive into the graph object we downloaded and see what the edges and nodes look like:"
},
{
"code": null,
"e": 2022,
"s": 1968,
"text": "# Displaying the 3rd node list(G.nodes(data=True))[2]"
},
{
"code": null,
"e": 2135,
"s": 2022,
"text": "(69128194, {‘y’: 33.7692046, ‘x’: -84.390567, ‘osmid’: 69128194, ‘ref’: ‘249C’, ‘highway’: ‘motorway_junction’})"
},
{
"code": null,
"e": 2307,
"s": 2135,
"text": "Above output shows the information of node id 69128194 with its x and y coordinates, OSM id, and type of node (a junction). Similarly, we can see the details of the edges:"
},
{
"code": null,
"e": 2360,
"s": 2307,
"text": "# Displaying the 1st edgelist(G.edges(data=True))[1]"
},
{
"code": null,
"e": 2514,
"s": 2360,
"text": "(69259268, 69508853, {‘osmid’: 9270483, ‘name’: ‘Lindsay Street Northwest’, ‘highway’: ‘residential’, ‘oneway’: False, ‘length’: 145.352, ‘geometry’: })"
},
{
"code": null,
"e": 2741,
"s": 2514,
"text": "This shows the details of the edge connecting node 69259264 to 69290452 along with its OSM id, name, type, oneway/twoway, length and one interesting element of type geometry.linestring. We can see how this geometry looks like."
},
{
"code": null,
"e": 2834,
"s": 2741,
"text": "# Displaying the shape of edge using the geometry list(G.edges(data=True))[1][2]['geometry']"
},
{
"code": null,
"e": 2978,
"s": 2834,
"text": "This shows that the edge is not a straight line but a curved path. We will use this information later while plotting this type of curved edges."
},
{
"code": null,
"e": 3349,
"s": 2978,
"text": "Now we will find the optimal path. For now, lets set our objective as to find the path with the smallest length. This can be changed to satisfy any criteria and will be covered in a separate blog. After deciding an origin and destination, first, we will need to get the closest nodes from these locations. This can be done using the function get_nearest_node from OSMnx."
},
{
"code": null,
"e": 3718,
"s": 3349,
"text": "# define origin and desination locations origin_point = (33.787201, -84.405076) destination_point = (33.764135, -84.394980)# get the nearest nodes to the locations origin_node = ox.get_nearest_node(G, origin_point) destination_node = ox.get_nearest_node(G, destination_point)# printing the closest node id to origin and destination points origin_node, destination_node"
},
{
"code": null,
"e": 3741,
"s": 3718,
"text": "(69425048, 2919090915)"
},
{
"code": null,
"e": 4000,
"s": 3741,
"text": "Now, we can use the shortest_path function from the NetworkX library to get the optimal path which minimizes the total length using Dijkstra's algorithm. Notice that we have provided weight='length'. This function returns a list of ordered nodes in the path."
},
{
"code": null,
"e": 4111,
"s": 4000,
"text": "# Finding the optimal path route = nx.shortest_path(G, origin_node, destination_node, weight = 'length') route"
},
{
"code": null,
"e": 4156,
"s": 4111,
"text": "[69425048, 69425021, 69466983, 69466977, . ."
},
{
"code": null,
"e": 4385,
"s": 4156,
"text": "Let’s plot these nodes on a map. We will use the Plotly library for this. We will plot all these nodes and connect them with lines to represent a path. Let’s see how it looks. But first, let’s get the co-ordinates of these nodes"
},
{
"code": null,
"e": 4596,
"s": 4385,
"text": "# getting coordinates of the nodes# we will store the longitudes and latitudes in following list long = [] lat = [] for i in route: point = G.nodes[i] long.append(point['x']) lat.append(point['y'])"
},
{
"code": null,
"e": 4679,
"s": 4596,
"text": "We will plot the path on a map multiple times so let’s define a function for this:"
},
{
"code": null,
"e": 6260,
"s": 4679,
"text": "def plot_path(lat, long, origin_point, destination_point): \"\"\" Given a list of latitudes and longitudes, origin and destination point, plots a path on a map Parameters ---------- lat, long: list of latitudes and longitudes origin_point, destination_point: co-ordinates of origin and destination Returns ------- Nothing. Only shows the map. \"\"\" # adding the lines joining the nodes fig = go.Figure(go.Scattermapbox( name = \"Path\", mode = \"lines\", lon = long, lat = lat, marker = {'size': 10}, line = dict(width = 4.5, color = 'blue'))) # adding source marker fig.add_trace(go.Scattermapbox( name = \"Source\", mode = \"markers\", lon = [origin_point[1]], lat = [origin_point[0]], marker = {'size': 12, 'color':\"red\"})) # adding destination marker fig.add_trace(go.Scattermapbox( name = \"Destination\", mode = \"markers\", lon = [destination_point[1]], lat = [destination_point[0]], marker = {'size': 12, 'color':'green'})) # getting center for plots: lat_center = np.mean(lat) long_center = np.mean(long) # defining the layout using mapbox_style fig.update_layout(mapbox_style=\"stamen-terrain\", mapbox_center_lat = 30, mapbox_center_lon=-80) fig.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0}, mapbox = { 'center': {'lat': lat_center, 'lon': long_center}, 'zoom': 13}) fig.show()"
},
{
"code": null,
"e": 6314,
"s": 6260,
"text": "Let’s call the function and plot the path on the map:"
},
{
"code": null,
"e": 6368,
"s": 6314,
"text": "plot_path(lat, long, origin_point, destination_point)"
},
{
"code": null,
"e": 6862,
"s": 6368,
"text": "This looks good. We have plotted a path from the source node to the destination node, and these nodes are very close to the actual co-ordinates we provided as the source and destination (shown using red and green markers respectively). But something is missing. Yes, the curves on road are replaced by straight lines joining the two nodes in the path. This can be observed in the orange boxes. If you remember the geometry element of the edges from above, we will use that to solve this issue."
},
{
"code": null,
"e": 7084,
"s": 6862,
"text": "To illustrate we will see the edge shape of this portion of the path. This path is between the 6th and 7th nodes from the end in out route variable. Let’s get the edge connecting these two nodes and we will see its shape."
},
{
"code": null,
"e": 7412,
"s": 7084,
"text": "# Getting the start and end node of this part start_node=route[-7] end_node=route[-6]# Getting the edge connecting these nodes and storing it as a list in z to maintain the data structure of G.edges z = [] for i in list(G.edges(data=True)): if (i[0]==start_node) & (i[1]==end_node): z.append(i) z[0][2]['geometry']"
},
{
"code": null,
"e": 7772,
"s": 7412,
"text": "This looks exactly like the street inside the second orange box. So now we have a way to get these curved shapes to plot. We just have to get these shapes and replace them with our original route data. For this, we will define a function that does exactly this. It loops over all the edges and if a curved shape is present for that edge, it stores that curve."
},
{
"code": null,
"e": 9282,
"s": 7772,
"text": "def node_list_to_path(G, node_list): \"\"\" Given a list of nodes, return a list of lines that together follow the path defined by the list of nodes. Parameters ---------- G : networkx multidigraph route : list the route as a list of nodes Returns ------- lines : list of lines given as pairs ( (x_start, y_start), (x_stop, y_stop) ) \"\"\" edge_nodes = list(zip(node_list[:-1], node_list[1:])) lines = [] for u, v in edge_nodes: # if there are parallel edges, select the shortest in length data = min(G.get_edge_data(u, v).values(), key=lambda x: x['length']) # if it has a geometry attribute if 'geometry' in data: # add them to the list of lines to plot xs, ys = data['geometry'].xy lines.append(list(zip(xs, ys))) else: # if it doesn't have a geometry attribute, # then the edge is a straight line from node to node x1 = G.nodes[u]['x'] y1 = G.nodes[u]['y'] x2 = G.nodes[v]['x'] y2 = G.nodes[v]['y'] line = [(x1, y1), (x2, y2)] lines.append(line)return lines# getting the list of coordinates from the path # (which is a list of nodes)lines = node_list_to_path(G, route)long2 = []lat2 = []for i in range(len(lines)): z = list(lines[i]) l1 = list(list(zip(*z))[0]) l2 = list(list(zip(*z))[1]) for j in range(len(l1)): long2.append(l1[j]) lat2.append(l2[j])"
},
{
"code": null,
"e": 9411,
"s": 9282,
"text": "If we compare the length of lat and lat2 we will notice that lat2 has more than 6 times the co-ordinates as compared to the lat."
},
{
"code": null,
"e": 9482,
"s": 9411,
"text": "print(\"Length of lat: \", len(lat))print(\"Length of lat2: \", len(lat2))"
},
{
"code": null,
"e": 9520,
"s": 9482,
"text": "Length of lat: 23 Length of lat2: 141"
},
{
"code": null,
"e": 9587,
"s": 9520,
"text": "The last thing to do now is to plot the path and see how it looks."
},
{
"code": null,
"e": 9643,
"s": 9587,
"text": "plot_path(lat2, long2, origin_point, destination_point)"
},
{
"code": null,
"e": 9907,
"s": 9643,
"text": "This looks much better. In this blog, we used libraries like OSMnx and Plotly to create our direction map. We used NetworkX to get the most optimal path based on our objective. Here we have used the most common objective – length, but this can be easily replaced."
}
] |
Ulong type in C#
|
The Ulong type in C# is an alias to the System.UInt64 type. It is an Unsigned integer.
Set the Ulong type −
ulong val = 7712059531;
To get the minimum and maximum value for Ulong type −
Console.WriteLine(ulong.MaxValue);
Console.WriteLine(ulong.MinValue);
Here is the complete code −
Live Demo
using System;
using System.Threading;
using System.Diagnostics;
public class Demo {
public static void Main() {
ulong val = 7712059531;
Console.WriteLine(val);
// Max and Min values
Console.WriteLine(ulong.MaxValue);
Console.WriteLine(ulong.MinValue);
// typeof
Console.WriteLine(typeof(ulong));
}
}
7712059531
18446744073709551615
0
System.UInt64
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "The Ulong type in C# is an alias to the System.UInt64 type. It is an Unsigned integer."
},
{
"code": null,
"e": 1170,
"s": 1149,
"text": "Set the Ulong type −"
},
{
"code": null,
"e": 1194,
"s": 1170,
"text": "ulong val = 7712059531;"
},
{
"code": null,
"e": 1248,
"s": 1194,
"text": "To get the minimum and maximum value for Ulong type −"
},
{
"code": null,
"e": 1318,
"s": 1248,
"text": "Console.WriteLine(ulong.MaxValue);\nConsole.WriteLine(ulong.MinValue);"
},
{
"code": null,
"e": 1346,
"s": 1318,
"text": "Here is the complete code −"
},
{
"code": null,
"e": 1357,
"s": 1346,
"text": " Live Demo"
},
{
"code": null,
"e": 1705,
"s": 1357,
"text": "using System;\nusing System.Threading;\nusing System.Diagnostics;\npublic class Demo {\n public static void Main() {\n ulong val = 7712059531;\n Console.WriteLine(val);\n // Max and Min values\n Console.WriteLine(ulong.MaxValue);\n Console.WriteLine(ulong.MinValue);\n // typeof\n Console.WriteLine(typeof(ulong));\n }\n}"
},
{
"code": null,
"e": 1753,
"s": 1705,
"text": "7712059531\n18446744073709551615\n0\nSystem.UInt64"
}
] |
Time Series Analysis in Python: An Introduction | by Will Koehrsen | Towards Data Science
|
Additive models for time series modeling
Time series are one of the most common data types encountered in daily life. Financial prices, weather, home energy usage, and even weight are all examples of data that can be collected at regular intervals. Almost every data scientist will encounter time series in their daily work and learning how to model them is an important skill in the data science toolbox. One powerful yet simple method for analyzing and predicting periodic data is the additive model. The idea is straightforward: represent a time-series as a combination of patterns at different scales such as daily, weekly, seasonally, and yearly, along with an overall trend. Your energy use might rise in the summer and decrease in the winter, but have an overall decreasing trend as you increase the energy efficiency of your home. An additive model can show us both patterns/trends and make predictions based on these observations.
The following image shows an additive model decomposition of a time-series into an overall trend, yearly trend, and weekly trend.
This post will walk through an introductory example of creating an additive model for financial time-series data using Python and the Prophet forecasting package developed by Facebook. Along the way, we will cover some data manipulation using pandas, accessing financial data using the Quandl library and, and plotting with matplotlib. I have included code where it is instructive, and I encourage anyone to check out the Jupyter Notebook on GitHub for the full analysis. This introduction will show you all the steps needed to start modeling time-series on your own!
Disclaimer: Now comes the boring part when I have to mention that when it comes to financial data, past performance is no indicator of future performance and you cannot use the methods here to get rich. I chose to use stock data because it is easily available on a daily frequency and fun to play around with. If you really want to become wealthy, learning data science is a better choice than playing the stock market!
Usually, about 80% of the time spent on a data science project is getting and cleaning data. Thanks to the quandl financial library, that was reduced to about 5% for this project. Quandl can be installed with pip from the command line, lets you access thousands of financial indicators with a single line of Python, and allows up to 50 requests a day without signing up. If you sign up for a free account, you get an api key that allows unlimited requests.
First, we import the required libraries and get some data. Quandl automatically puts our data into a pandas dataframe, the data structure of choice for data science. (For other companies, just replace the ‘TSLA’ or ‘GM’ with the stock ticker. You can also specify a date range).
# quandl for financial dataimport quandl# pandas for data manipulationimport pandas as pdquandl.ApiConfig.api_key = 'getyourownkey!'# Retrieve TSLA data from Quandltesla = quandl.get('WIKI/TSLA')# Retrieve the GM data from Quandlgm = quandl.get('WIKI/GM')gm.head(5)
There is an almost unlimited amount of data on quandl, but I wanted to focus on comparing two companies within the same industry, namely Tesla and General Motors. Tesla is a fascinating company not only because it is the first successful American car start-up in 111 years, but also because at times in 2017 it was the most valuable car company in America despite only selling 4 different cars. The other contender for the title of most valuable car company is General Motors which recently has shown signs of embracing the future of cars by building some pretty cool (but not cool-looking) all-electric vehicles.
We could easily have spent hours searching for this data and downloading it as csv spreadsheet files, but instead, thanks to quandl, we have all the data we need in a few seconds!
Before we can jump into modeling, it’s best to get an idea of the structure and ranges by making a few exploratory plots. This will also allows us to look for outliers or missing values that need to be corrected.
Pandas dataframes can be easily plotted with matplotlib. If any of the graphing code looks intimidating, don’t worry. I also find matplotlib to be unintuitive and often copy and paste examples from Stack Overflow or documentation to get the graph I want. One of the rules of programming is don’t reinvent a solution that already exists!
# The adjusted close accounts for stock splits, so that is what we should graphplt.plot(gm.index, gm['Adj. Close'])plt.title('GM Stock Price')plt.ylabel('Price ($)');plt.show()plt.plot(tesla.index, tesla['Adj. Close'], 'r')plt.title('Tesla Stock Price')plt.ylabel('Price ($)');plt.show();
Comparing the two companies on stock prices alone does not show which is more valuable because the total value of a company (market capitalization) also depends on the number of shares (Market cap= share price * number of shares). Quandl does not have number of shares data, but I was able to find average yearly stock shares for both companies with a quick Google search. Is is not exact, but will be accurate enough for our analysis. Sometimes we have to make do with imperfect data!
To create a column of market cap in our dataframe,we use a few tricks with pandas, such as moving the index to a column (reset_index) and simultaneously indexing and altering values in the dataframe using ix.
# Yearly average number of shares outstanding for Tesla and GMtesla_shares = {2018: 168e6, 2017: 162e6, 2016: 144e6, 2015: 128e6, 2014: 125e6, 2013: 119e6, 2012: 107e6, 2011: 100e6, 2010: 51e6}gm_shares = {2018: 1.42e9, 2017: 1.50e9, 2016: 1.54e9, 2015: 1.59e9, 2014: 1.61e9, 2013: 1.39e9, 2012: 1.57e9, 2011: 1.54e9, 2010:1.50e9}# Create a year column tesla['Year'] = tesla.index.year# Take Dates from index and move to Date column tesla.reset_index(level=0, inplace = True)tesla['cap'] = 0# Calculate market cap for all yearsfor i, year in enumerate(tesla['Year']): # Retrieve the shares for the year shares = tesla_shares.get(year) # Update the cap column to shares times the price tesla.ix[i, 'cap'] = shares * tesla.ix[i, 'Adj. Close']
This creates a ‘cap’ column for Tesla. We do the same process with the GM data and then merge the two. Merging is an essential part of a data science workflow because it allows us to join datasets on a shared column. In this case, we have stock prices for two different companies on the same dates and we therefore want to join the data on the date column. We perform an ‘inner’ merge to save only Date entries that are present in both dataframes. After merging, we rename the columns so we know which one goes with which car company.
# Merge the two datasets and rename the columnscars = gm.merge(tesla, how='inner', on='Date')cars.rename(columns={'cap_x': 'gm_cap', 'cap_y': 'tesla_cap'}, inplace=True)# Select only the relevant columnscars = cars.ix[:, ['Date', 'gm_cap', 'tesla_cap']]# Divide to get market cap in billions of dollarscars['gm_cap'] = cars['gm_cap'] / 1e9cars['tesla_cap'] = cars['tesla_cap'] / 1e9cars.head()
The market cap is in billions of dollars. We can see General Motors started off our period of analysis with a market cap about 30 times that of Tesla! Do things stay that way over the entire timeline?
plt.figure(figsize=(10, 8))plt.plot(cars['Date'], cars['gm_cap'], 'b-', label = 'GM')plt.plot(cars['Date'], cars['tesla_cap'], 'r-', label = 'TESLA')plt.xlabel('Date'); plt.ylabel('Market Cap (Billions $)'); plt.title('Market Cap of GM and Tesla')plt.legend();
We observe a meteoric rise for Tesla and a minor increase for General Motors over the course of the data. Tesla even surpasses GM in value during 2017!
import numpy as np# Find the first and last time Tesla was valued higher than GMfirst_date = cars.ix[np.min(list(np.where(cars['tesla_cap'] > cars['gm_cap'])[0])), 'Date']last_date = cars.ix[np.max(list(np.where(cars['tesla_cap'] > cars['gm_cap'])[0])), 'Date']print("Tesla was valued higher than GM from {} to {}.".format(first_date.date(), last_date.date()))Tesla was valued higher than GM from 2017-04-10 to 2017-09-21.
During that period, Tesla sold about 48,000 cars while GM sold 1,500,000. GM was valued less than Tesla during a period in which it sold 30 times more cars! This definitely displays the power of a persuasive executive and a high-quality — if extremely low-quantity — product. Although the value of Tesla is now lower than GM, a good question might be, can we expect Tesla to again surpass GM? When will this happen? For that we turn to additive models for forecasting, or in other words, predicting the future.
The Facebook Prophet package was released in 2017 for Python and R, and data scientists around the world rejoiced. Prophet is designed for analyzing time series with daily observations that display patterns on different time scales. It also has advanced capabilities for modeling the effects of holidays on a time-series and implementing custom changepoints, but we will stick to the basic functions to get a model up and running. Prophet, like quandl, can be installed with pip from the command line.
We first import prophet and rename the columns in our data to the correct format. The Date column must be called ‘ds’ and the value column we want to predict ‘y’. We then create prophet models and fit them to the data, much like a Scikit-Learn machine learning model:
import fbprophet# Prophet requires columns ds (Date) and y (value)gm = gm.rename(columns={'Date': 'ds', 'cap': 'y'})# Put market cap in billionsgm['y'] = gm['y'] / 1e9# Make the prophet model and fit on the datagm_prophet = fbprophet.Prophet(changepoint_prior_scale=0.15)gm_prophet.fit(gm)
When creating the prophet models, I set the changepoint prior to 0.15, up from the default value of 0.05. This hyperparameter is used to control how sensitive the trend is to changes, with a higher value being more sensitive and a lower value less sensitive. This value is used to combat one of the most fundamental trade-offs in machine learning: bias vs. variance.
If we fit too closely to our training data, called overfitting, we have too much variance and our model will not be able to generalize well to new data. On the other hand, if our model does not capture the trends in our training data it is underfitting and has too much bias. When a model is underfitting, increasing the changepoint prior allows more flexibility for the model to fit the data, and if the model is overfitting, decreasing the prior limits the amount of flexibility. The effect of the changepoint prior scale can be illustrated by graphing predictions made with a range of values:
The higher the changepoint prior scale, the more flexible the model and the closer it fits to the training data. This may seem like exactly what we want, but learning the training data too well can lead to overfitting and an inability to accurately make predictions on new data. We therefore need to find the right balance of fitting the training data and being able to generalize to new data. As stocks vary from day-to-day, and we want our model to capture this, I increased the flexibility after experimenting with a range of values.
In the call to create a prophet model, we can also specify changepoints, which occur when a time-series goes from increasing to decreasing, or from increasing slowly to increasing rapidly (they are located where the rate change in the time series is greatest). Changepoints can correspond to significant events such as product launches or macroeconomic swings in the market. If we do not specify changepoints, prophet will calculate them for us.
To make forecasts, we need to create what is called a future dataframe. We specify the number of future periods to predict (two years) and the frequency of predictions (daily). We then make predictions with the prophet model we created and the future dataframe:
# Make a future dataframe for 2 yearsgm_forecast = gm_prophet.make_future_dataframe(periods=365 * 2, freq='D')# Make predictionsgm_forecast = gm_prophet.predict(gm_forecast)
Our future dataframes contain the estimated market cap of Tesla and GM for the next two years. We can visualize predictions with the prophet plot function.
gm_prophet.plot(gm_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')plt.title('Market Cap of GM');
The black dots represent the actual values (notice how they stop at the beginning of 2018), the blue line indicates the forecasted values, and the light blue shaded region is the uncertainty (always a critical part of any prediction). The region of uncertainty increases the further out in the future the prediction is made because initial uncertainty propagates and grows over time. This is observed in weather forecasts which get less accurate the further out in time they are made.
We can also inspect changepoints identified by the model. Again, changepoints represent when the time series growth rate significantly changes (goes from increasing to decreasing for example).
tesla_prophet.changepoints[:10]61 2010-09-24122 2010-12-21182 2011-03-18243 2011-06-15304 2011-09-12365 2011-12-07425 2012-03-06486 2012-06-01547 2012-08-28608 2012-11-27
For comparison, we can look at the Google Search Trends for Tesla over this time range to see if the changes line up. We plot the changepoints (vertical lines) and search trends on the same graph:
# Load in the data tesla_search = pd.read_csv('data/tesla_search_terms.csv')# Convert month to a datetimetesla_search['Month'] = pd.to_datetime(tesla_search['Month'])tesla_changepoints = [str(date) for date in tesla_prophet.changepoints]# Plot the search frequencyplt.plot(tesla_search['Month'], tesla_search['Search'], label = 'Searches')# Plot the changepointsplt.vlines(tesla_changepoints, ymin = 0, ymax= 100, colors = 'r', linewidth=0.6, linestyles = 'dashed', label = 'Changepoints')# Formatting of plotplt.grid('off'); plt.ylabel('Relative Search Freq'); plt.legend()plt.title('Tesla Search Terms and Changepoints');
Some of the changepoints in the market value of Tesla align with changes in frequency of Tesla searches, but not all of them. From this, I would say that relative Google search frequency is not a great indicator of stock changes.
We still need to figure out when the market capitalization of Tesla will surpass that of General Motors. Since we have both predictions for the next two years we can plot both companies on the same graph after merging the dataframes. Before merging, we rename the columns to keep track of the data.
gm_names = ['gm_%s' % column for column in gm_forecast.columns]tesla_names = ['tesla_%s' % column for column in tesla_forecast.columns]# Dataframes to mergemerge_gm_forecast = gm_forecast.copy()merge_tesla_forecast = tesla_forecast.copy()# Rename the columnsmerge_gm_forecast.columns = gm_namesmerge_tesla_forecast.columns = tesla_names# Merge the two datasetsforecast = pd.merge(merge_gm_forecast, merge_tesla_forecast, how = 'inner', left_on = 'gm_ds', right_on = 'tesla_ds')# Rename date columnforecast = forecast.rename(columns={'gm_ds': 'Date'}).drop('tesla_ds', axis=1)
First we will plot just the estimate. The estimate (called ‘yhat’ in the prophet package) smooths out some of the noise in the data so it looks a little different than the raw plots. The level of smoothness will depend on the changepoint prior scale — higher priors mean a more flexible model and more ups and downs.
Our model thinks the brief surpassing of GM by Tesla in 2017 was just noise, and it is not until early 2018 that Tesla beats out GM for good in the forecast. The exact date is January 27, 2018, so if that happens, I will gladly take credit for predicting the future!
When making the above graph, we left out the most important part of a forecast: the uncertainty! We can use matplotlib (see notebook) to show the regions of doubt:
This is a better representation of the prediction. It shows the value of both companies is expected to increase, but Tesla will increase more rapidly than General Motors. Again, the uncertainty increases over time as expected for a prediction and the lower bound of Tesla is below the upper bound of GM in 2020 meaning GM might retain the lead.
The last step of the market capitalization analysis is looking at the overall trend and patterns. Prophet allows us to easily visualize the overall trend and the component patterns:
# Plot the trends and patternsgm_prophet.plot_components(gm_forecast)
The trend is pretty clear: GM stock is rising and going to keep rising. The yearly pattern is interesting because it seems to suggest GM increases in value at the end of the year with a long slow decline into the summer. We can try to determine if there is a correlation between the yearly market cap and the average monthly sales of GM over the time period. I first gathered the monthly vehicle sales from Google and then averaged over the months using groupby. This is another critical data science operation, because often we want to compare stats between categories, such as users of a specific age group, or vehicles from one manufacturer. In this case, we want to calculate average sales in each month, so we group the months together and then average the sales.
gm_sales_grouped = gm_sales.groupby('Month').mean()
It does not look like monthly sales are correlated with the market cap. The monthly sales are second highest in August, which is right at the lowest point for the market cap!
Looking at the weekly trend, there does not appear to be any meaningful signal (there are no stock prices recorded on the weekends so we look at the change during the week).This is to be expected as the random walk theory in economics states there is no predictable pattern in stock prices on a daily basis. As evidenced by our analysis, in the long run, stocks tend to increase, but on a day-to-day scale, there is almost no pattern that we can take advantage of even with the best models.
A simple look at the Dow Jones Industrial Average (a market index of the 30 largest companies on the stock exchange) nicely illustrates this point:
Clearly, the message is to go back to 1900 and invest your money! Or in reality, when the market drops, don’t withdraw because it will go back up according to history. On the overall scale, the day-to-day fluctuations are too small to even be seen and if we are thinking like data scientists, we realize that playing daily stocks is foolish compared to investing in the entire market and holding for long periods of time.
Prophet can also be applied to larger-scale data measures, such as Gross Domestic Product, a measure of the overall size of a country’s economy. I made the following forecast by creating prophet models based on the historical GDP of the US and China.
The exact date China will surpass the US in GDP is 2036! This model is limited because of the low frequency of the observations (GDP is measured once per quarter but prophet works best with daily data), but it provides a basic prediction with no macroeconomic knowledge required.
There are many ways to model time-series, from simple linear regression to recurrent neural networks with LSTM cells. Additive Models are useful because they are quick to develop, fast to train, provide interpretable patterns, and make predictions with uncertainties. The capabilities of Prophet are impressive and we have only scratched the surface here. I encourage you to use this article and the notebook to explore some of the data offered by Quandl or your own time series. Stay tuned for future work on time series analysis, and for an application of prophet to my daily life, see my post on using these techniques to model and predict weight change. As a first step in exploring time-series, additive models in Python are the way to go!
As always, I welcome feedback and constructive criticism. I can be reached at wjk68@case.edu.
|
[
{
"code": null,
"e": 213,
"s": 172,
"text": "Additive models for time series modeling"
},
{
"code": null,
"e": 1112,
"s": 213,
"text": "Time series are one of the most common data types encountered in daily life. Financial prices, weather, home energy usage, and even weight are all examples of data that can be collected at regular intervals. Almost every data scientist will encounter time series in their daily work and learning how to model them is an important skill in the data science toolbox. One powerful yet simple method for analyzing and predicting periodic data is the additive model. The idea is straightforward: represent a time-series as a combination of patterns at different scales such as daily, weekly, seasonally, and yearly, along with an overall trend. Your energy use might rise in the summer and decrease in the winter, but have an overall decreasing trend as you increase the energy efficiency of your home. An additive model can show us both patterns/trends and make predictions based on these observations."
},
{
"code": null,
"e": 1242,
"s": 1112,
"text": "The following image shows an additive model decomposition of a time-series into an overall trend, yearly trend, and weekly trend."
},
{
"code": null,
"e": 1810,
"s": 1242,
"text": "This post will walk through an introductory example of creating an additive model for financial time-series data using Python and the Prophet forecasting package developed by Facebook. Along the way, we will cover some data manipulation using pandas, accessing financial data using the Quandl library and, and plotting with matplotlib. I have included code where it is instructive, and I encourage anyone to check out the Jupyter Notebook on GitHub for the full analysis. This introduction will show you all the steps needed to start modeling time-series on your own!"
},
{
"code": null,
"e": 2230,
"s": 1810,
"text": "Disclaimer: Now comes the boring part when I have to mention that when it comes to financial data, past performance is no indicator of future performance and you cannot use the methods here to get rich. I chose to use stock data because it is easily available on a daily frequency and fun to play around with. If you really want to become wealthy, learning data science is a better choice than playing the stock market!"
},
{
"code": null,
"e": 2687,
"s": 2230,
"text": "Usually, about 80% of the time spent on a data science project is getting and cleaning data. Thanks to the quandl financial library, that was reduced to about 5% for this project. Quandl can be installed with pip from the command line, lets you access thousands of financial indicators with a single line of Python, and allows up to 50 requests a day without signing up. If you sign up for a free account, you get an api key that allows unlimited requests."
},
{
"code": null,
"e": 2966,
"s": 2687,
"text": "First, we import the required libraries and get some data. Quandl automatically puts our data into a pandas dataframe, the data structure of choice for data science. (For other companies, just replace the ‘TSLA’ or ‘GM’ with the stock ticker. You can also specify a date range)."
},
{
"code": null,
"e": 3232,
"s": 2966,
"text": "# quandl for financial dataimport quandl# pandas for data manipulationimport pandas as pdquandl.ApiConfig.api_key = 'getyourownkey!'# Retrieve TSLA data from Quandltesla = quandl.get('WIKI/TSLA')# Retrieve the GM data from Quandlgm = quandl.get('WIKI/GM')gm.head(5)"
},
{
"code": null,
"e": 3846,
"s": 3232,
"text": "There is an almost unlimited amount of data on quandl, but I wanted to focus on comparing two companies within the same industry, namely Tesla and General Motors. Tesla is a fascinating company not only because it is the first successful American car start-up in 111 years, but also because at times in 2017 it was the most valuable car company in America despite only selling 4 different cars. The other contender for the title of most valuable car company is General Motors which recently has shown signs of embracing the future of cars by building some pretty cool (but not cool-looking) all-electric vehicles."
},
{
"code": null,
"e": 4026,
"s": 3846,
"text": "We could easily have spent hours searching for this data and downloading it as csv spreadsheet files, but instead, thanks to quandl, we have all the data we need in a few seconds!"
},
{
"code": null,
"e": 4239,
"s": 4026,
"text": "Before we can jump into modeling, it’s best to get an idea of the structure and ranges by making a few exploratory plots. This will also allows us to look for outliers or missing values that need to be corrected."
},
{
"code": null,
"e": 4576,
"s": 4239,
"text": "Pandas dataframes can be easily plotted with matplotlib. If any of the graphing code looks intimidating, don’t worry. I also find matplotlib to be unintuitive and often copy and paste examples from Stack Overflow or documentation to get the graph I want. One of the rules of programming is don’t reinvent a solution that already exists!"
},
{
"code": null,
"e": 4865,
"s": 4576,
"text": "# The adjusted close accounts for stock splits, so that is what we should graphplt.plot(gm.index, gm['Adj. Close'])plt.title('GM Stock Price')plt.ylabel('Price ($)');plt.show()plt.plot(tesla.index, tesla['Adj. Close'], 'r')plt.title('Tesla Stock Price')plt.ylabel('Price ($)');plt.show();"
},
{
"code": null,
"e": 5351,
"s": 4865,
"text": "Comparing the two companies on stock prices alone does not show which is more valuable because the total value of a company (market capitalization) also depends on the number of shares (Market cap= share price * number of shares). Quandl does not have number of shares data, but I was able to find average yearly stock shares for both companies with a quick Google search. Is is not exact, but will be accurate enough for our analysis. Sometimes we have to make do with imperfect data!"
},
{
"code": null,
"e": 5560,
"s": 5351,
"text": "To create a column of market cap in our dataframe,we use a few tricks with pandas, such as moving the index to a column (reset_index) and simultaneously indexing and altering values in the dataframe using ix."
},
{
"code": null,
"e": 6317,
"s": 5560,
"text": "# Yearly average number of shares outstanding for Tesla and GMtesla_shares = {2018: 168e6, 2017: 162e6, 2016: 144e6, 2015: 128e6, 2014: 125e6, 2013: 119e6, 2012: 107e6, 2011: 100e6, 2010: 51e6}gm_shares = {2018: 1.42e9, 2017: 1.50e9, 2016: 1.54e9, 2015: 1.59e9, 2014: 1.61e9, 2013: 1.39e9, 2012: 1.57e9, 2011: 1.54e9, 2010:1.50e9}# Create a year column tesla['Year'] = tesla.index.year# Take Dates from index and move to Date column tesla.reset_index(level=0, inplace = True)tesla['cap'] = 0# Calculate market cap for all yearsfor i, year in enumerate(tesla['Year']): # Retrieve the shares for the year shares = tesla_shares.get(year) # Update the cap column to shares times the price tesla.ix[i, 'cap'] = shares * tesla.ix[i, 'Adj. Close']"
},
{
"code": null,
"e": 6852,
"s": 6317,
"text": "This creates a ‘cap’ column for Tesla. We do the same process with the GM data and then merge the two. Merging is an essential part of a data science workflow because it allows us to join datasets on a shared column. In this case, we have stock prices for two different companies on the same dates and we therefore want to join the data on the date column. We perform an ‘inner’ merge to save only Date entries that are present in both dataframes. After merging, we rename the columns so we know which one goes with which car company."
},
{
"code": null,
"e": 7246,
"s": 6852,
"text": "# Merge the two datasets and rename the columnscars = gm.merge(tesla, how='inner', on='Date')cars.rename(columns={'cap_x': 'gm_cap', 'cap_y': 'tesla_cap'}, inplace=True)# Select only the relevant columnscars = cars.ix[:, ['Date', 'gm_cap', 'tesla_cap']]# Divide to get market cap in billions of dollarscars['gm_cap'] = cars['gm_cap'] / 1e9cars['tesla_cap'] = cars['tesla_cap'] / 1e9cars.head()"
},
{
"code": null,
"e": 7447,
"s": 7246,
"text": "The market cap is in billions of dollars. We can see General Motors started off our period of analysis with a market cap about 30 times that of Tesla! Do things stay that way over the entire timeline?"
},
{
"code": null,
"e": 7708,
"s": 7447,
"text": "plt.figure(figsize=(10, 8))plt.plot(cars['Date'], cars['gm_cap'], 'b-', label = 'GM')plt.plot(cars['Date'], cars['tesla_cap'], 'r-', label = 'TESLA')plt.xlabel('Date'); plt.ylabel('Market Cap (Billions $)'); plt.title('Market Cap of GM and Tesla')plt.legend();"
},
{
"code": null,
"e": 7860,
"s": 7708,
"text": "We observe a meteoric rise for Tesla and a minor increase for General Motors over the course of the data. Tesla even surpasses GM in value during 2017!"
},
{
"code": null,
"e": 8283,
"s": 7860,
"text": "import numpy as np# Find the first and last time Tesla was valued higher than GMfirst_date = cars.ix[np.min(list(np.where(cars['tesla_cap'] > cars['gm_cap'])[0])), 'Date']last_date = cars.ix[np.max(list(np.where(cars['tesla_cap'] > cars['gm_cap'])[0])), 'Date']print(\"Tesla was valued higher than GM from {} to {}.\".format(first_date.date(), last_date.date()))Tesla was valued higher than GM from 2017-04-10 to 2017-09-21."
},
{
"code": null,
"e": 8794,
"s": 8283,
"text": "During that period, Tesla sold about 48,000 cars while GM sold 1,500,000. GM was valued less than Tesla during a period in which it sold 30 times more cars! This definitely displays the power of a persuasive executive and a high-quality — if extremely low-quantity — product. Although the value of Tesla is now lower than GM, a good question might be, can we expect Tesla to again surpass GM? When will this happen? For that we turn to additive models for forecasting, or in other words, predicting the future."
},
{
"code": null,
"e": 9296,
"s": 8794,
"text": "The Facebook Prophet package was released in 2017 for Python and R, and data scientists around the world rejoiced. Prophet is designed for analyzing time series with daily observations that display patterns on different time scales. It also has advanced capabilities for modeling the effects of holidays on a time-series and implementing custom changepoints, but we will stick to the basic functions to get a model up and running. Prophet, like quandl, can be installed with pip from the command line."
},
{
"code": null,
"e": 9564,
"s": 9296,
"text": "We first import prophet and rename the columns in our data to the correct format. The Date column must be called ‘ds’ and the value column we want to predict ‘y’. We then create prophet models and fit them to the data, much like a Scikit-Learn machine learning model:"
},
{
"code": null,
"e": 9854,
"s": 9564,
"text": "import fbprophet# Prophet requires columns ds (Date) and y (value)gm = gm.rename(columns={'Date': 'ds', 'cap': 'y'})# Put market cap in billionsgm['y'] = gm['y'] / 1e9# Make the prophet model and fit on the datagm_prophet = fbprophet.Prophet(changepoint_prior_scale=0.15)gm_prophet.fit(gm)"
},
{
"code": null,
"e": 10221,
"s": 9854,
"text": "When creating the prophet models, I set the changepoint prior to 0.15, up from the default value of 0.05. This hyperparameter is used to control how sensitive the trend is to changes, with a higher value being more sensitive and a lower value less sensitive. This value is used to combat one of the most fundamental trade-offs in machine learning: bias vs. variance."
},
{
"code": null,
"e": 10817,
"s": 10221,
"text": "If we fit too closely to our training data, called overfitting, we have too much variance and our model will not be able to generalize well to new data. On the other hand, if our model does not capture the trends in our training data it is underfitting and has too much bias. When a model is underfitting, increasing the changepoint prior allows more flexibility for the model to fit the data, and if the model is overfitting, decreasing the prior limits the amount of flexibility. The effect of the changepoint prior scale can be illustrated by graphing predictions made with a range of values:"
},
{
"code": null,
"e": 11354,
"s": 10817,
"text": "The higher the changepoint prior scale, the more flexible the model and the closer it fits to the training data. This may seem like exactly what we want, but learning the training data too well can lead to overfitting and an inability to accurately make predictions on new data. We therefore need to find the right balance of fitting the training data and being able to generalize to new data. As stocks vary from day-to-day, and we want our model to capture this, I increased the flexibility after experimenting with a range of values."
},
{
"code": null,
"e": 11800,
"s": 11354,
"text": "In the call to create a prophet model, we can also specify changepoints, which occur when a time-series goes from increasing to decreasing, or from increasing slowly to increasing rapidly (they are located where the rate change in the time series is greatest). Changepoints can correspond to significant events such as product launches or macroeconomic swings in the market. If we do not specify changepoints, prophet will calculate them for us."
},
{
"code": null,
"e": 12062,
"s": 11800,
"text": "To make forecasts, we need to create what is called a future dataframe. We specify the number of future periods to predict (two years) and the frequency of predictions (daily). We then make predictions with the prophet model we created and the future dataframe:"
},
{
"code": null,
"e": 12236,
"s": 12062,
"text": "# Make a future dataframe for 2 yearsgm_forecast = gm_prophet.make_future_dataframe(periods=365 * 2, freq='D')# Make predictionsgm_forecast = gm_prophet.predict(gm_forecast)"
},
{
"code": null,
"e": 12392,
"s": 12236,
"text": "Our future dataframes contain the estimated market cap of Tesla and GM for the next two years. We can visualize predictions with the prophet plot function."
},
{
"code": null,
"e": 12504,
"s": 12392,
"text": "gm_prophet.plot(gm_forecast, xlabel = 'Date', ylabel = 'Market Cap (billions $)')plt.title('Market Cap of GM');"
},
{
"code": null,
"e": 12989,
"s": 12504,
"text": "The black dots represent the actual values (notice how they stop at the beginning of 2018), the blue line indicates the forecasted values, and the light blue shaded region is the uncertainty (always a critical part of any prediction). The region of uncertainty increases the further out in the future the prediction is made because initial uncertainty propagates and grows over time. This is observed in weather forecasts which get less accurate the further out in time they are made."
},
{
"code": null,
"e": 13182,
"s": 12989,
"text": "We can also inspect changepoints identified by the model. Again, changepoints represent when the time series growth rate significantly changes (goes from increasing to decreasing for example)."
},
{
"code": null,
"e": 13374,
"s": 13182,
"text": "tesla_prophet.changepoints[:10]61 2010-09-24122 2010-12-21182 2011-03-18243 2011-06-15304 2011-09-12365 2011-12-07425 2012-03-06486 2012-06-01547 2012-08-28608 2012-11-27"
},
{
"code": null,
"e": 13571,
"s": 13374,
"text": "For comparison, we can look at the Google Search Trends for Tesla over this time range to see if the changes line up. We plot the changepoints (vertical lines) and search trends on the same graph:"
},
{
"code": null,
"e": 14195,
"s": 13571,
"text": "# Load in the data tesla_search = pd.read_csv('data/tesla_search_terms.csv')# Convert month to a datetimetesla_search['Month'] = pd.to_datetime(tesla_search['Month'])tesla_changepoints = [str(date) for date in tesla_prophet.changepoints]# Plot the search frequencyplt.plot(tesla_search['Month'], tesla_search['Search'], label = 'Searches')# Plot the changepointsplt.vlines(tesla_changepoints, ymin = 0, ymax= 100, colors = 'r', linewidth=0.6, linestyles = 'dashed', label = 'Changepoints')# Formatting of plotplt.grid('off'); plt.ylabel('Relative Search Freq'); plt.legend()plt.title('Tesla Search Terms and Changepoints');"
},
{
"code": null,
"e": 14425,
"s": 14195,
"text": "Some of the changepoints in the market value of Tesla align with changes in frequency of Tesla searches, but not all of them. From this, I would say that relative Google search frequency is not a great indicator of stock changes."
},
{
"code": null,
"e": 14724,
"s": 14425,
"text": "We still need to figure out when the market capitalization of Tesla will surpass that of General Motors. Since we have both predictions for the next two years we can plot both companies on the same graph after merging the dataframes. Before merging, we rename the columns to keep track of the data."
},
{
"code": null,
"e": 15300,
"s": 14724,
"text": "gm_names = ['gm_%s' % column for column in gm_forecast.columns]tesla_names = ['tesla_%s' % column for column in tesla_forecast.columns]# Dataframes to mergemerge_gm_forecast = gm_forecast.copy()merge_tesla_forecast = tesla_forecast.copy()# Rename the columnsmerge_gm_forecast.columns = gm_namesmerge_tesla_forecast.columns = tesla_names# Merge the two datasetsforecast = pd.merge(merge_gm_forecast, merge_tesla_forecast, how = 'inner', left_on = 'gm_ds', right_on = 'tesla_ds')# Rename date columnforecast = forecast.rename(columns={'gm_ds': 'Date'}).drop('tesla_ds', axis=1)"
},
{
"code": null,
"e": 15617,
"s": 15300,
"text": "First we will plot just the estimate. The estimate (called ‘yhat’ in the prophet package) smooths out some of the noise in the data so it looks a little different than the raw plots. The level of smoothness will depend on the changepoint prior scale — higher priors mean a more flexible model and more ups and downs."
},
{
"code": null,
"e": 15884,
"s": 15617,
"text": "Our model thinks the brief surpassing of GM by Tesla in 2017 was just noise, and it is not until early 2018 that Tesla beats out GM for good in the forecast. The exact date is January 27, 2018, so if that happens, I will gladly take credit for predicting the future!"
},
{
"code": null,
"e": 16048,
"s": 15884,
"text": "When making the above graph, we left out the most important part of a forecast: the uncertainty! We can use matplotlib (see notebook) to show the regions of doubt:"
},
{
"code": null,
"e": 16393,
"s": 16048,
"text": "This is a better representation of the prediction. It shows the value of both companies is expected to increase, but Tesla will increase more rapidly than General Motors. Again, the uncertainty increases over time as expected for a prediction and the lower bound of Tesla is below the upper bound of GM in 2020 meaning GM might retain the lead."
},
{
"code": null,
"e": 16575,
"s": 16393,
"text": "The last step of the market capitalization analysis is looking at the overall trend and patterns. Prophet allows us to easily visualize the overall trend and the component patterns:"
},
{
"code": null,
"e": 16645,
"s": 16575,
"text": "# Plot the trends and patternsgm_prophet.plot_components(gm_forecast)"
},
{
"code": null,
"e": 17414,
"s": 16645,
"text": "The trend is pretty clear: GM stock is rising and going to keep rising. The yearly pattern is interesting because it seems to suggest GM increases in value at the end of the year with a long slow decline into the summer. We can try to determine if there is a correlation between the yearly market cap and the average monthly sales of GM over the time period. I first gathered the monthly vehicle sales from Google and then averaged over the months using groupby. This is another critical data science operation, because often we want to compare stats between categories, such as users of a specific age group, or vehicles from one manufacturer. In this case, we want to calculate average sales in each month, so we group the months together and then average the sales."
},
{
"code": null,
"e": 17466,
"s": 17414,
"text": "gm_sales_grouped = gm_sales.groupby('Month').mean()"
},
{
"code": null,
"e": 17641,
"s": 17466,
"text": "It does not look like monthly sales are correlated with the market cap. The monthly sales are second highest in August, which is right at the lowest point for the market cap!"
},
{
"code": null,
"e": 18132,
"s": 17641,
"text": "Looking at the weekly trend, there does not appear to be any meaningful signal (there are no stock prices recorded on the weekends so we look at the change during the week).This is to be expected as the random walk theory in economics states there is no predictable pattern in stock prices on a daily basis. As evidenced by our analysis, in the long run, stocks tend to increase, but on a day-to-day scale, there is almost no pattern that we can take advantage of even with the best models."
},
{
"code": null,
"e": 18280,
"s": 18132,
"text": "A simple look at the Dow Jones Industrial Average (a market index of the 30 largest companies on the stock exchange) nicely illustrates this point:"
},
{
"code": null,
"e": 18702,
"s": 18280,
"text": "Clearly, the message is to go back to 1900 and invest your money! Or in reality, when the market drops, don’t withdraw because it will go back up according to history. On the overall scale, the day-to-day fluctuations are too small to even be seen and if we are thinking like data scientists, we realize that playing daily stocks is foolish compared to investing in the entire market and holding for long periods of time."
},
{
"code": null,
"e": 18953,
"s": 18702,
"text": "Prophet can also be applied to larger-scale data measures, such as Gross Domestic Product, a measure of the overall size of a country’s economy. I made the following forecast by creating prophet models based on the historical GDP of the US and China."
},
{
"code": null,
"e": 19233,
"s": 18953,
"text": "The exact date China will surpass the US in GDP is 2036! This model is limited because of the low frequency of the observations (GDP is measured once per quarter but prophet works best with daily data), but it provides a basic prediction with no macroeconomic knowledge required."
},
{
"code": null,
"e": 19978,
"s": 19233,
"text": "There are many ways to model time-series, from simple linear regression to recurrent neural networks with LSTM cells. Additive Models are useful because they are quick to develop, fast to train, provide interpretable patterns, and make predictions with uncertainties. The capabilities of Prophet are impressive and we have only scratched the surface here. I encourage you to use this article and the notebook to explore some of the data offered by Quandl or your own time series. Stay tuned for future work on time series analysis, and for an application of prophet to my daily life, see my post on using these techniques to model and predict weight change. As a first step in exploring time-series, additive models in Python are the way to go!"
}
] |
AngularJS | Factory Method - GeeksforGeeks
|
30 Aug, 2019
AngularJS Factory Method makes the development process of AngularJS application more robust. A factory is a simple function which allows us to add some logic to a created object and return the created object. The factory is also used to create/return a function in the form of reusable code which can be used anywhere within the application. Whenever we create an object using factory it always returns a new instance for that object. The object returned by the factory can be integrated(injectible) with different components of the Angularjs framework such as controller, service, filter or directive.
Use:In practical Scenario Factory generally acts as container or class for a collection of functions which fulfills different features of the application. When using with a constructor function it can be initiated within different Controllers.
Syntax:
module.factory( 'factoryName', function(){ Custom code....});
Example:The Following example illustrate the use of factory code instantiated inside a controller to generate a random number
<!DOCTYPE html><html> <head> <title>Factory Example 1</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <script> var application = angular.module('myApp', []); application.factory('random', function() { var randomObject = {}; var number = Math.floor(Math.random() * 100); randomObject.generate = function() { return number; }; return randomObject; }); application.controller('thisapp', function($scope, random) { $scope.generateRandom = function() { $scope.randomNumber = random.generate(); }; }); </script></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <h2>Factory Examples</h2> <div ng-app="myApp" ng-controller="thisapp"> <button ng-click="generateRandom()"> Generate Random Number </button> <br>{{randomNumber}} </div></body> </html>
Output:
On Clicking the generate random number button we get a different number every time. In this example, we use the factory method to define a function which carries a variable and using the Math.random we store a random value to that variable every time this function is called. This function is then called in the controller whose $scope variable carries the random value from the called function we then call this controller to our HTML code to display the result.
Example: This example make use of factory to create a function to find addition or subtraction of two numbers. this function is then loaded in the controller $scope variable which passes them to the html code for displaying the results.
<!DOCTYPE html><html> <head> <title>Factory Example 2</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <script> var application = angular.module('myApp', []); application.factory('MyFactoryService', function() { var factory = {}; factory.Subtract = function(a, b) { return a - b; }; factory.Add = function(a, b) { return a + b; }; return factory; }); application.controller('thisapp', function( $scope, MyFactoryService) { $scope.result = function() { $scope.results = MyFactoryService.Subtract($scope.num1, $scope.num2) }; $scope.result2 = function() { $scope.results = MyFactoryService.Add($scope.num1, $scope.num2) }; }); </script></head> <body> <h1 style="color:green">GeeksforGeeks</h1> <h2>Factory Example 2</h2> <div ng-app="myApp" ng-controller="thisapp"> <p> Enter A Number: <input type="number" ng-model="num1" /> <br/> Enter A Number: <input type="number" ng-model="num2" /> <br/> </p> <button ng-click="result()">Subtract</button> <button ng-click="result2()">Add</button> <p>Results: {{results}} </div></body> </html>
Output:Before:
After entering the input clicking on the add/subtract button displays the result:
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24650,
"s": 24622,
"text": "\n30 Aug, 2019"
},
{
"code": null,
"e": 25253,
"s": 24650,
"text": "AngularJS Factory Method makes the development process of AngularJS application more robust. A factory is a simple function which allows us to add some logic to a created object and return the created object. The factory is also used to create/return a function in the form of reusable code which can be used anywhere within the application. Whenever we create an object using factory it always returns a new instance for that object. The object returned by the factory can be integrated(injectible) with different components of the Angularjs framework such as controller, service, filter or directive."
},
{
"code": null,
"e": 25497,
"s": 25253,
"text": "Use:In practical Scenario Factory generally acts as container or class for a collection of functions which fulfills different features of the application. When using with a constructor function it can be initiated within different Controllers."
},
{
"code": null,
"e": 25505,
"s": 25497,
"text": "Syntax:"
},
{
"code": null,
"e": 25567,
"s": 25505,
"text": "module.factory( 'factoryName', function(){ Custom code....});"
},
{
"code": null,
"e": 25693,
"s": 25567,
"text": "Example:The Following example illustrate the use of factory code instantiated inside a controller to generate a random number"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Factory Example 1</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <script> var application = angular.module('myApp', []); application.factory('random', function() { var randomObject = {}; var number = Math.floor(Math.random() * 100); randomObject.generate = function() { return number; }; return randomObject; }); application.controller('thisapp', function($scope, random) { $scope.generateRandom = function() { $scope.randomNumber = random.generate(); }; }); </script></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>Factory Examples</h2> <div ng-app=\"myApp\" ng-controller=\"thisapp\"> <button ng-click=\"generateRandom()\"> Generate Random Number </button> <br>{{randomNumber}} </div></body> </html>",
"e": 26706,
"s": 25693,
"text": null
},
{
"code": null,
"e": 26714,
"s": 26706,
"text": "Output:"
},
{
"code": null,
"e": 27178,
"s": 26714,
"text": "On Clicking the generate random number button we get a different number every time. In this example, we use the factory method to define a function which carries a variable and using the Math.random we store a random value to that variable every time this function is called. This function is then called in the controller whose $scope variable carries the random value from the called function we then call this controller to our HTML code to display the result."
},
{
"code": null,
"e": 27415,
"s": 27178,
"text": "Example: This example make use of factory to create a function to find addition or subtraction of two numbers. this function is then loaded in the controller $scope variable which passes them to the html code for displaying the results."
},
{
"code": "<!DOCTYPE html><html> <head> <title>Factory Example 2</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <script> var application = angular.module('myApp', []); application.factory('MyFactoryService', function() { var factory = {}; factory.Subtract = function(a, b) { return a - b; }; factory.Add = function(a, b) { return a + b; }; return factory; }); application.controller('thisapp', function( $scope, MyFactoryService) { $scope.result = function() { $scope.results = MyFactoryService.Subtract($scope.num1, $scope.num2) }; $scope.result2 = function() { $scope.results = MyFactoryService.Add($scope.num1, $scope.num2) }; }); </script></head> <body> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>Factory Example 2</h2> <div ng-app=\"myApp\" ng-controller=\"thisapp\"> <p> Enter A Number: <input type=\"number\" ng-model=\"num1\" /> <br/> Enter A Number: <input type=\"number\" ng-model=\"num2\" /> <br/> </p> <button ng-click=\"result()\">Subtract</button> <button ng-click=\"result2()\">Add</button> <p>Results: {{results}} </div></body> </html>",
"e": 28894,
"s": 27415,
"text": null
},
{
"code": null,
"e": 28909,
"s": 28894,
"text": "Output:Before:"
},
{
"code": null,
"e": 28991,
"s": 28909,
"text": "After entering the input clicking on the add/subtract button displays the result:"
},
{
"code": null,
"e": 28998,
"s": 28991,
"text": "Picked"
},
{
"code": null,
"e": 29008,
"s": 28998,
"text": "AngularJS"
},
{
"code": null,
"e": 29025,
"s": 29008,
"text": "Web Technologies"
},
{
"code": null,
"e": 29123,
"s": 29025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29132,
"s": 29123,
"text": "Comments"
},
{
"code": null,
"e": 29145,
"s": 29132,
"text": "Old Comments"
},
{
"code": null,
"e": 29176,
"s": 29145,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 29218,
"s": 29176,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 29253,
"s": 29218,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 29327,
"s": 29253,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 29380,
"s": 29327,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 29436,
"s": 29380,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 29469,
"s": 29436,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29531,
"s": 29469,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29574,
"s": 29531,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Confusion Matrix for Object Detection | by Kiprono Elijah Koech | Towards Data Science
|
After training a machine learning classifier, the next step is to evaluate its performance using relevant metric(s). The confusion matrix is one of the evaluation metrics.
A confusion matrix is a table showing the performance of a classifier given some truth values/instances (supervised learning kind of).
But calculating of confusion matrix for object detection and instance segmentation tasks is less intuitive. First, it is necessary to understand another supporting metric: Intersection over Union (IoU). A key role in calculating metrics for object detection and instance segmentation tasks is played by Intersection over Union (IoU).
IoU, also called Jaccard index, is a metric that evaluates the overlap between the ground-truth mask (gt) and the predicted mask (pd). In object detection, we can use IoU to determine if a given detection is valid or not.
IoU is calculated as the area of overlap/intersection between gt and pd divided by the area of the union between the two, that is,
Diagrammatically, IoU is defined as shown below:
Note: IoU metric ranges from 0 and 1 with 0 signifying no overlap and 1 implying a perfect overlap between gt and pd.
A confusion matrix is made up of 4 components, namely, True Positive (TP), True Negative (TN), False Positive (FP) and False Negative (FN). To define all the components, we need to define some threshold (say α) based on IoU.
True Positive (TP) — This is an instance in which the classifier predicted positive when the truth is indeed positive, that is, a detection for which IoU ≥ α.
False Positive (FP) — This is a wrong positive detection, that is, a detection for which IoU < α.
False Negative (FN) — This is an actual instance that is not detected by the classifier.
True Negative (TN) — This metric implies a negative detection given that the actual instance is also negative. In object detection, this metric does not apply because there exist many possible predictions that should not be detected in an image. Thus, TN includes all possible wrong detection that were not detected.
These concepts can intuitively be understood with some diagrammatic examples (let's consider the IOU threshold, α = 0.5)
Remark : By the definition of IoU threshold, Fig 3 RIGHT turns to be FP if we choose threshold above 0.86 and Fig 4 RIGHT becomes a TP if we choose IoU threshold below 0.14
Other metrics that can be derived from confusion matrix includes:
Precision is the ability of a classifier to identify only relevant objects. It is the proportion of correct positive predictions and is given by
Recall is a metric which measures the ability of a classifier to find all the relevant cases (that is, all the ground-truths). It is the proportion of true positive detected among all ground-truths and is defined as
F1 score is harmonic mean of precision and recall.
Consider the following image with the ground truths (dark blue) and classifier detections (red). Through observation can you be able to tell the number of TP, FP and FN?
In Python, a confusion matrix can be calculated using Shapely library. The following function ( evaluation(ground,pred,iou_value) → 6-value tuple for TP, FP, FN, Precision, Recall, F1) can be used to determine confusion matrix for above image (Fig 5)
Parameters:
ground — is n × m × 2 array where n is number of the ground truth instances for the given image, m is the number of (x,y) pairs sampled on the circumference of the mask.
pred is p × q × 2 array where p is the number of detections, and q is the number of (x,y) points sampled for the prediction mask
iou_value is the IoU threshold
For Fig 5 and IoU threshold, α = 0.5, evaluation(ground,pred,iou_value) →
TP: 9 FP: 5 FN: 0 GT: 10Precall: 0.643 Recall: 1.0 F1 score: 0.783
Thank you for reading :-)
Join medium on https://medium.com/@kiprono_65591/membership to get full access to every story on Medium.
You can also get the articles into your email inbox whenever I post using this link: https://medium.com/subscribe/@kiprono_65591
Jordi Gene-Mola, Ricardo Sanz-Cortiella, Joan R. Rosell-Polo, Josep-Ramon Morros, Javier Ruiz-Hidalgo, Verónica Vilaplana, & Eduard Gregorio. (2020). Fuji-SfM dataset [Data set]. Zenodo. http://doi.org/10.528/zenodo.3712808
Everingham, M., Eslami, S. A., Van Gool, L., Williams, C. K., Winn, J., and Zisserman, A. The pascal visual object classes challenge: A retrospective. International journal of computer vision, 111(1):98–136, 2015.
Fawcett, T. An introduction to ROC analysis. Pattern recognition letters, 27(8):861–874, 2006.
|
[
{
"code": null,
"e": 344,
"s": 172,
"text": "After training a machine learning classifier, the next step is to evaluate its performance using relevant metric(s). The confusion matrix is one of the evaluation metrics."
},
{
"code": null,
"e": 479,
"s": 344,
"text": "A confusion matrix is a table showing the performance of a classifier given some truth values/instances (supervised learning kind of)."
},
{
"code": null,
"e": 813,
"s": 479,
"text": "But calculating of confusion matrix for object detection and instance segmentation tasks is less intuitive. First, it is necessary to understand another supporting metric: Intersection over Union (IoU). A key role in calculating metrics for object detection and instance segmentation tasks is played by Intersection over Union (IoU)."
},
{
"code": null,
"e": 1035,
"s": 813,
"text": "IoU, also called Jaccard index, is a metric that evaluates the overlap between the ground-truth mask (gt) and the predicted mask (pd). In object detection, we can use IoU to determine if a given detection is valid or not."
},
{
"code": null,
"e": 1166,
"s": 1035,
"text": "IoU is calculated as the area of overlap/intersection between gt and pd divided by the area of the union between the two, that is,"
},
{
"code": null,
"e": 1215,
"s": 1166,
"text": "Diagrammatically, IoU is defined as shown below:"
},
{
"code": null,
"e": 1333,
"s": 1215,
"text": "Note: IoU metric ranges from 0 and 1 with 0 signifying no overlap and 1 implying a perfect overlap between gt and pd."
},
{
"code": null,
"e": 1558,
"s": 1333,
"text": "A confusion matrix is made up of 4 components, namely, True Positive (TP), True Negative (TN), False Positive (FP) and False Negative (FN). To define all the components, we need to define some threshold (say α) based on IoU."
},
{
"code": null,
"e": 1717,
"s": 1558,
"text": "True Positive (TP) — This is an instance in which the classifier predicted positive when the truth is indeed positive, that is, a detection for which IoU ≥ α."
},
{
"code": null,
"e": 1815,
"s": 1717,
"text": "False Positive (FP) — This is a wrong positive detection, that is, a detection for which IoU < α."
},
{
"code": null,
"e": 1904,
"s": 1815,
"text": "False Negative (FN) — This is an actual instance that is not detected by the classifier."
},
{
"code": null,
"e": 2221,
"s": 1904,
"text": "True Negative (TN) — This metric implies a negative detection given that the actual instance is also negative. In object detection, this metric does not apply because there exist many possible predictions that should not be detected in an image. Thus, TN includes all possible wrong detection that were not detected."
},
{
"code": null,
"e": 2342,
"s": 2221,
"text": "These concepts can intuitively be understood with some diagrammatic examples (let's consider the IOU threshold, α = 0.5)"
},
{
"code": null,
"e": 2515,
"s": 2342,
"text": "Remark : By the definition of IoU threshold, Fig 3 RIGHT turns to be FP if we choose threshold above 0.86 and Fig 4 RIGHT becomes a TP if we choose IoU threshold below 0.14"
},
{
"code": null,
"e": 2581,
"s": 2515,
"text": "Other metrics that can be derived from confusion matrix includes:"
},
{
"code": null,
"e": 2726,
"s": 2581,
"text": "Precision is the ability of a classifier to identify only relevant objects. It is the proportion of correct positive predictions and is given by"
},
{
"code": null,
"e": 2942,
"s": 2726,
"text": "Recall is a metric which measures the ability of a classifier to find all the relevant cases (that is, all the ground-truths). It is the proportion of true positive detected among all ground-truths and is defined as"
},
{
"code": null,
"e": 2993,
"s": 2942,
"text": "F1 score is harmonic mean of precision and recall."
},
{
"code": null,
"e": 3163,
"s": 2993,
"text": "Consider the following image with the ground truths (dark blue) and classifier detections (red). Through observation can you be able to tell the number of TP, FP and FN?"
},
{
"code": null,
"e": 3414,
"s": 3163,
"text": "In Python, a confusion matrix can be calculated using Shapely library. The following function ( evaluation(ground,pred,iou_value) → 6-value tuple for TP, FP, FN, Precision, Recall, F1) can be used to determine confusion matrix for above image (Fig 5)"
},
{
"code": null,
"e": 3426,
"s": 3414,
"text": "Parameters:"
},
{
"code": null,
"e": 3596,
"s": 3426,
"text": "ground — is n × m × 2 array where n is number of the ground truth instances for the given image, m is the number of (x,y) pairs sampled on the circumference of the mask."
},
{
"code": null,
"e": 3725,
"s": 3596,
"text": "pred is p × q × 2 array where p is the number of detections, and q is the number of (x,y) points sampled for the prediction mask"
},
{
"code": null,
"e": 3756,
"s": 3725,
"text": "iou_value is the IoU threshold"
},
{
"code": null,
"e": 3830,
"s": 3756,
"text": "For Fig 5 and IoU threshold, α = 0.5, evaluation(ground,pred,iou_value) →"
},
{
"code": null,
"e": 3907,
"s": 3830,
"text": "TP: 9 FP: 5 FN: 0 GT: 10Precall: 0.643 Recall: 1.0 F1 score: 0.783"
},
{
"code": null,
"e": 3933,
"s": 3907,
"text": "Thank you for reading :-)"
},
{
"code": null,
"e": 4038,
"s": 3933,
"text": "Join medium on https://medium.com/@kiprono_65591/membership to get full access to every story on Medium."
},
{
"code": null,
"e": 4167,
"s": 4038,
"text": "You can also get the articles into your email inbox whenever I post using this link: https://medium.com/subscribe/@kiprono_65591"
},
{
"code": null,
"e": 4392,
"s": 4167,
"text": "Jordi Gene-Mola, Ricardo Sanz-Cortiella, Joan R. Rosell-Polo, Josep-Ramon Morros, Javier Ruiz-Hidalgo, Verónica Vilaplana, & Eduard Gregorio. (2020). Fuji-SfM dataset [Data set]. Zenodo. http://doi.org/10.528/zenodo.3712808"
},
{
"code": null,
"e": 4606,
"s": 4392,
"text": "Everingham, M., Eslami, S. A., Van Gool, L., Williams, C. K., Winn, J., and Zisserman, A. The pascal visual object classes challenge: A retrospective. International journal of computer vision, 111(1):98–136, 2015."
}
] |
Bitwise Logical Operations in R - GeeksforGeeks
|
08 May, 2021
Bitwise logical operations are used to perform logical operations bit by bit in a number. This article discusses how bitwise logical operators are used in the R programming language.
The logical operations include:
Let’s discuss these operators in detail.
R programming language uses bitwOr function to perform Bitwise OR operation on two numbers. It will take two values as input and return the value. Where value can be the numbers or lists/vectors.
Example:
2=0010
3=0011
bitwOr(2,3) ---> 0010
& 0011
--------------
0011 ---> 3
Program:
R
# bitwise or for 2 and 3print(bitwOr(2,3)) # bitwise or for 2 and 4print(bitwOr(2,4)) # bitwise or for 2 and 5print(bitwOr(2,5)) # bitwise or for 78 and 0print(bitwOr(78,0))
Output:
[1] 3
[1] 6
[1] 7
[1] 78
bitwOr can also be performed on vectors
Program:
R
s=c(1,2,3,4,5) # s and a are the two vectorsa=c(90,91,92,93,94) # bitwise or operation between# a ans s vector elementsprint(bitwOr(a,s))
Output:
[1] 91 91 95 93 95
In R, we can perform the bitwise xor operation using the function called bitwXor() function. This function takes two data at a time as input and perform the following operation. It converts the numbers into binary values (bits – 0’s and 1’s). Then it returns 0 if both are same, otherwise 1.
Input values can be integers or list/vector.
Example:
5 - 0101
6 - 0110
bitwXOR(5,6) ---> 0101
^ 0110
---------------
0011 ---> 3
Program
R
# range of a values# each value of a with # respect to ba=10:20b=58 for (i in a){ print(bitwXor(i,b))}
Output:
[1] 48
[1] 49
[1] 54
[1] 55
[1] 52
[1] 53
[1] 42
[1] 43
[1] 40
[1] 41
[1] 46
Bitwise not operator is used to return the inverse value of the given number i.e. if 0 then 1, if 1 then 0. In R, we can find bitwise not of the given number using function called bitwNot(). The input for this function can also be an integer, vector, matrix , list etc..
Example:
6- 0110
bitwNot(6) ----> 0110
+ 1
-----------
0111 ---> -7
Program
R
a=3b=6 # bitwise on 3print(bitwNot(a)) # bitwise on 6print(bitwNot(b))print("----------------") # consider values from 1 to 15 # to perform this operationvalues=1:15for (i in values){ print(bitwNot(i))}
Output:
[1] -4
[1] -7
[1] "----------------"
[1] -2
[1] -3
[1] -4
[1] -5
[1] -6
[1] -7
[1] -8
[1] -9
[1] -10
[1] -11
[1] -12
[1] -13
[1] -14
[1] -15
[1] -16
This can also be applied to vectors.
Program
Python
# create two vectors a and# b with elementsa=c(7058,7059,7056)b=c(34,45,63) # bitwise on vector aprint(bitwNot(a)) # bitwise on vector bprint(bitwNot(b))
Output:
[1] -7059 -7060 -7057
[1] -35 -46 -64
R language uses bitwAnd function to perform bitwise and operation. Where input values can be integers or list/vector.
Example:
3 - 0011
4 - 0100
bitwAnd(3,4) ----> 0011
& 0100
--------------
0000 ---> 0
Program
R
# bitwise operator between 4 and 3print(bitwAnd(4,3)) # bitwise operator between 4 and 7print(bitwAnd(4,7)) # bitwise operator between 1and 4print(bitwAnd(1,4)) # bitwise operator between 56 and 8print(bitwAnd(56,8)) # bitwise operator between 4 and 0print(bitwAnd(4,0))
Output:
[1] 0
[1] 4
[1] 0
[1] 8
[1] 0
bitwise AND can also be performed on vectors.
Program
R
s=c(1,2,3,4,5) # s and a are the two vectorsa=c(90,91,92,93,94) # bitwise And operation between# a ans s vector elementsprint(bitwAnd(s,a))
Output:
[1] 0 2 0 4 4
R language uses bitwShiftL function to perform bitwise left shift operation. The input to the function is shift value and an integer/vector/list
Formula:
N*(2^i)
Where N is the given number and i is the number of shifts.
Example:
bitwShiftL(1,4) - N=1 and i=4
so, N*(2^i)
1*(2^4)=16
Program
R
# shift 4 by 1 bitbitwShiftL(1,4) # shift 4 by 2 bitbitwShiftL(2,4) # shift 4 by 3 bitbitwShiftL(3,4) # shift 4 by 4 bitbitwShiftL(4,4) # shift 4 by 5 bitbitwShiftL(5,4)
Output:
16
32
48
64
80
It will perform the right shift operation. It will shift the bits from left to right.
Formula:
N*(2/i)
where N is the given number and i is the no of right shifts.
Example:
bitShiftR(4,1)
here N=4 and i=1
so 4*(2/1)=8
Program
R
# shift 1 by 4 bitbitwShiftR(1,4) # shift 4 by 2 bitbitwShiftR(4,2) # shift 4 by 3 bitbitwShiftR(3,4) # shift 16 by 2 bitbitwShiftR(16,2) # shift 8 by 2 bitbitwShiftR(8,2)
Output:
0
1
0
4
2
R-basics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n08 May, 2021"
},
{
"code": null,
"e": 25425,
"s": 25242,
"text": "Bitwise logical operations are used to perform logical operations bit by bit in a number. This article discusses how bitwise logical operators are used in the R programming language."
},
{
"code": null,
"e": 25457,
"s": 25425,
"text": "The logical operations include:"
},
{
"code": null,
"e": 25498,
"s": 25457,
"text": "Let’s discuss these operators in detail."
},
{
"code": null,
"e": 25694,
"s": 25498,
"text": "R programming language uses bitwOr function to perform Bitwise OR operation on two numbers. It will take two values as input and return the value. Where value can be the numbers or lists/vectors."
},
{
"code": null,
"e": 25703,
"s": 25694,
"text": "Example:"
},
{
"code": null,
"e": 25830,
"s": 25703,
"text": "2=0010\n3=0011\nbitwOr(2,3) ---> 0010\n & 0011\n --------------\n 0011 ---> 3"
},
{
"code": null,
"e": 25839,
"s": 25830,
"text": "Program:"
},
{
"code": null,
"e": 25841,
"s": 25839,
"text": "R"
},
{
"code": "# bitwise or for 2 and 3print(bitwOr(2,3)) # bitwise or for 2 and 4print(bitwOr(2,4)) # bitwise or for 2 and 5print(bitwOr(2,5)) # bitwise or for 78 and 0print(bitwOr(78,0))",
"e": 26018,
"s": 25841,
"text": null
},
{
"code": null,
"e": 26026,
"s": 26018,
"text": "Output:"
},
{
"code": null,
"e": 26051,
"s": 26026,
"text": "[1] 3\n[1] 6\n[1] 7\n[1] 78"
},
{
"code": null,
"e": 26091,
"s": 26051,
"text": "bitwOr can also be performed on vectors"
},
{
"code": null,
"e": 26100,
"s": 26091,
"text": "Program:"
},
{
"code": null,
"e": 26102,
"s": 26100,
"text": "R"
},
{
"code": "s=c(1,2,3,4,5) # s and a are the two vectorsa=c(90,91,92,93,94) # bitwise or operation between# a ans s vector elementsprint(bitwOr(a,s))",
"e": 26242,
"s": 26102,
"text": null
},
{
"code": null,
"e": 26250,
"s": 26242,
"text": "Output:"
},
{
"code": null,
"e": 26269,
"s": 26250,
"text": "[1] 91 91 95 93 95"
},
{
"code": null,
"e": 26561,
"s": 26269,
"text": "In R, we can perform the bitwise xor operation using the function called bitwXor() function. This function takes two data at a time as input and perform the following operation. It converts the numbers into binary values (bits – 0’s and 1’s). Then it returns 0 if both are same, otherwise 1."
},
{
"code": null,
"e": 26606,
"s": 26561,
"text": "Input values can be integers or list/vector."
},
{
"code": null,
"e": 26615,
"s": 26606,
"text": "Example:"
},
{
"code": null,
"e": 26746,
"s": 26615,
"text": "5 - 0101\n6 - 0110\nbitwXOR(5,6) ---> 0101\n ^ 0110\n ---------------\n 0011 ---> 3"
},
{
"code": null,
"e": 26754,
"s": 26746,
"text": "Program"
},
{
"code": null,
"e": 26756,
"s": 26754,
"text": "R"
},
{
"code": "# range of a values# each value of a with # respect to ba=10:20b=58 for (i in a){ print(bitwXor(i,b))}",
"e": 26863,
"s": 26756,
"text": null
},
{
"code": null,
"e": 26871,
"s": 26863,
"text": "Output:"
},
{
"code": null,
"e": 26948,
"s": 26871,
"text": "[1] 48\n[1] 49\n[1] 54\n[1] 55\n[1] 52\n[1] 53\n[1] 42\n[1] 43\n[1] 40\n[1] 41\n[1] 46"
},
{
"code": null,
"e": 27219,
"s": 26948,
"text": "Bitwise not operator is used to return the inverse value of the given number i.e. if 0 then 1, if 1 then 0. In R, we can find bitwise not of the given number using function called bitwNot(). The input for this function can also be an integer, vector, matrix , list etc.."
},
{
"code": null,
"e": 27228,
"s": 27219,
"text": "Example:"
},
{
"code": null,
"e": 27350,
"s": 27228,
"text": "6- 0110\nbitwNot(6) ----> 0110\n + 1\n -----------\n 0111 ---> -7"
},
{
"code": null,
"e": 27358,
"s": 27350,
"text": "Program"
},
{
"code": null,
"e": 27360,
"s": 27358,
"text": "R"
},
{
"code": "a=3b=6 # bitwise on 3print(bitwNot(a)) # bitwise on 6print(bitwNot(b))print(\"----------------\") # consider values from 1 to 15 # to perform this operationvalues=1:15for (i in values){ print(bitwNot(i))}",
"e": 27569,
"s": 27360,
"text": null
},
{
"code": null,
"e": 27577,
"s": 27569,
"text": "Output:"
},
{
"code": null,
"e": 27726,
"s": 27577,
"text": "[1] -4\n[1] -7\n[1] \"----------------\"\n[1] -2\n[1] -3\n[1] -4\n[1] -5\n[1] -6\n[1] -7\n[1] -8\n[1] -9\n[1] -10\n[1] -11\n[1] -12\n[1] -13\n[1] -14\n[1] -15\n[1] -16"
},
{
"code": null,
"e": 27763,
"s": 27726,
"text": "This can also be applied to vectors."
},
{
"code": null,
"e": 27771,
"s": 27763,
"text": "Program"
},
{
"code": null,
"e": 27778,
"s": 27771,
"text": "Python"
},
{
"code": "# create two vectors a and# b with elementsa=c(7058,7059,7056)b=c(34,45,63) # bitwise on vector aprint(bitwNot(a)) # bitwise on vector bprint(bitwNot(b))",
"e": 27935,
"s": 27778,
"text": null
},
{
"code": null,
"e": 27943,
"s": 27935,
"text": "Output:"
},
{
"code": null,
"e": 27981,
"s": 27943,
"text": "[1] -7059 -7060 -7057\n[1] -35 -46 -64"
},
{
"code": null,
"e": 28099,
"s": 27981,
"text": "R language uses bitwAnd function to perform bitwise and operation. Where input values can be integers or list/vector."
},
{
"code": null,
"e": 28108,
"s": 28099,
"text": "Example:"
},
{
"code": null,
"e": 28247,
"s": 28108,
"text": "3 - 0011\n4 - 0100\nbitwAnd(3,4) ----> 0011\n & 0100\n --------------\n 0000 ---> 0"
},
{
"code": null,
"e": 28255,
"s": 28247,
"text": "Program"
},
{
"code": null,
"e": 28257,
"s": 28255,
"text": "R"
},
{
"code": "# bitwise operator between 4 and 3print(bitwAnd(4,3)) # bitwise operator between 4 and 7print(bitwAnd(4,7)) # bitwise operator between 1and 4print(bitwAnd(1,4)) # bitwise operator between 56 and 8print(bitwAnd(56,8)) # bitwise operator between 4 and 0print(bitwAnd(4,0))",
"e": 28533,
"s": 28257,
"text": null
},
{
"code": null,
"e": 28541,
"s": 28533,
"text": "Output:"
},
{
"code": null,
"e": 28571,
"s": 28541,
"text": "[1] 0\n[1] 4\n[1] 0\n[1] 8\n[1] 0"
},
{
"code": null,
"e": 28617,
"s": 28571,
"text": "bitwise AND can also be performed on vectors."
},
{
"code": null,
"e": 28625,
"s": 28617,
"text": "Program"
},
{
"code": null,
"e": 28627,
"s": 28625,
"text": "R"
},
{
"code": "s=c(1,2,3,4,5) # s and a are the two vectorsa=c(90,91,92,93,94) # bitwise And operation between# a ans s vector elementsprint(bitwAnd(s,a))",
"e": 28769,
"s": 28627,
"text": null
},
{
"code": null,
"e": 28777,
"s": 28769,
"text": "Output:"
},
{
"code": null,
"e": 28791,
"s": 28777,
"text": "[1] 0 2 0 4 4"
},
{
"code": null,
"e": 28936,
"s": 28791,
"text": "R language uses bitwShiftL function to perform bitwise left shift operation. The input to the function is shift value and an integer/vector/list"
},
{
"code": null,
"e": 28945,
"s": 28936,
"text": "Formula:"
},
{
"code": null,
"e": 28953,
"s": 28945,
"text": "N*(2^i)"
},
{
"code": null,
"e": 29012,
"s": 28953,
"text": "Where N is the given number and i is the number of shifts."
},
{
"code": null,
"e": 29021,
"s": 29012,
"text": "Example:"
},
{
"code": null,
"e": 29074,
"s": 29021,
"text": "bitwShiftL(1,4) - N=1 and i=4\nso, N*(2^i)\n1*(2^4)=16"
},
{
"code": null,
"e": 29082,
"s": 29074,
"text": "Program"
},
{
"code": null,
"e": 29084,
"s": 29082,
"text": "R"
},
{
"code": "# shift 4 by 1 bitbitwShiftL(1,4) # shift 4 by 2 bitbitwShiftL(2,4) # shift 4 by 3 bitbitwShiftL(3,4) # shift 4 by 4 bitbitwShiftL(4,4) # shift 4 by 5 bitbitwShiftL(5,4)",
"e": 29258,
"s": 29084,
"text": null
},
{
"code": null,
"e": 29266,
"s": 29258,
"text": "Output:"
},
{
"code": null,
"e": 29281,
"s": 29266,
"text": "16\n32\n48\n64\n80"
},
{
"code": null,
"e": 29367,
"s": 29281,
"text": "It will perform the right shift operation. It will shift the bits from left to right."
},
{
"code": null,
"e": 29376,
"s": 29367,
"text": "Formula:"
},
{
"code": null,
"e": 29384,
"s": 29376,
"text": "N*(2/i)"
},
{
"code": null,
"e": 29445,
"s": 29384,
"text": "where N is the given number and i is the no of right shifts."
},
{
"code": null,
"e": 29454,
"s": 29445,
"text": "Example:"
},
{
"code": null,
"e": 29499,
"s": 29454,
"text": "bitShiftR(4,1)\nhere N=4 and i=1\nso 4*(2/1)=8"
},
{
"code": null,
"e": 29507,
"s": 29499,
"text": "Program"
},
{
"code": null,
"e": 29509,
"s": 29507,
"text": "R"
},
{
"code": "# shift 1 by 4 bitbitwShiftR(1,4) # shift 4 by 2 bitbitwShiftR(4,2) # shift 4 by 3 bitbitwShiftR(3,4) # shift 16 by 2 bitbitwShiftR(16,2) # shift 8 by 2 bitbitwShiftR(8,2)",
"e": 29685,
"s": 29509,
"text": null
},
{
"code": null,
"e": 29693,
"s": 29685,
"text": "Output:"
},
{
"code": null,
"e": 29703,
"s": 29693,
"text": "0\n1\n0\n4\n2"
},
{
"code": null,
"e": 29712,
"s": 29703,
"text": "R-basics"
},
{
"code": null,
"e": 29723,
"s": 29712,
"text": "R Language"
},
{
"code": null,
"e": 29821,
"s": 29723,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29873,
"s": 29821,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29911,
"s": 29873,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29946,
"s": 29911,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30004,
"s": 29946,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30053,
"s": 30004,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30090,
"s": 30053,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 30140,
"s": 30090,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 30183,
"s": 30140,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30209,
"s": 30183,
"text": "Time Series Analysis in R"
}
] |
Can you extend a static inner class in Java?
|
A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.
You can extend static inner class with another inner class.
Live Demo
public class SampleClass {
static abstract class Test{
int num = 300;
public abstract void display();
}
class DemoClass extends Test{
public void display() {
System.out.println("Hi how are you");
}
}
public static void main(String args[]){
SampleClass obj = new SampleClass();
obj.new DemoClass().display();
}
}
Hi how are you
|
[
{
"code": null,
"e": 1359,
"s": 1062,
"text": "A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class."
},
{
"code": null,
"e": 1419,
"s": 1359,
"text": "You can extend static inner class with another inner class."
},
{
"code": null,
"e": 1430,
"s": 1419,
"text": " Live Demo"
},
{
"code": null,
"e": 1805,
"s": 1430,
"text": "public class SampleClass {\n static abstract class Test{\n int num = 300;\n public abstract void display();\n }\n class DemoClass extends Test{\n public void display() {\n System.out.println(\"Hi how are you\");\n }\n }\n public static void main(String args[]){\n SampleClass obj = new SampleClass();\n obj.new DemoClass().display();\n }\n}"
},
{
"code": null,
"e": 1821,
"s": 1805,
"text": "Hi how are you\n"
}
] |
Check if a number is Fermat Pseudoprime - GeeksforGeeks
|
07 May, 2021
Given a number N and a base number A. The task is to check whether the number is a Fermat Pseudoprime to the base. The number N is called as Fermat Pseudoprime to the base A, if
1. A > 1 2. N is a composite number 3. N divides AN-1 – 1.
Examples:
Input : N = 645, a = 2 Output :1 645 = 3*5*43, Hence it is a composite number Also 645 divides 2^(644)-1 Hence it is a Fermat Pseudoprime.Input : N = 6, a = 2 Output :0
Approach: The approach is to check the below conditions:
Check if A > 1.
Check if N is a composite number.
Check if N divides AN-1 – 1.
If all of the above conditions satisfy then N is a fermat pseudoprime to base A.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if N is Fermat pseudoprime// to the base A or not#include <bits/stdc++.h>using namespace std; // Function to check if the given number is compositebool checkcomposite(int n){ // Check if there is any divisor of n less than sqrt(n) for (int i = 2; i <= sqrt(n); i++) { if (n % i == 0) return 1; } return 0;} // Effectively calculate (x^y) modulo modint power(int x, int y, int mod){ // Initialize result int res = 1; while (y) { // If power is odd, then update the answer if (y & 1) res = (res * x) % mod; // Square the number and reduce // the power to its half y = y >> 1; x = (x * x) % mod; } // Return the result return res;} // Function to check for Fermat Pseudoprimebool Check(int n, int a){ // If it is composite and satisfy Fermat criterion if (a>1 && checkcomposite(n) && power(a, n - 1, n) == 1) return 1; // Else return 0 return 0;} // Driver codeint main(){ int N = 645; int a = 2; // Function call cout << Check(N, a); return 0;}
// Java program to check if N is Fermat pseudoprime// to the base A or notclass GFG{ // Function to check if // the given number is composite static boolean checkcomposite(int n) { // Check if there is any divisor of n // less than sqrt(n) for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return true; } } return false; } // Effectively calculate (x^y) modulo mod static int power(int x, int y, int mod) { // Initialize result int res = 1; while (y != 0) { // If power is odd, // then update the answer if ((y & 1) == 1) { res = (res * x) % mod; } // Square the number and reduce // the power to its half y = y >> 1; x = (x * x) % mod; } // Return the result return res; } // Function to check for Fermat Pseudoprime static int Check(int n, int a) { // If it is composite and // satisfy Fermat criterion if (a > 1 && checkcomposite(n) && power(a, n - 1, n) == 1) { return 1; } // Else return 0 return 0; } // Driver Code public static void main(String[] args) { int N = 645; int a = 2; // Function call System.out.println(Check(N, a)); }} // This code is contributed by 29AjayKumar
# Python3 program to check if N is Fermat pseudoprime# to the base A or not from math import sqrt # Function to check if the given number is compositedef checkcomposite(n): # Check if there is any divisor of n less than sqrt(n) for i in range(2,int(sqrt(n))+1,1): if (n % i == 0): return 1 return 0 # Effectively calculate (x^y) modulo moddef power(x, y, mod): # Initialize result res = 1 while (y): # If power is odd, then update the answer if (y & 1): res = (res * x) % mod # Square the number and reduce # the power to its half y = y >> 1 x = (x * x) % mod # Return the result return res # Function to check for Fermat Pseudoprimedef Check(n,a): # If it is composite and satisfy Fermat criterion if (a>1 and checkcomposite(n) and power(a, n - 1, n) == 1): return 1 # Else return 0 return 0 # Driver codeif __name__ == '__main__': N = 645 a = 2 # Function call print(Check(N, a)) # This code is contributed by# Surendra_Gangwar
// C# program to check if N is Fermat pseudoprime// to the base A or notusing System; class GFG{ // Function to check if // the given number is composite static bool checkcomposite(int n) { // Check if there is any divisor of n // less than sqrt(n) for (int i = 2; i <= Math.Sqrt(n); i++) { if (n % i == 0) return true; } return false; } // Effectively calculate (x^y) modulo mod static int power(int x, int y, int mod) { // Initialize result int res = 1; while (y != 0) { // If power is odd, then update the answer if ((y & 1) == 1) res = (res * x) % mod; // Square the number and reduce // the power to its half y = y >> 1; x = (x * x) % mod; } // Return the result return res; } // Function to check for Fermat Pseudoprime static int Check(int n, int a) { // If it is composite and satisfy Fermat criterion if (a > 1 && checkcomposite(n) && power(a, n - 1, n) == 1) return 1; // Else return 0 return 0; } // Driver code static public void Main () { int N = 645; int a = 2; // Function call Console.WriteLine(Check(N, a)); }} // This code is contributed by AnkitRai01
<script> // Javascript program to check if// N is Fermat pseudoprime// to the base A or not // Function to check if the given// number is compositefunction checkcomposite(n){ // Check if there is any divisor // of n less than sqrt(n) for (let i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return 1; } return 0;} // Effectively calculate (x^y) modulo modfunction power(x, y, mod){ // Initialize result let res = 1; while (y) { // If power is odd, then update the answer if (y & 1) res = (res * x) % mod; // Square the number and reduce // the power to its half y = y >> 1; x = (x * x) % mod; } // Return the result return res;} // Function to check for Fermat Pseudoprimefunction Check(n, a){ // If it is composite and satisfy // Fermat criterion if (a>1 && checkcomposite(n) && power(a, n - 1, n) == 1) return 1; // Else return 0 return 0;} // Driver code let N = 645; let a = 2; // Function call document.write(Check(N, a)); </script>
1
Time Complexity : O(sqrt(N))
SURENDRA_GANGWAR
ankthon
29AjayKumar
harshit23
nidhi_biet
rishavmahato348
Numbers
Mathematical
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Sieve of Eratosthenes
Euclidean algorithms (Basic and Extended)
Algorithm to solve Rubik's Cube
|
[
{
"code": null,
"e": 25188,
"s": 25160,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 25368,
"s": 25188,
"text": "Given a number N and a base number A. The task is to check whether the number is a Fermat Pseudoprime to the base. The number N is called as Fermat Pseudoprime to the base A, if "
},
{
"code": null,
"e": 25429,
"s": 25368,
"text": "1. A > 1 2. N is a composite number 3. N divides AN-1 – 1. "
},
{
"code": null,
"e": 25441,
"s": 25429,
"text": "Examples: "
},
{
"code": null,
"e": 25612,
"s": 25441,
"text": "Input : N = 645, a = 2 Output :1 645 = 3*5*43, Hence it is a composite number Also 645 divides 2^(644)-1 Hence it is a Fermat Pseudoprime.Input : N = 6, a = 2 Output :0 "
},
{
"code": null,
"e": 25673,
"s": 25614,
"text": "Approach: The approach is to check the below conditions: "
},
{
"code": null,
"e": 25689,
"s": 25673,
"text": "Check if A > 1."
},
{
"code": null,
"e": 25723,
"s": 25689,
"text": "Check if N is a composite number."
},
{
"code": null,
"e": 25752,
"s": 25723,
"text": "Check if N divides AN-1 – 1."
},
{
"code": null,
"e": 25885,
"s": 25752,
"text": "If all of the above conditions satisfy then N is a fermat pseudoprime to base A.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25889,
"s": 25885,
"text": "C++"
},
{
"code": null,
"e": 25894,
"s": 25889,
"text": "Java"
},
{
"code": null,
"e": 25902,
"s": 25894,
"text": "Python3"
},
{
"code": null,
"e": 25905,
"s": 25902,
"text": "C#"
},
{
"code": null,
"e": 25916,
"s": 25905,
"text": "Javascript"
},
{
"code": "// C++ program to check if N is Fermat pseudoprime// to the base A or not#include <bits/stdc++.h>using namespace std; // Function to check if the given number is compositebool checkcomposite(int n){ // Check if there is any divisor of n less than sqrt(n) for (int i = 2; i <= sqrt(n); i++) { if (n % i == 0) return 1; } return 0;} // Effectively calculate (x^y) modulo modint power(int x, int y, int mod){ // Initialize result int res = 1; while (y) { // If power is odd, then update the answer if (y & 1) res = (res * x) % mod; // Square the number and reduce // the power to its half y = y >> 1; x = (x * x) % mod; } // Return the result return res;} // Function to check for Fermat Pseudoprimebool Check(int n, int a){ // If it is composite and satisfy Fermat criterion if (a>1 && checkcomposite(n) && power(a, n - 1, n) == 1) return 1; // Else return 0 return 0;} // Driver codeint main(){ int N = 645; int a = 2; // Function call cout << Check(N, a); return 0;}",
"e": 27032,
"s": 25916,
"text": null
},
{
"code": "// Java program to check if N is Fermat pseudoprime// to the base A or notclass GFG{ // Function to check if // the given number is composite static boolean checkcomposite(int n) { // Check if there is any divisor of n // less than sqrt(n) for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return true; } } return false; } // Effectively calculate (x^y) modulo mod static int power(int x, int y, int mod) { // Initialize result int res = 1; while (y != 0) { // If power is odd, // then update the answer if ((y & 1) == 1) { res = (res * x) % mod; } // Square the number and reduce // the power to its half y = y >> 1; x = (x * x) % mod; } // Return the result return res; } // Function to check for Fermat Pseudoprime static int Check(int n, int a) { // If it is composite and // satisfy Fermat criterion if (a > 1 && checkcomposite(n) && power(a, n - 1, n) == 1) { return 1; } // Else return 0 return 0; } // Driver Code public static void main(String[] args) { int N = 645; int a = 2; // Function call System.out.println(Check(N, a)); }} // This code is contributed by 29AjayKumar",
"e": 28544,
"s": 27032,
"text": null
},
{
"code": "# Python3 program to check if N is Fermat pseudoprime# to the base A or not from math import sqrt # Function to check if the given number is compositedef checkcomposite(n): # Check if there is any divisor of n less than sqrt(n) for i in range(2,int(sqrt(n))+1,1): if (n % i == 0): return 1 return 0 # Effectively calculate (x^y) modulo moddef power(x, y, mod): # Initialize result res = 1 while (y): # If power is odd, then update the answer if (y & 1): res = (res * x) % mod # Square the number and reduce # the power to its half y = y >> 1 x = (x * x) % mod # Return the result return res # Function to check for Fermat Pseudoprimedef Check(n,a): # If it is composite and satisfy Fermat criterion if (a>1 and checkcomposite(n) and power(a, n - 1, n) == 1): return 1 # Else return 0 return 0 # Driver codeif __name__ == '__main__': N = 645 a = 2 # Function call print(Check(N, a)) # This code is contributed by# Surendra_Gangwar",
"e": 29610,
"s": 28544,
"text": null
},
{
"code": "// C# program to check if N is Fermat pseudoprime// to the base A or notusing System; class GFG{ // Function to check if // the given number is composite static bool checkcomposite(int n) { // Check if there is any divisor of n // less than sqrt(n) for (int i = 2; i <= Math.Sqrt(n); i++) { if (n % i == 0) return true; } return false; } // Effectively calculate (x^y) modulo mod static int power(int x, int y, int mod) { // Initialize result int res = 1; while (y != 0) { // If power is odd, then update the answer if ((y & 1) == 1) res = (res * x) % mod; // Square the number and reduce // the power to its half y = y >> 1; x = (x * x) % mod; } // Return the result return res; } // Function to check for Fermat Pseudoprime static int Check(int n, int a) { // If it is composite and satisfy Fermat criterion if (a > 1 && checkcomposite(n) && power(a, n - 1, n) == 1) return 1; // Else return 0 return 0; } // Driver code static public void Main () { int N = 645; int a = 2; // Function call Console.WriteLine(Check(N, a)); }} // This code is contributed by AnkitRai01",
"e": 31076,
"s": 29610,
"text": null
},
{
"code": "<script> // Javascript program to check if// N is Fermat pseudoprime// to the base A or not // Function to check if the given// number is compositefunction checkcomposite(n){ // Check if there is any divisor // of n less than sqrt(n) for (let i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return 1; } return 0;} // Effectively calculate (x^y) modulo modfunction power(x, y, mod){ // Initialize result let res = 1; while (y) { // If power is odd, then update the answer if (y & 1) res = (res * x) % mod; // Square the number and reduce // the power to its half y = y >> 1; x = (x * x) % mod; } // Return the result return res;} // Function to check for Fermat Pseudoprimefunction Check(n, a){ // If it is composite and satisfy // Fermat criterion if (a>1 && checkcomposite(n) && power(a, n - 1, n) == 1) return 1; // Else return 0 return 0;} // Driver code let N = 645; let a = 2; // Function call document.write(Check(N, a)); </script>",
"e": 32176,
"s": 31076,
"text": null
},
{
"code": null,
"e": 32178,
"s": 32176,
"text": "1"
},
{
"code": null,
"e": 32210,
"s": 32180,
"text": "Time Complexity : O(sqrt(N)) "
},
{
"code": null,
"e": 32227,
"s": 32210,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 32235,
"s": 32227,
"text": "ankthon"
},
{
"code": null,
"e": 32247,
"s": 32235,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32257,
"s": 32247,
"text": "harshit23"
},
{
"code": null,
"e": 32268,
"s": 32257,
"text": "nidhi_biet"
},
{
"code": null,
"e": 32284,
"s": 32268,
"text": "rishavmahato348"
},
{
"code": null,
"e": 32292,
"s": 32284,
"text": "Numbers"
},
{
"code": null,
"e": 32305,
"s": 32292,
"text": "Mathematical"
},
{
"code": null,
"e": 32318,
"s": 32305,
"text": "Mathematical"
},
{
"code": null,
"e": 32326,
"s": 32318,
"text": "Numbers"
},
{
"code": null,
"e": 32424,
"s": 32326,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32433,
"s": 32424,
"text": "Comments"
},
{
"code": null,
"e": 32446,
"s": 32433,
"text": "Old Comments"
},
{
"code": null,
"e": 32488,
"s": 32446,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 32512,
"s": 32488,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 32555,
"s": 32512,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 32569,
"s": 32555,
"text": "Prime Numbers"
},
{
"code": null,
"e": 32618,
"s": 32569,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32652,
"s": 32618,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 32673,
"s": 32652,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 32695,
"s": 32673,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 32737,
"s": 32695,
"text": "Euclidean algorithms (Basic and Extended)"
}
] |
SQLite - WHERE Clause
|
SQLite WHERE clause is used to specify a condition while fetching the data from one table or multiple tables.
If the given condition is satisfied, means true, then it returns the specific value from the table. You will have to use WHERE clause to filter the records and fetching only necessary records.
The WHERE clause not only is used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which will be covered in subsequent chapters.
Following is the basic syntax of SQLite SELECT statement with WHERE clause.
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
You can specify a condition using Comparision or Logical Operators such as >, <, =, LIKE, NOT, etc. Consider COMPANY table with the following records −
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following is a simple examples showing the usage of SQLite Logical Operators. Following SELECT statement lists down all the records where AGE is greater than or equal to 25 AND salary is greater than or equal to 65000.00.
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00.
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE is not NULL, which means all the records because none of the record has AGE equal to NULL.
sqlite> SELECT * FROM COMPANY WHERE AGE IS NOT NULL;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'.
sqlite> SELECT * FROM COMPANY WHERE NAME LIKE 'Ki%';
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
6 Kim 22 South-Hall 45000.0
Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'.
sqlite> SELECT * FROM COMPANY WHERE NAME GLOB 'Ki*';
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
6 Kim 22 South-Hall 45000.0
Following SELECT statement lists down all the records where AGE value is either 25 or 27.
sqlite> SELECT * FROM COMPANY WHERE AGE IN ( 25, 27 );
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement lists down all the records where AGE value is neither 25 nor 27.
sqlite> SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 );
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
3 Teddy 23 Norway 20000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
Following SELECT statement lists down all the records where AGE value is in BETWEEN 25 AND 27.
sqlite> SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27;
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
2 Allen 25 Texas 15000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
Following SELECT statement makes use of SQL sub-query, where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with EXISTS operator to list down all the records where AGE from the outside query exists in the result returned by the sub-query −
sqlite> SELECT AGE FROM COMPANY
WHERE EXISTS (SELECT AGE FROM COMPANY WHERE SALARY > 65000);
AGE
----------
32
25
23
25
27
22
24
Following SELECT statement makes use of SQL sub-query where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with > operator to list down all the records where AGE from the outside query is greater than the age in the result returned by the sub-query.
sqlite> SELECT * FROM COMPANY
WHERE AGE > (SELECT AGE FROM COMPANY WHERE SALARY > 65000);
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2748,
"s": 2638,
"text": "SQLite WHERE clause is used to specify a condition while fetching the data from one table or multiple tables."
},
{
"code": null,
"e": 2941,
"s": 2748,
"text": "If the given condition is satisfied, means true, then it returns the specific value from the table. You will have to use WHERE clause to filter the records and fetching only necessary records."
},
{
"code": null,
"e": 3097,
"s": 2941,
"text": "The WHERE clause not only is used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which will be covered in subsequent chapters."
},
{
"code": null,
"e": 3173,
"s": 3097,
"text": "Following is the basic syntax of SQLite SELECT statement with WHERE clause."
},
{
"code": null,
"e": 3242,
"s": 3173,
"text": "SELECT column1, column2, columnN \nFROM table_name\nWHERE [condition]\n"
},
{
"code": null,
"e": 3394,
"s": 3242,
"text": "You can specify a condition using Comparision or Logical Operators such as >, <, =, LIKE, NOT, etc. Consider COMPANY table with the following records −"
},
{
"code": null,
"e": 3900,
"s": 3394,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 4122,
"s": 3900,
"text": "Following is a simple examples showing the usage of SQLite Logical Operators. Following SELECT statement lists down all the records where AGE is greater than or equal to 25 AND salary is greater than or equal to 65000.00."
},
{
"code": null,
"e": 4416,
"s": 4122,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 4559,
"s": 4416,
"text": "Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00."
},
{
"code": null,
"e": 4964,
"s": 4559,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 5119,
"s": 4964,
"text": "Following SELECT statement lists down all the records where AGE is not NULL, which means all the records because none of the record has AGE equal to NULL."
},
{
"code": null,
"e": 5680,
"s": 5119,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE IS NOT NULL;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 5802,
"s": 5680,
"text": "Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'."
},
{
"code": null,
"e": 6026,
"s": 5802,
"text": "sqlite> SELECT * FROM COMPANY WHERE NAME LIKE 'Ki%';\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n6 Kim 22 South-Hall 45000.0"
},
{
"code": null,
"e": 6148,
"s": 6026,
"text": "Following SELECT statement lists down all the records where NAME starts with 'Ki', does not matter what comes after 'Ki'."
},
{
"code": null,
"e": 6372,
"s": 6148,
"text": "sqlite> SELECT * FROM COMPANY WHERE NAME GLOB 'Ki*';\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n6 Kim 22 South-Hall 45000.0"
},
{
"code": null,
"e": 6462,
"s": 6372,
"text": "Following SELECT statement lists down all the records where AGE value is either 25 or 27."
},
{
"code": null,
"e": 6800,
"s": 6462,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE IN ( 25, 27 );\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 6892,
"s": 6800,
"text": "Following SELECT statement lists down all the records where AGE value is neither 25 nor 27."
},
{
"code": null,
"e": 7290,
"s": 6892,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE NOT IN ( 25, 27 );\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n3 Teddy 23 Norway 20000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0"
},
{
"code": null,
"e": 7385,
"s": 7290,
"text": "Following SELECT statement lists down all the records where AGE value is in BETWEEN 25 AND 27."
},
{
"code": null,
"e": 7727,
"s": 7385,
"text": "sqlite> SELECT * FROM COMPANY WHERE AGE BETWEEN 25 AND 27;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n2 Allen 25 Texas 15000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0"
},
{
"code": null,
"e": 8032,
"s": 7727,
"text": "Following SELECT statement makes use of SQL sub-query, where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with EXISTS operator to list down all the records where AGE from the outside query exists in the result returned by the sub-query −"
},
{
"code": null,
"e": 8166,
"s": 8032,
"text": "sqlite> SELECT AGE FROM COMPANY \n WHERE EXISTS (SELECT AGE FROM COMPANY WHERE SALARY > 65000);\n\nAGE\n----------\n32\n25\n23\n25\n27\n22\n24"
},
{
"code": null,
"e": 8481,
"s": 8166,
"text": "Following SELECT statement makes use of SQL sub-query where sub-query finds all the records with AGE field having SALARY > 65000 and later WHERE clause is being used along with > operator to list down all the records where AGE from the outside query is greater than the age in the result returned by the sub-query."
},
{
"code": null,
"e": 8746,
"s": 8481,
"text": "sqlite> SELECT * FROM COMPANY \n WHERE AGE > (SELECT AGE FROM COMPANY WHERE SALARY > 65000);\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0"
},
{
"code": null,
"e": 8781,
"s": 8746,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8802,
"s": 8781,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 8835,
"s": 8802,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8852,
"s": 8835,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 8883,
"s": 8852,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 8896,
"s": 8883,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 8903,
"s": 8896,
"text": " Print"
},
{
"code": null,
"e": 8914,
"s": 8903,
"text": " Add Notes"
}
] |
Check if a Float value is equivalent to an Integer value - GeeksforGeeks
|
28 Apr, 2021
Given a floating-point number N, the task is to check if the value of N is equivalent to an integer or not. If found to be true, then print “YES”. Otherwise, print “NO”.
Examples:
Input: N = 1.5Output: NO
Input: N = 1.0Output: YES
Approach: The idea is to use the concept of Type Casting. Follow the steps below to solve the problem:
Initialize a variable, say X, to store the integer value of N.
Convert the value float value of N to integer and store it in X.
Finally, check if (N – X) > 0 or not. If found to be true, then print “NO”.
Otherwise, print “YES”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to check if N is// equivalent to an integerbool isInteger(double N){ // Convert float value // of N to integer int X = N; double temp2 = N - X; // If N is not equivalent // to any integer if (temp2 > 0) { return false; } return true;} // Driver Codeint main(){ double N = 1.5; if (isInteger(N)) { cout << "YES"; } else { cout << "NO"; } return 0;}
// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to check if N is// equivalent to an integerstatic boolean isInteger(double N){ // Convert float value // of N to integer int X = (int)N; double temp2 = N - X; // If N is not equivalent // to any integer if (temp2 > 0) { return false; } return true;} // Driver codepublic static void main(String[] args){ double N = 1.5; if (isInteger(N)) { System.out.println("YES"); } else { System.out.println("NO"); }}} // This code is contributed by susmitakundugoaldanga
# Python3 program to implement# the above approach # Function to check if N is# equivalent to an integerdef isInteger(N): # Convert float value # of N to integer X = int(N) temp2 = N - X # If N is not equivalent # to any integer if (temp2 > 0): return False return True # Driver Codeif __name__ == '__main__': N = 1.5 if (isInteger(N)): print("YES") else: print("NO") # This code is contributed by mohit kumar 29
// C# program to implement// the above approachusing System; class GFG{ // Function to check if N is// equivalent to an integerstatic bool isint(double N){ // Convert float value // of N to integer int X = (int)N; double temp2 = N - X; // If N is not equivalent // to any integer if (temp2 > 0) { return false; } return true;} // Driver codepublic static void Main(String[] args){ double N = 1.5; if (isint(N)) { Console.WriteLine("YES"); } else { Console.WriteLine("NO"); }}} // This code is contributed by 29AjayKumar
<script>// Javascript program for the above approach // Function to check if N is// equivalent to an integerfunction isInteger(N){ // Convert float value // of N to integer let X = Math.floor(N); let temp2 = N - X; // If N is not equivalent // to any integer if (temp2 > 0) { return false; } return true;} // driver function let N = 1.5; if (isInteger(N)) { document.write("YES"); } else { document.write("NO"); } // This code is contributed by souravghosh0416.</script>
NO
Time Complexity: O(1)Auxiliary Space: O(1)
mohit kumar 29
susmitakundugoaldanga
29AjayKumar
souravghosh0416
Data Types
Maths
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
Prime Numbers
Program to find sum of elements in a given array
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java
|
[
{
"code": null,
"e": 24834,
"s": 24806,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 25004,
"s": 24834,
"text": "Given a floating-point number N, the task is to check if the value of N is equivalent to an integer or not. If found to be true, then print “YES”. Otherwise, print “NO”."
},
{
"code": null,
"e": 25014,
"s": 25004,
"text": "Examples:"
},
{
"code": null,
"e": 25039,
"s": 25014,
"text": "Input: N = 1.5Output: NO"
},
{
"code": null,
"e": 25065,
"s": 25039,
"text": "Input: N = 1.0Output: YES"
},
{
"code": null,
"e": 25168,
"s": 25065,
"text": "Approach: The idea is to use the concept of Type Casting. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25231,
"s": 25168,
"text": "Initialize a variable, say X, to store the integer value of N."
},
{
"code": null,
"e": 25296,
"s": 25231,
"text": "Convert the value float value of N to integer and store it in X."
},
{
"code": null,
"e": 25372,
"s": 25296,
"text": "Finally, check if (N – X) > 0 or not. If found to be true, then print “NO”."
},
{
"code": null,
"e": 25396,
"s": 25372,
"text": "Otherwise, print “YES”."
},
{
"code": null,
"e": 25447,
"s": 25396,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25451,
"s": 25447,
"text": "C++"
},
{
"code": null,
"e": 25456,
"s": 25451,
"text": "Java"
},
{
"code": null,
"e": 25464,
"s": 25456,
"text": "Python3"
},
{
"code": null,
"e": 25467,
"s": 25464,
"text": "C#"
},
{
"code": null,
"e": 25478,
"s": 25467,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to check if N is// equivalent to an integerbool isInteger(double N){ // Convert float value // of N to integer int X = N; double temp2 = N - X; // If N is not equivalent // to any integer if (temp2 > 0) { return false; } return true;} // Driver Codeint main(){ double N = 1.5; if (isInteger(N)) { cout << \"YES\"; } else { cout << \"NO\"; } return 0;}",
"e": 26005,
"s": 25478,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to check if N is// equivalent to an integerstatic boolean isInteger(double N){ // Convert float value // of N to integer int X = (int)N; double temp2 = N - X; // If N is not equivalent // to any integer if (temp2 > 0) { return false; } return true;} // Driver codepublic static void main(String[] args){ double N = 1.5; if (isInteger(N)) { System.out.println(\"YES\"); } else { System.out.println(\"NO\"); }}} // This code is contributed by susmitakundugoaldanga",
"e": 26635,
"s": 26005,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to check if N is# equivalent to an integerdef isInteger(N): # Convert float value # of N to integer X = int(N) temp2 = N - X # If N is not equivalent # to any integer if (temp2 > 0): return False return True # Driver Codeif __name__ == '__main__': N = 1.5 if (isInteger(N)): print(\"YES\") else: print(\"NO\") # This code is contributed by mohit kumar 29",
"e": 27126,
"s": 26635,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to check if N is// equivalent to an integerstatic bool isint(double N){ // Convert float value // of N to integer int X = (int)N; double temp2 = N - X; // If N is not equivalent // to any integer if (temp2 > 0) { return false; } return true;} // Driver codepublic static void Main(String[] args){ double N = 1.5; if (isint(N)) { Console.WriteLine(\"YES\"); } else { Console.WriteLine(\"NO\"); }}} // This code is contributed by 29AjayKumar",
"e": 27740,
"s": 27126,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to check if N is// equivalent to an integerfunction isInteger(N){ // Convert float value // of N to integer let X = Math.floor(N); let temp2 = N - X; // If N is not equivalent // to any integer if (temp2 > 0) { return false; } return true;} // driver function let N = 1.5; if (isInteger(N)) { document.write(\"YES\"); } else { document.write(\"NO\"); } // This code is contributed by souravghosh0416.</script> ",
"e": 28292,
"s": 27740,
"text": null
},
{
"code": null,
"e": 28295,
"s": 28292,
"text": "NO"
},
{
"code": null,
"e": 28340,
"s": 28297,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28355,
"s": 28340,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 28377,
"s": 28355,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 28389,
"s": 28377,
"text": "29AjayKumar"
},
{
"code": null,
"e": 28405,
"s": 28389,
"text": "souravghosh0416"
},
{
"code": null,
"e": 28416,
"s": 28405,
"text": "Data Types"
},
{
"code": null,
"e": 28422,
"s": 28416,
"text": "Maths"
},
{
"code": null,
"e": 28435,
"s": 28422,
"text": "Mathematical"
},
{
"code": null,
"e": 28454,
"s": 28435,
"text": "School Programming"
},
{
"code": null,
"e": 28467,
"s": 28454,
"text": "Mathematical"
},
{
"code": null,
"e": 28565,
"s": 28467,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28574,
"s": 28565,
"text": "Comments"
},
{
"code": null,
"e": 28587,
"s": 28574,
"text": "Old Comments"
},
{
"code": null,
"e": 28629,
"s": 28587,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 28672,
"s": 28629,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 28696,
"s": 28672,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 28710,
"s": 28696,
"text": "Prime Numbers"
},
{
"code": null,
"e": 28759,
"s": 28710,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28777,
"s": 28759,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28793,
"s": 28777,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 28812,
"s": 28793,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28837,
"s": 28812,
"text": "Reverse a string in Java"
}
] |
Five Tips for Automatic Python Documentation | by Louis de Bruijn | Towards Data Science
|
In this story, you will learn how to automatically generate documentation from Python modules with a bit of magic in our custom functions, the package mkgendocs, pre-commit Git hooks, and MkDocs. We will touch upon the following elements
MkDocs & Material installation
Automate type-hints to docstrings
Automate docstrings to MkDocs with mkgendocs
Automate the documentation of new Python functions
Tie everything together in pre-commit Git hooks
MkDocs is a static site generator for building project documentation and together with the Material framework, it simply looks gorgeous. First, we need to install a heap of packages in order to use all of the functionalities of MkDocs. All of these packages are pip-installable.
MkDocs uses a configuration file mkdocs.yml, where you can enable all of the functionalities and packages installed above. Please find mine here. It includes references to the /docs and /docs_assets folders with the theme.
Previously, I wrote on the importance of writing docstrings, with a focus on Sphinx documentation.
betterprogramming.pub
Docstrings are an essential tool to document your functions. Python 3.5+ introduced type-hints, a way to assign static types to variables directly in the function arguments.
Several IDEs such as Pycharm, Visual Studio, and Sublime Text support automatic docstring generation. They do not however infer variable types from type-hints yet, which means that you have to fill both the variable type and descriptions in the docstrings.
Shown above is the implementation in Pycharm with Google-style docstrings. You are free to use other styles (such as reStructuredText/Sphinx or NumPy), but I found a package that exclusively works with Google-style docstrings for our next automation steps.
Interested in automating type-hints to docstrings? Read the story below 👇
towardsdatascience.com
The package mkgendocs automatically translates Google-style docstrings into pages with the description of Python functions. It uses a configuration file mkgendocs.yml. The configuration file looks like this
sources_dir: docstemplates_dir: docs/templatesrepo: https://github.com/LouisdeBruijn/Mediumversion: masterpages: - page: "scripts/base/base.md" source: "Python tips/base.py" functions: - parse_arguments - print_df - unescape_html - equal_array_items
Two manual steps for the use of this package are
Add the pages, sources, and functions to be documented to this mkgendocs.yml file.Run $ gendocs --config mkgendocs.yml to create the static MkDocs pages with the documentation of these functions.
Add the pages, sources, and functions to be documented to this mkgendocs.yml file.
Run $ gendocs --config mkgendocs.yml to create the static MkDocs pages with the documentation of these functions.
Next up, we will automate both steps by first creating a script to pre-fill our configurations file, and next attach both steps in a pre-commit Git hook.
First, I wrote a module automate.py with a function automate_mkdocs_from_docstring() to fill the mkgendocs.yml configurations file with all the Python functions in modules (scripts) in a repository.
automate_mkdocs_from_docstring() uses Pathlib to read the Python scripts in a directory and extract the function names. It saves both the module and the function names in a dictionary and uses this to overwrite the mkgendocs.yml. This way we can automatically fil the configurations file for the mkgendocs package.
Second, we will include both the execution of automate.py and the $ gendocs --config mkgendocs.yml in a pre-commit Git hook.
Our last step is to add each automation step into a Git hook in the pre-commit-config.yaml. More on pre-commit Git hooks in the story below👇
betterprogramming.pub
We’re adding the two mandatory steps for the automatic generation of MkDocs pages with the mkgendocs package in a pre-commit Git hook. These hooks allow us to execute a Python script with an entry bash command.
This way, when we create or remove Python functions anywhere in our repository, they will automatically be added to the mkgendocs configuration file, automatically creating static MkDocs pages and building the documentation website.
The only thing left to do is to run our MkDocs site with $ mkdocs serve and find our documentation at http://127.0.0.1:8000/.
With the automation steps presented in this story, you can automatically create beautiful Python documentation in MkDocs. If you have any questions, feel free to contact me. Happy coding!
Looking for more Python clean coding tips? Find them here 👇
|
[
{
"code": null,
"e": 410,
"s": 172,
"text": "In this story, you will learn how to automatically generate documentation from Python modules with a bit of magic in our custom functions, the package mkgendocs, pre-commit Git hooks, and MkDocs. We will touch upon the following elements"
},
{
"code": null,
"e": 441,
"s": 410,
"text": "MkDocs & Material installation"
},
{
"code": null,
"e": 475,
"s": 441,
"text": "Automate type-hints to docstrings"
},
{
"code": null,
"e": 520,
"s": 475,
"text": "Automate docstrings to MkDocs with mkgendocs"
},
{
"code": null,
"e": 571,
"s": 520,
"text": "Automate the documentation of new Python functions"
},
{
"code": null,
"e": 619,
"s": 571,
"text": "Tie everything together in pre-commit Git hooks"
},
{
"code": null,
"e": 898,
"s": 619,
"text": "MkDocs is a static site generator for building project documentation and together with the Material framework, it simply looks gorgeous. First, we need to install a heap of packages in order to use all of the functionalities of MkDocs. All of these packages are pip-installable."
},
{
"code": null,
"e": 1121,
"s": 898,
"text": "MkDocs uses a configuration file mkdocs.yml, where you can enable all of the functionalities and packages installed above. Please find mine here. It includes references to the /docs and /docs_assets folders with the theme."
},
{
"code": null,
"e": 1220,
"s": 1121,
"text": "Previously, I wrote on the importance of writing docstrings, with a focus on Sphinx documentation."
},
{
"code": null,
"e": 1242,
"s": 1220,
"text": "betterprogramming.pub"
},
{
"code": null,
"e": 1416,
"s": 1242,
"text": "Docstrings are an essential tool to document your functions. Python 3.5+ introduced type-hints, a way to assign static types to variables directly in the function arguments."
},
{
"code": null,
"e": 1673,
"s": 1416,
"text": "Several IDEs such as Pycharm, Visual Studio, and Sublime Text support automatic docstring generation. They do not however infer variable types from type-hints yet, which means that you have to fill both the variable type and descriptions in the docstrings."
},
{
"code": null,
"e": 1930,
"s": 1673,
"text": "Shown above is the implementation in Pycharm with Google-style docstrings. You are free to use other styles (such as reStructuredText/Sphinx or NumPy), but I found a package that exclusively works with Google-style docstrings for our next automation steps."
},
{
"code": null,
"e": 2004,
"s": 1930,
"text": "Interested in automating type-hints to docstrings? Read the story below 👇"
},
{
"code": null,
"e": 2027,
"s": 2004,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2234,
"s": 2027,
"text": "The package mkgendocs automatically translates Google-style docstrings into pages with the description of Python functions. It uses a configuration file mkgendocs.yml. The configuration file looks like this"
},
{
"code": null,
"e": 2511,
"s": 2234,
"text": "sources_dir: docstemplates_dir: docs/templatesrepo: https://github.com/LouisdeBruijn/Mediumversion: masterpages: - page: \"scripts/base/base.md\" source: \"Python tips/base.py\" functions: - parse_arguments - print_df - unescape_html - equal_array_items"
},
{
"code": null,
"e": 2560,
"s": 2511,
"text": "Two manual steps for the use of this package are"
},
{
"code": null,
"e": 2756,
"s": 2560,
"text": "Add the pages, sources, and functions to be documented to this mkgendocs.yml file.Run $ gendocs --config mkgendocs.yml to create the static MkDocs pages with the documentation of these functions."
},
{
"code": null,
"e": 2839,
"s": 2756,
"text": "Add the pages, sources, and functions to be documented to this mkgendocs.yml file."
},
{
"code": null,
"e": 2953,
"s": 2839,
"text": "Run $ gendocs --config mkgendocs.yml to create the static MkDocs pages with the documentation of these functions."
},
{
"code": null,
"e": 3107,
"s": 2953,
"text": "Next up, we will automate both steps by first creating a script to pre-fill our configurations file, and next attach both steps in a pre-commit Git hook."
},
{
"code": null,
"e": 3306,
"s": 3107,
"text": "First, I wrote a module automate.py with a function automate_mkdocs_from_docstring() to fill the mkgendocs.yml configurations file with all the Python functions in modules (scripts) in a repository."
},
{
"code": null,
"e": 3621,
"s": 3306,
"text": "automate_mkdocs_from_docstring() uses Pathlib to read the Python scripts in a directory and extract the function names. It saves both the module and the function names in a dictionary and uses this to overwrite the mkgendocs.yml. This way we can automatically fil the configurations file for the mkgendocs package."
},
{
"code": null,
"e": 3746,
"s": 3621,
"text": "Second, we will include both the execution of automate.py and the $ gendocs --config mkgendocs.yml in a pre-commit Git hook."
},
{
"code": null,
"e": 3887,
"s": 3746,
"text": "Our last step is to add each automation step into a Git hook in the pre-commit-config.yaml. More on pre-commit Git hooks in the story below👇"
},
{
"code": null,
"e": 3909,
"s": 3887,
"text": "betterprogramming.pub"
},
{
"code": null,
"e": 4120,
"s": 3909,
"text": "We’re adding the two mandatory steps for the automatic generation of MkDocs pages with the mkgendocs package in a pre-commit Git hook. These hooks allow us to execute a Python script with an entry bash command."
},
{
"code": null,
"e": 4353,
"s": 4120,
"text": "This way, when we create or remove Python functions anywhere in our repository, they will automatically be added to the mkgendocs configuration file, automatically creating static MkDocs pages and building the documentation website."
},
{
"code": null,
"e": 4479,
"s": 4353,
"text": "The only thing left to do is to run our MkDocs site with $ mkdocs serve and find our documentation at http://127.0.0.1:8000/."
},
{
"code": null,
"e": 4667,
"s": 4479,
"text": "With the automation steps presented in this story, you can automatically create beautiful Python documentation in MkDocs. If you have any questions, feel free to contact me. Happy coding!"
}
] |
Bootstrap - Grid System
|
In this chapter we shall discuss the Bootstrap Grid System.
As put by wikepedia −
To put in simple words, grids in web design organise and structure content, makes the websites easy to scan and reduces the cognitive load on users.
As put by the official documentation of Bootstrap for grid system −
Let us understand the above statement. Bootstrap 3 is mobile first in the sense that the code for Bootstrap now starts by targeting smaller screens like mobile devices, tablets, and then “expands” components and grids for larger screens such as laptops, desktops.
Content
Determine what is most important.
Content
Determine what is most important.
Layout
Design to smaller widths first.
Base CSS address mobile device first; media queries address for tablet, desktops.
Layout
Design to smaller widths first.
Base CSS address mobile device first; media queries address for tablet, desktops.
Progressive Enhancement
Add elements as screen size increases.
Progressive Enhancement
Add elements as screen size increases.
Grid systems are used for creating page layouts through a series of rows and columns that house your content. Here's how the Bootstrap grid system works −
Rows must be placed within a .container class for proper alignment and padding.
Rows must be placed within a .container class for proper alignment and padding.
Use rows to create horizontal groups of columns.
Use rows to create horizontal groups of columns.
Content should be placed within the columns, and only columns may be the immediate children of rows.
Content should be placed within the columns, and only columns may be the immediate children of rows.
Predefined grid classes like .row and .col-xs-4 are available for quickly making grid layouts. LESS mixins can also be used for more semantic layouts.
Predefined grid classes like .row and .col-xs-4 are available for quickly making grid layouts. LESS mixins can also be used for more semantic layouts.
Columns create gutters (gaps between column content) via padding. That padding is offset in rows for the first and the last column via negative margin on .rows.
Columns create gutters (gaps between column content) via padding. That padding is offset in rows for the first and the last column via negative margin on .rows.
Grid columns are created by specifying the number of twelve available columns you wish to span. For example, three equal columns would use three .col-xs-4.
Grid columns are created by specifying the number of twelve available columns you wish to span. For example, three equal columns would use three .col-xs-4.
Media query is a really fancy term for "conditional CSS rule". It simply applies some CSS, based on certain conditions set forth. If those conditions are met, the style is applied.
Media Queries in Bootstrap allow you to move, show and hide content based on the viewport size. Following media queries are used in LESS files to create the key breakpoints in the Bootstrap grid system.
/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */
/* Small devices (tablets, 768px and up) */
@media (min-width: @screen-sm-min) { ... }
/* Medium devices (desktops, 992px and up) */
@media (min-width: @screen-md-min) { ... }
/* Large devices (large desktops, 1200px and up) */
@media (min-width: @screen-lg-min) { ... }
Occasionally these are expanded to include a max-width to limit CSS to a narrower set of devices.
@media (max-width: @screen-xs-max) { ... }
@media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) { ... }
@media (min-width: @screen-md-min) and (max-width: @screen-md-max) { ... }
@media (min-width: @screen-lg-min) { ... }
Media queries have two parts, a device specification and then a size rule. In the above case, the following rule is set −
Let us consider this line −
@media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) { ... }
For all devices no matter what kind with min-width: @screen-sm-min if the width of the screen gets smaller than @screen-sm-max, then do something.
The following table summarizes aspects of how Bootstrap grid system works across multiple devices −
30px
(15px on each side of a column)
30px
(15px on each side of a column)
30px
(15px on each side of a column)
30px
(15px on each side of a column)
Following is basic structure of Bootstrap grid −
<div class = "container">
<div class = "row">
<div class = "col-*-*"></div>
<div class = "col-*-*"></div>
</div>
<div class = "row">...</div>
</div>
<div class = "container">
....
</div>
Let us see some simple grid examples −
Example − Stacked-to-horizontal
Example − Stacked-to-horizontal
Example − Medium and Large Device
Example − Medium and Large Device
Example − Mobile, tablet, desktops
Example − Mobile, tablet, desktops
With the four tiers of grids available, you are bound to run into issues where at certain breakpoints, the columns don't clear quite right as one is taller than the other. To fix that, use a combination of a class .clearfix and the responsive utility classes as shown in the following example −
<div class = "container">
<div class = "row" >
<div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut.</p>
</div>
<div class = "clearfix visible-xs"></div>
<div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<div class = "col-xs-6 col-sm-3" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim</p>
</div>
</div>
</div>
This will produce the following result −
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut.
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim
Offsets are a useful feature for more specialized layouts. They can be used to push columns over for more spacing, (for example). The .col-xs = * classes don’t support offsets, but they are easily replicated by using an empty cell.
To use offsets on large displays, use the .col-md-offset-* classes. These classes increase the left margin of a column by * columns where * range from 1 to 11.
In the following example, we have <div class = "col-md-6">..</div>, We will center this using class .col-md-offset-3.
<div class = "container">
<h1>Hello, world!</h1>
<div class = "row" >
<div class = "col-xs-6 col-md-offset-3" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
</div>
</div>
This will produce the following result −
Lorem ipsum dolor sit amet, consectetur adipisicing
elit.
To nest your content with the default grid, add a new .row and set of .col-md-* columns within an existing .col-md-* column. Nested rows should include a set of columns that add up to 12.
In the following example, the layout has two columns, with the second one being split into four boxes over two rows.
<div class = "container">
<h1>Hello, world!</h1>
<div class = "row">
<div class = "col-md-3" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<h4>First Column</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<div class = "col-md-9" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<h4>Second Column- Split into 4 boxes</h4>
<div class = "row">
<div class = "col-md-6" style = "background-color: #B18904;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Consectetur art party Tonx culpa semiotics.
Pinterest assumenda minim organic quis.</p>
</div>
<div class = "col-md-6" style = "background-color: #B18904;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
<div class = "row">
<div class = "col-md-6" style = "background-color: #B18904;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat.</p>
</div>
<div class = "col-md-6" style = "background-color: #B18904;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim.</p>
</div>
</div>
</div>
</div>
</div>
This will produce the following result −
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Consectetur art party Tonx culpa semiotics. Pinterest
assumenda minim organic quis.
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim.
Another nice feature of Bootstrap grid system is that you can easily write the columns in an order, and show them in another one. You can easily change the order of built-in grid columns with .col-md-push-* and .col-md-pull-* modifier classes where * range from 1 to 11.
In the following example we have two columns layout with left column being the narrowest and acting as a sidebar. We will swap the order of these columns using .col-md-push-* and .col-md-pull-* classes.
<div class = "container">
<h1>Hello, world!</h1>
<div class = "row">
<p>Before Ordering</p>
<div class = "col-md-4" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
I am on left
</div>
<div class = "col-md-8" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
I am on right
</div>
</div>
<br>
<div class = "row">
<p>After Ordering</p>
<div class = "col-md-4 col-md-push-8" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
I was on left
</div>
<div class = "col-md-8 col-md-pull-4" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
I was on right
</div>
</div>
</div>
This will produce the following result −
Before Ordering
After Ordering
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3391,
"s": 3331,
"text": "In this chapter we shall discuss the Bootstrap Grid System."
},
{
"code": null,
"e": 3413,
"s": 3391,
"text": "As put by wikepedia −"
},
{
"code": null,
"e": 3562,
"s": 3413,
"text": "To put in simple words, grids in web design organise and structure content, makes the websites easy to scan and reduces the cognitive load on users."
},
{
"code": null,
"e": 3630,
"s": 3562,
"text": "As put by the official documentation of Bootstrap for grid system −"
},
{
"code": null,
"e": 3894,
"s": 3630,
"text": "Let us understand the above statement. Bootstrap 3 is mobile first in the sense that the code for Bootstrap now starts by targeting smaller screens like mobile devices, tablets, and then “expands” components and grids for larger screens such as laptops, desktops."
},
{
"code": null,
"e": 3939,
"s": 3894,
"text": "Content\n\nDetermine what is most important.\n\n"
},
{
"code": null,
"e": 3947,
"s": 3939,
"text": "Content"
},
{
"code": null,
"e": 3981,
"s": 3947,
"text": "Determine what is most important."
},
{
"code": null,
"e": 4105,
"s": 3981,
"text": "Layout\n\nDesign to smaller widths first.\nBase CSS address mobile device first; media queries address for tablet, desktops.\n\n"
},
{
"code": null,
"e": 4112,
"s": 4105,
"text": "Layout"
},
{
"code": null,
"e": 4144,
"s": 4112,
"text": "Design to smaller widths first."
},
{
"code": null,
"e": 4226,
"s": 4144,
"text": "Base CSS address mobile device first; media queries address for tablet, desktops."
},
{
"code": null,
"e": 4292,
"s": 4226,
"text": "Progressive Enhancement\n\nAdd elements as screen size increases.\n\n"
},
{
"code": null,
"e": 4316,
"s": 4292,
"text": "Progressive Enhancement"
},
{
"code": null,
"e": 4355,
"s": 4316,
"text": "Add elements as screen size increases."
},
{
"code": null,
"e": 4510,
"s": 4355,
"text": "Grid systems are used for creating page layouts through a series of rows and columns that house your content. Here's how the Bootstrap grid system works −"
},
{
"code": null,
"e": 4590,
"s": 4510,
"text": "Rows must be placed within a .container class for proper alignment and padding."
},
{
"code": null,
"e": 4670,
"s": 4590,
"text": "Rows must be placed within a .container class for proper alignment and padding."
},
{
"code": null,
"e": 4719,
"s": 4670,
"text": "Use rows to create horizontal groups of columns."
},
{
"code": null,
"e": 4768,
"s": 4719,
"text": "Use rows to create horizontal groups of columns."
},
{
"code": null,
"e": 4869,
"s": 4768,
"text": "Content should be placed within the columns, and only columns may be the immediate children of rows."
},
{
"code": null,
"e": 4970,
"s": 4869,
"text": "Content should be placed within the columns, and only columns may be the immediate children of rows."
},
{
"code": null,
"e": 5121,
"s": 4970,
"text": "Predefined grid classes like .row and .col-xs-4 are available for quickly making grid layouts. LESS mixins can also be used for more semantic layouts."
},
{
"code": null,
"e": 5272,
"s": 5121,
"text": "Predefined grid classes like .row and .col-xs-4 are available for quickly making grid layouts. LESS mixins can also be used for more semantic layouts."
},
{
"code": null,
"e": 5433,
"s": 5272,
"text": "Columns create gutters (gaps between column content) via padding. That padding is offset in rows for the first and the last column via negative margin on .rows."
},
{
"code": null,
"e": 5594,
"s": 5433,
"text": "Columns create gutters (gaps between column content) via padding. That padding is offset in rows for the first and the last column via negative margin on .rows."
},
{
"code": null,
"e": 5750,
"s": 5594,
"text": "Grid columns are created by specifying the number of twelve available columns you wish to span. For example, three equal columns would use three .col-xs-4."
},
{
"code": null,
"e": 5906,
"s": 5750,
"text": "Grid columns are created by specifying the number of twelve available columns you wish to span. For example, three equal columns would use three .col-xs-4."
},
{
"code": null,
"e": 6087,
"s": 5906,
"text": "Media query is a really fancy term for \"conditional CSS rule\". It simply applies some CSS, based on certain conditions set forth. If those conditions are met, the style is applied."
},
{
"code": null,
"e": 6290,
"s": 6087,
"text": "Media Queries in Bootstrap allow you to move, show and hide content based on the viewport size. Following media queries are used in LESS files to create the key breakpoints in the Bootstrap grid system."
},
{
"code": null,
"e": 6677,
"s": 6290,
"text": "/* Extra small devices (phones, less than 768px) */\n/* No media query since this is the default in Bootstrap */\n\n/* Small devices (tablets, 768px and up) */\n@media (min-width: @screen-sm-min) { ... }\n\n/* Medium devices (desktops, 992px and up) */\n@media (min-width: @screen-md-min) { ... }\n\n/* Large devices (large desktops, 1200px and up) */\n@media (min-width: @screen-lg-min) { ... }\n"
},
{
"code": null,
"e": 6775,
"s": 6677,
"text": "Occasionally these are expanded to include a max-width to limit CSS to a narrower set of devices."
},
{
"code": null,
"e": 7012,
"s": 6775,
"text": "@media (max-width: @screen-xs-max) { ... }\n@media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) { ... }\n@media (min-width: @screen-md-min) and (max-width: @screen-md-max) { ... }\n@media (min-width: @screen-lg-min) { ... }\n"
},
{
"code": null,
"e": 7134,
"s": 7012,
"text": "Media queries have two parts, a device specification and then a size rule. In the above case, the following rule is set −"
},
{
"code": null,
"e": 7162,
"s": 7134,
"text": "Let us consider this line −"
},
{
"code": null,
"e": 7238,
"s": 7162,
"text": "@media (min-width: @screen-sm-min) and (max-width: @screen-sm-max) { ... }\n"
},
{
"code": null,
"e": 7385,
"s": 7238,
"text": "For all devices no matter what kind with min-width: @screen-sm-min if the width of the screen gets smaller than @screen-sm-max, then do something."
},
{
"code": null,
"e": 7485,
"s": 7385,
"text": "The following table summarizes aspects of how Bootstrap grid system works across multiple devices −"
},
{
"code": null,
"e": 7490,
"s": 7485,
"text": "30px"
},
{
"code": null,
"e": 7522,
"s": 7490,
"text": "(15px on each side of a column)"
},
{
"code": null,
"e": 7527,
"s": 7522,
"text": "30px"
},
{
"code": null,
"e": 7559,
"s": 7527,
"text": "(15px on each side of a column)"
},
{
"code": null,
"e": 7564,
"s": 7559,
"text": "30px"
},
{
"code": null,
"e": 7596,
"s": 7564,
"text": "(15px on each side of a column)"
},
{
"code": null,
"e": 7601,
"s": 7596,
"text": "30px"
},
{
"code": null,
"e": 7633,
"s": 7601,
"text": "(15px on each side of a column)"
},
{
"code": null,
"e": 7682,
"s": 7633,
"text": "Following is basic structure of Bootstrap grid −"
},
{
"code": null,
"e": 7901,
"s": 7682,
"text": "<div class = \"container\">\n\n <div class = \"row\">\n <div class = \"col-*-*\"></div>\n <div class = \"col-*-*\"></div>\n </div>\n \n <div class = \"row\">...</div>\n\t\n</div>\n\n<div class = \"container\">\n ....\n</div>"
},
{
"code": null,
"e": 7940,
"s": 7901,
"text": "Let us see some simple grid examples −"
},
{
"code": null,
"e": 7972,
"s": 7940,
"text": "Example − Stacked-to-horizontal"
},
{
"code": null,
"e": 8004,
"s": 7972,
"text": "Example − Stacked-to-horizontal"
},
{
"code": null,
"e": 8038,
"s": 8004,
"text": "Example − Medium and Large Device"
},
{
"code": null,
"e": 8072,
"s": 8038,
"text": "Example − Medium and Large Device"
},
{
"code": null,
"e": 8107,
"s": 8072,
"text": "Example − Mobile, tablet, desktops"
},
{
"code": null,
"e": 8142,
"s": 8107,
"text": "Example − Mobile, tablet, desktops"
},
{
"code": null,
"e": 8437,
"s": 8142,
"text": "With the four tiers of grids available, you are bound to run into issues where at certain breakpoints, the columns don't clear quite right as one is taller than the other. To fix that, use a combination of a class .clearfix and the responsive utility classes as shown in the following example −"
},
{
"code": null,
"e": 10086,
"s": 8437,
"text": "<div class = \"container\">\n <div class = \"row\" >\n \n <div class = \"col-xs-6 col-sm-3\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>\n </div>\n \n <div class = \"col-xs-6 col-sm-3\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do \n eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut \n enim ad minim veniam, quis nostrud exercitation ullamco laboris \n nisi ut aliquip ex ea commodo consequat.</p>\n \n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do \n eiusmod tempor incididunt ut.</p>\n </div>\n\n <div class = \"clearfix visible-xs\"></div>\n \n <div class = \"col-xs-6 col-sm-3\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco \n laboris nisi ut aliquip ex ea commodo consequat.</p>\n </div>\n \n <div class = \"col-xs-6 col-sm-3\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do \n eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut \n enim ad minim</p>\n </div>\n \n </div>\n</div>"
},
{
"code": null,
"e": 10127,
"s": 10086,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 10185,
"s": 10127,
"text": "Lorem ipsum dolor sit amet, consectetur adipisicing elit."
},
{
"code": null,
"e": 10491,
"s": 10185,
"text": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do \n eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut \n enim ad minim veniam, quis nostrud exercitation ullamco laboris \n nisi ut aliquip ex ea commodo consequat.\n "
},
{
"code": null,
"e": 10622,
"s": 10491,
"text": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do \n eiusmod tempor incididunt ut. \n "
},
{
"code": null,
"e": 10766,
"s": 10622,
"text": "Ut enim ad minim veniam, quis nostrud exercitation ullamco \n laboris nisi ut aliquip ex ea commodo consequat. \n "
},
{
"code": null,
"e": 10963,
"s": 10766,
"text": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do \n eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut \n enim ad minim \n "
},
{
"code": null,
"e": 11195,
"s": 10963,
"text": "Offsets are a useful feature for more specialized layouts. They can be used to push columns over for more spacing, (for example). The .col-xs = * classes don’t support offsets, but they are easily replicated by using an empty cell."
},
{
"code": null,
"e": 11355,
"s": 11195,
"text": "To use offsets on large displays, use the .col-md-offset-* classes. These classes increase the left margin of a column by * columns where * range from 1 to 11."
},
{
"code": null,
"e": 11474,
"s": 11355,
"text": "In the following example, we have <div class = \"col-md-6\">..</div>, We will center this using class .col-md-offset-3."
},
{
"code": null,
"e": 11825,
"s": 11474,
"text": "<div class = \"container\">\n\n <h1>Hello, world!</h1>\n\n <div class = \"row\" >\n <div class = \"col-xs-6 col-md-offset-3\" style = \"background-color: #dedef8; \n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>\n </div>\n\n </div>\n\t\n</div>"
},
{
"code": null,
"e": 11866,
"s": 11825,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 11959,
"s": 11866,
"text": "Lorem ipsum dolor sit amet, consectetur adipisicing \n elit.\n "
},
{
"code": null,
"e": 12147,
"s": 11959,
"text": "To nest your content with the default grid, add a new .row and set of .col-md-* columns within an existing .col-md-* column. Nested rows should include a set of columns that add up to 12."
},
{
"code": null,
"e": 12264,
"s": 12147,
"text": "In the following example, the layout has two columns, with the second one being split into four boxes over two rows."
},
{
"code": null,
"e": 14423,
"s": 12264,
"text": "<div class = \"container\">\n <h1>Hello, world!</h1>\n\n <div class = \"row\">\n\n <div class = \"col-md-3\" style = \"background-color: #dedef8; \n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <h4>First Column</h4>\n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>\n </div>\n\n <div class = \"col-md-9\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <h4>Second Column- Split into 4 boxes</h4>\n <div class = \"row\">\n \n <div class = \"col-md-6\" style = \"background-color: #B18904;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <p>Consectetur art party Tonx culpa semiotics. \n Pinterest assumenda minim organic quis.</p>\n </div>\n \n <div class = \"col-md-6\" style = \"background-color: #B18904;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <p>sed do eiusmod tempor incididunt ut labore et dolore magna \n aliqua. Ut enim ad minim veniam, quis nostrud exercitation \n ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>\n </div>\n\t\t\t\t\n </div>\n\n <div class = \"row\">\n\t\t\t\n <div class = \"col-md-6\" style = \"background-color: #B18904;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <p>quis nostrud exercitation ullamco laboris nisi ut aliquip \n ex ea commodo consequat.</p>\n </div> \n \n <div class = \"col-md-6\" style = \"background-color: #B18904;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, \n sed do eiusmod tempor incididunt ut labore et dolore magna \n aliqua. Ut enim ad minim.</p>\n </div>\n\t\t\t\t\n </div>\n\n </div>\n\n </div>\n\t\n</div>"
},
{
"code": null,
"e": 14464,
"s": 14423,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 14522,
"s": 14464,
"text": "Lorem ipsum dolor sit amet, consectetur adipisicing elit."
},
{
"code": null,
"e": 14653,
"s": 14522,
"text": "Consectetur art party Tonx culpa semiotics. Pinterest \n assumenda minim organic quis.\n "
},
{
"code": null,
"e": 14901,
"s": 14653,
"text": " sed do eiusmod tempor incididunt ut labore et dolore magna \n aliqua. Ut enim ad minim veniam, quis nostrud exercitation \n ullamco laboris nisi ut aliquip ex ea commodo consequat.\n "
},
{
"code": null,
"e": 15031,
"s": 14901,
"text": "quis nostrud exercitation ullamco laboris nisi ut \n aliquip ex ea commodo consequat.\n "
},
{
"code": null,
"e": 15224,
"s": 15031,
"text": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, \n sed do eiusmod tempor incididunt ut labore et dolore magna \n aliqua. Ut enim ad minim."
},
{
"code": null,
"e": 15495,
"s": 15224,
"text": "Another nice feature of Bootstrap grid system is that you can easily write the columns in an order, and show them in another one. You can easily change the order of built-in grid columns with .col-md-push-* and .col-md-pull-* modifier classes where * range from 1 to 11."
},
{
"code": null,
"e": 15698,
"s": 15495,
"text": "In the following example we have two columns layout with left column being the narrowest and acting as a sidebar. We will swap the order of these columns using .col-md-push-* and .col-md-pull-* classes."
},
{
"code": null,
"e": 16705,
"s": 15698,
"text": "<div class = \"container\">\n <h1>Hello, world!</h1>\n \n <div class = \"row\">\n <p>Before Ordering</p>\n \n <div class = \"col-md-4\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n I am on left\n </div>\n \n <div class = \"col-md-8\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n I am on right\n </div>\n \n </div>\n\t\n <br>\n \n <div class = \"row\">\n <p>After Ordering</p>\n \n <div class = \"col-md-4 col-md-push-8\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n I was on left\n </div>\n \n <div class = \"col-md-8 col-md-pull-4\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n \n I was on right\n </div>\n\t\t\n </div>\n\n</div>"
},
{
"code": null,
"e": 16746,
"s": 16705,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 16762,
"s": 16746,
"text": "Before Ordering"
},
{
"code": null,
"e": 16777,
"s": 16762,
"text": "After Ordering"
},
{
"code": null,
"e": 16810,
"s": 16777,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 16824,
"s": 16810,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 16859,
"s": 16824,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 16876,
"s": 16859,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 16913,
"s": 16876,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 16941,
"s": 16913,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 16974,
"s": 16941,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 16986,
"s": 16974,
"text": " Azaz Patel"
},
{
"code": null,
"e": 17021,
"s": 16986,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 17038,
"s": 17021,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 17071,
"s": 17038,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 17091,
"s": 17071,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 17098,
"s": 17091,
"text": " Print"
},
{
"code": null,
"e": 17109,
"s": 17098,
"text": " Add Notes"
}
] |
aspell command in Linux with examples - GeeksforGeeks
|
04 Apr, 2019
aspell command is used as a spell checker in Linux. Generally, it will scan the given files or anything from standard input then it check for misspellings. Finally it allows the user to correct the words interactively.
Syntax:
aspell check [options] filename
Options:
-a : To check individual words.
-c : Check a file for specific error.
-mode=mode : The modes we have to use when checking files.
-master=name : It is the main dictionary to use.
-dont-backup : It doesn’t create a backup file.
-encoding=name :Encoding the file is expected to be in.
-lang=name -l name : It describes the language the document is written in. By default it depends on the current locale.
-sug-mode=mode : The Suggestion Mode.
Example 1: Check a file for spelling errors
aspell -c sample.txt
Sample Text
Example 2: Using aspell to check individual words.
aspell -a
Note: As soon as you run this command, it will wait for user input. Type a word in this mode, press enter, and you’ll see aspell offering spelling suggestions on stdout.
Example 3: Using aspell to check words in bulk. When run, will wait for user input. Add as many words as you want, and when done, press Ctrl+D. Then you’ll see that aspell will display incorrectly spelled words below the input you provided.
linux-command
Linux-text-processing-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Basic Operators in Shell Scripting
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
chown command in Linux with Examples
mv command in Linux with examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
scp command in Linux with Examples
Docker - COPY Instruction
|
[
{
"code": null,
"e": 24430,
"s": 24402,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 24649,
"s": 24430,
"text": "aspell command is used as a spell checker in Linux. Generally, it will scan the given files or anything from standard input then it check for misspellings. Finally it allows the user to correct the words interactively."
},
{
"code": null,
"e": 24657,
"s": 24649,
"text": "Syntax:"
},
{
"code": null,
"e": 24689,
"s": 24657,
"text": "aspell check [options] filename"
},
{
"code": null,
"e": 24698,
"s": 24689,
"text": "Options:"
},
{
"code": null,
"e": 24730,
"s": 24698,
"text": "-a : To check individual words."
},
{
"code": null,
"e": 24768,
"s": 24730,
"text": "-c : Check a file for specific error."
},
{
"code": null,
"e": 24827,
"s": 24768,
"text": "-mode=mode : The modes we have to use when checking files."
},
{
"code": null,
"e": 24876,
"s": 24827,
"text": "-master=name : It is the main dictionary to use."
},
{
"code": null,
"e": 24924,
"s": 24876,
"text": "-dont-backup : It doesn’t create a backup file."
},
{
"code": null,
"e": 24980,
"s": 24924,
"text": "-encoding=name :Encoding the file is expected to be in."
},
{
"code": null,
"e": 25100,
"s": 24980,
"text": "-lang=name -l name : It describes the language the document is written in. By default it depends on the current locale."
},
{
"code": null,
"e": 25138,
"s": 25100,
"text": "-sug-mode=mode : The Suggestion Mode."
},
{
"code": null,
"e": 25182,
"s": 25138,
"text": "Example 1: Check a file for spelling errors"
},
{
"code": null,
"e": 25203,
"s": 25182,
"text": "aspell -c sample.txt"
},
{
"code": null,
"e": 25215,
"s": 25203,
"text": "Sample Text"
},
{
"code": null,
"e": 25266,
"s": 25215,
"text": "Example 2: Using aspell to check individual words."
},
{
"code": null,
"e": 25276,
"s": 25266,
"text": "aspell -a"
},
{
"code": null,
"e": 25446,
"s": 25276,
"text": "Note: As soon as you run this command, it will wait for user input. Type a word in this mode, press enter, and you’ll see aspell offering spelling suggestions on stdout."
},
{
"code": null,
"e": 25687,
"s": 25446,
"text": "Example 3: Using aspell to check words in bulk. When run, will wait for user input. Add as many words as you want, and when done, press Ctrl+D. Then you’ll see that aspell will display incorrectly spelled words below the input you provided."
},
{
"code": null,
"e": 25701,
"s": 25687,
"text": "linux-command"
},
{
"code": null,
"e": 25732,
"s": 25701,
"text": "Linux-text-processing-commands"
},
{
"code": null,
"e": 25743,
"s": 25732,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25841,
"s": 25743,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25850,
"s": 25841,
"text": "Comments"
},
{
"code": null,
"e": 25863,
"s": 25850,
"text": "Old Comments"
},
{
"code": null,
"e": 25889,
"s": 25863,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 25924,
"s": 25889,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 25961,
"s": 25924,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26001,
"s": 25961,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26038,
"s": 26001,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26072,
"s": 26038,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26101,
"s": 26072,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26143,
"s": 26101,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 26178,
"s": 26143,
"text": "scp command in Linux with Examples"
}
] |
How to handle the Runtime Exception in Java?
|
The Runtime Exception is the parent class in all exceptions of the Java programming language that are expected to crash or break down the program or application when they occur. Unlike exceptions that are not considered as Runtime Exceptions, Runtime Exceptions are never checked.
The Runtime Exception usually shows the programmer's error, rather than the condition a program is expected to deal with. Runtime Exceptions are also used when a condition that can't happen. It should be noted that when a program is running out of memory, a program error is thrown instead of showing it as a Runtime Exception.
The most common Runtime Exceptions are NullPointerException, ArrayIndexOutOfBoundsException and the InvalidArgumentException. The Java Virtual Machine throws the first two Runtime Exceptions.
The NullPointerException is the exception thrown by the Java Virtual Machine when a user performs some operations on a certain object considered as null or is calling for some method on the null object. A user should not attempt to handle this kind of an exception because it will only patch the problem and not completely fix it.
The ArrayIndexOutOfBoundsException is the exception that is automatically thrown by the Java Runtime Environment when a certain Java program incorrectly tries to access a certain location in a set that is non-existent. This often happens when the array index requested is negative, or more than or equal to the array's size. The arrays of Java use the zero-based indexing; thus, the first element of that array has a zero index, the last element comes with an index of size 1, and the nth element comes with an index n-1.
The InvalidArgumentException is an exception raised when an invalid parameter is passed to a certain method on the server's referenced connection.
public class MyExceptionTest {
public void testRuntimeException () {
throw new MyException();
}
public static void main(String[] args) {
try {
new MyExceptionTest().testRuntimeException();
} catch(Exception e) {
System.out.println(e.getClass().getName());
}
}
}
class MyException extends RuntimeException {
public MyException() {
super();
}
}
MyException
|
[
{
"code": null,
"e": 1343,
"s": 1062,
"text": "The Runtime Exception is the parent class in all exceptions of the Java programming language that are expected to crash or break down the program or application when they occur. Unlike exceptions that are not considered as Runtime Exceptions, Runtime Exceptions are never checked."
},
{
"code": null,
"e": 1671,
"s": 1343,
"text": "The Runtime Exception usually shows the programmer's error, rather than the condition a program is expected to deal with. Runtime Exceptions are also used when a condition that can't happen. It should be noted that when a program is running out of memory, a program error is thrown instead of showing it as a Runtime Exception."
},
{
"code": null,
"e": 1863,
"s": 1671,
"text": "The most common Runtime Exceptions are NullPointerException, ArrayIndexOutOfBoundsException and the InvalidArgumentException. The Java Virtual Machine throws the first two Runtime Exceptions."
},
{
"code": null,
"e": 2194,
"s": 1863,
"text": "The NullPointerException is the exception thrown by the Java Virtual Machine when a user performs some operations on a certain object considered as null or is calling for some method on the null object. A user should not attempt to handle this kind of an exception because it will only patch the problem and not completely fix it."
},
{
"code": null,
"e": 2716,
"s": 2194,
"text": "The ArrayIndexOutOfBoundsException is the exception that is automatically thrown by the Java Runtime Environment when a certain Java program incorrectly tries to access a certain location in a set that is non-existent. This often happens when the array index requested is negative, or more than or equal to the array's size. The arrays of Java use the zero-based indexing; thus, the first element of that array has a zero index, the last element comes with an index of size 1, and the nth element comes with an index n-1."
},
{
"code": null,
"e": 2863,
"s": 2716,
"text": "The InvalidArgumentException is an exception raised when an invalid parameter is passed to a certain method on the server's referenced connection."
},
{
"code": null,
"e": 3272,
"s": 2863,
"text": "public class MyExceptionTest {\n public void testRuntimeException () {\n throw new MyException();\n }\n public static void main(String[] args) {\n try {\n new MyExceptionTest().testRuntimeException();\n } catch(Exception e) {\n System.out.println(e.getClass().getName());\n }\n }\n}\nclass MyException extends RuntimeException {\n public MyException() {\n super();\n }\n}"
},
{
"code": null,
"e": 3284,
"s": 3272,
"text": "MyException"
}
] |
Python - Calculate the variance of a column in a Pandas DataFrame
|
To calculate the variance of column values, use the var() method. At first, import the required Pandas library −
import pandas as pd
Create a DataFrame with two columns −
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
Finding Variance of "Units" column values using var() function −
print"Variance of Units column from DataFrame1 = ",dataFrame1['Units'].var()
In the same way, we have calculated the Variance from the 2nd DataFrame.
Following is the complete code −
import pandas as pd
# Create DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
print"DataFrame1 ...\n",dataFrame1
# Finding Variance of "Units" column values
print"Variance of Units column from DataFrame1 = ",dataFrame1['Units'].var()
# Create DataFrame2
dataFrame2 = pd.DataFrame(
{
"Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],
"Price": [8000, 500, 3000, 1500, 3000, 4000]
}
)
print"\nDataFrame2 ...\n",dataFrame2
# Finding Variance of "Price" column values
print"Variance of Price column from DataFrame2 = ",dataFrame2['Price'].var()
This will produce the following output −
DataFrame1 ...
Car Units
0 BMW 100
1 Lexus 150
2 Audi 110
3 Tesla 80
4 Bentley 110
5 Jaguar 90
Variance of Units column from DataFrame1 = 586.666666667
DataFrame2 ...
Price Product
0 8000 TV
1 500 PenDrive
2 3000 HeadPhone
3 1500 EarPhone
4 3000 HDD
5 4000 SSD
Variance of Price column from DataFrame2 = 6766666.66667
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "To calculate the variance of column values, use the var() method. At first, import the required Pandas library −"
},
{
"code": null,
"e": 1195,
"s": 1175,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1233,
"s": 1195,
"text": "Create a DataFrame with two columns −"
},
{
"code": null,
"e": 1387,
"s": 1233,
"text": "dataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)\n\n"
},
{
"code": null,
"e": 1452,
"s": 1387,
"text": "Finding Variance of \"Units\" column values using var() function −"
},
{
"code": null,
"e": 1529,
"s": 1452,
"text": "print\"Variance of Units column from DataFrame1 = \",dataFrame1['Units'].var()"
},
{
"code": null,
"e": 1602,
"s": 1529,
"text": "In the same way, we have calculated the Variance from the 2nd DataFrame."
},
{
"code": null,
"e": 1635,
"s": 1602,
"text": "Following is the complete code −"
},
{
"code": null,
"e": 2333,
"s": 1635,
"text": "import pandas as pd\n\n# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)\n\nprint\"DataFrame1 ...\\n\",dataFrame1\n\n# Finding Variance of \"Units\" column values\nprint\"Variance of Units column from DataFrame1 = \",dataFrame1['Units'].var()\n\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Product\": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],\n \"Price\": [8000, 500, 3000, 1500, 3000, 4000]\n }\n)\n\nprint\"\\nDataFrame2 ...\\n\",dataFrame2\n\n# Finding Variance of \"Price\" column values\nprint\"Variance of Price column from DataFrame2 = \",dataFrame2['Price'].var()"
},
{
"code": null,
"e": 2374,
"s": 2333,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2777,
"s": 2374,
"text": "DataFrame1 ...\n Car Units\n0 BMW 100\n1 Lexus 150\n2 Audi 110\n3 Tesla 80\n4 Bentley 110\n5 Jaguar 90\nVariance of Units column from DataFrame1 = 586.666666667\n\nDataFrame2 ...\n Price Product\n0 8000 TV\n1 500 PenDrive\n2 3000 HeadPhone\n3 1500 EarPhone\n4 3000 HDD\n5 4000 SSD\nVariance of Price column from DataFrame2 = 6766666.66667"
}
] |
Time-Series Forecasting with Google BigQuery ML | by Tobi Sam | Towards Data Science
|
If you have worked with any kind of forecasting models, you will know how laborious it can be at times especially when trying to predict multiple variables. From identifying if a time-series is stationary or not, to estimation and finally model evaluation, this process is nothing short of time-consuming. For example, before you can start time-series forecasting with the ARIMA method in Python, you will have to follow these steps:
Identification/Data-Prep: This tests if a time-series is stationary by visualising the data and/or applying one of the statistical stationarity testing methods such as; the Dickey-Fuller test or the KPSS test. You can also use an ACF plot to identify non-stationary time-series data.
Differencing: Differencing can help stabilise the mean of a time series by removing changes in the level of a time series, and therefore eliminating (or reducing) trend and seasonality. Based on the results of the tests from the previous step, this will determine what kind of differencing method you will use. Example; Lag differencing, Difference Transform, Log Transform and others (see reference links at the bottom for more information).
Parameter Estimation: To create your ARIMA model, you will find the order of each ARIMA coefficient, “p”,”q” and “d” by looking at the ACF and PACF plots in order to select the right model for prediction. It basically means finding the values of the model coefficients which provide the best fit to the data. You can use AIC — Akaike information criterion or BIC — Bayesian information criterion as the selection criterion.
Diagnostic: Involves testing the assumptions of the model to identify any areas where the model is inadequate. If the model is found to be inadequate, it is necessary to go back to Step 2 and try to identify a better model. If your model is adequate, you can proceed to the final step...
Forecasting/Production: You can now use your model to make forecasts.
Following this necessary process, known as the Box-Jenkins method, can take a while before arriving at a suitable model. Thankfully, Google has incorporated a number of Machine Learning models right into BigQuery, and time-series forecasting with ARIMA is one of them. What this means is that you can now use plain old SQL to design complex ML models and at a fraction of the time while Google takes care of model selection and the forecasting process under the hood!
In the article, I will show you how to make forecasts 90 days into the future, using BigQuery ML’s time series model.
Forecast a single variable
Forecast multiple variables
Evaluating the model
As with any Machine Learning problem, gathering the right training data is the key to getting good predictions. So in my experience, the more extensive your time-series data is, the more likely you are to get good predictions. I try to capture as many seasonal patterns as possible in my training data.
For an e-commerce company, it is important to capture at least one holiday period in your historical data so your model can learn the spikes and dips during those periods. In our case, we are looking at an 8-month historical view. I prefer looking at even longer historical windows but we will stick with this for now.
#standardSQLSELECT FORMAT_DATE(“%Y-%m-%d”, DATE(orderDate)) AS day, SUM(quantity) AS salesFROM `myproject.mydataset.mytable`WHERE orderDate > CAST(date_add(DATE_TRUNC((DATE_SUB(CURRENT_DATE, INTERVAL 8 MONTH)), MONTH), INTERVAL 1 day) AS TIMESTAMP)GROUP BY dayORDER BY day, sales DESC
From this chart, we can see recurring patterns throughout the year and a sales spike around December.
In this step, we will create a time-series ARIMA model called
mydataset.sales_forecast
The CREATE MODEL clause creates and trains the model for a single time-series.
CREATE OR REPLACE MODEL mydataset.sales_forecastOPTIONS(model_type=’ARIMA’,time_series_data_col=’sales’,time_series_timestamp_col=’day’,data_frequency=’DAILY’holiday_region=’US’) ASSELECT FORMAT_DATE(“%Y-%m-%d”, DATE(orderDate) as day, SUM(quantity) AS salesFROM `myproject.mydataset.mytable`WHERE orderDate > cast(date_add(DATE_TRUNC((DATE_SUB(CURRENT_DATE, INTERVAL 8 MONTH)), MONTH), INTERVAL 1 day) as TIMESTAMP)GROUP BY dayORDER BY day, sales DESC
BigQuery ML automatically divides your training data into train/test during model creation.
The OPTIONS(model_type='ARIMA', time_series_timestamp_col='date', ...) clause is where most of the magic happens.
model_type: indicates that you are creating a ARIMA-based time series model.
time_series_data_col: indicates what column we will be forecasting
time_series_timestamp_col: indicates the time-series timestamp column
data_frequency: tells the model what format your input data is in. This is usually inferred automatically but explicitly defining it comes in handy sometimes
holiday_region (optional): this indicates the geographical region based on which the holiday effects are applied in modelling. By default, holiday effects modelling is disabled but enabling it allows a more accurate modelling for holiday points in your time-series.
After creating the model, you can use the ML.EVALUATE function to see the evaluation metrics of all the candidate models evaluated during the process, as many ARIMA models are run in parallel.
BigQuery selects the best performing model and uses it when you call the ML.FORECAST method (in the next step). If you aren’t happy with the results, you can play around with the time-series training data. For example, looking at weekly data as opposed to daily.
#standardSQLSELECT *FROM ML.EVALUATE(MODEL mydataset.sales_forecast)
The key step is in the query below. By calling the ML.FORECAST function, the model below forecasts 90 days into the future with a prediction interval of 80%.
#standardSQLSELECT * FROM ML.FORECAST(MODEL `mydataset.sales_forecast`, STRUCT(90 AS horizon, 0.8 AS confidence_level))
And like that, we have sales forecasts for the next 90 days!
Now we can merge the forecast to our actuals to see how well our forecasts performs over time. We group the results by week to get a more holistic picture.
WITH actuals AS (SELECT DATE_TRUNC(DATE(orderDate), WEEK) AS week, SUM(quantity) AS sales FROM `myproject.mydataset.mytable`WHERE orderDate > "2020-12-25"GROUP BY week) SELECT DATE_TRUNC(date(forecast_timestamp), WEEK) AS week, SUM(sales) AS actuals, SUM(prediction_interval_lower_bound) AS lower_value, SUM(forecast_value) AS middle_value, SUM(prediction_interval_upper_bound) AS upper_value FROM ML.FORECAST(MODEL `mydataset.sales_forecast`, STRUCT(90 AS horizon, 0.9 AS confidence_level)) as ML LEFT JOIN actuals AS ac ON DATE_TRUNC(date(forecast_timestamp), WEEK) = ac.week GROUP BY 1
As you can see, our forecasts were pretty good and our actuals lie well within the forecasted value.
To forecast multiple time-series, all you have to do is include a new option called time_series_id_col. This specifies what column will be used to identify the different time-series. So looking at our example above, if we wanted to predict 90 day sales for different store locations, we will just need to add the time_series_id_col in the model creation and include a new column in the training data.
CREATE OR REPLACE MODEL mydataset.sales_forecastOPTIONS(model_type=’ARIMA’,time_series_data_col=’sales’,time_series_timestamp_col=’day’,time_series_id_col=’location’data_frequency=’DAILY’holiday_region=’US’) ASSELECT FORMAT_DATE(“%Y-%m-%d”, DATE(orderDate) as day,location,SUM(quantity) AS salesFROM `myproject.mydataset.mytable`WHERE orderDate > cast(date_add(DATE_TRUNC((DATE_SUB(CURRENT_DATE, INTERVAL 8 MONTH)), MONTH), INTERVAL 1 day) as TIMESTAMP)GROUP BY day, locationORDER BY day, sales DESC
Now when you run ML.FORECAST like before, you get a 90-day sales prediction for each individual location in the store.
#standardSQLSELECT * FROM ML.FORECAST(MODEL `mydataset.sales_forecast`, STRUCT(90 AS horizon, 0.8 AS confidence_level))
Make sure to give this a try in your next time-series project.
Feel free to share any suggestions you have on how the methods here could be improved.
You can become a Medium member and enjoy more stories like this.
References
8.1 Stationarity and differencing | Forecasting: Principles and Practice (otexts.com)
Detecting stationarity in time series data — KDnuggets
How to Remove Trends and Seasonality with a Difference Transform in Python (machinelearningmastery.com)
|
[
{
"code": null,
"e": 605,
"s": 171,
"text": "If you have worked with any kind of forecasting models, you will know how laborious it can be at times especially when trying to predict multiple variables. From identifying if a time-series is stationary or not, to estimation and finally model evaluation, this process is nothing short of time-consuming. For example, before you can start time-series forecasting with the ARIMA method in Python, you will have to follow these steps:"
},
{
"code": null,
"e": 889,
"s": 605,
"text": "Identification/Data-Prep: This tests if a time-series is stationary by visualising the data and/or applying one of the statistical stationarity testing methods such as; the Dickey-Fuller test or the KPSS test. You can also use an ACF plot to identify non-stationary time-series data."
},
{
"code": null,
"e": 1332,
"s": 889,
"text": "Differencing: Differencing can help stabilise the mean of a time series by removing changes in the level of a time series, and therefore eliminating (or reducing) trend and seasonality. Based on the results of the tests from the previous step, this will determine what kind of differencing method you will use. Example; Lag differencing, Difference Transform, Log Transform and others (see reference links at the bottom for more information)."
},
{
"code": null,
"e": 1756,
"s": 1332,
"text": "Parameter Estimation: To create your ARIMA model, you will find the order of each ARIMA coefficient, “p”,”q” and “d” by looking at the ACF and PACF plots in order to select the right model for prediction. It basically means finding the values of the model coefficients which provide the best fit to the data. You can use AIC — Akaike information criterion or BIC — Bayesian information criterion as the selection criterion."
},
{
"code": null,
"e": 2044,
"s": 1756,
"text": "Diagnostic: Involves testing the assumptions of the model to identify any areas where the model is inadequate. If the model is found to be inadequate, it is necessary to go back to Step 2 and try to identify a better model. If your model is adequate, you can proceed to the final step..."
},
{
"code": null,
"e": 2114,
"s": 2044,
"text": "Forecasting/Production: You can now use your model to make forecasts."
},
{
"code": null,
"e": 2582,
"s": 2114,
"text": "Following this necessary process, known as the Box-Jenkins method, can take a while before arriving at a suitable model. Thankfully, Google has incorporated a number of Machine Learning models right into BigQuery, and time-series forecasting with ARIMA is one of them. What this means is that you can now use plain old SQL to design complex ML models and at a fraction of the time while Google takes care of model selection and the forecasting process under the hood!"
},
{
"code": null,
"e": 2700,
"s": 2582,
"text": "In the article, I will show you how to make forecasts 90 days into the future, using BigQuery ML’s time series model."
},
{
"code": null,
"e": 2727,
"s": 2700,
"text": "Forecast a single variable"
},
{
"code": null,
"e": 2755,
"s": 2727,
"text": "Forecast multiple variables"
},
{
"code": null,
"e": 2776,
"s": 2755,
"text": "Evaluating the model"
},
{
"code": null,
"e": 3079,
"s": 2776,
"text": "As with any Machine Learning problem, gathering the right training data is the key to getting good predictions. So in my experience, the more extensive your time-series data is, the more likely you are to get good predictions. I try to capture as many seasonal patterns as possible in my training data."
},
{
"code": null,
"e": 3398,
"s": 3079,
"text": "For an e-commerce company, it is important to capture at least one holiday period in your historical data so your model can learn the spikes and dips during those periods. In our case, we are looking at an 8-month historical view. I prefer looking at even longer historical windows but we will stick with this for now."
},
{
"code": null,
"e": 3685,
"s": 3398,
"text": "#standardSQLSELECT FORMAT_DATE(“%Y-%m-%d”, DATE(orderDate)) AS day, SUM(quantity) AS salesFROM `myproject.mydataset.mytable`WHERE orderDate > CAST(date_add(DATE_TRUNC((DATE_SUB(CURRENT_DATE, INTERVAL 8 MONTH)), MONTH), INTERVAL 1 day) AS TIMESTAMP)GROUP BY dayORDER BY day, sales DESC"
},
{
"code": null,
"e": 3787,
"s": 3685,
"text": "From this chart, we can see recurring patterns throughout the year and a sales spike around December."
},
{
"code": null,
"e": 3849,
"s": 3787,
"text": "In this step, we will create a time-series ARIMA model called"
},
{
"code": null,
"e": 3874,
"s": 3849,
"text": "mydataset.sales_forecast"
},
{
"code": null,
"e": 3953,
"s": 3874,
"text": "The CREATE MODEL clause creates and trains the model for a single time-series."
},
{
"code": null,
"e": 4408,
"s": 3953,
"text": "CREATE OR REPLACE MODEL mydataset.sales_forecastOPTIONS(model_type=’ARIMA’,time_series_data_col=’sales’,time_series_timestamp_col=’day’,data_frequency=’DAILY’holiday_region=’US’) ASSELECT FORMAT_DATE(“%Y-%m-%d”, DATE(orderDate) as day, SUM(quantity) AS salesFROM `myproject.mydataset.mytable`WHERE orderDate > cast(date_add(DATE_TRUNC((DATE_SUB(CURRENT_DATE, INTERVAL 8 MONTH)), MONTH), INTERVAL 1 day) as TIMESTAMP)GROUP BY dayORDER BY day, sales DESC"
},
{
"code": null,
"e": 4500,
"s": 4408,
"text": "BigQuery ML automatically divides your training data into train/test during model creation."
},
{
"code": null,
"e": 4614,
"s": 4500,
"text": "The OPTIONS(model_type='ARIMA', time_series_timestamp_col='date', ...) clause is where most of the magic happens."
},
{
"code": null,
"e": 4691,
"s": 4614,
"text": "model_type: indicates that you are creating a ARIMA-based time series model."
},
{
"code": null,
"e": 4758,
"s": 4691,
"text": "time_series_data_col: indicates what column we will be forecasting"
},
{
"code": null,
"e": 4828,
"s": 4758,
"text": "time_series_timestamp_col: indicates the time-series timestamp column"
},
{
"code": null,
"e": 4986,
"s": 4828,
"text": "data_frequency: tells the model what format your input data is in. This is usually inferred automatically but explicitly defining it comes in handy sometimes"
},
{
"code": null,
"e": 5252,
"s": 4986,
"text": "holiday_region (optional): this indicates the geographical region based on which the holiday effects are applied in modelling. By default, holiday effects modelling is disabled but enabling it allows a more accurate modelling for holiday points in your time-series."
},
{
"code": null,
"e": 5445,
"s": 5252,
"text": "After creating the model, you can use the ML.EVALUATE function to see the evaluation metrics of all the candidate models evaluated during the process, as many ARIMA models are run in parallel."
},
{
"code": null,
"e": 5708,
"s": 5445,
"text": "BigQuery selects the best performing model and uses it when you call the ML.FORECAST method (in the next step). If you aren’t happy with the results, you can play around with the time-series training data. For example, looking at weekly data as opposed to daily."
},
{
"code": null,
"e": 5777,
"s": 5708,
"text": "#standardSQLSELECT *FROM ML.EVALUATE(MODEL mydataset.sales_forecast)"
},
{
"code": null,
"e": 5935,
"s": 5777,
"text": "The key step is in the query below. By calling the ML.FORECAST function, the model below forecasts 90 days into the future with a prediction interval of 80%."
},
{
"code": null,
"e": 6056,
"s": 5935,
"text": "#standardSQLSELECT * FROM ML.FORECAST(MODEL `mydataset.sales_forecast`, STRUCT(90 AS horizon, 0.8 AS confidence_level))"
},
{
"code": null,
"e": 6117,
"s": 6056,
"text": "And like that, we have sales forecasts for the next 90 days!"
},
{
"code": null,
"e": 6273,
"s": 6117,
"text": "Now we can merge the forecast to our actuals to see how well our forecasts performs over time. We group the results by week to get a more holistic picture."
},
{
"code": null,
"e": 6866,
"s": 6273,
"text": "WITH actuals AS (SELECT DATE_TRUNC(DATE(orderDate), WEEK) AS week, SUM(quantity) AS sales FROM `myproject.mydataset.mytable`WHERE orderDate > \"2020-12-25\"GROUP BY week) SELECT DATE_TRUNC(date(forecast_timestamp), WEEK) AS week, SUM(sales) AS actuals, SUM(prediction_interval_lower_bound) AS lower_value, SUM(forecast_value) AS middle_value, SUM(prediction_interval_upper_bound) AS upper_value FROM ML.FORECAST(MODEL `mydataset.sales_forecast`, STRUCT(90 AS horizon, 0.9 AS confidence_level)) as ML LEFT JOIN actuals AS ac ON DATE_TRUNC(date(forecast_timestamp), WEEK) = ac.week GROUP BY 1"
},
{
"code": null,
"e": 6967,
"s": 6866,
"text": "As you can see, our forecasts were pretty good and our actuals lie well within the forecasted value."
},
{
"code": null,
"e": 7368,
"s": 6967,
"text": "To forecast multiple time-series, all you have to do is include a new option called time_series_id_col. This specifies what column will be used to identify the different time-series. So looking at our example above, if we wanted to predict 90 day sales for different store locations, we will just need to add the time_series_id_col in the model creation and include a new column in the training data."
},
{
"code": null,
"e": 7870,
"s": 7368,
"text": "CREATE OR REPLACE MODEL mydataset.sales_forecastOPTIONS(model_type=’ARIMA’,time_series_data_col=’sales’,time_series_timestamp_col=’day’,time_series_id_col=’location’data_frequency=’DAILY’holiday_region=’US’) ASSELECT FORMAT_DATE(“%Y-%m-%d”, DATE(orderDate) as day,location,SUM(quantity) AS salesFROM `myproject.mydataset.mytable`WHERE orderDate > cast(date_add(DATE_TRUNC((DATE_SUB(CURRENT_DATE, INTERVAL 8 MONTH)), MONTH), INTERVAL 1 day) as TIMESTAMP)GROUP BY day, locationORDER BY day, sales DESC"
},
{
"code": null,
"e": 7989,
"s": 7870,
"text": "Now when you run ML.FORECAST like before, you get a 90-day sales prediction for each individual location in the store."
},
{
"code": null,
"e": 8110,
"s": 7989,
"text": "#standardSQLSELECT * FROM ML.FORECAST(MODEL `mydataset.sales_forecast`, STRUCT(90 AS horizon, 0.8 AS confidence_level))"
},
{
"code": null,
"e": 8173,
"s": 8110,
"text": "Make sure to give this a try in your next time-series project."
},
{
"code": null,
"e": 8260,
"s": 8173,
"text": "Feel free to share any suggestions you have on how the methods here could be improved."
},
{
"code": null,
"e": 8325,
"s": 8260,
"text": "You can become a Medium member and enjoy more stories like this."
},
{
"code": null,
"e": 8336,
"s": 8325,
"text": "References"
},
{
"code": null,
"e": 8422,
"s": 8336,
"text": "8.1 Stationarity and differencing | Forecasting: Principles and Practice (otexts.com)"
},
{
"code": null,
"e": 8477,
"s": 8422,
"text": "Detecting stationarity in time series data — KDnuggets"
}
] |
Sort The Array | Practice | GeeksforGeeks
|
Given a random set of numbers, Print them in sorted order.
Example 1:
Input:
N = 4
arr[] = {1, 5, 3, 2}
Output: {1, 2, 3, 5}
Explanation: After sorting array will
be like {1, 2, 3, 5}.
Example 2:
Input:
N = 2
arr[] = {3, 1}
Output: {1, 3}
Explanation: After sorting array will
be like {3, 1}.
Your Task:
You don't need to read input or print anything. Your task is to complete the function sortArr() which takes the list of integers and the size N as inputs and returns the modified list.
Expected Time Complexity: O(N * log N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N, A[i] ≤ 105
0
shubhamshah141022 days ago
I Have used Merge sort in java but it gives me a runtime error for time being exceeded. How can this code be optimized??class Solution {
int[] sortArr(int[] arr, int n) { sort(arr, 0, n-1); return arr; } public static void sort(int a[], int low, int high) { int[] temp= new int[a.length]; if(low<high) { int mid=low+ (high-low)/2; sort(a,low,mid); sort(a,mid+1,high); merge(a,temp,low, mid, high); } } public static void merge(int[] a ,int[] temp, int low, int mid , int high) { for(int i=low;i<=high;i++) { temp[i]=a[i]; } int i=low,j=mid+1, k=low; while(i<=mid&&j<=high) { if(temp[i]<=temp[j]) { a[k]=temp[i]; i++; } else { a[k]=temp[j]; j++; } k++; } while(i<=mid) { a[k]=temp[i]; i++; k++; } }}
0
jy9041471 week ago
int[] sortArr(int[] arr, int n) { sort(arr,0,arr.length-1); return arr; } public static void merge(int arr[], int l, int m, int r) { int n1 = m -l+ 1; int n2 = r - m; int L[] = new int[n1]; int R[] = new int[n2]; for (int i = 0; i < n1; i++) L[i] = arr[l + i]; for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void sort(int arr[], int l, int r) { if (l < r) { int m =(l+ r)/2; sort(arr, l, m); sort(arr, m + 1, r); merge(arr, l, m, r);
}
}
0
nandasobhan4 weeks ago
vector<int> sortArr(vector<int>arr, int n){ //complete the function here sort(arr.begin(),arr.end()); return arr; }
0
shreyash9779664 weeks ago
vector<int> sortArr(vector<int>a, int n){
//complete the function here
sort(a.begin(),a.end());
return a;
}
0
patelshivanshu20171 month ago
//java solution
//merge sort for nlogn time complexity
class Solution { void merge(int[]arr,int s,int m,int l){ int i,j,k; int n1=m+1-s; int n2=l-m; int []leftarr=new int[n1]; int []rightarr=new int[n2]; for(i=0;i<n1;i++){ leftarr[i]=arr[s+i]; } for(j=0;j<n2;j++){ rightarr[j]=arr[m+1+j]; } i=0; j=0; k=s; while(i<n1 && j<n2){ if(leftarr[i]<=rightarr[j]){ arr[k]=leftarr[i]; i++; }else{ arr[k]=rightarr[j]; j++; } k++; } while(i<n1){ arr[k]= leftarr[i]; i++; k++; } while(j<n2){ arr[k]=rightarr[j]; j++; k++; } } void sort(int arr[],int s,int l){ if(s<l){ int m=(s+l)/2; sort(arr,s,m); sort(arr,m+1,l); merge(arr,s,m,l); } } int[] sortArr(int[] arr, int n) { // code here sort(arr,0,arr.length-1); return arr; } }
0
tushargoutam151 month ago
Python3 1 line Solution:
arr.sort() this will sort the arr in O(log n)
now just return the arr
code:
class Solution: def sortArr(self, arr, n): arr.sort() return arr
0
devil041 month ago
java solution(100% correct)
Arrays.sort(arr); return arr;
0
popudev071 month ago
typical mergeSort TC O(nlogn) but SPace took O(n)
//ideal method would be quicksort
private static void mergeSort(int[] arr, int start, int end) { if (start < end) { int mid = (start + end) / 2; mergeSort(arr, start, mid); mergeSort(arr, mid + 1, end); merge(arr, start, mid, end); }}
private static void merge(int[] arr, int start, int mid, int end) { if (arr[mid] > arr[mid + 1]) { int[] temp = new int[end - start + 1]; int i = start, j = mid + 1, k = 0;
while (i <= mid && j <= end) { if (arr[i] < arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; } }
while (i <= mid) { temp[k++] = arr[i++]; }
while (j <= end) { temp[k++] = arr[j++]; } k = 0; for (i = start; i < end + 1; i++) { arr[i] = temp[k++]; } }}
+1
atulp2001np1 month ago
vector<int >v;
priority_queue<int>maxh;
for (int i=0; i<n; i++){
maxh.push(arr[i]);
}
while(maxh.size()!=0){
v.push_back(maxh.top());
maxh.pop();
}
reverse(v.begin(),v.end());
return v;
-1
jaisprajwal19992 months ago
So here is a one-liner for java
class Solution
{
int[] sortArr(int[] arr, int n)
{
Arrays.sort(arr);
return arr;
}
}
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": 285,
"s": 226,
"text": "Given a random set of numbers, Print them in sorted order."
},
{
"code": null,
"e": 296,
"s": 285,
"text": "Example 1:"
},
{
"code": null,
"e": 412,
"s": 296,
"text": "Input:\nN = 4\narr[] = {1, 5, 3, 2}\nOutput: {1, 2, 3, 5}\nExplanation: After sorting array will \nbe like {1, 2, 3, 5}."
},
{
"code": null,
"e": 423,
"s": 412,
"text": "Example 2:"
},
{
"code": null,
"e": 520,
"s": 423,
"text": "Input:\nN = 2\narr[] = {3, 1}\nOutput: {1, 3}\nExplanation: After sorting array will\nbe like {3, 1}."
},
{
"code": null,
"e": 789,
"s": 520,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function sortArr() which takes the list of integers and the size N as inputs and returns the modified list.\n\nExpected Time Complexity: O(N * log N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 820,
"s": 789,
"text": "Constraints:\n1 ≤ N, A[i] ≤ 105"
},
{
"code": null,
"e": 822,
"s": 820,
"text": "0"
},
{
"code": null,
"e": 849,
"s": 822,
"text": "shubhamshah141022 days ago"
},
{
"code": null,
"e": 986,
"s": 849,
"text": "I Have used Merge sort in java but it gives me a runtime error for time being exceeded. How can this code be optimized??class Solution {"
},
{
"code": null,
"e": 1891,
"s": 986,
"text": " int[] sortArr(int[] arr, int n) { sort(arr, 0, n-1); return arr; } public static void sort(int a[], int low, int high) { int[] temp= new int[a.length]; if(low<high) { int mid=low+ (high-low)/2; sort(a,low,mid); sort(a,mid+1,high); merge(a,temp,low, mid, high); } } public static void merge(int[] a ,int[] temp, int low, int mid , int high) { for(int i=low;i<=high;i++) { temp[i]=a[i]; } int i=low,j=mid+1, k=low; while(i<=mid&&j<=high) { if(temp[i]<=temp[j]) { a[k]=temp[i]; i++; } else { a[k]=temp[j]; j++; } k++; } while(i<=mid) { a[k]=temp[i]; i++; k++; } }} "
},
{
"code": null,
"e": 1893,
"s": 1891,
"text": "0"
},
{
"code": null,
"e": 1912,
"s": 1893,
"text": "jy9041471 week ago"
},
{
"code": null,
"e": 3101,
"s": 1912,
"text": " int[] sortArr(int[] arr, int n) { sort(arr,0,arr.length-1); return arr; } public static void merge(int arr[], int l, int m, int r) { int n1 = m -l+ 1; int n2 = r - m; int L[] = new int[n1]; int R[] = new int[n2]; for (int i = 0; i < n1; i++) L[i] = arr[l + i]; for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void sort(int arr[], int l, int r) { if (l < r) { int m =(l+ r)/2; sort(arr, l, m); sort(arr, m + 1, r); merge(arr, l, m, r);"
},
{
"code": null,
"e": 3114,
"s": 3101,
"text": " }"
},
{
"code": null,
"e": 3123,
"s": 3114,
"text": " }"
},
{
"code": null,
"e": 3125,
"s": 3123,
"text": "0"
},
{
"code": null,
"e": 3148,
"s": 3125,
"text": "nandasobhan4 weeks ago"
},
{
"code": null,
"e": 3273,
"s": 3148,
"text": " vector<int> sortArr(vector<int>arr, int n){ //complete the function here sort(arr.begin(),arr.end()); return arr; }"
},
{
"code": null,
"e": 3275,
"s": 3273,
"text": "0"
},
{
"code": null,
"e": 3301,
"s": 3275,
"text": "shreyash9779664 weeks ago"
},
{
"code": null,
"e": 3425,
"s": 3301,
"text": "vector<int> sortArr(vector<int>a, int n){\n //complete the function here\n sort(a.begin(),a.end());\n return a;\n }"
},
{
"code": null,
"e": 3427,
"s": 3425,
"text": "0"
},
{
"code": null,
"e": 3457,
"s": 3427,
"text": "patelshivanshu20171 month ago"
},
{
"code": null,
"e": 3473,
"s": 3457,
"text": "//java solution"
},
{
"code": null,
"e": 3512,
"s": 3473,
"text": "//merge sort for nlogn time complexity"
},
{
"code": null,
"e": 4762,
"s": 3514,
"text": "class Solution { void merge(int[]arr,int s,int m,int l){ int i,j,k; int n1=m+1-s; int n2=l-m; int []leftarr=new int[n1]; int []rightarr=new int[n2]; for(i=0;i<n1;i++){ leftarr[i]=arr[s+i]; } for(j=0;j<n2;j++){ rightarr[j]=arr[m+1+j]; } i=0; j=0; k=s; while(i<n1 && j<n2){ if(leftarr[i]<=rightarr[j]){ arr[k]=leftarr[i]; i++; }else{ arr[k]=rightarr[j]; j++; } k++; } while(i<n1){ arr[k]= leftarr[i]; i++; k++; } while(j<n2){ arr[k]=rightarr[j]; j++; k++; } } void sort(int arr[],int s,int l){ if(s<l){ int m=(s+l)/2; sort(arr,s,m); sort(arr,m+1,l); merge(arr,s,m,l); } } int[] sortArr(int[] arr, int n) { // code here sort(arr,0,arr.length-1); return arr; } } "
},
{
"code": null,
"e": 4764,
"s": 4762,
"text": "0"
},
{
"code": null,
"e": 4790,
"s": 4764,
"text": "tushargoutam151 month ago"
},
{
"code": null,
"e": 4815,
"s": 4790,
"text": "Python3 1 line Solution:"
},
{
"code": null,
"e": 4862,
"s": 4815,
"text": "arr.sort() this will sort the arr in O(log n)"
},
{
"code": null,
"e": 4886,
"s": 4862,
"text": "now just return the arr"
},
{
"code": null,
"e": 4892,
"s": 4886,
"text": "code:"
},
{
"code": null,
"e": 4972,
"s": 4892,
"text": "class Solution: def sortArr(self, arr, n): arr.sort() return arr"
},
{
"code": null,
"e": 4974,
"s": 4972,
"text": "0"
},
{
"code": null,
"e": 4993,
"s": 4974,
"text": "devil041 month ago"
},
{
"code": null,
"e": 5021,
"s": 4993,
"text": "java solution(100% correct)"
},
{
"code": null,
"e": 5052,
"s": 5021,
"text": "Arrays.sort(arr); return arr;"
},
{
"code": null,
"e": 5054,
"s": 5052,
"text": "0"
},
{
"code": null,
"e": 5075,
"s": 5054,
"text": "popudev071 month ago"
},
{
"code": null,
"e": 5126,
"s": 5075,
"text": "typical mergeSort TC O(nlogn) but SPace took O(n) "
},
{
"code": null,
"e": 5160,
"s": 5126,
"text": "//ideal method would be quicksort"
},
{
"code": null,
"e": 5367,
"s": 5162,
"text": "private static void mergeSort(int[] arr, int start, int end) { if (start < end) { int mid = (start + end) / 2; mergeSort(arr, start, mid); mergeSort(arr, mid + 1, end); merge(arr, start, mid, end); }}"
},
{
"code": null,
"e": 5542,
"s": 5367,
"text": "private static void merge(int[] arr, int start, int mid, int end) { if (arr[mid] > arr[mid + 1]) { int[] temp = new int[end - start + 1]; int i = start, j = mid + 1, k = 0;"
},
{
"code": null,
"e": 5668,
"s": 5542,
"text": " while (i <= mid && j <= end) { if (arr[i] < arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; } }"
},
{
"code": null,
"e": 5716,
"s": 5668,
"text": " while (i <= mid) { temp[k++] = arr[i++]; }"
},
{
"code": null,
"e": 5837,
"s": 5716,
"text": " while (j <= end) { temp[k++] = arr[j++]; } k = 0; for (i = start; i < end + 1; i++) { arr[i] = temp[k++]; } }}"
},
{
"code": null,
"e": 5840,
"s": 5837,
"text": "+1"
},
{
"code": null,
"e": 5863,
"s": 5840,
"text": "atulp2001np1 month ago"
},
{
"code": null,
"e": 6121,
"s": 5863,
"text": "\tvector<int >v;\n \n priority_queue<int>maxh;\n for (int i=0; i<n; i++){\n maxh.push(arr[i]);\n \n }\n while(maxh.size()!=0){\n v.push_back(maxh.top());\n maxh.pop();\n }\n reverse(v.begin(),v.end());\n \n return v;"
},
{
"code": null,
"e": 6124,
"s": 6121,
"text": "-1"
},
{
"code": null,
"e": 6152,
"s": 6124,
"text": "jaisprajwal19992 months ago"
},
{
"code": null,
"e": 6185,
"s": 6152,
"text": "So here is a one-liner for java "
},
{
"code": null,
"e": 6303,
"s": 6185,
"text": "class Solution \n{ \n int[] sortArr(int[] arr, int n) \n { \n Arrays.sort(arr);\n return arr;\n }\n} "
},
{
"code": null,
"e": 6449,
"s": 6303,
"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": 6485,
"s": 6449,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6495,
"s": 6485,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6505,
"s": 6495,
"text": "\nContest\n"
},
{
"code": null,
"e": 6568,
"s": 6505,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6716,
"s": 6568,
"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": 6924,
"s": 6716,
"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": 7030,
"s": 6924,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C++ Pointers ( Incrementing a variable) | Set 1 | Practice | GeeksforGeeks
|
Given a pointer to a variable a, the task is to complete the function updateVar() which will increment the value of the variable by 10. The function does not returns anything.
Example 1:
Input:
a = 4
Output:
14
Example 2:
Input:
a = 61
Output:
71
Your Task:
Since this is a functional problem you don't have to worry about input, you just have to complete the function updateVar().
Constraints:
1 <= T <= 100
1 <= A <= 103
+1
0niharika22 months ago
*a += 10;
0
gargharshit5033 months ago
#include <iostream>
using namespace std;
int add(int *a)
{
int b;
*a= *a+10;
b= *a;
return b;
}
int main()
{
int a;
cin>>a;
cout<<add(&a);
return 0;
}
0
satyanandgupta19104 months ago
here , user give input to a value . then a is equal to a + 10 so variable value will increase by 10.
+1
seeagarg02034 months ago
*a += 10;
0
abdulmuqsitzargar015 months ago
void updateVar(int *a){ *a=*a+10; }
0
bhalgatshreya26 months ago
void updateVar(int *a)
{
*a+=10;
// write your code here
}
-3
aimlabhinavpatil7 months ago
#include <stdio.h>int main(){ int x, *b, inc; printf("Enter Value of x\n"); scanf("%d",&x);
b = &x;
inc = 10 + *b; printf("Incremented Value = %d\n",inc); return 0;}
0
aimlabhinavpatil
This comment was deleted.
0
Gurucharan Rajput10 months ago
Gurucharan Rajput
*a+=10;
-4
shivam1 year ago
shivam
void updateVar(int *a){ *a=*a+10;}
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": 402,
"s": 226,
"text": "Given a pointer to a variable a, the task is to complete the function updateVar() which will increment the value of the variable by 10. The function does not returns anything."
},
{
"code": null,
"e": 415,
"s": 402,
"text": "Example 1: "
},
{
"code": null,
"e": 441,
"s": 415,
"text": "Input:\na = 4\nOutput: \n14\n"
},
{
"code": null,
"e": 453,
"s": 441,
"text": "Example 2: "
},
{
"code": null,
"e": 480,
"s": 453,
"text": "Input:\na = 61\nOutput: \n71\n"
},
{
"code": null,
"e": 615,
"s": 480,
"text": "Your Task:\nSince this is a functional problem you don't have to worry about input, you just have to complete the function updateVar()."
},
{
"code": null,
"e": 656,
"s": 615,
"text": "Constraints:\n1 <= T <= 100\n1 <= A <= 103"
},
{
"code": null,
"e": 659,
"s": 656,
"text": "+1"
},
{
"code": null,
"e": 682,
"s": 659,
"text": "0niharika22 months ago"
},
{
"code": null,
"e": 692,
"s": 682,
"text": "*a += 10;"
},
{
"code": null,
"e": 694,
"s": 692,
"text": "0"
},
{
"code": null,
"e": 721,
"s": 694,
"text": "gargharshit5033 months ago"
},
{
"code": null,
"e": 741,
"s": 721,
"text": "#include <iostream>"
},
{
"code": null,
"e": 762,
"s": 741,
"text": "using namespace std;"
},
{
"code": null,
"e": 778,
"s": 762,
"text": "int add(int *a)"
},
{
"code": null,
"e": 780,
"s": 778,
"text": "{"
},
{
"code": null,
"e": 791,
"s": 780,
"text": " int b;"
},
{
"code": null,
"e": 806,
"s": 791,
"text": " *a= *a+10;"
},
{
"code": null,
"e": 817,
"s": 806,
"text": " b= *a;"
},
{
"code": null,
"e": 831,
"s": 817,
"text": " return b;"
},
{
"code": null,
"e": 833,
"s": 831,
"text": "}"
},
{
"code": null,
"e": 844,
"s": 833,
"text": "int main()"
},
{
"code": null,
"e": 846,
"s": 844,
"text": "{"
},
{
"code": null,
"e": 853,
"s": 846,
"text": "int a;"
},
{
"code": null,
"e": 861,
"s": 853,
"text": "cin>>a;"
},
{
"code": null,
"e": 876,
"s": 861,
"text": "cout<<add(&a);"
},
{
"code": null,
"e": 886,
"s": 876,
"text": "return 0;"
},
{
"code": null,
"e": 888,
"s": 886,
"text": "}"
},
{
"code": null,
"e": 890,
"s": 888,
"text": "0"
},
{
"code": null,
"e": 921,
"s": 890,
"text": "satyanandgupta19104 months ago"
},
{
"code": null,
"e": 1022,
"s": 921,
"text": "here , user give input to a value . then a is equal to a + 10 so variable value will increase by 10."
},
{
"code": null,
"e": 1025,
"s": 1022,
"text": "+1"
},
{
"code": null,
"e": 1050,
"s": 1025,
"text": "seeagarg02034 months ago"
},
{
"code": null,
"e": 1060,
"s": 1050,
"text": "*a += 10;"
},
{
"code": null,
"e": 1062,
"s": 1060,
"text": "0"
},
{
"code": null,
"e": 1094,
"s": 1062,
"text": "abdulmuqsitzargar015 months ago"
},
{
"code": null,
"e": 1133,
"s": 1094,
"text": "void updateVar(int *a){ *a=*a+10; }"
},
{
"code": null,
"e": 1135,
"s": 1133,
"text": "0"
},
{
"code": null,
"e": 1162,
"s": 1135,
"text": "bhalgatshreya26 months ago"
},
{
"code": null,
"e": 1244,
"s": 1162,
"text": "void updateVar(int *a)\n{\n *a+=10;\n \n \n // write your code here\n}"
},
{
"code": null,
"e": 1247,
"s": 1244,
"text": "-3"
},
{
"code": null,
"e": 1276,
"s": 1247,
"text": "aimlabhinavpatil7 months ago"
},
{
"code": null,
"e": 1374,
"s": 1276,
"text": "#include <stdio.h>int main(){ int x, *b, inc; printf(\"Enter Value of x\\n\"); scanf(\"%d\",&x);"
},
{
"code": null,
"e": 1382,
"s": 1374,
"text": "b = &x;"
},
{
"code": null,
"e": 1456,
"s": 1382,
"text": "inc = 10 + *b; printf(\"Incremented Value = %d\\n\",inc); return 0;} "
},
{
"code": null,
"e": 1458,
"s": 1456,
"text": "0"
},
{
"code": null,
"e": 1475,
"s": 1458,
"text": "aimlabhinavpatil"
},
{
"code": null,
"e": 1501,
"s": 1475,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1503,
"s": 1501,
"text": "0"
},
{
"code": null,
"e": 1534,
"s": 1503,
"text": "Gurucharan Rajput10 months ago"
},
{
"code": null,
"e": 1552,
"s": 1534,
"text": "Gurucharan Rajput"
},
{
"code": null,
"e": 1560,
"s": 1552,
"text": "*a+=10;"
},
{
"code": null,
"e": 1563,
"s": 1560,
"text": "-4"
},
{
"code": null,
"e": 1580,
"s": 1563,
"text": "shivam1 year ago"
},
{
"code": null,
"e": 1587,
"s": 1580,
"text": "shivam"
},
{
"code": null,
"e": 1622,
"s": 1587,
"text": "void updateVar(int *a){ *a=*a+10;}"
},
{
"code": null,
"e": 1768,
"s": 1622,
"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": 1804,
"s": 1768,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 1814,
"s": 1804,
"text": "\nProblem\n"
},
{
"code": null,
"e": 1824,
"s": 1814,
"text": "\nContest\n"
},
{
"code": null,
"e": 1887,
"s": 1824,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2035,
"s": 1887,
"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": 2243,
"s": 2035,
"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": 2349,
"s": 2243,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Useful Excel Functions for Data Science | by Pranjal Saxena | Towards Data Science
|
A Data Scientist spends plenty of time with the data. And, When we talk about the data, excel come in handy all the time. Excel has many useful functions like addition, subtraction, multiplication, but those are useful for calculation. In the data science field, we need a massive amount of data to train our machine learning models. The data can come from different sources, but finally, we need it organized. And, in most of the case, we convert our data in tabular format.
Once we convert the data in the tabular format, we need to plot different graphs and charts to visualize the data features and get the relation in other data columns. Before plotting the data, we need to make many changes and perform many operations in our data. And, there comes the need for excel functions.
This article will discuss some latest and useful functions in excel that we generally use for our data science tasks.
Match function helps in getting the index number of any item in a list. We generally use the match function with Horizontal Lookup or the Vertical Lookup. I will be discussing the vertical and horizontal lookup later in this article.
MATCH(lookup_value, lookup_array, [match_type])
Here, match type can be 0, which is for Exact Match, -1 for less than any number, and 1 for Greater than any number.
Lookup functions help in creating sub-data from the main data sources. The main data source can be in the same excel sheet or the different excel sheets. The columns in the sub-data should be a part of the main data source; else, we will get a null value for those columns. Lookup functions search for the data in two ways; first is the vertical lookup, and the second is a horizontal lookup.
Vertical Lookup
There should be a common column name for the vertical lookup in both the main data source and the sub-data. The common column in the main data should be present on the extreme left-hand side of the data.
VLOOKUP(lookup value, range containing the lookup value, the column number in the range containing the return value, Approximate match (TRUE) or Exact match (FALSE))
Here, the lookup value is the value of the common column value in both sub data and the main data. The range is the selected data part of the main lookup data. And the column number is the list of sub column names that should be present in the main data. These sub-columns names help in generating sub table.
For our example below, we will use a vertical lookup with the match function to get the column index in the main data.
=VLOOKUP($A29,lookup_table!$A:$K,MATCH(B$28,lookup_table!$A$1:$K$1,0),0)
Horizontal Lookup
Horizontal lookup, we generally use for getting the calculated result value for any column name. The result column names should be part of the main data. Those columns’ names should be present in the top row of the data in the main data.
HLOOKUP(lookup_value,table_array,row_index_num,range_lookup)
Vertical and Horizontal works on the condition that the lookup range list should be either extreme left or at the top first place. Sometimes, we need to make the match with the list at any random position. In that case, we use Index & Match.
INDEX(array, row number,[column number])
=INDEX(lookup_table_2!$A$2:$K$38,MATCH($B61,lookup_table_2!$K$2:$K$38,0),MATCH(Sheet1!C$60,lookup_table_2!$A$1:$K$1,0))
Here, we need to select our main lookup table and then define the matches for row and the columns using the match function.
Vertical lookup search for the match in the top to bottom direction, X Lookup provides us the functionality to shuffle the direction from top to bottom and bottom to top.
The freeze method helps in freezing any column or row. It is useful when we copy our function to the entire table. We need to use the dollar “$” symbol to freeze any row or column. The shortcut key for freezing any cell is “f4” on the keyboard.
We have discussed some main functions that we generally for our data science tasks. These are many handy excel functions when we have to deal with data visualization, and we have to get the sub-data from our main data sources. And, also in data science interviews, these are the much-asked topics in excel.
www.linkedin.com
Well, that’s it for now. I hope you find this article useful, keep enjoying data science.
|
[
{
"code": null,
"e": 648,
"s": 172,
"text": "A Data Scientist spends plenty of time with the data. And, When we talk about the data, excel come in handy all the time. Excel has many useful functions like addition, subtraction, multiplication, but those are useful for calculation. In the data science field, we need a massive amount of data to train our machine learning models. The data can come from different sources, but finally, we need it organized. And, in most of the case, we convert our data in tabular format."
},
{
"code": null,
"e": 958,
"s": 648,
"text": "Once we convert the data in the tabular format, we need to plot different graphs and charts to visualize the data features and get the relation in other data columns. Before plotting the data, we need to make many changes and perform many operations in our data. And, there comes the need for excel functions."
},
{
"code": null,
"e": 1076,
"s": 958,
"text": "This article will discuss some latest and useful functions in excel that we generally use for our data science tasks."
},
{
"code": null,
"e": 1310,
"s": 1076,
"text": "Match function helps in getting the index number of any item in a list. We generally use the match function with Horizontal Lookup or the Vertical Lookup. I will be discussing the vertical and horizontal lookup later in this article."
},
{
"code": null,
"e": 1358,
"s": 1310,
"text": "MATCH(lookup_value, lookup_array, [match_type])"
},
{
"code": null,
"e": 1475,
"s": 1358,
"text": "Here, match type can be 0, which is for Exact Match, -1 for less than any number, and 1 for Greater than any number."
},
{
"code": null,
"e": 1868,
"s": 1475,
"text": "Lookup functions help in creating sub-data from the main data sources. The main data source can be in the same excel sheet or the different excel sheets. The columns in the sub-data should be a part of the main data source; else, we will get a null value for those columns. Lookup functions search for the data in two ways; first is the vertical lookup, and the second is a horizontal lookup."
},
{
"code": null,
"e": 1884,
"s": 1868,
"text": "Vertical Lookup"
},
{
"code": null,
"e": 2088,
"s": 1884,
"text": "There should be a common column name for the vertical lookup in both the main data source and the sub-data. The common column in the main data should be present on the extreme left-hand side of the data."
},
{
"code": null,
"e": 2256,
"s": 2088,
"text": "VLOOKUP(lookup value, range containing the lookup value, the column number in the range containing the return value, Approximate match (TRUE) or Exact match (FALSE))"
},
{
"code": null,
"e": 2565,
"s": 2256,
"text": "Here, the lookup value is the value of the common column value in both sub data and the main data. The range is the selected data part of the main lookup data. And the column number is the list of sub column names that should be present in the main data. These sub-columns names help in generating sub table."
},
{
"code": null,
"e": 2684,
"s": 2565,
"text": "For our example below, we will use a vertical lookup with the match function to get the column index in the main data."
},
{
"code": null,
"e": 2757,
"s": 2684,
"text": "=VLOOKUP($A29,lookup_table!$A:$K,MATCH(B$28,lookup_table!$A$1:$K$1,0),0)"
},
{
"code": null,
"e": 2775,
"s": 2757,
"text": "Horizontal Lookup"
},
{
"code": null,
"e": 3013,
"s": 2775,
"text": "Horizontal lookup, we generally use for getting the calculated result value for any column name. The result column names should be part of the main data. Those columns’ names should be present in the top row of the data in the main data."
},
{
"code": null,
"e": 3074,
"s": 3013,
"text": "HLOOKUP(lookup_value,table_array,row_index_num,range_lookup)"
},
{
"code": null,
"e": 3316,
"s": 3074,
"text": "Vertical and Horizontal works on the condition that the lookup range list should be either extreme left or at the top first place. Sometimes, we need to make the match with the list at any random position. In that case, we use Index & Match."
},
{
"code": null,
"e": 3358,
"s": 3316,
"text": "INDEX(array, row number,[column number]) "
},
{
"code": null,
"e": 3478,
"s": 3358,
"text": "=INDEX(lookup_table_2!$A$2:$K$38,MATCH($B61,lookup_table_2!$K$2:$K$38,0),MATCH(Sheet1!C$60,lookup_table_2!$A$1:$K$1,0))"
},
{
"code": null,
"e": 3602,
"s": 3478,
"text": "Here, we need to select our main lookup table and then define the matches for row and the columns using the match function."
},
{
"code": null,
"e": 3773,
"s": 3602,
"text": "Vertical lookup search for the match in the top to bottom direction, X Lookup provides us the functionality to shuffle the direction from top to bottom and bottom to top."
},
{
"code": null,
"e": 4018,
"s": 3773,
"text": "The freeze method helps in freezing any column or row. It is useful when we copy our function to the entire table. We need to use the dollar “$” symbol to freeze any row or column. The shortcut key for freezing any cell is “f4” on the keyboard."
},
{
"code": null,
"e": 4325,
"s": 4018,
"text": "We have discussed some main functions that we generally for our data science tasks. These are many handy excel functions when we have to deal with data visualization, and we have to get the sub-data from our main data sources. And, also in data science interviews, these are the much-asked topics in excel."
},
{
"code": null,
"e": 4342,
"s": 4325,
"text": "www.linkedin.com"
}
] |
eject command in Linux with examples - GeeksforGeeks
|
15 May, 2019
eject allows ejecting a removable media (typically a CD-ROM, floppy disk, tape, or JAZ or ZIP disk) using the software. You can also control some multi-disc CD-ROM changers, the auto-eject feature (supported by some devices) and also close the disc tray of some CD-ROM drives. The methods of ejecting depend on the device type, whether it is a CD-ROM, SCSI device, removable floppy, or tape. The default action of eject is that it tries all four methods in order until it achieves success. The device is unmounted, if it is mounted, before ejecting.
Syntax:
eject [...OPTIONS]
Options of the eject command:
-h or –help : Display help for available commands.Syntax:eject -hOutput:
Syntax:
eject -h
Output:
-v or –verbose : Log out more information about the command’s execution.Syntax:eject -vOutput:
Syntax:
eject -v
Output:
-d or –default : List default device name.Syntax:eject -dOutput:
Syntax:
eject -d
Output:
-a on|1|off|0 or –auto on|1|off|0 : Control auto-eject mode supported by some devices with this command. Enable this to auto-eject when the device is closed.Syntax:eject -a on
Syntax:
eject -a on
-c or –changerslot : Select a CD slot from an ATAPI/IDE CD-ROM changer. You need Linux 2.0+ to use this feature. You have to make sure that the CD slot is not already in use. The first available slot is referred to as 0.Syntax:eject -c 0
Syntax:
eject -c 0
-t or –trayclose : Use this command to give the drive a tray close command.Note: Hardware support for this feature is limited.Syntax:eject -t
Note: Hardware support for this feature is limited.
Syntax:
eject -t
-T or –traytoggle : This option gives the tray close command, if the slot is open, or an eject command, if the slot is closed.Note: Hardware support for this command is limited, as it makes use of the above -t command.Syntax:eject -T
Note: Hardware support for this command is limited, as it makes use of the above -t command.
Syntax:
eject -T
-x or –cdspeed : Give a CD-ROM select speed command to the drive with this option. An argument is a number, which indicates the desired speed (e.g. 3 for 3X speed), or 0 for maximum data rate. Device support for this command is limited, and you can only specify speeds that the drive is capable of. The option is cleared everytime the media is changed. This option can also be used with -c or -t command.Syntax:eject -x 0
Syntax:
eject -x 0
-X or –listspeed : Display a list of available speeds from the CD-ROM drive using this option. You can use the speeds listed as an argument in the -x option. You need Linux 2.6.13+ to work with this option. On older versions, it will only report the maximum speed. Also, some drives may not correctly report the speed, thus this option does not work with them.Syntax:eject -X
Syntax:
eject -X
-n or –noop : Display the selected device, but perform no action using this option.Syntax:eject -nOutput:
Syntax:
eject -n
Output:
-r or –cdrom : Specify that the drive should be ejected using a CDROM eject command using this option.Syntax:eject -r
Syntax:
eject -r
-s or –scsi : Specify that the drive should be ejected using SCSI commands using this option.Syntax:eject -s
Syntax:
eject -s
-f or –floppy : Specify that the drive should be ejected using a removable floppy disk eject command using this option.Syntax:eject -f
Syntax:
eject -f
-q or –tape : Specify that the drive should be ejected using a tape drive offline command using this option.Syntax:eject -q
Syntax:
eject -q
-p or –proc : Use /proc/mounts instead /etc/mtab with this command. It also passes the -n option to umount.Syntax:eject -p
eject -p
-m or –no-unmount : Allow eject to work with device drivers which autonomously mount removable media and therefore must be always mounted. The option tells eject not to try to unmount the given device, even if it is mounted according to /proc/mounts or /etc/mtab.Syntax:eject -m
Syntax:
eject -m
-V or –version : Log the version number to console and exit.Syntax:eject -VOutput:
Syntax:
eject -V
Output:
Exit Status: On successful operation, 0 is returned, and on failed operation, 1 is returned.
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
|
[
{
"code": null,
"e": 24015,
"s": 23987,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 24565,
"s": 24015,
"text": "eject allows ejecting a removable media (typically a CD-ROM, floppy disk, tape, or JAZ or ZIP disk) using the software. You can also control some multi-disc CD-ROM changers, the auto-eject feature (supported by some devices) and also close the disc tray of some CD-ROM drives. The methods of ejecting depend on the device type, whether it is a CD-ROM, SCSI device, removable floppy, or tape. The default action of eject is that it tries all four methods in order until it achieves success. The device is unmounted, if it is mounted, before ejecting."
},
{
"code": null,
"e": 24573,
"s": 24565,
"text": "Syntax:"
},
{
"code": null,
"e": 24592,
"s": 24573,
"text": "eject [...OPTIONS]"
},
{
"code": null,
"e": 24622,
"s": 24592,
"text": "Options of the eject command:"
},
{
"code": null,
"e": 24695,
"s": 24622,
"text": "-h or –help : Display help for available commands.Syntax:eject -hOutput:"
},
{
"code": null,
"e": 24703,
"s": 24695,
"text": "Syntax:"
},
{
"code": null,
"e": 24712,
"s": 24703,
"text": "eject -h"
},
{
"code": null,
"e": 24720,
"s": 24712,
"text": "Output:"
},
{
"code": null,
"e": 24815,
"s": 24720,
"text": "-v or –verbose : Log out more information about the command’s execution.Syntax:eject -vOutput:"
},
{
"code": null,
"e": 24823,
"s": 24815,
"text": "Syntax:"
},
{
"code": null,
"e": 24832,
"s": 24823,
"text": "eject -v"
},
{
"code": null,
"e": 24840,
"s": 24832,
"text": "Output:"
},
{
"code": null,
"e": 24905,
"s": 24840,
"text": "-d or –default : List default device name.Syntax:eject -dOutput:"
},
{
"code": null,
"e": 24913,
"s": 24905,
"text": "Syntax:"
},
{
"code": null,
"e": 24922,
"s": 24913,
"text": "eject -d"
},
{
"code": null,
"e": 24930,
"s": 24922,
"text": "Output:"
},
{
"code": null,
"e": 25106,
"s": 24930,
"text": "-a on|1|off|0 or –auto on|1|off|0 : Control auto-eject mode supported by some devices with this command. Enable this to auto-eject when the device is closed.Syntax:eject -a on"
},
{
"code": null,
"e": 25114,
"s": 25106,
"text": "Syntax:"
},
{
"code": null,
"e": 25126,
"s": 25114,
"text": "eject -a on"
},
{
"code": null,
"e": 25364,
"s": 25126,
"text": "-c or –changerslot : Select a CD slot from an ATAPI/IDE CD-ROM changer. You need Linux 2.0+ to use this feature. You have to make sure that the CD slot is not already in use. The first available slot is referred to as 0.Syntax:eject -c 0"
},
{
"code": null,
"e": 25372,
"s": 25364,
"text": "Syntax:"
},
{
"code": null,
"e": 25383,
"s": 25372,
"text": "eject -c 0"
},
{
"code": null,
"e": 25525,
"s": 25383,
"text": "-t or –trayclose : Use this command to give the drive a tray close command.Note: Hardware support for this feature is limited.Syntax:eject -t"
},
{
"code": null,
"e": 25577,
"s": 25525,
"text": "Note: Hardware support for this feature is limited."
},
{
"code": null,
"e": 25585,
"s": 25577,
"text": "Syntax:"
},
{
"code": null,
"e": 25594,
"s": 25585,
"text": "eject -t"
},
{
"code": null,
"e": 25828,
"s": 25594,
"text": "-T or –traytoggle : This option gives the tray close command, if the slot is open, or an eject command, if the slot is closed.Note: Hardware support for this command is limited, as it makes use of the above -t command.Syntax:eject -T"
},
{
"code": null,
"e": 25921,
"s": 25828,
"text": "Note: Hardware support for this command is limited, as it makes use of the above -t command."
},
{
"code": null,
"e": 25929,
"s": 25921,
"text": "Syntax:"
},
{
"code": null,
"e": 25938,
"s": 25929,
"text": "eject -T"
},
{
"code": null,
"e": 26360,
"s": 25938,
"text": "-x or –cdspeed : Give a CD-ROM select speed command to the drive with this option. An argument is a number, which indicates the desired speed (e.g. 3 for 3X speed), or 0 for maximum data rate. Device support for this command is limited, and you can only specify speeds that the drive is capable of. The option is cleared everytime the media is changed. This option can also be used with -c or -t command.Syntax:eject -x 0"
},
{
"code": null,
"e": 26368,
"s": 26360,
"text": "Syntax:"
},
{
"code": null,
"e": 26379,
"s": 26368,
"text": "eject -x 0"
},
{
"code": null,
"e": 26755,
"s": 26379,
"text": "-X or –listspeed : Display a list of available speeds from the CD-ROM drive using this option. You can use the speeds listed as an argument in the -x option. You need Linux 2.6.13+ to work with this option. On older versions, it will only report the maximum speed. Also, some drives may not correctly report the speed, thus this option does not work with them.Syntax:eject -X"
},
{
"code": null,
"e": 26763,
"s": 26755,
"text": "Syntax:"
},
{
"code": null,
"e": 26772,
"s": 26763,
"text": "eject -X"
},
{
"code": null,
"e": 26878,
"s": 26772,
"text": "-n or –noop : Display the selected device, but perform no action using this option.Syntax:eject -nOutput:"
},
{
"code": null,
"e": 26886,
"s": 26878,
"text": "Syntax:"
},
{
"code": null,
"e": 26895,
"s": 26886,
"text": "eject -n"
},
{
"code": null,
"e": 26903,
"s": 26895,
"text": "Output:"
},
{
"code": null,
"e": 27021,
"s": 26903,
"text": "-r or –cdrom : Specify that the drive should be ejected using a CDROM eject command using this option.Syntax:eject -r"
},
{
"code": null,
"e": 27029,
"s": 27021,
"text": "Syntax:"
},
{
"code": null,
"e": 27038,
"s": 27029,
"text": "eject -r"
},
{
"code": null,
"e": 27147,
"s": 27038,
"text": "-s or –scsi : Specify that the drive should be ejected using SCSI commands using this option.Syntax:eject -s"
},
{
"code": null,
"e": 27155,
"s": 27147,
"text": "Syntax:"
},
{
"code": null,
"e": 27164,
"s": 27155,
"text": "eject -s"
},
{
"code": null,
"e": 27299,
"s": 27164,
"text": "-f or –floppy : Specify that the drive should be ejected using a removable floppy disk eject command using this option.Syntax:eject -f"
},
{
"code": null,
"e": 27307,
"s": 27299,
"text": "Syntax:"
},
{
"code": null,
"e": 27316,
"s": 27307,
"text": "eject -f"
},
{
"code": null,
"e": 27440,
"s": 27316,
"text": "-q or –tape : Specify that the drive should be ejected using a tape drive offline command using this option.Syntax:eject -q"
},
{
"code": null,
"e": 27448,
"s": 27440,
"text": "Syntax:"
},
{
"code": null,
"e": 27457,
"s": 27448,
"text": "eject -q"
},
{
"code": null,
"e": 27580,
"s": 27457,
"text": "-p or –proc : Use /proc/mounts instead /etc/mtab with this command. It also passes the -n option to umount.Syntax:eject -p"
},
{
"code": null,
"e": 27589,
"s": 27580,
"text": "eject -p"
},
{
"code": null,
"e": 27868,
"s": 27589,
"text": "-m or –no-unmount : Allow eject to work with device drivers which autonomously mount removable media and therefore must be always mounted. The option tells eject not to try to unmount the given device, even if it is mounted according to /proc/mounts or /etc/mtab.Syntax:eject -m"
},
{
"code": null,
"e": 27876,
"s": 27868,
"text": "Syntax:"
},
{
"code": null,
"e": 27885,
"s": 27876,
"text": "eject -m"
},
{
"code": null,
"e": 27968,
"s": 27885,
"text": "-V or –version : Log the version number to console and exit.Syntax:eject -VOutput:"
},
{
"code": null,
"e": 27976,
"s": 27968,
"text": "Syntax:"
},
{
"code": null,
"e": 27985,
"s": 27976,
"text": "eject -V"
},
{
"code": null,
"e": 27993,
"s": 27985,
"text": "Output:"
},
{
"code": null,
"e": 28086,
"s": 27993,
"text": "Exit Status: On successful operation, 0 is returned, and on failed operation, 1 is returned."
},
{
"code": null,
"e": 28100,
"s": 28086,
"text": "linux-command"
},
{
"code": null,
"e": 28120,
"s": 28100,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 28127,
"s": 28120,
"text": "Picked"
},
{
"code": null,
"e": 28138,
"s": 28127,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28236,
"s": 28138,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28245,
"s": 28236,
"text": "Comments"
},
{
"code": null,
"e": 28258,
"s": 28245,
"text": "Old Comments"
},
{
"code": null,
"e": 28293,
"s": 28258,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 28330,
"s": 28293,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 28364,
"s": 28330,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 28390,
"s": 28364,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 28416,
"s": 28390,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 28453,
"s": 28416,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 28493,
"s": 28453,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 28522,
"s": 28493,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 28564,
"s": 28522,
"text": "Named Pipe or FIFO with example C program"
}
] |
How to create Tkinter buttons in a Python for loop?
|
Tkinter Button widgets are very useful in terms of handling events and performing actions during the execution of an application. We can create Tkinter Buttons using the Button(parent, text, option..) constructor. Using the constructor, we can create multiple buttons within the loop.
In this example, we will create multiple buttons in the range using a Python for loop.
#import required libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win= Tk()
#Set the geometry of the window
win.geometry("750x250")
#Create a LabelFrame
labelframe= LabelFrame(win)
#Define a canvas in the window
canvas= Canvas(labelframe)
canvas.pack(side=RIGHT, fill=BOTH, expand=1)
labelframe.pack(fill= BOTH, expand= 1, padx= 30, pady=30)
#Create Button widget in Canvas
for i in range(5):
ttk.Button(canvas, text= "Button " +str(i)).pack()
win.mainloop()
Running the above code will display a window containing some buttons inside a LabelFrame object.
|
[
{
"code": null,
"e": 1347,
"s": 1062,
"text": "Tkinter Button widgets are very useful in terms of handling events and performing actions during the execution of an application. We can create Tkinter Buttons using the Button(parent, text, option..) constructor. Using the constructor, we can create multiple buttons within the loop."
},
{
"code": null,
"e": 1434,
"s": 1347,
"text": "In this example, we will create multiple buttons in the range using a Python for loop."
},
{
"code": null,
"e": 1947,
"s": 1434,
"text": "#import required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n#Create an instance of Tkinter frame\nwin= Tk()\n\n#Set the geometry of the window\nwin.geometry(\"750x250\")\n\n#Create a LabelFrame\nlabelframe= LabelFrame(win)\n\n#Define a canvas in the window\ncanvas= Canvas(labelframe)\ncanvas.pack(side=RIGHT, fill=BOTH, expand=1)\n\nlabelframe.pack(fill= BOTH, expand= 1, padx= 30, pady=30)\n\n#Create Button widget in Canvas\nfor i in range(5):\n ttk.Button(canvas, text= \"Button \" +str(i)).pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 2044,
"s": 1947,
"text": "Running the above code will display a window containing some buttons inside a LabelFrame object."
}
] |
How to set up a GPU VM with Ubuntu 18 on Oracle Cloud | by Luigi Saetta | Towards Data Science
|
If you want to develop a Deep Learning model and want a good likelihood to be successful, you need two things:
lots of data, for the training of the model
enough computational power, in the form of GPUs
A Deep Learning model commonly is based on a Deep (many layers) Neural Network. The algorithm commonly used for the training of the model is based on some form of the “back-propagation” algorithm and it requires many “tensor” operations. For this kind of operations, a GPU is much more effective than a CPU since it can execute with a degree of parallelism that you can’t achieve even with a modern CPU. Nvidia P100 has 3584 core and is capable of 5.3 TeraFlops, just as an example.
As a result, if you adopt modern GPUs you will be able to reduce the time needed to train your model of at least one order of magnitude, compared to the time needed using CPUs.
But GPUs are still expensive. Also, in this area, the development is strong and your GPU can become quickly old.
Therefore, the choice of adopting a Cloud-based environment, where you only pay for the use, is nowadays the best option. Just as an example, on Oracle Cloud, you can use a VM with one NVidia P100 (16 GB), 12 OCPU and 72 GB Ram (VM.GPU2.1 shape) for about 30 $/day. And you can get shapes with more GPUs if needed.
Having said that, the correct set-up of the environment for TensorFlow is not the simplest thing to do and you risk not being able to make full use of your GPU. I have done some research online and discovered that the documentation is not perfect. For this reason, I have decided to write this note about how to set up an Ubuntu 18 environment for TensorFlow and GPU.
As I said, I’m focusing on setting up a VM in Oracle Cloud Infrastructure (OCI) and I want to use these components:
Ubuntu 18.04 LTS
Anaconda Python distribution
Tensorflow
Jupyter Notebook
What is a little bit complicated is the correct alignment between OS libraries, Nvidia drivers for the GPU, the CUDA toolkit version and TensorFlow version. If all these things are not correctly aligned, you risk to have an environment where your TensorFlow program will run correctly, but without using the GPU and with much longer execution time. Not exactly what you want.
I have documented here the simplest series of steps I have found till now, and, honestly, I started writing this note as a personal one. Then I decided that probably it is worth to share.
From the OCI Console, the settings I have chosen for the creation of the VM are the followings:
Shape: VM.GPU2.1 (1 GPU, 12 OCPU)
OS: Ubuntu 18.04
Public IP: Yes
Boot volume: 100 GB of disk space
and I have added a public key, to be able to connect from remote, using ssh.
The creation of the VM is fast. Good.
The first thing to do is to update the list of packages available:
sudo apt update
Then, since we want to use Jupyter Notebook, we need to open in the on-board firewall the port 8888. The recommended way is the following:
sudo iptables -I INPUT -p tcp -s 0.0.0.0/0 --dport 8888 -j ACCEPTsudo service netfilter-persistent save
Do not use ufw. You risk canceling some settings needed to connect the VM to the storage.
After this, we need to add an inbound network security rule, to enable connection to port 8888 from the browser:
Log into OCI console.Under Core Infrastructure go to Networking and then Virtual Cloud Networks.Select the right cloud network.Under Resources click on Security Lists and then the security list that you’re interested in.Under Resources, click Ingress Rules and then Add Ingress Rule.Enter 0.0.0.0/0 for the Source CIDR, TCP for the IP Protocol, and 8888 for the destination port.At the bottom of the page, click Add Ingress Rules.
At this point, we need to install the right Nvidia drivers. This is a crucial point where I have lost some time. The easiest way I have found, for Ubuntu 18, is the following:
sudo apt install ubuntu-drivers-commonsudo ubuntu-drivers autoinstall
After the reboot (mandatory), you could check that drivers are correctly installed using the following command (the output is reported). From the command, you can also get drivers’ version.
nvidia-smiMon Sep 30 13:34:03 2019+ — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -+| NVIDIA-SMI 430.26 Driver Version: 430.26 CUDA Version: 10.2 || — — — — — — — — — — — — — — — -+ — — — — — — — — — — — + — — — — — — — — — — — +| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC || Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. ||===============================+======================+======================|| 0 Tesla P100-SXM2... Off | 00000000:00:04.0 Off | 0 || N/A 37C P0 24W / 300W | 0MiB / 16280MiB | 0% Default |+ — — — — — — — — — — — — — — — -+ — — — — — — — — — — — + — — — — — — — — — — — ++ — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -+| Processes: GPU Memory || GPU PID Type Process name Usage ||=============================================================================|| No running processes found |
The “nvidia-smi” command will be also useful in the future to check that GPU is used during the training process.
Next step is to install the Anaconda Python distribution.
At the moment of writing, the “July version” is the latest available, but you should check on the Anaconda site.
wget https://repo.continuum.io/archive/Anaconda3-2019.07-Linux-x86_64.shbash Anaconda3–2019.07-Linux-x86_64.sh -becho -e ‘export PATH=”$HOME/anaconda3/bin:$PATH”’ >> $HOME/.bashrcsource ~/.bashrc
It is worthwhile to do a last update of the Anaconda distribution, with the command:
conda update -n base -c defaults condaconda init bashsource ~/.bashrc
At this point, I get the 4.7 version. The last two commands enable the use of “conda activate” command.
Next, we need to create a new “conda” virtual environment, that we’re going to call “gpu”
conda create --name gpuconda activate gpu
After, we can install Python in the created “gpu” env:
conda install python
The next important step is TensorFlow installation. Here, we want to install the version supporting GPUs. It is important to use conda and not pip, for installation, since it ensures that all dependencies are correctly installed and met.
conda install tensorflow-gpu
Next, Jupyter installation:
conda install nb_condajupyter notebook --generate-config
After, you need to write the following lines in the Jupyter’s configuration
In /home/ubuntu/.jupyter/jupyter_notebook_config.py file, add the following linesc = get_config()c.NotebookApp.ip = '0.0.0.0'c.NotebookApp.open_browser = Falsec.NotebookApp.port = 8888
In this way, you enable connection to Jupyter from outside the VM (any IP address).
Then, since you want connections only through SSL, you can generate a self-signed certificate using OpenSSL:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout jupyter-key.key -out jupyter-cert.pem
After all these steps, you can start Jupyter using the following command
jupyter notebook — certfile=jupyter-cert.pem — keyfile=jupyter-key.key
(eventually, you could add nohup).
The browser will give you a security warning, but you understand what you’re doing and can continue right away.
Now, it is finally time to check if everything is OK. We want to be sure, before starting training a complex Deep Learning model, that TensorFlow is going to use GPU. So, we test using TensorFlow.
In a Notebook cell type:
import tensorflow as tffrom time import strftime, localtime, timewith tf.Session() as sess:devices = sess.list_devices()devices
In the output, you should see, in the list of available devices, GPU.
Then as a final check (I found it on StackOverflow)
import tensorflow as tfif tf.test.gpu_device_name():print(‘Default GPU Device: {}’.format(tf.test.gpu_device_name()))else:print(“Please install GPU version of TF”)
You want to see the output of the first “print” statement.
As final checks:
have a look at the logs produced by Jupyter;
run your model and at the same time execute the “nvidia-smi” command; You should see a “Volatile GPU utilization” greater than 0
If you want to seriously experiment in the Deep Learning field, you need GPUs. There are several ways to set up a Linux environment with GPU: in this note, I have documented how to set up an environment with the latest LTS Ubuntu version, on Oracle OCI.
And, more, I have documented how to be sure that TensorFlow is actually using GPU.
|
[
{
"code": null,
"e": 283,
"s": 172,
"text": "If you want to develop a Deep Learning model and want a good likelihood to be successful, you need two things:"
},
{
"code": null,
"e": 327,
"s": 283,
"text": "lots of data, for the training of the model"
},
{
"code": null,
"e": 375,
"s": 327,
"text": "enough computational power, in the form of GPUs"
},
{
"code": null,
"e": 858,
"s": 375,
"text": "A Deep Learning model commonly is based on a Deep (many layers) Neural Network. The algorithm commonly used for the training of the model is based on some form of the “back-propagation” algorithm and it requires many “tensor” operations. For this kind of operations, a GPU is much more effective than a CPU since it can execute with a degree of parallelism that you can’t achieve even with a modern CPU. Nvidia P100 has 3584 core and is capable of 5.3 TeraFlops, just as an example."
},
{
"code": null,
"e": 1035,
"s": 858,
"text": "As a result, if you adopt modern GPUs you will be able to reduce the time needed to train your model of at least one order of magnitude, compared to the time needed using CPUs."
},
{
"code": null,
"e": 1148,
"s": 1035,
"text": "But GPUs are still expensive. Also, in this area, the development is strong and your GPU can become quickly old."
},
{
"code": null,
"e": 1463,
"s": 1148,
"text": "Therefore, the choice of adopting a Cloud-based environment, where you only pay for the use, is nowadays the best option. Just as an example, on Oracle Cloud, you can use a VM with one NVidia P100 (16 GB), 12 OCPU and 72 GB Ram (VM.GPU2.1 shape) for about 30 $/day. And you can get shapes with more GPUs if needed."
},
{
"code": null,
"e": 1831,
"s": 1463,
"text": "Having said that, the correct set-up of the environment for TensorFlow is not the simplest thing to do and you risk not being able to make full use of your GPU. I have done some research online and discovered that the documentation is not perfect. For this reason, I have decided to write this note about how to set up an Ubuntu 18 environment for TensorFlow and GPU."
},
{
"code": null,
"e": 1947,
"s": 1831,
"text": "As I said, I’m focusing on setting up a VM in Oracle Cloud Infrastructure (OCI) and I want to use these components:"
},
{
"code": null,
"e": 1964,
"s": 1947,
"text": "Ubuntu 18.04 LTS"
},
{
"code": null,
"e": 1993,
"s": 1964,
"text": "Anaconda Python distribution"
},
{
"code": null,
"e": 2004,
"s": 1993,
"text": "Tensorflow"
},
{
"code": null,
"e": 2021,
"s": 2004,
"text": "Jupyter Notebook"
},
{
"code": null,
"e": 2397,
"s": 2021,
"text": "What is a little bit complicated is the correct alignment between OS libraries, Nvidia drivers for the GPU, the CUDA toolkit version and TensorFlow version. If all these things are not correctly aligned, you risk to have an environment where your TensorFlow program will run correctly, but without using the GPU and with much longer execution time. Not exactly what you want."
},
{
"code": null,
"e": 2585,
"s": 2397,
"text": "I have documented here the simplest series of steps I have found till now, and, honestly, I started writing this note as a personal one. Then I decided that probably it is worth to share."
},
{
"code": null,
"e": 2681,
"s": 2585,
"text": "From the OCI Console, the settings I have chosen for the creation of the VM are the followings:"
},
{
"code": null,
"e": 2715,
"s": 2681,
"text": "Shape: VM.GPU2.1 (1 GPU, 12 OCPU)"
},
{
"code": null,
"e": 2732,
"s": 2715,
"text": "OS: Ubuntu 18.04"
},
{
"code": null,
"e": 2747,
"s": 2732,
"text": "Public IP: Yes"
},
{
"code": null,
"e": 2781,
"s": 2747,
"text": "Boot volume: 100 GB of disk space"
},
{
"code": null,
"e": 2858,
"s": 2781,
"text": "and I have added a public key, to be able to connect from remote, using ssh."
},
{
"code": null,
"e": 2896,
"s": 2858,
"text": "The creation of the VM is fast. Good."
},
{
"code": null,
"e": 2963,
"s": 2896,
"text": "The first thing to do is to update the list of packages available:"
},
{
"code": null,
"e": 2979,
"s": 2963,
"text": "sudo apt update"
},
{
"code": null,
"e": 3118,
"s": 2979,
"text": "Then, since we want to use Jupyter Notebook, we need to open in the on-board firewall the port 8888. The recommended way is the following:"
},
{
"code": null,
"e": 3222,
"s": 3118,
"text": "sudo iptables -I INPUT -p tcp -s 0.0.0.0/0 --dport 8888 -j ACCEPTsudo service netfilter-persistent save"
},
{
"code": null,
"e": 3312,
"s": 3222,
"text": "Do not use ufw. You risk canceling some settings needed to connect the VM to the storage."
},
{
"code": null,
"e": 3425,
"s": 3312,
"text": "After this, we need to add an inbound network security rule, to enable connection to port 8888 from the browser:"
},
{
"code": null,
"e": 3856,
"s": 3425,
"text": "Log into OCI console.Under Core Infrastructure go to Networking and then Virtual Cloud Networks.Select the right cloud network.Under Resources click on Security Lists and then the security list that you’re interested in.Under Resources, click Ingress Rules and then Add Ingress Rule.Enter 0.0.0.0/0 for the Source CIDR, TCP for the IP Protocol, and 8888 for the destination port.At the bottom of the page, click Add Ingress Rules."
},
{
"code": null,
"e": 4032,
"s": 3856,
"text": "At this point, we need to install the right Nvidia drivers. This is a crucial point where I have lost some time. The easiest way I have found, for Ubuntu 18, is the following:"
},
{
"code": null,
"e": 4102,
"s": 4032,
"text": "sudo apt install ubuntu-drivers-commonsudo ubuntu-drivers autoinstall"
},
{
"code": null,
"e": 4292,
"s": 4102,
"text": "After the reboot (mandatory), you could check that drivers are correctly installed using the following command (the output is reported). From the command, you can also get drivers’ version."
},
{
"code": null,
"e": 5204,
"s": 4292,
"text": "nvidia-smiMon Sep 30 13:34:03 2019+ — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -+| NVIDIA-SMI 430.26 Driver Version: 430.26 CUDA Version: 10.2 || — — — — — — — — — — — — — — — -+ — — — — — — — — — — — + — — — — — — — — — — — +| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC || Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. ||===============================+======================+======================|| 0 Tesla P100-SXM2... Off | 00000000:00:04.0 Off | 0 || N/A 37C P0 24W / 300W | 0MiB / 16280MiB | 0% Default |+ — — — — — — — — — — — — — — — -+ — — — — — — — — — — — + — — — — — — — — — — — ++ — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -+| Processes: GPU Memory || GPU PID Type Process name Usage ||=============================================================================|| No running processes found |"
},
{
"code": null,
"e": 5318,
"s": 5204,
"text": "The “nvidia-smi” command will be also useful in the future to check that GPU is used during the training process."
},
{
"code": null,
"e": 5376,
"s": 5318,
"text": "Next step is to install the Anaconda Python distribution."
},
{
"code": null,
"e": 5489,
"s": 5376,
"text": "At the moment of writing, the “July version” is the latest available, but you should check on the Anaconda site."
},
{
"code": null,
"e": 5685,
"s": 5489,
"text": "wget https://repo.continuum.io/archive/Anaconda3-2019.07-Linux-x86_64.shbash Anaconda3–2019.07-Linux-x86_64.sh -becho -e ‘export PATH=”$HOME/anaconda3/bin:$PATH”’ >> $HOME/.bashrcsource ~/.bashrc"
},
{
"code": null,
"e": 5770,
"s": 5685,
"text": "It is worthwhile to do a last update of the Anaconda distribution, with the command:"
},
{
"code": null,
"e": 5840,
"s": 5770,
"text": "conda update -n base -c defaults condaconda init bashsource ~/.bashrc"
},
{
"code": null,
"e": 5944,
"s": 5840,
"text": "At this point, I get the 4.7 version. The last two commands enable the use of “conda activate” command."
},
{
"code": null,
"e": 6034,
"s": 5944,
"text": "Next, we need to create a new “conda” virtual environment, that we’re going to call “gpu”"
},
{
"code": null,
"e": 6076,
"s": 6034,
"text": "conda create --name gpuconda activate gpu"
},
{
"code": null,
"e": 6131,
"s": 6076,
"text": "After, we can install Python in the created “gpu” env:"
},
{
"code": null,
"e": 6152,
"s": 6131,
"text": "conda install python"
},
{
"code": null,
"e": 6390,
"s": 6152,
"text": "The next important step is TensorFlow installation. Here, we want to install the version supporting GPUs. It is important to use conda and not pip, for installation, since it ensures that all dependencies are correctly installed and met."
},
{
"code": null,
"e": 6419,
"s": 6390,
"text": "conda install tensorflow-gpu"
},
{
"code": null,
"e": 6447,
"s": 6419,
"text": "Next, Jupyter installation:"
},
{
"code": null,
"e": 6504,
"s": 6447,
"text": "conda install nb_condajupyter notebook --generate-config"
},
{
"code": null,
"e": 6580,
"s": 6504,
"text": "After, you need to write the following lines in the Jupyter’s configuration"
},
{
"code": null,
"e": 6765,
"s": 6580,
"text": "In /home/ubuntu/.jupyter/jupyter_notebook_config.py file, add the following linesc = get_config()c.NotebookApp.ip = '0.0.0.0'c.NotebookApp.open_browser = Falsec.NotebookApp.port = 8888"
},
{
"code": null,
"e": 6849,
"s": 6765,
"text": "In this way, you enable connection to Jupyter from outside the VM (any IP address)."
},
{
"code": null,
"e": 6958,
"s": 6849,
"text": "Then, since you want connections only through SSL, you can generate a self-signed certificate using OpenSSL:"
},
{
"code": null,
"e": 7056,
"s": 6958,
"text": "openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout jupyter-key.key -out jupyter-cert.pem"
},
{
"code": null,
"e": 7129,
"s": 7056,
"text": "After all these steps, you can start Jupyter using the following command"
},
{
"code": null,
"e": 7200,
"s": 7129,
"text": "jupyter notebook — certfile=jupyter-cert.pem — keyfile=jupyter-key.key"
},
{
"code": null,
"e": 7235,
"s": 7200,
"text": "(eventually, you could add nohup)."
},
{
"code": null,
"e": 7347,
"s": 7235,
"text": "The browser will give you a security warning, but you understand what you’re doing and can continue right away."
},
{
"code": null,
"e": 7544,
"s": 7347,
"text": "Now, it is finally time to check if everything is OK. We want to be sure, before starting training a complex Deep Learning model, that TensorFlow is going to use GPU. So, we test using TensorFlow."
},
{
"code": null,
"e": 7569,
"s": 7544,
"text": "In a Notebook cell type:"
},
{
"code": null,
"e": 7697,
"s": 7569,
"text": "import tensorflow as tffrom time import strftime, localtime, timewith tf.Session() as sess:devices = sess.list_devices()devices"
},
{
"code": null,
"e": 7767,
"s": 7697,
"text": "In the output, you should see, in the list of available devices, GPU."
},
{
"code": null,
"e": 7819,
"s": 7767,
"text": "Then as a final check (I found it on StackOverflow)"
},
{
"code": null,
"e": 7983,
"s": 7819,
"text": "import tensorflow as tfif tf.test.gpu_device_name():print(‘Default GPU Device: {}’.format(tf.test.gpu_device_name()))else:print(“Please install GPU version of TF”)"
},
{
"code": null,
"e": 8042,
"s": 7983,
"text": "You want to see the output of the first “print” statement."
},
{
"code": null,
"e": 8059,
"s": 8042,
"text": "As final checks:"
},
{
"code": null,
"e": 8104,
"s": 8059,
"text": "have a look at the logs produced by Jupyter;"
},
{
"code": null,
"e": 8233,
"s": 8104,
"text": "run your model and at the same time execute the “nvidia-smi” command; You should see a “Volatile GPU utilization” greater than 0"
},
{
"code": null,
"e": 8487,
"s": 8233,
"text": "If you want to seriously experiment in the Deep Learning field, you need GPUs. There are several ways to set up a Linux environment with GPU: in this note, I have documented how to set up an environment with the latest LTS Ubuntu version, on Oracle OCI."
}
] |
C# General Date Short Time ("g") Format Specifier
|
The Generate Date Short Time format specifier is a combination of the short date ("d") and short time ("t") patterns, separated by a space.
Set a date using DateTime.
DateTime dt = new DateTime(2018, 10, 2, 7, 59, 20);
Now, use the (“g”) format specifier.
dt.ToString("g", DateTimeFormatInfo.InvariantInfo));
Live Demo
using System;
using System.Globalization;
class Demo {
static void Main() {
DateTime dt = new DateTime(2018, 10, 2, 7, 59, 20);
Console.WriteLine(dt.ToString("g", DateTimeFormatInfo.InvariantInfo));
Console.WriteLine(dt.ToString("g", CultureInfo.CreateSpecificCulture("en-us")));
}
}
10/02/2018 07:59
10/2/2018 7:59 AM
|
[
{
"code": null,
"e": 1202,
"s": 1062,
"text": "The Generate Date Short Time format specifier is a combination of the short date (\"d\") and short time (\"t\") patterns, separated by a space."
},
{
"code": null,
"e": 1229,
"s": 1202,
"text": "Set a date using DateTime."
},
{
"code": null,
"e": 1281,
"s": 1229,
"text": "DateTime dt = new DateTime(2018, 10, 2, 7, 59, 20);"
},
{
"code": null,
"e": 1318,
"s": 1281,
"text": "Now, use the (“g”) format specifier."
},
{
"code": null,
"e": 1371,
"s": 1318,
"text": "dt.ToString(\"g\", DateTimeFormatInfo.InvariantInfo));"
},
{
"code": null,
"e": 1382,
"s": 1371,
"text": " Live Demo"
},
{
"code": null,
"e": 1690,
"s": 1382,
"text": "using System;\nusing System.Globalization;\nclass Demo {\n static void Main() {\n DateTime dt = new DateTime(2018, 10, 2, 7, 59, 20);\n Console.WriteLine(dt.ToString(\"g\", DateTimeFormatInfo.InvariantInfo));\n Console.WriteLine(dt.ToString(\"g\", CultureInfo.CreateSpecificCulture(\"en-us\")));\n }\n}"
},
{
"code": null,
"e": 1725,
"s": 1690,
"text": "10/02/2018 07:59\n10/2/2018 7:59 AM"
}
] |
Getting error- <type table> is not an internal table “OCCURS n” specification is missing in SAP method
|
You need to define the et_flights parameter as of type SFLIGHT. As per method defined, you have this type as structure type and also declare transparent table SFLIGHT at the same time.
You should use an already available dictionary table type with row structure of SFLIGHT for et_flight.
You should declare et_flights inside the method in class definition as a private member or as a return value of the method.
class myclass definition.
public section.
types ty_mytable type standard table of sflight.
methods mymethod exporting mydata type ty_mytable.
endclass.
class myclass implementation.
method mymethod.
select * from sflight into table mydata.
endmethod.
endclass.
|
[
{
"code": null,
"e": 1247,
"s": 1062,
"text": "You need to define the et_flights parameter as of type SFLIGHT. As per method defined, you have this type as structure type and also declare transparent table SFLIGHT at the same time."
},
{
"code": null,
"e": 1350,
"s": 1247,
"text": "You should use an already available dictionary table type with row structure of SFLIGHT for et_flight."
},
{
"code": null,
"e": 1474,
"s": 1350,
"text": "You should declare et_flights inside the method in class definition as a private member or as a return value of the method."
},
{
"code": null,
"e": 1760,
"s": 1474,
"text": "class myclass definition.\n public section.\n types ty_mytable type standard table of sflight.\n methods mymethod exporting mydata type ty_mytable.\nendclass.\n\nclass myclass implementation.\n method mymethod.\n select * from sflight into table mydata.\n endmethod.\nendclass."
}
] |
Median in a row-wise sorted Matrix | Practice | GeeksforGeeks
|
Given a row wise sorted matrix of size RxC where R and C are always odd, find the median of the matrix.
Example 1:
Input:
R = 3, C = 3
M = [[1, 3, 5],
[2, 6, 9],
[3, 6, 9]]
Output: 5
Explanation:
Sorting matrix elements gives us
{1,2,3,3,5,6,6,9,9}. Hence, 5 is median.
Example 2:
Input:
R = 3, C = 1
M = [[1], [2], [3]]
Output: 2
Your Task:
You don't need to read input or print anything. Your task is to complete the function median() which takes the integers R and C along with the 2D matrix as input parameters and returns the median of the matrix.
Expected Time Complexity: O(32 * R * log(C))
Expected Auxiliary Space: O(1)
Constraints:
1<= R,C <=150
1<= matrix[i][j] <=2000
0
ashu0120024 days ago
vector<int> v; int s=r*c; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ v.push_back(m[i][j]); } } sort(v.begin(),v.end()); return v[(s/2)];
+1
kshitij14101 week ago
int median(vector<vector<int>> &matrix, int r, int c){ int ans=-1; int high=2000; int low=1; int medianplace=((r*c)/2)+1 ; while(low<=high) { int mid=(low+high)/2; int count=0; for(int i=0;i<r;i++) { count+=upper_bound(matrix[i].begin(),matrix[i].end(),mid) -matrix[i].begin(); } if(count>=medianplace) { ans=mid; high=mid-1; } else low=mid+1; } return ans; }
0
anishmeena0011 week ago
int median(vector<vector<int>> &matrix, int r, int c){ // code here int k=0; int n=r*c; int ans[n]; for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { k=i*c+j; ans[k]=matrix[i][j]; } } sort(ans,ans+n); int median =ans[n/2]; return median; }
+3
mridulkapoor1234561 week ago
class Solution{
public:
int CountSmallerThanMid(vector<int>&row,int mid){
int lo=0, hi=row.size()-1;
while(lo<=hi){
int md=(lo+hi)/2;
if(row[md]<=mid)
lo=md+1;
else
hi=md-1;
}
return lo;
}
int median(vector<vector<int>> &matrix, int r, int c){
int lo=1;
int hi=1e9;
while(lo<=hi){
int mid=(lo+hi)/2;
int cnt=0;
for(int i=0;i<r;i++){
cnt+=CountSmallerThanMid(matrix[i],mid);
}
if(cnt<=r*c/2)
lo=mid+1;
else hi=mid-1;
}
return lo;
}
};
0
iit20202182 weeks ago
bool helper(int mid,vector<vector<int>> &mat,int r,int c){ int n = r*c; int ans1 = 0; for(int i=0;i<r;i++){ int temp = upper_bound(mat[i].begin(),mat[i].end(),mid)-mat[i].begin(); ans1 += temp; } if(ans1 <= (n/2)){ return true; } return false; } int BinarySearch(int s,int e,vector<vector<int>> &mat, int r, int c){ int ans; while((e-s)>1){ int mid = s+((e-s)/2); if(helper(mid,mat,r,c)){ s=mid+1; //ans=mid; }else{ e=mid; ans=mid; } } if(!helper(s,mat,r,c))return s; if(!helper(e,mat,r,c))return e; return ans; } int median(vector<vector<int>> &mat, int r, int c){ // code here int mini = 100000; int maxi = 0; for(int i=0;i<r;i++){ mini = min(mini,mat[i][0]); maxi = max(maxi,mat[i][c-1]); } return BinarySearch(1,2000,mat,r,c); }
Using BinarySearch in O(1) space and O(r*logc) complexity
+1
harshit68rocking2 weeks ago
vector<int> merge(vector<int> &a, vector<int> &b){
int m = a.size();
int n= b.size();
int i=0,j=0,k=0;
vector<int> c(m+n);
while(i<m && j<n){
if(a[i]<=b[j]){
c[k] = a[i]; i++;k++;
}
else if(a[i]>=b[j]){
c[k] = b[j]; j++;k++;
}
}
if(i<m){
while(i<m){
c[k] = a[i];i++;k++;
}
}
if(j<n){
while(j<n){
c[k] = b[j];j++;k++;
}
}
return c;
}
int median(vector<vector<int>> &matrix, int r, int c){
// code here
vector<int> v;
for(int i=0;i<r;i++){
v = merge(v,matrix[i]);
}
return v[(r*c)/2];
}
};
-4
yashvardhansingh20192 weeks ago
//Java Simple
int k=0; int[] ans = new int[r*c]; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ k = i*c+j; ans[k] = matrix[i][j]; } } Arrays.sort(ans); return ans[(r*c)/2];
-5
karthikbhatp3 weeks ago
class Solution { int median(int matrix[][], int r, int c) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { list.add(matrix[i][j]); } } int[] values = new int[list.size()]; for (int i = 0; i < list.size(); i++) { values[i] = list.get(i); }
Arrays.sort(values); int median; int totalElements = values.length; if (totalElements % 2 == 0) { int sumOfMiddleElements = values[totalElements / 2] + values[totalElements / 2 - 1]; median = sumOfMiddleElements / 2; } else { median = values[values.length / 2]; } return median; } }
-3
dibyendudey3033 weeks ago
Fast and Simple C++ solution:
class Solution{
public:
int median(vector<vector<int>> &matrix, int r, int c){
// code here
vector<int> v;
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
v.push_back(matrix[i][j]);
}
}
sort(v.begin(),v.end());
int pos=(v.size()/2);
return v[pos];
}
};
-3
arthurshelby4 weeks ago
😉🇮🇳✌️❄️
class Solution{
public:
int median(vector<vector<int>> &matrix, int r, int c){
// code here
vector<int> vc;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
vc.push_back(matrix[i][j]);
}
}
sort(vc.begin(),vc.end());
return vc[vc.size()/2];
}
};
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": 342,
"s": 238,
"text": "Given a row wise sorted matrix of size RxC where R and C are always odd, find the median of the matrix."
},
{
"code": null,
"e": 353,
"s": 342,
"text": "Example 1:"
},
{
"code": null,
"e": 525,
"s": 353,
"text": "Input:\nR = 3, C = 3\nM = [[1, 3, 5], \n [2, 6, 9], \n [3, 6, 9]]\n\nOutput: 5\n\nExplanation:\nSorting matrix elements gives us \n{1,2,3,3,5,6,6,9,9}. Hence, 5 is median. \n"
},
{
"code": null,
"e": 538,
"s": 527,
"text": "Example 2:"
},
{
"code": null,
"e": 589,
"s": 538,
"text": "Input:\nR = 3, C = 1\nM = [[1], [2], [3]]\nOutput: 2\n"
},
{
"code": null,
"e": 891,
"s": 589,
"text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function median() which takes the integers R and C along with the 2D matrix as input parameters and returns the median of the matrix.\n\nExpected Time Complexity: O(32 * R * log(C))\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 946,
"s": 891,
"text": "\nConstraints:\n1<= R,C <=150\n1<= matrix[i][j] <=2000\n\n "
},
{
"code": null,
"e": 948,
"s": 946,
"text": "0"
},
{
"code": null,
"e": 969,
"s": 948,
"text": "ashu0120024 days ago"
},
{
"code": null,
"e": 1171,
"s": 969,
"text": "vector<int> v; int s=r*c; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ v.push_back(m[i][j]); } } sort(v.begin(),v.end()); return v[(s/2)];"
},
{
"code": null,
"e": 1174,
"s": 1171,
"text": "+1"
},
{
"code": null,
"e": 1196,
"s": 1174,
"text": "kshitij14101 week ago"
},
{
"code": null,
"e": 1820,
"s": 1196,
"text": "int median(vector<vector<int>> &matrix, int r, int c){ int ans=-1; int high=2000; int low=1; int medianplace=((r*c)/2)+1 ; while(low<=high) { int mid=(low+high)/2; int count=0; for(int i=0;i<r;i++) { count+=upper_bound(matrix[i].begin(),matrix[i].end(),mid) -matrix[i].begin(); } if(count>=medianplace) { ans=mid; high=mid-1; } else low=mid+1; } return ans; }"
},
{
"code": null,
"e": 1822,
"s": 1820,
"text": "0"
},
{
"code": null,
"e": 1846,
"s": 1822,
"text": "anishmeena0011 week ago"
},
{
"code": null,
"e": 2219,
"s": 1846,
"text": "int median(vector<vector<int>> &matrix, int r, int c){ // code here int k=0; int n=r*c; int ans[n]; for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { k=i*c+j; ans[k]=matrix[i][j]; } } sort(ans,ans+n); int median =ans[n/2]; return median; }"
},
{
"code": null,
"e": 2222,
"s": 2219,
"text": "+3"
},
{
"code": null,
"e": 2251,
"s": 2222,
"text": "mridulkapoor1234561 week ago"
},
{
"code": null,
"e": 2949,
"s": 2251,
"text": "class Solution{ \npublic:\n int CountSmallerThanMid(vector<int>&row,int mid){\n int lo=0, hi=row.size()-1;\n while(lo<=hi){\n int md=(lo+hi)/2;\n if(row[md]<=mid)\n lo=md+1;\n else\n hi=md-1;\n }\n return lo;\n }\n\n int median(vector<vector<int>> &matrix, int r, int c){\n int lo=1;\n int hi=1e9;\n while(lo<=hi){\n int mid=(lo+hi)/2;\n int cnt=0;\n for(int i=0;i<r;i++){\n cnt+=CountSmallerThanMid(matrix[i],mid);\n }\n if(cnt<=r*c/2)\n lo=mid+1;\n else hi=mid-1;\n }\n return lo;\n }\n};"
},
{
"code": null,
"e": 2951,
"s": 2949,
"text": "0"
},
{
"code": null,
"e": 2973,
"s": 2951,
"text": "iit20202182 weeks ago"
},
{
"code": null,
"e": 3990,
"s": 2973,
"text": "bool helper(int mid,vector<vector<int>> &mat,int r,int c){ int n = r*c; int ans1 = 0; for(int i=0;i<r;i++){ int temp = upper_bound(mat[i].begin(),mat[i].end(),mid)-mat[i].begin(); ans1 += temp; } if(ans1 <= (n/2)){ return true; } return false; } int BinarySearch(int s,int e,vector<vector<int>> &mat, int r, int c){ int ans; while((e-s)>1){ int mid = s+((e-s)/2); if(helper(mid,mat,r,c)){ s=mid+1; //ans=mid; }else{ e=mid; ans=mid; } } if(!helper(s,mat,r,c))return s; if(!helper(e,mat,r,c))return e; return ans; } int median(vector<vector<int>> &mat, int r, int c){ // code here int mini = 100000; int maxi = 0; for(int i=0;i<r;i++){ mini = min(mini,mat[i][0]); maxi = max(maxi,mat[i][c-1]); } return BinarySearch(1,2000,mat,r,c); }"
},
{
"code": null,
"e": 4052,
"s": 3994,
"text": "Using BinarySearch in O(1) space and O(r*logc) complexity"
},
{
"code": null,
"e": 4055,
"s": 4052,
"text": "+1"
},
{
"code": null,
"e": 4083,
"s": 4055,
"text": "harshit68rocking2 weeks ago"
},
{
"code": null,
"e": 4896,
"s": 4083,
"text": " vector<int> merge(vector<int> &a, vector<int> &b){\n int m = a.size();\n int n= b.size();\n int i=0,j=0,k=0;\n vector<int> c(m+n);\n while(i<m && j<n){\n if(a[i]<=b[j]){\n c[k] = a[i]; i++;k++;\n }\n else if(a[i]>=b[j]){\n c[k] = b[j]; j++;k++;\n }\n }\n if(i<m){\n while(i<m){\n c[k] = a[i];i++;k++;\n }\n }\n if(j<n){\n while(j<n){\n c[k] = b[j];j++;k++;\n }\n }\n return c;\n }\n \n int median(vector<vector<int>> &matrix, int r, int c){\n // code here \n vector<int> v;\n for(int i=0;i<r;i++){\n v = merge(v,matrix[i]);\n }\n return v[(r*c)/2];\n }\n};"
},
{
"code": null,
"e": 4899,
"s": 4896,
"text": "-4"
},
{
"code": null,
"e": 4931,
"s": 4899,
"text": "yashvardhansingh20192 weeks ago"
},
{
"code": null,
"e": 4945,
"s": 4931,
"text": "//Java Simple"
},
{
"code": null,
"e": 5186,
"s": 4945,
"text": " int k=0; int[] ans = new int[r*c]; for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ k = i*c+j; ans[k] = matrix[i][j]; } } Arrays.sort(ans); return ans[(r*c)/2];"
},
{
"code": null,
"e": 5189,
"s": 5186,
"text": "-5"
},
{
"code": null,
"e": 5213,
"s": 5189,
"text": "karthikbhatp3 weeks ago"
},
{
"code": null,
"e": 5532,
"s": 5213,
"text": "class Solution { int median(int matrix[][], int r, int c) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { list.add(matrix[i][j]); } } int[] values = new int[list.size()]; for (int i = 0; i < list.size(); i++) { values[i] = list.get(i); }"
},
{
"code": null,
"e": 5848,
"s": 5532,
"text": " Arrays.sort(values); int median; int totalElements = values.length; if (totalElements % 2 == 0) { int sumOfMiddleElements = values[totalElements / 2] + values[totalElements / 2 - 1]; median = sumOfMiddleElements / 2; } else { median = values[values.length / 2]; } return median; } }"
},
{
"code": null,
"e": 5851,
"s": 5848,
"text": "-3"
},
{
"code": null,
"e": 5877,
"s": 5851,
"text": "dibyendudey3033 weeks ago"
},
{
"code": null,
"e": 5907,
"s": 5877,
"text": "Fast and Simple C++ solution:"
},
{
"code": null,
"e": 6295,
"s": 5907,
"text": "class Solution{ \npublic:\n int median(vector<vector<int>> &matrix, int r, int c){\n // code here \n vector<int> v;\n for(int i=0;i<r;i++)\n {\n for(int j=0;j<c;j++)\n {\n v.push_back(matrix[i][j]);\n }\n }\n sort(v.begin(),v.end());\n int pos=(v.size()/2);\n return v[pos];\n }\n};"
},
{
"code": null,
"e": 6298,
"s": 6295,
"text": "-3"
},
{
"code": null,
"e": 6322,
"s": 6298,
"text": "arthurshelby4 weeks ago"
},
{
"code": null,
"e": 6694,
"s": 6322,
"text": "😉🇮🇳✌️❄️\nclass Solution{ \npublic:\n int median(vector<vector<int>> &matrix, int r, int c){\n // code here \n vector<int> vc;\n for(int i=0;i<r;i++){\n for(int j=0;j<c;j++){\n vc.push_back(matrix[i][j]);\n }\n }\n sort(vc.begin(),vc.end());\n \n return vc[vc.size()/2];\n }\n \n};"
},
{
"code": null,
"e": 6840,
"s": 6694,
"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": 6876,
"s": 6840,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6886,
"s": 6876,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6896,
"s": 6886,
"text": "\nContest\n"
},
{
"code": null,
"e": 6959,
"s": 6896,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7107,
"s": 6959,
"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": 7315,
"s": 7107,
"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": 7421,
"s": 7315,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Understanding ROC Curves with Python | by Lucas Soares | Towards Data Science
|
If you google: “ROC curve machine learning”, you get a Wikipedia answer like this:
A receiver operating characteristic curve, or ROC curve, is a graphical plot that illustrates the diagnostic ability of a binary classifier system as its discrimination threshold is varied
Another common description is that the ROC Curve reflects the sensitivity of the model across different classification thresholds. When I was starting out in Machine Learning, these definitions would always confuse me.
In this article, I will share how I learned to disentangle my “beginner-like” confusions and develop a good enough intuition about the ROC curve.
One way to understand the ROC curve is that it describes a relationship between the model’s sensitivity (the true-positive rate or TPR) versus it’s specificity (described with respect to the false-positive rate: 1-FPR).
Now, let’s disentangle each concept here.
The TPR, known as the sensitivity of the model, is the ratio of correct classifications of the “positive” class divided by all the positive classes available in the dataset, mathematically:
while the FPR is the ratio between false positives (number of predictions misclassified as positives) and all the negative classes available, mathematically:
So in essence, you are comparing how the sensitivity of the model changes with respect to the false-positive rate across different threshold scores that reflect a decision boundary of the model to classify an input as positive.
The intuition that alluded me, in the beginning, was to grasp the role of the threshold score. One good starting point is to build a mental picture:
With this classic visualization, one can learn the first intuition, which is that the ideal model is one with the true positive rate as high as possible while keeping the false positive rate as low as possible.
The threshold corresponds to some value T (like a value between 0 and 1 for example) that serves as the decision boundary for the classifier and it affects the trade-off between TPR and FPR.
Let’s write some code to get a visual of all of these components.
The steps to visualize this will be:
Import our dependenciesDraw some fake data with the drawdata package for Jupyter notebooksImport the fake data to a pandas dataframeFit a logistic regression model on the dataGet predictions of the logistic regression model in the form of probability valuesSet different threshold scoresVisualize the roc curve plotDraw some final conclusions
Import our dependencies
Draw some fake data with the drawdata package for Jupyter notebooks
Import the fake data to a pandas dataframe
Fit a logistic regression model on the data
Get predictions of the logistic regression model in the form of probability values
Set different threshold scores
Visualize the roc curve plot
Draw some final conclusions
from drawdata import draw_scatterimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_score, precision_recall_curve,precision_score, plot_roc_curve
draw_scatter()
Output:
df = pd.read_csv("./data.csv")
def get_fp_tp(y, proba, threshold): """Return the number of false positives and true positives.""" # source: https://towardsdatascience.com/roc-curve-explained-50acab4f7bd8 # Classify into classes pred = pd.Series(np.where(proba>=threshold, 1, 0), dtype='category') pred.cat.set_categories([0,1], inplace=True) # Create confusion matrix confusion_matrix = pred.groupby([y, pred]).size().unstack()\ .rename(columns={0: 'pred_0', 1: 'pred_1'}, index={0: 'actual_0', 1: 'actual_1'}) false_positives = confusion_matrix.loc['actual_0', 'pred_1'] true_positives = confusion_matrix.loc['actual_1', 'pred_1'] return false_positives, true_positives# train test split on the fake generated datasetX = df[["x", "y"]].valuesY = df["z"].valuesX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=42)y_test = np.array([1 if p=="a" else 0 for p in y_test])y_train = np.array([1 if p=="a" else 0 for p in y_train])# create the modellgr = LogisticRegression()lgr.fit(X_train, y_train)
y_hat = lgr.predict_proba(X_test)[:,1]
thresholds = np.linspace(0,1,100)
# defining fpr and tprtpr = []fpr = []# defining positives and negativespositives = np.sum(y_test==1)negatives = np.sum(y_test==0)# looping over threshold scores and getting the number of false positives and true positivesfor th in thresholds: fp,tp = get_fp_tp(y_test, y_hat, th) tpr.append(tp/positives) fpr.append(fp/negatives) plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',label='Random', alpha=.8)plt.plot(fpr,tpr, label="ROC Curve",color="blue")plt.text(0.5, 0.5, "varying threshold scores (0-1)", rotation=0, size=12,ha="center", va="center",bbox=dict(boxstyle="rarrow"))plt.xlabel("False Positve Rate")plt.ylabel("True Positive Rate")plt.legend()plt.show()
By varying the threshold scores we get increasing values of both true positive and false-positive rates. A good model is one where the threshold score puts the true positive rate as close as possible to 1 while keeping the false positive rate as low as possible.
But, how could we choose the best classification threshold?
A simple method is to take the one with the maximal sum of true positive and false-negative rates (1- FPR).
Another criterion could be to simply choose the point closest to the top left corner of your ROC space. However, that implies that the true positive rate and the true negative rate have the same weight (source), which is not necessarily true in cases like cancer classification where the negative impact of a false positive is bigger than the impact of a true positive.
I think taking some time to digest evaluation metrics is extremely beneficial in the long run for your machine learning journey. In this article you learned:
A basic intuition on how ROC curves work
How classification thresholds affect the relationship between the sensitivity and specificity of a model
An intuition on how to use the ROC curve to set an optimal classification threshold
If you want to learn more about Python for Machine Learning, check out these courses:
These are affiliate links, if you use them I get a small commission, cheers! :)
Machine Learning A-ZTM: Hands-On Python & R In Data Science
Python for Data Science and Machine Learning Bootcamp
If you liked this post, follow me on Medium, subscribe to my newsletter, connect with me on Twitter, LinkedIn, Instagram, or join Medium! Thanks and see you next time! :)
Awesome tutorial on the ROC Curve
Stack exchange thread on the ROC Curve
Wikipedia page on the ROC Curve
Neat article by Zolzaya Luvsandorj about ROC Curves with Python
|
[
{
"code": null,
"e": 254,
"s": 171,
"text": "If you google: “ROC curve machine learning”, you get a Wikipedia answer like this:"
},
{
"code": null,
"e": 443,
"s": 254,
"text": "A receiver operating characteristic curve, or ROC curve, is a graphical plot that illustrates the diagnostic ability of a binary classifier system as its discrimination threshold is varied"
},
{
"code": null,
"e": 662,
"s": 443,
"text": "Another common description is that the ROC Curve reflects the sensitivity of the model across different classification thresholds. When I was starting out in Machine Learning, these definitions would always confuse me."
},
{
"code": null,
"e": 808,
"s": 662,
"text": "In this article, I will share how I learned to disentangle my “beginner-like” confusions and develop a good enough intuition about the ROC curve."
},
{
"code": null,
"e": 1028,
"s": 808,
"text": "One way to understand the ROC curve is that it describes a relationship between the model’s sensitivity (the true-positive rate or TPR) versus it’s specificity (described with respect to the false-positive rate: 1-FPR)."
},
{
"code": null,
"e": 1070,
"s": 1028,
"text": "Now, let’s disentangle each concept here."
},
{
"code": null,
"e": 1260,
"s": 1070,
"text": "The TPR, known as the sensitivity of the model, is the ratio of correct classifications of the “positive” class divided by all the positive classes available in the dataset, mathematically:"
},
{
"code": null,
"e": 1418,
"s": 1260,
"text": "while the FPR is the ratio between false positives (number of predictions misclassified as positives) and all the negative classes available, mathematically:"
},
{
"code": null,
"e": 1646,
"s": 1418,
"text": "So in essence, you are comparing how the sensitivity of the model changes with respect to the false-positive rate across different threshold scores that reflect a decision boundary of the model to classify an input as positive."
},
{
"code": null,
"e": 1795,
"s": 1646,
"text": "The intuition that alluded me, in the beginning, was to grasp the role of the threshold score. One good starting point is to build a mental picture:"
},
{
"code": null,
"e": 2006,
"s": 1795,
"text": "With this classic visualization, one can learn the first intuition, which is that the ideal model is one with the true positive rate as high as possible while keeping the false positive rate as low as possible."
},
{
"code": null,
"e": 2197,
"s": 2006,
"text": "The threshold corresponds to some value T (like a value between 0 and 1 for example) that serves as the decision boundary for the classifier and it affects the trade-off between TPR and FPR."
},
{
"code": null,
"e": 2263,
"s": 2197,
"text": "Let’s write some code to get a visual of all of these components."
},
{
"code": null,
"e": 2300,
"s": 2263,
"text": "The steps to visualize this will be:"
},
{
"code": null,
"e": 2643,
"s": 2300,
"text": "Import our dependenciesDraw some fake data with the drawdata package for Jupyter notebooksImport the fake data to a pandas dataframeFit a logistic regression model on the dataGet predictions of the logistic regression model in the form of probability valuesSet different threshold scoresVisualize the roc curve plotDraw some final conclusions"
},
{
"code": null,
"e": 2667,
"s": 2643,
"text": "Import our dependencies"
},
{
"code": null,
"e": 2735,
"s": 2667,
"text": "Draw some fake data with the drawdata package for Jupyter notebooks"
},
{
"code": null,
"e": 2778,
"s": 2735,
"text": "Import the fake data to a pandas dataframe"
},
{
"code": null,
"e": 2822,
"s": 2778,
"text": "Fit a logistic regression model on the data"
},
{
"code": null,
"e": 2905,
"s": 2822,
"text": "Get predictions of the logistic regression model in the form of probability values"
},
{
"code": null,
"e": 2936,
"s": 2905,
"text": "Set different threshold scores"
},
{
"code": null,
"e": 2965,
"s": 2936,
"text": "Visualize the roc curve plot"
},
{
"code": null,
"e": 2993,
"s": 2965,
"text": "Draw some final conclusions"
},
{
"code": null,
"e": 3247,
"s": 2993,
"text": "from drawdata import draw_scatterimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_score, precision_recall_curve,precision_score, plot_roc_curve"
},
{
"code": null,
"e": 3262,
"s": 3247,
"text": "draw_scatter()"
},
{
"code": null,
"e": 3270,
"s": 3262,
"text": "Output:"
},
{
"code": null,
"e": 3301,
"s": 3270,
"text": "df = pd.read_csv(\"./data.csv\")"
},
{
"code": null,
"e": 4500,
"s": 3301,
"text": "def get_fp_tp(y, proba, threshold): \"\"\"Return the number of false positives and true positives.\"\"\" # source: https://towardsdatascience.com/roc-curve-explained-50acab4f7bd8 # Classify into classes pred = pd.Series(np.where(proba>=threshold, 1, 0), dtype='category') pred.cat.set_categories([0,1], inplace=True) # Create confusion matrix confusion_matrix = pred.groupby([y, pred]).size().unstack()\\ .rename(columns={0: 'pred_0', 1: 'pred_1'}, index={0: 'actual_0', 1: 'actual_1'}) false_positives = confusion_matrix.loc['actual_0', 'pred_1'] true_positives = confusion_matrix.loc['actual_1', 'pred_1'] return false_positives, true_positives# train test split on the fake generated datasetX = df[[\"x\", \"y\"]].valuesY = df[\"z\"].valuesX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=42)y_test = np.array([1 if p==\"a\" else 0 for p in y_test])y_train = np.array([1 if p==\"a\" else 0 for p in y_train])# create the modellgr = LogisticRegression()lgr.fit(X_train, y_train)"
},
{
"code": null,
"e": 4539,
"s": 4500,
"text": "y_hat = lgr.predict_proba(X_test)[:,1]"
},
{
"code": null,
"e": 4573,
"s": 4539,
"text": "thresholds = np.linspace(0,1,100)"
},
{
"code": null,
"e": 5261,
"s": 4573,
"text": "# defining fpr and tprtpr = []fpr = []# defining positives and negativespositives = np.sum(y_test==1)negatives = np.sum(y_test==0)# looping over threshold scores and getting the number of false positives and true positivesfor th in thresholds: fp,tp = get_fp_tp(y_test, y_hat, th) tpr.append(tp/positives) fpr.append(fp/negatives) plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',label='Random', alpha=.8)plt.plot(fpr,tpr, label=\"ROC Curve\",color=\"blue\")plt.text(0.5, 0.5, \"varying threshold scores (0-1)\", rotation=0, size=12,ha=\"center\", va=\"center\",bbox=dict(boxstyle=\"rarrow\"))plt.xlabel(\"False Positve Rate\")plt.ylabel(\"True Positive Rate\")plt.legend()plt.show()"
},
{
"code": null,
"e": 5524,
"s": 5261,
"text": "By varying the threshold scores we get increasing values of both true positive and false-positive rates. A good model is one where the threshold score puts the true positive rate as close as possible to 1 while keeping the false positive rate as low as possible."
},
{
"code": null,
"e": 5584,
"s": 5524,
"text": "But, how could we choose the best classification threshold?"
},
{
"code": null,
"e": 5692,
"s": 5584,
"text": "A simple method is to take the one with the maximal sum of true positive and false-negative rates (1- FPR)."
},
{
"code": null,
"e": 6062,
"s": 5692,
"text": "Another criterion could be to simply choose the point closest to the top left corner of your ROC space. However, that implies that the true positive rate and the true negative rate have the same weight (source), which is not necessarily true in cases like cancer classification where the negative impact of a false positive is bigger than the impact of a true positive."
},
{
"code": null,
"e": 6220,
"s": 6062,
"text": "I think taking some time to digest evaluation metrics is extremely beneficial in the long run for your machine learning journey. In this article you learned:"
},
{
"code": null,
"e": 6261,
"s": 6220,
"text": "A basic intuition on how ROC curves work"
},
{
"code": null,
"e": 6366,
"s": 6261,
"text": "How classification thresholds affect the relationship between the sensitivity and specificity of a model"
},
{
"code": null,
"e": 6450,
"s": 6366,
"text": "An intuition on how to use the ROC curve to set an optimal classification threshold"
},
{
"code": null,
"e": 6536,
"s": 6450,
"text": "If you want to learn more about Python for Machine Learning, check out these courses:"
},
{
"code": null,
"e": 6616,
"s": 6536,
"text": "These are affiliate links, if you use them I get a small commission, cheers! :)"
},
{
"code": null,
"e": 6676,
"s": 6616,
"text": "Machine Learning A-ZTM: Hands-On Python & R In Data Science"
},
{
"code": null,
"e": 6730,
"s": 6676,
"text": "Python for Data Science and Machine Learning Bootcamp"
},
{
"code": null,
"e": 6901,
"s": 6730,
"text": "If you liked this post, follow me on Medium, subscribe to my newsletter, connect with me on Twitter, LinkedIn, Instagram, or join Medium! Thanks and see you next time! :)"
},
{
"code": null,
"e": 6935,
"s": 6901,
"text": "Awesome tutorial on the ROC Curve"
},
{
"code": null,
"e": 6974,
"s": 6935,
"text": "Stack exchange thread on the ROC Curve"
},
{
"code": null,
"e": 7006,
"s": 6974,
"text": "Wikipedia page on the ROC Curve"
}
] |
How to add special characters to text to print in color in the console in JavaScript ? - GeeksforGeeks
|
15 Apr, 2021
The purpose of this article is to add special characters to text to print in color in the console in JavaScript.
Approach: The ANSI escape codes help change/specify the color of the output in the console. The color of the output of the console can be changed by adding these escape codes just before the actual text.
Syntax:
/*Codes for different Colors*/
black = "\x1b[30m"
red = "\x1b[31m"
green = "\x1b[32m"
yellow = "\x1b[33m"
blue = "\x1b[34m"
magenta = "\x1b[35m"
cyan = "\x1b[36m"
white = "\x1b[37m"
Example :
Javascript
<script> console.log("\x1b[31m"+ "Red"); console.log("\x1b[32m"+ "Green"); console.log("\x1b[35m"+ "Magenta");</script>
Output:
Note: The above task can be simplified by adding a custom helper function in the script which can be invoked with the color and data to be displayed in the console.
Example: The following is the JavaScript code for performing the task using a custom helper function.
Javascript
<script>function colorHelper(color,data){ /* function receives 2 arguments color and data*/ const black = "\x1b[30m"; const red = "\x1b[31m"; const green = "\x1b[32m"; const yellow = "\x1b[33m"; const blue = "\x1b[34m"; const magenta = "\x1b[35m"; const cyan = "\x1b[36m"; const white = "\x1b[37m"; const arr=[]; /* Storing the color codes in Array */ arr[0] = black; arr[1] = red; arr[2] = green; arr[3] = yellow; arr[4] = blue; arr[5] = magenta; arr[6] = cyan; arr[7] = white; console.log(arr[color]+data);} /* colorHelper function called with color and data */colorHelper(1,"I am Red"); colorHelper(2,"I am Green");colorHelper(5,"I am Magenta");</script>
Output:
javascript-basics
Picked
JavaScript
Web Technologies
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 PUT and PATCH Request
How to detect browser or tab closing in JavaScript ?
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25246,
"s": 25218,
"text": "\n15 Apr, 2021"
},
{
"code": null,
"e": 25359,
"s": 25246,
"text": "The purpose of this article is to add special characters to text to print in color in the console in JavaScript."
},
{
"code": null,
"e": 25564,
"s": 25359,
"text": "Approach: The ANSI escape codes help change/specify the color of the output in the console. The color of the output of the console can be changed by adding these escape codes just before the actual text. "
},
{
"code": null,
"e": 25573,
"s": 25564,
"text": "Syntax: "
},
{
"code": null,
"e": 25755,
"s": 25573,
"text": "/*Codes for different Colors*/\nblack = \"\\x1b[30m\"\nred = \"\\x1b[31m\"\ngreen = \"\\x1b[32m\"\nyellow = \"\\x1b[33m\"\nblue = \"\\x1b[34m\"\nmagenta = \"\\x1b[35m\"\ncyan = \"\\x1b[36m\"\nwhite = \"\\x1b[37m\""
},
{
"code": null,
"e": 25766,
"s": 25755,
"text": "Example : "
},
{
"code": null,
"e": 25777,
"s": 25766,
"text": "Javascript"
},
{
"code": "<script> console.log(\"\\x1b[31m\"+ \"Red\"); console.log(\"\\x1b[32m\"+ \"Green\"); console.log(\"\\x1b[35m\"+ \"Magenta\");</script>",
"e": 25900,
"s": 25777,
"text": null
},
{
"code": null,
"e": 25908,
"s": 25900,
"text": "Output:"
},
{
"code": null,
"e": 26073,
"s": 25908,
"text": "Note: The above task can be simplified by adding a custom helper function in the script which can be invoked with the color and data to be displayed in the console."
},
{
"code": null,
"e": 26175,
"s": 26073,
"text": "Example: The following is the JavaScript code for performing the task using a custom helper function."
},
{
"code": null,
"e": 26186,
"s": 26175,
"text": "Javascript"
},
{
"code": "<script>function colorHelper(color,data){ /* function receives 2 arguments color and data*/ const black = \"\\x1b[30m\"; const red = \"\\x1b[31m\"; const green = \"\\x1b[32m\"; const yellow = \"\\x1b[33m\"; const blue = \"\\x1b[34m\"; const magenta = \"\\x1b[35m\"; const cyan = \"\\x1b[36m\"; const white = \"\\x1b[37m\"; const arr=[]; /* Storing the color codes in Array */ arr[0] = black; arr[1] = red; arr[2] = green; arr[3] = yellow; arr[4] = blue; arr[5] = magenta; arr[6] = cyan; arr[7] = white; console.log(arr[color]+data);} /* colorHelper function called with color and data */colorHelper(1,\"I am Red\"); colorHelper(2,\"I am Green\");colorHelper(5,\"I am Magenta\");</script>",
"e": 26896,
"s": 26186,
"text": null
},
{
"code": null,
"e": 26905,
"s": 26896,
"text": "Output: "
},
{
"code": null,
"e": 26923,
"s": 26905,
"text": "javascript-basics"
},
{
"code": null,
"e": 26930,
"s": 26923,
"text": "Picked"
},
{
"code": null,
"e": 26941,
"s": 26930,
"text": "JavaScript"
},
{
"code": null,
"e": 26958,
"s": 26941,
"text": "Web Technologies"
},
{
"code": null,
"e": 27056,
"s": 26958,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27065,
"s": 27056,
"text": "Comments"
},
{
"code": null,
"e": 27078,
"s": 27065,
"text": "Old Comments"
},
{
"code": null,
"e": 27139,
"s": 27078,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27180,
"s": 27139,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27233,
"s": 27180,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 27287,
"s": 27233,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27335,
"s": 27287,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27377,
"s": 27335,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27410,
"s": 27377,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27472,
"s": 27410,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27515,
"s": 27472,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
ASP.NET Core - Project Layout
|
In this chapter, we will discuss how ASP.NET core project appears on the file system and how the different files and directories all work together.
Let us open the FirstAppDemo project created in the previous chapter.
In the Solution Explorer window, right-click on the Solution node and select the Open Folder in File Explorer.
You will see now the root directory with two files in it: FirstAppDemo.sln and global.json.
FirstAppDemo.sln is a solution file. Visual Studio has used this extension for years by default, and you can double-click on the file if you want to open the app in Studio and work on it.
There is also a global.json file. Let us open this file in Visual Studio.
In the file, the project's setting is significant. This project setting tells ASP.NET where to look for your source code and what folders contain your projects.
There are two possible folders “src” for source and a “test” folder. Unless your projects and source code are in one of these two folders, the code won't be available to build. You can change these settings if you want.
The Windows Explorer has the “src” folder on disk. You don't have a test folder. In the test folder, you could place your unit testing projects. Let us double-click on the “src” folder.
You can see the FirstAppDemo project, and the web application. Now, double-click on the folder.
These are the source code files for the application and you can also see this folder structure in the Solution Explorer window. This is because in the present version of ASP.NET Core, the file system determines what is in your project.
If you add a new file to the disk, the file will be added to the project. If you delete a file, the file is removed from the project. Everything stays in sync and that is a little bit different than previous versions of ASP.NET Core where a project file, a *.cs proj file, that contained a manifest of everything that is in the project.
ASP.NET Core also compiles your application when a file changes or a new file appears.
Let us see a simple example by opening the Startup.cs file in the text editor.
It is this line of code that responds to every HTTP request to your application and it simply responds with Hello World!
Let us change the string in the above screenshot by saying “Hello World! This ASP.NET Core Application” as shown in the following program.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FirstAppDemo {
public class Startup {
// This method gets called by the runtime.
// Use this method to add services to the container.
// For more information on how to configure your application,
// visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) {
}
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory) {
loggerFactory.AddConsole();
if (env.IsDevelopment()){
app.UseDeveloperExceptionPage();
}
app.Run(async (context) => {
await context.Response.WriteAsync(
"Hello World! This ASP.NET Core Application");
});
}
}
}
Save this file in the text editor by pressing Ctrl + S and then go back to the web browser and refresh the application.
You can now see that your changes are reflected in the browser.
This is because ASP.NET will monitor the file system and automatically recompile the application when a file changes. You don't need to explicitly build the application in Visual Studio.
This is because ASP.NET will monitor the file system and automatically recompile the application when a file changes. You don't need to explicitly build the application in Visual Studio.
In fact, you can use a completely different editor, something like Visual Studio Code.
In fact, you can use a completely different editor, something like Visual Studio Code.
All you need to do with the Visual Studio is get the web server started by running without the debugger. You can also press Ctrl + F5, and can edit files, save files, and just refresh the browser to see the changes.
All you need to do with the Visual Studio is get the web server started by running without the debugger. You can also press Ctrl + F5, and can edit files, save files, and just refresh the browser to see the changes.
This is a nice workflow for building web applications with a compiled language like C#.
This is a nice workflow for building web applications with a compiled language like C#.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2609,
"s": 2461,
"text": "In this chapter, we will discuss how ASP.NET core project appears on the file system and how the different files and directories all work together."
},
{
"code": null,
"e": 2679,
"s": 2609,
"text": "Let us open the FirstAppDemo project created in the previous chapter."
},
{
"code": null,
"e": 2790,
"s": 2679,
"text": "In the Solution Explorer window, right-click on the Solution node and select the Open Folder in File Explorer."
},
{
"code": null,
"e": 2882,
"s": 2790,
"text": "You will see now the root directory with two files in it: FirstAppDemo.sln and global.json."
},
{
"code": null,
"e": 3070,
"s": 2882,
"text": "FirstAppDemo.sln is a solution file. Visual Studio has used this extension for years by default, and you can double-click on the file if you want to open the app in Studio and work on it."
},
{
"code": null,
"e": 3144,
"s": 3070,
"text": "There is also a global.json file. Let us open this file in Visual Studio."
},
{
"code": null,
"e": 3305,
"s": 3144,
"text": "In the file, the project's setting is significant. This project setting tells ASP.NET where to look for your source code and what folders contain your projects."
},
{
"code": null,
"e": 3525,
"s": 3305,
"text": "There are two possible folders “src” for source and a “test” folder. Unless your projects and source code are in one of these two folders, the code won't be available to build. You can change these settings if you want."
},
{
"code": null,
"e": 3711,
"s": 3525,
"text": "The Windows Explorer has the “src” folder on disk. You don't have a test folder. In the test folder, you could place your unit testing projects. Let us double-click on the “src” folder."
},
{
"code": null,
"e": 3807,
"s": 3711,
"text": "You can see the FirstAppDemo project, and the web application. Now, double-click on the folder."
},
{
"code": null,
"e": 4043,
"s": 3807,
"text": "These are the source code files for the application and you can also see this folder structure in the Solution Explorer window. This is because in the present version of ASP.NET Core, the file system determines what is in your project."
},
{
"code": null,
"e": 4380,
"s": 4043,
"text": "If you add a new file to the disk, the file will be added to the project. If you delete a file, the file is removed from the project. Everything stays in sync and that is a little bit different than previous versions of ASP.NET Core where a project file, a *.cs proj file, that contained a manifest of everything that is in the project."
},
{
"code": null,
"e": 4467,
"s": 4380,
"text": "ASP.NET Core also compiles your application when a file changes or a new file appears."
},
{
"code": null,
"e": 4546,
"s": 4467,
"text": "Let us see a simple example by opening the Startup.cs file in the text editor."
},
{
"code": null,
"e": 4667,
"s": 4546,
"text": "It is this line of code that responds to every HTTP request to your application and it simply responds with Hello World!"
},
{
"code": null,
"e": 4806,
"s": 4667,
"text": "Let us change the string in the above screenshot by saying “Hello World! This ASP.NET Core Application” as shown in the following program."
},
{
"code": null,
"e": 6042,
"s": 4806,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n\nusing Microsoft.AspNetCore.Builder; \nusing Microsoft.AspNetCore.Hosting; \nusing Microsoft.AspNetCore.Http; \n\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Logging; \n\nnamespace FirstAppDemo {\n public class Startup { \n // This method gets called by the runtime. \n // Use this method to add services to the container. \n // For more information on how to configure your application, \n // visit http://go.microsoft.com/fwlink/?LinkID=398940 \n public void ConfigureServices(IServiceCollection services) { \n } \n \n // This method gets called by the runtime. \n // Use this method to configure the HTTP request pipeline. \n public void Configure(IApplicationBuilder app, \n IHostingEnvironment env, ILoggerFactory loggerFactory) { \n loggerFactory.AddConsole(); \n \n if (env.IsDevelopment()){ \n app.UseDeveloperExceptionPage(); \n } \n app.Run(async (context) => { \n await context.Response.WriteAsync(\n \"Hello World! This ASP.NET Core Application\");\n });\n } \n } \n} "
},
{
"code": null,
"e": 6162,
"s": 6042,
"text": "Save this file in the text editor by pressing Ctrl + S and then go back to the web browser and refresh the application."
},
{
"code": null,
"e": 6226,
"s": 6162,
"text": "You can now see that your changes are reflected in the browser."
},
{
"code": null,
"e": 6413,
"s": 6226,
"text": "This is because ASP.NET will monitor the file system and automatically recompile the application when a file changes. You don't need to explicitly build the application in Visual Studio."
},
{
"code": null,
"e": 6600,
"s": 6413,
"text": "This is because ASP.NET will monitor the file system and automatically recompile the application when a file changes. You don't need to explicitly build the application in Visual Studio."
},
{
"code": null,
"e": 6687,
"s": 6600,
"text": "In fact, you can use a completely different editor, something like Visual Studio Code."
},
{
"code": null,
"e": 6774,
"s": 6687,
"text": "In fact, you can use a completely different editor, something like Visual Studio Code."
},
{
"code": null,
"e": 6990,
"s": 6774,
"text": "All you need to do with the Visual Studio is get the web server started by running without the debugger. You can also press Ctrl + F5, and can edit files, save files, and just refresh the browser to see the changes."
},
{
"code": null,
"e": 7206,
"s": 6990,
"text": "All you need to do with the Visual Studio is get the web server started by running without the debugger. You can also press Ctrl + F5, and can edit files, save files, and just refresh the browser to see the changes."
},
{
"code": null,
"e": 7294,
"s": 7206,
"text": "This is a nice workflow for building web applications with a compiled language like C#."
},
{
"code": null,
"e": 7382,
"s": 7294,
"text": "This is a nice workflow for building web applications with a compiled language like C#."
},
{
"code": null,
"e": 7417,
"s": 7382,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7431,
"s": 7417,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7466,
"s": 7431,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7489,
"s": 7466,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 7523,
"s": 7489,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 7543,
"s": 7523,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7578,
"s": 7543,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7595,
"s": 7578,
"text": " University Code"
},
{
"code": null,
"e": 7630,
"s": 7595,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7647,
"s": 7630,
"text": " University Code"
},
{
"code": null,
"e": 7681,
"s": 7647,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 7696,
"s": 7681,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 7703,
"s": 7696,
"text": " Print"
},
{
"code": null,
"e": 7714,
"s": 7703,
"text": " Add Notes"
}
] |
\backsimeq - Tex Command
|
\backsimeq - Command to show back sim equal symbol
{ \backsimeq }
\backsimeq command shows back sim symbol.
\backsimeq
⋍
\backsimeq
⋍
\backsimeq
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8037,
"s": 7986,
"text": "\\backsimeq - Command to show back sim equal symbol"
},
{
"code": null,
"e": 8052,
"s": 8037,
"text": "{ \\backsimeq }"
},
{
"code": null,
"e": 8094,
"s": 8052,
"text": "\\backsimeq command shows back sim symbol."
},
{
"code": null,
"e": 8113,
"s": 8094,
"text": "\n\\backsimeq \n\n⋍\n\n\n"
},
{
"code": null,
"e": 8130,
"s": 8113,
"text": "\\backsimeq \n\n⋍\n\n"
},
{
"code": null,
"e": 8142,
"s": 8130,
"text": "\\backsimeq "
},
{
"code": null,
"e": 8174,
"s": 8142,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8187,
"s": 8174,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8220,
"s": 8187,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8233,
"s": 8220,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8265,
"s": 8233,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8301,
"s": 8265,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8336,
"s": 8301,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8353,
"s": 8336,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8386,
"s": 8353,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8400,
"s": 8386,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8432,
"s": 8400,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8447,
"s": 8432,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8454,
"s": 8447,
"text": " Print"
},
{
"code": null,
"e": 8465,
"s": 8454,
"text": " Add Notes"
}
] |
How to change a table's fontsize with matplotlib.pyplot?
|
To change a table's fontsize with matplotlib, we can use set_fontsize() method.
Create a figure and a set of subplots, nrows=1 and ncols=1.
Create random data using numpy.
Create columns value.
Make the axis tight and off.
Initialize a variable fontsize to change the font size.
Set the font size of the table using set_font_size() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, axs = plt.subplots(1, 1)
data = np.random.random((10, 3))
columns = ("Column I", "Column II", "Column III")
axs.axis('tight')
axs.axis('off')
the_table = axs.table(cellText=data, colLabels=columns, loc='center')
the_table.auto_set_font_size(False)
the_table.set_fontsize(10)
plt.show()
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "To change a table's fontsize with matplotlib, we can use set_fontsize() method."
},
{
"code": null,
"e": 1202,
"s": 1142,
"text": "Create a figure and a set of subplots, nrows=1 and ncols=1."
},
{
"code": null,
"e": 1234,
"s": 1202,
"text": "Create random data using numpy."
},
{
"code": null,
"e": 1256,
"s": 1234,
"text": "Create columns value."
},
{
"code": null,
"e": 1285,
"s": 1256,
"text": "Make the axis tight and off."
},
{
"code": null,
"e": 1341,
"s": 1285,
"text": "Initialize a variable fontsize to change the font size."
},
{
"code": null,
"e": 1402,
"s": 1341,
"text": "Set the font size of the table using set_font_size() method."
},
{
"code": null,
"e": 1444,
"s": 1402,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1878,
"s": 1444,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nfig, axs = plt.subplots(1, 1)\ndata = np.random.random((10, 3))\ncolumns = (\"Column I\", \"Column II\", \"Column III\")\naxs.axis('tight')\naxs.axis('off')\nthe_table = axs.table(cellText=data, colLabels=columns, loc='center')\nthe_table.auto_set_font_size(False)\nthe_table.set_fontsize(10)\nplt.show()"
}
] |
Design a Drum-kit web app using JavaScript - GeeksforGeeks
|
08 Feb, 2021
We all must have seen a drum kit in some concert or elsewhere, it is a collection of drums, cymbals and other percussion instruments. But have you ever imagined making that drum kit on your own virtually with the help of some scripting language? Well, so here we are with the goal for this article to build a drum kit app that runs in the browser. The main concepts presented in the article are DOM, key events and CSS animations. So by the end of this article, you would have not only understood how to add event listeners to buttons and keystrokes so that you’ll know when the user is tapping on the keyboard or clicking on a particular button on your Website and you can respond to it, but you also end up with an awesome Website that you can impress all of your friends with.
Preview of the Website:
So the way this website would work that we’ve got a number of keys on the webpage that represents different drums in a typical drum set and when you click on any of those buttons then you’ll get the corresponding sound of the drum. And in addition you can also use the keys on the keyboard to have a sound effect.
Designing the HTML Layout: For the website, we only have seven buttons to display on the page, clicking upon which sound would be played. First we would add the DOCTYPE HTML format, then give a suitable title to the web page, in our case it is The Drum Kit . Inside the body tag, we would give a heading, say, The Drum Kit using h1 tag and display those seven buttons. The code for the same would be:
HTML
<!DOCTYPE html><html> <head> <title>The Drum Kit</title></head> <body> <h1>The Drum Kit</h1> <div class="all"> <button>w</button> <button>a</button> <button>s</button> <button>d</button> <button>j</button> <button>k</button> <button>l</button> </div></body> </html>
Output would be something like that:
Adding CSS Styling: CSS is used to style the different portions and make it more visually appealing. But, this is a personal opinion as to which style does the developer like the most. Feel free to use any styling but keep these main points in your mind:
Give whatever color, background color, font-family, margin and font size you want to give to the body and the heading.
We have given background images of drums, cymbals, etc. to every button to make the page more attractive. All the images are in “images” directory. Additionally, we have given some common styling to all the buttons.
We have also given styling as to how each button will look when pressed in the class animation. We would append this class using JavaScript whenever a button is pressed.
To append these classes we have to add the classes in HTML tags also and link the stylesheet. So the modified HTML and new CSS code would be:
HTML
<!DOCTYPE html><html> <head> <title>The Drum Kit</title> <link rel="stylesheet" href="index.css"></head> <body> <h1>The Drum Kit</h1> <div class="all"> <button class="w button">w</button> <button class="a button">a</button> <button class="s button">s</button> <button class="d button">d</button> <button class="j button">j</button> <button class="k button">k</button> <button class="l button">l</button> </div></body> </html>
CSS
body { text-align: center; background-color: #a06060;} h1 { font-size: 5rem; color: #DBEDF3; font-family: cursive; text-shadow: 3px 0 #DA0463;} .w { background-image: url("images/w.png");} .a { background-image: url("images/a.png");} .s { background-image: url("images/s.png");} .d { background-image: url("images/d.png");} .j { background-image: url("images/j.png");} .k { background-image: url("images/k.png");} .l { background-image: url("images/l.png");} .all { margin: 10% auto;} .animation { box-shadow: 0 3px 4px 0 #DBEDF3; opacity: 0.5;} .button { outline: none; border: 10px solid #404B69; font-size: 5rem; font-family: 'Arvo', cursive; line-height: 2; font-weight: 900; color: #DA0463; text-shadow: 3px 0 #DBEDF3; border-radius: 15px; display: inline-block; width: 150px; height: 150px; text-align: center; margin: 10px; background-color: white;}
Adding Functionality with JavaScript:
Important: Add script tag to the HTML document linking it with the JavaScript file (before closing the body tag).HTMLHTML<script src="drumKit.js"></script>
HTML
<script src="drumKit.js"></script>
Add event listeners to all the buttons as follows:JavaScriptJavaScriptvar numberOfButtons = document.querySelectorAll(".button").length; for (var j = 0; j < numberOfButtons; j++) { document.querySelectorAll(".button")[j] .addEventListener("click", function() { var buttonStyle = this.innerHTML; sound(buttonStyle); animation(buttonStyle); });}
JavaScript
var numberOfButtons = document.querySelectorAll(".button").length; for (var j = 0; j < numberOfButtons; j++) { document.querySelectorAll(".button")[j] .addEventListener("click", function() { var buttonStyle = this.innerHTML; sound(buttonStyle); animation(buttonStyle); });}
Add keypress function which will describe what will happen when a particular key is produced. Here we will produce the sound effect and animation effect. Code for the same is:JavaScriptJavaScriptdocument.addEventListener("keypress", function(event) { sound(event.key); animation(event.key);});
JavaScript
document.addEventListener("keypress", function(event) { sound(event.key); animation(event.key);});
Now we will code sound() function. It will tell which sound should be played when we press or/and click a specific key. Here we have already stored some basic sound effects of drums, cymbals and other percussion instruments, and we will play those sounds (using new Audio) when their respective key is clicked or pressed. All the sounds are in “music” directory. Code for the same should be:JavaScriptJavaScriptfunction sound(key) { switch (key) { case "w": var sound1 = new Audio("music/w.mp3"); sound1.play(); break; case "a": var sound2 = new Audio("music/a.mp3"); sound2.play(); break; case "s": var sound3 = new Audio('music/s.mp3'); sound3.play(); break; case "d": var sound4 = new Audio('music/d.mp3'); sound4.play(); break; case "j": var sound5 = new Audio('music/j.mp3'); sound5.play(); break; case "k": var sound6 = new Audio('music/k.mp3'); sound6.play(); break; case "l": var sound7 = new Audio('music/l.mp3'); sound7.play(); break; default: console.log(key); }}Now we will code animation() function. This will animate the button differently when it is being clicked. To do this, we will add pressed (which we have already defined in CSS file) class to the respective button when it is being clicked. Code for the same would be:JavaScriptJavaScriptfunction animation(currentKey) { var activeButton = document.querySelector("." + currentKey); activeButton.classList.add("animation"); setTimeout(function() { activeButton.classList.remove("animation"); }, 100);}Complete HTML and JavaScript File will look like that:index.htmldrumKit.jsindex.html<!DOCTYPE html><html> <head> <title>The Drum Kit</title> <link rel="stylesheet" href="index.css"> </head> <body> <h1>The Drum Kit</h1> <div class="all"> <button class="w button">w</button> <button class="a button">a</button> <button class="s button">s</button> <button class="d button">d</button> <button class="j button">j</button> <button class="k button">k</button> <button class="l button">l</button> </div> <script src="drumKit.js"></script> </body> </html>drumKit.jsvar numberOfButtons = document.querySelectorAll(".button").length; for (var j = 0; j < numberOfButtons; j++) { document.querySelectorAll(".button")[j] .addEventListener("click", function() { var buttonStyle = this.innerHTML; sound(buttonStyle); animation(buttonStyle); });} document.addEventListener("keypress", function(event) { sound(event.key); animation(event.key);}); function sound(key) { switch (key) { case "w": var sound1 = new Audio("music/w.mp3"); sound1.play(); break; case "a": var sound2 = new Audio("music/a.mp3"); sound2.play(); break; case "s": var sound3 = new Audio('music/s.mp3'); sound3.play(); break; case "d": var sound4 = new Audio('music/d.mp3'); sound4.play(); break; case "j": var sound5 = new Audio('music/j.mp3'); sound5.play(); break; case "k": var sound6 = new Audio('music/k.mp3'); sound6.play(); break; case "l": var sound7 = new Audio('music/l.mp3'); sound7.play(); break; default: console.log(key); }} function animation(currentKey) { var activeButton = document.querySelector("." + currentKey); activeButton.classList.add("animation"); setTimeout(function() { activeButton.classList.remove("animation"); }, 100);}Final Output:As can be seen when “l” button is pressed, it’s animation changesYou can look up for the whole code with sound and images on my GitHubMy Personal Notes
arrow_drop_upSave
JavaScript
function sound(key) { switch (key) { case "w": var sound1 = new Audio("music/w.mp3"); sound1.play(); break; case "a": var sound2 = new Audio("music/a.mp3"); sound2.play(); break; case "s": var sound3 = new Audio('music/s.mp3'); sound3.play(); break; case "d": var sound4 = new Audio('music/d.mp3'); sound4.play(); break; case "j": var sound5 = new Audio('music/j.mp3'); sound5.play(); break; case "k": var sound6 = new Audio('music/k.mp3'); sound6.play(); break; case "l": var sound7 = new Audio('music/l.mp3'); sound7.play(); break; default: console.log(key); }}
Now we will code animation() function. This will animate the button differently when it is being clicked. To do this, we will add pressed (which we have already defined in CSS file) class to the respective button when it is being clicked. Code for the same would be:JavaScriptJavaScriptfunction animation(currentKey) { var activeButton = document.querySelector("." + currentKey); activeButton.classList.add("animation"); setTimeout(function() { activeButton.classList.remove("animation"); }, 100);}Complete HTML and JavaScript File will look like that:index.htmldrumKit.jsindex.html<!DOCTYPE html><html> <head> <title>The Drum Kit</title> <link rel="stylesheet" href="index.css"> </head> <body> <h1>The Drum Kit</h1> <div class="all"> <button class="w button">w</button> <button class="a button">a</button> <button class="s button">s</button> <button class="d button">d</button> <button class="j button">j</button> <button class="k button">k</button> <button class="l button">l</button> </div> <script src="drumKit.js"></script> </body> </html>drumKit.jsvar numberOfButtons = document.querySelectorAll(".button").length; for (var j = 0; j < numberOfButtons; j++) { document.querySelectorAll(".button")[j] .addEventListener("click", function() { var buttonStyle = this.innerHTML; sound(buttonStyle); animation(buttonStyle); });} document.addEventListener("keypress", function(event) { sound(event.key); animation(event.key);}); function sound(key) { switch (key) { case "w": var sound1 = new Audio("music/w.mp3"); sound1.play(); break; case "a": var sound2 = new Audio("music/a.mp3"); sound2.play(); break; case "s": var sound3 = new Audio('music/s.mp3'); sound3.play(); break; case "d": var sound4 = new Audio('music/d.mp3'); sound4.play(); break; case "j": var sound5 = new Audio('music/j.mp3'); sound5.play(); break; case "k": var sound6 = new Audio('music/k.mp3'); sound6.play(); break; case "l": var sound7 = new Audio('music/l.mp3'); sound7.play(); break; default: console.log(key); }} function animation(currentKey) { var activeButton = document.querySelector("." + currentKey); activeButton.classList.add("animation"); setTimeout(function() { activeButton.classList.remove("animation"); }, 100);}Final Output:As can be seen when “l” button is pressed, it’s animation changesYou can look up for the whole code with sound and images on my GitHubMy Personal Notes
arrow_drop_upSave
JavaScript
function animation(currentKey) { var activeButton = document.querySelector("." + currentKey); activeButton.classList.add("animation"); setTimeout(function() { activeButton.classList.remove("animation"); }, 100);}
Complete HTML and JavaScript File will look like that:
index.html
drumKit.js
<!DOCTYPE html><html> <head> <title>The Drum Kit</title> <link rel="stylesheet" href="index.css"> </head> <body> <h1>The Drum Kit</h1> <div class="all"> <button class="w button">w</button> <button class="a button">a</button> <button class="s button">s</button> <button class="d button">d</button> <button class="j button">j</button> <button class="k button">k</button> <button class="l button">l</button> </div> <script src="drumKit.js"></script> </body> </html>
var numberOfButtons = document.querySelectorAll(".button").length; for (var j = 0; j < numberOfButtons; j++) { document.querySelectorAll(".button")[j] .addEventListener("click", function() { var buttonStyle = this.innerHTML; sound(buttonStyle); animation(buttonStyle); });} document.addEventListener("keypress", function(event) { sound(event.key); animation(event.key);}); function sound(key) { switch (key) { case "w": var sound1 = new Audio("music/w.mp3"); sound1.play(); break; case "a": var sound2 = new Audio("music/a.mp3"); sound2.play(); break; case "s": var sound3 = new Audio('music/s.mp3'); sound3.play(); break; case "d": var sound4 = new Audio('music/d.mp3'); sound4.play(); break; case "j": var sound5 = new Audio('music/j.mp3'); sound5.play(); break; case "k": var sound6 = new Audio('music/k.mp3'); sound6.play(); break; case "l": var sound7 = new Audio('music/l.mp3'); sound7.play(); break; default: console.log(key); }} function animation(currentKey) { var activeButton = document.querySelector("." + currentKey); activeButton.classList.add("animation"); setTimeout(function() { activeButton.classList.remove("animation"); }, 100);}
Final Output:
As can be seen when “l” button is pressed, it’s animation changes
You can look up for the whole code with sound and images on my GitHub
Technical Scripter 2020
CSS
HTML
JavaScript
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Primer CSS Flexbox Flex Direction
HTML Course | First Web Page | Printing Hello World
Design a web page using HTML and CSS
Search Bar using HTML, CSS and JavaScript
How to wrap the text around an image using HTML and CSS ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTML | <img> align Attribute
Form validation using HTML and JavaScript
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 25765,
"s": 24985,
"text": "We all must have seen a drum kit in some concert or elsewhere, it is a collection of drums, cymbals and other percussion instruments. But have you ever imagined making that drum kit on your own virtually with the help of some scripting language? Well, so here we are with the goal for this article to build a drum kit app that runs in the browser. The main concepts presented in the article are DOM, key events and CSS animations. So by the end of this article, you would have not only understood how to add event listeners to buttons and keystrokes so that you’ll know when the user is tapping on the keyboard or clicking on a particular button on your Website and you can respond to it, but you also end up with an awesome Website that you can impress all of your friends with."
},
{
"code": null,
"e": 25789,
"s": 25765,
"text": "Preview of the Website:"
},
{
"code": null,
"e": 26103,
"s": 25789,
"text": "So the way this website would work that we’ve got a number of keys on the webpage that represents different drums in a typical drum set and when you click on any of those buttons then you’ll get the corresponding sound of the drum. And in addition you can also use the keys on the keyboard to have a sound effect."
},
{
"code": null,
"e": 26504,
"s": 26103,
"text": "Designing the HTML Layout: For the website, we only have seven buttons to display on the page, clicking upon which sound would be played. First we would add the DOCTYPE HTML format, then give a suitable title to the web page, in our case it is The Drum Kit . Inside the body tag, we would give a heading, say, The Drum Kit using h1 tag and display those seven buttons. The code for the same would be:"
},
{
"code": null,
"e": 26509,
"s": 26504,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>The Drum Kit</title></head> <body> <h1>The Drum Kit</h1> <div class=\"all\"> <button>w</button> <button>a</button> <button>s</button> <button>d</button> <button>j</button> <button>k</button> <button>l</button> </div></body> </html>",
"e": 26841,
"s": 26509,
"text": null
},
{
"code": null,
"e": 26878,
"s": 26841,
"text": "Output would be something like that:"
},
{
"code": null,
"e": 27133,
"s": 26878,
"text": "Adding CSS Styling: CSS is used to style the different portions and make it more visually appealing. But, this is a personal opinion as to which style does the developer like the most. Feel free to use any styling but keep these main points in your mind:"
},
{
"code": null,
"e": 27252,
"s": 27133,
"text": "Give whatever color, background color, font-family, margin and font size you want to give to the body and the heading."
},
{
"code": null,
"e": 27468,
"s": 27252,
"text": "We have given background images of drums, cymbals, etc. to every button to make the page more attractive. All the images are in “images” directory. Additionally, we have given some common styling to all the buttons."
},
{
"code": null,
"e": 27638,
"s": 27468,
"text": "We have also given styling as to how each button will look when pressed in the class animation. We would append this class using JavaScript whenever a button is pressed."
},
{
"code": null,
"e": 27780,
"s": 27638,
"text": "To append these classes we have to add the classes in HTML tags also and link the stylesheet. So the modified HTML and new CSS code would be:"
},
{
"code": null,
"e": 27785,
"s": 27780,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>The Drum Kit</title> <link rel=\"stylesheet\" href=\"index.css\"></head> <body> <h1>The Drum Kit</h1> <div class=\"all\"> <button class=\"w button\">w</button> <button class=\"a button\">a</button> <button class=\"s button\">s</button> <button class=\"d button\">d</button> <button class=\"j button\">j</button> <button class=\"k button\">k</button> <button class=\"l button\">l</button> </div></body> </html>",
"e": 28280,
"s": 27785,
"text": null
},
{
"code": null,
"e": 28284,
"s": 28280,
"text": "CSS"
},
{
"code": "body { text-align: center; background-color: #a06060;} h1 { font-size: 5rem; color: #DBEDF3; font-family: cursive; text-shadow: 3px 0 #DA0463;} .w { background-image: url(\"images/w.png\");} .a { background-image: url(\"images/a.png\");} .s { background-image: url(\"images/s.png\");} .d { background-image: url(\"images/d.png\");} .j { background-image: url(\"images/j.png\");} .k { background-image: url(\"images/k.png\");} .l { background-image: url(\"images/l.png\");} .all { margin: 10% auto;} .animation { box-shadow: 0 3px 4px 0 #DBEDF3; opacity: 0.5;} .button { outline: none; border: 10px solid #404B69; font-size: 5rem; font-family: 'Arvo', cursive; line-height: 2; font-weight: 900; color: #DA0463; text-shadow: 3px 0 #DBEDF3; border-radius: 15px; display: inline-block; width: 150px; height: 150px; text-align: center; margin: 10px; background-color: white;}",
"e": 29245,
"s": 28284,
"text": null
},
{
"code": null,
"e": 29283,
"s": 29245,
"text": "Adding Functionality with JavaScript:"
},
{
"code": null,
"e": 29440,
"s": 29283,
"text": "Important: Add script tag to the HTML document linking it with the JavaScript file (before closing the body tag).HTMLHTML<script src=\"drumKit.js\"></script> "
},
{
"code": null,
"e": 29445,
"s": 29440,
"text": "HTML"
},
{
"code": "<script src=\"drumKit.js\"></script> ",
"e": 29481,
"s": 29445,
"text": null
},
{
"code": null,
"e": 29848,
"s": 29481,
"text": "Add event listeners to all the buttons as follows:JavaScriptJavaScriptvar numberOfButtons = document.querySelectorAll(\".button\").length; for (var j = 0; j < numberOfButtons; j++) { document.querySelectorAll(\".button\")[j] .addEventListener(\"click\", function() { var buttonStyle = this.innerHTML; sound(buttonStyle); animation(buttonStyle); });}"
},
{
"code": null,
"e": 29859,
"s": 29848,
"text": "JavaScript"
},
{
"code": "var numberOfButtons = document.querySelectorAll(\".button\").length; for (var j = 0; j < numberOfButtons; j++) { document.querySelectorAll(\".button\")[j] .addEventListener(\"click\", function() { var buttonStyle = this.innerHTML; sound(buttonStyle); animation(buttonStyle); });}",
"e": 30156,
"s": 29859,
"text": null
},
{
"code": null,
"e": 30452,
"s": 30156,
"text": "Add keypress function which will describe what will happen when a particular key is produced. Here we will produce the sound effect and animation effect. Code for the same is:JavaScriptJavaScriptdocument.addEventListener(\"keypress\", function(event) { sound(event.key); animation(event.key);});"
},
{
"code": null,
"e": 30463,
"s": 30452,
"text": "JavaScript"
},
{
"code": "document.addEventListener(\"keypress\", function(event) { sound(event.key); animation(event.key);});",
"e": 30564,
"s": 30463,
"text": null
},
{
"code": null,
"e": 34293,
"s": 30564,
"text": "Now we will code sound() function. It will tell which sound should be played when we press or/and click a specific key. Here we have already stored some basic sound effects of drums, cymbals and other percussion instruments, and we will play those sounds (using new Audio) when their respective key is clicked or pressed. All the sounds are in “music” directory. Code for the same should be:JavaScriptJavaScriptfunction sound(key) { switch (key) { case \"w\": var sound1 = new Audio(\"music/w.mp3\"); sound1.play(); break; case \"a\": var sound2 = new Audio(\"music/a.mp3\"); sound2.play(); break; case \"s\": var sound3 = new Audio('music/s.mp3'); sound3.play(); break; case \"d\": var sound4 = new Audio('music/d.mp3'); sound4.play(); break; case \"j\": var sound5 = new Audio('music/j.mp3'); sound5.play(); break; case \"k\": var sound6 = new Audio('music/k.mp3'); sound6.play(); break; case \"l\": var sound7 = new Audio('music/l.mp3'); sound7.play(); break; default: console.log(key); }}Now we will code animation() function. This will animate the button differently when it is being clicked. To do this, we will add pressed (which we have already defined in CSS file) class to the respective button when it is being clicked. Code for the same would be:JavaScriptJavaScriptfunction animation(currentKey) { var activeButton = document.querySelector(\".\" + currentKey); activeButton.classList.add(\"animation\"); setTimeout(function() { activeButton.classList.remove(\"animation\"); }, 100);}Complete HTML and JavaScript File will look like that:index.htmldrumKit.jsindex.html<!DOCTYPE html><html> <head> <title>The Drum Kit</title> <link rel=\"stylesheet\" href=\"index.css\"> </head> <body> <h1>The Drum Kit</h1> <div class=\"all\"> <button class=\"w button\">w</button> <button class=\"a button\">a</button> <button class=\"s button\">s</button> <button class=\"d button\">d</button> <button class=\"j button\">j</button> <button class=\"k button\">k</button> <button class=\"l button\">l</button> </div> <script src=\"drumKit.js\"></script> </body> </html>drumKit.jsvar numberOfButtons = document.querySelectorAll(\".button\").length; for (var j = 0; j < numberOfButtons; j++) { document.querySelectorAll(\".button\")[j] .addEventListener(\"click\", function() { var buttonStyle = this.innerHTML; sound(buttonStyle); animation(buttonStyle); });} document.addEventListener(\"keypress\", function(event) { sound(event.key); animation(event.key);}); function sound(key) { switch (key) { case \"w\": var sound1 = new Audio(\"music/w.mp3\"); sound1.play(); break; case \"a\": var sound2 = new Audio(\"music/a.mp3\"); sound2.play(); break; case \"s\": var sound3 = new Audio('music/s.mp3'); sound3.play(); break; case \"d\": var sound4 = new Audio('music/d.mp3'); sound4.play(); break; case \"j\": var sound5 = new Audio('music/j.mp3'); sound5.play(); break; case \"k\": var sound6 = new Audio('music/k.mp3'); sound6.play(); break; case \"l\": var sound7 = new Audio('music/l.mp3'); sound7.play(); break; default: console.log(key); }} function animation(currentKey) { var activeButton = document.querySelector(\".\" + currentKey); activeButton.classList.add(\"animation\"); setTimeout(function() { activeButton.classList.remove(\"animation\"); }, 100);}Final Output:As can be seen when “l” button is pressed, it’s animation changesYou can look up for the whole code with sound and images on my GitHubMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 34304,
"s": 34293,
"text": "JavaScript"
},
{
"code": "function sound(key) { switch (key) { case \"w\": var sound1 = new Audio(\"music/w.mp3\"); sound1.play(); break; case \"a\": var sound2 = new Audio(\"music/a.mp3\"); sound2.play(); break; case \"s\": var sound3 = new Audio('music/s.mp3'); sound3.play(); break; case \"d\": var sound4 = new Audio('music/d.mp3'); sound4.play(); break; case \"j\": var sound5 = new Audio('music/j.mp3'); sound5.play(); break; case \"k\": var sound6 = new Audio('music/k.mp3'); sound6.play(); break; case \"l\": var sound7 = new Audio('music/l.mp3'); sound7.play(); break; default: console.log(key); }}",
"e": 35013,
"s": 34304,
"text": null
},
{
"code": null,
"e": 37622,
"s": 35013,
"text": "Now we will code animation() function. This will animate the button differently when it is being clicked. To do this, we will add pressed (which we have already defined in CSS file) class to the respective button when it is being clicked. Code for the same would be:JavaScriptJavaScriptfunction animation(currentKey) { var activeButton = document.querySelector(\".\" + currentKey); activeButton.classList.add(\"animation\"); setTimeout(function() { activeButton.classList.remove(\"animation\"); }, 100);}Complete HTML and JavaScript File will look like that:index.htmldrumKit.jsindex.html<!DOCTYPE html><html> <head> <title>The Drum Kit</title> <link rel=\"stylesheet\" href=\"index.css\"> </head> <body> <h1>The Drum Kit</h1> <div class=\"all\"> <button class=\"w button\">w</button> <button class=\"a button\">a</button> <button class=\"s button\">s</button> <button class=\"d button\">d</button> <button class=\"j button\">j</button> <button class=\"k button\">k</button> <button class=\"l button\">l</button> </div> <script src=\"drumKit.js\"></script> </body> </html>drumKit.jsvar numberOfButtons = document.querySelectorAll(\".button\").length; for (var j = 0; j < numberOfButtons; j++) { document.querySelectorAll(\".button\")[j] .addEventListener(\"click\", function() { var buttonStyle = this.innerHTML; sound(buttonStyle); animation(buttonStyle); });} document.addEventListener(\"keypress\", function(event) { sound(event.key); animation(event.key);}); function sound(key) { switch (key) { case \"w\": var sound1 = new Audio(\"music/w.mp3\"); sound1.play(); break; case \"a\": var sound2 = new Audio(\"music/a.mp3\"); sound2.play(); break; case \"s\": var sound3 = new Audio('music/s.mp3'); sound3.play(); break; case \"d\": var sound4 = new Audio('music/d.mp3'); sound4.play(); break; case \"j\": var sound5 = new Audio('music/j.mp3'); sound5.play(); break; case \"k\": var sound6 = new Audio('music/k.mp3'); sound6.play(); break; case \"l\": var sound7 = new Audio('music/l.mp3'); sound7.play(); break; default: console.log(key); }} function animation(currentKey) { var activeButton = document.querySelector(\".\" + currentKey); activeButton.classList.add(\"animation\"); setTimeout(function() { activeButton.classList.remove(\"animation\"); }, 100);}Final Output:As can be seen when “l” button is pressed, it’s animation changesYou can look up for the whole code with sound and images on my GitHubMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 37633,
"s": 37622,
"text": "JavaScript"
},
{
"code": "function animation(currentKey) { var activeButton = document.querySelector(\".\" + currentKey); activeButton.classList.add(\"animation\"); setTimeout(function() { activeButton.classList.remove(\"animation\"); }, 100);}",
"e": 37857,
"s": 37633,
"text": null
},
{
"code": null,
"e": 37912,
"s": 37857,
"text": "Complete HTML and JavaScript File will look like that:"
},
{
"code": null,
"e": 37923,
"s": 37912,
"text": "index.html"
},
{
"code": null,
"e": 37934,
"s": 37923,
"text": "drumKit.js"
},
{
"code": "<!DOCTYPE html><html> <head> <title>The Drum Kit</title> <link rel=\"stylesheet\" href=\"index.css\"> </head> <body> <h1>The Drum Kit</h1> <div class=\"all\"> <button class=\"w button\">w</button> <button class=\"a button\">a</button> <button class=\"s button\">s</button> <button class=\"d button\">d</button> <button class=\"j button\">j</button> <button class=\"k button\">k</button> <button class=\"l button\">l</button> </div> <script src=\"drumKit.js\"></script> </body> </html>",
"e": 38429,
"s": 37934,
"text": null
},
{
"code": "var numberOfButtons = document.querySelectorAll(\".button\").length; for (var j = 0; j < numberOfButtons; j++) { document.querySelectorAll(\".button\")[j] .addEventListener(\"click\", function() { var buttonStyle = this.innerHTML; sound(buttonStyle); animation(buttonStyle); });} document.addEventListener(\"keypress\", function(event) { sound(event.key); animation(event.key);}); function sound(key) { switch (key) { case \"w\": var sound1 = new Audio(\"music/w.mp3\"); sound1.play(); break; case \"a\": var sound2 = new Audio(\"music/a.mp3\"); sound2.play(); break; case \"s\": var sound3 = new Audio('music/s.mp3'); sound3.play(); break; case \"d\": var sound4 = new Audio('music/d.mp3'); sound4.play(); break; case \"j\": var sound5 = new Audio('music/j.mp3'); sound5.play(); break; case \"k\": var sound6 = new Audio('music/k.mp3'); sound6.play(); break; case \"l\": var sound7 = new Audio('music/l.mp3'); sound7.play(); break; default: console.log(key); }} function animation(currentKey) { var activeButton = document.querySelector(\".\" + currentKey); activeButton.classList.add(\"animation\"); setTimeout(function() { activeButton.classList.remove(\"animation\"); }, 100);}",
"e": 39759,
"s": 38429,
"text": null
},
{
"code": null,
"e": 39773,
"s": 39759,
"text": "Final Output:"
},
{
"code": null,
"e": 39839,
"s": 39773,
"text": "As can be seen when “l” button is pressed, it’s animation changes"
},
{
"code": null,
"e": 39909,
"s": 39839,
"text": "You can look up for the whole code with sound and images on my GitHub"
},
{
"code": null,
"e": 39933,
"s": 39909,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 39937,
"s": 39933,
"text": "CSS"
},
{
"code": null,
"e": 39942,
"s": 39937,
"text": "HTML"
},
{
"code": null,
"e": 39953,
"s": 39942,
"text": "JavaScript"
},
{
"code": null,
"e": 39972,
"s": 39953,
"text": "Technical Scripter"
},
{
"code": null,
"e": 39989,
"s": 39972,
"text": "Web Technologies"
},
{
"code": null,
"e": 39994,
"s": 39989,
"text": "HTML"
},
{
"code": null,
"e": 40092,
"s": 39994,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40101,
"s": 40092,
"text": "Comments"
},
{
"code": null,
"e": 40114,
"s": 40101,
"text": "Old Comments"
},
{
"code": null,
"e": 40148,
"s": 40114,
"text": "Primer CSS Flexbox Flex Direction"
},
{
"code": null,
"e": 40200,
"s": 40148,
"text": "HTML Course | First Web Page | Printing Hello World"
},
{
"code": null,
"e": 40237,
"s": 40200,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 40279,
"s": 40237,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 40337,
"s": 40279,
"text": "How to wrap the text around an image using HTML and CSS ?"
},
{
"code": null,
"e": 40398,
"s": 40337,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 40427,
"s": 40398,
"text": "HTML | <img> align Attribute"
},
{
"code": null,
"e": 40469,
"s": 40427,
"text": "Form validation using HTML and JavaScript"
}
] |
How to Make CardView Checkable In Android? - GeeksforGeeks
|
28 Jan, 2021
In Android, We can make a CardView checkable, which can be really a useful feature. If we want the user to select some items and want to display the items that the user has chosen then this one is the most important feature for us. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the Build.Gradle(App Level) File
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation ‘com.google.android.material:material:1.1.0’
Add the kotlin android extensions inside the plugins { } tag.
plugins {
——–
——–
id ‘kotlin-android-extensions’
}
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><!--Constraint Layout as the parent layout--><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#CFCDCD" tools:context=".MainActivity"> <!--Linear Layout as the child layout--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="15dp" tools:layout_editor_absoluteX="-16dp" tools:layout_editor_absoluteY="-287dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Long Press to Check" android:textColor="#4CAF50" android:textSize="25sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="1"> <!--CardView for Taj Mahal --> <com.google.android.material.card.MaterialCardView android:id="@+id/cardTajMahal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_weight=".5" android:checkable="true" android:clickable="true" android:focusable="true" android:padding="4dp" app:cardBackgroundColor="@android:color/white" app:cardCornerRadius="7dp" app:cardElevation="3dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="5dp" android:text="Taj Mahal" android:textAppearance="@style/TextAppearance.AppCompat.Headline" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="5dp" android:layout_marginTop="15dp" android:text="It is Ivory White Marbel Statue on South Bank of Yamuna River" android:textAppearance="@style/TextAppearance.AppCompat.Subhead" /> </LinearLayout> </com.google.android.material.card.MaterialCardView> <!--CardView for Statue of Unity --> <com.google.android.material.card.MaterialCardView android:id="@+id/cardStatueOfUnity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginTop="20dp" android:layout_weight=".5" android:checkable="true" android:clickable="true" android:focusable="true" android:padding="4dp" app:cardBackgroundColor="@android:color/white" app:cardCornerRadius="7dp" app:cardElevation="3dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="5dp" android:text="Statue Of Unity" android:textAppearance="@style/TextAppearance.AppCompat.Headline" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="5dp" android:layout_marginTop="15dp" android:text="It is a statue of Indian Independence Activist Sardar Vallabh Bhai Patel" android:textAppearance="@style/TextAppearance.AppCompat.Subhead" /> </LinearLayout> </com.google.android.material.card.MaterialCardView> </LinearLayout> <!--Card View for Lotus Temple--> <com.google.android.material.card.MaterialCardView android:id="@+id/cardLotusTemple" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="25dp" android:layout_marginBottom="5dp" android:checkable="true" android:clickable="true" android:focusable="true" android:padding="4dp" app:cardBackgroundColor="@android:color/white" app:cardCornerRadius="7dp" app:cardElevation="3dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/txvLotusTemple" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="5dp" android:text="Lotus Temple" android:textAppearance="@style/TextAppearance.AppCompat.Headline" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="5dp" android:layout_marginTop="15dp" android:layout_marginBottom="15dp" android:text="Notable for its flowerlike shape, located in Delhi, India, is a Baha'i House of worship that was dedicated in December 1986." android:textAppearance="@style/TextAppearance.AppCompat.Subhead" /> </LinearLayout> </com.google.android.material.card.MaterialCardView> <Button android:id="@+id/btnWhatsSelected" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="10dp" android:backgroundTint="#B13C3C" android:text="Show what's selected" android:textAllCaps="false" android:textSize="20sp" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport com.google.android.material.snackbar.Snackbarimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // implementing the long click listener // for when pressed on card view cardTajMahal.setOnLongClickListener { // if the card view is checked,make // it unchecked and vice-versa cardTajMahal.isChecked = !cardTajMahal.isChecked true } // implementing the long click listener // for when pressed on card view cardStatueOfUnity.setOnLongClickListener { cardStatueOfUnity.isChecked = !cardStatueOfUnity.isChecked true } // implementing the long click listener // for when pressed on card view cardLotusTemple.setOnLongClickListener { cardLotusTemple.isChecked = !cardLotusTemple.isChecked true } btnWhatsSelected.setOnClickListener { // getting the info about which // card view has been selected var msg = "" if (cardTajMahal.isChecked) { msg += "'Taj Mahal' " } if (cardStatueOfUnity.isChecked) { msg += "'Statue Of Unity' " } if (cardTajMahal.isChecked) { msg += "'Lotus Temple' " } // snack bar is just like a toast msg Snackbar.make(it, " $msg Selected", Snackbar.LENGTH_LONG).show() } }}
android
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
How to Read Data from SQLite Database in Android?
How to Delete Data in SQLite Database in Android?
MVP (Model View Presenter) Architecture Pattern in Android with Example
How to Change the Background Color After Clicking the Button in Android?
Android | How to Create/Start a New Project in Android Studio?
Android Menus
Android UI Layouts
Kotlin Array
Kotlin Setters and Getters
Notifications in Android with Example
|
[
{
"code": null,
"e": 24751,
"s": 24723,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 25150,
"s": 24751,
"text": "In Android, We can make a CardView checkable, which can be really a useful feature. If we want the user to select some items and want to display the items that the user has chosen then this one is the most important feature for us. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 25179,
"s": 25150,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 25343,
"s": 25179,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 25397,
"s": 25343,
"text": "Step 2: Working with the Build.Gradle(App Level) File"
},
{
"code": null,
"e": 25514,
"s": 25397,
"text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 25574,
"s": 25514,
"text": "implementation ‘com.google.android.material:material:1.1.0’"
},
{
"code": null,
"e": 25636,
"s": 25574,
"text": "Add the kotlin android extensions inside the plugins { } tag."
},
{
"code": null,
"e": 25646,
"s": 25636,
"text": "plugins {"
},
{
"code": null,
"e": 25653,
"s": 25646,
"text": " ——–"
},
{
"code": null,
"e": 25660,
"s": 25653,
"text": " ——–"
},
{
"code": null,
"e": 25694,
"s": 25660,
"text": " id ‘kotlin-android-extensions’"
},
{
"code": null,
"e": 25696,
"s": 25694,
"text": "}"
},
{
"code": null,
"e": 25744,
"s": 25696,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 25887,
"s": 25744,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 25891,
"s": 25887,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--Constraint Layout as the parent layout--><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#CFCDCD\" tools:context=\".MainActivity\"> <!--Linear Layout as the child layout--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:padding=\"15dp\" tools:layout_editor_absoluteX=\"-16dp\" tools:layout_editor_absoluteY=\"-287dp\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:text=\"Long Press to Check\" android:textColor=\"#4CAF50\" android:textSize=\"25sp\" android:textStyle=\"bold\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:weightSum=\"1\"> <!--CardView for Taj Mahal --> <com.google.android.material.card.MaterialCardView android:id=\"@+id/cardTajMahal\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:layout_weight=\".5\" android:checkable=\"true\" android:clickable=\"true\" android:focusable=\"true\" android:padding=\"4dp\" app:cardBackgroundColor=\"@android:color/white\" app:cardCornerRadius=\"7dp\" app:cardElevation=\"3dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"5dp\" android:text=\"Taj Mahal\" android:textAppearance=\"@style/TextAppearance.AppCompat.Headline\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"5dp\" android:layout_marginTop=\"15dp\" android:text=\"It is Ivory White Marbel Statue on South Bank of Yamuna River\" android:textAppearance=\"@style/TextAppearance.AppCompat.Subhead\" /> </LinearLayout> </com.google.android.material.card.MaterialCardView> <!--CardView for Statue of Unity --> <com.google.android.material.card.MaterialCardView android:id=\"@+id/cardStatueOfUnity\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginTop=\"20dp\" android:layout_weight=\".5\" android:checkable=\"true\" android:clickable=\"true\" android:focusable=\"true\" android:padding=\"4dp\" app:cardBackgroundColor=\"@android:color/white\" app:cardCornerRadius=\"7dp\" app:cardElevation=\"3dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"5dp\" android:text=\"Statue Of Unity\" android:textAppearance=\"@style/TextAppearance.AppCompat.Headline\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"5dp\" android:layout_marginTop=\"15dp\" android:text=\"It is a statue of Indian Independence Activist Sardar Vallabh Bhai Patel\" android:textAppearance=\"@style/TextAppearance.AppCompat.Subhead\" /> </LinearLayout> </com.google.android.material.card.MaterialCardView> </LinearLayout> <!--Card View for Lotus Temple--> <com.google.android.material.card.MaterialCardView android:id=\"@+id/cardLotusTemple\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"25dp\" android:layout_marginBottom=\"5dp\" android:checkable=\"true\" android:clickable=\"true\" android:focusable=\"true\" android:padding=\"4dp\" app:cardBackgroundColor=\"@android:color/white\" app:cardCornerRadius=\"7dp\" app:cardElevation=\"3dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/txvLotusTemple\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"5dp\" android:text=\"Lotus Temple\" android:textAppearance=\"@style/TextAppearance.AppCompat.Headline\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"5dp\" android:layout_marginTop=\"15dp\" android:layout_marginBottom=\"15dp\" android:text=\"Notable for its flowerlike shape, located in Delhi, India, is a Baha'i House of worship that was dedicated in December 1986.\" android:textAppearance=\"@style/TextAppearance.AppCompat.Subhead\" /> </LinearLayout> </com.google.android.material.card.MaterialCardView> <Button android:id=\"@+id/btnWhatsSelected\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_margin=\"10dp\" android:backgroundTint=\"#B13C3C\" android:text=\"Show what's selected\" android:textAllCaps=\"false\" android:textSize=\"20sp\" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 33062,
"s": 25891,
"text": null
},
{
"code": null,
"e": 33108,
"s": 33062,
"text": "Step 4: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 33294,
"s": 33108,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 33301,
"s": 33294,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport com.google.android.material.snackbar.Snackbarimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // implementing the long click listener // for when pressed on card view cardTajMahal.setOnLongClickListener { // if the card view is checked,make // it unchecked and vice-versa cardTajMahal.isChecked = !cardTajMahal.isChecked true } // implementing the long click listener // for when pressed on card view cardStatueOfUnity.setOnLongClickListener { cardStatueOfUnity.isChecked = !cardStatueOfUnity.isChecked true } // implementing the long click listener // for when pressed on card view cardLotusTemple.setOnLongClickListener { cardLotusTemple.isChecked = !cardLotusTemple.isChecked true } btnWhatsSelected.setOnClickListener { // getting the info about which // card view has been selected var msg = \"\" if (cardTajMahal.isChecked) { msg += \"'Taj Mahal' \" } if (cardStatueOfUnity.isChecked) { msg += \"'Statue Of Unity' \" } if (cardTajMahal.isChecked) { msg += \"'Lotus Temple' \" } // snack bar is just like a toast msg Snackbar.make(it, \" $msg Selected\", Snackbar.LENGTH_LONG).show() } }}",
"e": 35023,
"s": 33301,
"text": null
},
{
"code": null,
"e": 35031,
"s": 35023,
"text": "android"
},
{
"code": null,
"e": 35055,
"s": 35031,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 35063,
"s": 35055,
"text": "Android"
},
{
"code": null,
"e": 35070,
"s": 35063,
"text": "Kotlin"
},
{
"code": null,
"e": 35089,
"s": 35070,
"text": "Technical Scripter"
},
{
"code": null,
"e": 35097,
"s": 35089,
"text": "Android"
},
{
"code": null,
"e": 35195,
"s": 35097,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35204,
"s": 35195,
"text": "Comments"
},
{
"code": null,
"e": 35217,
"s": 35204,
"text": "Old Comments"
},
{
"code": null,
"e": 35267,
"s": 35217,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 35317,
"s": 35267,
"text": "How to Delete Data in SQLite Database in Android?"
},
{
"code": null,
"e": 35389,
"s": 35317,
"text": "MVP (Model View Presenter) Architecture Pattern in Android with Example"
},
{
"code": null,
"e": 35462,
"s": 35389,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 35525,
"s": 35462,
"text": "Android | How to Create/Start a New Project in Android Studio?"
},
{
"code": null,
"e": 35539,
"s": 35525,
"text": "Android Menus"
},
{
"code": null,
"e": 35558,
"s": 35539,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 35571,
"s": 35558,
"text": "Kotlin Array"
},
{
"code": null,
"e": 35598,
"s": 35571,
"text": "Kotlin Setters and Getters"
}
] |
Multiply a given Integer with 3.5 - GeeksforGeeks
|
13 Oct, 2021
Given an integer x, write a function that multiplies x with 3.5 and returns the integer result. You are not allowed to use %, /, *.
Examples :
Input: 2
Output: 7
Input: 5
Output: 17 (Ignore the digits after decimal point)
Solution: 1. We can get x*3.5 by adding 2*x, x and x/2. To calculate 2*x, left shift x by 1 and to calculate x/2, right shift x by 1. Below is the implementation of the above approach:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to multiply// a number with 3.5#include <iostream>using namespace std; int multiplyWith3Point5(int x){ return (x<<1) + x + (x>>1);} /* Driver program to test above functions*/int main(){ int x = 4; cout << " "<< multiplyWith3Point5(x); getchar(); return 0;} // This code is contributed by shivanisinghss2110.
// C++ program to multiply// a number with 3.5#include <stdio.h> int multiplyWith3Point5(int x){ return (x<<1) + x + (x>>1);} /* Driver program to test above functions*/int main(){ int x = 4; printf("%d", multiplyWith3Point5(x)); getchar(); return 0;}
// Java Program to multiply// a number with 3.5 class GFG { static int multiplyWith3Point5(int x) { return (x<<1) + x + (x>>1); } /* Driver program to test above functions*/ public static void main(String[] args) { int x = 2; System.out.println(multiplyWith3Point5(x)); }} // This code is contributed by prerna saini.
# Python 3 program to multiply# a number with 3.5 def multiplyWith3Point5(x): return (x<<1) + x + (x>>1) # Driver program to# test above functionsx = 4print(multiplyWith3Point5(x)) # This code is contributed by# Smitha Dinesh Semwal
// C# Program to multiply// a number with 3.5using System; class GFG{ static int multiplyWith3Point5(int x) { return (x<<1) + x + (x>>1); } /* Driver program to test above functions*/ public static void Main() { int x = 2; Console.Write(multiplyWith3Point5(x)); } } // This code is contributed by Sam007
<?php// PHP program to multiply// a number with 3.5 function multiplyWith3Point5( $x){ return ($x << 1) + $x + ($x >> 1);} // Driver Code$x = 4;echo multiplyWith3Point5($x); // This code is contributed by vt_m.?>
<script>// javascript Program to multiply// a number with 3.5 function multiplyWith3Point5(x){ return (x<<1) + x + (x>>1);} /* Driver program to test above functions*/var x = 4;document.write(multiplyWith3Point5(x)); // This code is contributed by Amit Katiyar</script>
14
2. Another way of doing this could be (8*x – x)/2 (See below code). Thanks to Ajaym for suggesting this.
C++
C
Java
Python3
C#
Javascript
// C++ program approach #include <iostream>using namespace std; int multiplyWith3Point5(int x){ return ((x<<3) - x)>>1;} // This code is contributed by shivanisinghss2110
#include <stdio.h>int multiplyWith3Point5(int x){ return ((x<<3) - x)>>1;}
// Java program for above approachimport java.io.*; class GFG{ // Function static int multiplyWith3Point5(int x) { return ((x<<3) - x)>>1; }} // This code is contributed by shivanisinghss2110
# Python program for above approach# Functiondef multiplyWith3Point5(x): return ((x<<3) - x)>>1 # This code is contributed by shivanisinghss2110
// C# program for above approachusing System; class GFG{ // Function to multiple number// with 3.5static int multiplyWith3Point5(int x) { return ((x<<3) - x)>>1; }} // This code is contributed by shivanisinghss2110.
// JavaScript program for above approach// Functionfunction multiplyWith3Point5(x) { return ((x<<3) - x)>>1; } // This code is contributed by shivanisinghss2110
Another Approach:
Another way of doing this could be by doing a binary multiplication by 7 then divide by 2 using only <<, ^, &, and >>.
But here we have to mention that only positive numbers can be passed to this method.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <iostream>using namespace std; // Function to multiple number// with 3.5int multiplyWith3Point5(int x){ int r = 0; // The 3.5 is 7/2, so multiply // by 7 (x * 7) then // divide the result by 2 // (result/2) x * 7 -> 7 is // 0111 so by doing multiply // by 7 it means we do 2 // shifting for the number // but since we doing // multiply we need to take // care of carry one. int x1Shift = x << 1; int x2Shifts = x << 2; r = (x ^ x1Shift) ^ x2Shifts; int c = (x & x1Shift) | (x & x2Shifts) | (x1Shift & x2Shifts); while (c > 0) { c <<= 1; int t = r; r ^= c; c &= t; } // Then divide by 2 // r / 2 r = r >> 1; return r; } // Driver Codeint main() { cout<<(multiplyWith3Point5(5)); return 0;} // This code is contributed by rohitsingh07052.
// Java program for above approachimport java.io.*; class GFG{ // Function to multiple number // with 3.5 static int multiplyWith3Point5(int x) { int r = 0; // The 3.5 is 7/2, so multiply // by 7 (x * 7) then // divide the result by 2 // (result/2) x * 7 -> 7 is // 0111 so by doing multiply // by 7 it means we do 2 // shifting for the number // but since we doing // multiply we need to take // care of carry one. int x1Shift = x << 1; int x2Shifts = x << 2; r = (x ^ x1Shift) ^ x2Shifts; int c = (x & x1Shift) | (x & x2Shifts) | (x1Shift & x2Shifts); while (c > 0) { c <<= 1; int t = r; r ^= c; c &= t; } // Then divide by 2 // r / 2 r = r >> 1; return r; } // Driver Code public static void main(String[] args) { System.out.println(multiplyWith3Point5(5)); }}
# Python3 program for the above approach # Function to multiple number# with 3.5def multiplyWith3Point5(x): r = 0 # The 3.5 is 7/2, so multiply # by 7 (x * 7) then # divide the result by 2 # (result/2) x * 7 -> 7 is # 0111 so by doing multiply # by 7 it means we do 2 # shifting for the number # but since we doing # multiply we need to take # care of carry one. x1Shift = x << 1 x2Shifts = x << 2 r = (x ^ x1Shift) ^ x2Shifts c = (x & x1Shift) | (x & x2Shifts) | (x1Shift & x2Shifts) while (c > 0): c <<= 1 t = r r ^= c c &= t # Then divide by 2 # r / 2 r = r >> 1 return r # Driver Codeif __name__ == '__main__': print(multiplyWith3Point5(5)) # This code is contributed by nirajgusain5
// C# program for above approachusing System; class GFG{ // Function to multiple number// with 3.5static int multiplyWith3Point5(int x){ int r = 0; // The 3.5 is 7/2, so multiply // by 7 (x * 7) then // divide the result by 2 // (result/2) x * 7 -> 7 is // 0111 so by doing multiply // by 7 it means we do 2 // shifting for the number // but since we doing // multiply we need to take // care of carry one. int x1Shift = x << 1; int x2Shifts = x << 2; r = (x ^ x1Shift) ^ x2Shifts; int c = (x & x1Shift) | (x & x2Shifts) | (x1Shift & x2Shifts); while (c > 0) { c <<= 1; int t = r; r ^= c; c &= t; } // Then divide by 2 // r / 2 r = r >> 1; return r;} // Driver Codepublic static void Main(string[] args){ Console.WriteLine(multiplyWith3Point5(5));}} // This code is contributed by ukasp
<script> // Javascript program for the above approach // Function to multiple number// with 3.5function multiplyWith3Polet5(x){ let r = 0; // The 3.5 is 7/2, so multiply // by 7 (x * 7) then // divide the result by 2 // (result/2) x * 7 -> 7 is // 0111 so by doing multiply // by 7 it means we do 2 // shifting for the number // but since we doing // multiply we need to take // care of carry one. let x1Shift = x << 1; let x2Shifts = x << 2; r = (x ^ x1Shift) ^ x2Shifts; let c = (x & x1Shift) | (x & x2Shifts) | (x1Shift & x2Shifts); while (c > 0) { c <<= 1; let t = r; r ^= c; c &= t; } // Then divide by 2 // r / 2 r = r >> 1; return r;} // Driver codedocument.write(multiplyWith3Polet5(5)); // This code is contributed by avijitmondal1998 </script>
17
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oG2_XmdQnVs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem
vt_m
ghanykamal
amit143katiyar
rohitsingh07052
ukasp
avijitmondal1998
nirajgusain5
rajeev0719singh
shivanisinghss2110
piyushsachan1
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find the element that appears once
Bits manipulation (Important tactics)
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
C++ bitset and its application
Write an Efficient C Program to Reverse Bits of a Number
Check whether K-th bit is set or not
Count total set bits in all numbers from 1 to n
Divide two integers without using multiplication, division and mod operator
1's and 2's complement of a Binary Number
|
[
{
"code": null,
"e": 24567,
"s": 24539,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 24700,
"s": 24567,
"text": "Given an integer x, write a function that multiplies x with 3.5 and returns the integer result. You are not allowed to use %, /, *. "
},
{
"code": null,
"e": 24791,
"s": 24700,
"text": "Examples :\nInput: 2\nOutput: 7\n\nInput: 5\nOutput: 17 (Ignore the digits after decimal point)"
},
{
"code": null,
"e": 24977,
"s": 24791,
"text": "Solution: 1. We can get x*3.5 by adding 2*x, x and x/2. To calculate 2*x, left shift x by 1 and to calculate x/2, right shift x by 1. Below is the implementation of the above approach:"
},
{
"code": null,
"e": 24981,
"s": 24977,
"text": "C++"
},
{
"code": null,
"e": 24983,
"s": 24981,
"text": "C"
},
{
"code": null,
"e": 24988,
"s": 24983,
"text": "Java"
},
{
"code": null,
"e": 24996,
"s": 24988,
"text": "Python3"
},
{
"code": null,
"e": 24999,
"s": 24996,
"text": "C#"
},
{
"code": null,
"e": 25003,
"s": 24999,
"text": "PHP"
},
{
"code": null,
"e": 25014,
"s": 25003,
"text": "Javascript"
},
{
"code": "// C++ program to multiply// a number with 3.5#include <iostream>using namespace std; int multiplyWith3Point5(int x){ return (x<<1) + x + (x>>1);} /* Driver program to test above functions*/int main(){ int x = 4; cout << \" \"<< multiplyWith3Point5(x); getchar(); return 0;} // This code is contributed by shivanisinghss2110.",
"e": 25354,
"s": 25014,
"text": null
},
{
"code": "// C++ program to multiply// a number with 3.5#include <stdio.h> int multiplyWith3Point5(int x){ return (x<<1) + x + (x>>1);} /* Driver program to test above functions*/int main(){ int x = 4; printf(\"%d\", multiplyWith3Point5(x)); getchar(); return 0;}",
"e": 25621,
"s": 25354,
"text": null
},
{
"code": "// Java Program to multiply// a number with 3.5 class GFG { static int multiplyWith3Point5(int x) { return (x<<1) + x + (x>>1); } /* Driver program to test above functions*/ public static void main(String[] args) { int x = 2; System.out.println(multiplyWith3Point5(x)); }} // This code is contributed by prerna saini.",
"e": 25995,
"s": 25621,
"text": null
},
{
"code": "# Python 3 program to multiply# a number with 3.5 def multiplyWith3Point5(x): return (x<<1) + x + (x>>1) # Driver program to# test above functionsx = 4print(multiplyWith3Point5(x)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 26234,
"s": 25995,
"text": null
},
{
"code": "// C# Program to multiply// a number with 3.5using System; class GFG{ static int multiplyWith3Point5(int x) { return (x<<1) + x + (x>>1); } /* Driver program to test above functions*/ public static void Main() { int x = 2; Console.Write(multiplyWith3Point5(x)); } } // This code is contributed by Sam007",
"e": 26598,
"s": 26234,
"text": null
},
{
"code": "<?php// PHP program to multiply// a number with 3.5 function multiplyWith3Point5( $x){ return ($x << 1) + $x + ($x >> 1);} // Driver Code$x = 4;echo multiplyWith3Point5($x); // This code is contributed by vt_m.?>",
"e": 26819,
"s": 26598,
"text": null
},
{
"code": "<script>// javascript Program to multiply// a number with 3.5 function multiplyWith3Point5(x){ return (x<<1) + x + (x>>1);} /* Driver program to test above functions*/var x = 4;document.write(multiplyWith3Point5(x)); // This code is contributed by Amit Katiyar</script>",
"e": 27093,
"s": 26819,
"text": null
},
{
"code": null,
"e": 27096,
"s": 27093,
"text": "14"
},
{
"code": null,
"e": 27201,
"s": 27096,
"text": "2. Another way of doing this could be (8*x – x)/2 (See below code). Thanks to Ajaym for suggesting this."
},
{
"code": null,
"e": 27205,
"s": 27201,
"text": "C++"
},
{
"code": null,
"e": 27207,
"s": 27205,
"text": "C"
},
{
"code": null,
"e": 27212,
"s": 27207,
"text": "Java"
},
{
"code": null,
"e": 27220,
"s": 27212,
"text": "Python3"
},
{
"code": null,
"e": 27223,
"s": 27220,
"text": "C#"
},
{
"code": null,
"e": 27234,
"s": 27223,
"text": "Javascript"
},
{
"code": "// C++ program approach #include <iostream>using namespace std; int multiplyWith3Point5(int x){ return ((x<<3) - x)>>1;} // This code is contributed by shivanisinghss2110",
"e": 27409,
"s": 27234,
"text": null
},
{
"code": "#include <stdio.h>int multiplyWith3Point5(int x){ return ((x<<3) - x)>>1;} ",
"e": 27488,
"s": 27409,
"text": null
},
{
"code": "// Java program for above approachimport java.io.*; class GFG{ // Function static int multiplyWith3Point5(int x) { return ((x<<3) - x)>>1; }} // This code is contributed by shivanisinghss2110",
"e": 27688,
"s": 27488,
"text": null
},
{
"code": "# Python program for above approach# Functiondef multiplyWith3Point5(x): return ((x<<3) - x)>>1 # This code is contributed by shivanisinghss2110",
"e": 27841,
"s": 27688,
"text": null
},
{
"code": "// C# program for above approachusing System; class GFG{ // Function to multiple number// with 3.5static int multiplyWith3Point5(int x) { return ((x<<3) - x)>>1; }} // This code is contributed by shivanisinghss2110.",
"e": 28061,
"s": 27841,
"text": null
},
{
"code": "// JavaScript program for above approach// Functionfunction multiplyWith3Point5(x) { return ((x<<3) - x)>>1; } // This code is contributed by shivanisinghss2110",
"e": 28227,
"s": 28061,
"text": null
},
{
"code": null,
"e": 28245,
"s": 28227,
"text": "Another Approach:"
},
{
"code": null,
"e": 28364,
"s": 28245,
"text": "Another way of doing this could be by doing a binary multiplication by 7 then divide by 2 using only <<, ^, &, and >>."
},
{
"code": null,
"e": 28449,
"s": 28364,
"text": "But here we have to mention that only positive numbers can be passed to this method."
},
{
"code": null,
"e": 28500,
"s": 28449,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28504,
"s": 28500,
"text": "C++"
},
{
"code": null,
"e": 28509,
"s": 28504,
"text": "Java"
},
{
"code": null,
"e": 28517,
"s": 28509,
"text": "Python3"
},
{
"code": null,
"e": 28520,
"s": 28517,
"text": "C#"
},
{
"code": null,
"e": 28531,
"s": 28520,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <iostream>using namespace std; // Function to multiple number// with 3.5int multiplyWith3Point5(int x){ int r = 0; // The 3.5 is 7/2, so multiply // by 7 (x * 7) then // divide the result by 2 // (result/2) x * 7 -> 7 is // 0111 so by doing multiply // by 7 it means we do 2 // shifting for the number // but since we doing // multiply we need to take // care of carry one. int x1Shift = x << 1; int x2Shifts = x << 2; r = (x ^ x1Shift) ^ x2Shifts; int c = (x & x1Shift) | (x & x2Shifts) | (x1Shift & x2Shifts); while (c > 0) { c <<= 1; int t = r; r ^= c; c &= t; } // Then divide by 2 // r / 2 r = r >> 1; return r; } // Driver Codeint main() { cout<<(multiplyWith3Point5(5)); return 0;} // This code is contributed by rohitsingh07052.",
"e": 29530,
"s": 28531,
"text": null
},
{
"code": "// Java program for above approachimport java.io.*; class GFG{ // Function to multiple number // with 3.5 static int multiplyWith3Point5(int x) { int r = 0; // The 3.5 is 7/2, so multiply // by 7 (x * 7) then // divide the result by 2 // (result/2) x * 7 -> 7 is // 0111 so by doing multiply // by 7 it means we do 2 // shifting for the number // but since we doing // multiply we need to take // care of carry one. int x1Shift = x << 1; int x2Shifts = x << 2; r = (x ^ x1Shift) ^ x2Shifts; int c = (x & x1Shift) | (x & x2Shifts) | (x1Shift & x2Shifts); while (c > 0) { c <<= 1; int t = r; r ^= c; c &= t; } // Then divide by 2 // r / 2 r = r >> 1; return r; } // Driver Code public static void main(String[] args) { System.out.println(multiplyWith3Point5(5)); }}",
"e": 30544,
"s": 29530,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to multiple number# with 3.5def multiplyWith3Point5(x): r = 0 # The 3.5 is 7/2, so multiply # by 7 (x * 7) then # divide the result by 2 # (result/2) x * 7 -> 7 is # 0111 so by doing multiply # by 7 it means we do 2 # shifting for the number # but since we doing # multiply we need to take # care of carry one. x1Shift = x << 1 x2Shifts = x << 2 r = (x ^ x1Shift) ^ x2Shifts c = (x & x1Shift) | (x & x2Shifts) | (x1Shift & x2Shifts) while (c > 0): c <<= 1 t = r r ^= c c &= t # Then divide by 2 # r / 2 r = r >> 1 return r # Driver Codeif __name__ == '__main__': print(multiplyWith3Point5(5)) # This code is contributed by nirajgusain5",
"e": 31332,
"s": 30544,
"text": null
},
{
"code": "// C# program for above approachusing System; class GFG{ // Function to multiple number// with 3.5static int multiplyWith3Point5(int x){ int r = 0; // The 3.5 is 7/2, so multiply // by 7 (x * 7) then // divide the result by 2 // (result/2) x * 7 -> 7 is // 0111 so by doing multiply // by 7 it means we do 2 // shifting for the number // but since we doing // multiply we need to take // care of carry one. int x1Shift = x << 1; int x2Shifts = x << 2; r = (x ^ x1Shift) ^ x2Shifts; int c = (x & x1Shift) | (x & x2Shifts) | (x1Shift & x2Shifts); while (c > 0) { c <<= 1; int t = r; r ^= c; c &= t; } // Then divide by 2 // r / 2 r = r >> 1; return r;} // Driver Codepublic static void Main(string[] args){ Console.WriteLine(multiplyWith3Point5(5));}} // This code is contributed by ukasp",
"e": 32231,
"s": 31332,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to multiple number// with 3.5function multiplyWith3Polet5(x){ let r = 0; // The 3.5 is 7/2, so multiply // by 7 (x * 7) then // divide the result by 2 // (result/2) x * 7 -> 7 is // 0111 so by doing multiply // by 7 it means we do 2 // shifting for the number // but since we doing // multiply we need to take // care of carry one. let x1Shift = x << 1; let x2Shifts = x << 2; r = (x ^ x1Shift) ^ x2Shifts; let c = (x & x1Shift) | (x & x2Shifts) | (x1Shift & x2Shifts); while (c > 0) { c <<= 1; let t = r; r ^= c; c &= t; } // Then divide by 2 // r / 2 r = r >> 1; return r;} // Driver codedocument.write(multiplyWith3Polet5(5)); // This code is contributed by avijitmondal1998 </script>",
"e": 33101,
"s": 32231,
"text": null
},
{
"code": null,
"e": 33104,
"s": 33101,
"text": "17"
},
{
"code": null,
"e": 33396,
"s": 33104,
"text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=oG2_XmdQnVs\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 33512,
"s": 33396,
"text": "Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem"
},
{
"code": null,
"e": 33519,
"s": 33514,
"text": "vt_m"
},
{
"code": null,
"e": 33530,
"s": 33519,
"text": "ghanykamal"
},
{
"code": null,
"e": 33545,
"s": 33530,
"text": "amit143katiyar"
},
{
"code": null,
"e": 33561,
"s": 33545,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 33567,
"s": 33561,
"text": "ukasp"
},
{
"code": null,
"e": 33584,
"s": 33567,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 33597,
"s": 33584,
"text": "nirajgusain5"
},
{
"code": null,
"e": 33613,
"s": 33597,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 33632,
"s": 33613,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 33646,
"s": 33632,
"text": "piyushsachan1"
},
{
"code": null,
"e": 33656,
"s": 33646,
"text": "Bit Magic"
},
{
"code": null,
"e": 33666,
"s": 33656,
"text": "Bit Magic"
},
{
"code": null,
"e": 33764,
"s": 33666,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33773,
"s": 33764,
"text": "Comments"
},
{
"code": null,
"e": 33786,
"s": 33773,
"text": "Old Comments"
},
{
"code": null,
"e": 33821,
"s": 33786,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 33859,
"s": 33821,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 33910,
"s": 33859,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 33926,
"s": 33910,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 33957,
"s": 33926,
"text": "C++ bitset and its application"
},
{
"code": null,
"e": 34014,
"s": 33957,
"text": "Write an Efficient C Program to Reverse Bits of a Number"
},
{
"code": null,
"e": 34051,
"s": 34014,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 34099,
"s": 34051,
"text": "Count total set bits in all numbers from 1 to n"
},
{
"code": null,
"e": 34175,
"s": 34099,
"text": "Divide two integers without using multiplication, division and mod operator"
}
] |
A Simple HDR Implementation on OpenCV Python | by Felipe Cunha | Towards Data Science
|
HDR images encompass the information of multiple pictures with different exposures. In a scene which the source of light is uneven, a single shot may overexpose certain areas of the image and details will be lost due to elevated brightness. Conversely, this picture may also present underexposed areas which will also lead to information loss.
To create an HDR image you will need:
Take pictures with different exposures. Minimum of 2, generally 3, you can use more than 3 images but it will take a lot of CPU resources.Align the images. Even if you use a tripod you will need to perform this step (we are talking about pixel level alignment). Not properly aligning your image will lead to artifacts and ‘ghosts’ in your HDR image.Merge the aligned images into one.Perform tone mapping on the merged image. In nature the minimum possible brightness is zero but the maximum is not limited to 255, in fact there is no limit to it, it can be infinity. For this reason we need to map the image obtained in the third step to a (0, 255) range. This can be achieved with tone mapping.
Take pictures with different exposures. Minimum of 2, generally 3, you can use more than 3 images but it will take a lot of CPU resources.
Align the images. Even if you use a tripod you will need to perform this step (we are talking about pixel level alignment). Not properly aligning your image will lead to artifacts and ‘ghosts’ in your HDR image.
Merge the aligned images into one.
Perform tone mapping on the merged image. In nature the minimum possible brightness is zero but the maximum is not limited to 255, in fact there is no limit to it, it can be infinity. For this reason we need to map the image obtained in the third step to a (0, 255) range. This can be achieved with tone mapping.
import cv2 as cvimport numpy as np# Loading exposure images into a listimg_fn = [r"C:\Users\felipe.cunha\Documents\venv\HDRTest\100.jpg", r"C:\Users\felipe.cunha\Documents\venv\HDRTest\250.jpg", r"C:\Users\felipe.cunha\Documents\venv\HDRTest\500.jpg"]img_list = [cv.imread(fn) for fn in img_fn]exposure_times = np.array([100, 250, 500], dtype=np.float32)# Merge exposures to HDR imagemerge_debevec = cv.createMergeDebevec()hdr_debevec = merge_debevec.process(img_list, times=exposure_times.copy())merge_robertson = cv.createMergeRobertson()hdr_robertson = merge_robertson.process(img_list, times=exposure_times.copy())# Tonemap HDR imagetonemap1 = cv.createTonemap(gamma=2.2)res_debevec = tonemap1.process(hdr_debevec.copy())# Exposure fusion using Mertensmerge_mertens = cv.createMergeMertens()res_mertens = merge_mertens.process(img_list)# Convert datatype to 8-bit and saveres_debevec_8bit = np.clip(res_debevec*255, 0, 255).astype('uint8')res_mertens_8bit = np.clip(res_mertens*255, 0, 255).astype('uint8')cv.imwrite(r"C:\Users\felipe.cunha\Documents\venv\HDRTest\ldr_debevec.jpg", res_debevec_8bit)cv.imwrite(r"C:\Users\felipe.cunha\Documents\venv\HDRTest\fusion_mertens.jpg", res_mertens_8bit)
We’ve covered the very basics of HDR. This technique is specially helpful in situations that you need to located features in a large field of view that has under and overexposed areas.
I hope this can help you with your computer vision projects.
Let me know in the comments if you would like a more in depth article about this topic.
|
[
{
"code": null,
"e": 515,
"s": 171,
"text": "HDR images encompass the information of multiple pictures with different exposures. In a scene which the source of light is uneven, a single shot may overexpose certain areas of the image and details will be lost due to elevated brightness. Conversely, this picture may also present underexposed areas which will also lead to information loss."
},
{
"code": null,
"e": 553,
"s": 515,
"text": "To create an HDR image you will need:"
},
{
"code": null,
"e": 1249,
"s": 553,
"text": "Take pictures with different exposures. Minimum of 2, generally 3, you can use more than 3 images but it will take a lot of CPU resources.Align the images. Even if you use a tripod you will need to perform this step (we are talking about pixel level alignment). Not properly aligning your image will lead to artifacts and ‘ghosts’ in your HDR image.Merge the aligned images into one.Perform tone mapping on the merged image. In nature the minimum possible brightness is zero but the maximum is not limited to 255, in fact there is no limit to it, it can be infinity. For this reason we need to map the image obtained in the third step to a (0, 255) range. This can be achieved with tone mapping."
},
{
"code": null,
"e": 1388,
"s": 1249,
"text": "Take pictures with different exposures. Minimum of 2, generally 3, you can use more than 3 images but it will take a lot of CPU resources."
},
{
"code": null,
"e": 1600,
"s": 1388,
"text": "Align the images. Even if you use a tripod you will need to perform this step (we are talking about pixel level alignment). Not properly aligning your image will lead to artifacts and ‘ghosts’ in your HDR image."
},
{
"code": null,
"e": 1635,
"s": 1600,
"text": "Merge the aligned images into one."
},
{
"code": null,
"e": 1948,
"s": 1635,
"text": "Perform tone mapping on the merged image. In nature the minimum possible brightness is zero but the maximum is not limited to 255, in fact there is no limit to it, it can be infinity. For this reason we need to map the image obtained in the third step to a (0, 255) range. This can be achieved with tone mapping."
},
{
"code": null,
"e": 3148,
"s": 1948,
"text": "import cv2 as cvimport numpy as np# Loading exposure images into a listimg_fn = [r\"C:\\Users\\felipe.cunha\\Documents\\venv\\HDRTest\\100.jpg\", r\"C:\\Users\\felipe.cunha\\Documents\\venv\\HDRTest\\250.jpg\", r\"C:\\Users\\felipe.cunha\\Documents\\venv\\HDRTest\\500.jpg\"]img_list = [cv.imread(fn) for fn in img_fn]exposure_times = np.array([100, 250, 500], dtype=np.float32)# Merge exposures to HDR imagemerge_debevec = cv.createMergeDebevec()hdr_debevec = merge_debevec.process(img_list, times=exposure_times.copy())merge_robertson = cv.createMergeRobertson()hdr_robertson = merge_robertson.process(img_list, times=exposure_times.copy())# Tonemap HDR imagetonemap1 = cv.createTonemap(gamma=2.2)res_debevec = tonemap1.process(hdr_debevec.copy())# Exposure fusion using Mertensmerge_mertens = cv.createMergeMertens()res_mertens = merge_mertens.process(img_list)# Convert datatype to 8-bit and saveres_debevec_8bit = np.clip(res_debevec*255, 0, 255).astype('uint8')res_mertens_8bit = np.clip(res_mertens*255, 0, 255).astype('uint8')cv.imwrite(r\"C:\\Users\\felipe.cunha\\Documents\\venv\\HDRTest\\ldr_debevec.jpg\", res_debevec_8bit)cv.imwrite(r\"C:\\Users\\felipe.cunha\\Documents\\venv\\HDRTest\\fusion_mertens.jpg\", res_mertens_8bit)"
},
{
"code": null,
"e": 3333,
"s": 3148,
"text": "We’ve covered the very basics of HDR. This technique is specially helpful in situations that you need to located features in a large field of view that has under and overexposed areas."
},
{
"code": null,
"e": 3394,
"s": 3333,
"text": "I hope this can help you with your computer vision projects."
}
] |
RSpec - Helpers
|
Sometimes your RSpec examples need an easy way to share reusable code. The best way to accomplish this is with Helpers. Helpers are basically regular Ruby methods which you share across examples. To illustrate the benefit of using helpers, let’s consider this code −
class Dog
attr_reader :good_dog, :has_been_walked
def initialize(good_or_not)
@good_dog = good_or_not
@has_been_walked = false
end
def walk_dog
@has_been_walked = true
end
end
describe Dog do
it 'should be able to create and walk a good dog' do
dog = Dog.new(true)
dog.walk_dog
expect(dog.good_dog).to be true
expect(dog.has_been_walked).to be true
end
it 'should be able to create and walk a bad dog' do
dog = Dog.new(false)
dog.walk_dog
expect(dog.good_dog).to be false
expect(dog.has_been_walked).to be true
end
end
This code is clear, but it’s always a good idea to reduce repeated code whenever possible. We can take the above code and reduce some of this repetition with a helper method called create_and_walk_dog().
class Dog
attr_reader :good_dog, :has_been_walked
def initialize(good_or_not)
@good_dog = good_or_not
@has_been_walked = false
end
def walk_dog
@has_been_walked = true
end
end
describe Dog do
def create_and_walk_dog(good_or_bad)
dog = Dog.new(good_or_bad)
dog.walk_dog
return dog
end
it 'should be able to create and walk a good dog' do
dog = create_and_walk_dog(true)
expect(dog.good_dog).to be true
expect(dog.has_been_walked).to be true
end
it 'should be able to create and walk a bad dog' do
dog = create_and_walk_dog(false)
expect(dog.good_dog).to be false
expect(dog.has_been_walked).to be true
end
end
When you run the above code, you will see this output −
..
Finished in 0.002 seconds (files took 0.11401 seconds to load)
2 examples, 0 failures
As you can see, we were able to push the logic for creating and walking a dog object into a Helper which allows our examples to be shorter and cleaner.
9 Lectures
37 mins
Harshit Srivastava
27 Lectures
7 hours
Atul Tiwari
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2061,
"s": 1794,
"text": "Sometimes your RSpec examples need an easy way to share reusable code. The best way to accomplish this is with Helpers. Helpers are basically regular Ruby methods which you share across examples. To illustrate the benefit of using helpers, let’s consider this code −"
},
{
"code": null,
"e": 2717,
"s": 2061,
"text": "class Dog \n attr_reader :good_dog, :has_been_walked \n \n def initialize(good_or_not) \n @good_dog = good_or_not \n @has_been_walked = false \n end \n \n def walk_dog \n @has_been_walked = true \n end \nend \n\ndescribe Dog do \n it 'should be able to create and walk a good dog' do \n dog = Dog.new(true) \n dog.walk_dog \n \n expect(dog.good_dog).to be true\n expect(dog.has_been_walked).to be true \n end \n \n it 'should be able to create and walk a bad dog' do \n dog = Dog.new(false) \n dog.walk_dog \n\n expect(dog.good_dog).to be false\n expect(dog.has_been_walked).to be true \n \n end \nend"
},
{
"code": null,
"e": 2921,
"s": 2717,
"text": "This code is clear, but it’s always a good idea to reduce repeated code whenever possible. We can take the above code and reduce some of this repetition with a helper method called create_and_walk_dog()."
},
{
"code": null,
"e": 3682,
"s": 2921,
"text": "class Dog\n attr_reader :good_dog, :has_been_walked \n \n def initialize(good_or_not)\n @good_dog = good_or_not \n @has_been_walked = false \n end \n \n def walk_dog \n @has_been_walked = true \n end \nend \n\ndescribe Dog do \n def create_and_walk_dog(good_or_bad)\n dog = Dog.new(good_or_bad)\n dog.walk_dog\n return dog \n end \n \n it 'should be able to create and walk a good dog' do\n dog = create_and_walk_dog(true)\n \n expect(dog.good_dog).to be true\n expect(dog.has_been_walked).to be true \n end \n \n it 'should be able to create and walk a bad dog' do \n dog = create_and_walk_dog(false)\n \n expect(dog.good_dog).to be false\n expect(dog.has_been_walked).to be true \n end \nend"
},
{
"code": null,
"e": 3738,
"s": 3682,
"text": "When you run the above code, you will see this output −"
},
{
"code": null,
"e": 3830,
"s": 3738,
"text": ".. \nFinished in 0.002 seconds (files took 0.11401 seconds to load) \n2 examples, 0 failures\n"
},
{
"code": null,
"e": 3982,
"s": 3830,
"text": "As you can see, we were able to push the logic for creating and walking a dog object into a Helper which allows our examples to be shorter and cleaner."
},
{
"code": null,
"e": 4013,
"s": 3982,
"text": "\n 9 Lectures \n 37 mins\n"
},
{
"code": null,
"e": 4033,
"s": 4013,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4066,
"s": 4033,
"text": "\n 27 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4079,
"s": 4066,
"text": " Atul Tiwari"
},
{
"code": null,
"e": 4086,
"s": 4079,
"text": " Print"
},
{
"code": null,
"e": 4097,
"s": 4086,
"text": " Add Notes"
}
] |
C# | Collection Class - GeeksforGeeks
|
01 Feb, 2019
Collection<T> Class provides the base class for a generic collection. Here T is the type of elements in the collection. This class comes under the System.Collections.ObjectModel namespace.
Characteristics:
The Collection<T> class can be used immediately by creating an instance of one of its constructed types.
The Collection<T> class provides protected methods that can be used to customize its behavior when adding and removing items, clearing the collection, or setting the value of an existing item.
Most Collection<T> objects can be modified. However, a Collection object that is initialized with a read-only IList<T> object cannot be modified.
Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
Collection<T> accepts null as a valid value for reference types and allows duplicate elements.
Example:
// C# code to create a Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of ints Collection<int> myColl = new Collection<int>(); // Adding elements in Collection myColl myColl.Add(2); myColl.Add(3); myColl.Add(4); myColl.Add(5); // Displaying the elements in myColl foreach(int i in myColl) { Console.WriteLine(i); } }}
Output:
2
3
4
5
Example:
// C# Code to illustrate the // Properties of Collection classusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); // Adding elements in Collection myColl myColl.Add("A"); myColl.Add("B"); myColl.Add("C"); myColl.Add("D"); myColl.Add("E"); // ------- Count Property ---------- // To print the count of // elements in Collection Console.WriteLine("Count : " + myColl.Count); // -------- Item[Int32] Property -------- // Get the element at index 2 Console.WriteLine("Element at index 2 is : " + myColl[2]); // Get the element at index 3 Console.WriteLine("Element at index 3 is : " + myColl[3]); }}
Output:
Count : 5
Element at index 2 is : C
Element at index 3 is : D
Example:
// C# code to check if an// element is in the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); myColl.Add("A"); myColl.Add("B"); myColl.Add("C"); myColl.Add("D"); myColl.Add("E"); // Checking if an element is in the Collection // The function returns "True" if the // item is present in Collection // else returns "False" Console.WriteLine(myColl.Contains("A")); }}
Output:
True
Example 2:
// C# code to copy the entire Collection// to a compatible one-dimensional Array,// starting at the specified index of// the target arrayusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); myColl.Add("A"); myColl.Add("B"); myColl.Add("C"); myColl.Add("D"); myColl.Add("E"); // Creating a string array string[] myArr = new string[myColl.Count]; // Copying the entire Collection to a // compatible one-dimensional Array, // starting at the specified index // of the target array myColl.CopyTo(myArr, 0); // Displaying the elements in myArr foreach(string str in myArr) { Console.WriteLine(str); } }}
Output:
A
B
C
D
E
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1?view=netframework-4.7.2
CSharp-Collection-Class
CSharp-Collections.ObjectModel-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | IsNullOrEmpty() Method
Main Method in C#
C# | Dictionary.Add() Method
Lambda Expressions in C#
Different ways to sort an array in descending order in C#
C# | Arrays of Strings
C# | How to use strings in switch statement
C# | List Class
C# | How to check whether a List contains a specified element
How to find the length of an Array in C#
|
[
{
"code": null,
"e": 24889,
"s": 24861,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 25078,
"s": 24889,
"text": "Collection<T> Class provides the base class for a generic collection. Here T is the type of elements in the collection. This class comes under the System.Collections.ObjectModel namespace."
},
{
"code": null,
"e": 25095,
"s": 25078,
"text": "Characteristics:"
},
{
"code": null,
"e": 25200,
"s": 25095,
"text": "The Collection<T> class can be used immediately by creating an instance of one of its constructed types."
},
{
"code": null,
"e": 25393,
"s": 25200,
"text": "The Collection<T> class provides protected methods that can be used to customize its behavior when adding and removing items, clearing the collection, or setting the value of an existing item."
},
{
"code": null,
"e": 25539,
"s": 25393,
"text": "Most Collection<T> objects can be modified. However, a Collection object that is initialized with a read-only IList<T> object cannot be modified."
},
{
"code": null,
"e": 25650,
"s": 25539,
"text": "Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based."
},
{
"code": null,
"e": 25745,
"s": 25650,
"text": "Collection<T> accepts null as a valid value for reference types and allows duplicate elements."
},
{
"code": null,
"e": 25754,
"s": 25745,
"text": "Example:"
},
{
"code": "// C# code to create a Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of ints Collection<int> myColl = new Collection<int>(); // Adding elements in Collection myColl myColl.Add(2); myColl.Add(3); myColl.Add(4); myColl.Add(5); // Displaying the elements in myColl foreach(int i in myColl) { Console.WriteLine(i); } }}",
"e": 26305,
"s": 25754,
"text": null
},
{
"code": null,
"e": 26313,
"s": 26305,
"text": "Output:"
},
{
"code": null,
"e": 26322,
"s": 26313,
"text": "2\n3\n4\n5\n"
},
{
"code": null,
"e": 26331,
"s": 26322,
"text": "Example:"
},
{
"code": "// C# Code to illustrate the // Properties of Collection classusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); // Adding elements in Collection myColl myColl.Add(\"A\"); myColl.Add(\"B\"); myColl.Add(\"C\"); myColl.Add(\"D\"); myColl.Add(\"E\"); // ------- Count Property ---------- // To print the count of // elements in Collection Console.WriteLine(\"Count : \" + myColl.Count); // -------- Item[Int32] Property -------- // Get the element at index 2 Console.WriteLine(\"Element at index 2 is : \" + myColl[2]); // Get the element at index 3 Console.WriteLine(\"Element at index 3 is : \" + myColl[3]); }}",
"e": 27289,
"s": 26331,
"text": null
},
{
"code": null,
"e": 27297,
"s": 27289,
"text": "Output:"
},
{
"code": null,
"e": 27360,
"s": 27297,
"text": "Count : 5\nElement at index 2 is : C\nElement at index 3 is : D\n"
},
{
"code": null,
"e": 27369,
"s": 27360,
"text": "Example:"
},
{
"code": "// C# code to check if an// element is in the Collectionusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); myColl.Add(\"A\"); myColl.Add(\"B\"); myColl.Add(\"C\"); myColl.Add(\"D\"); myColl.Add(\"E\"); // Checking if an element is in the Collection // The function returns \"True\" if the // item is present in Collection // else returns \"False\" Console.WriteLine(myColl.Contains(\"A\")); }}",
"e": 28028,
"s": 27369,
"text": null
},
{
"code": null,
"e": 28036,
"s": 28028,
"text": "Output:"
},
{
"code": null,
"e": 28042,
"s": 28036,
"text": "True\n"
},
{
"code": null,
"e": 28053,
"s": 28042,
"text": "Example 2:"
},
{
"code": "// C# code to copy the entire Collection// to a compatible one-dimensional Array,// starting at the specified index of// the target arrayusing System;using System.Collections.Generic;using System.Collections.ObjectModel; class GFG { // Driver code public static void Main() { // Creating a collection of strings Collection<string> myColl = new Collection<string>(); myColl.Add(\"A\"); myColl.Add(\"B\"); myColl.Add(\"C\"); myColl.Add(\"D\"); myColl.Add(\"E\"); // Creating a string array string[] myArr = new string[myColl.Count]; // Copying the entire Collection to a // compatible one-dimensional Array, // starting at the specified index // of the target array myColl.CopyTo(myArr, 0); // Displaying the elements in myArr foreach(string str in myArr) { Console.WriteLine(str); } }}",
"e": 28988,
"s": 28053,
"text": null
},
{
"code": null,
"e": 28996,
"s": 28988,
"text": "Output:"
},
{
"code": null,
"e": 29007,
"s": 28996,
"text": "A\nB\nC\nD\nE\n"
},
{
"code": null,
"e": 29018,
"s": 29007,
"text": "Reference:"
},
{
"code": null,
"e": 29130,
"s": 29018,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1?view=netframework-4.7.2"
},
{
"code": null,
"e": 29154,
"s": 29130,
"text": "CSharp-Collection-Class"
},
{
"code": null,
"e": 29195,
"s": 29154,
"text": "CSharp-Collections.ObjectModel-Namespace"
},
{
"code": null,
"e": 29198,
"s": 29195,
"text": "C#"
},
{
"code": null,
"e": 29296,
"s": 29198,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29305,
"s": 29296,
"text": "Comments"
},
{
"code": null,
"e": 29318,
"s": 29305,
"text": "Old Comments"
},
{
"code": null,
"e": 29346,
"s": 29318,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 29364,
"s": 29346,
"text": "Main Method in C#"
},
{
"code": null,
"e": 29393,
"s": 29364,
"text": "C# | Dictionary.Add() Method"
},
{
"code": null,
"e": 29418,
"s": 29393,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 29476,
"s": 29418,
"text": "Different ways to sort an array in descending order in C#"
},
{
"code": null,
"e": 29499,
"s": 29476,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 29543,
"s": 29499,
"text": "C# | How to use strings in switch statement"
},
{
"code": null,
"e": 29559,
"s": 29543,
"text": "C# | List Class"
},
{
"code": null,
"e": 29621,
"s": 29559,
"text": "C# | How to check whether a List contains a specified element"
}
] |
PL/SQL - Functions
|
In this chapter, we will discuss the functions in PL/SQL. A function is same as a procedure except that it returns a value. Therefore, all the discussions of the previous chapter are true for functions too.
A standalone function is created using the CREATE FUNCTION statement. The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,
function-name specifies the name of the function.
function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
[OR REPLACE] option allows the modification of an existing function.
The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure.
The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure.
The function must contain a return statement.
The function must contain a return statement.
The RETURN clause specifies the data type you are going to return from the function.
The RETURN clause specifies the data type you are going to return from the function.
function-body contains the executable part.
function-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone function.
The AS keyword is used instead of the IS keyword for creating a standalone function.
The following example illustrates how to create and call a standalone function. This function returns the total number of CUSTOMERS in the customers table.
We will use the CUSTOMERS table, which we had created in the PL/SQL Variables chapter −
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;
RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Function created.
While creating a function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function.
A called function performs the defined task and when its return statement is executed or when the last end statement is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name and if the function returns a value, then you can store the returned value. Following program calls the function totalCustomers from an anonymous block −
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Total no. of Customers: 6
PL/SQL procedure successfully completed.
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL Function that computes and returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Maximum of (23,45): 45
PL/SQL procedure successfully completed.
We have seen that a program or subprogram may call another subprogram. When a subprogram calls itself, it is referred to as a recursive call and the process is known as recursion.
To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n is defined as −
n! = n*(n-1)!
= n*(n-1)*(n-2)!
...
= n*(n-1)*(n-2)*(n-3)... 1
The following program calculates the factorial of a given number by calling itself recursively −
DECLARE
num number;
factorial number;
FUNCTION fact(x number)
RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Factorial 6 is 720
PL/SQL procedure successfully completed.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2272,
"s": 2065,
"text": "In this chapter, we will discuss the functions in PL/SQL. A function is same as a procedure except that it returns a value. Therefore, all the discussions of the previous chapter are true for functions too."
},
{
"code": null,
"e": 2426,
"s": 2272,
"text": "A standalone function is created using the CREATE FUNCTION statement. The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −"
},
{
"code": null,
"e": 2609,
"s": 2426,
"text": "CREATE [OR REPLACE] FUNCTION function_name \n[(parameter_name [IN | OUT | IN OUT] type [, ...])] \nRETURN return_datatype \n{IS | AS} \nBEGIN \n < function_body > \nEND [function_name];\n"
},
{
"code": null,
"e": 2616,
"s": 2609,
"text": "Where,"
},
{
"code": null,
"e": 2666,
"s": 2616,
"text": "function-name specifies the name of the function."
},
{
"code": null,
"e": 2716,
"s": 2666,
"text": "function-name specifies the name of the function."
},
{
"code": null,
"e": 2785,
"s": 2716,
"text": "[OR REPLACE] option allows the modification of an existing function."
},
{
"code": null,
"e": 2854,
"s": 2785,
"text": "[OR REPLACE] option allows the modification of an existing function."
},
{
"code": null,
"e": 3083,
"s": 2854,
"text": "The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure."
},
{
"code": null,
"e": 3312,
"s": 3083,
"text": "The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure."
},
{
"code": null,
"e": 3358,
"s": 3312,
"text": "The function must contain a return statement."
},
{
"code": null,
"e": 3404,
"s": 3358,
"text": "The function must contain a return statement."
},
{
"code": null,
"e": 3489,
"s": 3404,
"text": "The RETURN clause specifies the data type you are going to return from the function."
},
{
"code": null,
"e": 3574,
"s": 3489,
"text": "The RETURN clause specifies the data type you are going to return from the function."
},
{
"code": null,
"e": 3618,
"s": 3574,
"text": "function-body contains the executable part."
},
{
"code": null,
"e": 3662,
"s": 3618,
"text": "function-body contains the executable part."
},
{
"code": null,
"e": 3747,
"s": 3662,
"text": "The AS keyword is used instead of the IS keyword for creating a standalone function."
},
{
"code": null,
"e": 3832,
"s": 3747,
"text": "The AS keyword is used instead of the IS keyword for creating a standalone function."
},
{
"code": null,
"e": 3988,
"s": 3832,
"text": "The following example illustrates how to create and call a standalone function. This function returns the total number of CUSTOMERS in the customers table."
},
{
"code": null,
"e": 4076,
"s": 3988,
"text": "We will use the CUSTOMERS table, which we had created in the PL/SQL Variables chapter −"
},
{
"code": null,
"e": 4586,
"s": 4076,
"text": "Select * from customers; \n \n+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 6 | Komal | 22 | MP | 4500.00 | \n+----+----------+-----+-----------+----------+ \n"
},
{
"code": null,
"e": 4763,
"s": 4586,
"text": "CREATE OR REPLACE FUNCTION totalCustomers \nRETURN number IS \n total number(2) := 0; \nBEGIN \n SELECT count(*) into total \n FROM customers; \n \n RETURN total; \nEND; \n/ "
},
{
"code": null,
"e": 4856,
"s": 4763,
"text": "When the above code is executed using the SQL prompt, it will produce the following result −"
},
{
"code": null,
"e": 4875,
"s": 4856,
"text": "Function created.\n"
},
{
"code": null,
"e": 5132,
"s": 4875,
"text": "While creating a function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function."
},
{
"code": null,
"e": 5318,
"s": 5132,
"text": "A called function performs the defined task and when its return statement is executed or when the last end statement is reached, it returns the program control back to the main program."
},
{
"code": null,
"e": 5569,
"s": 5318,
"text": "To call a function, you simply need to pass the required parameters along with the function name and if the function returns a value, then you can store the returned value. Following program calls the function totalCustomers from an anonymous block −"
},
{
"code": null,
"e": 5696,
"s": 5569,
"text": "DECLARE \n c number(2); \nBEGIN \n c := totalCustomers(); \n dbms_output.put_line('Total no. of Customers: ' || c); \nEND; \n/"
},
{
"code": null,
"e": 5782,
"s": 5696,
"text": "When the above code is executed at the SQL prompt, it produces the following result −"
},
{
"code": null,
"e": 5854,
"s": 5782,
"text": "Total no. of Customers: 6 \n\nPL/SQL procedure successfully completed. \n"
},
{
"code": null,
"e": 6001,
"s": 5854,
"text": "The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL Function that computes and returns the maximum of two values."
},
{
"code": null,
"e": 6347,
"s": 6001,
"text": "DECLARE \n a number; \n b number; \n c number; \nFUNCTION findMax(x IN number, y IN number) \nRETURN number \nIS \n z number; \nBEGIN \n IF x > y THEN \n z:= x; \n ELSE \n Z:= y; \n END IF; \n RETURN z; \nEND; \nBEGIN \n a:= 23; \n b:= 45; \n c := findMax(a, b); \n dbms_output.put_line(' Maximum of (23,45): ' || c); \nEND; \n/ "
},
{
"code": null,
"e": 6433,
"s": 6347,
"text": "When the above code is executed at the SQL prompt, it produces the following result −"
},
{
"code": null,
"e": 6503,
"s": 6433,
"text": "Maximum of (23,45): 45 \n\nPL/SQL procedure successfully completed. \n"
},
{
"code": null,
"e": 6683,
"s": 6503,
"text": "We have seen that a program or subprogram may call another subprogram. When a subprogram calls itself, it is referred to as a recursive call and the process is known as recursion."
},
{
"code": null,
"e": 6794,
"s": 6683,
"text": "To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n is defined as −"
},
{
"code": null,
"e": 6873,
"s": 6794,
"text": "n! = n*(n-1)! \n = n*(n-1)*(n-2)! \n ... \n = n*(n-1)*(n-2)*(n-3)... 1 \n"
},
{
"code": null,
"e": 6970,
"s": 6873,
"text": "The following program calculates the factorial of a given number by calling itself recursively −"
},
{
"code": null,
"e": 7312,
"s": 6970,
"text": "DECLARE \n num number; \n factorial number; \n \nFUNCTION fact(x number) \nRETURN number \nIS \n f number; \nBEGIN \n IF x=0 THEN \n f := 1; \n ELSE \n f := x * fact(x-1); \n END IF; \nRETURN f; \nEND; \n\nBEGIN \n num:= 6; \n factorial := fact(num); \n dbms_output.put_line(' Factorial '|| num || ' is ' || factorial); \nEND; \n/"
},
{
"code": null,
"e": 7398,
"s": 7312,
"text": "When the above code is executed at the SQL prompt, it produces the following result −"
},
{
"code": null,
"e": 7463,
"s": 7398,
"text": "Factorial 6 is 720 \n \nPL/SQL procedure successfully completed.\n"
},
{
"code": null,
"e": 7470,
"s": 7463,
"text": " Print"
},
{
"code": null,
"e": 7481,
"s": 7470,
"text": " Add Notes"
}
] |
Batch Script - NET STATISTICS
|
Display network statistics of the workstation or server.
Net statistics [SERVER/WORKSTATION]
Net statistics Server
Server Statistics for \\WIN-50GP30FGO75
Statistics since 1/3/2016 9:16:28 PM
Sessions accepted 0
Sessions timed-out 0
Sessions errored-out 0
Kilobytes sent 0
Kilobytes received 0
Mean response time (msec) 0
System errors 0
Permission violations 0
Password violations 0
Files accessed 0
Communication devices accessed 0
Print jobs spooled 0
Times buffers exhausted
Big buffers 0
Request buffers 0
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2226,
"s": 2169,
"text": "Display network statistics of the workstation or server."
},
{
"code": null,
"e": 2263,
"s": 2226,
"text": "Net statistics [SERVER/WORKSTATION]\n"
},
{
"code": null,
"e": 2285,
"s": 2263,
"text": "Net statistics Server"
},
{
"code": null,
"e": 2901,
"s": 2285,
"text": "Server Statistics for \\\\WIN-50GP30FGO75\n\n\nStatistics since 1/3/2016 9:16:28 PM\n\n\nSessions accepted 0\nSessions timed-out 0\nSessions errored-out 0\n\nKilobytes sent 0\nKilobytes received 0\n\nMean response time (msec) 0\n\nSystem errors 0\nPermission violations 0\nPassword violations 0\n\nFiles accessed 0\nCommunication devices accessed 0\nPrint jobs spooled 0\n\nTimes buffers exhausted\n\nBig buffers 0\nRequest buffers 0\n"
},
{
"code": null,
"e": 2908,
"s": 2901,
"text": " Print"
},
{
"code": null,
"e": 2919,
"s": 2908,
"text": " Add Notes"
}
] |
Bootstrap pre tag styling
|
If the code needs to be displayed as a standalone block element or if it has multiple lines, then you should use the <pre> tag.
You can try to run the following code to implement the pre tag for code −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<pre>
<h1>Heading One</h1>
<h2>Heading Two</h2>
</pre>
</body>
</html>
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "If the code needs to be displayed as a standalone block element or if it has multiple lines, then you should use the <pre> tag."
},
{
"code": null,
"e": 1264,
"s": 1190,
"text": "You can try to run the following code to implement the pre tag for code −"
},
{
"code": null,
"e": 1274,
"s": 1264,
"text": "Live Demo"
},
{
"code": null,
"e": 1663,
"s": 1274,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <pre>\n <h1>Heading One</h1>\n <h2>Heading Two</h2>\n </pre>\n </body>\n</html>"
}
] |
Program to replace all digits with characters using Python
|
Suppose we have an alphanumeric string s that contains lowercase English letters in its even positions and digits in its odd positions. Consider an operation shift(c, x), where c is any character and x is a number (digit), this will find the xth character after c. So, for example, shift('p', 5) = 'u' and shift('a', 0) = 'a'. Now for every odd index i, we want to replace the digit s[i] with shift(s[i-1], s[i]). We have to find s after replacing all digits.
So, if the input is like s = "a2b1d4f3h2", then the output will be "acbcdhfihj" because
shift('a', 2) = 'c'
shift('a', 2) = 'c'
shift('b', 1) = 'c'
shift('b', 1) = 'c'
shift('d', 4) = 'h'
shift('d', 4) = 'h'
shift('f', 3) = 'i'
shift('f', 3) = 'i'
shift('h', 2) = 'j'
shift('h', 2) = 'j'
To solve this, we will follow these steps −
res:= blank string
res:= blank string
for i in range 0 to size of s, doif s[i] is a digit, thenres := res concatenate character from (ASCII s[i] + ASCII of s[i-1])otherwise,res := res concatenate s[i]
for i in range 0 to size of s, do
if s[i] is a digit, thenres := res concatenate character from (ASCII s[i] + ASCII of s[i-1])
if s[i] is a digit, then
res := res concatenate character from (ASCII s[i] + ASCII of s[i-1])
res := res concatenate character from (ASCII s[i] + ASCII of s[i-1])
otherwise,res := res concatenate s[i]
otherwise,
res := res concatenate s[i]
res := res concatenate s[i]
return res
return res
Let us see the following implementation to get better understanding −
Live Demo
def solve(s):
res=""
for i in range(len(s)):
if s[i].isdigit():
res+= chr(int(s[i])+ord(s[i-1]))
else:
res+=s[i]
return res
s = "a2b1d4f3h2"
print(solve(s))
"a2b1d4f3h2"
acbcdhfihj
|
[
{
"code": null,
"e": 1522,
"s": 1062,
"text": "Suppose we have an alphanumeric string s that contains lowercase English letters in its even positions and digits in its odd positions. Consider an operation shift(c, x), where c is any character and x is a number (digit), this will find the xth character after c. So, for example, shift('p', 5) = 'u' and shift('a', 0) = 'a'. Now for every odd index i, we want to replace the digit s[i] with shift(s[i-1], s[i]). We have to find s after replacing all digits."
},
{
"code": null,
"e": 1610,
"s": 1522,
"text": "So, if the input is like s = \"a2b1d4f3h2\", then the output will be \"acbcdhfihj\" because"
},
{
"code": null,
"e": 1630,
"s": 1610,
"text": "shift('a', 2) = 'c'"
},
{
"code": null,
"e": 1650,
"s": 1630,
"text": "shift('a', 2) = 'c'"
},
{
"code": null,
"e": 1670,
"s": 1650,
"text": "shift('b', 1) = 'c'"
},
{
"code": null,
"e": 1690,
"s": 1670,
"text": "shift('b', 1) = 'c'"
},
{
"code": null,
"e": 1710,
"s": 1690,
"text": "shift('d', 4) = 'h'"
},
{
"code": null,
"e": 1730,
"s": 1710,
"text": "shift('d', 4) = 'h'"
},
{
"code": null,
"e": 1750,
"s": 1730,
"text": "shift('f', 3) = 'i'"
},
{
"code": null,
"e": 1770,
"s": 1750,
"text": "shift('f', 3) = 'i'"
},
{
"code": null,
"e": 1790,
"s": 1770,
"text": "shift('h', 2) = 'j'"
},
{
"code": null,
"e": 1810,
"s": 1790,
"text": "shift('h', 2) = 'j'"
},
{
"code": null,
"e": 1854,
"s": 1810,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1873,
"s": 1854,
"text": "res:= blank string"
},
{
"code": null,
"e": 1892,
"s": 1873,
"text": "res:= blank string"
},
{
"code": null,
"e": 2055,
"s": 1892,
"text": "for i in range 0 to size of s, doif s[i] is a digit, thenres := res concatenate character from (ASCII s[i] + ASCII of s[i-1])otherwise,res := res concatenate s[i]"
},
{
"code": null,
"e": 2089,
"s": 2055,
"text": "for i in range 0 to size of s, do"
},
{
"code": null,
"e": 2182,
"s": 2089,
"text": "if s[i] is a digit, thenres := res concatenate character from (ASCII s[i] + ASCII of s[i-1])"
},
{
"code": null,
"e": 2207,
"s": 2182,
"text": "if s[i] is a digit, then"
},
{
"code": null,
"e": 2276,
"s": 2207,
"text": "res := res concatenate character from (ASCII s[i] + ASCII of s[i-1])"
},
{
"code": null,
"e": 2345,
"s": 2276,
"text": "res := res concatenate character from (ASCII s[i] + ASCII of s[i-1])"
},
{
"code": null,
"e": 2383,
"s": 2345,
"text": "otherwise,res := res concatenate s[i]"
},
{
"code": null,
"e": 2394,
"s": 2383,
"text": "otherwise,"
},
{
"code": null,
"e": 2422,
"s": 2394,
"text": "res := res concatenate s[i]"
},
{
"code": null,
"e": 2450,
"s": 2422,
"text": "res := res concatenate s[i]"
},
{
"code": null,
"e": 2461,
"s": 2450,
"text": "return res"
},
{
"code": null,
"e": 2472,
"s": 2461,
"text": "return res"
},
{
"code": null,
"e": 2542,
"s": 2472,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2553,
"s": 2542,
"text": " Live Demo"
},
{
"code": null,
"e": 2749,
"s": 2553,
"text": "def solve(s):\n res=\"\"\n for i in range(len(s)):\n if s[i].isdigit():\n res+= chr(int(s[i])+ord(s[i-1]))\n else:\n res+=s[i]\n return res\ns = \"a2b1d4f3h2\"\nprint(solve(s))"
},
{
"code": null,
"e": 2762,
"s": 2749,
"text": "\"a2b1d4f3h2\""
},
{
"code": null,
"e": 2773,
"s": 2762,
"text": "acbcdhfihj"
}
] |
How to extract the p-value from t test in R?
|
To extract the p-value from t test in R, we can follow the below steps −
First of all, create a data frame with numerical column or a numerical vector.
Then, use t.test function to perform the test and put $p.value at the end to extract the p-value from the test output.
Create the data frame
Let's create a data frame as shown below −
Live Demo
x<-rnorm(20,5,1)
df<-data.frame(x)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x
1 5.854093
2 6.075394
3 5.114147
4 3.672250
5 6.519127
6 5.145577
7 3.005657
8 2.994189
9 6.031218
10 4.981937
11 5.359909
12 4.914696
13 4.767514
14 6.090447
15 5.644259
16 6.210392
17 4.097178
18 5.242026
19 4.999231
20 5.494340
Using t.test function to perform the t-test on column x of df and extract the p-value with $p.value −
Live Demo
x<-rnorm(20,5,1)
df<-data.frame(x)
t.test(df$x,mu=5.8,alternative="less")$p.value
[1] 0.003168284
Create the vector
Let’s create a vector as shown below −
Live Demo
y<-sample(1:1000,200)
y
[1] 761 40 629 167 687 200 873 481 218 708 315 649 119 16 603 177 733 852
[19] 925 940 693 620 146 416 13 790 79 464 801 543 91 754 505 235 549 770
[37] 630 991 762 703 805 713 968 316 883 52 717 747 121 756 773 308 283 372
[55] 425 918 391 997 276 912 253 874 281 76 759 658 197 516 917 126 26 615
[73] 240 10 84 676 766 553 286 307 877 778 560 994 736 75 295 697 864 256
[91] 70 50 739 686 66 902 836 125 606 194 819 462 900 891 213 68 808 834
[109] 501 945 325 140 107 531 311 755 169 361 663 577 590 589 211 889 684 257
[127] 580 180 318 872 839 413 936 503 246 190 333 178 46 434 894 365 669 937
[145] 884 752 840 656 698 757 984 772 933 139 317 626 591 502 189 53 410 751
[163] 351 72 645 944 170 465 628 639 243 844 493 855 709 913 710 993 858 504
[181] 596 585 350 618 942 934 980 490 782 699 722 284 740 715 562 156 210 767
[199] 621 19
Using t.test function to perform the t-test on vector x and extract the p-value with $p.value −
Live Demo
y<-sample(1:1000,200)
t.test(y,mu=500,alternative="greater")$p.value
[1] 0.04181906
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "To extract the p-value from t test in R, we can follow the below steps −"
},
{
"code": null,
"e": 1214,
"s": 1135,
"text": "First of all, create a data frame with numerical column or a numerical vector."
},
{
"code": null,
"e": 1333,
"s": 1214,
"text": "Then, use t.test function to perform the test and put $p.value at the end to extract the p-value from the test output."
},
{
"code": null,
"e": 1355,
"s": 1333,
"text": "Create the data frame"
},
{
"code": null,
"e": 1398,
"s": 1355,
"text": "Let's create a data frame as shown below −"
},
{
"code": null,
"e": 1409,
"s": 1398,
"text": " Live Demo"
},
{
"code": null,
"e": 1447,
"s": 1409,
"text": "x<-rnorm(20,5,1)\ndf<-data.frame(x)\ndf"
},
{
"code": null,
"e": 1566,
"s": 1447,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −"
},
{
"code": null,
"e": 1802,
"s": 1566,
"text": " x\n1 5.854093\n2 6.075394\n3 5.114147\n4 3.672250\n5 6.519127\n6 5.145577\n7 3.005657\n8 2.994189\n9 6.031218\n10 4.981937\n11 5.359909\n12 4.914696\n13 4.767514\n14 6.090447\n15 5.644259\n16 6.210392\n17 4.097178\n18 5.242026\n19 4.999231\n20 5.494340"
},
{
"code": null,
"e": 1904,
"s": 1802,
"text": "Using t.test function to perform the t-test on column x of df and extract the p-value with $p.value −"
},
{
"code": null,
"e": 1915,
"s": 1904,
"text": " Live Demo"
},
{
"code": null,
"e": 1997,
"s": 1915,
"text": "x<-rnorm(20,5,1)\ndf<-data.frame(x)\nt.test(df$x,mu=5.8,alternative=\"less\")$p.value"
},
{
"code": null,
"e": 2013,
"s": 1997,
"text": "[1] 0.003168284"
},
{
"code": null,
"e": 2031,
"s": 2013,
"text": "Create the vector"
},
{
"code": null,
"e": 2070,
"s": 2031,
"text": "Let’s create a vector as shown below −"
},
{
"code": null,
"e": 2081,
"s": 2070,
"text": " Live Demo"
},
{
"code": null,
"e": 2105,
"s": 2081,
"text": "y<-sample(1:1000,200)\ny"
},
{
"code": null,
"e": 2951,
"s": 2105,
"text": "[1] 761 40 629 167 687 200 873 481 218 708 315 649 119 16 603 177 733 852\n[19] 925 940 693 620 146 416 13 790 79 464 801 543 91 754 505 235 549 770\n[37] 630 991 762 703 805 713 968 316 883 52 717 747 121 756 773 308 283 372\n[55] 425 918 391 997 276 912 253 874 281 76 759 658 197 516 917 126 26 615\n[73] 240 10 84 676 766 553 286 307 877 778 560 994 736 75 295 697 864 256\n[91] 70 50 739 686 66 902 836 125 606 194 819 462 900 891 213 68 808 834\n[109] 501 945 325 140 107 531 311 755 169 361 663 577 590 589 211 889 684 257\n[127] 580 180 318 872 839 413 936 503 246 190 333 178 46 434 894 365 669 937\n[145] 884 752 840 656 698 757 984 772 933 139 317 626 591 502 189 53 410 751\n[163] 351 72 645 944 170 465 628 639 243 844 493 855 709 913 710 993 858 504\n[181] 596 585 350 618 942 934 980 490 782 699 722 284 740 715 562 156 210 767\n[199] 621 19"
},
{
"code": null,
"e": 3047,
"s": 2951,
"text": "Using t.test function to perform the t-test on vector x and extract the p-value with $p.value −"
},
{
"code": null,
"e": 3058,
"s": 3047,
"text": " Live Demo"
},
{
"code": null,
"e": 3127,
"s": 3058,
"text": "y<-sample(1:1000,200)\nt.test(y,mu=500,alternative=\"greater\")$p.value"
},
{
"code": null,
"e": 3142,
"s": 3127,
"text": "[1] 0.04181906"
}
] |
How to auto-increment the property of a JSONObject in Java?
|
A JSONObject is an unordered collection of name/value pairs and parses text from a String to produce a map-like object. However, we can auto-increment the property of a JSONObject using the increment() method of JSONObject class. If there is no such property, create one with a value of 1. If there is such a property and if it is an Integer, Long, Double or Float then add one to it.
public JSONObject increment(java.lang.String key) throws JSONException
import org.json.JSONException;
import org.json.JSONObject;
public class IncrementJSONObjectTest {
public static void main(String[] args) throws JSONException {
JSONObject jsonObj = new JSONObject();
jsonObj.put("year", 2019);
jsonObj.put("age", 25);
System.out.println(jsonObj.toString(3));
jsonObj.increment("year").increment("age");
System.out.println(jsonObj.toString(3));
jsonObj.increment("year").increment("age");
System.out.println(jsonObj.toString(3));
jsonObj.increment("year").increment("age");
System.out.println(jsonObj.toString(3));
}
}
{
"year": 2019,
"age": 25
}
{
"year": 2020,
"age": 26
}
{
"year": 2021,
"age": 27
}
{
"year": 2022,
"age": 28
}
|
[
{
"code": null,
"e": 1447,
"s": 1062,
"text": "A JSONObject is an unordered collection of name/value pairs and parses text from a String to produce a map-like object. However, we can auto-increment the property of a JSONObject using the increment() method of JSONObject class. If there is no such property, create one with a value of 1. If there is such a property and if it is an Integer, Long, Double or Float then add one to it."
},
{
"code": null,
"e": 1518,
"s": 1447,
"text": "public JSONObject increment(java.lang.String key) throws JSONException"
},
{
"code": null,
"e": 2134,
"s": 1518,
"text": "import org.json.JSONException;\nimport org.json.JSONObject;\npublic class IncrementJSONObjectTest {\n public static void main(String[] args) throws JSONException {\n JSONObject jsonObj = new JSONObject();\n jsonObj.put(\"year\", 2019);\n jsonObj.put(\"age\", 25);\n System.out.println(jsonObj.toString(3));\n jsonObj.increment(\"year\").increment(\"age\");\n System.out.println(jsonObj.toString(3));\n jsonObj.increment(\"year\").increment(\"age\");\n System.out.println(jsonObj.toString(3));\n jsonObj.increment(\"year\").increment(\"age\");\n System.out.println(jsonObj.toString(3));\n }\n}"
},
{
"code": null,
"e": 2254,
"s": 2134,
"text": "{\n \"year\": 2019,\n \"age\": 25\n}\n{\n \"year\": 2020,\n \"age\": 26\n}\n{\n \"year\": 2021,\n \"age\": 27\n}\n{\n \"year\": 2022,\n \"age\": 28\n}"
}
] |
How to Solve Analogies with Word2Vec | by Khuyen Tran | Towards Data Science
|
To make words understood by machine learning algorithms, word embedding is used to map words into vectors of real numbers. There are various word embedding models and word2vec is one of them.
In simple words, word2vec is a group of related models that are used to produce word embeddings. These models are trained to construct the linguistic contexts of words. Word2vec takes a large corpus of text and produces a vector space, with each unique word in the corpus being assigned to a corresponding vector in the space.
But how the word vectors are positioned in the vector space? They are positioned such that words that share common contexts in the corpus are located close to one another in the space.
To understand how word2vec works, let’s explore some methods that we can use with word2vec such as finding similarities between words or solving analogies like this
We will use the pre-trained word vectors from Glove. We are especially interested in Twitter dataset with 2B tweets, 27B tokens, and 200d vectors. The data could be downloaded here. We use Gensim to convert Glove vectors into the word2vec, then use KeyedVectors to load vectors in word2vec format.
Now we use model.most_similar() to find the top-N most similar words. Positive words contribute positively towards the similarity. Negative words contribute negatively towards the similarity, or in another word, contribute to the difference. Let’s test out this model!
Find the words that are most similar to ‘love’
model.most_similar(positive=['love'])
How about ‘girl’?
model.most_similar(positive=['girl'])
.We might as well look up the words that are similar to ‘boy’
model.most_similar(positive=['boy'])
Hmm. So is there a difference in similar words between ‘boy’ and ‘man’
model.most_similar(positive=['man'])
It seems like there are clearly some difference as a ‘boy’ becomes a ‘man’
The word embedding approach is also able to capture multiple different degrees of similarity between words. Semantic patterns can be reproduced using vector arithmetics. Thus, we could also use word2vec to solve analogies. If US has hamburger, what food does Canada have?
The results seem to show a variety of foods that are popular in Canada. Readers who are from Canada can confirm if these top words seem reasonable. Let’s explore a couple more countries with a function called analogy(). This time, we just return the one topmost similar word for each analogy.
Since visualizing is nice, let’s create a map between the countries and their corresponding foods. We use PCA to reduce the dimension of the data to 2.
From this map, the distance between countries indicates which countries are closer to one another in a 2 dimension space. The arrows indicate the relationship between countries and foods.
Congratulations! You have learned what word2vec is and how to find similarities between words with word2Vec. Seeing the power of word2vec, you may wonder: “How this method can work so well?”
We know that word2vec object function causes words that occur in similar contexts to have similar embeddings. But interestingly, what makes word embedding learning in the word2vec framework work so well is poorly understood. Whatever reason makes this embedding successful, I hope you understand its functionality and take advantage of this powerful tool for your text analysis. I encourage you to play with this dataset or the dataset of your choice to create other analogies with word2vec.
Feel free to fork and play with the code for this article in this Github repo.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Word2vec. Wikipedia. https://en.wikipedia.org/wiki/Word2vec
|
[
{
"code": null,
"e": 364,
"s": 172,
"text": "To make words understood by machine learning algorithms, word embedding is used to map words into vectors of real numbers. There are various word embedding models and word2vec is one of them."
},
{
"code": null,
"e": 691,
"s": 364,
"text": "In simple words, word2vec is a group of related models that are used to produce word embeddings. These models are trained to construct the linguistic contexts of words. Word2vec takes a large corpus of text and produces a vector space, with each unique word in the corpus being assigned to a corresponding vector in the space."
},
{
"code": null,
"e": 876,
"s": 691,
"text": "But how the word vectors are positioned in the vector space? They are positioned such that words that share common contexts in the corpus are located close to one another in the space."
},
{
"code": null,
"e": 1041,
"s": 876,
"text": "To understand how word2vec works, let’s explore some methods that we can use with word2vec such as finding similarities between words or solving analogies like this"
},
{
"code": null,
"e": 1339,
"s": 1041,
"text": "We will use the pre-trained word vectors from Glove. We are especially interested in Twitter dataset with 2B tweets, 27B tokens, and 200d vectors. The data could be downloaded here. We use Gensim to convert Glove vectors into the word2vec, then use KeyedVectors to load vectors in word2vec format."
},
{
"code": null,
"e": 1608,
"s": 1339,
"text": "Now we use model.most_similar() to find the top-N most similar words. Positive words contribute positively towards the similarity. Negative words contribute negatively towards the similarity, or in another word, contribute to the difference. Let’s test out this model!"
},
{
"code": null,
"e": 1655,
"s": 1608,
"text": "Find the words that are most similar to ‘love’"
},
{
"code": null,
"e": 1693,
"s": 1655,
"text": "model.most_similar(positive=['love'])"
},
{
"code": null,
"e": 1711,
"s": 1693,
"text": "How about ‘girl’?"
},
{
"code": null,
"e": 1749,
"s": 1711,
"text": "model.most_similar(positive=['girl'])"
},
{
"code": null,
"e": 1811,
"s": 1749,
"text": ".We might as well look up the words that are similar to ‘boy’"
},
{
"code": null,
"e": 1848,
"s": 1811,
"text": "model.most_similar(positive=['boy'])"
},
{
"code": null,
"e": 1919,
"s": 1848,
"text": "Hmm. So is there a difference in similar words between ‘boy’ and ‘man’"
},
{
"code": null,
"e": 1956,
"s": 1919,
"text": "model.most_similar(positive=['man'])"
},
{
"code": null,
"e": 2031,
"s": 1956,
"text": "It seems like there are clearly some difference as a ‘boy’ becomes a ‘man’"
},
{
"code": null,
"e": 2303,
"s": 2031,
"text": "The word embedding approach is also able to capture multiple different degrees of similarity between words. Semantic patterns can be reproduced using vector arithmetics. Thus, we could also use word2vec to solve analogies. If US has hamburger, what food does Canada have?"
},
{
"code": null,
"e": 2596,
"s": 2303,
"text": "The results seem to show a variety of foods that are popular in Canada. Readers who are from Canada can confirm if these top words seem reasonable. Let’s explore a couple more countries with a function called analogy(). This time, we just return the one topmost similar word for each analogy."
},
{
"code": null,
"e": 2748,
"s": 2596,
"text": "Since visualizing is nice, let’s create a map between the countries and their corresponding foods. We use PCA to reduce the dimension of the data to 2."
},
{
"code": null,
"e": 2936,
"s": 2748,
"text": "From this map, the distance between countries indicates which countries are closer to one another in a 2 dimension space. The arrows indicate the relationship between countries and foods."
},
{
"code": null,
"e": 3127,
"s": 2936,
"text": "Congratulations! You have learned what word2vec is and how to find similarities between words with word2Vec. Seeing the power of word2vec, you may wonder: “How this method can work so well?”"
},
{
"code": null,
"e": 3619,
"s": 3127,
"text": "We know that word2vec object function causes words that occur in similar contexts to have similar embeddings. But interestingly, what makes word embedding learning in the word2vec framework work so well is poorly understood. Whatever reason makes this embedding successful, I hope you understand its functionality and take advantage of this powerful tool for your text analysis. I encourage you to play with this dataset or the dataset of your choice to create other analogies with word2vec."
},
{
"code": null,
"e": 3698,
"s": 3619,
"text": "Feel free to fork and play with the code for this article in this Github repo."
},
{
"code": null,
"e": 3858,
"s": 3698,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
},
{
"code": null,
"e": 4034,
"s": 3858,
"text": "Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:"
},
{
"code": null,
"e": 4057,
"s": 4034,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4080,
"s": 4057,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4103,
"s": 4080,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4126,
"s": 4103,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4149,
"s": 4126,
"text": "towardsdatascience.com"
}
] |
Tryit Editor v3.7
|
Tryit: Sort the flex items
|
[] |
PyQt5 - Gradient Color Progress Bar - GeeksforGeeks
|
22 Apr, 2020
In this article we will see how we can set gradient color to the progress bar. Below is how normal color progress bar looks like vs the gradient color progress bar looks like.
In order to do this we have to change the CSS style sheet, below is the code for style sheet.
QProgressBar::chunk
{
border : 1px solid black;
background: QLinearGradient( x1: 0, y1: 0,
x2: 1, y2: 0,
stop: 0 #000fff,
stop: 1 #ff000f );
}
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, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 150, 200, 30) # set value to progress bar bar.setValue(30) # setting alignment to center bar.setAlignment(Qt.AlignCenter) # setting gradient color to progress bar bar.setStyleSheet("QProgressBar" "{" "border : 1px solid black;" "background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 # 00ffff, stop: 1 # ff000f );" "}") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24508,
"s": 24480,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 24685,
"s": 24508,
"text": "In this article we will see how we can set gradient color to the progress bar. Below is how normal color progress bar looks like vs the gradient color progress bar looks like. "
},
{
"code": null,
"e": 24779,
"s": 24685,
"text": "In order to do this we have to change the CSS style sheet, below is the code for style sheet."
},
{
"code": null,
"e": 25007,
"s": 24779,
"text": "QProgressBar::chunk \n{\nborder : 1px solid black;\nbackground: QLinearGradient( x1: 0, y1: 0,\n x2: 1, y2: 0, \n stop: 0 #000fff, \n stop: 1 #ff000f );\n}\n"
},
{
"code": null,
"e": 25036,
"s": 25007,
"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, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 150, 200, 30) # set value to progress bar bar.setValue(30) # setting alignment to center bar.setAlignment(Qt.AlignCenter) # setting gradient color to progress bar bar.setStyleSheet(\"QProgressBar\" \"{\" \"border : 1px solid black;\" \"background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 # 00ffff, stop: 1 # ff000f );\" \"}\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 26469,
"s": 25036,
"text": null
},
{
"code": null,
"e": 26478,
"s": 26469,
"text": "Output :"
},
{
"code": null,
"e": 26489,
"s": 26478,
"text": "Python-gui"
},
{
"code": null,
"e": 26501,
"s": 26489,
"text": "Python-PyQt"
},
{
"code": null,
"e": 26508,
"s": 26501,
"text": "Python"
},
{
"code": null,
"e": 26606,
"s": 26508,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26624,
"s": 26606,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26659,
"s": 26624,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26681,
"s": 26659,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26713,
"s": 26681,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26743,
"s": 26713,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26785,
"s": 26743,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26811,
"s": 26785,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26848,
"s": 26811,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26891,
"s": 26848,
"text": "Python program to convert a list to string"
}
] |
Tryit Editor v3.7
|
Tryit: Link URL's
|
[] |
Represent the fraction of two numbers in the string format
|
03 Sep, 2021
Given two integers representing the Numerator and Denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses.
Examples:
Input: Numerator = 1, Denominator = 2
Output: "0.5"
1/2 = 0.5 with no repeating part.
Input: Numerator = 50, Denominator = 22
Output: "2.(27)"
50/22 = 2.27272727... Since fractional part (27)
is repeating, it is enclosed in parentheses.
Prerequisites: Recurring Sequence in a Fraction
Approach: The idea is to first calculate the integral quotient (absolute part before decimal point) and then calculate the fractional part. To check if the fractional part is repeating, insert the remainder (numerator % denominator) in a map with key as remainder and value as the index position at which this remainder occurs. If at any point of time, the remainder becomes zero, then there doesn’t exist a repeating fraction otherwise if the remainder is already found in the map, then there exists a repeating fraction.
Below is the implementation of above approach.
C++
Java
Python3
Javascript
// C++ program to calculate// fraction of two numbers#include <bits/stdc++.h>using namespace std; // Function to return the required fraction// in string formatstring calculateFraction(int num, int den){ // If the numerator is zero, answer is 0 if (num == 0) return "0"; // If any one (out of numerator and denominator) // is -ve, sign of resultant answer -ve. int sign = (num < 0) ^ (den < 0) ? -1 : 1; num = abs(num); den = abs(den); // Calculate the absolute part // (before decimal point). int initial = num / den; // Output string to store the answer string res; // Append sign if (sign == -1) res += "-"; // Append the initial part res += to_string(initial); // If completely divisible, return answer. if (num % den == 0) return res; res += "."; // Initialize Remainder int rem = num % den; map<int, int> mp; // Position at which fraction starts repeating // if it exists int index; bool repeating = false; while (rem > 0 && !repeating) { // If this remainder is already seen, // then there exists a repeating fraction. if (mp.find(rem) != mp.end()) { // Index to insert parentheses index = mp[rem]; repeating = true; break; } else mp[rem] = res.size(); rem = rem * 10; // Calculate quotient, append // it to result and // calculate next remainder int temp = rem / den; res += to_string(temp); rem = rem % den; } // If repeating fraction exists, // insert parentheses. if (repeating) { res += ")"; res.insert(index, "("); } // Return result. return res;} // Drivers Codeint main(){ int num = 50, den = 22; cout << calculateFraction(num, den) << endl; num = -1, den = 2; cout << calculateFraction(num, den) << endl; return 0;}
// Java program to calculate fraction// of two numbersimport java.util.*; class GFG { // Function to return the required fraction // in string format public static String calculateFraction(int num, int den) { if (num == 0) return "0"; // if numerator is zero if (den == 0) return ""; // if denominator is zero // result StringBuilder StringBuilder result = new StringBuilder(); if ((num < 0) ^ (den < 0)) result.append("-"); // check -ve sign // absolute values of num and den num = Math.abs(num); den = Math.abs(den); long quo = num / den; // Quotient long rem = num % den * 10; // calculating remainder result.append( String.valueOf(quo)); // appending quotient if (rem == 0) return result .toString(); // return if remainder is 0 // if remainder is not zero, continue result.append("."); Map<Long, Integer> m = new HashMap<>(); // map for storing remainder // and the indexes of the // appropriate decimal in // stringbuilder while (rem != 0) { if (m.containsKey(rem)) { // if the rem is already present, find the // index and append ( ) int index = m.get(rem); String part1 = result.substring(0, index); String part2 = "(" + result.substring( index, result.length()) + ")"; return part1 + part2; } // continue updating the map and appending quo // which was generated by dividing rem with den m.put(rem, result.length()); quo = rem / den; result.append(String.valueOf(quo)); // update rem rem = (rem % den) * 10; } return result.toString(); } // Driver code public static void main(String[] args) { int num = 113; int den = 56; String resString1 = calculateFraction(num, den); num = -1; den = 2; String resString2 = calculateFraction(num, den); System.out.println(resString1); System.out.println(resString2); }} // This code is contributed by Saiteja Marisetti
# Python3 program to calculate fraction# of two numbers # Function to return the required# fraction in string formatdef calculateFraction(num, den) : # If the numerator is zero, answer is 0 if (num == 0): return "0" # If any one (out of numerator and denominator) # is -ve, sign of resultant answer -ve. sign = -1 if (num < 0) ^ (den < 0) else 1 num = abs(num) den = abs(den) # Calculate the absolute part # (before decimal point). initial = num // den # Output string to store the answer res = "" # Append sign if (sign == -1): res += "-" # Append the initial part res += str(initial) # If completely divisible, return answer. if (num % den == 0): return res res += "." # Initialize Remainder rem = num % den mp = {} # Position at which fraction starts # repeating if it exists index = 0 repeating = False while (rem > 0 and not repeating) : # If this remainder is already seen, # then there exists a repeating fraction. if ( rem in mp): # Index to insert parentheses index = mp[rem] repeating = True break else: mp[rem] = len(res) rem = rem * 10 # Calculate quotient, append it to result # and calculate next remainder temp = rem // den res += str(temp ) rem = rem % den # If repeating fraction exists, # insert parentheses. if (repeating) : res += ")" x = res[:index] x += "(" x += res[index:] res = x # Return result. return res # Driver codeif __name__ =="__main__": num = 50 den = 22 print(calculateFraction(num, den)) num = -1 den = 2 print(calculateFraction(num, den)) # This code is contributed# Shubham Singh(SHUBHAMSINGH10)
<script> // JavaScript program to calculate// fraction of two numbers // Function to return the required fraction// in string formatfunction calculateFraction(num, den){ // If the numerator is zero, answer is 0 if (num == 0) return "0"; // If any one (out of numerator and denominator) // is -ve, sign of resultant answer -ve. var sign = (num < 0) ^ (den < 0) ? -1 : 1; num = Math.abs(num); den = Math.abs(den); // Calculate the absolute part // (before decimal point). var initial = parseInt(num / den); // Output string to store the answer var res = []; // Append sign if (sign == -1) res.push("-"); // Append the initial part res.push(initial.toString()); // If completely divisible, return answer. if (num % den == 0) return res; res.push("."); // Initialize Remainder var rem = num % den; var mp = new Map(); // Position at which fraction starts repeating // if it exists var index; var repeating = false; while (rem > 0 && !repeating) { // If this remainder is already seen, // then there exists a repeating fraction. if (mp.has(rem)) { // Index to insert parentheses index = mp.get(rem); repeating = true; break; } else mp.set(rem, res.length); rem = rem * 10; // Calculate quotient, append // it to result and // calculate next remainder var temp = parseInt(rem / den); res.push(temp.toString()); rem = rem % den; } // If repeating fraction exists, // insert parentheses. if (repeating) { res.push(")"); res.splice(index,0, "("); } // Return result. return res.join('');} // Drivers Codevar num = 50, den = 22;document.write( calculateFraction(num, den) + "<br>");num = -1, den = 2;document.write( calculateFraction(num, den)); </script>
2.(27)
-0.5
SHUBHAMSINGH10
Akanksha_Rai
hitheshkumarcm33309
SaiTejaMarisetti
rrrtnx
anikakapoor
Fraction
Java-HashMap
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": "\n03 Sep, 2021"
},
{
"code": null,
"e": 247,
"s": 52,
"text": "Given two integers representing the Numerator and Denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses."
},
{
"code": null,
"e": 258,
"s": 247,
"text": "Examples: "
},
{
"code": null,
"e": 497,
"s": 258,
"text": "Input: Numerator = 1, Denominator = 2\nOutput: \"0.5\"\n1/2 = 0.5 with no repeating part.\n\nInput: Numerator = 50, Denominator = 22\nOutput: \"2.(27)\"\n50/22 = 2.27272727... Since fractional part (27) \nis repeating, it is enclosed in parentheses."
},
{
"code": null,
"e": 545,
"s": 497,
"text": "Prerequisites: Recurring Sequence in a Fraction"
},
{
"code": null,
"e": 1068,
"s": 545,
"text": "Approach: The idea is to first calculate the integral quotient (absolute part before decimal point) and then calculate the fractional part. To check if the fractional part is repeating, insert the remainder (numerator % denominator) in a map with key as remainder and value as the index position at which this remainder occurs. If at any point of time, the remainder becomes zero, then there doesn’t exist a repeating fraction otherwise if the remainder is already found in the map, then there exists a repeating fraction."
},
{
"code": null,
"e": 1117,
"s": 1068,
"text": "Below is the implementation of above approach. "
},
{
"code": null,
"e": 1121,
"s": 1117,
"text": "C++"
},
{
"code": null,
"e": 1126,
"s": 1121,
"text": "Java"
},
{
"code": null,
"e": 1134,
"s": 1126,
"text": "Python3"
},
{
"code": null,
"e": 1145,
"s": 1134,
"text": "Javascript"
},
{
"code": "// C++ program to calculate// fraction of two numbers#include <bits/stdc++.h>using namespace std; // Function to return the required fraction// in string formatstring calculateFraction(int num, int den){ // If the numerator is zero, answer is 0 if (num == 0) return \"0\"; // If any one (out of numerator and denominator) // is -ve, sign of resultant answer -ve. int sign = (num < 0) ^ (den < 0) ? -1 : 1; num = abs(num); den = abs(den); // Calculate the absolute part // (before decimal point). int initial = num / den; // Output string to store the answer string res; // Append sign if (sign == -1) res += \"-\"; // Append the initial part res += to_string(initial); // If completely divisible, return answer. if (num % den == 0) return res; res += \".\"; // Initialize Remainder int rem = num % den; map<int, int> mp; // Position at which fraction starts repeating // if it exists int index; bool repeating = false; while (rem > 0 && !repeating) { // If this remainder is already seen, // then there exists a repeating fraction. if (mp.find(rem) != mp.end()) { // Index to insert parentheses index = mp[rem]; repeating = true; break; } else mp[rem] = res.size(); rem = rem * 10; // Calculate quotient, append // it to result and // calculate next remainder int temp = rem / den; res += to_string(temp); rem = rem % den; } // If repeating fraction exists, // insert parentheses. if (repeating) { res += \")\"; res.insert(index, \"(\"); } // Return result. return res;} // Drivers Codeint main(){ int num = 50, den = 22; cout << calculateFraction(num, den) << endl; num = -1, den = 2; cout << calculateFraction(num, den) << endl; return 0;}",
"e": 3085,
"s": 1145,
"text": null
},
{
"code": "// Java program to calculate fraction// of two numbersimport java.util.*; class GFG { // Function to return the required fraction // in string format public static String calculateFraction(int num, int den) { if (num == 0) return \"0\"; // if numerator is zero if (den == 0) return \"\"; // if denominator is zero // result StringBuilder StringBuilder result = new StringBuilder(); if ((num < 0) ^ (den < 0)) result.append(\"-\"); // check -ve sign // absolute values of num and den num = Math.abs(num); den = Math.abs(den); long quo = num / den; // Quotient long rem = num % den * 10; // calculating remainder result.append( String.valueOf(quo)); // appending quotient if (rem == 0) return result .toString(); // return if remainder is 0 // if remainder is not zero, continue result.append(\".\"); Map<Long, Integer> m = new HashMap<>(); // map for storing remainder // and the indexes of the // appropriate decimal in // stringbuilder while (rem != 0) { if (m.containsKey(rem)) { // if the rem is already present, find the // index and append ( ) int index = m.get(rem); String part1 = result.substring(0, index); String part2 = \"(\" + result.substring( index, result.length()) + \")\"; return part1 + part2; } // continue updating the map and appending quo // which was generated by dividing rem with den m.put(rem, result.length()); quo = rem / den; result.append(String.valueOf(quo)); // update rem rem = (rem % den) * 10; } return result.toString(); } // Driver code public static void main(String[] args) { int num = 113; int den = 56; String resString1 = calculateFraction(num, den); num = -1; den = 2; String resString2 = calculateFraction(num, den); System.out.println(resString1); System.out.println(resString2); }} // This code is contributed by Saiteja Marisetti",
"e": 5535,
"s": 3085,
"text": null
},
{
"code": "# Python3 program to calculate fraction# of two numbers # Function to return the required# fraction in string formatdef calculateFraction(num, den) : # If the numerator is zero, answer is 0 if (num == 0): return \"0\" # If any one (out of numerator and denominator) # is -ve, sign of resultant answer -ve. sign = -1 if (num < 0) ^ (den < 0) else 1 num = abs(num) den = abs(den) # Calculate the absolute part # (before decimal point). initial = num // den # Output string to store the answer res = \"\" # Append sign if (sign == -1): res += \"-\" # Append the initial part res += str(initial) # If completely divisible, return answer. if (num % den == 0): return res res += \".\" # Initialize Remainder rem = num % den mp = {} # Position at which fraction starts # repeating if it exists index = 0 repeating = False while (rem > 0 and not repeating) : # If this remainder is already seen, # then there exists a repeating fraction. if ( rem in mp): # Index to insert parentheses index = mp[rem] repeating = True break else: mp[rem] = len(res) rem = rem * 10 # Calculate quotient, append it to result # and calculate next remainder temp = rem // den res += str(temp ) rem = rem % den # If repeating fraction exists, # insert parentheses. if (repeating) : res += \")\" x = res[:index] x += \"(\" x += res[index:] res = x # Return result. return res # Driver codeif __name__ ==\"__main__\": num = 50 den = 22 print(calculateFraction(num, den)) num = -1 den = 2 print(calculateFraction(num, den)) # This code is contributed# Shubham Singh(SHUBHAMSINGH10)",
"e": 7399,
"s": 5535,
"text": null
},
{
"code": "<script> // JavaScript program to calculate// fraction of two numbers // Function to return the required fraction// in string formatfunction calculateFraction(num, den){ // If the numerator is zero, answer is 0 if (num == 0) return \"0\"; // If any one (out of numerator and denominator) // is -ve, sign of resultant answer -ve. var sign = (num < 0) ^ (den < 0) ? -1 : 1; num = Math.abs(num); den = Math.abs(den); // Calculate the absolute part // (before decimal point). var initial = parseInt(num / den); // Output string to store the answer var res = []; // Append sign if (sign == -1) res.push(\"-\"); // Append the initial part res.push(initial.toString()); // If completely divisible, return answer. if (num % den == 0) return res; res.push(\".\"); // Initialize Remainder var rem = num % den; var mp = new Map(); // Position at which fraction starts repeating // if it exists var index; var repeating = false; while (rem > 0 && !repeating) { // If this remainder is already seen, // then there exists a repeating fraction. if (mp.has(rem)) { // Index to insert parentheses index = mp.get(rem); repeating = true; break; } else mp.set(rem, res.length); rem = rem * 10; // Calculate quotient, append // it to result and // calculate next remainder var temp = parseInt(rem / den); res.push(temp.toString()); rem = rem % den; } // If repeating fraction exists, // insert parentheses. if (repeating) { res.push(\")\"); res.splice(index,0, \"(\"); } // Return result. return res.join('');} // Drivers Codevar num = 50, den = 22;document.write( calculateFraction(num, den) + \"<br>\");num = -1, den = 2;document.write( calculateFraction(num, den)); </script>",
"e": 9338,
"s": 7399,
"text": null
},
{
"code": null,
"e": 9350,
"s": 9338,
"text": "2.(27)\n-0.5"
},
{
"code": null,
"e": 9367,
"s": 9352,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 9380,
"s": 9367,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9400,
"s": 9380,
"text": "hitheshkumarcm33309"
},
{
"code": null,
"e": 9417,
"s": 9400,
"text": "SaiTejaMarisetti"
},
{
"code": null,
"e": 9424,
"s": 9417,
"text": "rrrtnx"
},
{
"code": null,
"e": 9436,
"s": 9424,
"text": "anikakapoor"
},
{
"code": null,
"e": 9445,
"s": 9436,
"text": "Fraction"
},
{
"code": null,
"e": 9458,
"s": 9445,
"text": "Java-HashMap"
},
{
"code": null,
"e": 9471,
"s": 9458,
"text": "Mathematical"
},
{
"code": null,
"e": 9484,
"s": 9471,
"text": "Mathematical"
}
] |
Python | Pandas dataframe.resample()
|
22 Oct, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.resample() function is primarily used for time series data.A time series is a series of data points indexed (or listed or graphed) in time order. Most commonly, a time series is a sequence taken at successive equally spaced points in time. It is a Convenience method for frequency conversion and resampling of time series. Object must have a datetime-like index (DatetimeIndex, PeriodIndex, or TimedeltaIndex), or pass datetime-like values to the on or level keyword.
Syntax : DataFrame.resample(rule, how=None, axis=0, fill_method=None, closed=None, label=None, convention=’start’, kind=None, loffset=None, limit=None, base=0, on=None, level=None)
Parameters :rule : the offset string or object representing target conversionaxis : int, optional, default 0closed : {‘right’, ‘left’}label : {‘right’, ‘left’}convention : For PeriodIndex only, controls whether to use the start or end of ruleloffset : Adjust the resampled time labelsbase : For frequencies that evenly subdivide 1 day, the “origin” of the aggregated intervals. For example, for ‘5min’ frequency, base could range from 0 through 4. Defaults to 0.on : For a DataFrame, column to use instead of index for resampling. Column must be datetime-like.level : For a MultiIndex, level (name or number) to use for resampling. Level must be datetime-like.
Resampling generates a unique sampling distribution on the basis of the actual data. We can apply various frequency to resample our time series data. This is a very important technique in the field of analytics.Most commonly used time series frequency are –W : weekly frequencyM : month end frequencySM : semi-month end frequency (15th and end of month)Q : quarter end frequency
There are many other types of time series frequency available. Let’s see how to apply these time series frequency on data and resample it.
For link to CSV file Used in Code, click here
This is a stock price data of Apple for a duration of 1 year from (13-11-17) to (13-11-18)
Example #1: Resampling the data on monthly frequency
# importing pandas as pdimport pandas as pd # By default the "date" column was in string format,# we need to convert it into date-time format # parse_dates =["date"], converts the "date" # column to date-time format. We know that # resampling works with time-series data only# so convert "date" column to index # index_col ="date", makes "date" column, the index of the data framedf = pd.read_csv("apple.csv", parse_dates =["date"], index_col ="date") # Printing the first 10 rows of dataframedf[:10]
# Resampling the time series data based on months# we apply it on stock close price# 'M' indicates monthmonthly_resampled_data = df.close.resample('M').mean() # the above command will find the mean closing price# of each month for a duration of 12 months.monthly_resampled_data
Output : Example #2: Resampling the data on weekly frequency
# importing pandas as pdimport pandas as pd # We know that resampling works with time-series data# only so convert "date" column to index# index_col ="date", makes "date" column. df = pd.read_csv("apple.csv", parse_dates =["date"], index_col ="date") # Resampling the time series data based on weekly frequency# we apply it on stock open price 'W' indicates weekweekly_resampled_data = df.open.resample('W').mean() # find the mean opening price of each week # for each week over a period of 1 year.weekly_resampled_data
Output : Example #3: Resampling the data on Quarterly frequency
# importing pandas as pdimport pandas as pd # We know that resampling works with time-series# data only so convert our "date" column to index# index_col ="date", makes "date" columndf = pd.read_csv("apple.csv", parse_dates =["date"], index_col ="date") # Resampling the time series data# based on Quarterly frequency# 'Q' indicates quarter Quarterly_resampled_data = df.open.resample('Q').mean() # mean opening price of each quarter# over a period of 1 year.Quarterly_resampled_data
Output :
reddy_bhargava
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Oct, 2019"
},
{
"code": null,
"e": 267,
"s": 53,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 752,
"s": 267,
"text": "Pandas dataframe.resample() function is primarily used for time series data.A time series is a series of data points indexed (or listed or graphed) in time order. Most commonly, a time series is a sequence taken at successive equally spaced points in time. It is a Convenience method for frequency conversion and resampling of time series. Object must have a datetime-like index (DatetimeIndex, PeriodIndex, or TimedeltaIndex), or pass datetime-like values to the on or level keyword."
},
{
"code": null,
"e": 933,
"s": 752,
"text": "Syntax : DataFrame.resample(rule, how=None, axis=0, fill_method=None, closed=None, label=None, convention=’start’, kind=None, loffset=None, limit=None, base=0, on=None, level=None)"
},
{
"code": null,
"e": 1594,
"s": 933,
"text": "Parameters :rule : the offset string or object representing target conversionaxis : int, optional, default 0closed : {‘right’, ‘left’}label : {‘right’, ‘left’}convention : For PeriodIndex only, controls whether to use the start or end of ruleloffset : Adjust the resampled time labelsbase : For frequencies that evenly subdivide 1 day, the “origin” of the aggregated intervals. For example, for ‘5min’ frequency, base could range from 0 through 4. Defaults to 0.on : For a DataFrame, column to use instead of index for resampling. Column must be datetime-like.level : For a MultiIndex, level (name or number) to use for resampling. Level must be datetime-like."
},
{
"code": null,
"e": 1973,
"s": 1594,
"text": "Resampling generates a unique sampling distribution on the basis of the actual data. We can apply various frequency to resample our time series data. This is a very important technique in the field of analytics.Most commonly used time series frequency are –W : weekly frequencyM : month end frequencySM : semi-month end frequency (15th and end of month)Q : quarter end frequency"
},
{
"code": null,
"e": 2112,
"s": 1973,
"text": "There are many other types of time series frequency available. Let’s see how to apply these time series frequency on data and resample it."
},
{
"code": null,
"e": 2158,
"s": 2112,
"text": "For link to CSV file Used in Code, click here"
},
{
"code": null,
"e": 2249,
"s": 2158,
"text": "This is a stock price data of Apple for a duration of 1 year from (13-11-17) to (13-11-18)"
},
{
"code": null,
"e": 2302,
"s": 2249,
"text": "Example #1: Resampling the data on monthly frequency"
},
{
"code": "# importing pandas as pdimport pandas as pd # By default the \"date\" column was in string format,# we need to convert it into date-time format # parse_dates =[\"date\"], converts the \"date\" # column to date-time format. We know that # resampling works with time-series data only# so convert \"date\" column to index # index_col =\"date\", makes \"date\" column, the index of the data framedf = pd.read_csv(\"apple.csv\", parse_dates =[\"date\"], index_col =\"date\") # Printing the first 10 rows of dataframedf[:10]",
"e": 2807,
"s": 2302,
"text": null
},
{
"code": "# Resampling the time series data based on months# we apply it on stock close price# 'M' indicates monthmonthly_resampled_data = df.close.resample('M').mean() # the above command will find the mean closing price# of each month for a duration of 12 months.monthly_resampled_data",
"e": 3086,
"s": 2807,
"text": null
},
{
"code": null,
"e": 3147,
"s": 3086,
"text": "Output : Example #2: Resampling the data on weekly frequency"
},
{
"code": "# importing pandas as pdimport pandas as pd # We know that resampling works with time-series data# only so convert \"date\" column to index# index_col =\"date\", makes \"date\" column. df = pd.read_csv(\"apple.csv\", parse_dates =[\"date\"], index_col =\"date\") # Resampling the time series data based on weekly frequency# we apply it on stock open price 'W' indicates weekweekly_resampled_data = df.open.resample('W').mean() # find the mean opening price of each week # for each week over a period of 1 year.weekly_resampled_data",
"e": 3671,
"s": 3147,
"text": null
},
{
"code": null,
"e": 3735,
"s": 3671,
"text": "Output : Example #3: Resampling the data on Quarterly frequency"
},
{
"code": "# importing pandas as pdimport pandas as pd # We know that resampling works with time-series# data only so convert our \"date\" column to index# index_col =\"date\", makes \"date\" columndf = pd.read_csv(\"apple.csv\", parse_dates =[\"date\"], index_col =\"date\") # Resampling the time series data# based on Quarterly frequency# 'Q' indicates quarter Quarterly_resampled_data = df.open.resample('Q').mean() # mean opening price of each quarter# over a period of 1 year.Quarterly_resampled_data",
"e": 4224,
"s": 3735,
"text": null
},
{
"code": null,
"e": 4233,
"s": 4224,
"text": "Output :"
},
{
"code": null,
"e": 4248,
"s": 4233,
"text": "reddy_bhargava"
},
{
"code": null,
"e": 4272,
"s": 4248,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 4304,
"s": 4272,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 4318,
"s": 4304,
"text": "Python-pandas"
},
{
"code": null,
"e": 4325,
"s": 4318,
"text": "Python"
},
{
"code": null,
"e": 4423,
"s": 4325,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4441,
"s": 4423,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4483,
"s": 4441,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4505,
"s": 4483,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4537,
"s": 4505,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4566,
"s": 4537,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4593,
"s": 4566,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4614,
"s": 4593,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4650,
"s": 4614,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 4673,
"s": 4650,
"text": "Introduction To PYTHON"
}
] |
Java Integer compare() method
|
05 Dec, 2018
The compare() method of Integer class of java.lang package compares two integer values (x, y) givenas a parameter and returns the value zero if (x==y), if (x < y) then it returns a value less than zero andif (x > y) then it returns a value greater than zero.
Syntax :
public static int compare(int x, int y)
Parameter :
x : the first int to compare
y : the second int to compare
Return :
This method returns the value zero if (x==y),
if (x < y) then it returns a value less than zero
and if (x > y) then it returns a value greater than zero.
Example :To show working of java.lang.Integer.compare() method.
// Java program to demonstrate working// of java.lang.Integer.compare() methodimport java.lang.Integer; class Gfg { // driver code public static void main(String args[]) { int a = 10; int b = 20; // as 10 less than 20, Output will be a value less than zero System.out.println(Integer.compare(a, b)); int x = 30; int y = 30; // as 30 equals 30, Output will be zero System.out.println(Integer.compare(x, y)); int w = 15; int z = 8; // as 15 is greater than 8, Output will be a value greater than zero System.out.println(Integer.compare(w, z)); }}
Output:
-1
0
1
Java-Functions
Java-Integer
Java-lang 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": 53,
"s": 25,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 312,
"s": 53,
"text": "The compare() method of Integer class of java.lang package compares two integer values (x, y) givenas a parameter and returns the value zero if (x==y), if (x < y) then it returns a value less than zero andif (x > y) then it returns a value greater than zero."
},
{
"code": null,
"e": 321,
"s": 312,
"text": "Syntax :"
},
{
"code": null,
"e": 598,
"s": 321,
"text": "public static int compare(int x, int y)\nParameter :\nx : the first int to compare\ny : the second int to compare\nReturn :\nThis method returns the value zero if (x==y), \nif (x < y) then it returns a value less than zero \nand if (x > y) then it returns a value greater than zero.\n"
},
{
"code": null,
"e": 662,
"s": 598,
"text": "Example :To show working of java.lang.Integer.compare() method."
},
{
"code": "// Java program to demonstrate working// of java.lang.Integer.compare() methodimport java.lang.Integer; class Gfg { // driver code public static void main(String args[]) { int a = 10; int b = 20; // as 10 less than 20, Output will be a value less than zero System.out.println(Integer.compare(a, b)); int x = 30; int y = 30; // as 30 equals 30, Output will be zero System.out.println(Integer.compare(x, y)); int w = 15; int z = 8; // as 15 is greater than 8, Output will be a value greater than zero System.out.println(Integer.compare(w, z)); }}",
"e": 1314,
"s": 662,
"text": null
},
{
"code": null,
"e": 1322,
"s": 1314,
"text": "Output:"
},
{
"code": null,
"e": 1330,
"s": 1322,
"text": "-1\n0\n1\n"
},
{
"code": null,
"e": 1345,
"s": 1330,
"text": "Java-Functions"
},
{
"code": null,
"e": 1358,
"s": 1345,
"text": "Java-Integer"
},
{
"code": null,
"e": 1376,
"s": 1358,
"text": "Java-lang package"
},
{
"code": null,
"e": 1381,
"s": 1376,
"text": "Java"
},
{
"code": null,
"e": 1386,
"s": 1381,
"text": "Java"
},
{
"code": null,
"e": 1484,
"s": 1386,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1535,
"s": 1484,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 1566,
"s": 1535,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 1585,
"s": 1566,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 1615,
"s": 1585,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 1630,
"s": 1615,
"text": "Stream In Java"
},
{
"code": null,
"e": 1648,
"s": 1630,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 1668,
"s": 1648,
"text": "Collections in Java"
},
{
"code": null,
"e": 1692,
"s": 1668,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 1724,
"s": 1692,
"text": "Multidimensional Arrays in Java"
}
] |
ReactJS UI Ant Design Upload Component
|
03 Jun, 2021
Ant Design Library has this component pre-built, and it is very easy to integrate as well. Upload Component is used for uploading files by selecting or dragging. We can use the following approach in ReactJS to use the Ant Design Upload Component.
Upload Props:
accept: It is used to denote the file types that can be accepted.
action: It is used to denote the Uploading URL.
beforeUpload: It is a Hook function that will be executed before uploading.
customRequest: It is used to override the default xhr behavior.
data: It is used for uploading extra params or function which can return uploading extra params.
defaultFileList: It is used to denote the Default list of files that have been uploaded.
directory: It is used to support upload the whole directory.
disabled: It is used to disable the upload button.
fileList: It is used to denote the list of files that have been uploaded.
headers: It is used to set request headers.
iconRender: It is used for the custom show icon.
isImageUrl: It is used to customize if render <img /> in thumbnail.
itemRender: It is used for the custom item of uploadList.
listType: It is the Built-in stylesheets, support for text, picture, or picture-card type.
maxCount: It is used to limit the number of uploaded files.
method: It is the HTTP method of upload request.
multiple: It is used to indicate whether to support selected multiple files.
name: It is used to denote the name of the uploading file.
openFileDialogOnClick: It is used to open the file dialog on click of it.
previewFile: It is used for the customized preview file logic.
progress: It is used for the Custom progress bar.
showUploadList: It is used to indicate whether to show the default upload list.
withCredentials: It is the Ajax upload with cookie sent.
onChange: It is a callback function that is triggered when the uploading state is changing.
onDrop: It is a callback function that is triggered when files are dragged and dropped into the upload area.
onDownload: It is the method to download the file when it is clicked.
onPreview: It is a callback function that is triggered when a file link or preview icon is clicked.
onRemove: It is a callback function that is triggered when the removing file button is clicked.
UploadFile Props:
name: It is used to denote the file name.
percent: It is used to denote the upload progress percent.
status: It is used to denote the upload status.
thumbUrl: It is used to pass the thumb image URL.
uid: It is the unique ID, and it will be generated automatically when not provided.
url: It is used to denote the download URL.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install antd
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'import "antd/dist/antd.css";import { Upload, message, Button } from 'antd'; const props = { headers: { authorization: 'authorization-text', }, action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76', name: 'file',}; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Upload Component</h4> <> <Upload {...props} onChange={(response) => { if (response.file.status !== 'uploading') { console.log(response.file, response.fileList); } if (response.file.status === 'done') { message.success(`${response.file.name} file uploaded successfully`); } else if (response.file.status === 'error') { message.error(`${response.file.name} file upload failed.`); } }} > <Button>Upload File</Button> </Upload> </> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://ant.design/components/upload/
ReactJS-Ant Design
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 275,
"s": 28,
"text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. Upload Component is used for uploading files by selecting or dragging. We can use the following approach in ReactJS to use the Ant Design Upload Component."
},
{
"code": null,
"e": 289,
"s": 275,
"text": "Upload Props:"
},
{
"code": null,
"e": 355,
"s": 289,
"text": "accept: It is used to denote the file types that can be accepted."
},
{
"code": null,
"e": 403,
"s": 355,
"text": "action: It is used to denote the Uploading URL."
},
{
"code": null,
"e": 479,
"s": 403,
"text": "beforeUpload: It is a Hook function that will be executed before uploading."
},
{
"code": null,
"e": 543,
"s": 479,
"text": "customRequest: It is used to override the default xhr behavior."
},
{
"code": null,
"e": 640,
"s": 543,
"text": "data: It is used for uploading extra params or function which can return uploading extra params."
},
{
"code": null,
"e": 729,
"s": 640,
"text": "defaultFileList: It is used to denote the Default list of files that have been uploaded."
},
{
"code": null,
"e": 790,
"s": 729,
"text": "directory: It is used to support upload the whole directory."
},
{
"code": null,
"e": 841,
"s": 790,
"text": "disabled: It is used to disable the upload button."
},
{
"code": null,
"e": 915,
"s": 841,
"text": "fileList: It is used to denote the list of files that have been uploaded."
},
{
"code": null,
"e": 959,
"s": 915,
"text": "headers: It is used to set request headers."
},
{
"code": null,
"e": 1008,
"s": 959,
"text": "iconRender: It is used for the custom show icon."
},
{
"code": null,
"e": 1076,
"s": 1008,
"text": "isImageUrl: It is used to customize if render <img /> in thumbnail."
},
{
"code": null,
"e": 1134,
"s": 1076,
"text": "itemRender: It is used for the custom item of uploadList."
},
{
"code": null,
"e": 1225,
"s": 1134,
"text": "listType: It is the Built-in stylesheets, support for text, picture, or picture-card type."
},
{
"code": null,
"e": 1285,
"s": 1225,
"text": "maxCount: It is used to limit the number of uploaded files."
},
{
"code": null,
"e": 1334,
"s": 1285,
"text": "method: It is the HTTP method of upload request."
},
{
"code": null,
"e": 1411,
"s": 1334,
"text": "multiple: It is used to indicate whether to support selected multiple files."
},
{
"code": null,
"e": 1470,
"s": 1411,
"text": "name: It is used to denote the name of the uploading file."
},
{
"code": null,
"e": 1544,
"s": 1470,
"text": "openFileDialogOnClick: It is used to open the file dialog on click of it."
},
{
"code": null,
"e": 1607,
"s": 1544,
"text": "previewFile: It is used for the customized preview file logic."
},
{
"code": null,
"e": 1657,
"s": 1607,
"text": "progress: It is used for the Custom progress bar."
},
{
"code": null,
"e": 1737,
"s": 1657,
"text": "showUploadList: It is used to indicate whether to show the default upload list."
},
{
"code": null,
"e": 1794,
"s": 1737,
"text": "withCredentials: It is the Ajax upload with cookie sent."
},
{
"code": null,
"e": 1886,
"s": 1794,
"text": "onChange: It is a callback function that is triggered when the uploading state is changing."
},
{
"code": null,
"e": 1995,
"s": 1886,
"text": "onDrop: It is a callback function that is triggered when files are dragged and dropped into the upload area."
},
{
"code": null,
"e": 2065,
"s": 1995,
"text": "onDownload: It is the method to download the file when it is clicked."
},
{
"code": null,
"e": 2165,
"s": 2065,
"text": "onPreview: It is a callback function that is triggered when a file link or preview icon is clicked."
},
{
"code": null,
"e": 2261,
"s": 2165,
"text": "onRemove: It is a callback function that is triggered when the removing file button is clicked."
},
{
"code": null,
"e": 2279,
"s": 2261,
"text": "UploadFile Props:"
},
{
"code": null,
"e": 2321,
"s": 2279,
"text": "name: It is used to denote the file name."
},
{
"code": null,
"e": 2380,
"s": 2321,
"text": "percent: It is used to denote the upload progress percent."
},
{
"code": null,
"e": 2428,
"s": 2380,
"text": "status: It is used to denote the upload status."
},
{
"code": null,
"e": 2478,
"s": 2428,
"text": "thumbUrl: It is used to pass the thumb image URL."
},
{
"code": null,
"e": 2562,
"s": 2478,
"text": "uid: It is the unique ID, and it will be generated automatically when not provided."
},
{
"code": null,
"e": 2606,
"s": 2562,
"text": "url: It is used to denote the download URL."
},
{
"code": null,
"e": 2658,
"s": 2608,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 2753,
"s": 2658,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 2817,
"s": 2753,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 2849,
"s": 2817,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 2962,
"s": 2849,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 3062,
"s": 2962,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 3076,
"s": 3062,
"text": "cd foldername"
},
{
"code": null,
"e": 3197,
"s": 3076,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd"
},
{
"code": null,
"e": 3302,
"s": 3197,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 3319,
"s": 3302,
"text": "npm install antd"
},
{
"code": null,
"e": 3371,
"s": 3319,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 3389,
"s": 3371,
"text": "Project Structure"
},
{
"code": null,
"e": 3519,
"s": 3389,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 3526,
"s": 3519,
"text": "App.js"
},
{
"code": "import React from 'react'import \"antd/dist/antd.css\";import { Upload, message, Button } from 'antd'; const props = { headers: { authorization: 'authorization-text', }, action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76', name: 'file',}; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Upload Component</h4> <> <Upload {...props} onChange={(response) => { if (response.file.status !== 'uploading') { console.log(response.file, response.fileList); } if (response.file.status === 'done') { message.success(`${response.file.name} file uploaded successfully`); } else if (response.file.status === 'error') { message.error(`${response.file.name} file upload failed.`); } }} > <Button>Upload File</Button> </Upload> </> </div> );}",
"e": 4577,
"s": 3526,
"text": null
},
{
"code": null,
"e": 4690,
"s": 4577,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 4700,
"s": 4690,
"text": "npm start"
},
{
"code": null,
"e": 4799,
"s": 4700,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 4848,
"s": 4799,
"text": "Reference: https://ant.design/components/upload/"
},
{
"code": null,
"e": 4867,
"s": 4848,
"text": "ReactJS-Ant Design"
},
{
"code": null,
"e": 4875,
"s": 4867,
"text": "ReactJS"
},
{
"code": null,
"e": 4892,
"s": 4875,
"text": "Web Technologies"
}
] |
Maximum repeated frequency of characters in a given string
|
09 Jun, 2021
Given a string S, the task is to find the count of maximum repeated frequency of characters in the given string S.Examples:
Input: S = “geeksgeeks” Output: Frequency 2 is repeated 3 times Explanation: Frequency of characters in the given string – {“g”: 2, “e”: 4, “k”: 2, “s”: 2} The frequency 2 is repeated thrice for the characters “g”, “k”, “s”.Input: S = “abcabcdedee” Output: Frequency 2 is repeated 4 times. Explanation: Frequency of characters in the given string – {“a”: 2, “b”: 2, “c”: 2, “d”: 2, “e”: 3} The frequency 2 is repeated four times for the characters “a”, “b”, “c”, “d”.
Efficient Approach:
The idea is to first store the frequency of characters of the string in an array of size 26. Since all characters of strings are among 26 lowercase English alphabets, we can store the frequency of characters in an array of size 26.
Create a hash map, to store the count of frequencies of the characters and return the frequency which occurred max times.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// maximum repeated frequency of// characters in the given string #include <bits/stdc++.h>using namespace std; // Function to find the maximum// repeated frequency of the// characters in the given stringvoid findMaxFrequency(string s){ // Hash-Array to store the // frequency of characters int arr[26] = { 0 }; // Loop to find the frequency // of the characters for (int i = 0; i < s.length(); i++) arr[s[i] - 'a']++; // Hash map to store the occurrence // of frequencies of characters unordered_map<int, int> hash; for (int i = 0; i < 26; i++) if (arr[i] != 0) hash[arr[i]]++; // Loop to find the maximum // Repeated frequency from hash-map int max_count = 0, res = -1; for (auto i : hash) { if (max_count < i.second) { res = i.first; max_count = i.second; } } cout <<"Frequency " << res << " is repeated " << max_count<<" times";} // Driver Codeint main(){ string s = "geeksgeeks"; // Function Call findMaxFrequency(s); return 0;}
// Java implementation to find the// maximum repeated frequency of// characters in the given Stringimport java.util.*; class GFG{ // Function to find the maximum// repeated frequency of the// characters in the given Stringstatic void findMaxFrequency(String s){ // Hash-Array to store the // frequency of characters int arr[] = new int[26]; // Loop to find the frequency // of the characters for (int i = 0; i < s.length(); i++) arr[s.charAt(i) - 'a']++; // Hash map to store the occurrence // of frequencies of characters HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>(); for (int i = 0; i < 26; i++) if (arr[i] != 0) { if(hash.containsKey(arr[i])){ hash.put(arr[i], hash.get(arr[i])+1); } else{ hash.put(arr[i], 1); } } // Loop to find the maximum // Repeated frequency from hash-map int max_count = 0, res = -1; for (Map.Entry<Integer,Integer> i : hash.entrySet()){ if (max_count < i.getValue()) { res = i.getKey(); max_count = i.getValue(); } } System.out.println("Frequency " + res+ " is repeated " + max_count+" times");} // Driver Codepublic static void main(String[] args){ String s = "geeksgeeks"; // Function Call findMaxFrequency(s);}} // This code is contributed by sapnasingh4991
# Python3 implementation to find the# maximum repeated frequency of# characters in the given string # Function to find the maximum# repeated frequency of the# characters in the given stringdef findMaxFrequency(s): # Hash-Array to store the # frequency of characters arr = [0]*26 # Loop to find the frequency # of the characters for i in range(len(s)): arr[ord(s[i]) - ord('a')] += 1 # Hash map to store the occurrence # of frequencies of characters hash = {} for i in range(26): if (arr[i] != 0): if arr[i] not in hash: hash[arr[i]] = 0 hash[arr[i]] += 1 # Loop to find the maximum # Repeated frequency from hash-map max_count = 0 res = -1 for i in hash: if (max_count < hash[i]): res = i max_count = hash[i] print("Frequency", res, "is repeated", max_count, "times") # Driver Code s = "geeksgeeks" # Function CallfindMaxFrequency(s) # This code is contributed by shubhamsingh10
// C# implementation to find the// maximum repeated frequency of// characters in the given Stringusing System;using System.Collections.Generic; class GFG{ // Function to find the maximum// repeated frequency of the// characters in the given Stringstatic void findMaxFrequency(String s){ // Hash-Array to store the // frequency of characters int []arr = new int[26]; // Loop to find the frequency // of the characters for (int i = 0; i < s.Length; i++) arr[s[i] - 'a']++; // Hash map to store the occurrence // of frequencies of characters Dictionary<int,int> hash = new Dictionary<int,int>(); for (int i = 0; i < 26; i++) if (arr[i] != 0) { if(hash.ContainsKey(arr[i])){ hash[arr[i]] = hash[arr[i]]+1; } else{ hash.Add(arr[i], 1); } } // Loop to find the maximum // Repeated frequency from hash-map int max_count = 0, res = -1; foreach( KeyValuePair<int,int> i in hash){ if (max_count < i.Value) { res = i.Key; max_count = i.Value; } } Console.WriteLine("Frequency " + res+ " is repeated " + max_count+" times");} // Driver Codepublic static void Main(String[] args){ String s = "geeksgeeks"; // Function Call findMaxFrequency(s);}} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation to find the// maximum repeated frequency of// characters in the given string // Function to find the maximum// repeated frequency of the// characters in the given stringfunction findMaxFrequency(s){ // Hash-Array to store the // frequency of characters var arr = Array(26).fill(0); // Loop to find the frequency // of the characters for (var i = 0; i < s.length; i++) arr[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // Hash map to store the occurrence // of frequencies of characters var hash = new Map(); for (var i = 0; i < 26; i++) if (arr[i] != 0) { if(hash.has(arr[i])) hash.set(arr[i], hash.get(arr[i])+1) else hash.set(arr[i], 1) } // Loop to find the maximum // Repeated frequency from hash-map var max_count = 0, res = -1; hash.forEach((value, key) => { if (max_count < value) { res = key; max_count = value; } }); document.write( "Frequency " + res + " is repeated " + max_count+" times");} // Driver Codevar s = "geeksgeeks"; // Function CallfindMaxFrequency(s); </script>
Frequency 2 is repeated 3 times
Performance Analysis:
Time Complexity: O(N)
Auxiliary Space: O(N)
SHUBHAMSINGH10
sapnasingh4991
29AjayKumar
nidhi_biet
rrrtnx
Algorithms
Competitive Programming
Hash
Strings
Technical Scripter
Write From Home
Hash
Strings
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 154,
"s": 28,
"text": "Given a string S, the task is to find the count of maximum repeated frequency of characters in the given string S.Examples: "
},
{
"code": null,
"e": 624,
"s": 154,
"text": "Input: S = “geeksgeeks” Output: Frequency 2 is repeated 3 times Explanation: Frequency of characters in the given string – {“g”: 2, “e”: 4, “k”: 2, “s”: 2} The frequency 2 is repeated thrice for the characters “g”, “k”, “s”.Input: S = “abcabcdedee” Output: Frequency 2 is repeated 4 times. Explanation: Frequency of characters in the given string – {“a”: 2, “b”: 2, “c”: 2, “d”: 2, “e”: 3} The frequency 2 is repeated four times for the characters “a”, “b”, “c”, “d”. "
},
{
"code": null,
"e": 648,
"s": 626,
"text": "Efficient Approach: "
},
{
"code": null,
"e": 880,
"s": 648,
"text": "The idea is to first store the frequency of characters of the string in an array of size 26. Since all characters of strings are among 26 lowercase English alphabets, we can store the frequency of characters in an array of size 26."
},
{
"code": null,
"e": 1002,
"s": 880,
"text": "Create a hash map, to store the count of frequencies of the characters and return the frequency which occurred max times."
},
{
"code": null,
"e": 1054,
"s": 1002,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1058,
"s": 1054,
"text": "C++"
},
{
"code": null,
"e": 1063,
"s": 1058,
"text": "Java"
},
{
"code": null,
"e": 1071,
"s": 1063,
"text": "Python3"
},
{
"code": null,
"e": 1074,
"s": 1071,
"text": "C#"
},
{
"code": null,
"e": 1085,
"s": 1074,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// maximum repeated frequency of// characters in the given string #include <bits/stdc++.h>using namespace std; // Function to find the maximum// repeated frequency of the// characters in the given stringvoid findMaxFrequency(string s){ // Hash-Array to store the // frequency of characters int arr[26] = { 0 }; // Loop to find the frequency // of the characters for (int i = 0; i < s.length(); i++) arr[s[i] - 'a']++; // Hash map to store the occurrence // of frequencies of characters unordered_map<int, int> hash; for (int i = 0; i < 26; i++) if (arr[i] != 0) hash[arr[i]]++; // Loop to find the maximum // Repeated frequency from hash-map int max_count = 0, res = -1; for (auto i : hash) { if (max_count < i.second) { res = i.first; max_count = i.second; } } cout <<\"Frequency \" << res << \" is repeated \" << max_count<<\" times\";} // Driver Codeint main(){ string s = \"geeksgeeks\"; // Function Call findMaxFrequency(s); return 0;}",
"e": 2201,
"s": 1085,
"text": null
},
{
"code": "// Java implementation to find the// maximum repeated frequency of// characters in the given Stringimport java.util.*; class GFG{ // Function to find the maximum// repeated frequency of the// characters in the given Stringstatic void findMaxFrequency(String s){ // Hash-Array to store the // frequency of characters int arr[] = new int[26]; // Loop to find the frequency // of the characters for (int i = 0; i < s.length(); i++) arr[s.charAt(i) - 'a']++; // Hash map to store the occurrence // of frequencies of characters HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>(); for (int i = 0; i < 26; i++) if (arr[i] != 0) { if(hash.containsKey(arr[i])){ hash.put(arr[i], hash.get(arr[i])+1); } else{ hash.put(arr[i], 1); } } // Loop to find the maximum // Repeated frequency from hash-map int max_count = 0, res = -1; for (Map.Entry<Integer,Integer> i : hash.entrySet()){ if (max_count < i.getValue()) { res = i.getKey(); max_count = i.getValue(); } } System.out.println(\"Frequency \" + res+ \" is repeated \" + max_count+\" times\");} // Driver Codepublic static void main(String[] args){ String s = \"geeksgeeks\"; // Function Call findMaxFrequency(s);}} // This code is contributed by sapnasingh4991",
"e": 3624,
"s": 2201,
"text": null
},
{
"code": "# Python3 implementation to find the# maximum repeated frequency of# characters in the given string # Function to find the maximum# repeated frequency of the# characters in the given stringdef findMaxFrequency(s): # Hash-Array to store the # frequency of characters arr = [0]*26 # Loop to find the frequency # of the characters for i in range(len(s)): arr[ord(s[i]) - ord('a')] += 1 # Hash map to store the occurrence # of frequencies of characters hash = {} for i in range(26): if (arr[i] != 0): if arr[i] not in hash: hash[arr[i]] = 0 hash[arr[i]] += 1 # Loop to find the maximum # Repeated frequency from hash-map max_count = 0 res = -1 for i in hash: if (max_count < hash[i]): res = i max_count = hash[i] print(\"Frequency\", res, \"is repeated\", max_count, \"times\") # Driver Code s = \"geeksgeeks\" # Function CallfindMaxFrequency(s) # This code is contributed by shubhamsingh10",
"e": 4678,
"s": 3624,
"text": null
},
{
"code": "// C# implementation to find the// maximum repeated frequency of// characters in the given Stringusing System;using System.Collections.Generic; class GFG{ // Function to find the maximum// repeated frequency of the// characters in the given Stringstatic void findMaxFrequency(String s){ // Hash-Array to store the // frequency of characters int []arr = new int[26]; // Loop to find the frequency // of the characters for (int i = 0; i < s.Length; i++) arr[s[i] - 'a']++; // Hash map to store the occurrence // of frequencies of characters Dictionary<int,int> hash = new Dictionary<int,int>(); for (int i = 0; i < 26; i++) if (arr[i] != 0) { if(hash.ContainsKey(arr[i])){ hash[arr[i]] = hash[arr[i]]+1; } else{ hash.Add(arr[i], 1); } } // Loop to find the maximum // Repeated frequency from hash-map int max_count = 0, res = -1; foreach( KeyValuePair<int,int> i in hash){ if (max_count < i.Value) { res = i.Key; max_count = i.Value; } } Console.WriteLine(\"Frequency \" + res+ \" is repeated \" + max_count+\" times\");} // Driver Codepublic static void Main(String[] args){ String s = \"geeksgeeks\"; // Function Call findMaxFrequency(s);}} // This code is contributed by 29AjayKumar",
"e": 6079,
"s": 4678,
"text": null
},
{
"code": "<script> // JavaScript implementation to find the// maximum repeated frequency of// characters in the given string // Function to find the maximum// repeated frequency of the// characters in the given stringfunction findMaxFrequency(s){ // Hash-Array to store the // frequency of characters var arr = Array(26).fill(0); // Loop to find the frequency // of the characters for (var i = 0; i < s.length; i++) arr[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // Hash map to store the occurrence // of frequencies of characters var hash = new Map(); for (var i = 0; i < 26; i++) if (arr[i] != 0) { if(hash.has(arr[i])) hash.set(arr[i], hash.get(arr[i])+1) else hash.set(arr[i], 1) } // Loop to find the maximum // Repeated frequency from hash-map var max_count = 0, res = -1; hash.forEach((value, key) => { if (max_count < value) { res = key; max_count = value; } }); document.write( \"Frequency \" + res + \" is repeated \" + max_count+\" times\");} // Driver Codevar s = \"geeksgeeks\"; // Function CallfindMaxFrequency(s); </script>",
"e": 7298,
"s": 6079,
"text": null
},
{
"code": null,
"e": 7330,
"s": 7298,
"text": "Frequency 2 is repeated 3 times"
},
{
"code": null,
"e": 7356,
"s": 7332,
"text": "Performance Analysis: "
},
{
"code": null,
"e": 7378,
"s": 7356,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 7400,
"s": 7378,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 7417,
"s": 7402,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 7432,
"s": 7417,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 7444,
"s": 7432,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7455,
"s": 7444,
"text": "nidhi_biet"
},
{
"code": null,
"e": 7462,
"s": 7455,
"text": "rrrtnx"
},
{
"code": null,
"e": 7473,
"s": 7462,
"text": "Algorithms"
},
{
"code": null,
"e": 7497,
"s": 7473,
"text": "Competitive Programming"
},
{
"code": null,
"e": 7502,
"s": 7497,
"text": "Hash"
},
{
"code": null,
"e": 7510,
"s": 7502,
"text": "Strings"
},
{
"code": null,
"e": 7529,
"s": 7510,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7545,
"s": 7529,
"text": "Write From Home"
},
{
"code": null,
"e": 7550,
"s": 7545,
"text": "Hash"
},
{
"code": null,
"e": 7558,
"s": 7550,
"text": "Strings"
},
{
"code": null,
"e": 7569,
"s": 7558,
"text": "Algorithms"
},
{
"code": null,
"e": 7667,
"s": 7569,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7705,
"s": 7667,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 7773,
"s": 7705,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 7800,
"s": 7773,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 7843,
"s": 7800,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 7910,
"s": 7843,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 7953,
"s": 7910,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 7996,
"s": 7953,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 8037,
"s": 7996,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 8064,
"s": 8037,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Minimum number of Water to Land conversion to make two islands connected in a Grid
|
04 Apr, 2022
Given a 2D grid arr[][] of ‘W’ and ‘L’ where ‘W’ denotes water and ‘L’ denotes land, the task is to find the minimum number of water components ‘W’ that must be changed to land component ‘L’ so that two islands becomes connected.
An island is the set of connected ‘L’s.
Note: There can be only two disjoint islands.
Examples:
Input: arr[][] = {{‘W’, ‘L’}, {‘L’, ‘W’}}; Output: 1 Explanation: For the given set of islands if we change arr[1][1] to ‘W’ then, set of all island are connected. Therefore, the minimum number of ‘W’ must be changed to ‘L’ is 1.
Input: arr[][] = {{‘W’, ‘L’, ‘W’}, {‘W’, ‘W’, ‘W’}, {‘W’, ‘W’, ‘L’}} Output: 2
Approach: This problem can be solved using Floodfill algorithm. Below are the steps:
Use Floodfill algorithm for the first set of the connected islands and make all the islands as visited and store the coordinates in a hash (say hash1).Use Floodfill algorithm for the second set of the connected islands and make all the islands as visited and store the coordinates in a second hash(say hash2).The minimum difference between coordinates stored in both the hash is the required result.
Use Floodfill algorithm for the first set of the connected islands and make all the islands as visited and store the coordinates in a hash (say hash1).
Use Floodfill algorithm for the second set of the connected islands and make all the islands as visited and store the coordinates in a second hash(say hash2).
The minimum difference between coordinates stored in both the hash is the required result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Determine the distance between two// coordinatesint dist(pair<int, int>& p1, pair<int, int>& p2){ return abs(p1.first - p2.first) + abs(p2.second - p1.second) - 1;} // Function to implement floodfill algorithmvoid floodfill(set<pair<int, int> >& hash, int i, int j, vector<vector<char> >& A){ // Base Case if (i < 0 || i >= A.size() || j < 0 || j >= A[0].size() || A[i][j] != 'L') { return; } // Mark the current node visited A[i][j] = 'V'; // Store the coordinates of in the // hash set hash.insert(make_pair(i, j)); // Recursively iterate for the next // four directions floodfill(hash, i - 1, j, A); floodfill(hash, i + 1, j, A); floodfill(hash, i, j - 1, A); floodfill(hash, i, j + 1, A);} // Function to find the minimum 'W' to flippedvoid findMinimumW(vector<vector<char> >& A){ // Base Case if (A.size() == 0) return; // Two sets to store the coordinates of // connected island set<pair<int, int> > hash1, hash2; // Traversing the given grid[][] for (int i = 0; i < A.size(); i++) { for (int j = 0; j < A[0].size(); j++) { // If an island is found if (A[i][j] == 'L') { // Floodfill Algorithm for // the first island if (hash1.empty()) { floodfill(hash1, i, j, A); } // Floodfill Algorithm for // the second island if (hash2.empty() && !hash1.count({ i, j })) { floodfill(hash2, i, j, A); } } } } // To store the minimum count of 'W' int ans = INT_MAX; // Traverse both pairs of hashes for (auto i : hash1) { for (auto j : hash2) { ans = min(ans, dist(i, j)); } } // Print the final answer cout << ans << endl;} // Driver Codeint main(){ // Given grid of land and water vector<vector<char> > arr; arr = { { 'W', 'L' }, { 'L', 'W' } }; // Function Call findMinimumW(arr); return 0;}
// Java program for the above approachimport java.util.*; class GFG { // Determine the distance between two // coordinates static int dist(Pair p1, Pair p2) { return Math.abs(p1.first - p2.first) + Math.abs(p2.second - p1.second) - 1; } // class Pair to represent coordinates // of elements in grid static class Pair { int first; int second; Pair(int f, int s) { this.first = f; this.second = s; } } // Function to implement floodfill algorithm static void floodfill(HashSet<Pair> hash, int i, int j, char[][] A) { // Base Case if (i < 0 || i >= A.length || j < 0 || j >= A[0].length || A[i][j] != 'L') { return; } // Mark the current node visited A[i][j] = 'V'; // Store the coordinates of in the // hash set hash.add(new Pair(i, j)); // Recursively iterate for the next // four directions floodfill(hash, i - 1, j, A); floodfill(hash, i + 1, j, A); floodfill(hash, i, j - 1, A); floodfill(hash, i, j + 1, A); } // Function to find the minimum 'W' to flipped static void findMinimumW(char[][] A) { // Base Case if (A.length == 0) return; // Two sets to store the coordinates of // connected island HashSet<Pair> hash1 = new HashSet<>(); HashSet<Pair> hash2 = new HashSet<>(); // Traversing the given grid[][] for (int i = 0; i < A.length; i++) { for (int j = 0; j < A[0].length; j++) { // If an island is found if (A[i][j] == 'L') { // Floodfill Algorithm for // the first island if (hash1.isEmpty()) { floodfill(hash1, i, j, A); } // Floodfill Algorithm for // the second island if (hash2.isEmpty() && !hash1.contains( new Pair(i, j))) { floodfill(hash2, i, j, A); } } } } // To store the minimum count of 'W' int ans = Integer.MAX_VALUE; // Traverse both pairs of hashes for (Pair i : hash1) { for (Pair j : hash2) { ans = Math.min(ans, dist(i, j)); } } // Print the final answer System.out.println(ans); } // Driver Code public static void main(String[] args) { // Given grid of land and water char[][] arr = { { 'W', 'L' }, { 'L', 'W' } }; // Function Call findMinimumW(arr); }} // This code is contributed by kdeepsingh2002
# Python3 program for the above approachimport sys # Determine the distance between two# coordinatesdef dist(p1, p2): return (abs(p1[0] - p2[0]) + abs(p2[1] - p1[1]) - 1) # Function to implement floodfill algorithmdef floodfill(hash, i, j, A): # Base Case if (i < 0 or i >= len(A) or j < 0 or j >= len(A[0]) or A[i][j] != 'L'): return hash, A # Mark the current node visited A[i][j] = 'V' # Store the coordinates of in the # hash set hash.add((i, j)) # Recursively iterate for the next # four directions hash, A = floodfill(hash, i - 1, j, A) hash, A = floodfill(hash, i + 1, j, A) hash, A = floodfill(hash, i, j - 1, A) hash, A = floodfill(hash, i, j + 1, A) return hash, A # Function to find the minimum 'W' to flippeddef findMinimumW(A): # Base Case if (len(A) == 0): return set(), A # Two sets to store the coordinates of # connected island hash1 = set() hash2 = set() # Traversing the given grid[][] for i in range(len(A)): for j in range(len(A[0])): # If an island is found if (A[i][j] == 'L'): # Floodfill Algorithm for # the first island if (len(hash1) == 0): hash1, A = floodfill(hash1, i, j, A) # Floodfill Algorithm for # the second island if (len(hash2) == 0 and (i, j) not in hash1): hash2, A = floodfill(hash2, i, j, A) # To store the minimum count of 'W' ans = sys.maxsize # Traverse both pairs of hashes for i in hash1: for j in hash2: ans = min(ans, dist(i, j)) # Print the final answer print(ans) # Driver Codeif __name__=='__main__': # Given grid of land and water arr = [] arr = [ [ 'W', 'L' ], [ 'L', 'W' ] ] # Function Call findMinimumW(arr) # This code is contributed by pratham76
// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Determine the distance between two // coordinates static int dist(Pair p1, Pair p2) { return Math.Abs(p1.first - p2.first) + Math.Abs(p2.second - p1.second) - 1; } // class Pair to represent coordinates // of elements in grid class Pair { public int first; public int second; public Pair(int f, int s) { this.first = f; this.second = s; } } // Function to implement floodfill algorithm static void floodfill(HashSet<Pair> hash, int i, int j, char[,] A) { // Base Case if (i < 0 || i >= A.GetLength(0) || j < 0 || j >= A.GetLength(1) || A[i,j] != 'L') { return; } // Mark the current node visited A[i,j] = 'V'; // Store the coordinates of in the // hash set hash.Add(new Pair(i, j)); // Recursively iterate for the next // four directions floodfill(hash, i - 1, j, A); floodfill(hash, i + 1, j, A); floodfill(hash, i, j - 1, A); floodfill(hash, i, j + 1, A); } // Function to find the minimum 'W' to flipped static void findMinimumW(char[,] A) { // Base Case if (A.GetLength(0) == 0) return; // Two sets to store the coordinates of // connected island HashSet<Pair> hash1 = new HashSet<Pair>(); HashSet<Pair> hash2 = new HashSet<Pair>(); // Traversing the given grid[,] for (int i = 0; i < A.GetLength(0); i++) { for (int j = 0; j < A.GetLength(1); j++) { // If an island is found if (A[i,j] == 'L') { // Floodfill Algorithm for // the first island if (hash1.Count==0) { floodfill(hash1, i, j, A); } // Floodfill Algorithm for // the second island if (hash2.Count==0 && !hash1.Contains( new Pair(i, j))) { floodfill(hash2, i, j, A); } } } } // To store the minimum count of 'W' int ans = int.MaxValue; // Traverse both pairs of hashes foreach (Pair i in hash1) { foreach (Pair j in hash2) { ans = Math.Min(ans, dist(i, j)); } } // Print the readonly answer Console.WriteLine(ans); } // Driver Code public static void Main(String[] args) { // Given grid of land and water char[,] arr = { { 'W', 'L' }, { 'L', 'W' } }; // Function Call findMinimumW(arr); }} // This code is contributed by shikhasingrajput
<script> // JavaScript program for the above approach // Determine the distance between two// coordinatesfunction dist(p1,p2){ return Math.abs(p1[0] - p2[0]) + Math.abs(p2[1] - p1[1]) - 1;} // Function to implement floodfill algorithmfunction floodfill(hash,i,j, A){ // Base Case if (i < 0 || i >= A.length || j < 0 || j >= A[0].length || A[i][j] != 'L') { return; } // Mark the current node visited A[i][j] = 'V'; // Store the coordinates of in the // hash set hash.add([i, j]); // Recursively iterate for the next // four directions floodfill(hash, i - 1, j, A); floodfill(hash, i + 1, j, A); floodfill(hash, i, j - 1, A); floodfill(hash, i, j + 1, A);} // Function to find the minimum 'W' to flippedfunction findMinimumW(A){ // Base Case if (A.length == 0) return; // Two sets to store the coordinates of // connected island let hash1 = new Set(), hash2 = new Set(); // Traversing the given grid[][] for (let i = 0; i < A.length; i++) { for (let j = 0; j < A[0].length; j++) { // If an island is found if (A[i][j] == 'L') { // Floodfill Algorithm for // the first island if (hash1.size == 0) { floodfill(hash1, i, j, A); } // Floodfill Algorithm for // the second island if (hash2.size == 0 && !hash1.has([ i, j ])) { floodfill(hash2, i, j, A); } } } } // To store the minimum count of 'W' let ans = Number.MAX_VALUE; // Traverse both pairs of hashes for (let i of hash1) { for (let j of hash2) { ans = Math.min(ans, dist(i, j)); } } // Print the final answer document.write(ans,"</br>");} // Driver Code // Given grid of land and waterlet arr = [ [ 'W', 'L' ], [ 'L', 'W' ] ]; // Function CallfindMinimumW(arr); // This code is contributed by shinjanpatra </script>
1
Time Complexity: O(N4) Auxiliary Space: O(N2)
pratham76
ruhelaa48
pankajsharmagfg
karandeep1234
shikhasingrajput
shinjanpatra
Algorithms
Graph
Hash
Matrix
Hash
Matrix
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Apr, 2022"
},
{
"code": null,
"e": 285,
"s": 54,
"text": "Given a 2D grid arr[][] of ‘W’ and ‘L’ where ‘W’ denotes water and ‘L’ denotes land, the task is to find the minimum number of water components ‘W’ that must be changed to land component ‘L’ so that two islands becomes connected. "
},
{
"code": null,
"e": 326,
"s": 285,
"text": "An island is the set of connected ‘L’s. "
},
{
"code": null,
"e": 372,
"s": 326,
"text": "Note: There can be only two disjoint islands."
},
{
"code": null,
"e": 384,
"s": 372,
"text": "Examples: "
},
{
"code": null,
"e": 614,
"s": 384,
"text": "Input: arr[][] = {{‘W’, ‘L’}, {‘L’, ‘W’}}; Output: 1 Explanation: For the given set of islands if we change arr[1][1] to ‘W’ then, set of all island are connected. Therefore, the minimum number of ‘W’ must be changed to ‘L’ is 1."
},
{
"code": null,
"e": 694,
"s": 614,
"text": "Input: arr[][] = {{‘W’, ‘L’, ‘W’}, {‘W’, ‘W’, ‘W’}, {‘W’, ‘W’, ‘L’}} Output: 2 "
},
{
"code": null,
"e": 781,
"s": 694,
"text": "Approach: This problem can be solved using Floodfill algorithm. Below are the steps: "
},
{
"code": null,
"e": 1181,
"s": 781,
"text": "Use Floodfill algorithm for the first set of the connected islands and make all the islands as visited and store the coordinates in a hash (say hash1).Use Floodfill algorithm for the second set of the connected islands and make all the islands as visited and store the coordinates in a second hash(say hash2).The minimum difference between coordinates stored in both the hash is the required result."
},
{
"code": null,
"e": 1333,
"s": 1181,
"text": "Use Floodfill algorithm for the first set of the connected islands and make all the islands as visited and store the coordinates in a hash (say hash1)."
},
{
"code": null,
"e": 1492,
"s": 1333,
"text": "Use Floodfill algorithm for the second set of the connected islands and make all the islands as visited and store the coordinates in a second hash(say hash2)."
},
{
"code": null,
"e": 1583,
"s": 1492,
"text": "The minimum difference between coordinates stored in both the hash is the required result."
},
{
"code": null,
"e": 1635,
"s": 1583,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1639,
"s": 1635,
"text": "C++"
},
{
"code": null,
"e": 1644,
"s": 1639,
"text": "Java"
},
{
"code": null,
"e": 1652,
"s": 1644,
"text": "Python3"
},
{
"code": null,
"e": 1655,
"s": 1652,
"text": "C#"
},
{
"code": null,
"e": 1666,
"s": 1655,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Determine the distance between two// coordinatesint dist(pair<int, int>& p1, pair<int, int>& p2){ return abs(p1.first - p2.first) + abs(p2.second - p1.second) - 1;} // Function to implement floodfill algorithmvoid floodfill(set<pair<int, int> >& hash, int i, int j, vector<vector<char> >& A){ // Base Case if (i < 0 || i >= A.size() || j < 0 || j >= A[0].size() || A[i][j] != 'L') { return; } // Mark the current node visited A[i][j] = 'V'; // Store the coordinates of in the // hash set hash.insert(make_pair(i, j)); // Recursively iterate for the next // four directions floodfill(hash, i - 1, j, A); floodfill(hash, i + 1, j, A); floodfill(hash, i, j - 1, A); floodfill(hash, i, j + 1, A);} // Function to find the minimum 'W' to flippedvoid findMinimumW(vector<vector<char> >& A){ // Base Case if (A.size() == 0) return; // Two sets to store the coordinates of // connected island set<pair<int, int> > hash1, hash2; // Traversing the given grid[][] for (int i = 0; i < A.size(); i++) { for (int j = 0; j < A[0].size(); j++) { // If an island is found if (A[i][j] == 'L') { // Floodfill Algorithm for // the first island if (hash1.empty()) { floodfill(hash1, i, j, A); } // Floodfill Algorithm for // the second island if (hash2.empty() && !hash1.count({ i, j })) { floodfill(hash2, i, j, A); } } } } // To store the minimum count of 'W' int ans = INT_MAX; // Traverse both pairs of hashes for (auto i : hash1) { for (auto j : hash2) { ans = min(ans, dist(i, j)); } } // Print the final answer cout << ans << endl;} // Driver Codeint main(){ // Given grid of land and water vector<vector<char> > arr; arr = { { 'W', 'L' }, { 'L', 'W' } }; // Function Call findMinimumW(arr); return 0;}",
"e": 3882,
"s": 1666,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG { // Determine the distance between two // coordinates static int dist(Pair p1, Pair p2) { return Math.abs(p1.first - p2.first) + Math.abs(p2.second - p1.second) - 1; } // class Pair to represent coordinates // of elements in grid static class Pair { int first; int second; Pair(int f, int s) { this.first = f; this.second = s; } } // Function to implement floodfill algorithm static void floodfill(HashSet<Pair> hash, int i, int j, char[][] A) { // Base Case if (i < 0 || i >= A.length || j < 0 || j >= A[0].length || A[i][j] != 'L') { return; } // Mark the current node visited A[i][j] = 'V'; // Store the coordinates of in the // hash set hash.add(new Pair(i, j)); // Recursively iterate for the next // four directions floodfill(hash, i - 1, j, A); floodfill(hash, i + 1, j, A); floodfill(hash, i, j - 1, A); floodfill(hash, i, j + 1, A); } // Function to find the minimum 'W' to flipped static void findMinimumW(char[][] A) { // Base Case if (A.length == 0) return; // Two sets to store the coordinates of // connected island HashSet<Pair> hash1 = new HashSet<>(); HashSet<Pair> hash2 = new HashSet<>(); // Traversing the given grid[][] for (int i = 0; i < A.length; i++) { for (int j = 0; j < A[0].length; j++) { // If an island is found if (A[i][j] == 'L') { // Floodfill Algorithm for // the first island if (hash1.isEmpty()) { floodfill(hash1, i, j, A); } // Floodfill Algorithm for // the second island if (hash2.isEmpty() && !hash1.contains( new Pair(i, j))) { floodfill(hash2, i, j, A); } } } } // To store the minimum count of 'W' int ans = Integer.MAX_VALUE; // Traverse both pairs of hashes for (Pair i : hash1) { for (Pair j : hash2) { ans = Math.min(ans, dist(i, j)); } } // Print the final answer System.out.println(ans); } // Driver Code public static void main(String[] args) { // Given grid of land and water char[][] arr = { { 'W', 'L' }, { 'L', 'W' } }; // Function Call findMinimumW(arr); }} // This code is contributed by kdeepsingh2002",
"e": 6297,
"s": 3882,
"text": null
},
{
"code": "# Python3 program for the above approachimport sys # Determine the distance between two# coordinatesdef dist(p1, p2): return (abs(p1[0] - p2[0]) + abs(p2[1] - p1[1]) - 1) # Function to implement floodfill algorithmdef floodfill(hash, i, j, A): # Base Case if (i < 0 or i >= len(A) or j < 0 or j >= len(A[0]) or A[i][j] != 'L'): return hash, A # Mark the current node visited A[i][j] = 'V' # Store the coordinates of in the # hash set hash.add((i, j)) # Recursively iterate for the next # four directions hash, A = floodfill(hash, i - 1, j, A) hash, A = floodfill(hash, i + 1, j, A) hash, A = floodfill(hash, i, j - 1, A) hash, A = floodfill(hash, i, j + 1, A) return hash, A # Function to find the minimum 'W' to flippeddef findMinimumW(A): # Base Case if (len(A) == 0): return set(), A # Two sets to store the coordinates of # connected island hash1 = set() hash2 = set() # Traversing the given grid[][] for i in range(len(A)): for j in range(len(A[0])): # If an island is found if (A[i][j] == 'L'): # Floodfill Algorithm for # the first island if (len(hash1) == 0): hash1, A = floodfill(hash1, i, j, A) # Floodfill Algorithm for # the second island if (len(hash2) == 0 and (i, j) not in hash1): hash2, A = floodfill(hash2, i, j, A) # To store the minimum count of 'W' ans = sys.maxsize # Traverse both pairs of hashes for i in hash1: for j in hash2: ans = min(ans, dist(i, j)) # Print the final answer print(ans) # Driver Codeif __name__=='__main__': # Given grid of land and water arr = [] arr = [ [ 'W', 'L' ], [ 'L', 'W' ] ] # Function Call findMinimumW(arr) # This code is contributed by pratham76",
"e": 8368,
"s": 6297,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Determine the distance between two // coordinates static int dist(Pair p1, Pair p2) { return Math.Abs(p1.first - p2.first) + Math.Abs(p2.second - p1.second) - 1; } // class Pair to represent coordinates // of elements in grid class Pair { public int first; public int second; public Pair(int f, int s) { this.first = f; this.second = s; } } // Function to implement floodfill algorithm static void floodfill(HashSet<Pair> hash, int i, int j, char[,] A) { // Base Case if (i < 0 || i >= A.GetLength(0) || j < 0 || j >= A.GetLength(1) || A[i,j] != 'L') { return; } // Mark the current node visited A[i,j] = 'V'; // Store the coordinates of in the // hash set hash.Add(new Pair(i, j)); // Recursively iterate for the next // four directions floodfill(hash, i - 1, j, A); floodfill(hash, i + 1, j, A); floodfill(hash, i, j - 1, A); floodfill(hash, i, j + 1, A); } // Function to find the minimum 'W' to flipped static void findMinimumW(char[,] A) { // Base Case if (A.GetLength(0) == 0) return; // Two sets to store the coordinates of // connected island HashSet<Pair> hash1 = new HashSet<Pair>(); HashSet<Pair> hash2 = new HashSet<Pair>(); // Traversing the given grid[,] for (int i = 0; i < A.GetLength(0); i++) { for (int j = 0; j < A.GetLength(1); j++) { // If an island is found if (A[i,j] == 'L') { // Floodfill Algorithm for // the first island if (hash1.Count==0) { floodfill(hash1, i, j, A); } // Floodfill Algorithm for // the second island if (hash2.Count==0 && !hash1.Contains( new Pair(i, j))) { floodfill(hash2, i, j, A); } } } } // To store the minimum count of 'W' int ans = int.MaxValue; // Traverse both pairs of hashes foreach (Pair i in hash1) { foreach (Pair j in hash2) { ans = Math.Min(ans, dist(i, j)); } } // Print the readonly answer Console.WriteLine(ans); } // Driver Code public static void Main(String[] args) { // Given grid of land and water char[,] arr = { { 'W', 'L' }, { 'L', 'W' } }; // Function Call findMinimumW(arr); }} // This code is contributed by shikhasingrajput",
"e": 10862,
"s": 8368,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Determine the distance between two// coordinatesfunction dist(p1,p2){ return Math.abs(p1[0] - p2[0]) + Math.abs(p2[1] - p1[1]) - 1;} // Function to implement floodfill algorithmfunction floodfill(hash,i,j, A){ // Base Case if (i < 0 || i >= A.length || j < 0 || j >= A[0].length || A[i][j] != 'L') { return; } // Mark the current node visited A[i][j] = 'V'; // Store the coordinates of in the // hash set hash.add([i, j]); // Recursively iterate for the next // four directions floodfill(hash, i - 1, j, A); floodfill(hash, i + 1, j, A); floodfill(hash, i, j - 1, A); floodfill(hash, i, j + 1, A);} // Function to find the minimum 'W' to flippedfunction findMinimumW(A){ // Base Case if (A.length == 0) return; // Two sets to store the coordinates of // connected island let hash1 = new Set(), hash2 = new Set(); // Traversing the given grid[][] for (let i = 0; i < A.length; i++) { for (let j = 0; j < A[0].length; j++) { // If an island is found if (A[i][j] == 'L') { // Floodfill Algorithm for // the first island if (hash1.size == 0) { floodfill(hash1, i, j, A); } // Floodfill Algorithm for // the second island if (hash2.size == 0 && !hash1.has([ i, j ])) { floodfill(hash2, i, j, A); } } } } // To store the minimum count of 'W' let ans = Number.MAX_VALUE; // Traverse both pairs of hashes for (let i of hash1) { for (let j of hash2) { ans = Math.min(ans, dist(i, j)); } } // Print the final answer document.write(ans,\"</br>\");} // Driver Code // Given grid of land and waterlet arr = [ [ 'W', 'L' ], [ 'L', 'W' ] ]; // Function CallfindMinimumW(arr); // This code is contributed by shinjanpatra </script>",
"e": 12899,
"s": 10862,
"text": null
},
{
"code": null,
"e": 12901,
"s": 12899,
"text": "1"
},
{
"code": null,
"e": 12950,
"s": 12903,
"text": "Time Complexity: O(N4) Auxiliary Space: O(N2) "
},
{
"code": null,
"e": 12960,
"s": 12950,
"text": "pratham76"
},
{
"code": null,
"e": 12970,
"s": 12960,
"text": "ruhelaa48"
},
{
"code": null,
"e": 12986,
"s": 12970,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 13000,
"s": 12986,
"text": "karandeep1234"
},
{
"code": null,
"e": 13017,
"s": 13000,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 13030,
"s": 13017,
"text": "shinjanpatra"
},
{
"code": null,
"e": 13041,
"s": 13030,
"text": "Algorithms"
},
{
"code": null,
"e": 13047,
"s": 13041,
"text": "Graph"
},
{
"code": null,
"e": 13052,
"s": 13047,
"text": "Hash"
},
{
"code": null,
"e": 13059,
"s": 13052,
"text": "Matrix"
},
{
"code": null,
"e": 13064,
"s": 13059,
"text": "Hash"
},
{
"code": null,
"e": 13071,
"s": 13064,
"text": "Matrix"
},
{
"code": null,
"e": 13077,
"s": 13071,
"text": "Graph"
},
{
"code": null,
"e": 13088,
"s": 13077,
"text": "Algorithms"
}
] |
How to create an HTML checkbox with a clickable label?
|
10 Apr, 2019
To make an HTML checkbox with a clickable label means the checkbox gets on/off when the label is clicked.
Below are the methods:
Using checkbox inside label tag:<!DOCTYPE html><html> <head> <title> Create an HTML checkbox with a clickable label </title> <!-- Adding Style to label --> <style> .GFG { background-color: white; border: 2px solid black; color: green; padding: 5px 10px; text-align: center; display: inline-block; font-size: 20px; margin: 10px 10px; cursor: pointer; } </style></head> <body> <h1> GeeksforGeeks </h1> <!-- Putting checkbox inside label tag --> <label class="GFG"> <input type="checkbox" name="checkbox" value="Geeks"> GFG </label></body> </html>Output:Before clicking the label:After clicking the label:
<!DOCTYPE html><html> <head> <title> Create an HTML checkbox with a clickable label </title> <!-- Adding Style to label --> <style> .GFG { background-color: white; border: 2px solid black; color: green; padding: 5px 10px; text-align: center; display: inline-block; font-size: 20px; margin: 10px 10px; cursor: pointer; } </style></head> <body> <h1> GeeksforGeeks </h1> <!-- Putting checkbox inside label tag --> <label class="GFG"> <input type="checkbox" name="checkbox" value="Geeks"> GFG </label></body> </html>
Output:Before clicking the label:
After clicking the label:
Using the for attribute: Create a checkbox using input tag then create a label for the created checkbox using the for attribute.<!DOCTYPE html><html> <head> <title> Create an HTML checkbox with a clickable label </title> <!-- Adding Style to label --> <style> .GFG { background-color: white; border: 2px solid black; color: green; padding: 5px 10px; text-align: center; display: inline-block; font-size: 20px; margin: 10px 10px; cursor: pointer; } </style></head> <body> <h1>GeeksforGeeks</h1> <!-- Using the for attribute in label --> <input type="checkbox" name="checkbox" id="checkID" value="Geeks"> <label class="GFG" for="checkID"> GFG </label></body> </html>Output:Before clicking the label:After clicking the label:
<!DOCTYPE html><html> <head> <title> Create an HTML checkbox with a clickable label </title> <!-- Adding Style to label --> <style> .GFG { background-color: white; border: 2px solid black; color: green; padding: 5px 10px; text-align: center; display: inline-block; font-size: 20px; margin: 10px 10px; cursor: pointer; } </style></head> <body> <h1>GeeksforGeeks</h1> <!-- Using the for attribute in label --> <input type="checkbox" name="checkbox" id="checkID" value="Geeks"> <label class="GFG" for="checkID"> GFG </label></body> </html>
Output:Before clicking the label:
After clicking the label:
HTML-Misc
Picked
HTML
Web Technologies
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 ?
Types of CSS (Cascading Style Sheet)
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
How do you run JavaScript script through the Terminal?
Node.js fs.readFileSync() Method
How to set space between the flexbox ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Apr, 2019"
},
{
"code": null,
"e": 134,
"s": 28,
"text": "To make an HTML checkbox with a clickable label means the checkbox gets on/off when the label is clicked."
},
{
"code": null,
"e": 157,
"s": 134,
"text": "Below are the methods:"
},
{
"code": null,
"e": 960,
"s": 157,
"text": "Using checkbox inside label tag:<!DOCTYPE html><html> <head> <title> Create an HTML checkbox with a clickable label </title> <!-- Adding Style to label --> <style> .GFG { background-color: white; border: 2px solid black; color: green; padding: 5px 10px; text-align: center; display: inline-block; font-size: 20px; margin: 10px 10px; cursor: pointer; } </style></head> <body> <h1> GeeksforGeeks </h1> <!-- Putting checkbox inside label tag --> <label class=\"GFG\"> <input type=\"checkbox\" name=\"checkbox\" value=\"Geeks\"> GFG </label></body> </html>Output:Before clicking the label:After clicking the label:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Create an HTML checkbox with a clickable label </title> <!-- Adding Style to label --> <style> .GFG { background-color: white; border: 2px solid black; color: green; padding: 5px 10px; text-align: center; display: inline-block; font-size: 20px; margin: 10px 10px; cursor: pointer; } </style></head> <body> <h1> GeeksforGeeks </h1> <!-- Putting checkbox inside label tag --> <label class=\"GFG\"> <input type=\"checkbox\" name=\"checkbox\" value=\"Geeks\"> GFG </label></body> </html>",
"e": 1673,
"s": 960,
"text": null
},
{
"code": null,
"e": 1707,
"s": 1673,
"text": "Output:Before clicking the label:"
},
{
"code": null,
"e": 1733,
"s": 1707,
"text": "After clicking the label:"
},
{
"code": null,
"e": 2663,
"s": 1733,
"text": "Using the for attribute: Create a checkbox using input tag then create a label for the created checkbox using the for attribute.<!DOCTYPE html><html> <head> <title> Create an HTML checkbox with a clickable label </title> <!-- Adding Style to label --> <style> .GFG { background-color: white; border: 2px solid black; color: green; padding: 5px 10px; text-align: center; display: inline-block; font-size: 20px; margin: 10px 10px; cursor: pointer; } </style></head> <body> <h1>GeeksforGeeks</h1> <!-- Using the for attribute in label --> <input type=\"checkbox\" name=\"checkbox\" id=\"checkID\" value=\"Geeks\"> <label class=\"GFG\" for=\"checkID\"> GFG </label></body> </html>Output:Before clicking the label:After clicking the label:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Create an HTML checkbox with a clickable label </title> <!-- Adding Style to label --> <style> .GFG { background-color: white; border: 2px solid black; color: green; padding: 5px 10px; text-align: center; display: inline-block; font-size: 20px; margin: 10px 10px; cursor: pointer; } </style></head> <body> <h1>GeeksforGeeks</h1> <!-- Using the for attribute in label --> <input type=\"checkbox\" name=\"checkbox\" id=\"checkID\" value=\"Geeks\"> <label class=\"GFG\" for=\"checkID\"> GFG </label></body> </html>",
"e": 3407,
"s": 2663,
"text": null
},
{
"code": null,
"e": 3441,
"s": 3407,
"text": "Output:Before clicking the label:"
},
{
"code": null,
"e": 3467,
"s": 3441,
"text": "After clicking the label:"
},
{
"code": null,
"e": 3477,
"s": 3467,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3484,
"s": 3477,
"text": "Picked"
},
{
"code": null,
"e": 3489,
"s": 3484,
"text": "HTML"
},
{
"code": null,
"e": 3506,
"s": 3489,
"text": "Web Technologies"
},
{
"code": null,
"e": 3511,
"s": 3506,
"text": "HTML"
},
{
"code": null,
"e": 3609,
"s": 3511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3657,
"s": 3609,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3694,
"s": 3657,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3755,
"s": 3694,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 3779,
"s": 3755,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3829,
"s": 3779,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 3862,
"s": 3829,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3920,
"s": 3862,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 3975,
"s": 3920,
"text": "How do you run JavaScript script through the Terminal?"
},
{
"code": null,
"e": 4008,
"s": 3975,
"text": "Node.js fs.readFileSync() Method"
}
] |
SQL query to find unique column values from table
|
13 Aug, 2020
We take a sample table named Geeks and return unique column values by applying various SQL queries on it.
SQL query to find unique values of column department from Geeks table.
Select distinct DEPARTMENT
from Geeks;
Output –
SQL query to find details of column department where name as “DBA”.
Select *
from Geeks
where DEPARTMENT like 'DBA%';
Output –
SQL query to find the count of rows in the department ‘Admin’.
SELECT COUNT(*)
FROM Geeks
WHERE DEPARTMENT = 'Admin';
Output –
DBMS-SQL
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
Difference between OLAP and OLTP in DBMS
OLAP Guidelines (Codd's Rule)
What is Temporary Table in SQL?
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Aug, 2020"
},
{
"code": null,
"e": 134,
"s": 28,
"text": "We take a sample table named Geeks and return unique column values by applying various SQL queries on it."
},
{
"code": null,
"e": 205,
"s": 134,
"text": "SQL query to find unique values of column department from Geeks table."
},
{
"code": null,
"e": 245,
"s": 205,
"text": "Select distinct DEPARTMENT \nfrom Geeks;"
},
{
"code": null,
"e": 254,
"s": 245,
"text": "Output –"
},
{
"code": null,
"e": 322,
"s": 254,
"text": "SQL query to find details of column department where name as “DBA”."
},
{
"code": null,
"e": 374,
"s": 322,
"text": "Select * \nfrom Geeks \nwhere DEPARTMENT like 'DBA%';"
},
{
"code": null,
"e": 383,
"s": 374,
"text": "Output –"
},
{
"code": null,
"e": 446,
"s": 383,
"text": "SQL query to find the count of rows in the department ‘Admin’."
},
{
"code": null,
"e": 503,
"s": 446,
"text": "SELECT COUNT(*) \nFROM Geeks \nWHERE DEPARTMENT = 'Admin';"
},
{
"code": null,
"e": 512,
"s": 503,
"text": "Output –"
},
{
"code": null,
"e": 521,
"s": 512,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 526,
"s": 521,
"text": "DBMS"
},
{
"code": null,
"e": 530,
"s": 526,
"text": "SQL"
},
{
"code": null,
"e": 535,
"s": 530,
"text": "DBMS"
},
{
"code": null,
"e": 539,
"s": 535,
"text": "SQL"
},
{
"code": null,
"e": 637,
"s": 539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 678,
"s": 637,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 715,
"s": 678,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 756,
"s": 715,
"text": "Difference between OLAP and OLTP in DBMS"
},
{
"code": null,
"e": 786,
"s": 756,
"text": "OLAP Guidelines (Codd's Rule)"
},
{
"code": null,
"e": 818,
"s": 786,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 860,
"s": 818,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 904,
"s": 860,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 925,
"s": 904,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 991,
"s": 925,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
}
] |
Tuples in C++
|
26 Jun, 2020
What is a tuple?A tuple is an object that can hold a number of elements. The elements can be of different data types. The elements of tuples are initialized as arguments in order in which they will be accessed.
Operations on tuple :-
1. get() :- get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element.
2. make_tuple() :- make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in tuple.
// C++ code to demonstrate tuple, get() and make_pair()#include<iostream>#include<tuple> // for tupleusing namespace std;int main(){ // Declaring tuple tuple <char, int, float> geek; // Assigning values to tuple using make_tuple() geek = make_tuple('a', 10, 15.5); // Printing initial tuple values using get() cout << "The initial values of tuple are : "; cout << get<0>(geek) << " " << get<1>(geek); cout << " " << get<2>(geek) << endl; // Use of get() to change values of tuple get<0>(geek) = 'b'; get<2>(geek) = 20.5; // Printing modified tuple values cout << "The modified values of tuple are : "; cout << get<0>(geek) << " " << get<1>(geek); cout << " " << get<2>(geek) << endl; return 0;}
Output:
The initial values of tuple are : a 10 15.5
The modified values of tuple are : b 10 20.5
In the above code, get() modifies the 1st nd 3rd value of tuple.
3. tuple_size :- It returns the number of elements present in the tuple.
//C++ code to demonstrate tuple_size#include<iostream>#include<tuple> // for tuple_size and tupleusing namespace std;int main(){ // Initializing tuple tuple <char,int,float> geek(20,'g',17.5); // Use of size to find tuple_size of tuple cout << "The size of tuple is : "; cout << tuple_size<decltype(geek)>::value << endl; return 0; }
Output:
The size of tuple is : 3
4. swap() :- The swap(), swaps the elements of the two different tuples.
//C++ code to demonstrate swap()#include<iostream>#include<tuple> // for swap() and tupleusing namespace std;int main(){ // Initializing 1st tuple tuple <int,char,float> tup1(20,'g',17.5); // Initializing 2nd tuple tuple <int,char,float> tup2(10,'f',15.5); // Printing 1st and 2nd tuple before swapping cout << "The first tuple elements before swapping are : "; cout << get<0>(tup1) << " " << get<1>(tup1) << " " << get<2>(tup1) << endl; cout << "The second tuple elements before swapping are : "; cout << get<0>(tup2) << " " << get<1>(tup2) << " " << get<2>(tup2) << endl; // Swapping tup1 values with tup2 tup1.swap(tup2); // Printing 1st and 2nd tuple after swapping cout << "The first tuple elements after swapping are : "; cout << get<0>(tup1) << " " << get<1>(tup1) << " " << get<2>(tup1) << endl; cout << "The second tuple elements after swapping are : "; cout << get<0>(tup2) << " " << get<1>(tup2) << " " << get<2>(tup2) << endl; return 0;}
Output:
The first tuple elements before swapping are : 20 g 17.5
The second tuple elements before swapping are : 10 f 15.5
The first tuple elements after swapping are : 10 f 15.5
The second tuple elements after swapping are : 20 g 17.5
5. tie() :- The work of tie() is to unpack the tuple values into separate variables. There are two variants of tie(), with and without “ignore” , the “ignore” ignores a particular tuple element and stops it from getting unpacked.
// C++ code to demonstrate working of tie()#include<iostream>#include<tuple> // for tie() and tupleusing namespace std;int main(){ // Initializing variables for unpacking int i_val; char ch_val; float f_val; // Initializing tuple tuple <int,char,float> tup1(20,'g',17.5); // Use of tie() without ignore tie(i_val,ch_val,f_val) = tup1; // Displaying unpacked tuple elements // without ignore cout << "The unpacked tuple values (without ignore) are : "; cout << i_val << " " << ch_val << " " << f_val; cout << endl; // Use of tie() with ignore // ignores char value tie(i_val,ignore,f_val) = tup1; // Displaying unpacked tuple elements // with ignore cout << "The unpacked tuple values (with ignore) are : "; cout << i_val << " " << f_val; cout << endl; return 0; }
Output:
The unpacked tuple values (without ignore) are : 20 g 17.5
The unpacked tuple values (with ignore) are : 20 17.5
6. tuple_cat() :- This function concatenates two tuples and returns a new tuple.
// C++ code to demonstrate working of tuple_cat()#include<iostream>#include<tuple> // for tuple_cat() and tupleusing namespace std;int main(){ // Initializing 1st tuple tuple <int,char,float> tup1(20,'g',17.5); // Initializing 2nd tuple tuple <int,char,float> tup2(30,'f',10.5); // Concatenating 2 tuples to return a new tuple auto tup3 = tuple_cat(tup1,tup2); // Displaying new tuple elements cout << "The new tuple elements in order are : "; cout << get<0>(tup3) << " " << get<1>(tup3) << " "; cout << get<2>(tup3) << " " << get<3>(tup3) << " "; cout << get<4>(tup3) << " " << get<5>(tup3) << endl; return 0;}
Output:
The new tuple elements in order are : 20 g 17.5 30 f 10.5
This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nidhi_biet
CPP-Library
cpp-tuple
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
unordered_map in C++ STL
Inheritance in C++
vector erase() and clear() in C++
The C++ Standard Template Library (STL)
C++ Classes and Objects
Substring in C++
Object Oriented Programming in C++
Priority Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Jun, 2020"
},
{
"code": null,
"e": 263,
"s": 52,
"text": "What is a tuple?A tuple is an object that can hold a number of elements. The elements can be of different data types. The elements of tuples are initialized as arguments in order in which they will be accessed."
},
{
"code": null,
"e": 286,
"s": 263,
"text": "Operations on tuple :-"
},
{
"code": null,
"e": 443,
"s": 286,
"text": "1. get() :- get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element."
},
{
"code": null,
"e": 584,
"s": 443,
"text": "2. make_tuple() :- make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in tuple."
},
{
"code": "// C++ code to demonstrate tuple, get() and make_pair()#include<iostream>#include<tuple> // for tupleusing namespace std;int main(){ // Declaring tuple tuple <char, int, float> geek; // Assigning values to tuple using make_tuple() geek = make_tuple('a', 10, 15.5); // Printing initial tuple values using get() cout << \"The initial values of tuple are : \"; cout << get<0>(geek) << \" \" << get<1>(geek); cout << \" \" << get<2>(geek) << endl; // Use of get() to change values of tuple get<0>(geek) = 'b'; get<2>(geek) = 20.5; // Printing modified tuple values cout << \"The modified values of tuple are : \"; cout << get<0>(geek) << \" \" << get<1>(geek); cout << \" \" << get<2>(geek) << endl; return 0;}",
"e": 1339,
"s": 584,
"text": null
},
{
"code": null,
"e": 1347,
"s": 1339,
"text": "Output:"
},
{
"code": null,
"e": 1437,
"s": 1347,
"text": "The initial values of tuple are : a 10 15.5\nThe modified values of tuple are : b 10 20.5\n"
},
{
"code": null,
"e": 1502,
"s": 1437,
"text": "In the above code, get() modifies the 1st nd 3rd value of tuple."
},
{
"code": null,
"e": 1575,
"s": 1502,
"text": "3. tuple_size :- It returns the number of elements present in the tuple."
},
{
"code": "//C++ code to demonstrate tuple_size#include<iostream>#include<tuple> // for tuple_size and tupleusing namespace std;int main(){ // Initializing tuple tuple <char,int,float> geek(20,'g',17.5); // Use of size to find tuple_size of tuple cout << \"The size of tuple is : \"; cout << tuple_size<decltype(geek)>::value << endl; return 0; }",
"e": 1934,
"s": 1575,
"text": null
},
{
"code": null,
"e": 1942,
"s": 1934,
"text": "Output:"
},
{
"code": null,
"e": 1968,
"s": 1942,
"text": "The size of tuple is : 3\n"
},
{
"code": null,
"e": 2041,
"s": 1968,
"text": "4. swap() :- The swap(), swaps the elements of the two different tuples."
},
{
"code": "//C++ code to demonstrate swap()#include<iostream>#include<tuple> // for swap() and tupleusing namespace std;int main(){ // Initializing 1st tuple tuple <int,char,float> tup1(20,'g',17.5); // Initializing 2nd tuple tuple <int,char,float> tup2(10,'f',15.5); // Printing 1st and 2nd tuple before swapping cout << \"The first tuple elements before swapping are : \"; cout << get<0>(tup1) << \" \" << get<1>(tup1) << \" \" << get<2>(tup1) << endl; cout << \"The second tuple elements before swapping are : \"; cout << get<0>(tup2) << \" \" << get<1>(tup2) << \" \" << get<2>(tup2) << endl; // Swapping tup1 values with tup2 tup1.swap(tup2); // Printing 1st and 2nd tuple after swapping cout << \"The first tuple elements after swapping are : \"; cout << get<0>(tup1) << \" \" << get<1>(tup1) << \" \" << get<2>(tup1) << endl; cout << \"The second tuple elements after swapping are : \"; cout << get<0>(tup2) << \" \" << get<1>(tup2) << \" \" << get<2>(tup2) << endl; return 0;}",
"e": 3109,
"s": 2041,
"text": null
},
{
"code": null,
"e": 3117,
"s": 3109,
"text": "Output:"
},
{
"code": null,
"e": 3346,
"s": 3117,
"text": "The first tuple elements before swapping are : 20 g 17.5\nThe second tuple elements before swapping are : 10 f 15.5\nThe first tuple elements after swapping are : 10 f 15.5\nThe second tuple elements after swapping are : 20 g 17.5\n"
},
{
"code": null,
"e": 3576,
"s": 3346,
"text": "5. tie() :- The work of tie() is to unpack the tuple values into separate variables. There are two variants of tie(), with and without “ignore” , the “ignore” ignores a particular tuple element and stops it from getting unpacked."
},
{
"code": "// C++ code to demonstrate working of tie()#include<iostream>#include<tuple> // for tie() and tupleusing namespace std;int main(){ // Initializing variables for unpacking int i_val; char ch_val; float f_val; // Initializing tuple tuple <int,char,float> tup1(20,'g',17.5); // Use of tie() without ignore tie(i_val,ch_val,f_val) = tup1; // Displaying unpacked tuple elements // without ignore cout << \"The unpacked tuple values (without ignore) are : \"; cout << i_val << \" \" << ch_val << \" \" << f_val; cout << endl; // Use of tie() with ignore // ignores char value tie(i_val,ignore,f_val) = tup1; // Displaying unpacked tuple elements // with ignore cout << \"The unpacked tuple values (with ignore) are : \"; cout << i_val << \" \" << f_val; cout << endl; return 0; }",
"e": 4442,
"s": 3576,
"text": null
},
{
"code": null,
"e": 4450,
"s": 4442,
"text": "Output:"
},
{
"code": null,
"e": 4564,
"s": 4450,
"text": "The unpacked tuple values (without ignore) are : 20 g 17.5\nThe unpacked tuple values (with ignore) are : 20 17.5\n"
},
{
"code": null,
"e": 4645,
"s": 4564,
"text": "6. tuple_cat() :- This function concatenates two tuples and returns a new tuple."
},
{
"code": "// C++ code to demonstrate working of tuple_cat()#include<iostream>#include<tuple> // for tuple_cat() and tupleusing namespace std;int main(){ // Initializing 1st tuple tuple <int,char,float> tup1(20,'g',17.5); // Initializing 2nd tuple tuple <int,char,float> tup2(30,'f',10.5); // Concatenating 2 tuples to return a new tuple auto tup3 = tuple_cat(tup1,tup2); // Displaying new tuple elements cout << \"The new tuple elements in order are : \"; cout << get<0>(tup3) << \" \" << get<1>(tup3) << \" \"; cout << get<2>(tup3) << \" \" << get<3>(tup3) << \" \"; cout << get<4>(tup3) << \" \" << get<5>(tup3) << endl; return 0;}",
"e": 5309,
"s": 4645,
"text": null
},
{
"code": null,
"e": 5317,
"s": 5309,
"text": "Output:"
},
{
"code": null,
"e": 5376,
"s": 5317,
"text": "The new tuple elements in order are : 20 g 17.5 30 f 10.5\n"
},
{
"code": null,
"e": 5677,
"s": 5376,
"text": "This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5802,
"s": 5677,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5813,
"s": 5802,
"text": "nidhi_biet"
},
{
"code": null,
"e": 5825,
"s": 5813,
"text": "CPP-Library"
},
{
"code": null,
"e": 5835,
"s": 5825,
"text": "cpp-tuple"
},
{
"code": null,
"e": 5839,
"s": 5835,
"text": "STL"
},
{
"code": null,
"e": 5843,
"s": 5839,
"text": "C++"
},
{
"code": null,
"e": 5847,
"s": 5843,
"text": "STL"
},
{
"code": null,
"e": 5851,
"s": 5847,
"text": "CPP"
},
{
"code": null,
"e": 5949,
"s": 5851,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5976,
"s": 5949,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 6019,
"s": 5976,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6044,
"s": 6019,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 6063,
"s": 6044,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 6097,
"s": 6063,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 6137,
"s": 6097,
"text": "The C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 6161,
"s": 6137,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 6178,
"s": 6161,
"text": "Substring in C++"
},
{
"code": null,
"e": 6213,
"s": 6178,
"text": "Object Oriented Programming in C++"
}
] |
Boolean Indexing in Pandas - GeeksforGeeks
|
21 Oct, 2021
In boolean indexing, we will select subsets of data based on the actual values of the data in the DataFrame and not on their row/column labels or integer locations. In boolean indexing, we use a boolean vector to filter the data.
Boolean indexing is a type of indexing which uses actual values of the data in the DataFrame. In boolean indexing, we can filter a data in four ways –
Accessing a DataFrame with a boolean index
Applying a boolean mask to a dataframe
Masking data based on column value
Masking data based on an index value
Accessing a DataFrame with a boolean index : In order to access a dataframe with a boolean index, we have to create a dataframe in which the index of dataframe contains a boolean value that is “True” or “False”. For Example
Python3
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["MBA", "BCA", "M.Tech", "MBA"], 'score':[90, 40, 80, 98]} df = pd.DataFrame(dict, index = [True, False, True, False]) print(df)
Output:
Now we have created a dataframe with the boolean index after that user can access a dataframe with the help of the boolean index. User can access a dataframe using three functions that is .loc[], .iloc[], .ix[]
In order to access a dataframe with a boolean index using .loc[], we simply pass a boolean value (True or False) in a .loc[] function.
Python3
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["MBA", "BCA", "M.Tech", "MBA"], 'score':[90, 40, 80, 98]} # creating a dataframe with boolean indexdf = pd.DataFrame(dict, index = [True, False, True, False]) # accessing a dataframe using .loc[] functionprint(df.loc[True])
Output:
In order to access a dataframe using .iloc[], we have to pass a boolean value (True or False) but iloc[] function accept only integer as an argument so it will throw an error so we can only access a dataframe when we pass an integer in iloc[] function Code #1:
Python3
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["MBA", "BCA", "M.Tech", "MBA"], 'score':[90, 40, 80, 98]} # creating a dataframe with boolean index df = pd.DataFrame(dict, index = [True, False, True, False]) # accessing a dataframe using .iloc[] functionprint(df.iloc[True])
Output:
TypeError
Code #2:
Python3
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["MBA", "BCA", "M.Tech", "MBA"], 'score':[90, 40, 80, 98]} # creating a dataframe with boolean index df = pd.DataFrame(dict, index = [True, False, True, False]) # accessing a dataframe using .iloc[] functionprint(df.iloc[1])
Output:
In order to access a dataframe using .ix[], we have to pass boolean value (True or False) and integer value to .ix[] function because as we know that .ix[] function is a hybrid of .loc[] and .iloc[] function. Code #1:
Python3
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["MBA", "BCA", "M.Tech", "MBA"], 'score':[90, 40, 80, 98]} # creating a dataframe with boolean indexdf = pd.DataFrame(dict, index = [True, False, True, False]) # accessing a dataframe using .ix[] functionprint(df.ix[True])
Output:
Code #2:
Python
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["MBA", "BCA", "M.Tech", "MBA"], 'score':[90, 40, 80, 98]} # creating a dataframe with boolean indexdf = pd.DataFrame(dict, index = [True, False, True, False]) # accessing a dataframe using .ix[] functionprint(df.ix[1])
Output:
Applying a boolean mask to a dataframe : In a dataframe we can apply a boolean mask in order to do that we, can use __getitems__ or [] accessor. We can apply a boolean mask by giving a list of True and False of the same length as contain in a dataframe. When we apply a boolean mask it will print only that dataframe in which we pass a boolean value True. To download “nba1.1” CSV file click here.Code #1:
Python3
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["MBA", "BCA", "M.Tech", "MBA"], 'score':[90, 40, 80, 98]} df = pd.DataFrame(dict, index = [0, 1, 2, 3]) print(df[[True, False, True, False]])
Output:
Code #2:
Python3
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba1.1.csv") df = pd.DataFrame(data, index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) df[[True, False, True, False, True, False, True, False, True, False, True, False, True]]
Output:
Masking data based on column value : In a dataframe we can filter a data based on a column value in order to filter data, we can apply certain conditions on the dataframe using different operators like ==, >, <, <=, >=. When we apply these operators to the dataframe then it produces a Series of True and False. To download the “nba.csv” CSV, click here.Code #1:
Python
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["BCA", "BCA", "M.Tech", "BCA"], 'score':[90, 40, 80, 98]} # creating a dataframedf = pd.DataFrame(dict) # using a comparison operator for filtering of dataprint(df['degree'] == 'BCA')
Output:
Code #2:
Python
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv", index_col ="Name") # using greater than operator for filtering of dataprint(data['Age'] > 25)
Output:
Masking data based on index value : In a dataframe we can filter a data based on a column value in order to filter data, we can create a mask based on the index values using different operators like ==, >, <, etc... . To download “nba1.1” CSV file click here.Code #1:
Python3
# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':["aparna", "pankaj", "sudhir", "Geeku"], 'degree': ["BCA", "BCA", "M.Tech", "BCA"], 'score':[90, 40, 80, 98]} df = pd.DataFrame(dict, index = [0, 1, 2, 3]) mask = df.index == 0 print(df[mask])
Output:
Code #2:
Python3
# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba1.1.csv") # giving a index to a dataframedf = pd.DataFrame(data, index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # filtering data on index valuemask = df.index > 7 df[mask]
Output:
Akanksha_Rai
ysachin2314
sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g
Python pandas-dataFrame
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
|
[
{
"code": null,
"e": 41554,
"s": 41526,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 41786,
"s": 41554,
"text": "In boolean indexing, we will select subsets of data based on the actual values of the data in the DataFrame and not on their row/column labels or integer locations. In boolean indexing, we use a boolean vector to filter the data. "
},
{
"code": null,
"e": 41939,
"s": 41786,
"text": "Boolean indexing is a type of indexing which uses actual values of the data in the DataFrame. In boolean indexing, we can filter a data in four ways – "
},
{
"code": null,
"e": 41982,
"s": 41939,
"text": "Accessing a DataFrame with a boolean index"
},
{
"code": null,
"e": 42021,
"s": 41982,
"text": "Applying a boolean mask to a dataframe"
},
{
"code": null,
"e": 42056,
"s": 42021,
"text": "Masking data based on column value"
},
{
"code": null,
"e": 42093,
"s": 42056,
"text": "Masking data based on an index value"
},
{
"code": null,
"e": 42319,
"s": 42093,
"text": "Accessing a DataFrame with a boolean index : In order to access a dataframe with a boolean index, we have to create a dataframe in which the index of dataframe contains a boolean value that is “True” or “False”. For Example "
},
{
"code": null,
"e": 42327,
"s": 42319,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"], 'score':[90, 40, 80, 98]} df = pd.DataFrame(dict, index = [True, False, True, False]) print(df)",
"e": 42604,
"s": 42327,
"text": null
},
{
"code": null,
"e": 42614,
"s": 42604,
"text": "Output: "
},
{
"code": null,
"e": 42827,
"s": 42614,
"text": "Now we have created a dataframe with the boolean index after that user can access a dataframe with the help of the boolean index. User can access a dataframe using three functions that is .loc[], .iloc[], .ix[] "
},
{
"code": null,
"e": 42964,
"s": 42827,
"text": "In order to access a dataframe with a boolean index using .loc[], we simply pass a boolean value (True or False) in a .loc[] function. "
},
{
"code": null,
"e": 42972,
"s": 42964,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"], 'score':[90, 40, 80, 98]} # creating a dataframe with boolean indexdf = pd.DataFrame(dict, index = [True, False, True, False]) # accessing a dataframe using .loc[] functionprint(df.loc[True])",
"e": 43343,
"s": 42972,
"text": null
},
{
"code": null,
"e": 43353,
"s": 43343,
"text": "Output: "
},
{
"code": null,
"e": 43619,
"s": 43355,
"text": "In order to access a dataframe using .iloc[], we have to pass a boolean value (True or False) but iloc[] function accept only integer as an argument so it will throw an error so we can only access a dataframe when we pass an integer in iloc[] function Code #1: "
},
{
"code": null,
"e": 43627,
"s": 43619,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"], 'score':[90, 40, 80, 98]} # creating a dataframe with boolean index df = pd.DataFrame(dict, index = [True, False, True, False]) # accessing a dataframe using .iloc[] functionprint(df.iloc[True])",
"e": 44001,
"s": 43627,
"text": null
},
{
"code": null,
"e": 44011,
"s": 44001,
"text": "Output: "
},
{
"code": null,
"e": 44021,
"s": 44011,
"text": "TypeError"
},
{
"code": null,
"e": 44032,
"s": 44021,
"text": "Code #2: "
},
{
"code": null,
"e": 44040,
"s": 44032,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"], 'score':[90, 40, 80, 98]} # creating a dataframe with boolean index df = pd.DataFrame(dict, index = [True, False, True, False]) # accessing a dataframe using .iloc[] functionprint(df.iloc[1])",
"e": 44413,
"s": 44040,
"text": null
},
{
"code": null,
"e": 44423,
"s": 44413,
"text": "Output: "
},
{
"code": null,
"e": 44645,
"s": 44425,
"text": "In order to access a dataframe using .ix[], we have to pass boolean value (True or False) and integer value to .ix[] function because as we know that .ix[] function is a hybrid of .loc[] and .iloc[] function. Code #1: "
},
{
"code": null,
"e": 44653,
"s": 44645,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"], 'score':[90, 40, 80, 98]} # creating a dataframe with boolean indexdf = pd.DataFrame(dict, index = [True, False, True, False]) # accessing a dataframe using .ix[] functionprint(df.ix[True])",
"e": 45024,
"s": 44653,
"text": null
},
{
"code": null,
"e": 45034,
"s": 45024,
"text": "Output: "
},
{
"code": null,
"e": 45045,
"s": 45034,
"text": "Code #2: "
},
{
"code": null,
"e": 45052,
"s": 45045,
"text": "Python"
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"], 'score':[90, 40, 80, 98]} # creating a dataframe with boolean indexdf = pd.DataFrame(dict, index = [True, False, True, False]) # accessing a dataframe using .ix[] functionprint(df.ix[1])",
"e": 45420,
"s": 45052,
"text": null
},
{
"code": null,
"e": 45430,
"s": 45420,
"text": "Output: "
},
{
"code": null,
"e": 45840,
"s": 45430,
"text": " Applying a boolean mask to a dataframe : In a dataframe we can apply a boolean mask in order to do that we, can use __getitems__ or [] accessor. We can apply a boolean mask by giving a list of True and False of the same length as contain in a dataframe. When we apply a boolean mask it will print only that dataframe in which we pass a boolean value True. To download “nba1.1” CSV file click here.Code #1: "
},
{
"code": null,
"e": 45848,
"s": 45840,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"MBA\", \"BCA\", \"M.Tech\", \"MBA\"], 'score':[90, 40, 80, 98]} df = pd.DataFrame(dict, index = [0, 1, 2, 3]) print(df[[True, False, True, False]])",
"e": 46141,
"s": 45848,
"text": null
},
{
"code": null,
"e": 46151,
"s": 46141,
"text": "Output: "
},
{
"code": null,
"e": 46162,
"s": 46151,
"text": "Code #2: "
},
{
"code": null,
"e": 46170,
"s": 46162,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba1.1.csv\") df = pd.DataFrame(data, index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) df[[True, False, True, False, True, False, True, False, True, False, True, False, True]]",
"e": 46501,
"s": 46170,
"text": null
},
{
"code": null,
"e": 46511,
"s": 46501,
"text": "Output: "
},
{
"code": null,
"e": 46878,
"s": 46511,
"text": " Masking data based on column value : In a dataframe we can filter a data based on a column value in order to filter data, we can apply certain conditions on the dataframe using different operators like ==, >, <, <=, >=. When we apply these operators to the dataframe then it produces a Series of True and False. To download the “nba.csv” CSV, click here.Code #1: "
},
{
"code": null,
"e": 46885,
"s": 46878,
"text": "Python"
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"BCA\", \"BCA\", \"M.Tech\", \"BCA\"], 'score':[90, 40, 80, 98]} # creating a dataframedf = pd.DataFrame(dict) # using a comparison operator for filtering of dataprint(df['degree'] == 'BCA')",
"e": 47217,
"s": 46885,
"text": null
},
{
"code": null,
"e": 47227,
"s": 47217,
"text": "Output: "
},
{
"code": null,
"e": 47238,
"s": 47227,
"text": "Code #2: "
},
{
"code": null,
"e": 47245,
"s": 47238,
"text": "Python"
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\", index_col =\"Name\") # using greater than operator for filtering of dataprint(data['Age'] > 25)",
"e": 47450,
"s": 47245,
"text": null
},
{
"code": null,
"e": 47460,
"s": 47450,
"text": "Output: "
},
{
"code": null,
"e": 47732,
"s": 47460,
"text": " Masking data based on index value : In a dataframe we can filter a data based on a column value in order to filter data, we can create a mask based on the index values using different operators like ==, >, <, etc... . To download “nba1.1” CSV file click here.Code #1: "
},
{
"code": null,
"e": 47740,
"s": 47732,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # dictionary of listsdict = {'name':[\"aparna\", \"pankaj\", \"sudhir\", \"Geeku\"], 'degree': [\"BCA\", \"BCA\", \"M.Tech\", \"BCA\"], 'score':[90, 40, 80, 98]} df = pd.DataFrame(dict, index = [0, 1, 2, 3]) mask = df.index == 0 print(df[mask])",
"e": 48030,
"s": 47740,
"text": null
},
{
"code": null,
"e": 48040,
"s": 48030,
"text": "Output: "
},
{
"code": null,
"e": 48051,
"s": 48040,
"text": "Code #2: "
},
{
"code": null,
"e": 48059,
"s": 48051,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba1.1.csv\") # giving a index to a dataframedf = pd.DataFrame(data, index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # filtering data on index valuemask = df.index > 7 df[mask]",
"e": 48371,
"s": 48059,
"text": null
},
{
"code": null,
"e": 48381,
"s": 48371,
"text": "Output: "
},
{
"code": null,
"e": 48396,
"s": 48383,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 48408,
"s": 48396,
"text": "ysachin2314"
},
{
"code": null,
"e": 48449,
"s": 48408,
"text": "sg4ipiafwot258z3lh6xa2mjq2qtxd89f49zgt7g"
},
{
"code": null,
"e": 48473,
"s": 48449,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 48496,
"s": 48473,
"text": "Python pandas-indexing"
},
{
"code": null,
"e": 48510,
"s": 48496,
"text": "Python-pandas"
},
{
"code": null,
"e": 48517,
"s": 48510,
"text": "Python"
},
{
"code": null,
"e": 48615,
"s": 48517,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48643,
"s": 48615,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 48693,
"s": 48643,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 48715,
"s": 48693,
"text": "Python map() function"
},
{
"code": null,
"e": 48759,
"s": 48715,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 48794,
"s": 48759,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 48816,
"s": 48794,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 48848,
"s": 48816,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 48878,
"s": 48848,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 48920,
"s": 48878,
"text": "Different ways to create Pandas Dataframe"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.